euredact 0.3.0 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +213 -29
- package/dist/cjs/index.js +3 -1
- package/dist/cjs/rules/context.js +50 -0
- package/dist/cjs/rules/countries/index.js +7 -1
- package/dist/cjs/rules/deDistricts.js +92 -0
- package/dist/cjs/rules/engine.js +231 -67
- package/dist/cjs/rules/evidence.js +201 -0
- package/dist/cjs/rules/matchers.js +10 -0
- package/dist/cjs/rules/suppressors.js +40 -1
- package/dist/cjs/sdk.js +23 -5
- package/dist/esm/index.d.ts +2 -1
- package/dist/esm/index.js +1 -0
- package/dist/esm/rules/context.d.ts +31 -0
- package/dist/esm/rules/context.js +46 -0
- package/dist/esm/rules/countries/index.js +7 -1
- package/dist/esm/rules/deDistricts.d.ts +16 -0
- package/dist/esm/rules/deDistricts.js +89 -0
- package/dist/esm/rules/engine.d.ts +28 -4
- package/dist/esm/rules/engine.js +198 -67
- package/dist/esm/rules/evidence.d.ts +63 -0
- package/dist/esm/rules/evidence.js +195 -0
- package/dist/esm/rules/matchers.d.ts +10 -0
- package/dist/esm/rules/matchers.js +10 -0
- package/dist/esm/rules/suppressors.js +40 -1
- package/dist/esm/sdk.d.ts +21 -0
- package/dist/esm/sdk.js +23 -5
- package/dist/esm/types.d.ts +53 -0
- package/package.json +5 -3
package/dist/esm/rules/engine.js
CHANGED
|
@@ -3,6 +3,7 @@ import { MultiPatternMatcher } from "./matchers.js";
|
|
|
3
3
|
import { shouldSuppress } from "./suppressors.js";
|
|
4
4
|
import { detectStructuralDob } from "./structural.js";
|
|
5
5
|
import { COUNTRY_CONFIGS } from "./countries/index.js";
|
|
6
|
+
import * as evidenceMod from "./evidence.js";
|
|
6
7
|
/**
|
|
7
8
|
* Heuristic to detect nested quantifiers that cause catastrophic backtracking.
|
|
8
9
|
* After stripping escaped chars and character classes, look for an unbounded
|
|
@@ -100,118 +101,248 @@ export class RuleEngine {
|
|
|
100
101
|
if (newCountries)
|
|
101
102
|
this.matcher.compile();
|
|
102
103
|
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
104
|
+
/**
|
|
105
|
+
* Generate candidate matches. Country-blind, by contract.
|
|
106
|
+
*
|
|
107
|
+
* This is the only caller of {@link MultiPatternMatcher.scan}, and it takes
|
|
108
|
+
* no country argument. Which country the caller declared may influence how a
|
|
109
|
+
* match is *scored*; it may never influence whether the match is *found*.
|
|
110
|
+
* Before this held, `countries: ["BE"]` made a valid Dutch BSN vanish
|
|
111
|
+
* entirely because the Dutch patterns were never run.
|
|
112
|
+
*/
|
|
113
|
+
generateCandidates(text) {
|
|
114
|
+
this.loadCountries(null);
|
|
115
|
+
return this.matcher.scan(text, null);
|
|
116
|
+
}
|
|
117
|
+
detect(text, countryCodes, countryHint) {
|
|
118
|
+
return this.detectWithEvidence(text, countryCodes, countryHint).detections;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* {@link RuleEngine.detect}, plus the country evidence it reasoned from.
|
|
122
|
+
*
|
|
123
|
+
* `countryCodes` is **scope**: it flags detections from elsewhere as
|
|
124
|
+
* `outOfScope` and, like `countryHint`, contributes a prior. `countryHint` is
|
|
125
|
+
* **only** a prior — it helps resolve ambiguity without marking anything out
|
|
126
|
+
* of scope. Neither gates what is looked for.
|
|
127
|
+
*/
|
|
128
|
+
detectWithEvidence(text, countryCodes, countryHint, priorEvidence) {
|
|
129
|
+
const rawMatches = this.generateCandidates(text);
|
|
130
|
+
// The declared countries are a scoring signal from here on: they rank
|
|
131
|
+
// candidates and flag out-of-scope detections. They do not gate.
|
|
132
|
+
let declared = null;
|
|
109
133
|
if (countryCodes !== null) {
|
|
110
|
-
|
|
134
|
+
declared = new Set();
|
|
111
135
|
for (const c of countryCodes) {
|
|
112
136
|
const code = resolveCountryCode(c);
|
|
113
|
-
if (code
|
|
114
|
-
|
|
137
|
+
if (code === null)
|
|
138
|
+
warnUnknownCountry(c);
|
|
139
|
+
else
|
|
140
|
+
declared.add(code);
|
|
115
141
|
}
|
|
116
|
-
|
|
117
|
-
|
|
142
|
+
declared.add("SHARED");
|
|
143
|
+
declared.add("CUSTOM");
|
|
144
|
+
}
|
|
145
|
+
// The prior fed to the evidence bus. Declared countries count too — a
|
|
146
|
+
// caller naming a country is asserting context, which is exactly what a
|
|
147
|
+
// prior is — but a hint never narrows scope, so it is kept out of
|
|
148
|
+
// `declared` and cannot flag anything out of scope.
|
|
149
|
+
const prior = new Set(declared ?? []);
|
|
150
|
+
for (const c of countryHint ?? []) {
|
|
151
|
+
const code = resolveCountryCode(c);
|
|
152
|
+
if (code === null)
|
|
153
|
+
warnUnknownCountry(c);
|
|
154
|
+
else
|
|
155
|
+
prior.add(code);
|
|
118
156
|
}
|
|
119
|
-
|
|
120
|
-
//
|
|
121
|
-
//
|
|
122
|
-
//
|
|
123
|
-
// positives and must be suppressed.
|
|
157
|
+
// Pass 1: checksum validation. A span that matched a checksummed pattern
|
|
158
|
+
// but failed the checksum is recorded with its country and entity type;
|
|
159
|
+
// what it is allowed to demote is decided below, once the document's
|
|
160
|
+
// countries are known.
|
|
124
161
|
const validated = [];
|
|
125
|
-
const
|
|
162
|
+
const failedSpans = [];
|
|
126
163
|
for (const m of rawMatches) {
|
|
127
|
-
|
|
128
|
-
if (isValid) {
|
|
164
|
+
if (this.matcher.validate(m)) {
|
|
129
165
|
validated.push({ match: m, hasValidValidator: m.patternDef.validator !== null });
|
|
130
166
|
}
|
|
131
167
|
else if (m.patternDef.validator !== null && !m.patternDef.requiresContext) {
|
|
132
|
-
|
|
168
|
+
failedSpans.push({ start: m.start, end: m.end, code: m.countryCode,
|
|
169
|
+
etype: String(m.patternDef.entityType) });
|
|
133
170
|
}
|
|
134
171
|
}
|
|
135
|
-
//
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
172
|
+
// Evidence pass: work out which countries this document belongs to, from
|
|
173
|
+
// the entities that carry their country in the string.
|
|
174
|
+
//
|
|
175
|
+
// Every surviving candidate is eligible, not only checksum-backed ones. An
|
|
176
|
+
// earlier version required a validator here, which silently dropped the
|
|
177
|
+
// email ccTLD — the second-strongest signal at 4.50 log-odds and present in
|
|
178
|
+
// 98,949 of 152,300 corpus documents — because EMAIL has nothing to
|
|
179
|
+
// checksum. Candidates that failed a validator never reach `validated`, so
|
|
180
|
+
// this admits the unvalidatable, not the invalid.
|
|
181
|
+
const evidenceDets = [];
|
|
182
|
+
for (const { match } of validated) {
|
|
183
|
+
if (!evidenceMod.EVIDENCE_TYPES.has(String(match.patternDef.entityType)))
|
|
184
|
+
continue;
|
|
185
|
+
evidenceDets.push({
|
|
186
|
+
entityType: match.patternDef.entityType,
|
|
187
|
+
start: match.start, end: match.end, text: match.text,
|
|
188
|
+
source: DetectionSource.RULES,
|
|
189
|
+
country: (match.countryCode !== "SHARED" && match.countryCode !== "CUSTOM")
|
|
190
|
+
? match.countryCode : null,
|
|
191
|
+
confidence: "high",
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
const countryEvidence = evidenceMod.collect(evidenceDets);
|
|
195
|
+
const countryScores = evidenceMod.accumulate(priorEvidence && priorEvidence.length ? [...countryEvidence, ...priorEvidence] : countryEvidence, prior);
|
|
196
|
+
const hasScores = countryScores.size > 0;
|
|
197
|
+
const corroborated = (code) => !hasScores || code === "SHARED" || code === "CUSTOM" || countryScores.has(code);
|
|
198
|
+
// Now that the document's countries are known, decide which failed
|
|
199
|
+
// validators are entitled to demote anything. A checksum failure only means
|
|
200
|
+
// "not a valid X"; it says nothing about the span unless X was plausible
|
|
201
|
+
// here in the first place. A Belgian national-ID pattern failing on
|
|
202
|
+
// 0612345678 is not evidence against that span being a Dutch phone number.
|
|
203
|
+
//
|
|
204
|
+
// Zones are also per entity type. A failed checksum is evidence against
|
|
205
|
+
// *that type*, not against the span: Sweden's own personnummer checksum
|
|
206
|
+
// failing on 0708787668 used to demote the Swedish *phone* candidate for
|
|
207
|
+
// the same digits, handing the span to a Danish CPR that happened to
|
|
208
|
+
// validate. Worth 878 mistyped phone numbers per 30,000 documents.
|
|
209
|
+
const zonesByType = new Map();
|
|
210
|
+
for (const f of failedSpans) {
|
|
211
|
+
if (!corroborated(f.code))
|
|
212
|
+
continue;
|
|
213
|
+
const list = zonesByType.get(f.etype);
|
|
214
|
+
if (list)
|
|
215
|
+
list.push([f.start, f.end]);
|
|
216
|
+
else
|
|
217
|
+
zonesByType.set(f.etype, [[f.start, f.end]]);
|
|
218
|
+
}
|
|
219
|
+
const mergedZones = new Map();
|
|
220
|
+
for (const [etype, spans] of zonesByType) {
|
|
221
|
+
spans.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
|
|
222
|
+
const starts = [];
|
|
223
|
+
const ends = [];
|
|
224
|
+
let [ms, me] = spans[0];
|
|
225
|
+
for (let i = 1; i < spans.length; i++) {
|
|
226
|
+
const [zs, ze] = spans[i];
|
|
227
|
+
if (zs <= me)
|
|
144
228
|
me = Math.max(me, ze);
|
|
145
|
-
}
|
|
146
229
|
else {
|
|
147
|
-
|
|
148
|
-
|
|
230
|
+
starts.push(ms);
|
|
231
|
+
ends.push(me);
|
|
149
232
|
ms = zs;
|
|
150
233
|
me = ze;
|
|
151
234
|
}
|
|
152
235
|
}
|
|
153
|
-
|
|
154
|
-
|
|
236
|
+
starts.push(ms);
|
|
237
|
+
ends.push(me);
|
|
238
|
+
mergedZones.set(etype, { starts, ends });
|
|
155
239
|
}
|
|
156
|
-
// Build candidates with priority: validated (3) > custom (2) > regex-only (1)
|
|
157
240
|
const candidates = [];
|
|
158
241
|
for (const { match, hasValidValidator } of validated) {
|
|
159
242
|
if (shouldSuppress(text, match))
|
|
160
243
|
continue;
|
|
161
|
-
//
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
244
|
+
// A validator-less match inside a failed-validation span of its own type
|
|
245
|
+
// is demoted below every other candidate rather than deleted. Demotion
|
|
246
|
+
// cannot silence a detection, which is the property deletion lacked:
|
|
247
|
+
// measured across the corpus, deletion removed 454 detections of which
|
|
248
|
+
// 454 overlapped real labelled PII.
|
|
249
|
+
let demoted = false;
|
|
250
|
+
if (match.patternDef.validator === null) {
|
|
251
|
+
const zone = mergedZones.get(String(match.patternDef.entityType));
|
|
252
|
+
if (zone) {
|
|
253
|
+
let lo = 0, hi = zone.starts.length;
|
|
254
|
+
while (lo < hi) {
|
|
255
|
+
const mid = (lo + hi) >>> 1;
|
|
256
|
+
if (zone.starts[mid] <= match.start)
|
|
257
|
+
lo = mid + 1;
|
|
258
|
+
else
|
|
259
|
+
hi = mid;
|
|
260
|
+
}
|
|
261
|
+
const idx = lo - 1;
|
|
262
|
+
demoted = idx >= 0 && zone.ends[idx] >= match.end;
|
|
170
263
|
}
|
|
171
|
-
const idx = lo - 1;
|
|
172
|
-
if (idx >= 0 && zoneEnds[idx] >= match.end)
|
|
173
|
-
continue;
|
|
174
264
|
}
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
265
|
+
let priority;
|
|
266
|
+
if (demoted) {
|
|
267
|
+
priority = -1;
|
|
268
|
+
}
|
|
269
|
+
else if (hasValidValidator) {
|
|
270
|
+
// A passing checksum normally outranks everything. But a checksum only
|
|
271
|
+
// says the digits fit *some* national scheme, and weak ones fit by luck
|
|
272
|
+
// — a mod-11 scheme accepts a random number about one time in eleven.
|
|
273
|
+
// So a validated candidate from a country the document shows no trace
|
|
274
|
+
// of is treated as coincidence, not evidence.
|
|
275
|
+
//
|
|
276
|
+
// Concretely: the Dutch phone number 0612345678 also passes the Danish
|
|
277
|
+
// CPR checksum. Entities that carry their own country vouch for
|
|
278
|
+
// themselves — an IBAN emits evidence for its own country — so a
|
|
279
|
+
// foreign IBAN in a domestic invoice keeps its rank.
|
|
280
|
+
priority = corroborated(match.countryCode) ? 3 : 1;
|
|
281
|
+
}
|
|
282
|
+
else if (match.countryCode === "CUSTOM") {
|
|
283
|
+
priority = 2;
|
|
284
|
+
}
|
|
285
|
+
else if (match.patternDef.entityType === EntityType.POSTAL_CODE) {
|
|
286
|
+
// A bare digit run is the weakest evidence in the engine and must never
|
|
287
|
+
// re-cut a span a structured detector claims (PHONE, SSN, NATIONAL_ID,
|
|
288
|
+
// BANK_ACCOUNT, VAT...). Postal codes take unclaimed spans only,
|
|
289
|
+
// whatever the span lengths.
|
|
290
|
+
priority = 0;
|
|
291
|
+
}
|
|
292
|
+
else {
|
|
293
|
+
priority = 1;
|
|
294
|
+
}
|
|
295
|
+
const country = (match.countryCode !== "SHARED" && match.countryCode !== "CUSTOM")
|
|
296
|
+
? match.countryCode : null;
|
|
188
297
|
candidates.push({
|
|
298
|
+
priority,
|
|
299
|
+
length: match.end - match.start,
|
|
300
|
+
countryScore: countryScores.get(match.countryCode) ?? 0,
|
|
301
|
+
inScope: declared === null || declared.has(match.countryCode) ? 1 : 0,
|
|
189
302
|
det: {
|
|
190
303
|
entityType: match.patternDef.entityType,
|
|
191
304
|
start: match.start,
|
|
192
305
|
end: match.end,
|
|
193
306
|
text: match.text,
|
|
194
307
|
source: DetectionSource.RULES,
|
|
195
|
-
country
|
|
308
|
+
country,
|
|
196
309
|
confidence: "high",
|
|
310
|
+
outOfScope: declared !== null && country !== null && !declared.has(match.countryCode),
|
|
197
311
|
},
|
|
198
|
-
score,
|
|
199
312
|
});
|
|
200
313
|
}
|
|
201
314
|
for (const d of detectStructuralDob(text)) {
|
|
202
|
-
candidates.push({
|
|
315
|
+
candidates.push({ priority: 1, length: d.end - d.start, countryScore: 0, inScope: 1, det: d });
|
|
316
|
+
}
|
|
317
|
+
const detections = this.deduplicate(candidates);
|
|
318
|
+
detections.sort((a, b) => a.start - b.start || b.end - a.end);
|
|
319
|
+
// Attach the confidence behind each country attribution, so a caller can
|
|
320
|
+
// tell "Danish, and the document is plainly Danish" from "Danish, on a
|
|
321
|
+
// checksum alone".
|
|
322
|
+
const ranking = evidenceMod.weightsToRanking(countryScores);
|
|
323
|
+
for (const d of detections) {
|
|
324
|
+
d.countryConfidence = (d.country !== null ? ranking.get(d.country) : undefined) ?? 0;
|
|
203
325
|
}
|
|
204
|
-
return
|
|
326
|
+
return { detections, evidence: countryEvidence, scores: countryScores };
|
|
205
327
|
}
|
|
206
328
|
/**
|
|
207
329
|
* Remove overlapping detections with priority-aware resolution.
|
|
208
|
-
* Priority: validated (3) > custom (2) > regex-only (1)
|
|
209
|
-
* Within
|
|
330
|
+
* Priority: validated (3) > custom (2) > regex-only (1) > postal (0) >
|
|
331
|
+
* demoted (-1). Within a tier, longer span wins, then country evidence.
|
|
210
332
|
*/
|
|
211
333
|
deduplicate(candidates) {
|
|
212
334
|
if (candidates.length === 0)
|
|
213
335
|
return [];
|
|
214
|
-
|
|
336
|
+
// Span length outranks scope: preferring the declared country over the
|
|
337
|
+
// longest match can truncate an entity. Measured: with countries ["BE"],
|
|
338
|
+
// the Belgian phone pattern claims 11 of the 14 characters of
|
|
339
|
+
// "06 12 34 56 78" and leaves three digits exposed. Scope only breaks ties
|
|
340
|
+
// between candidates of equal length, so it can change WHICH country is
|
|
341
|
+
// attributed, never WHAT is masked.
|
|
342
|
+
const sorted = [...candidates].sort((a, b) => b.priority - a.priority ||
|
|
343
|
+
b.length - a.length ||
|
|
344
|
+
b.countryScore - a.countryScore ||
|
|
345
|
+
b.inScope - a.inScope);
|
|
215
346
|
const result = [];
|
|
216
347
|
const occupied = new Set();
|
|
217
348
|
for (const { det } of sorted) {
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Country evidence: what a document says about which country it belongs to.
|
|
3
|
+
*
|
|
4
|
+
* Some entities carry their country in the string — an IBAN's country code, a
|
|
5
|
+
* `+CC` dialling prefix, a VAT prefix, an email ccTLD. Those are used to work
|
|
6
|
+
* out which country a document belongs to, which in turn decides which
|
|
7
|
+
* national scheme owns an ambiguous value elsewhere in the same document.
|
|
8
|
+
* 36.6% of national-ID values in the corpus validate under more than one
|
|
9
|
+
* country's checksum, so without this the engine cannot tell a Dutch BSN from
|
|
10
|
+
* a Polish PESEL.
|
|
11
|
+
*
|
|
12
|
+
* Evidence influences **scoring only**. It ranks candidates that already exist
|
|
13
|
+
* and annotates the result; it never decides what is looked for. A wrong
|
|
14
|
+
* inference must not be able to cause a miss.
|
|
15
|
+
*
|
|
16
|
+
* Weights are derived, not chosen — measured as P(document country = X |
|
|
17
|
+
* signal claims X) across the corpus. Kept identical to the Python SDK's
|
|
18
|
+
* `rules/evidence.py`; re-derive there and port, rather than tuning by feel.
|
|
19
|
+
*/
|
|
20
|
+
import { type CountryEvidence, type Detection } from "../types.js";
|
|
21
|
+
export declare const WEIGHTS: Record<string, number>;
|
|
22
|
+
/**
|
|
23
|
+
* E.164 calling code -> country, for the countries this engine supports. Codes
|
|
24
|
+
* are unique within this set; a shared code (+1, +7) would have to emit
|
|
25
|
+
* evidence for every candidate country rather than one.
|
|
26
|
+
*/
|
|
27
|
+
export declare const DIALLING_CODES: Record<string, string>;
|
|
28
|
+
/**
|
|
29
|
+
* ccTLD -> country. Deliberately excludes .eu/.com/.org/.net: those are not
|
|
30
|
+
* weak evidence, they are no evidence, and treating them as weak would let a
|
|
31
|
+
* .com address outvote a genuine national signal.
|
|
32
|
+
*/
|
|
33
|
+
export declare const CC_TLDS: Record<string, string>;
|
|
34
|
+
/** Entity types that can carry country evidence. */
|
|
35
|
+
export declare const EVIDENCE_TYPES: ReadonlySet<string>;
|
|
36
|
+
/**
|
|
37
|
+
* Country evidence carried by *detections*, in document order.
|
|
38
|
+
*
|
|
39
|
+
* Deduplicated by (span, source): several countries' patterns can match the
|
|
40
|
+
* same IBAN, and counting that span once per pattern would let a single entity
|
|
41
|
+
* outvote the rest of the document.
|
|
42
|
+
*/
|
|
43
|
+
export declare function collect(detections: Detection[]): CountryEvidence[];
|
|
44
|
+
/**
|
|
45
|
+
* Sum evidence into a per-country log-odds score.
|
|
46
|
+
*
|
|
47
|
+
* Returns a weighted set, never a single winner: a Belgian supplier invoicing a
|
|
48
|
+
* German customer is not "70% Belgian", both countries are genuinely present,
|
|
49
|
+
* and an ambiguous value must be resolvable against either.
|
|
50
|
+
*/
|
|
51
|
+
export declare function accumulate(evidence: CountryEvidence[], declared?: Iterable<string> | null): Map<string, number>;
|
|
52
|
+
/**
|
|
53
|
+
* Convert per-country log-odds into confidences in [0, 1].
|
|
54
|
+
*
|
|
55
|
+
* Each country is scored independently — a logistic on its own log-odds —
|
|
56
|
+
* because document countries are not mutually exclusive. A Belgian supplier
|
|
57
|
+
* invoicing a German customer is genuinely both; softmaxing across countries
|
|
58
|
+
* would report the German side of that invoice at 0.00 and make cross-border
|
|
59
|
+
* documents indistinguishable from misattributions.
|
|
60
|
+
*
|
|
61
|
+
* Confidences therefore do not sum to 1, by design.
|
|
62
|
+
*/
|
|
63
|
+
export declare function weightsToRanking(scores: Map<string, number>): Map<string, number>;
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Country evidence: what a document says about which country it belongs to.
|
|
3
|
+
*
|
|
4
|
+
* Some entities carry their country in the string — an IBAN's country code, a
|
|
5
|
+
* `+CC` dialling prefix, a VAT prefix, an email ccTLD. Those are used to work
|
|
6
|
+
* out which country a document belongs to, which in turn decides which
|
|
7
|
+
* national scheme owns an ambiguous value elsewhere in the same document.
|
|
8
|
+
* 36.6% of national-ID values in the corpus validate under more than one
|
|
9
|
+
* country's checksum, so without this the engine cannot tell a Dutch BSN from
|
|
10
|
+
* a Polish PESEL.
|
|
11
|
+
*
|
|
12
|
+
* Evidence influences **scoring only**. It ranks candidates that already exist
|
|
13
|
+
* and annotates the result; it never decides what is looked for. A wrong
|
|
14
|
+
* inference must not be able to cause a miss.
|
|
15
|
+
*
|
|
16
|
+
* Weights are derived, not chosen — measured as P(document country = X |
|
|
17
|
+
* signal claims X) across the corpus. Kept identical to the Python SDK's
|
|
18
|
+
* `rules/evidence.py`; re-derive there and port, rather than tuning by feel.
|
|
19
|
+
*/
|
|
20
|
+
import { EntityType } from "../types.js";
|
|
21
|
+
// ── Derived weights ─────────────────────────────────────────────────────
|
|
22
|
+
//
|
|
23
|
+
// Measured on 152,300 documents:
|
|
24
|
+
//
|
|
25
|
+
// signal agree total P(doc=X|signal) raw log-odds
|
|
26
|
+
// e164Prefix 41,402 41,402 0.9999 9.21
|
|
27
|
+
// bicCountry 2,588 2,588 0.9999 9.21
|
|
28
|
+
// emailTld 97,865 98,949 0.9890 4.50
|
|
29
|
+
// vatPrefix 19,022 20,136 0.9447 2.84
|
|
30
|
+
// ibanPrefix 110,572 126,428 0.8746 1.94
|
|
31
|
+
//
|
|
32
|
+
// The IBAN prefix being the *weakest* signal is real and worth knowing: a
|
|
33
|
+
// Belgian IBAN in a Dutch invoice is ordinary, so the account's country is only
|
|
34
|
+
// weak evidence about the document's.
|
|
35
|
+
//
|
|
36
|
+
// The perfect scores are capped. They are perfect because the generator emits
|
|
37
|
+
// country-consistent values, not because a foreign mobile number never appears
|
|
38
|
+
// in a real document. Treating a synthetic 1.0 as certainty would make a single
|
|
39
|
+
// phone number unfalsifiable by any amount of contrary evidence.
|
|
40
|
+
const MAX_LOG_ODDS = 4.0;
|
|
41
|
+
export const WEIGHTS = {
|
|
42
|
+
e164Prefix: Math.min(9.21, MAX_LOG_ODDS),
|
|
43
|
+
bicCountry: Math.min(9.21, MAX_LOG_ODDS),
|
|
44
|
+
emailTld: Math.min(4.5, MAX_LOG_ODDS),
|
|
45
|
+
vatPrefix: 2.84,
|
|
46
|
+
ibanPrefix: 1.94,
|
|
47
|
+
declared: 2.0, // the caller's `countries`, a prior rather than a measurement
|
|
48
|
+
};
|
|
49
|
+
// ── Signal tables ───────────────────────────────────────────────────────
|
|
50
|
+
/**
|
|
51
|
+
* E.164 calling code -> country, for the countries this engine supports. Codes
|
|
52
|
+
* are unique within this set; a shared code (+1, +7) would have to emit
|
|
53
|
+
* evidence for every candidate country rather than one.
|
|
54
|
+
*/
|
|
55
|
+
export const DIALLING_CODES = {
|
|
56
|
+
"43": "AT", "32": "BE", "359": "BG", "41": "CH", "357": "CY", "420": "CZ",
|
|
57
|
+
"49": "DE", "45": "DK", "372": "EE", "30": "EL", "34": "ES", "358": "FI",
|
|
58
|
+
"33": "FR", "385": "HR", "36": "HU", "353": "IE", "354": "IS", "39": "IT",
|
|
59
|
+
"370": "LT", "352": "LU", "371": "LV", "356": "MT", "31": "NL", "47": "NO",
|
|
60
|
+
"48": "PL", "351": "PT", "40": "RO", "46": "SE", "386": "SI", "421": "SK",
|
|
61
|
+
"44": "UK",
|
|
62
|
+
};
|
|
63
|
+
/**
|
|
64
|
+
* ccTLD -> country. Deliberately excludes .eu/.com/.org/.net: those are not
|
|
65
|
+
* weak evidence, they are no evidence, and treating them as weak would let a
|
|
66
|
+
* .com address outvote a genuine national signal.
|
|
67
|
+
*/
|
|
68
|
+
export const CC_TLDS = {
|
|
69
|
+
at: "AT", be: "BE", bg: "BG", ch: "CH", cy: "CY", cz: "CZ",
|
|
70
|
+
de: "DE", dk: "DK", ee: "EE", gr: "EL", es: "ES", fi: "FI",
|
|
71
|
+
fr: "FR", hr: "HR", hu: "HU", ie: "IE", is: "IS", it: "IT",
|
|
72
|
+
lt: "LT", lu: "LU", lv: "LV", mt: "MT", nl: "NL", no: "NO",
|
|
73
|
+
pl: "PL", pt: "PT", ro: "RO", se: "SE", si: "SI", sk: "SK",
|
|
74
|
+
uk: "UK",
|
|
75
|
+
};
|
|
76
|
+
/** VAT prefixes that are not the ISO code: Greece trades as EL, Northern
|
|
77
|
+
* Ireland as XI. Naive alpha-2 handling gets both wrong. */
|
|
78
|
+
const VAT_PREFIX_OVERRIDES = { EL: "EL", XI: "UK" };
|
|
79
|
+
const emitIban = (det) => {
|
|
80
|
+
const code = det.text.slice(0, 2).toUpperCase();
|
|
81
|
+
if (!/^[A-Z]{2}$/.test(code))
|
|
82
|
+
return [];
|
|
83
|
+
return [{ country: code, source: "ibanPrefix", logOdds: WEIGHTS.ibanPrefix,
|
|
84
|
+
span: [det.start, det.end] }];
|
|
85
|
+
};
|
|
86
|
+
const emitE164 = (det) => {
|
|
87
|
+
if (!det.text.trimStart().startsWith("+"))
|
|
88
|
+
return [];
|
|
89
|
+
const digits = det.text.replace(/\D/g, "");
|
|
90
|
+
for (const len of [3, 2]) {
|
|
91
|
+
const country = DIALLING_CODES[digits.slice(0, len)];
|
|
92
|
+
if (country) {
|
|
93
|
+
return [{ country, source: "e164Prefix", logOdds: WEIGHTS.e164Prefix,
|
|
94
|
+
span: [det.start, det.end] }];
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return [];
|
|
98
|
+
};
|
|
99
|
+
const emitVat = (det) => {
|
|
100
|
+
const prefix = det.text.slice(0, 2).toUpperCase();
|
|
101
|
+
if (!/^[A-Z]{2}$/.test(prefix))
|
|
102
|
+
return [];
|
|
103
|
+
const country = VAT_PREFIX_OVERRIDES[prefix] ?? prefix;
|
|
104
|
+
return [{ country, source: "vatPrefix", logOdds: WEIGHTS.vatPrefix,
|
|
105
|
+
span: [det.start, det.end] }];
|
|
106
|
+
};
|
|
107
|
+
const emitBic = (det) => {
|
|
108
|
+
const clean = det.text.replace(/ /g, "").toUpperCase();
|
|
109
|
+
if (clean.length < 6)
|
|
110
|
+
return [];
|
|
111
|
+
return [{ country: clean.slice(4, 6), source: "bicCountry",
|
|
112
|
+
logOdds: WEIGHTS.bicCountry, span: [det.start, det.end] }];
|
|
113
|
+
};
|
|
114
|
+
const emitTld = (det) => {
|
|
115
|
+
const parts = det.text.split(".");
|
|
116
|
+
const country = CC_TLDS[parts[parts.length - 1].toLowerCase()];
|
|
117
|
+
if (!country)
|
|
118
|
+
return [];
|
|
119
|
+
return [{ country, source: "emailTld", logOdds: WEIGHTS.emailTld,
|
|
120
|
+
span: [det.start, det.end] }];
|
|
121
|
+
};
|
|
122
|
+
/** Dispatch by entity type, mirroring the suppressor tables. */
|
|
123
|
+
const TYPE_EMITTERS = {
|
|
124
|
+
[EntityType.BANK_ACCOUNT]: [emitIban],
|
|
125
|
+
[EntityType.PHONE]: [emitE164],
|
|
126
|
+
[EntityType.VAT]: [emitVat],
|
|
127
|
+
[EntityType.BIC]: [emitBic],
|
|
128
|
+
[EntityType.EMAIL]: [emitTld],
|
|
129
|
+
};
|
|
130
|
+
/** Entity types that can carry country evidence. */
|
|
131
|
+
export const EVIDENCE_TYPES = new Set(Object.keys(TYPE_EMITTERS));
|
|
132
|
+
/**
|
|
133
|
+
* Country evidence carried by *detections*, in document order.
|
|
134
|
+
*
|
|
135
|
+
* Deduplicated by (span, source): several countries' patterns can match the
|
|
136
|
+
* same IBAN, and counting that span once per pattern would let a single entity
|
|
137
|
+
* outvote the rest of the document.
|
|
138
|
+
*/
|
|
139
|
+
export function collect(detections) {
|
|
140
|
+
const evidence = [];
|
|
141
|
+
const seen = new Set();
|
|
142
|
+
for (const det of detections) {
|
|
143
|
+
for (const emit of TYPE_EMITTERS[det.entityType] ?? []) {
|
|
144
|
+
for (const ev of emit(det)) {
|
|
145
|
+
const key = `${ev.span[0]}:${ev.span[1]}:${ev.source}`;
|
|
146
|
+
if (!seen.has(key)) {
|
|
147
|
+
seen.add(key);
|
|
148
|
+
evidence.push(ev);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
// Document order, not pattern-registration order: this list is an audit
|
|
154
|
+
// trail, and a reader checking it against the text should not have to jump
|
|
155
|
+
// around. Also keeps the two SDKs byte-comparable.
|
|
156
|
+
evidence.sort((a, b) => a.span[0] - b.span[0] || a.span[1] - b.span[1]);
|
|
157
|
+
return evidence;
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Sum evidence into a per-country log-odds score.
|
|
161
|
+
*
|
|
162
|
+
* Returns a weighted set, never a single winner: a Belgian supplier invoicing a
|
|
163
|
+
* German customer is not "70% Belgian", both countries are genuinely present,
|
|
164
|
+
* and an ambiguous value must be resolvable against either.
|
|
165
|
+
*/
|
|
166
|
+
export function accumulate(evidence, declared) {
|
|
167
|
+
const scores = new Map();
|
|
168
|
+
for (const ev of evidence) {
|
|
169
|
+
scores.set(ev.country, (scores.get(ev.country) ?? 0) + ev.logOdds);
|
|
170
|
+
}
|
|
171
|
+
for (const country of declared ?? []) {
|
|
172
|
+
if (country !== "SHARED" && country !== "CUSTOM") {
|
|
173
|
+
scores.set(country, (scores.get(country) ?? 0) + WEIGHTS.declared);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return scores;
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Convert per-country log-odds into confidences in [0, 1].
|
|
180
|
+
*
|
|
181
|
+
* Each country is scored independently — a logistic on its own log-odds —
|
|
182
|
+
* because document countries are not mutually exclusive. A Belgian supplier
|
|
183
|
+
* invoicing a German customer is genuinely both; softmaxing across countries
|
|
184
|
+
* would report the German side of that invoice at 0.00 and make cross-border
|
|
185
|
+
* documents indistinguishable from misattributions.
|
|
186
|
+
*
|
|
187
|
+
* Confidences therefore do not sum to 1, by design.
|
|
188
|
+
*/
|
|
189
|
+
export function weightsToRanking(scores) {
|
|
190
|
+
const out = new Map();
|
|
191
|
+
for (const [country, score] of scores) {
|
|
192
|
+
out.set(country, 1 / (1 + Math.exp(-score)));
|
|
193
|
+
}
|
|
194
|
+
return out;
|
|
195
|
+
}
|
|
@@ -7,6 +7,16 @@ export declare class MultiPatternMatcher {
|
|
|
7
7
|
addPattern(patternDef: PatternDef, countryCode: string): void;
|
|
8
8
|
addCountry(config: CountryConfig): void;
|
|
9
9
|
compile(): void;
|
|
10
|
+
/**
|
|
11
|
+
* Scan text against patterns.
|
|
12
|
+
*
|
|
13
|
+
* `countryCodes` restricts which patterns run. **The engine never passes
|
|
14
|
+
* it.** Generation is country-blind by contract — see
|
|
15
|
+
* `RuleEngine.generateCandidates` and `src/__tests__/inference.ts` — because
|
|
16
|
+
* gating generation on the caller's declared country caused silent misses.
|
|
17
|
+
* The parameter is kept for a future opt-in fast mode, which would be the
|
|
18
|
+
* only caller permitted to trade recall for speed.
|
|
19
|
+
*/
|
|
10
20
|
scan(text: string, countryCodes?: Set<string> | null): RawMatch[];
|
|
11
21
|
validate(match: RawMatch): boolean;
|
|
12
22
|
}
|
|
@@ -19,6 +19,16 @@ export class MultiPatternMatcher {
|
|
|
19
19
|
compile() {
|
|
20
20
|
this.compiled = true;
|
|
21
21
|
}
|
|
22
|
+
/**
|
|
23
|
+
* Scan text against patterns.
|
|
24
|
+
*
|
|
25
|
+
* `countryCodes` restricts which patterns run. **The engine never passes
|
|
26
|
+
* it.** Generation is country-blind by contract — see
|
|
27
|
+
* `RuleEngine.generateCandidates` and `src/__tests__/inference.ts` — because
|
|
28
|
+
* gating generation on the caller's declared country caused silent misses.
|
|
29
|
+
* The parameter is kept for a future opt-in fast mode, which would be the
|
|
30
|
+
* only caller permitted to trade recall for speed.
|
|
31
|
+
*/
|
|
22
32
|
scan(text, countryCodes = null) {
|
|
23
33
|
if (!this.compiled)
|
|
24
34
|
this.compile();
|