flare-redact 1.6.1 → 1.8.0
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/CHANGELOG.md +64 -0
- package/README.md +99 -6
- package/SECURITY.md +5 -0
- package/bench/entities-cases.json +154 -0
- package/bench/entities.mjs +151 -0
- package/dist/checksums.d.ts +13 -0
- package/dist/checksums.d.ts.map +1 -1
- package/dist/checksums.js +38 -1
- package/dist/checksums.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +8 -0
- package/dist/cli.js.map +1 -1
- package/dist/detectors.d.ts.map +1 -1
- package/dist/detectors.js +7 -2
- package/dist/detectors.js.map +1 -1
- package/dist/engine.d.ts +30 -0
- package/dist/engine.d.ts.map +1 -1
- package/dist/engine.js +56 -1
- package/dist/engine.js.map +1 -1
- package/dist/entities.d.ts +36 -0
- package/dist/entities.d.ts.map +1 -0
- package/dist/entities.js +897 -0
- package/dist/entities.js.map +1 -0
- package/dist/entity-lexicon.d.ts +11 -0
- package/dist/entity-lexicon.d.ts.map +1 -0
- package/dist/entity-lexicon.js +202 -0
- package/dist/entity-lexicon.js.map +1 -0
- package/dist/gateway/cli.d.ts +1 -1
- package/dist/gateway/cli.d.ts.map +1 -1
- package/dist/gateway/cli.js +4 -0
- package/dist/gateway/cli.js.map +1 -1
- package/dist/gateway/config.d.ts.map +1 -1
- package/dist/gateway/config.js +11 -0
- package/dist/gateway/config.js.map +1 -1
- package/dist/gateway/server.d.ts.map +1 -1
- package/dist/gateway/server.js +7 -0
- package/dist/gateway/server.js.map +1 -1
- package/dist/help.d.ts +1 -1
- package/dist/help.d.ts.map +1 -1
- package/dist/help.js +12 -2
- package/dist/help.js.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/init.d.ts +35 -0
- package/dist/init.d.ts.map +1 -0
- package/dist/init.js +183 -0
- package/dist/init.js.map +1 -0
- package/dist/locales.d.ts.map +1 -1
- package/dist/locales.js +10 -5
- package/dist/locales.js.map +1 -1
- package/dist/stream.d.ts.map +1 -1
- package/dist/stream.js +6 -3
- package/dist/stream.js.map +1 -1
- package/dist/transforms.d.ts.map +1 -1
- package/dist/transforms.js +5 -2
- package/dist/transforms.js.map +1 -1
- package/package.json +8 -1
- package/spec/SPEC.md +10 -4
- package/spec/conformance/cases.json +12 -0
- package/spec/conformance/expected.json +176 -0
- package/spec/detectors.json +7 -7
package/dist/entities.js
ADDED
|
@@ -0,0 +1,897 @@
|
|
|
1
|
+
// Model-free entity recognition: the job a PII token-classification model does
|
|
2
|
+
// (openai/privacy-filter, GLiNER-PII and similar), done with cues, shapes,
|
|
3
|
+
// word lists and a score instead of weights.
|
|
4
|
+
//
|
|
5
|
+
// A model is good at text with no fixed format: a name in a sentence, an
|
|
6
|
+
// address over two lines, a birth date as opposed to any other date, a
|
|
7
|
+
// customer number that only means something because of the words before it.
|
|
8
|
+
// Regex detectors miss all of these. This module scores each candidate on the
|
|
9
|
+
// same evidence a model learns to use:
|
|
10
|
+
//
|
|
11
|
+
// - a cue before it ("my name is", "lives at", "DOB", "account no."), in the
|
|
12
|
+
// library's 24 languages
|
|
13
|
+
// - its shape (capitalised tokens, house number + street type, postcode)
|
|
14
|
+
// - the word lists in entity-lexicon.ts (given names, surnames, non-persons)
|
|
15
|
+
// - context around it (person words nearby, "order"/"invoice" nearby)
|
|
16
|
+
// - consistency: once "Alice Johnson" is a person, a later "Alice" is too
|
|
17
|
+
//
|
|
18
|
+
// The labels follow openai/privacy-filter where they overlap, so the output can
|
|
19
|
+
// stand in for that model: private_person, private_address, private_phone,
|
|
20
|
+
// private_date, account_number, private_url, secret, plus private_handle.
|
|
21
|
+
// Email addresses stay with the core `email` detector.
|
|
22
|
+
//
|
|
23
|
+
// Everything is synchronous, deterministic and linear in the input: every
|
|
24
|
+
// pattern has bounded repetition, and each pass is one scan of the text.
|
|
25
|
+
import { AMBIGUOUS_NAMES, GIVEN_NAMES, NON_PERSON, SURNAMES } from './entity-lexicon.js';
|
|
26
|
+
export const ENTITY_LABELS = [
|
|
27
|
+
'private_person',
|
|
28
|
+
'private_address',
|
|
29
|
+
'private_phone',
|
|
30
|
+
'private_date',
|
|
31
|
+
'account_number',
|
|
32
|
+
'private_handle',
|
|
33
|
+
'private_url',
|
|
34
|
+
'secret',
|
|
35
|
+
];
|
|
36
|
+
const NEVER = /(?!)/;
|
|
37
|
+
function entityDetector(id, label, why, mask, risk = 'high', priority) {
|
|
38
|
+
const det = { id, label, why, pattern: NEVER, mask: () => mask, default: false, tags: ['entities'], risk, confidence: 0.8 };
|
|
39
|
+
if (priority !== undefined)
|
|
40
|
+
det.priority = priority;
|
|
41
|
+
return det;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Registry entries, so `enable: ['entities']`, `disable: ['private_url']`,
|
|
45
|
+
* `--list` and the masks work like any other detector. Their pattern never
|
|
46
|
+
* matches; the engine hands them to recognizeEntities() instead.
|
|
47
|
+
*/
|
|
48
|
+
export const ENTITY_DETECTORS = [
|
|
49
|
+
// Priority 75 lets these win over the older label-only person_name (60),
|
|
50
|
+
// street_address (65) and date_of_birth (70) detectors on the same text.
|
|
51
|
+
entityDetector('private_person', 'Person (recognised)', 'A person named in free text, found from cues, name lists and context.', '[REDACTED PERSON]', 'high', 75),
|
|
52
|
+
entityDetector('private_address', 'Postal address (recognised)', 'A street address, PO box or postcode line written in free text.', '[REDACTED ADDRESS]', 'high', 75),
|
|
53
|
+
entityDetector('private_phone', 'Phone number (recognised)', 'A phone number identified by a nearby cue or an international prefix.', '[REDACTED PHONE]'),
|
|
54
|
+
entityDetector('private_date', 'Personal date (recognised)', 'A birth date or another date tied to a person (admission, death, appointment).', '[REDACTED DATE]', 'high', 75),
|
|
55
|
+
entityDetector('account_number', 'Account or ID number (recognised)', 'A customer, policy, passport, patient or other ID that only a nearby label identifies.', '[REDACTED ACCOUNT]'),
|
|
56
|
+
entityDetector('private_handle', 'Username or handle (recognised)', 'A social handle or login name that points at one person.', '[REDACTED HANDLE]'),
|
|
57
|
+
entityDetector('private_url', 'Personal URL (recognised)', 'A profile link, or a URL whose query carries personal data.', '[REDACTED URL]'),
|
|
58
|
+
entityDetector('secret', 'Secret in prose (recognised)', 'A password, PIN or one-time code given in a sentence rather than a key=value pair.', '[REDACTED SECRET]', 'critical'),
|
|
59
|
+
];
|
|
60
|
+
const ENTITY_SET = new Set(ENTITY_DETECTORS);
|
|
61
|
+
const RISK = new Map(ENTITY_DETECTORS.map((d) => [d.id, d.risk]));
|
|
62
|
+
export const isEntityDetector = (det) => ENTITY_SET.has(det);
|
|
63
|
+
// ---------------------------------------------------------------------------
|
|
64
|
+
// Pattern building blocks
|
|
65
|
+
// ---------------------------------------------------------------------------
|
|
66
|
+
const SP = '[ \\t\\u00A0]';
|
|
67
|
+
// Unicode-mode patterns reject needless escapes such as \-, so only syntax characters are escaped.
|
|
68
|
+
const esc = (s) => s.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&');
|
|
69
|
+
/** Case-insensitive source for a cue phrase, leaving the rest of the pattern case-sensitive. */
|
|
70
|
+
function ci(phrase) {
|
|
71
|
+
let out = '';
|
|
72
|
+
for (const ch of phrase) {
|
|
73
|
+
if (ch === ' ')
|
|
74
|
+
out += `${SP}+`;
|
|
75
|
+
else if (ch === "'")
|
|
76
|
+
out += "['\\u2019]";
|
|
77
|
+
else {
|
|
78
|
+
const lo = ch.toLowerCase();
|
|
79
|
+
const up = ch.toUpperCase();
|
|
80
|
+
out += lo !== up && lo.length === 1 && up.length === 1 ? `[${esc(lo)}${esc(up)}]` : esc(ch);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
/** Longest phrase first, so "full name" wins over "name" in an alternation. */
|
|
86
|
+
const alt = (phrases) => [...new Set(phrases)].sort((a, b) => b.length - a.length).map(ci).join('|');
|
|
87
|
+
const NOT_WORD_BEFORE = '(?<![\\p{L}\\p{N}_])';
|
|
88
|
+
const NOT_WORD_AFTER = '(?![\\p{L}\\p{N}_])';
|
|
89
|
+
const UP = '\\p{Lu}';
|
|
90
|
+
const LO = '[\\p{Ll}\\p{M}]';
|
|
91
|
+
const TOKEN = `(?:(?:Mc|Mac|O['\\u2019]|D['\\u2019])?${UP}${LO}{1,24}(?:-${UP}${LO}{1,24})?)`;
|
|
92
|
+
const INITIAL = `${UP}\\.`;
|
|
93
|
+
const PARTICLE = '(?:van|von|der|den|de|del|della|di|da|du|dos|das|la|le|bin|ibn|al|el|ter|ten|zu|af)';
|
|
94
|
+
const NAME = `(?:${INITIAL}${SP}?){0,2}${TOKEN}` +
|
|
95
|
+
`(?:${SP}(?:${INITIAL}${SP}?){0,2}(?:${PARTICLE}${SP}){0,2}${TOKEN}){0,3}`;
|
|
96
|
+
const UNCASED_NAME = '(?:\\p{Script=Han}{2,4}|\\p{Script=Hangul}{2,4}|\\p{Script=Katakana}{2,10}' +
|
|
97
|
+
`|\\p{Script=Arabic}{2,20}(?:${SP}\\p{Script=Arabic}{2,20})?` +
|
|
98
|
+
`|\\p{Script=Hebrew}{2,15}(?:${SP}\\p{Script=Hebrew}{2,15})?` +
|
|
99
|
+
`|\\p{Script=Devanagari}{2,20}(?:${SP}\\p{Script=Devanagari}{2,20})?` +
|
|
100
|
+
'|\\p{Script=Thai}{2,20})';
|
|
101
|
+
// ---------------------------------------------------------------------------
|
|
102
|
+
// Cue vocabularies (the 24 library languages; see the language policy)
|
|
103
|
+
// ---------------------------------------------------------------------------
|
|
104
|
+
/** "my name is" and its equivalents: the strongest evidence for a person. */
|
|
105
|
+
const SELF_INTRO = [
|
|
106
|
+
'my name is', "my name's", 'my full name is', 'i am called', 'call me', 'me llamo', 'mi nombre es',
|
|
107
|
+
"je m'appelle", 'mon nom est', 'ich heiße', 'ich heisse', 'mein name ist', 'mi chiamo', 'il mio nome è',
|
|
108
|
+
'meu nome é', 'me chamo', 'mijn naam is', 'ik heet', 'nazywam się', 'mam na imię', 'benim adım',
|
|
109
|
+
'adım', 'ismim', 'mənim adım', 'menim adim', 'меня зовут', 'моё имя', 'мое имя', 'мене звати', "моє ім'я",
|
|
110
|
+
'numele meu este', 'mă numesc', 'ma numesc', 'nama saya', 'tên tôi là', 'tôi tên là', 'με λένε',
|
|
111
|
+
'ονομάζομαι', 'το όνομά μου είναι', '我叫', '我的名字是', '私の名前は', 'اسمي', 'שמי',
|
|
112
|
+
'קוראים לי', 'اسم من', 'نام من', 'मेरा नाम', 'ฉันชื่อ', 'ผมชื่อ',
|
|
113
|
+
];
|
|
114
|
+
/** Form labels whose value is a person. `name` alone is weaker: it also labels services. */
|
|
115
|
+
const NAME_LABELS = [
|
|
116
|
+
'full name', 'first name', 'last name', 'given name', 'surname', 'family name', 'legal name', 'patient name',
|
|
117
|
+
'patient', 'customer name', 'client name', 'contact name', 'contact person', 'account holder', 'cardholder',
|
|
118
|
+
'card holder', 'beneficiary', 'recipient name', 'applicant', 'employee name', 'guardian', 'next of kin',
|
|
119
|
+
'emergency contact', 'signed by', 'signature', 'attn', 'attention', 'c/o', 'nombre completo', 'apellido',
|
|
120
|
+
'nom complet', 'prénom', 'vorname', 'nachname', 'cognome', 'nome completo', 'sobrenome', 'voornaam',
|
|
121
|
+
'achternaam', 'imię', 'nazwisko', 'ad soyad', 'soyadı', 'soyad', 'фамилия',
|
|
122
|
+
'отчество', 'ім\'я', 'прізвище', 'nume', 'prenume', 'nama lengkap', 'họ tên', 'họ và tên', 'όνομα',
|
|
123
|
+
'επώνυμο', '姓名', '氏名', '이름', 'الاسم', 'שם', 'نام', 'नाम', 'ชื่อ',
|
|
124
|
+
];
|
|
125
|
+
const GENERIC_NAME_LABELS = ['name', 'nombre', 'nom', 'nome', 'naam', 'isim', 'ad', 'adı', 'имя'];
|
|
126
|
+
const HONORIFICS = [
|
|
127
|
+
'mr', 'mrs', 'ms', 'mx', 'miss', 'dr', 'prof', 'sir', 'dame', 'madam', 'mister', 'señor', 'señora', 'sr',
|
|
128
|
+
'sra', 'srta', 'doña', 'herr', 'frau', 'monsieur', 'madame', 'mademoiselle', 'mme', 'mlle', 'signor',
|
|
129
|
+
'signora', 'sig', 'dott', 'senhor', 'senhora', 'meneer', 'mevrouw', 'dhr', 'mevr', 'pan', 'pani', 'sayın',
|
|
130
|
+
'cənab', 'господин', 'госпожа', 'г-н', 'г-жа', 'пан', 'пані', 'domnul', 'doamna', 'bapak', 'ibu', 'ông',
|
|
131
|
+
'bà', 'κύριος', 'κυρία',
|
|
132
|
+
];
|
|
133
|
+
const GREETINGS = [
|
|
134
|
+
'hi', 'hello', 'hey', 'dear', 'good morning', 'good afternoon', 'good evening', 'hola', 'estimado',
|
|
135
|
+
'estimada', 'bonjour', 'salut', 'cher', 'chère', 'hallo', 'liebe', 'lieber', 'sehr geehrte', 'sehr geehrter',
|
|
136
|
+
'ciao', 'caro', 'cara', 'gentile', 'olá', 'oi', 'prezado', 'prezada', 'beste', 'merhaba', 'sayın', 'salam',
|
|
137
|
+
'hörmətli', 'привет', 'здравствуйте', 'уважаемый', 'уважаемая', 'шановний', 'шановна', 'cześć',
|
|
138
|
+
'szanowny', 'szanowna', 'dragă', 'stimate', 'halo', 'xin chào', 'γεια σου', 'αγαπητέ', 'αγαπητή',
|
|
139
|
+
];
|
|
140
|
+
const SIGN_OFFS = [
|
|
141
|
+
'regards', 'best regards', 'kind regards', 'warm regards', 'best', 'thanks', 'thank you', 'many thanks',
|
|
142
|
+
'cheers', 'sincerely', 'yours sincerely', 'yours truly', 'yours', 'all the best', 'mit freundlichen grüßen',
|
|
143
|
+
'viele grüße', 'beste grüße', 'cordialement', 'bien à vous', 'saludos', 'atentamente', 'un saludo',
|
|
144
|
+
'cordiali saluti', 'distinti saluti', 'atenciosamente', 'abraços', 'met vriendelijke groet', 'groeten',
|
|
145
|
+
'pozdrawiam', 'z poważaniem', 'saygılarımla', 'iyi çalışmalar', 'hörmətlə', 'с уважением', 'з повагою',
|
|
146
|
+
'cu stimă', 'cu stima', 'salam hormat', 'trân trọng', 'με εκτίμηση',
|
|
147
|
+
];
|
|
148
|
+
/** Verbs and phrases that put a person after them, weaker than an introduction. */
|
|
149
|
+
const PERSON_VERBS = [
|
|
150
|
+
'spoke with', 'spoke to', 'talked with', 'talked to', 'met with', 'emailed', 'texted', 'messaged', 'called',
|
|
151
|
+
'phoned', 'contacted', 'assigned to', 'reported by', 'requested by', 'submitted by', 'approved by',
|
|
152
|
+
'reviewed by', 'created by', 'written by', 'prepared by', 'handled by', 'referred by', 'seen by',
|
|
153
|
+
'treated by', 'married to', 'son of', 'daughter of', 'wife of', 'husband of', 'mother of', 'father of',
|
|
154
|
+
'named', 'patient', 'customer', 'client', 'tenant', 'employee', 'student', 'colleague', 'friend', 'neighbour',
|
|
155
|
+
'neighbor', 'his wife', 'her husband', 'my wife', 'my husband', 'my son', 'my daughter', 'my mother',
|
|
156
|
+
'my father', 'my brother', 'my sister', 'my friend', 'my colleague',
|
|
157
|
+
];
|
|
158
|
+
/** "I'm", "Ich bin": also introduce jobs and nationalities, so they need a known name. */
|
|
159
|
+
const WEAK_INTROS = [
|
|
160
|
+
"i'm", 'i am', 'this is', "it's", 'ich bin', 'je suis', 'soy', 'sono', 'sou', 'eu sou', 'ik ben', 'jestem',
|
|
161
|
+
];
|
|
162
|
+
/** A copula between a cue and its value: "Adresse ist", "teléfono es", "numer telefonu to". */
|
|
163
|
+
const COPULA = '(?:is|was|are|ist|war|est|este|es|era|è|é|jest|to|это|це|adalah|là|είναι|olan)';
|
|
164
|
+
const KO_SURNAME = '(?:남궁|황보|제갈|선우|독고|사공|서문|[김이박최정강조윤장임한오서신권황안송류유전홍고문양손배백허남심노하곽성차주우구민진나지엄채원천방공현함변염여추도소석선설마길연위표명기반왕금옥육인맹모탁국어은편용예경봉사부가복태목형피두감음빈동온시호범좌팽승간상갈단견당])';
|
|
165
|
+
/** Korean nouns that start like a surname but say what someone is, not who. */
|
|
166
|
+
const KO_NOT_NAME = new Set([
|
|
167
|
+
'선생님', '선생', '간호사', '기자', '주부', '가수', '배우', '변호사', '공무원', '사장', '사장님', '경찰', '교수',
|
|
168
|
+
'교수님', '교사', '대학생', '회사원', '개발자', '한국인', '한국사람', '미국인', '중국인', '일본인', '남자', '여자',
|
|
169
|
+
'사람', '주인', '고객', '고객님', '부모', '부장', '부장님', '과장', '과장님', '대리', '이사', '이사님', '팀장',
|
|
170
|
+
'정상', '기사', '조교', '박사', '전문가', '안내원', '상담원', '직원', '신입', '신입생', '성인', '노인', '유학생',
|
|
171
|
+
]);
|
|
172
|
+
const PERSON_CONTEXT = new RegExp(`${NOT_WORD_BEFORE}(?:${alt([
|
|
173
|
+
'said', 'says', 'told', 'asked', 'wrote', 'called', 'emailed', 'texted', 'replied', 'lives', 'lived', 'born',
|
|
174
|
+
'died', 'aged', 'years old', 'his', 'her', 'him', 'she', 'he', 'patient', 'customer', 'client', 'employee',
|
|
175
|
+
'colleague', 'friend', 'wife', 'husband', 'son', 'daughter', 'mother', 'father', 'brother', 'sister',
|
|
176
|
+
'phone', 'email', 'address', 'contact', 'diagnosed', 'admitted', 'signed',
|
|
177
|
+
])})${NOT_WORD_AFTER}`, 'u');
|
|
178
|
+
const ADDRESS_CUES = [
|
|
179
|
+
'lives at', 'living at', 'live at', 'resides at', 'residing at', 'located at', 'staying at', 'moved to',
|
|
180
|
+
'address is', 'address', 'home address', 'billing address', 'shipping address', 'mailing address',
|
|
181
|
+
'postal address', 'ship to', 'shipping to', 'deliver to', 'delivery to', 'send it to', 'mail it to',
|
|
182
|
+
'wohnt in der', 'wohnt am', 'wohnt in', 'wohne in der', 'wohne am', 'wohne in', "j'habite au", "j'habite à",
|
|
183
|
+
"j'habite", 'vivo en la', 'vivo en', 'abito in', 'moro na', 'moro em', 'woon aan', 'woon op', 'woon in',
|
|
184
|
+
'mieszkam na', 'mieszkam przy', 'mieszkam w', 'yaşayıram', 'живу на', 'живу по адресу', 'живу в', 'i live at', 'anschrift', 'adresse', 'habite au', 'habite à', 'habite',
|
|
185
|
+
'vive en la', 'vive en', 'dirección', 'direccion', 'domicilio', 'abita in', 'indirizzo', 'mora na', 'mora em',
|
|
186
|
+
'mora no', 'endereço', 'woont aan', 'woont op', 'woont in', 'adres', 'mieszka na', 'mieszka przy',
|
|
187
|
+
'mieszka w', 'ikamet adresi', 'ünvan', 'unvan', 'yaşayış ünvanı', 'живет на', 'живёт на', 'живет по адресу',
|
|
188
|
+
'проживает по адресу', 'адрес', 'живе на', 'адреса', 'locuiește pe', 'locuieste pe', 'adresa', 'tinggal di',
|
|
189
|
+
'alamat', 'sống tại', 'địa chỉ', 'μένει στην', 'μένει στο', 'διεύθυνση', '住址', '地址', '住所', '주소',
|
|
190
|
+
'العنوان', 'عنوان', 'כתובת', 'آدرس', 'पता', 'ที่อยู่',
|
|
191
|
+
];
|
|
192
|
+
const DOB_CUES = [
|
|
193
|
+
'date of birth', 'birth date', 'birthdate', 'born on', 'born in', 'born', 'dob', 'd.o.b', 'birthday',
|
|
194
|
+
'geburtsdatum', 'geboren am', 'geboren', 'geb', 'date de naissance', 'né le', 'née le', 'fecha de nacimiento',
|
|
195
|
+
'nacido el', 'nacida el', 'data di nascita', 'nato il', 'nata il', 'data de nascimento', 'nascido em',
|
|
196
|
+
'nascida em', 'geboortedatum', 'geboren op', 'data urodzenia', 'urodzony', 'urodzona', 'doğum tarihi',
|
|
197
|
+
'doğum tarixi', 'dogum tarixi', 'дата рождения', 'родился', 'родилась', 'дата народження', 'народився',
|
|
198
|
+
'народилася', 'data nașterii', 'data nasterii', 'născut', 'născută', 'tanggal lahir', 'ngày sinh',
|
|
199
|
+
'ημερομηνία γέννησης', 'γεννήθηκε', '出生日期', '生年月日', '생년월일', 'تاريخ الميلاد', 'תאריך לידה',
|
|
200
|
+
'تاریخ تولد', 'जन्म तिथि', 'วันเกิด',
|
|
201
|
+
];
|
|
202
|
+
const LIFE_EVENT_CUES = [
|
|
203
|
+
'admitted on', 'admitted', 'discharged on', 'discharged', 'date of death', 'died on', 'passed away on',
|
|
204
|
+
'deceased on', 'surgery on', 'surgery date', 'operated on', 'diagnosed on', 'diagnosed in', 'appointment on',
|
|
205
|
+
'appointment date', 'visit date', 'date of visit', 'date of service', 'hired on', 'start date', 'married on',
|
|
206
|
+
'divorced on', 'arrested on', 'aufgenommen am', 'entlassen am', 'gestorben am', 'admis le', 'décédé le',
|
|
207
|
+
'ingresó el', 'falleció el', 'ricoverato il', 'internado em', 'opgenomen op', 'przyjęty', 'yatış tarihi',
|
|
208
|
+
'поступил', 'дата смерти',
|
|
209
|
+
];
|
|
210
|
+
/** Events tied to one person; a date later in the same clause is theirs. */
|
|
211
|
+
const EVENT_NOUNS = [
|
|
212
|
+
'appointment', 'consultation', 'surgery', 'operation', 'admission', 'check-up', 'checkup', 'follow-up',
|
|
213
|
+
'procedure', 'vaccination', 'termin', 'rendez-vous', 'cita', 'appuntamento', 'consulta', 'afspraak', 'wizyta',
|
|
214
|
+
'randevu', 'приём', 'прием', 'запись',
|
|
215
|
+
];
|
|
216
|
+
const ACCOUNT_CUES = [
|
|
217
|
+
'account number', 'account no', 'account #', 'account id', 'acct no', 'acct #', 'acct', 'a/c', 'customer id',
|
|
218
|
+
'customer number', 'customer no', 'client id', 'client number', 'member id', 'member number',
|
|
219
|
+
'membership number', 'membership no', 'policy number', 'policy no', 'policy #', 'claim number', 'claim no',
|
|
220
|
+
'claim #', 'passport number', 'passport no', 'passport #', 'passport', "driver's license number",
|
|
221
|
+
"driver's license", 'drivers license', "driver's licence", 'driving licence number', 'driving licence',
|
|
222
|
+
'license number', 'licence number', 'license no', 'dl #', 'national id number', 'national id', 'id number',
|
|
223
|
+
'identity card number', 'id card number', 'id card', 'mrn', 'medical record number', 'medical record no',
|
|
224
|
+
'patient id', 'patient number', 'health card number', 'health insurance number', 'insurance number',
|
|
225
|
+
'insurance id', 'subscriber id', 'employee id', 'employee number', 'employee no', 'staff id', 'staff number',
|
|
226
|
+
'student id', 'student number', 'badge number', 'case number', 'case no', 'case #', 'docket number', 'tax id',
|
|
227
|
+
'taxpayer id', 'tin', 'routing number', 'sort code', 'bsb', 'card ending in', 'card ending', 'ending in',
|
|
228
|
+
'last four digits', 'last 4 digits', 'wallet address', 'imei', 'sim number', 'vehicle registration',
|
|
229
|
+
'license plate', 'licence plate', 'plate number', 'kontonummer', 'kundennummer', 'mitgliedsnummer',
|
|
230
|
+
'versicherungsnummer', 'versichertennummer', 'personalausweisnummer', 'reisepassnummer', 'steuernummer',
|
|
231
|
+
'numéro de compte', 'numéro client', 'numéro de passeport', 'numéro de sécurité sociale', 'numéro fiscal',
|
|
232
|
+
'número de cuenta', 'número de cliente', 'número de pasaporte', 'número de póliza', 'número de socio',
|
|
233
|
+
'numero di conto', 'codice cliente', 'numero di passaporto', 'numero cliente', 'número da conta',
|
|
234
|
+
'número do cliente', 'número do passaporte', 'número de contribuinte', 'rekeningnummer', 'klantnummer',
|
|
235
|
+
'paspoortnummer', 'polisnummer', 'numer konta', 'numer klienta', 'numer paszportu', 'numer polisy',
|
|
236
|
+
'hesap numarası', 'hesap no', 'müşteri numarası', 'müşteri no', 'pasaport numarası', 'pasaport no',
|
|
237
|
+
'hesab nömrəsi', 'müştəri nömrəsi', 'pasport nömrəsi', 'şəxsiyyət vəsiqəsi', 'fin kod', 'fin',
|
|
238
|
+
'номер счета', 'номер счёта', 'лицевой счет', 'лицевой счёт', 'номер паспорта', 'номер клиента',
|
|
239
|
+
'номер полиса', 'номер рахунку', 'номер клієнта', 'numărul contului', 'numar cont', 'cod client',
|
|
240
|
+
'numărul pașaportului', 'nomor rekening', 'nomor pelanggan', 'nomor paspor', 'số tài khoản',
|
|
241
|
+
'số hộ chiếu', 'mã khách hàng', 'αριθμός λογαριασμού', 'αριθμός διαβατηρίου', 'αριθμός πελάτη', '账号',
|
|
242
|
+
'账户', '卡号', '护照号', '口座番号', '会員番号', '계좌번호', '여권번호', 'رقم الحساب', 'رقم جواز السفر',
|
|
243
|
+
'מספר חשבון', 'מספר דרכון', 'شماره حساب', 'شماره پاسپورت', 'खाता संख्या', 'खाता नंबर', 'เลขที่บัญชี',
|
|
244
|
+
];
|
|
245
|
+
/** Labels whose number is a business reference, not a person's identifier. */
|
|
246
|
+
const NOT_ACCOUNT = new RegExp(`${NOT_WORD_BEFORE}(?:${alt([
|
|
247
|
+
'order', 'invoice', 'ticket', 'tracking', 'shipment', 'purchase order', 'po', 'version', 'build', 'release',
|
|
248
|
+
'isbn', 'issn', 'doi', 'icd', 'jira', 'issue', 'pull request', 'pr', 'commit', 'page', 'line', 'room', 'flight',
|
|
249
|
+
'gate', 'seat', 'table', 'model', 'part', 'sku', 'item', 'product', 'transaction', 'reference', 'ref',
|
|
250
|
+
'confirmation', 'booking', 'batch', 'lot', 'serial',
|
|
251
|
+
])})${NOT_WORD_AFTER}`, 'u');
|
|
252
|
+
const PHONE_CUES = [
|
|
253
|
+
'call me at', 'call me on', 'call me', 'call', 'phone number', 'phone', 'telephone', 'tel', 'mobile', 'cell',
|
|
254
|
+
'cellphone', 'text me at', 'text me', 'reach me at', 'reach me on', 'whatsapp', 'viber', 'contact number',
|
|
255
|
+
'my number is', 'my number', 'fax', 'telefon', 'handy', 'telefonnummer', 'handynummer', 'téléphone',
|
|
256
|
+
'portable', 'numéro de téléphone', 'teléfono', 'número de teléfono', 'móvil', 'celular', 'telefono',
|
|
257
|
+
'numero di telefono', 'cellulare', 'telemóvel', 'telefone', 'número de telefone', 'nr telefonu', 'nr tel',
|
|
258
|
+
'telefoonnummer', 'mobiel', 'numer telefonu', 'komórka', 'telefon numarası', 'cep telefonu', 'cep',
|
|
259
|
+
'telefon nömrəsi', 'mobil nömrə', 'телефон', 'номер телефона', 'мобильный', 'номер телефону', 'nomor telepon',
|
|
260
|
+
'nomor hp', 'số điện thoại', 'sđt', 'τηλέφωνο', 'κινητό', '电话', '手机', '電話番号', '전화번호', '휴대폰',
|
|
261
|
+
'هاتف', 'رقم الهاتف', 'טלפון', 'تلفن', 'شماره تلفن', 'फ़ोन', 'फोन नंबर', 'मोबाइल', 'โทร', 'เบอร์โทร',
|
|
262
|
+
];
|
|
263
|
+
const SECRET_CUES = [
|
|
264
|
+
'password', 'passwd', 'pwd', 'passcode', 'pass code', 'pin code', 'pin', 'otp', 'one-time code',
|
|
265
|
+
'one time code', 'one-time password', 'verification code', 'security code', '2fa code', 'auth code',
|
|
266
|
+
'access code', 'recovery code', 'backup code', 'security answer', 'secret answer', 'wifi password',
|
|
267
|
+
'wi-fi password', 'passphrase', 'parol', 'parola', 'şifre', 'şifrə', 'contraseña', 'clave', 'mot de passe',
|
|
268
|
+
'senha', 'passwort', 'kennwort', 'wachtwoord', 'hasło', 'пароль', 'kata sandi', 'mật khẩu', 'κωδικός',
|
|
269
|
+
'密码', 'パスワード', '비밀번호', 'كلمة المرور', 'סיסמה', 'رمز عبور', 'पासवर्ड', 'รหัสผ่าน',
|
|
270
|
+
];
|
|
271
|
+
/** Words that follow "password is" in sentences about passwords rather than ones that give one. */
|
|
272
|
+
const NOT_A_SECRET = new Set(('required incorrect invalid wrong missing empty expired reset too not the a an set changed correct weak strong ' +
|
|
273
|
+
'valid ok okay case sensitive mandatory optional needed saved stored hidden encrypted hashed protected secure ' +
|
|
274
|
+
'insecure same different long short new old being still now also only my your his her our their this that it ' +
|
|
275
|
+
'there here and or but because when if forgotten lost unknown blank null none undefined changeable').split(' '));
|
|
276
|
+
const HANDLE_CUES = [
|
|
277
|
+
'username', 'user name', 'login', 'handle', 'nickname', 'nick', 'gamertag', 'discord', 'telegram', 'skype',
|
|
278
|
+
'instagram', 'insta', 'ig', 'twitter', 'tiktok', 'snapchat', 'snap', 'threads', 'mastodon', 'bluesky',
|
|
279
|
+
'reddit', 'kullanıcı adı', 'istifadəçi adı', 'benutzername', "nom d'utilisateur", 'nombre de usuario',
|
|
280
|
+
'nome utente', 'nome de usuário', 'gebruikersnaam', 'nazwa użytkownika', 'имя пользователя', 'логин', 'ник',
|
|
281
|
+
];
|
|
282
|
+
/** Code annotations, CSS at-rules and pragmas that look like handles. */
|
|
283
|
+
const NOT_HANDLE = new Set(('param params returns return type typedef throws deprecated see example override component injectable input ' +
|
|
284
|
+
'output media import keyframes font-face supports layer tailwind apply ts-ignore ts-expect-error ts-nocheck ' +
|
|
285
|
+
'jsx property interface author version since todo fixme license module namespace callback event fires ' +
|
|
286
|
+
'internal private public protected readonly abstract async static template link inheritdoc summary remarks ' +
|
|
287
|
+
'test before after beforeeach aftereach describe it everyone here channel all true false null function ' +
|
|
288
|
+
'handler string number boolean object undefined none').split(' '));
|
|
289
|
+
const MONTHS = [
|
|
290
|
+
'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november',
|
|
291
|
+
'december', 'jan', 'feb', 'mar', 'apr', 'jun', 'jul', 'aug', 'sep', 'sept', 'oct', 'nov', 'dec', 'januar',
|
|
292
|
+
'jänner', 'februar', 'märz', 'mai', 'juni', 'juli', 'oktober', 'dezember', 'janvier', 'février', 'mars',
|
|
293
|
+
'avril', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre', 'enero', 'febrero',
|
|
294
|
+
'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'setiembre', 'octubre', 'noviembre',
|
|
295
|
+
'diciembre', 'gennaio', 'febbraio', 'aprile', 'maggio', 'giugno', 'luglio', 'settembre', 'ottobre',
|
|
296
|
+
'dicembre', 'janeiro', 'fevereiro', 'março', 'maio', 'junho', 'julho', 'setembro', 'outubro', 'novembro',
|
|
297
|
+
'dezembro', 'januari', 'februari', 'maart', 'mei', 'augustus', 'ocak', 'şubat', 'mart', 'nisan', 'mayıs',
|
|
298
|
+
'haziran', 'temmuz', 'ağustos', 'eylül', 'ekim', 'kasım', 'aralık', 'yanvar', 'fevral', 'aprel', 'iyun',
|
|
299
|
+
'iyul', 'avqust', 'sentyabr', 'oktyabr', 'noyabr', 'dekabr', 'января', 'февраля', 'марта', 'апреля', 'мая',
|
|
300
|
+
'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря', 'січня', 'лютого', 'березня',
|
|
301
|
+
'квітня', 'травня', 'червня', 'липня', 'серпня', 'вересня', 'жовтня', 'листопада', 'грудня', 'stycznia',
|
|
302
|
+
'lutego', 'marca', 'kwietnia', 'maja', 'czerwca', 'lipca', 'sierpnia', 'września', 'października',
|
|
303
|
+
'listopada', 'grudnia', 'ianuarie', 'februarie', 'martie', 'aprilie', 'iunie', 'iulie', 'septembrie',
|
|
304
|
+
'octombrie', 'noiembrie', 'decembrie', 'maret', 'agustus', 'desember', 'ιανουαρίου', 'φεβρουαρίου',
|
|
305
|
+
'μαρτίου', 'απριλίου', 'μαΐου', 'ιουνίου', 'ιουλίου', 'αυγούστου', 'σεπτεμβρίου', 'οκτωβρίου',
|
|
306
|
+
'νοεμβρίου', 'δεκεμβρίου',
|
|
307
|
+
];
|
|
308
|
+
const ORDINAL = '(?:st|nd|rd|th|er|e|º|°)?';
|
|
309
|
+
const MONTH = `(?:${alt(MONTHS)})\\.?`;
|
|
310
|
+
const DATE = '(?:' +
|
|
311
|
+
'(?:19|20)\\d{2}[-/.](?:0?[1-9]|1[0-2])[-/.](?:0?[1-9]|[12]\\d|3[01])' +
|
|
312
|
+
'|(?:0?[1-9]|[12]\\d|3[01])[-/.](?:0?[1-9]|[12]\\d|3[01])[-/.](?:(?:19|20)\\d{2}|\\d{2})' +
|
|
313
|
+
`|(?:0?[1-9]|[12]\\d|3[01])${ORDINAL}\\.?${SP}+(?:(?:de|of)${SP}+)?${MONTH}(?:,?${SP}+(?:de${SP}+)?(?:19|20)\\d{2})?` +
|
|
314
|
+
`|${MONTH}${SP}+(?:0?[1-9]|[12]\\d|3[01])${ORDINAL}(?:,?${SP}+(?:19|20)\\d{2})?` +
|
|
315
|
+
`|${MONTH}${SP}+(?:19|20)\\d{2}` +
|
|
316
|
+
'|(?:19|20)\\d{2}年\\d{1,2}月\\d{1,2}日' +
|
|
317
|
+
`|(?:19|20)\\d{2}년${SP}?\\d{1,2}월${SP}?\\d{1,2}일` +
|
|
318
|
+
`|ngày${SP}+\\d{1,2}${SP}+tháng${SP}+\\d{1,2}(?:${SP}+năm${SP}+(?:19|20)\\d{2})?` +
|
|
319
|
+
')';
|
|
320
|
+
// Street types. "Hauptstraße" carries its type as a suffix; "rue de la Paix"
|
|
321
|
+
// and "ul. Marszałkowska" put it first; "Main Street" puts it last.
|
|
322
|
+
const STREET_SUFFIX_EN = '(?:Street|St|Avenue|Ave|Road|Rd|Boulevard|Blvd|Lane|Ln|Drive|Dr|Court|Ct|Place|Pl|Square|Sq|Terrace|Ter|' +
|
|
323
|
+
'Way|Parkway|Pkwy|Highway|Hwy|Circle|Cir|Trail|Trl|Close|Crescent|Cres|Row|Gardens|Gdns|Mews|Walk|Alley|' +
|
|
324
|
+
'Plaza|Loop|Pike|Path|Grove|Heights|Hts)\\.?';
|
|
325
|
+
const STREET_PREFIX = alt([
|
|
326
|
+
'rue', 'avenue', 'av.', 'bd', 'boulevard', 'chemin', 'allée', 'impasse', 'place', 'quai', 'cours', 'route',
|
|
327
|
+
'calle', 'c/', 'avenida', 'avda.', 'paseo', 'plaza', 'camino', 'carrer', 'carretera', 'ronda', 'via', 'viale',
|
|
328
|
+
'piazza', 'corso', 'largo', 'vicolo', 'strada', 'rua', 'travessa', 'praça', 'praca', 'alameda', 'estrada',
|
|
329
|
+
'calea', 'aleea', 'bulevardul', 'șoseaua', 'soseaua', 'ulica', 'ul.', 'aleja', 'al.', 'plac', 'os.',
|
|
330
|
+
'osiedle', 'улица', 'ул.', 'проспект', 'пр-т', 'пр.', 'переулок', 'пер.', 'шоссе', 'бульвар', 'б-р',
|
|
331
|
+
'вулиця', 'вул.', 'площа', 'οδός', 'οδ.', 'λεωφόρος', 'λεωφ.', 'jalan', 'jl.', 'đường', 'phố',
|
|
332
|
+
]);
|
|
333
|
+
const STREET_SUFFIX_ATTACHED = '(?:straße|strasse|str\\.|weg|gasse|allee|platz|damm|ufer|steig|pfad|chaussee|straat|laan|gracht|' +
|
|
334
|
+
'plein|kade|singel|dijk|gatan|vägen|veien|gata)';
|
|
335
|
+
const STREET_WORD_AFTER = alt([
|
|
336
|
+
'caddesi', 'cad.', 'cd.', 'sokak', 'sokağı', 'sok.', 'sk.', 'bulvarı', 'blv.', 'mahallesi', 'mah.', 'mh.',
|
|
337
|
+
'küçəsi', 'küç.', 'prospekti', 'pr.', 'döngəsi', 'məhəlləsi', 'qəsəbəsi', 'straße', 'strasse', 'str.',
|
|
338
|
+
'weg', 'allee', 'platz', 'gasse',
|
|
339
|
+
]);
|
|
340
|
+
const STREET_PARTICLE = '(?:de|del|de la|des|du|da|do|dos|das|di|della|delle|dei|le|la|les|el|los|las|san|santa|são|sur|y)';
|
|
341
|
+
const NUM = '\\d{1,5}[A-Za-z]?(?:[-/]\\d{1,4}[A-Za-z]?)?';
|
|
342
|
+
const UPW = `${UP}[\\p{L}\\p{M}'\\u2019.-]{0,24}`;
|
|
343
|
+
const UNIT = `(?:,?${SP}*(?:${alt(['apt', 'apartment', 'suite', 'ste', 'unit', 'flat', 'floor', 'fl', 'room', 'rm', 'bldg', 'building', 'wohnung', 'whg', 'etage', 'piso', 'apto', 'daire', 'mənzil', 'kv.', 'кв.'])})\\.?${SP}*#?${SP}?[A-Za-z0-9-]{1,6}|,?${SP}*#${SP}?[A-Za-z0-9-]{1,6})`;
|
|
344
|
+
// No dots inside city words: "Berlin. Geburtsdatum" is a city and a new sentence.
|
|
345
|
+
const CITY = `(?:St\\.${SP})?${UP}[\\p{L}\\p{M}'\\u2019-]{1,30}(?:${SP}${UP}[\\p{L}\\p{M}'\\u2019-]{1,30}){0,2}`;
|
|
346
|
+
const POSTAL_TAIL = '(?:' +
|
|
347
|
+
`${CITY},?${SP}+[A-Z]{2}${SP}+\\d{5}(?:-\\d{4})?` + // Springfield, IL 62704
|
|
348
|
+
`|${CITY},?${SP}+[A-Z]\\d[A-Z]${SP}?\\d[A-Z]\\d` + // Ottawa, ON K1A 0B1 (province before it handled by CITY)
|
|
349
|
+
`|${CITY},?${SP}+[A-Z]{1,2}\\d[A-Z\\d]?${SP}?\\d[A-Z]{2}` + // London SW1A 1AA
|
|
350
|
+
`|\\d{4}${SP}?[A-Z]{2}${SP}+${CITY}` + // 1012 AB Amsterdam
|
|
351
|
+
`|\\d{2}-\\d{3}${SP}+${CITY}` + // 00-001 Warszawa
|
|
352
|
+
`|\\d{4,6}${SP}+${CITY}` + // 75008 Paris, 10115 Berlin
|
|
353
|
+
`|${CITY},?${SP}+\\d{4,6}` + // Baku 1000
|
|
354
|
+
`|${CITY}` +
|
|
355
|
+
')';
|
|
356
|
+
// Separators between digit groups are required, so a run of digits splits one
|
|
357
|
+
// way only and a failed match cannot backtrack through every partition.
|
|
358
|
+
const PHONE_GROUPED = `\\+?(?:\\(\\d{1,4}\\)|\\d{1,5})(?:${SP}?\\(\\d{1,5}\\)|[ .\\-]\\d{1,8}){1,6}`;
|
|
359
|
+
let compiled;
|
|
360
|
+
function patterns() {
|
|
361
|
+
if (compiled)
|
|
362
|
+
return compiled;
|
|
363
|
+
const g = (source) => new RegExp(source, 'gdu');
|
|
364
|
+
const one = (source) => new RegExp(source, 'du');
|
|
365
|
+
const anyName = `(${NAME}|${UNCASED_NAME})`;
|
|
366
|
+
compiled = {
|
|
367
|
+
selfIntro: g(`${NOT_WORD_BEFORE}(?:${alt(SELF_INTRO)})${SP}*[:,]?${SP}*["'\\u201C\\u00AB]?${anyName}`),
|
|
368
|
+
nameLabel: g(`${NOT_WORD_BEFORE}(?:${alt(NAME_LABELS)})${SP}*[:=\\uFF1A]${SP}*["'\\u201C]?${anyName}`),
|
|
369
|
+
genericNameLabel: g(`${NOT_WORD_BEFORE}(?:${alt(GENERIC_NAME_LABELS)})${SP}*[:=\\uFF1A]${SP}*["'\\u201C]?(${NAME})`),
|
|
370
|
+
honorific: g(`${NOT_WORD_BEFORE}(?:${alt(HONORIFICS)})\\.?${SP}+(${NAME})`),
|
|
371
|
+
greeting: g(`(?:^|[\\n.!?]${SP}*)(?:${alt(GREETINGS)})${SP}+(${NAME})(?=${SP}*(?:[,!:\\n]|$))`),
|
|
372
|
+
signOff: g(`${NOT_WORD_BEFORE}(?:${alt(SIGN_OFFS)})${SP}*[,!.]?${SP}*\\r?\\n${SP}*(${NAME})(?=${SP}*(?:\\r?\\n|$))`),
|
|
373
|
+
personVerb: g(`${NOT_WORD_BEFORE}(?:${alt([...PERSON_VERBS, ...WEAK_INTROS])})${SP}+(${NAME})`),
|
|
374
|
+
emailHeader: g(`(?:^|\\n)${SP}*(?:From|To|Cc|Bcc|Reply-To|De|Von|An|Para|À|Da|Van|Od|Kimden|Kime|От|Кому)${SP}*:${SP}*(${NAME})${SP}*(?:<|\\r?\\n|$)`),
|
|
375
|
+
nameBeforeEmail: g(`(${NAME})${SP}*[<(][A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,24}[>)]`),
|
|
376
|
+
nameSuffixCue: g(`(\\p{Script=Han}{2,4}|\\p{Script=Katakana}{2,10})(?:と申します|といいます)|(${NAME})${SP}+(?:Bey|Hanım|Hanim|bəy|xanım|müəllim|müəllimə)${NOT_WORD_AFTER}`),
|
|
377
|
+
// "저는 김민준입니다": Hangul runs straight into the copula, so the name is cut at it.
|
|
378
|
+
koreanIntro: g(`(?:저는|제${SP}*이름은|나는|내${SP}*이름은)${SP}*(${KO_SURNAME}\\p{Script=Hangul}{1,2}?)(?:입니다|이에요|예요|이야|이고|이며|(?:이)?라고${SP}*합니다)`),
|
|
379
|
+
nameRun: g(`${NOT_WORD_BEFORE}${NAME}${NOT_WORD_AFTER}`),
|
|
380
|
+
streetEn: g(`${NOT_WORD_BEFORE}${NUM}${SP}+(?:[NSEW]{1,2}\\.?${SP}+)?(?:(?:${UPW}|\\d{1,3}(?:st|nd|rd|th))${SP}+){1,4}${STREET_SUFFIX_EN}${NOT_WORD_AFTER}(?:${UNIT})?`),
|
|
381
|
+
streetPrefix: g(`${NOT_WORD_BEFORE}(?:${NUM},?${SP}+)?(?:${STREET_PREFIX})${SP}*(?:(?:${STREET_PARTICLE})${SP}+){0,3}${UPW}(?:${SP}+(?:(?:${STREET_PARTICLE})${SP}+){0,2}${UPW}){0,3}(?:,?${SP}*(?:n\\.?[º°o]?|nº|no\\.?|nr\\.?|д\\.|дом|№|number)?${SP}*${NUM})?(?:${UNIT})?`),
|
|
382
|
+
streetAttached: g(`${NOT_WORD_BEFORE}(?:${UPW}${SP}+)?${UP}[\\p{Ll}\\p{M}ß-]{1,30}?${STREET_SUFFIX_ATTACHED}${SP}+\\d{1,4}[a-zA-Z]?(?:[-/]\\d{1,4})?(?:${UNIT})?`),
|
|
383
|
+
streetWordAfter: g(`${NOT_WORD_BEFORE}${UPW}(?:${SP}+${UPW}){0,2}${SP}+(?:${STREET_WORD_AFTER})(?:,?${SP}*(?:No|Nu|Numara|ev|bina|№)?[:.]?${SP}*${NUM})?`),
|
|
384
|
+
poBox: g(`${NOT_WORD_BEFORE}(?:P\\.?${SP}?O\\.?${SP}?Box|Post${SP}+Office${SP}+Box|Postfach|Apartado(?:${SP}+de${SP}+correos)?|Caixa${SP}+Postal|Bo[iî]te${SP}+postale|Casella${SP}+postale|Posta${SP}+Kutusu|а/я)${SP}*\\d{1,7}`),
|
|
385
|
+
// 北京市朝阳区建国路88号: admin units, a road, a number. Unit names exclude unit
|
|
386
|
+
// suffixes and function characters, so the match starts at the place name.
|
|
387
|
+
zhAddress: g('(?:(?:(?![省市区县區縣镇鎮州的了在是我他她你们去住于到从向])\\p{Script=Han}){1,4}[省市区县區縣镇鎮州]){0,4}' +
|
|
388
|
+
'(?:(?![省市区县區縣镇鎮州的了在是我他她你们去住于到从向路街巷弄号號])\\p{Script=Han}){1,6}(?:大道|路|街|巷|弄)' +
|
|
389
|
+
'[0-90-9]{1,5}[号號](?:[0-90-9]{1,5}(?:室|楼|樓|层|層))?'),
|
|
390
|
+
// 東京都千代田区丸の内1丁目2番3号
|
|
391
|
+
jaAddress: g('(?:\\p{Script=Han}{1,3}[都道府県])?(?:\\p{Script=Han}{1,4}[市区町村郡]){1,2}' +
|
|
392
|
+
'[\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}ー]{1,8}?[0-90-9]{1,3}丁目' +
|
|
393
|
+
'(?:[0-90-9]{1,4}(?:番地?|[-−-]))?(?:[0-90-9]{1,4}号?)?'),
|
|
394
|
+
// 서울특별시 강남구 테헤란로 123
|
|
395
|
+
koAddress: g(`(?:\\p{Script=Hangul}{1,6}(?:특별자치시|특별시|광역시|도|시)${SP}+)?(?:\\p{Script=Hangul}{1,6}(?:시|군|구)${SP}+){1,2}` +
|
|
396
|
+
`\\p{Script=Hangul}{2,10}?(?:대로|로|길)${SP}?\\d{1,4}(?:-\\d{1,4})?(?:번길${SP}?\\d{1,4})?`),
|
|
397
|
+
addressCue: g(`${NOT_WORD_BEFORE}(?:${alt(ADDRESS_CUES)})${SP}*(?:${COPULA}${SP}+)?[:=\\uFF1A]?${SP}*`),
|
|
398
|
+
postalTail: one(`^(?:,${SP}*|${SP}*\\r?\\n${SP}*|${SP}+)(${POSTAL_TAIL})(?:,${SP}*(${UP}[\\p{L}\\p{M}]+(?:${SP}${UP}[\\p{L}\\p{M}]+)?|[A-Z]{2,3}))?`),
|
|
399
|
+
dobCue: g(`${NOT_WORD_BEFORE}(?:${alt(DOB_CUES)})\\.?${NOT_WORD_AFTER}`),
|
|
400
|
+
lifeCue: g(`${NOT_WORD_BEFORE}(?:${alt(LIFE_EVENT_CUES)})${NOT_WORD_AFTER}`),
|
|
401
|
+
// "appointment confirmed for Thomas Lee on 3 October 2025": an event noun, then the date later in the clause.
|
|
402
|
+
eventDate: g(`${NOT_WORD_BEFORE}(?:${alt(EVENT_NOUNS)})${NOT_WORD_AFTER}[^.!?\\n]{0,60}?${SP}(?:on|for|am|le|el|il|em|op|w|в|на)${SP}+(${DATE})(?![\\p{L}\\p{N}])`),
|
|
403
|
+
date: one(`^[\\s:=,(\\-\\u2013\\uFF1A]*(?:(?:on|in|the|am|le|el|il|em|op|w|в|на|is|was|est|ist|es|è|é|era|war|of)${SP}+){0,2}(${DATE})(?![\\p{L}\\p{N}])`),
|
|
404
|
+
birthYear: one(`^[\\s:=,(\\-\\u2013\\uFF1A]*(?:in${SP}+)?((?:19|20)\\d{2})(?![\\p{L}\\p{N}])`),
|
|
405
|
+
accountCue: g(`${NOT_WORD_BEFORE}(?:${alt(ACCOUNT_CUES)})${NOT_WORD_AFTER}`),
|
|
406
|
+
phoneCue: g(`${NOT_WORD_BEFORE}(?:${alt(PHONE_CUES)})${NOT_WORD_AFTER}`),
|
|
407
|
+
phoneValue: one(`^[\\s:=,\\-\\u2013\\uFF1A]*(?:(?:${COPULA}|at|on|number|no\\.?|#)${SP}*){0,2}[:=]?${SP}*(${PHONE_GROUPED}|\\+?\\d{7,15})(?![\\d])`),
|
|
408
|
+
phoneIntl: g(`(?<![\\w+])(?:\\+[1-9]\\d{0,3}(?:${SP}?\\(\\d{1,5}\\)|[ .\\-]\\d{1,5}){2,6}|\\+[1-9]\\d{7,14})(?![\\d])`),
|
|
409
|
+
phoneNanp: g(`(?<![\\w.+\\-/])\\(?[2-9]\\d{2}\\)?[\\-. ][2-9]\\d{2}[\\-. ]\\d{4}(?![\\w\\-])`),
|
|
410
|
+
secretCue: g(`${NOT_WORD_BEFORE}(?:${alt(SECRET_CUES)})${NOT_WORD_AFTER}`),
|
|
411
|
+
handleCue: g(`${NOT_WORD_BEFORE}(?:${alt(HANDLE_CUES)})${SP}*(?:is${SP}+|[:=]${SP}*)@?([A-Za-z0-9_](?:[A-Za-z0-9_.\\-]{1,30}[A-Za-z0-9_])?)(?![A-Za-z0-9_@])`),
|
|
412
|
+
atHandle: g(`(?<![\\w.@/])@([A-Za-z0-9_](?:[A-Za-z0-9_.]{1,28}[A-Za-z0-9_])?)(?![\\w@/(\\-])`),
|
|
413
|
+
profileUrl: g(`(?<![\\w.\\-/])(?:https?://)?(?:www\\.|m\\.)?(?:facebook\\.com|fb\\.com|instagram\\.com|github\\.com|gitlab\\.com|twitch\\.tv|behance\\.net|dribbble\\.com|soundcloud\\.com|bsky\\.app/profile|twitter\\.com|x\\.com|linkedin\\.com/in|tiktok\\.com/@|t\\.me|vk\\.com|medium\\.com/@|youtube\\.com/@|threads\\.net/@|reddit\\.com/u(?:ser)?|pinterest\\.com|snapchat\\.com/add|onlyfans\\.com|patreon\\.com)/?[A-Za-z0-9_.@\\-]{2,60}/?(?![A-Za-z0-9_./\\-])`),
|
|
414
|
+
personalQueryUrl: g(`https?://[^\\s"'<>]{1,200}[?&](?:e-?mail|mail|name|first_?name|last_?name|full_?name|phone|tel|mobile|address|dob|birth_?date|ssn|user(?:name)?|uid|token|session|sid|api_?key|password|pwd)=[^\\s"'<>&]{1,200}[^\\s"'<>]{0,300}`),
|
|
415
|
+
};
|
|
416
|
+
return compiled;
|
|
417
|
+
}
|
|
418
|
+
function groupSpan(m, group) {
|
|
419
|
+
const span = m.indices?.[group];
|
|
420
|
+
return span ? [span[0], span[1]] : undefined;
|
|
421
|
+
}
|
|
422
|
+
function each(re, text, fn) {
|
|
423
|
+
re.lastIndex = 0;
|
|
424
|
+
let m;
|
|
425
|
+
while ((m = re.exec(text)) !== null) {
|
|
426
|
+
if (m[0].length === 0)
|
|
427
|
+
re.lastIndex++;
|
|
428
|
+
fn(m);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
const clamp = (n) => Math.max(0, Math.min(0.99, n));
|
|
432
|
+
const nameTokens = (value) => value.split(/[ \t\u00A0]+/).filter((t) => !/^\p{Lu}\.$/u.test(t));
|
|
433
|
+
function isSentenceStart(text, start) {
|
|
434
|
+
for (let i = start - 1; i >= 0; i--) {
|
|
435
|
+
const ch = text[i];
|
|
436
|
+
if (ch === ' ' || ch === '\t' || ch === '"' || ch === "'" || ch === '(' || ch === '*' || ch === '-')
|
|
437
|
+
continue;
|
|
438
|
+
return ch === '.' || ch === '!' || ch === '?' || ch === '\n' || ch === ':' || ch === '>' || ch === '#';
|
|
439
|
+
}
|
|
440
|
+
return true;
|
|
441
|
+
}
|
|
442
|
+
/**
|
|
443
|
+
* Cut a captured name at the first token that cannot be part of one ("Alice
|
|
444
|
+
* Thanks", "Bob From Accounting"), and report how much name evidence is left.
|
|
445
|
+
*/
|
|
446
|
+
function trimName(text, start, end) {
|
|
447
|
+
const value = text.slice(start, end);
|
|
448
|
+
if (!/\p{Lu}/u.test(value[0] ?? ''))
|
|
449
|
+
return { end, tokens: [value] }; // uncased script
|
|
450
|
+
const parts = value.split(/([ \t\u00A0]+)/);
|
|
451
|
+
let kept = '';
|
|
452
|
+
const tokens = [];
|
|
453
|
+
for (let i = 0; i < parts.length; i += 2) {
|
|
454
|
+
const token = parts[i];
|
|
455
|
+
const bare = token.replace(/\.$/, '');
|
|
456
|
+
if (NON_PERSON.has(bare) && !/^\p{Lu}\.$/u.test(token))
|
|
457
|
+
break;
|
|
458
|
+
kept += (i ? parts[i - 1] : '') + token;
|
|
459
|
+
if (!/^\p{Lu}\.$/u.test(token))
|
|
460
|
+
tokens.push(bare);
|
|
461
|
+
}
|
|
462
|
+
if (!tokens.length)
|
|
463
|
+
return undefined;
|
|
464
|
+
return { end: start + kept.length, tokens };
|
|
465
|
+
}
|
|
466
|
+
function personScore(tokens, base) {
|
|
467
|
+
let score = base;
|
|
468
|
+
const first = tokens[0];
|
|
469
|
+
const last = tokens[tokens.length - 1];
|
|
470
|
+
if (GIVEN_NAMES.has(first))
|
|
471
|
+
score += AMBIGUOUS_NAMES.has(first) ? 0.15 : 0.3;
|
|
472
|
+
else if (tokens.length === 1 && SURNAMES.has(first))
|
|
473
|
+
score += 0.2;
|
|
474
|
+
if (tokens.length > 1) {
|
|
475
|
+
score += 0.05;
|
|
476
|
+
if (SURNAMES.has(last))
|
|
477
|
+
score += AMBIGUOUS_NAMES.has(last) ? 0.15 : 0.25;
|
|
478
|
+
else if (GIVEN_NAMES.has(last) && !AMBIGUOUS_NAMES.has(last))
|
|
479
|
+
score += 0.1;
|
|
480
|
+
}
|
|
481
|
+
return score;
|
|
482
|
+
}
|
|
483
|
+
function recognizePersons(text, p, push) {
|
|
484
|
+
const cued = (re, base, group = 1, gazetteerOnly = false) => {
|
|
485
|
+
each(re, text, (m) => {
|
|
486
|
+
let span = groupSpan(m, group);
|
|
487
|
+
if (!span && group === 1)
|
|
488
|
+
span = groupSpan(m, 2);
|
|
489
|
+
if (!span)
|
|
490
|
+
return;
|
|
491
|
+
const trimmed = trimName(text, span[0], span[1]);
|
|
492
|
+
if (!trimmed)
|
|
493
|
+
return;
|
|
494
|
+
const score = personScore(trimmed.tokens, base);
|
|
495
|
+
if (gazetteerOnly && score <= base)
|
|
496
|
+
return;
|
|
497
|
+
push('private_person', span[0], trimmed.end, clamp(score + (PERSON_CONTEXT.test(window(text, span[0], trimmed.end)) ? 0.05 : 0)));
|
|
498
|
+
});
|
|
499
|
+
};
|
|
500
|
+
cued(p.selfIntro, 0.82);
|
|
501
|
+
cued(p.nameLabel, 0.75);
|
|
502
|
+
cued(p.honorific, 0.75);
|
|
503
|
+
cued(p.emailHeader, 0.75);
|
|
504
|
+
cued(p.nameBeforeEmail, 0.7);
|
|
505
|
+
cued(p.signOff, 0.66);
|
|
506
|
+
cued(p.greeting, 0.6);
|
|
507
|
+
cued(p.nameSuffixCue, 0.82);
|
|
508
|
+
each(p.koreanIntro, text, (m) => {
|
|
509
|
+
const span = groupSpan(m, 1);
|
|
510
|
+
if (span && !KO_NOT_NAME.has(text.slice(span[0], span[1])))
|
|
511
|
+
push('private_person', span[0], span[1], 0.88);
|
|
512
|
+
});
|
|
513
|
+
cued(p.personVerb, 0.4, 1, true);
|
|
514
|
+
// A bare "name:" also labels services and products, so it needs one more
|
|
515
|
+
// signal: a known name, or two tokens that end the line like a form field.
|
|
516
|
+
each(p.genericNameLabel, text, (m) => {
|
|
517
|
+
const span = groupSpan(m, 1);
|
|
518
|
+
if (!span)
|
|
519
|
+
return;
|
|
520
|
+
const trimmed = trimName(text, span[0], span[1]);
|
|
521
|
+
if (!trimmed)
|
|
522
|
+
return;
|
|
523
|
+
const atLineEnd = /^[ \t]*(?:\r?\n|$|[,;|])/.test(text.slice(trimmed.end, trimmed.end + 3));
|
|
524
|
+
const score = personScore(trimmed.tokens, 0.45) + (trimmed.tokens.length > 1 && atLineEnd ? 0.05 : 0);
|
|
525
|
+
push('private_person', span[0], trimmed.end, clamp(score));
|
|
526
|
+
});
|
|
527
|
+
// No cue at all: capitalised runs scored on the word lists and context.
|
|
528
|
+
each(p.nameRun, text, (m) => {
|
|
529
|
+
let start = m.index;
|
|
530
|
+
let run = m[0];
|
|
531
|
+
// "Later Alice called", "Ich bin Katrin": a capitalised opener (and a particle
|
|
532
|
+
// look-alike such as "bin") in front of a known name is not part of it.
|
|
533
|
+
const lead = LEAD_OPENER.exec(run);
|
|
534
|
+
if (lead && !GIVEN_NAMES.has(lead[1]) && (isSentenceStart(text, start) || NON_PERSON.has(lead[1])) && GIVEN_NAMES.has(run.slice(lead[0].length).split(/[ \t\u00A0]/)[0])) {
|
|
535
|
+
start += lead[0].length;
|
|
536
|
+
run = run.slice(lead[0].length);
|
|
537
|
+
}
|
|
538
|
+
const trimmed = trimName(text, start, start + run.length);
|
|
539
|
+
if (!trimmed)
|
|
540
|
+
return;
|
|
541
|
+
const { tokens } = trimmed;
|
|
542
|
+
const first = tokens[0];
|
|
543
|
+
const known = GIVEN_NAMES.has(first) || tokens.some((t, i) => i > 0 && SURNAMES.has(t));
|
|
544
|
+
if (!known)
|
|
545
|
+
return;
|
|
546
|
+
// One bare known name ("Mercedes and BMW") stays under the threshold without context.
|
|
547
|
+
let score = personScore(tokens, tokens.length === 1 ? 0.15 : 0.2);
|
|
548
|
+
if (tokens.length === 1 && AMBIGUOUS_NAMES.has(first))
|
|
549
|
+
return;
|
|
550
|
+
if (isSentenceStart(text, start) && AMBIGUOUS_NAMES.has(first))
|
|
551
|
+
score -= 0.2;
|
|
552
|
+
if (PERSON_CONTEXT.test(window(text, start, trimmed.end)))
|
|
553
|
+
score += 0.1;
|
|
554
|
+
push('private_person', start, trimmed.end, clamp(score));
|
|
555
|
+
});
|
|
556
|
+
}
|
|
557
|
+
const LEAD_OPENER = new RegExp(`^(\\p{Lu}[\\p{Ll}\\p{M}]+)${SP}+(?:${PARTICLE}${SP}+){0,2}(?=\\p{Lu})`, 'u');
|
|
558
|
+
function window(text, start, end, radius = 40) {
|
|
559
|
+
return text.slice(Math.max(0, start - radius), Math.min(text.length, end + radius));
|
|
560
|
+
}
|
|
561
|
+
const TAIL_STOP = new Set(['The', 'This', 'That', 'It', 'I', 'We', 'He', 'She', 'They', 'And', 'But', 'Then', 'Please', 'Thanks', 'Thank', 'Call', 'Phone', 'Email', 'Tel']);
|
|
562
|
+
/** Extend an address with the city/postcode line that follows it, if any. */
|
|
563
|
+
function withPostalTail(text, p, end) {
|
|
564
|
+
const tail = p.postalTail.exec(text.slice(end, end + 120));
|
|
565
|
+
if (!tail || !tail[1])
|
|
566
|
+
return { end, postal: false };
|
|
567
|
+
const postal = /\d/.test(tail[1]);
|
|
568
|
+
// A bare city after a comma is evidence; a bare capitalised word after a space is not.
|
|
569
|
+
if (!postal && !/^,/.test(tail[0]) && !/\n/.test(tail[0]))
|
|
570
|
+
return { end, postal: false };
|
|
571
|
+
if (!postal && TAIL_STOP.has(tail[1].split(/[ \t]/)[0]))
|
|
572
|
+
return { end, postal: false };
|
|
573
|
+
return { end: end + tail[0].length, postal };
|
|
574
|
+
}
|
|
575
|
+
/** "IP address", "email address", "wallet address": addresses that are not postal. */
|
|
576
|
+
const NOT_POSTAL_ADDRESS = /(?:e-?mail|ip|ipv4|ipv6|mac|wallet|memory|web|server|return|base|bind|listen|bitcoin|btc|eth|ethereum|contract|host|network|hardware|physical|virtual|logical|url|ip-)\s*$/i;
|
|
577
|
+
const LOWERCASE_STREET_STOP = /(?:^|\s)(?:the|on|in|at|of|a|an|to|my|our|your|and|with|for|down|up|along|across|miles|km|blocks|minutes|meters|metres|steps|times|cars|people|more|than|every)(?:\s|$)/i;
|
|
578
|
+
function recognizeAddresses(text, p, push) {
|
|
579
|
+
const structural = (re, base, needsNumber) => {
|
|
580
|
+
each(re, text, (m) => {
|
|
581
|
+
if (needsNumber && !/\d/.test(m[0]))
|
|
582
|
+
return;
|
|
583
|
+
if (LOWERCASE_STREET_STOP.test(m[0]) && !/\p{Lu}/u.test(m[0].replace(/^[\d\s,.-]+/, '')[0] ?? ''))
|
|
584
|
+
return;
|
|
585
|
+
const tail = withPostalTail(text, p, m.index + m[0].length);
|
|
586
|
+
push('private_address', m.index, tail.end, clamp(base + (tail.postal ? 0.1 : tail.end > m.index + m[0].length ? 0.05 : 0)));
|
|
587
|
+
});
|
|
588
|
+
};
|
|
589
|
+
structural(p.streetEn, 0.85, true);
|
|
590
|
+
each(p.streetPrefix, text, (m) => {
|
|
591
|
+
if (!/\d/.test(m[0]))
|
|
592
|
+
return;
|
|
593
|
+
const end = m.index + m[0].length;
|
|
594
|
+
// "via Slack 3 times", "Route 66 is": a type word in prose, not an address.
|
|
595
|
+
if (!/^\d/.test(m[0]) && /^[ \t]+\p{Ll}/u.test(text.slice(end, end + 3)))
|
|
596
|
+
return;
|
|
597
|
+
const tail = withPostalTail(text, p, end);
|
|
598
|
+
push('private_address', m.index, tail.end, clamp(0.82 + (tail.postal ? 0.1 : tail.end > end ? 0.05 : 0)));
|
|
599
|
+
});
|
|
600
|
+
structural(p.streetAttached, 0.85, true);
|
|
601
|
+
structural(p.streetWordAfter, 0.8, true);
|
|
602
|
+
each(p.poBox, text, (m) => {
|
|
603
|
+
const tail = withPostalTail(text, p, m.index + m[0].length);
|
|
604
|
+
push('private_address', m.index, tail.end, 0.9);
|
|
605
|
+
});
|
|
606
|
+
for (const re of [p.zhAddress, p.jaAddress, p.koAddress]) {
|
|
607
|
+
each(re, text, (m) => push('private_address', m.index, m.index + m[0].length, 0.86));
|
|
608
|
+
}
|
|
609
|
+
// A cue followed by a span with a house number or a postcode, up to the end
|
|
610
|
+
// of the line or sentence.
|
|
611
|
+
each(p.addressCue, text, (m) => {
|
|
612
|
+
if (NOT_POSTAL_ADDRESS.test(text.slice(Math.max(0, m.index - 12), m.index)))
|
|
613
|
+
return;
|
|
614
|
+
const from = m.index + m[0].length;
|
|
615
|
+
const rest = text.slice(from, from + 160);
|
|
616
|
+
const stop = rest.search(/\r?\n\s*\r?\n|\.(?:\s+\p{Lu}|\s*$)|[;!?](?:\s|$)|[。!?;]|\s(?:and|but|until|since|from|for|und|et|y|e|ve|və|и)\s/u);
|
|
617
|
+
let segment = (stop === -1 ? rest : rest.slice(0, stop)).replace(/[\s,.;:)"'\u201D,、]+$/u, '');
|
|
618
|
+
// Two lines are allowed (street, then city); a third starts something else.
|
|
619
|
+
const lines = segment.split(/\r?\n/);
|
|
620
|
+
const cityLine = lines[1] !== undefined && !/[:=]/.test(lines[1]) && lines[1].trim().length <= 48 && /^\s*(?:\d|\p{Lu})/u.test(lines[1]);
|
|
621
|
+
segment = (cityLine ? lines.slice(0, 2).join('\n') : lines[0]).replace(/[\s,]+$/, '');
|
|
622
|
+
if (segment.length < 6 || !/\d/.test(segment) || !/\p{L}{3}/u.test(segment))
|
|
623
|
+
return;
|
|
624
|
+
if (/^\s*(?:0x|[0-9a-f]{2}[:-][0-9a-f]{2}|\d{1,3}\.\d{1,3}\.|\S+@\S+|https?:|[a-z0-9]{20,})/i.test(segment))
|
|
625
|
+
return;
|
|
626
|
+
if (/^\s*(?:\d{1,2}[:.]\d{2}|\d+\s*(?:%|am|pm|kg|km|miles?|years?|days?|hours?))/i.test(segment))
|
|
627
|
+
return;
|
|
628
|
+
// 住所は…です, 주소는 … 입니다: a topic particle before and a copula after are not the address.
|
|
629
|
+
const particle = /^[ \t]*(?:は|が|は、|은|는|이|가)?[ \t::]*/u.exec(segment)[0].length;
|
|
630
|
+
const copula = /[ \t]*(?:です|でございます|입니다|이에요|예요|이다)$/u.exec(segment);
|
|
631
|
+
if (copula)
|
|
632
|
+
segment = segment.slice(0, copula.index);
|
|
633
|
+
if (segment.length - particle < 6)
|
|
634
|
+
return;
|
|
635
|
+
push('private_address', from + particle, from + segment.length, 0.86);
|
|
636
|
+
});
|
|
637
|
+
}
|
|
638
|
+
function recognizeDates(text, p, push) {
|
|
639
|
+
const after = (re, confidence) => {
|
|
640
|
+
each(re, text, (m) => {
|
|
641
|
+
const from = m.index + m[0].length;
|
|
642
|
+
const found = p.date.exec(text.slice(from, from + 60));
|
|
643
|
+
const span = found && groupSpan(found, 1);
|
|
644
|
+
if (!span)
|
|
645
|
+
return;
|
|
646
|
+
push('private_date', from + span[0], from + span[1], confidence);
|
|
647
|
+
});
|
|
648
|
+
};
|
|
649
|
+
after(p.dobCue, 0.95);
|
|
650
|
+
after(p.lifeCue, 0.8);
|
|
651
|
+
each(p.eventDate, text, (m) => {
|
|
652
|
+
const span = groupSpan(m, 1);
|
|
653
|
+
if (span)
|
|
654
|
+
push('private_date', span[0], span[1], 0.75);
|
|
655
|
+
});
|
|
656
|
+
// "born in 1985": a year alone is a birth date only right after a birth cue.
|
|
657
|
+
each(p.dobCue, text, (m) => {
|
|
658
|
+
const from = m.index + m[0].length;
|
|
659
|
+
if (p.date.exec(text.slice(from, from + 60)))
|
|
660
|
+
return;
|
|
661
|
+
const found = p.birthYear.exec(text.slice(from, from + 12));
|
|
662
|
+
const span = found && groupSpan(found, 1);
|
|
663
|
+
if (span)
|
|
664
|
+
push('private_date', from + span[0], from + span[1], 0.85);
|
|
665
|
+
});
|
|
666
|
+
}
|
|
667
|
+
const DATE_LIKE = /^(?:(?:19|20)\d{2}[-/.]\d{1,2}[-/.]\d{1,2}|\d{1,2}[-/.]\d{1,2}[-/.]\d{2,4})$/;
|
|
668
|
+
function recognizeAccounts(text, p, push) {
|
|
669
|
+
each(p.accountCue, text, (m) => {
|
|
670
|
+
const before = text.slice(Math.max(0, m.index - 16), m.index);
|
|
671
|
+
if (NOT_ACCOUNT.test(before))
|
|
672
|
+
return;
|
|
673
|
+
// Short acronyms are also ordinary words ("tin can", "fin"): only their capitalised form counts.
|
|
674
|
+
if (/^(?:tin|fin|mrn|bsb|imei)$/i.test(m[0]) && m[0] !== m[0].toUpperCase())
|
|
675
|
+
return;
|
|
676
|
+
const from = m.index + m[0].length;
|
|
677
|
+
const rest = text.slice(from, from + 64);
|
|
678
|
+
const value = /^\.?[ \t]*(?:(?:number|no\.?|num\.?|nr\.?|#|id|code|is|was|are|of|ending|in|es|est|ist|é|è|era|war|wynosi|olan|это)[ \t]*){0,3}[:=#\-\u2013\u2014\uFF1A]?[ \t]*["'(]?([A-Za-z0-9](?:[A-Za-z0-9]|[-/.](?=[A-Za-z0-9])|[ ](?=\d)){2,33})/.exec(rest);
|
|
679
|
+
if (!value)
|
|
680
|
+
return;
|
|
681
|
+
let raw = value[1];
|
|
682
|
+
raw = raw.replace(/[ .\-/]+$/, '');
|
|
683
|
+
const digits = raw.replace(/\D/g, '').length;
|
|
684
|
+
const shortOk = /ending|last|sort code|bsb|ending in/i.test(m[0]);
|
|
685
|
+
if (digits < (shortOk ? 4 : 3))
|
|
686
|
+
return;
|
|
687
|
+
if (DATE_LIKE.test(raw))
|
|
688
|
+
return;
|
|
689
|
+
if (/^\d{1,2}$/.test(raw))
|
|
690
|
+
return;
|
|
691
|
+
const start = from + value.index + value[0].length - value[1].length;
|
|
692
|
+
push('account_number', start, start + raw.length, 0.86);
|
|
693
|
+
});
|
|
694
|
+
}
|
|
695
|
+
function phoneDigitsOk(value) {
|
|
696
|
+
const digits = value.replace(/\D/g, '').length;
|
|
697
|
+
if (digits < 7 || digits > 15)
|
|
698
|
+
return false;
|
|
699
|
+
return !DATE_LIKE.test(value.trim());
|
|
700
|
+
}
|
|
701
|
+
const NOT_PHONE_BEFORE = /(?:order|invoice|ticket|ref|reference|id|sku|account|acct|isbn|serial|tracking|case|claim|policy|no\.?|#)\s*[:#]?\s*$/i;
|
|
702
|
+
function recognizePhones(text, p, push) {
|
|
703
|
+
each(p.phoneCue, text, (m) => {
|
|
704
|
+
const from = m.index + m[0].length;
|
|
705
|
+
const found = p.phoneValue.exec(text.slice(from, from + 48));
|
|
706
|
+
const span = found && groupSpan(found, 1);
|
|
707
|
+
if (!span)
|
|
708
|
+
return;
|
|
709
|
+
const value = text.slice(from + span[0], from + span[1]);
|
|
710
|
+
if (!phoneDigitsOk(value))
|
|
711
|
+
return;
|
|
712
|
+
push('private_phone', from + span[0], from + span[1], 0.9);
|
|
713
|
+
});
|
|
714
|
+
each(p.phoneIntl, text, (m) => {
|
|
715
|
+
if (!phoneDigitsOk(m[0]) || m[0].replace(/\D/g, '').length < 8)
|
|
716
|
+
return;
|
|
717
|
+
push('private_phone', m.index, m.index + m[0].length, 0.8);
|
|
718
|
+
});
|
|
719
|
+
each(p.phoneNanp, text, (m) => {
|
|
720
|
+
if (NOT_PHONE_BEFORE.test(text.slice(Math.max(0, m.index - 24), m.index)))
|
|
721
|
+
return;
|
|
722
|
+
push('private_phone', m.index, m.index + m[0].length, 0.62);
|
|
723
|
+
});
|
|
724
|
+
}
|
|
725
|
+
function recognizeSecrets(text, p, push) {
|
|
726
|
+
each(p.secretCue, text, (m) => {
|
|
727
|
+
const from = m.index + m[0].length;
|
|
728
|
+
const rest = text.slice(from, from + 100);
|
|
729
|
+
const found = /^(?:[ \t]+(?:for[ \t]+[\p{L}\p{N} .'-]{1,30}?[ \t]+)?(?:is|was|will be|would be|=|:|es|est|ist|é|è|olarak|is now|is set to|set to)|[ \t]*[:=\uFF1A])[ \t]*(?:(["'\u201C\u00AB`])([^"'\u201D\u00BB`\n]{3,64})(?=["'\u201D\u00BB`])|([^\s"'\u201D\u00BB`,;]{3,64}))/u.exec(rest);
|
|
730
|
+
if (!found)
|
|
731
|
+
return;
|
|
732
|
+
const quotedValue = found[2];
|
|
733
|
+
let value = quotedValue ?? found[3].replace(/[.!?)\]]+$/, '');
|
|
734
|
+
const isNumericCue = /pin|otp|code|kod|код|코드/i.test(m[0]);
|
|
735
|
+
if (isNumericCue && !/^\d{4,10}$/.test(value))
|
|
736
|
+
return;
|
|
737
|
+
const lower = value.toLowerCase();
|
|
738
|
+
if (NOT_A_SECRET.has(lower))
|
|
739
|
+
return;
|
|
740
|
+
if (value.length < 3)
|
|
741
|
+
return;
|
|
742
|
+
const plainWord = /^\p{Ll}+$/u.test(value);
|
|
743
|
+
const confidence = quotedValue !== undefined || !plainWord ? 0.9 : 0.62;
|
|
744
|
+
const start = from + found[0].length - (quotedValue ?? found[3]).length;
|
|
745
|
+
value = text.slice(start, start + value.length);
|
|
746
|
+
push('secret', start, start + value.length, confidence);
|
|
747
|
+
});
|
|
748
|
+
}
|
|
749
|
+
function recognizeHandles(text, p, push) {
|
|
750
|
+
each(p.handleCue, text, (m) => {
|
|
751
|
+
const span = groupSpan(m, 1);
|
|
752
|
+
if (!span)
|
|
753
|
+
return;
|
|
754
|
+
const value = text.slice(span[0], span[1]).toLowerCase();
|
|
755
|
+
if (NOT_A_SECRET.has(value) || NOT_HANDLE.has(value))
|
|
756
|
+
return;
|
|
757
|
+
let start = span[0];
|
|
758
|
+
if (text[start - 1] === '@')
|
|
759
|
+
start--;
|
|
760
|
+
push('private_handle', start, span[1], 0.86);
|
|
761
|
+
});
|
|
762
|
+
each(p.atHandle, text, (m) => {
|
|
763
|
+
const name = m[1].toLowerCase();
|
|
764
|
+
if (NOT_HANDLE.has(name))
|
|
765
|
+
return;
|
|
766
|
+
const end = m.index + m[0].length;
|
|
767
|
+
// "@app.route(" and "@pytest.mark" are decorators, not handles.
|
|
768
|
+
if (/^\.[A-Za-z_]/.test(text.slice(end, end + 2)))
|
|
769
|
+
return;
|
|
770
|
+
if (/^\d+$/.test(name))
|
|
771
|
+
return;
|
|
772
|
+
push('private_handle', m.index, m.index + m[0].length, 0.74);
|
|
773
|
+
});
|
|
774
|
+
}
|
|
775
|
+
function recognizeUrls(text, p, push) {
|
|
776
|
+
each(p.profileUrl, text, (m) => {
|
|
777
|
+
const path = m[0].replace(/^(?:https?:\/\/)?(?:www\.|m\.)?[^/]+\/(?:in\/|@|u\/|user\/|add\/)?/, '').replace(/\/$/, '');
|
|
778
|
+
if (!path || /^(?:home|about|help|login|signup|share|sharer|intent|explore|search|settings|privacy|terms|policies|jobs|company|groups|pages|events|hashtag|watch|channel|c|r|p|status|features|pricing|enterprise|topics|marketplace|sponsors|orgs|organizations|trending|collections|security|notifications|new|apps|team|contact|blog|docs|download|downloads|directory|discover|gallery|live|videos|music|stream|tos|feed)$/i.test(path))
|
|
779
|
+
return;
|
|
780
|
+
push('private_url', m.index, m.index + m[0].length, 0.8);
|
|
781
|
+
});
|
|
782
|
+
each(p.personalQueryUrl, text, (m) => {
|
|
783
|
+
const url = m[0].replace(/[.,;:!?)\]]+$/, '');
|
|
784
|
+
// A link carrying a token or session is a credential: mask all of it, ahead of the token alone.
|
|
785
|
+
const credential = /[?&](?:token|session|sid|api_?key|password|pwd)=/i.test(url);
|
|
786
|
+
push('private_url', m.index, m.index + url.length, credential ? 0.95 : 0.86, credential ? 'critical' : undefined);
|
|
787
|
+
});
|
|
788
|
+
}
|
|
789
|
+
/** Later mentions of a confidently recognised person: "Alice Johnson ... Alice said". */
|
|
790
|
+
function propagatePersons(text, found, push) {
|
|
791
|
+
const names = new Set();
|
|
792
|
+
for (const c of found) {
|
|
793
|
+
if (c.label !== 'private_person' || c.confidence < 0.6)
|
|
794
|
+
continue;
|
|
795
|
+
const value = text.slice(c.start, c.end);
|
|
796
|
+
names.add(value);
|
|
797
|
+
for (const token of nameTokens(value)) {
|
|
798
|
+
if (token.length >= 3 && !NON_PERSON.has(token) && !AMBIGUOUS_NAMES.has(token) && !/^\p{Ll}/u.test(token))
|
|
799
|
+
names.add(token);
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
if (!names.size)
|
|
803
|
+
return;
|
|
804
|
+
const list = [...names].sort((a, b) => b.length - a.length).slice(0, 200).map(esc);
|
|
805
|
+
const re = new RegExp(`${NOT_WORD_BEFORE}(?:${list.join('|')})${NOT_WORD_AFTER}`, 'gu');
|
|
806
|
+
each(re, text, (m) => push('private_person', m.index, m.index + m[0].length, 0.8));
|
|
807
|
+
}
|
|
808
|
+
/** Merge overlapping candidates of one label into their union, keeping the best score. */
|
|
809
|
+
function mergeSameLabel(candidates) {
|
|
810
|
+
const byLabel = new Map();
|
|
811
|
+
for (const c of candidates) {
|
|
812
|
+
const list = byLabel.get(c.label) ?? [];
|
|
813
|
+
list.push(c);
|
|
814
|
+
byLabel.set(c.label, list);
|
|
815
|
+
}
|
|
816
|
+
const out = [];
|
|
817
|
+
for (const list of byLabel.values()) {
|
|
818
|
+
list.sort((a, b) => a.start - b.start || b.end - a.end);
|
|
819
|
+
let current;
|
|
820
|
+
for (const c of list) {
|
|
821
|
+
if (current && c.start < current.end) {
|
|
822
|
+
current.end = Math.max(current.end, c.end);
|
|
823
|
+
current.confidence = Math.max(current.confidence, c.confidence);
|
|
824
|
+
if (c.risk === 'critical')
|
|
825
|
+
current.risk = 'critical';
|
|
826
|
+
}
|
|
827
|
+
else {
|
|
828
|
+
if (current)
|
|
829
|
+
out.push(current);
|
|
830
|
+
current = { ...c };
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
if (current)
|
|
834
|
+
out.push(current);
|
|
835
|
+
}
|
|
836
|
+
return out.sort((a, b) => a.start - b.start || a.end - b.end);
|
|
837
|
+
}
|
|
838
|
+
const LABEL_TEXT = new Map(ENTITY_DETECTORS.map((d) => [d.id, d]));
|
|
839
|
+
/**
|
|
840
|
+
* Find people, addresses, phone numbers, personal dates, account numbers,
|
|
841
|
+
* handles, personal URLs and secrets written in free text.
|
|
842
|
+
*
|
|
843
|
+
* recognizeEntities('My name is Alice Johnson, I live at 12 Baker Street.')
|
|
844
|
+
* // [{ detector: 'private_person', start: 11, end: 24, confidence: 0.99, ... },
|
|
845
|
+
* // { detector: 'private_address', start: 36, end: 52, ... }]
|
|
846
|
+
*/
|
|
847
|
+
export function recognizeEntities(text, options = {}) {
|
|
848
|
+
if (!text || text.length < 3)
|
|
849
|
+
return [];
|
|
850
|
+
const labels = new Set(options.labels ?? ENTITY_LABELS);
|
|
851
|
+
const minConfidence = options.minConfidence ?? 0.5;
|
|
852
|
+
const p = patterns();
|
|
853
|
+
const candidates = [];
|
|
854
|
+
const push = (label, start, end, confidence, risk) => {
|
|
855
|
+
if (end > start)
|
|
856
|
+
candidates.push(risk ? { label, start, end, confidence, risk } : { label, start, end, confidence });
|
|
857
|
+
};
|
|
858
|
+
if (labels.has('private_person'))
|
|
859
|
+
recognizePersons(text, p, push);
|
|
860
|
+
if (labels.has('private_address'))
|
|
861
|
+
recognizeAddresses(text, p, push);
|
|
862
|
+
if (labels.has('private_date'))
|
|
863
|
+
recognizeDates(text, p, push);
|
|
864
|
+
if (labels.has('account_number'))
|
|
865
|
+
recognizeAccounts(text, p, push);
|
|
866
|
+
if (labels.has('private_phone'))
|
|
867
|
+
recognizePhones(text, p, push);
|
|
868
|
+
if (labels.has('secret'))
|
|
869
|
+
recognizeSecrets(text, p, push);
|
|
870
|
+
if (labels.has('private_handle'))
|
|
871
|
+
recognizeHandles(text, p, push);
|
|
872
|
+
if (labels.has('private_url'))
|
|
873
|
+
recognizeUrls(text, p, push);
|
|
874
|
+
let kept = candidates.filter((c) => c.confidence >= minConfidence);
|
|
875
|
+
if (labels.has('private_person') && options.propagate !== false) {
|
|
876
|
+
const extra = [];
|
|
877
|
+
propagatePersons(text, kept, (label, start, end, confidence) => extra.push({ label, start, end, confidence }));
|
|
878
|
+
kept = kept.concat(extra.filter((c) => c.confidence >= minConfidence));
|
|
879
|
+
}
|
|
880
|
+
return mergeSameLabel(kept).map((c) => {
|
|
881
|
+
const det = LABEL_TEXT.get(c.label);
|
|
882
|
+
return {
|
|
883
|
+
detector: c.label,
|
|
884
|
+
label: det.label,
|
|
885
|
+
why: det.why,
|
|
886
|
+
start: c.start,
|
|
887
|
+
end: c.end,
|
|
888
|
+
risk: c.risk ?? RISK.get(c.label),
|
|
889
|
+
confidence: Math.round(c.confidence * 100) / 100,
|
|
890
|
+
};
|
|
891
|
+
});
|
|
892
|
+
}
|
|
893
|
+
/** The recogniser as a SemanticProvider, for code that already takes one. */
|
|
894
|
+
export function createEntityRecognizer(options = {}) {
|
|
895
|
+
return { detect: (text) => recognizeEntities(text, options) };
|
|
896
|
+
}
|
|
897
|
+
//# sourceMappingURL=entities.js.map
|