ppuzio commited on
Commit
e519157
·
1 Parent(s): 1564cb0

Move PII scrubbing to SlayerLab/NERGAL (#38)

Browse files

- Move PII scrubbing out of the corpus repo to SlayerLab/NERGAL. (12f7612e6c5f2f661c1d4d4617a5d26ff9883127)

AGENTS.md CHANGED
@@ -114,12 +114,11 @@ What a fetcher should do to `text` before writing the `.jsonl.zst`:
114
  source (license footers, institutional disclaimers, "Pokaż odpowiedź"-style UI
115
  chrome) should be detected by frequency across the shard and removed, not
116
  hand-listed.
117
- - **Personal data**: scrub before the parquet is written, not after. At minimum
118
- email addresses, phone numbers, and national identifiers (PESEL, NIP, REGON,
119
- account numbers). Replace with a stable placeholder (`[PII]`, `[Telefon]`)
120
- rather than deleting, so sentence structure survives. Names of public
121
- officials acting in an official capacity are not PII and should stay —
122
- removing them would gut parliamentary and judicial sources.
123
 
124
  Two rules about all of the above:
125
 
 
114
  source (license footers, institutional disclaimers, "Pokaż odpowiedź"-style UI
115
  chrome) should be detected by frequency across the shard and removed, not
116
  hand-listed.
117
+ - **Personal data**: do not keep a scrubber in this repo. Apply
118
+ [`SlayerLab/NERGAL`](https://huggingface.co/SlayerLab/NERGAL) before the
119
+ parquet is written (frozen regex ∪ model; placeholders `[PII]` / `[Telefon]`).
120
+ Names of public officials acting in an official capacity are not PII and
121
+ should stay — removing them would gut parliamentary and judicial sources.
 
122
 
123
  Two rules about all of the above:
124
 
src/clean_hplt_v3.py CHANGED
@@ -17,8 +17,6 @@ import pyarrow as pa, pyarrow.parquet as pq
17
  import tiktoken
18
 
19
  sys.path.insert(0, str(Path(__file__).resolve().parent))
20
- from scrub_entities import scrub_entities
21
- from scrub_pii import scrub_pii
22
 
23
  ADDED = "2026-07-14"
24
  SOURCE = "european_hplt_v3_pl"
@@ -129,7 +127,6 @@ def main():
129
  t0 = time.time()
130
 
131
  drops = {}; regs = {}; doms = {}; dom_counts = {}
132
- pii_tot = {k: 0 for k in ("email", "phone", "pesel", "nip", "regon", "account")}
133
  ids, texts, tokens = [], [], []
134
  read = kept = chars = toks = 0
135
  mt_sum = 0.0
@@ -174,11 +171,6 @@ def main():
174
  reg = o.get("web-register") or {}
175
  rtop, _ = top_register(reg); regs[rtop] = regs.get(rtop, 0) + 1
176
  mt_sum += float(reg.get("MT", 0.0)) if isinstance(reg, dict) else 0.0
177
- text, pii = scrub_pii(text)
178
- text, ner = scrub_entities(text, SOURCE)
179
- for k, v in pii.items():
180
- pii_tot[k] = pii_tot.get(k, 0) + v
181
- pii_tot["person"] = pii_tot.get("person", 0) + ner["person"]
182
  tk = len(ENC.encode(text, disallowed_special=()))
183
  ids.append(f"{out}_{kept}"); texts.append(text); tokens.append(tk)
184
  kept += 1; chars += len(text); toks += tk
@@ -202,7 +194,6 @@ def main():
202
  "mt_prob_mean_kept": round(mt_sum / max(1, kept), 3),
203
  "domains_top_sample": dict(sorted(doms.items(), key=lambda x: -x[1])[:30]),
204
  "secs": round(time.time()-t0, 1),
205
- "pii_scrub": pii_tot,
206
  "source_repo": f"HPLT/HPLT3.0 pol_Latn {a.bin_label} via {a.inp}"}
207
  (outd / f"{out}.stats.json").write_text(json.dumps(stats, ensure_ascii=False, indent=2)+"\n", encoding="utf-8")
208
  print("=== STATS ===")
 
17
  import tiktoken
18
 
19
  sys.path.insert(0, str(Path(__file__).resolve().parent))
 
 
20
 
21
  ADDED = "2026-07-14"
22
  SOURCE = "european_hplt_v3_pl"
 
127
  t0 = time.time()
128
 
129
  drops = {}; regs = {}; doms = {}; dom_counts = {}
 
130
  ids, texts, tokens = [], [], []
131
  read = kept = chars = toks = 0
132
  mt_sum = 0.0
 
171
  reg = o.get("web-register") or {}
172
  rtop, _ = top_register(reg); regs[rtop] = regs.get(rtop, 0) + 1
173
  mt_sum += float(reg.get("MT", 0.0)) if isinstance(reg, dict) else 0.0
 
 
 
 
 
174
  tk = len(ENC.encode(text, disallowed_special=()))
175
  ids.append(f"{out}_{kept}"); texts.append(text); tokens.append(tk)
176
  kept += 1; chars += len(text); toks += tk
 
194
  "mt_prob_mean_kept": round(mt_sum / max(1, kept), 3),
195
  "domains_top_sample": dict(sorted(doms.items(), key=lambda x: -x[1])[:30]),
196
  "secs": round(time.time()-t0, 1),
 
197
  "source_repo": f"HPLT/HPLT3.0 pol_Latn {a.bin_label} via {a.inp}"}
198
  (outd / f"{out}.stats.json").write_text(json.dumps(stats, ensure_ascii=False, indent=2)+"\n", encoding="utf-8")
199
  print("=== STATS ===")
src/fetch_sejm_api.py CHANGED
@@ -17,7 +17,6 @@ import sys
17
  from typing import Any, Iterable
18
 
19
  sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
20
- from scrub_pii import scrub_pii
21
 
22
  SOURCE_NAME = "sejm_api"
23
  SOURCE_REPOSITORY = "PiotrSty/sejm-speeches-corpus"
@@ -84,7 +83,6 @@ def normalize_source_row(
84
  return None
85
 
86
  text = str(row["text"]).strip()
87
- text, _ = scrub_pii(text)
88
  author = str(row.get("speaker", "")).strip()
89
  source_url = str(row.get("source_url", "")).strip()
90
  term = str(row.get("term", "")).strip()
 
17
  from typing import Any, Iterable
18
 
19
  sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
 
20
 
21
  SOURCE_NAME = "sejm_api"
22
  SOURCE_REPOSITORY = "PiotrSty/sejm-speeches-corpus"
 
83
  return None
84
 
85
  text = str(row["text"]).strip()
 
86
  author = str(row.get("speaker", "")).strip()
87
  source_url = str(row.get("source_url", "")).strip()
88
  term = str(row.get("term", "")).strip()
src/fetch_sejm_interpellations.py CHANGED
@@ -7,7 +7,7 @@ same legal basis as the shipped sejm_api shard. HTML body endpoints only —
7
  attachment-only replies (PDFs) and keyless prolongation stubs are skipped.
8
 
9
  Header chrome (nr / recipient / title / signatory / date) is stripped so it
10
- lives in meta, not text. PII regex-scrub runs before the line is written.
11
 
12
  Usage:
13
  python3 src/fetch_sejm_interpellations.py --out ~/speakleash
@@ -21,7 +21,6 @@ from urllib.request import Request, urlopen
21
 
22
  sys.path.insert(0, str(Path(__file__).resolve().parent))
23
  from html_text import html_to_text
24
- from scrub_pii import scrub_pii
25
 
26
  API = "https://api.sejm.gov.pl"
27
  KEY = "sejm_interpellations"
@@ -93,7 +92,6 @@ def extract_body(html: str) -> str:
93
  def normalize_document(kind: str, item: dict, html: str, reply: dict | None = None):
94
  """Listing item + body HTML → {text, meta}, or None if thin / stub."""
95
  text = extract_body(html)
96
- text, _ = scrub_pii(text)
97
  if len(text) < MIN_CHARS:
98
  return None
99
  collection = _COLLECTION[kind]
 
7
  attachment-only replies (PDFs) and keyless prolongation stubs are skipped.
8
 
9
  Header chrome (nr / recipient / title / signatory / date) is stripped so it
10
+ lives in meta, not text. PII scrubbing is SlayerLab/NERGAL, not this repo.
11
 
12
  Usage:
13
  python3 src/fetch_sejm_interpellations.py --out ~/speakleash
 
21
 
22
  sys.path.insert(0, str(Path(__file__).resolve().parent))
23
  from html_text import html_to_text
 
24
 
25
  API = "https://api.sejm.gov.pl"
26
  KEY = "sejm_interpellations"
 
92
  def normalize_document(kind: str, item: dict, html: str, reply: dict | None = None):
93
  """Listing item + body HTML → {text, meta}, or None if thin / stub."""
94
  text = extract_body(html)
 
95
  if len(text) < MIN_CHARS:
96
  return None
97
  collection = _COLLECTION[kind]
src/pii_mixed_regression_cases.json DELETED
@@ -1,446 +0,0 @@
1
- {
2
- "synthetic": true,
3
- "policy": "Invented regression examples; no corpus excerpts or document references. Email and web domains use example.com. Phone/identifier values test syntax, not assignment; public emergency codes retain their literal semantics.",
4
- "cases": [
5
- {
6
- "name": "vanity_phone",
7
- "text": "Biuro Przykład, ☏ +1 202 555-TEST (8378), +1 202 555-0142.",
8
- "mask": [
9
- {
10
- "start": 18,
11
- "end": 40,
12
- "text": "+1 202 555-TEST (8378)",
13
- "label": "phone"
14
- },
15
- {
16
- "start": 42,
17
- "end": 57,
18
- "text": "+1 202 555-0142",
19
- "label": "phone"
20
- }
21
- ],
22
- "preserve": []
23
- },
24
- {
25
- "name": "email_space_inside_domain",
26
- "text": "Kontakt: osoba@sub- domena.example.com.",
27
- "mask": [
28
- {
29
- "start": 9,
30
- "end": 38,
31
- "text": "osoba@sub- domena.example.com",
32
- "label": "pii"
33
- }
34
- ],
35
- "preserve": []
36
- },
37
- {
38
- "name": "shared_area_code_phone_pair",
39
- "text": "Restauracja Przykład, ulica Przykładowa 12. ☎ (8426) 23-45-61, 23-45-62. Godziny 10.00-22.00.",
40
- "mask": [
41
- {
42
- "start": 46,
43
- "end": 61,
44
- "text": "(8426) 23-45-61",
45
- "label": "phone"
46
- },
47
- {
48
- "start": 63,
49
- "end": 71,
50
- "text": "23-45-62",
51
- "label": "phone"
52
- }
53
- ],
54
- "preserve": [
55
- {
56
- "start": 81,
57
- "end": 92,
58
- "text": "10.00-22.00"
59
- }
60
- ]
61
- },
62
- {
63
- "name": "email_domain_line_break",
64
- "text": "Autor przykładowego artykułu (autor@poczta.\nexample.com).\nTytuł publikacji.",
65
- "mask": [
66
- {
67
- "start": 30,
68
- "end": 55,
69
- "text": "autor@poczta.\nexample.com",
70
- "label": "pii"
71
- }
72
- ],
73
- "preserve": []
74
- },
75
- {
76
- "name": "international_trunk_in_business_listing",
77
- "text": "Kemping Przykład, +27 (0)13 234-5612 oferuje noclegi.\n\nKemping Testowy +27 (0)13 234-5613 ma basen.",
78
- "mask": [
79
- {
80
- "start": 18,
81
- "end": 36,
82
- "text": "+27 (0)13 234-5612",
83
- "label": "phone"
84
- },
85
- {
86
- "start": 71,
87
- "end": 89,
88
- "text": "+27 (0)13 234-5613",
89
- "label": "phone"
90
- }
91
- ],
92
- "preserve": []
93
- },
94
- {
95
- "name": "emergency_number_lists",
96
- "text": "Biuro testowe, tel. 22 123-45-67, tel. alarmowe 997 i 112.\n\nStraż pożarna\ntel. 22 123-45-68, tel. alarmowe 998 i 112.",
97
- "mask": [
98
- {
99
- "start": 48,
100
- "end": 51,
101
- "text": "997",
102
- "label": "phone"
103
- },
104
- {
105
- "start": 54,
106
- "end": 57,
107
- "text": "112",
108
- "label": "phone"
109
- },
110
- {
111
- "start": 107,
112
- "end": 110,
113
- "text": "998",
114
- "label": "phone"
115
- },
116
- {
117
- "start": 113,
118
- "end": 116,
119
- "text": "112",
120
- "label": "phone"
121
- }
122
- ],
123
- "preserve": []
124
- },
125
- {
126
- "name": "emergency_directory_labels",
127
- "text": "Numery telefonów\nW sytuacjach awaryjnych\nStraż pożarna: 122\nPolicja: 133\nRatunek: 144\nLekarz pogotowia ratunkowego: 141",
128
- "mask": [
129
- {
130
- "start": 82,
131
- "end": 85,
132
- "text": "144",
133
- "label": "phone"
134
- },
135
- {
136
- "start": 116,
137
- "end": 119,
138
- "text": "141",
139
- "label": "phone"
140
- }
141
- ],
142
- "preserve": []
143
- },
144
- {
145
- "name": "foreign_short_service_directory",
146
- "text": "W przypadku pytań i problemów\nBiuro podróży Przykład: +43 (0)5 2345\nObsługa rzeczy znalezionych: +43 (0)1 23 456 78 23 456\nAwaria automatów: +43 (0)5 2345 67\nSiedziba administracji: +43 (0)1 23456\nInformacje można uzyskać dzwoniąc pod numer biura podróży +43 (0)5 2345.",
147
- "mask": [
148
- {
149
- "start": 54,
150
- "end": 67,
151
- "text": "+43 (0)5 2345",
152
- "label": "phone"
153
- },
154
- {
155
- "start": 97,
156
- "end": 122,
157
- "text": "+43 (0)1 23 456 78 23 456",
158
- "label": "phone"
159
- },
160
- {
161
- "start": 141,
162
- "end": 157,
163
- "text": "+43 (0)5 2345 67",
164
- "label": "phone"
165
- },
166
- {
167
- "start": 182,
168
- "end": 196,
169
- "text": "+43 (0)1 23456",
170
- "label": "phone"
171
- },
172
- {
173
- "start": 255,
174
- "end": 268,
175
- "text": "+43 (0)5 2345",
176
- "label": "phone"
177
- }
178
- ],
179
- "preserve": []
180
- },
181
- {
182
- "name": "email_space_after_at",
183
- "text": "Faks: +81 23-456-7812, biuro@ sub.example.com. Godziny 09:00-18:00.",
184
- "mask": [
185
- {
186
- "start": 23,
187
- "end": 45,
188
- "text": "biuro@ sub.example.com",
189
- "label": "pii"
190
- }
191
- ],
192
- "preserve": [
193
- {
194
- "start": 55,
195
- "end": 66,
196
- "text": "09:00-18:00"
197
- }
198
- ]
199
- },
200
- {
201
- "name": "phone_symbol_with_foreign_area_code",
202
- "text": "Punkt Przykład. ☎ (384) 234 - 56 - 71. Godziny 10:00-22:00.",
203
- "mask": [
204
- {
205
- "start": 18,
206
- "end": 37,
207
- "text": "(384) 234 - 56 - 71",
208
- "label": "phone"
209
- }
210
- ],
211
- "preserve": [
212
- {
213
- "start": 47,
214
- "end": 58,
215
- "text": "10:00-22:00"
216
- }
217
- ]
218
- },
219
- {
220
- "name": "phone_stops_before_street_number",
221
- "text": "Restauracja Przykład, ☏ +86 574-2345-6712. 87 ulica Przykładowa. Opis lokalu.",
222
- "mask": [
223
- {
224
- "start": 24,
225
- "end": 41,
226
- "text": "+86 574-2345-6712",
227
- "label": "phone"
228
- }
229
- ],
230
- "preserve": [
231
- {
232
- "start": 41,
233
- "end": 45,
234
- "text": ". 87"
235
- }
236
- ]
237
- },
238
- {
239
- "name": "five_digit_helpline",
240
- "text": "Informacje o usłudze.\n\nInfolinia Centrum Przykład (dla zgłoszeń produkcyjnych): 19 876\n\nDalszy opis usługi.",
241
- "mask": [
242
- {
243
- "start": 80,
244
- "end": 86,
245
- "text": "19 876",
246
- "label": "phone"
247
- }
248
- ],
249
- "preserve": []
250
- },
251
- {
252
- "name": "epuap_list_with_lub",
253
- "text": "Skrytki ePUAP: /przyklad123/skrytka lub /przyklad123/SkrytkaESP, albo\nadres e-mail: biuro@example.com.",
254
- "mask": [
255
- {
256
- "start": 15,
257
- "end": 35,
258
- "text": "/przyklad123/skrytka",
259
- "label": "pii"
260
- },
261
- {
262
- "start": 40,
263
- "end": 63,
264
- "text": "/przyklad123/SkrytkaESP",
265
- "label": "pii"
266
- },
267
- {
268
- "start": 84,
269
- "end": 101,
270
- "text": "biuro@example.com",
271
- "label": "pii"
272
- }
273
- ],
274
- "preserve": []
275
- },
276
- {
277
- "name": "microcontroller_is_not_iban",
278
- "text": "The test device uses the AD0227 microcontroller and transmits sample data.",
279
- "mask": [],
280
- "preserve": [
281
- {
282
- "start": 25,
283
- "end": 51,
284
- "text": "AD0227 microcontroller and"
285
- }
286
- ]
287
- },
288
- {
289
- "name": "helpline_and_support_line_context",
290
- "text": "Całodobowy telefon w sprawie pomocy – 116 789 oraz Linię Wsparcia dla Uczestników - 22 123 45 67.\n\nOsoby dzwoniące na numer 116 789 otrzymują informacje.",
291
- "mask": [
292
- {
293
- "start": 38,
294
- "end": 45,
295
- "text": "116 789",
296
- "label": "phone"
297
- },
298
- {
299
- "start": 84,
300
- "end": 96,
301
- "text": "22 123 45 67",
302
- "label": "phone"
303
- },
304
- {
305
- "start": 124,
306
- "end": 131,
307
- "text": "116 789",
308
- "label": "phone"
309
- }
310
- ],
311
- "preserve": []
312
- },
313
- {
314
- "name": "phone_range_suffix",
315
- "text": "Centrum Przykład, ulica Testowa 12, telefon centrala: 048/ 234 56 71 do 73.\nDalszy opis działalności.",
316
- "mask": [
317
- {
318
- "start": 54,
319
- "end": 74,
320
- "text": "048/ 234 56 71 do 73",
321
- "label": "phone"
322
- }
323
- ],
324
- "preserve": []
325
- },
326
- {
327
- "name": "short_foreign_emergency_numbers",
328
- "text": "Placówka Przykład, ☏ +49341 2345-6, numer bezpłatny: 110 (w nagłych wypadkach).\nPlacówka Testowa, ☏ +49341987-65432, bezpłatny: 110 (w nagłych wypadkach).",
329
- "mask": [
330
- {
331
- "start": 53,
332
- "end": 56,
333
- "text": "110",
334
- "label": "phone"
335
- },
336
- {
337
- "start": 128,
338
- "end": 131,
339
- "text": "110",
340
- "label": "phone"
341
- }
342
- ],
343
- "preserve": []
344
- },
345
- {
346
- "name": "blik_phone_contact",
347
- "text": "Można przesłać środki Blikiem: 794 23 45 67 z dopiskiem Test.\n\nDalsze informacje.",
348
- "mask": [
349
- {
350
- "start": 31,
351
- "end": 43,
352
- "text": "794 23 45 67",
353
- "label": "phone"
354
- }
355
- ],
356
- "preserve": []
357
- },
358
- {
359
- "name": "phone_before_price",
360
- "text": "Bar Przykład, ulica Testowa 12, ☎ +39552345671. 3,00 € za przekąskę. 9-19.",
361
- "mask": [
362
- {
363
- "start": 34,
364
- "end": 46,
365
- "text": "+39552345671",
366
- "label": "phone"
367
- }
368
- ],
369
- "preserve": [
370
- {
371
- "start": 48,
372
- "end": 54,
373
- "text": "3,00 €"
374
- },
375
- {
376
- "start": 69,
377
- "end": 73,
378
- "text": "9-19"
379
- }
380
- ]
381
- },
382
- {
383
- "name": "url_query_digits_are_not_pesel",
384
- "text": "https://example.com/article/?doing_wp_cron=1234567890.44051401458\n12345678901.\nPrzykładowy przypis.",
385
- "mask": [],
386
- "preserve": [
387
- {
388
- "start": 54,
389
- "end": 65,
390
- "text": "44051401458"
391
- }
392
- ]
393
- },
394
- {
395
- "name": "six_digit_helpline",
396
- "text": "Informacja o finansowaniu dla telefonu zaufania, 116 789, jest dostępna w raporcie.",
397
- "mask": [
398
- {
399
- "start": 49,
400
- "end": 56,
401
- "text": "116 789",
402
- "label": "phone"
403
- }
404
- ],
405
- "preserve": []
406
- },
407
- {
408
- "name": "foreign_mobile_dotted_format",
409
- "text": "Ośrodek Przykład, ulica Testowa 12. Tel 075.2345671 Tel. komórkowy 347.2345671. Dalszy opis.",
410
- "mask": [
411
- {
412
- "start": 67,
413
- "end": 78,
414
- "text": "347.2345671",
415
- "label": "phone"
416
- }
417
- ],
418
- "preserve": []
419
- },
420
- {
421
- "name": "trademark_registration_is_not_pii",
422
- "text": "Przykładowy znak towarowy o numerze R-234567 jest chroniony do 2027 roku.",
423
- "mask": [],
424
- "preserve": [
425
- {
426
- "start": 36,
427
- "end": 44,
428
- "text": "R-234567"
429
- }
430
- ]
431
- },
432
- {
433
- "name": "ordinary_phone_keeps_phone_label",
434
- "text": "Biuro Przykład, ☏ +1 202 555-0142, numer bezpłatny: +1 202 555-0143.",
435
- "mask": [
436
- {
437
- "start": 52,
438
- "end": 67,
439
- "text": "+1 202 555-0143",
440
- "label": "phone"
441
- }
442
- ],
443
- "preserve": []
444
- }
445
- ]
446
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/pii_wikivoyage_regression_cases.json DELETED
@@ -1,415 +0,0 @@
1
- {
2
- "synthetic": true,
3
- "policy": "Invented regression examples; no corpus excerpts or document references. Email and web domains use example.com. Phone/identifier values test syntax, not assignment; public emergency codes retain their literal semantics.",
4
- "cases": [
5
- {
6
- "name": "wikivoyage_thai_dialling_and_fax_list",
7
- "text": "Kontakt\n\nPlacówka Przykład\n\nBudynek 123-125, piętro 4\n\nUlica Testowa, 12345 Miasto\n\nStrona www: https://example.com/\n\nTelefony:\n\nCentrala placówki\n\n- dzwoniąc z Polski z tel. stacjonarnego 0066 2 234 5612\n\n- dzwoniąc z Polski z tel. komórkowego +66 2 234 5612\n\n- dzwoniąc z Tajlandii z tel. lokalnego 0 2 234 5612\n\nFax:\n\n- z Polski 0066 2 234 5613\n\n- z Tajlandii 0 2 234 5613\n\nAdresy e-mail:\n\nSekretariat: sekretariat@example.com\n\nBiuro: biuro@example.com\n\nInna placówka\n\nUlica Testowa 2, D - 12345 Miasto\n\nTelefon: +49 30 23 45 67 12\n\nFax: +49 30 23 45 67 13\n\nhttps://branch.example.com\n\nE-mail: kontakt@branch.example.com",
8
- "mask": [
9
- {
10
- "start": 189,
11
- "end": 204,
12
- "text": "0066 2 234 5612",
13
- "label": "phone"
14
- },
15
- {
16
- "start": 245,
17
- "end": 259,
18
- "text": "+66 2 234 5612",
19
- "label": "phone"
20
- },
21
- {
22
- "start": 301,
23
- "end": 313,
24
- "text": "0 2 234 5612",
25
- "label": "phone"
26
- },
27
- {
28
- "start": 332,
29
- "end": 347,
30
- "text": "0066 2 234 5613",
31
- "label": "phone"
32
- },
33
- {
34
- "start": 363,
35
- "end": 375,
36
- "text": "0 2 234 5613",
37
- "label": "phone"
38
- },
39
- {
40
- "start": 406,
41
- "end": 429,
42
- "text": "sekretariat@example.com",
43
- "label": "pii"
44
- },
45
- {
46
- "start": 438,
47
- "end": 455,
48
- "text": "biuro@example.com",
49
- "label": "pii"
50
- },
51
- {
52
- "start": 516,
53
- "end": 534,
54
- "text": "+49 30 23 45 67 12",
55
- "label": "phone"
56
- },
57
- {
58
- "start": 541,
59
- "end": 559,
60
- "text": "+49 30 23 45 67 13",
61
- "label": "phone"
62
- },
63
- {
64
- "start": 597,
65
- "end": 623,
66
- "text": "kontakt@branch.example.com",
67
- "label": "pii"
68
- }
69
- ],
70
- "preserve": [
71
- {
72
- "start": 36,
73
- "end": 43,
74
- "text": "123-125"
75
- },
76
- {
77
- "start": 70,
78
- "end": 75,
79
- "text": "12345"
80
- },
81
- {
82
- "start": 489,
83
- "end": 498,
84
- "text": "D - 12345"
85
- }
86
- ]
87
- },
88
- {
89
- "name": "wikivoyage_italian_restaurant_directory",
90
- "text": "Restauracje:\nLokal Alfa, ulica Testowa 12, +39 0575-234561. 19:00-23:00. 15-30 EUR.\nLokal Beta, ulica Testowa 14, ☏ + 39-0575 23456. Opis restauracji.\nLokal Gamma, ulica Testowa 16, ☏ +39 0575234567. Menu za 25 lub 20 €.\nLokal Delta, ulica Testowa 18, ☏ +39 0575 23457. Oferta lokalu.\n\nNapoje\nLokal Epsilon, ulica Testowa 20, ☏ +39 057523458. 11:30-24:00. 15-30 EUR.\nLokal Zeta, ulica Testowa 22. 06:00-20:30. Opis przykładowej oferty.\nLokal Eta, ulica Testowa 24, +39 0575 234562. Opis lokalu.\n\nFestiwale",
91
- "mask": [
92
- {
93
- "start": 116,
94
- "end": 131,
95
- "text": "+ 39-0575 23456",
96
- "label": "phone"
97
- },
98
- {
99
- "start": 184,
100
- "end": 198,
101
- "text": "+39 0575234567",
102
- "label": "phone"
103
- },
104
- {
105
- "start": 254,
106
- "end": 268,
107
- "text": "+39 0575 23457",
108
- "label": "phone"
109
- },
110
- {
111
- "start": 328,
112
- "end": 341,
113
- "text": "+39 057523458",
114
- "label": "phone"
115
- },
116
- {
117
- "start": 465,
118
- "end": 480,
119
- "text": "+39 0575 234562",
120
- "label": "phone"
121
- }
122
- ],
123
- "preserve": [
124
- {
125
- "start": 208,
126
- "end": 219,
127
- "text": "25 lub 20 €"
128
- },
129
- {
130
- "start": 343,
131
- "end": 354,
132
- "text": "11:30-24:00"
133
- },
134
- {
135
- "start": 397,
136
- "end": 408,
137
- "text": "06:00-20:30"
138
- }
139
- ]
140
- },
141
- {
142
- "name": "wikivoyage_chinese_hotel_directory",
143
- "text": "Hotel Alfa, ulica Testowa 12, ☏ +86 351 2345612.\nHotel Beta, 115 ulica Testowa. Pokoje z dostępem do sieci. Cena od 188¥.\nHotel Gamma, 99 ulica Testowa, +86 351 2345613.\n\nUmiarkowanie\nHotel Delta, ulica Testowa 14, ☏ +86 351 2345614, faks: +86 351 2345615.\nHotel Epsilon, ulica Testowa 16, ☏ +86 351 2345616, faks: +86 351 2345617.\nHotel Zeta, ulica Testowa 18, ☏ +86 351 2345618, faks: +86 351 2345619.\n\nEkskluzywnie\nHotel Eta, ulica Testowa 20, ☏ +86 351 2345621.\nHotel Theta, ulica Testowa 22, +86-21-23456712 wew. 1234, rezerwacja@example.com. 5-gwiazdkowy hotel z restauracją.\n\nKontakt",
144
- "mask": [
145
- {
146
- "start": 153,
147
- "end": 168,
148
- "text": "+86 351 2345613",
149
- "label": "phone"
150
- },
151
- {
152
- "start": 217,
153
- "end": 232,
154
- "text": "+86 351 2345614",
155
- "label": "phone"
156
- },
157
- {
158
- "start": 240,
159
- "end": 255,
160
- "text": "+86 351 2345615",
161
- "label": "phone"
162
- },
163
- {
164
- "start": 292,
165
- "end": 307,
166
- "text": "+86 351 2345616",
167
- "label": "phone"
168
- },
169
- {
170
- "start": 315,
171
- "end": 330,
172
- "text": "+86 351 2345617",
173
- "label": "phone"
174
- },
175
- {
176
- "start": 364,
177
- "end": 379,
178
- "text": "+86 351 2345618",
179
- "label": "phone"
180
- },
181
- {
182
- "start": 387,
183
- "end": 402,
184
- "text": "+86 351 2345619",
185
- "label": "phone"
186
- },
187
- {
188
- "start": 449,
189
- "end": 464,
190
- "text": "+86 351 2345621",
191
- "label": "phone"
192
- },
193
- {
194
- "start": 497,
195
- "end": 522,
196
- "text": "+86-21-23456712 wew. 1234",
197
- "label": "phone"
198
- },
199
- {
200
- "start": 524,
201
- "end": 546,
202
- "text": "rezerwacja@example.com",
203
- "label": "pii"
204
- }
205
- ],
206
- "preserve": [
207
- {
208
- "start": 61,
209
- "end": 78,
210
- "text": "115 ulica Testowa"
211
- },
212
- {
213
- "start": 116,
214
- "end": 120,
215
- "text": "188¥"
216
- },
217
- {
218
- "start": 135,
219
- "end": 151,
220
- "text": "99 ulica Testowa"
221
- },
222
- {
223
- "start": 548,
224
- "end": 560,
225
- "text": "5-gwiazdkowy"
226
- }
227
- ]
228
- },
229
- {
230
- "name": "wikivoyage_labelled_damaged_phone",
231
- "text": "Wstęp na teren ośrodka:\nWejście w godz. 7.00-18.00\nNormalny – 4,00 zł\nPowierzchnia 2040 ha.\n\nGastronomia\nRestauracje, pizzerie\nLokal Alfa, ulica Testowa 12; tel. 77-234-56-712\nLokal Beta; tel. 77 234 56 71\nLokal Gamma; tel. 77-234-56-72\nLokal Delta; tel. 77-234-56-73\nLokal Epsilon; tel. 77-234-56-74\nLokal Zeta; tel: 77-234-56-75\nLokal Eta; tel: 77-234-56-76\nLokal Theta, tel. 730234567\nLokal Iota, tel. 77 2345677\nLokal Kappa, tel 602234571\nLokal Lambda, tel. 77 2345678\n\nPuby\nLokal Mu; tel. 77-234-56-79\nLokal Nu; tel. []",
232
- "mask": [
233
- {
234
- "start": 162,
235
- "end": 175,
236
- "text": "77-234-56-712",
237
- "label": "phone"
238
- },
239
- {
240
- "start": 193,
241
- "end": 205,
242
- "text": "77 234 56 71",
243
- "label": "phone"
244
- },
245
- {
246
- "start": 224,
247
- "end": 236,
248
- "text": "77-234-56-72",
249
- "label": "phone"
250
- },
251
- {
252
- "start": 255,
253
- "end": 267,
254
- "text": "77-234-56-73",
255
- "label": "phone"
256
- },
257
- {
258
- "start": 288,
259
- "end": 300,
260
- "text": "77-234-56-74",
261
- "label": "phone"
262
- },
263
- {
264
- "start": 318,
265
- "end": 330,
266
- "text": "77-234-56-75",
267
- "label": "phone"
268
- },
269
- {
270
- "start": 347,
271
- "end": 359,
272
- "text": "77-234-56-76",
273
- "label": "phone"
274
- },
275
- {
276
- "start": 378,
277
- "end": 387,
278
- "text": "730234567",
279
- "label": "phone"
280
- },
281
- {
282
- "start": 405,
283
- "end": 415,
284
- "text": "77 2345677",
285
- "label": "phone"
286
- },
287
- {
288
- "start": 433,
289
- "end": 442,
290
- "text": "602234571",
291
- "label": "phone"
292
- },
293
- {
294
- "start": 462,
295
- "end": 472,
296
- "text": "77 2345678",
297
- "label": "phone"
298
- },
299
- {
300
- "start": 494,
301
- "end": 506,
302
- "text": "77-234-56-79",
303
- "label": "phone"
304
- }
305
- ],
306
- "preserve": [
307
- {
308
- "start": 40,
309
- "end": 50,
310
- "text": "7.00-18.00"
311
- },
312
- {
313
- "start": 62,
314
- "end": 69,
315
- "text": "4,00 zł"
316
- },
317
- {
318
- "start": 83,
319
- "end": 90,
320
- "text": "2040 ha"
321
- }
322
- ]
323
- },
324
- {
325
- "name": "wikivoyage_hungarian_hotel_directory",
326
- "text": "Hotel Alfa, ulica Testowa 12, ☏ +36 84 234561, ✉ alfa@example.com. Pokój Ft 18 000–27 000.\nHotel Beta, ulica Testowa 14, ☏ +36 30 2345671. Zameldowanie: 10:00, wymeldowanie: 14:00.\nHotel Gamma, ulica Testowa 16, ☏ +36 84 234 562, ✉ gamma@example.com. Dodatkowe łóżko Ft 4500-11500.\nHotel Delta, ulica Testowa 18, delta@example.com. Od 15 € / noc / osoba.\nHotel Epsilon, ulica Testowa 20, ✉ epsilon@example.com. 14-27 € / noc / osoba.\nHotel Zeta, restauracja i bar, ulica Testowa 22, +36 84 234 563. Oferta noclegów.",
327
- "mask": [
328
- {
329
- "start": 123,
330
- "end": 137,
331
- "text": "+36 30 2345671",
332
- "label": "phone"
333
- },
334
- {
335
- "start": 214,
336
- "end": 228,
337
- "text": "+36 84 234 562",
338
- "label": "phone"
339
- },
340
- {
341
- "start": 232,
342
- "end": 249,
343
- "text": "gamma@example.com",
344
- "label": "pii"
345
- },
346
- {
347
- "start": 313,
348
- "end": 330,
349
- "text": "delta@example.com",
350
- "label": "pii"
351
- },
352
- {
353
- "start": 390,
354
- "end": 409,
355
- "text": "epsilon@example.com",
356
- "label": "pii"
357
- },
358
- {
359
- "start": 483,
360
- "end": 497,
361
- "text": "+36 84 234 563",
362
- "label": "phone"
363
- }
364
- ],
365
- "preserve": [
366
- {
367
- "start": 73,
368
- "end": 89,
369
- "text": "Ft 18 000–27 000"
370
- },
371
- {
372
- "start": 267,
373
- "end": 280,
374
- "text": "Ft 4500-11500"
375
- }
376
- ]
377
- },
378
- {
379
- "name": "wikivoyage_qualified_mobile_label",
380
- "text": "Nauka\nSzkoła Przykład oferuje kursy od 1 tygodnia/20 godzin do 4 tygodni/80 godzin (~360 USD). Kontakt: nauka@example.com.\nZajęcia taneczne w szkole Testowej. Kontakt: taniec@example.com. Telefon komórkowy: (53) 05 234567123.\n\nZakupy\nPrzykładowe informacje o mieście.",
381
- "mask": [
382
- {
383
- "start": 104,
384
- "end": 121,
385
- "text": "nauka@example.com",
386
- "label": "pii"
387
- },
388
- {
389
- "start": 168,
390
- "end": 186,
391
- "text": "taniec@example.com",
392
- "label": "pii"
393
- },
394
- {
395
- "start": 207,
396
- "end": 224,
397
- "text": "(53) 05 234567123",
398
- "label": "phone"
399
- }
400
- ],
401
- "preserve": [
402
- {
403
- "start": 39,
404
- "end": 59,
405
- "text": "1 tygodnia/20 godzin"
406
- },
407
- {
408
- "start": 84,
409
- "end": 92,
410
- "text": "~360 USD"
411
- }
412
- ]
413
- }
414
- ]
415
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/scrub_entities.py DELETED
@@ -1,160 +0,0 @@
1
- """PERSON-only NER replace for allowlisted web sources.
2
-
3
- FastPDN (ArkadiuszPawlak/fastpdn-ner-polish-pii, ONNX) tags person / street /
4
- city / org. We replace only PERSON* and expand to the whole word so a
5
- HerBERT hole cannot leave `[PII]ru[PII]`. Official and encyclopaedic sources
6
- are default-deny — names there are the content.
7
-
8
- Call after scrub_pii. Needs: pip install huggingface_hub tokenizers onnxruntime
9
- """
10
- from __future__ import annotations
11
-
12
- import json
13
- import re
14
- from pathlib import Path
15
-
16
- from scrub_pii import PII_TAG
17
-
18
- MODEL_ID = "ArkadiuszPawlak/fastpdn-ner-polish-pii"
19
- PERSON_LABELS = frozenset({"PERSON", "PERSON_F", "PERSON_L"})
20
- NER_SOURCES = frozenset({
21
- "european_hplt_v3_pl",
22
- "govpl",
23
- "samorzad_gov_pl",
24
- })
25
- _WORD = re.compile(r"[0-9A-Za-zÀ-ÿĄąĆćĘꣳŃńÓóŚśŹźŻż'-]")
26
-
27
- _NER = None
28
-
29
-
30
- def source_allows_ner(source: str) -> bool:
31
- return source in NER_SOURCES
32
-
33
-
34
- def _expand(text: str, start: int, end: int) -> tuple[int, int]:
35
- while start > 0 and _WORD.match(text[start - 1]):
36
- start -= 1
37
- while end < len(text) and _WORD.match(text[end]):
38
- end += 1
39
- return start, end
40
-
41
-
42
- def apply_person_spans(text: str, spans: list[dict]) -> tuple[str, int]:
43
- """Replace PERSON* spans with [PII]. City/org/street spans are ignored."""
44
- kept: list[tuple[int, int]] = []
45
- for s in spans:
46
- if s.get("label") not in PERSON_LABELS:
47
- continue
48
- a, b = _expand(text, int(s["start"]), int(s["end"]))
49
- if a < b:
50
- kept.append((a, b))
51
- kept.sort()
52
- merged: list[tuple[int, int]] = []
53
- for a, b in kept:
54
- if merged and a <= merged[-1][1]:
55
- merged[-1] = (merged[-1][0], max(merged[-1][1], b))
56
- else:
57
- merged.append((a, b))
58
- out = text
59
- for a, b in reversed(merged):
60
- out = out[:a] + PII_TAG + out[b:]
61
- return out, len(merged)
62
-
63
-
64
- def load_ner():
65
- import onnxruntime as ort
66
- from huggingface_hub import hf_hub_download
67
- from tokenizers import Tokenizer
68
-
69
- cfg = json.loads(Path(hf_hub_download(MODEL_ID, "config.json")).read_text())
70
- tok = Tokenizer.from_file(hf_hub_download(MODEL_ID, "tokenizer.json"))
71
- tok.enable_truncation(max_length=512)
72
- sess = ort.InferenceSession(
73
- hf_hub_download(MODEL_ID, "model_quantized.onnx"),
74
- providers=["CPUExecutionProvider"],
75
- )
76
- return {
77
- "sess": sess,
78
- "tok": tok,
79
- "id2label": {int(k): v for k, v in cfg["id2label"].items()},
80
- }
81
-
82
-
83
- def _aggregate(text: str, labels: list[str], offsets, scores) -> list[dict]:
84
- spans = []
85
- cur = None
86
- for lab, (start, end), score in zip(labels, offsets, scores):
87
- if start == end or lab == "O" or "-" not in lab:
88
- if cur:
89
- spans.append(cur)
90
- cur = None
91
- continue
92
- prefix, typ = lab.split("-", 1)
93
- if cur and cur["label"] == typ and start <= cur["end"] + 1:
94
- cur["end"] = end
95
- cur["scores"].append(score)
96
- elif prefix == "B" or cur is None or cur["label"] != typ:
97
- if cur:
98
- spans.append(cur)
99
- cur = {"label": typ, "start": start, "end": end, "scores": [score]}
100
- else:
101
- cur["end"] = end
102
- cur["scores"].append(score)
103
- if cur:
104
- spans.append(cur)
105
- return [
106
- {
107
- "label": s["label"],
108
- "text": text[s["start"]:s["end"]],
109
- "score": round(sum(s["scores"]) / len(s["scores"]), 3),
110
- "start": s["start"],
111
- "end": s["end"],
112
- }
113
- for s in spans
114
- ]
115
-
116
-
117
- def predict(ner, text: str) -> list[dict]:
118
- import numpy as np
119
-
120
- enc = ner["tok"].encode(text)
121
- ids = np.array([enc.ids], dtype=np.int64)
122
- mask = np.array([enc.attention_mask], dtype=np.int64)
123
- logits = ner["sess"].run(
124
- None,
125
- {
126
- "input_ids": ids,
127
- "attention_mask": mask,
128
- "token_type_ids": np.zeros_like(ids),
129
- },
130
- )[0][0]
131
- pred = logits.argmax(axis=-1)
132
- shift = logits - logits.max(axis=-1, keepdims=True)
133
- exp = np.exp(shift)
134
- prob = exp / exp.sum(axis=-1, keepdims=True)
135
- labels = [ner["id2label"][int(i)] for i in pred]
136
- scores = [float(prob[i, int(pred[i])]) for i in range(len(pred))]
137
- return _aggregate(text, labels, enc.offsets, scores)
138
-
139
-
140
- def _ner():
141
- global _NER
142
- if _NER is None:
143
- _NER = load_ner()
144
- return _NER
145
-
146
-
147
- def scrub_entities(
148
- text: str,
149
- source: str,
150
- spans: list[dict] | None = None,
151
- ) -> tuple[str, dict[str, int]]:
152
- """Return (text, {person: n}). No-op unless source is in NER_SOURCES."""
153
- counts = {"person": 0}
154
- if not text or not source_allows_ner(source):
155
- return text, counts
156
- if spans is None:
157
- spans = predict(_ner(), text)
158
- out, n = apply_person_spans(text, spans)
159
- counts["person"] = n
160
- return out, counts
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/scrub_pii.py DELETED
@@ -1,677 +0,0 @@
1
- """Regex PII scrub for Polish web/official text.
2
-
3
- Replaces emails, phones, PESEL/NIP/REGON/KRS, electronic contact addresses and account numbers in place so
4
- sentence structure survives. Names of public officials are left untouched —
5
- that is intentional, not a gap. Phones map to [Telefon]; everything else
6
- to [PII]. Bare PESEL requires checksum and date validation; explicit identifier
7
- labels also redact damaged numbers (including common OCR O/I/l substitutions).
8
- NIP/REGON/KRS and identity documents require explicit nearby labels. Passport
9
- variants include one-letter and diplomatic IDs. Foreign IBANs use country
10
- lengths and MOD-97. ePUAP paths require a label; e-Doreczenia uses its AE:PL form.
11
- Wrapped email domains and small extraction gaps around @/hyphens are supported.
12
- Explicit phone extensions and terminal suffix ranges are included; room numbers are not. Labelled numeric
13
- PINs (including URL pin= values) map to [PII] before phone detection.
14
- Contact/helpline headings cover consecutive descriptive phone-list entries;
15
- unrelated lines end the list. Bounded staff/address-directory evidence also covers
16
- formatted phone fields. Labelled full-number ranges retain shared prefixes.
17
- Phones require a nearby contact cue, a Polish +48/0048 prefix, or explicit
18
- international country/trunk notation such as +CC (0). Short service numbers
19
- need strong labels; 116xxx numbers also accept nearby telephone prose. Unlabelled
20
- domestic numbers are left for audit because table cells have the same shapes.
21
-
22
- Call after HTML-to-text, before the parquet is written.
23
- """
24
- from __future__ import annotations
25
- import datetime as dt
26
- import re
27
-
28
- PHONE_TAG = "[Telefon]"
29
- PII_TAG = "[PII]"
30
- COUNTS = ("email", "phone", "pesel", "nip", "regon", "account", "document", "krs", "electronic_address", "pin")
31
-
32
- # Mobile + geographic area codes (2-digit national prefix after trunk 0 / +48).
33
- _PL_PREFIX = {
34
- "12", "13", "14", "15", "16", "17", "18", "22", "23", "24", "25", "26", "29",
35
- "32", "33", "34", "39", "41", "42", "43", "44", "45", "46", "47", "48",
36
- "50", "51", "52", "53", "54", "55", "56", "57", "58", "59",
37
- "60", "61", "62", "63", "65", "66", "67", "68", "69",
38
- "70", "71", "72", "73", "74", "75", "76", "77", "78", "79",
39
- "80", "81", "82", "83", "84", "85", "86", "87", "88", "89",
40
- "91", "94", "95",
41
- }
42
-
43
- _EMAIL_DOMAIN = r"[^\W_](?:[^\W_]|-[ \t]{0,3}(?=[^\W_]))*"
44
- _EMAIL_START = r"\b[\w.%+&-]+[ \t]{0,3}@"
45
- _EMAIL_RE = re.compile(_EMAIL_START + r"[ \t]{0,3}(?:" + _EMAIL_DOMAIN + r"\.)+[^\W\d_]{2,}\b")
46
- _EMAIL_WRAP_RE = re.compile(_EMAIL_START + r"[ \t]{0,3}(?:" + _EMAIL_DOMAIN
47
- + r"\.)+[ \t]*\r?\n[ \t]*(?:" + _EMAIL_DOMAIN + r"\.)*[^\W\d_]{2,}\b")
48
- # Damaged contact fields can retain only the local part and @.
49
- _EMAIL_FRAGMENT_RE = re.compile(_EMAIL_START + r"(?=[ \t]*\r?$)", re.M)
50
- _EMAIL_LABEL_RE = re.compile(r"\be[ -]?mail[ \t]*:[ \t]*\Z", re.I)
51
- _EDELIVERY_RE = re.compile(r"\bAE:PL-\d{5}-\d{5}-[A-Z0-9]{5}-\d{2}(?![\w-])", re.I)
52
- _EPUAP_RE = re.compile(r"(?<![\w/])/[\w-]+/[\w-]+(?![\w/-])")
53
- _EPUAP_LABEL_RE = re.compile(
54
- r"\b(?:e[ -]?puap|elektroniczna[ \t]+skrzynka[ \t]+podawcza)\b[^\n/\[\]]{0,50}\Z", re.I)
55
- _PIN_RE = re.compile(
56
- r"(?P<label>\bPIN[ \t]*[:=][ \t]*)"
57
- r"(?P<number>[\u202a-\u202e\u2066-\u2069]*\d(?:[ \t]?\d){3,15}#?)"
58
- r"(?!\w|[ \t]*\d)", re.I)
59
- # Horizontal Unicode spaces from HTML/PDF extraction; preserve paragraph breaks.
60
- _SPACES = str.maketrans({c: " " for c in "\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000"})
61
- # Country lengths checked against Apache Commons Validator's IBAN registry table:
62
- # https://commons.apache.org/proper/commons-validator/xref/org/apache/commons/validator/routines/IBANValidator.html
63
- # ponytail: country/length/MOD-97 only; add national BBAN rules if false positives appear.
64
- _IBAN_LENGTHS = {
65
- country: length for length, countries in {
66
- 15: "NO", 16: "BE", 18: "DK FI AX FK FO GL NL SD",
67
- 19: "MK SI", 20: "AT BA EE KZ LT LU MN XK",
68
- 21: "CH HR LI LV", 22: "BG BH CR DE GB IM JE GG GE IE ME RS VA",
69
- 23: "AE GI IL IQ OM SO TL", 24: "AD CZ ES MD PK RO SA SE SK TN VG",
70
- 25: "LY PT ST", 26: "IS TR",
71
- 27: "BI DJ FR GF GP MQ RE PF TF YT NC BL MF PM WF GR IT MC MR SM",
72
- 28: "AL AZ BY CY DO GT HN HU LB NI PL SV", 29: "BR EG PS QA UA",
73
- 30: "JO KW MU YE", 31: "MT SC", 32: "LC", 33: "RU",
74
- }.items() for country in countries.split()
75
- }
76
- _IBAN_RE = re.compile(
77
- r"\b(?:" + "|".join(
78
- country + r"[ \t-]*[0-9]{2}(?:[ \t-]*[A-Z0-9]){" + str(length - 4) + "}"
79
- for country, length in _IBAN_LENGTHS.items()
80
- ) + r")\b", re.I,
81
- )
82
- # Optional PL, then 26 digits with short space/tab/hyphen gaps (invoice style).
83
- _ACCOUNT_RE = re.compile(r"\b(?:PL[ \t-]*)?(?:\d[ \t-]*){25}\d\b", re.I)
84
- _REGON14_RE = re.compile(r"\b\d{14}\b")
85
- _PESEL_RE = re.compile(r"\b\d{11}\b")
86
- _NIP_DASH_RE = re.compile(r"\b(?:PL[ \t]*)?\d{3}(?:[- \t]\d{3}[- \t]\d{2}[- \t]\d{2}|[- \t]\d{2}[- \t]\d{2}[- \t]\d{3})\b", re.I)
87
- _NIP_RE = re.compile(r"\b(?:PL[ \t]*)?\d{10}\b", re.I)
88
- _DOCUMENT_RE = re.compile(
89
- r"\b(?P<label>(?:dow[oó]d(?:u|em)?[ \t]+osobist(?:y|ego|ym)|"
90
- r"(?:nr|numer)[ \t]+dowodu|paszport(?:u|em)?(?:[ \t]+dyplomatyczn(?:y|ego|ym))?)"
91
- r"[ \t]*(?:(?:seria[ \t]+i[ \t]+numer|serii|seria|numer|nr)\.?[ \t]*)?"
92
- r"[:=-]?[ \t]*)"
93
- r"(?P<number>[A-Z]{3}[ \t-]?[0-9OIl]{6}|[A-Z]{2}[ \t-]?[0-9OIl]{7}|[A-Z][ \t-]?[0-9]{6,9}|[0-9]{4,12})\b", re.I,
94
- )
95
- _LABELLED_ID_RE = re.compile(
96
- r"\b(?P<label>(?P<kind>PESEL|NIP|REGON)\b"
97
- r"(?:[ \t]+(?:Gminy|Powiatu|Miasta|firmy)(?:[ \t]+[^\W\d_][^\W\d_-]*){0,4})?[ \t]{0,8}"
98
- r"(?:(?:nr\.?|numer)[ \t]{0,8})?[:=.\-]?[ \t]{0,8}(?:\r?\n[ \t]{0,8})?)"
99
- r"(?P<number>(?:PL[ \t]*)?(?:[0-9OIl]{9,14}|\d(?:[ \t-]?\d){8,13}))"
100
- r"(?!\w|[ \t-]*\d)", re.I,
101
- )
102
- _REGON9_RE = re.compile(r"\b\d{9}\b")
103
- _ID_LABEL_END = r"[ \t]{0,8}(?:(?:nr\.?|numer)[ \t]{0,8})?[:=.\-]?[ \t]{0,8}(?:\r?\n[ \t]{0,8})?\Z"
104
- _NIP_LABEL_RE = re.compile(r"\bNIP\b" + _ID_LABEL_END, re.I)
105
- _REGON_LABEL_RE = re.compile(r"\bREGON\b" + _ID_LABEL_END, re.I)
106
- _KRS_RE = re.compile(r"\b\d{6,10}(?!\w|[ \t-]*\d)")
107
- _KRS_LABEL_RE = re.compile(r"\bKRS\b" + _ID_LABEL_END, re.I)
108
- # Separators are short and local: one newline *or* a few punct/spaces.
109
- # Letters and blank lines break the match so body text is not swallowed.
110
- _SEP = r"(?:[ \t./\-()\u2013\u2014]{0,3}|\n)"
111
- _VANITY_PHONE_RE = re.compile(
112
- r"(?<!\w)\+1[ \t-]+\d{3}[ \t-]+(?:\d{3}-[A-Z]{4}|[A-Z]{7})"
113
- r"(?:[ \t]+\(\d{4,7}\))?(?!\w)")
114
- _PHONE_RE = re.compile(
115
- _VANITY_PHONE_RE.pattern + r"|(?:(?<!\w)|(?<=telefon)|(?<=tel)|(?<=faks)|(?<=fax))(?:\(?\+[ \t]*)?"
116
- r"(?:\((?:0|0?\d{2,4}(?:-\d{1,2})?)\)" + _SEP + r")?"
117
- r"\d(?:" + _SEP + r"\d){4,}(?!\w)", re.I,
118
- )
119
- _SHORT_PHONE_LABEL_RE = re.compile(
120
- r"(?:\b(?:tel(?:efon\w*)?(?:(?:\.[ \t]*|[ \t]+)(?:kom[oó]rk\w*|lokaln\w*|stacjonarn\w*))?|fax|faks(?:em)?|phone|"
121
- r"toll[ -]free|numer[ \t]+bezpłatny)|[☎☏📞📱])[.: \t/]{0,8}\Z|"
122
- r"\binfolini[^\W\d_]*[^\d\n]{0,80}:[ \t]*\Z", re.I)
123
- _PHONE_LABEL_RE = re.compile(
124
- r"\b(?:tel(?:efon[^\W\d_]*)?|fax|faks(?:em)?|kom(?:[oó]rk[^\W\d_]*)?|gsm|"
125
- r"infolini[^\W\d_]*|(?:za)?dzwo[ńn][^\W\d_]*|Blikiem|"
126
- r"lini[ęaąie][ \t]+wsparcia)(?![^\W\d_])|"
127
- r"\bkontakt(?=tel[.:])|[☎☏📞📱]", re.I,
128
- )
129
- _PHONE_BREAK_RE = re.compile(
130
- r"\n|\.[ \t]+(?=\d)|[ \t]+(?=\(?(?:[01]?\d|2[0-3])[.:][0-5]\d"
131
- r"|\d{1,2}[.)][ \t]+\d{1,2}[./]\d{1,2}[./](?:19|20)\d{2})")
132
- _PHONE_EXTENSION_RE = re.compile(r"(?:(?:[ \t]+,?[ \t]*|,[ \t]*)wew(?:n(?:ętrzny)?)?\.?[ \t]*\d{1,5}|[ \t]+do[ \t]+\d{1,3}(?=[ \t]*(?:[.;,](?!\d)|\r?\n|\Z)))(?!\w|[ \t]*\d)", re.I)
133
- _SERVICE_PHONE_RE = re.compile(r"(?<![\w+])[1-9]\d{2}(?![\w\d]|[ \t./()-]*\d)")
134
- _SERVICE_PHONE_LABEL_RE = re.compile(
135
- r"(?:\b(?:tel(?:efon\w*)?|phone)[.: \t]{0,8}(?:alarmow\w*[.: \t]{0,8})?|"
136
- r"\b(?:numer[ \t]+)?bezpłatny[.: \t]{0,8}|"
137
- r"\b(?:bezpłatny[ \t]+)?numer[ \t]+alarmowy[.: \t]{0,8}|"
138
- r"(?:^|\n)[ \t]*(?:Straż pożarna|Policja|Pogotowie|Ratunek|Lekarz pogotowia ratunkowego)"
139
- r"(?:[ \t]+\([^()\n]{1,60}\))?[ \t]*:[ \t]*)"
140
- r"(?:[1-9]\d{2}[ \t]*(?:[,;]|i|lub|oraz)[ \t]*)*\Z", re.I)
141
- _OTHER_NUMBER_LABEL_RE = re.compile(r"\b(?:NIP|REGON|PESEL|KRS|ISBN|kod)\b[^\d\n]{0,20}\Z", re.I)
142
- _PHONE_LIST_HEADING_RE = re.compile(
143
- r"[ \t]*(?:numery[ \t]+kontaktowe|telefony(?:[ \t]+(?:kontaktowe|zaufania))?|fax|faks|zapisz[ \t]+się|"
144
- r"(?:[^.!?\n]{0,40}\?[ \t]*)?(?:za)?dzwoń!?)"
145
- r"(?:[ \t]*\([^()\n]{1,80}\))?[ \t]*:?[ \t]*", re.I)
146
- _CONTACT_INTRO_RE = re.compile(
147
- r"\b(?:kontakt\b|zapisy\b|zapisz[ \t]+się\b|rejestracja\b)"
148
- r"(?:nr\.|[^\n.!?;]){0,75}\Z", re.I)
149
- _PHONE_HEADING_RE = re.compile(
150
- r"(?<!\[)\b(?:tel(?:efon[^\W\d_]*)?\b|kontakt\b|zapisy\b|zapisz[ \t]+się\b|"
151
- r"(?:za)?dzwo[ńn][^\W\d_]*\b|(?:pod|na)[ \t]+numer(?:em)?)"
152
- r"(?:tj\.|nr\.|[^\d\n.!?;\[\]]){0,75}:?[ \t]*(?:\n[ \t]*){1,4}\Z", re.I)
153
- _CONTACT_EXCLUDE_RE = re.compile(r"\b(?:spraw\w*|kod\w*|kwot\w*|statystyk\w*|taryf\w*)\b", re.I)
154
- _PHONE_LINE_RE = re.compile(r"(?<!\w)\d{2,3}(?:[ \t-]\d{2,4}){2,3}(?!\w)")
155
- _STAFF_ROLE_RE = re.compile(
156
- r"\b(?:inspektor|referent|koordynator|psycholog|księgowość|księgowy|księgowa|"
157
- r"pracownicy[ \t]+socjalni|łowczy|podłowczy)\b", re.I)
158
-
159
-
160
- def _phone_list_context(text: str, start: int) -> bool:
161
- # ponytail: 2,000-character lookback and 400-character entry suffix; longer
162
- # lists need repeated headings or a section parser. Never cross prose.
163
- end = text.find('\n', start, start + 401)
164
- if end < 0 and len(text) > start + 400:
165
- return False
166
- lines = text[max(0, start - 2000):end if end >= 0 else len(text)].splitlines()
167
- if start > 2000:
168
- lines = lines[1:] # A truncated line cannot establish a heading.
169
- for i, line in enumerate(reversed(lines)):
170
- if _PHONE_LIST_HEADING_RE.fullmatch(line):
171
- return i > 0
172
- if not line.strip():
173
- continue
174
- phone = _PHONE_RE.search(line)
175
- if not phone or not _phone_ok(phone[0], short=True) or _is_amount(line, *phone.span()):
176
- return False
177
- if i == 0 and phone.start() != start - (text.rfind('\n', 0, start) + 1):
178
- return False # Numbers in an entry's description are not list items.
179
- before, after = line[:phone.start()].strip(), line[phone.end():].strip()
180
- if _OTHER_NUMBER_LABEL_RE.search(before):
181
- return False
182
- # Either "City: number" or "number – helpline description". Bare
183
- # numeric rows are ambiguous even below an earlier contact heading.
184
- named = re.fullmatch(r"[^\W\d_][^\d\n:;]{0,79}[:–—-]", before)
185
- described = before in ('', '•', '-', '*') and re.match(r"[–—-][ \t]+[^\W\d_]", after)
186
- dialling = re.fullmatch(r"[-•*]?[ \t]*(?:dzwoniąc[ \t]+)?z[ \t]+[^\W\d_][^\d\n:;.!?]{0,100}", before, re.I)
187
- if not (((named or dialling) and after in ('', ',', ';', '.')) or described):
188
- return False
189
- return False
190
-
191
-
192
- def _phone_context(text: str, start: int, raw: str) -> bool:
193
- # A previous redaction is a boundary, not a fresh "Telefon" cue. Include
194
- # one marker's extra width so the 75-character window cannot bisect it.
195
- before = re.split(r"\n[ \t]*\n|\[Telefon\]|\[PII\]",
196
- text[max(0, start - 75 - len(PHONE_TAG)):start])[-1][-75:]
197
- if _OTHER_NUMBER_LABEL_RE.search(before):
198
- return False
199
- intro = _CONTACT_INTRO_RE.search(before)
200
- if intro and not _CONTACT_EXCLUDE_RE.search(intro[0]):
201
- return True
202
- # A contact email must not erase an explicit contact label for the phone
203
- # following it. Other redactions still form boundaries.
204
- if re.search(r'\bkontakt[ \t]*:[ \t]*\[PII\][ \t,;]*\Z',
205
- text[max(0, start-75):start], re.I):
206
- return True
207
- lead = re.split(r'\[Telefon\]|\[PII\]', text[max(0, start-240):start])[-1]
208
- # "Pod numerem" also introduces contract/case references. Require a
209
- # communication cue when the number has no explicit telephone label.
210
- number_contact = bool((_PHONE_LABEL_RE.search(lead) or re.search(
211
- r'\b(?:informacj[^\W\d_]*|zgłosz[^\W\d_]*|zapis[^\W\d_]*|SMS(?:-a)?|połączeni[^\W\d_]*)\b', lead, re.I))
212
- and not _CONTACT_EXCLUDE_RE.search(lead)
213
- and not re.search(r'\b(?:umow|faktur|dokument)[^\W\d_]*\b', lead, re.I))
214
- heading = _PHONE_HEADING_RE.search(text[max(0, start-160):start])
215
- if (heading and not _CONTACT_EXCLUDE_RE.search(heading[0])
216
- and (not re.match(r'(?:pod|na)\b', heading[0], re.I)
217
- or _PHONE_LABEL_RE.search(heading[0]) or number_contact)):
218
- return True
219
- if (number_contact and re.search(r'\b(?:pod[ \t]+numerem|na[ \t]+numer)[ \t]*:?[ \t]*\Z', before, re.I)):
220
- return True
221
- if re.search(r'\bтелефону[ \t]*:[ \t]*\Z', before, re.I):
222
- return True
223
- # An international phone may precede a labelled fax in the same contact list.
224
- # Keep this cue adjacent: arbitrary later contact prose is not evidence.
225
- after = text[start + len(raw):start + len(raw) + 40]
226
- if re.match(r'[ \t]*[–—-][ \t]+telefon\b', after, re.I):
227
- return True
228
- if (re.match(r"\(?(?:\+|00)", raw)
229
- and re.match(r"[ \t]*[,;][ \t]*(?:fax|faks(?:em)?)[.: \t]*(?=[+(0-9])", after, re.I)):
230
- return True
231
- # A foreign-looking +number can also be an increment in a financial table.
232
- return bool(re.match(r"\(?(?:\+|00)[ \t]*48|\+\d{1,3}[ \t]+\(0\)", raw)
233
- or _PHONE_LABEL_RE.search(before))
234
-
235
-
236
- def _directory_context(text: str, start: int, end: int) -> bool:
237
- """Recognize phones in bounded staff and named-address contact records."""
238
- raw = text[start:end]
239
- foreign = raw.startswith('+') and _phone_ok(raw)
240
- if not foreign and (not _pl_national_ok(_digits(raw)) or not re.search(r'[ \t-]', raw)):
241
- return False
242
- # ponytail: local 1,600-character directory evidence; longer isolated rows
243
- # need preserved upstream table structure, not an unbounded document cue.
244
- left, right = max(0, start-800), min(len(text), end+800)
245
- nearby = text[left:right]
246
- line_start, line_end = text.rfind('\n', 0, start)+1, text.find('\n', end)
247
- line_end = len(text) if line_end < 0 else line_end
248
- before, after = text[line_start:start], text[end:line_end]
249
- if _CONTACT_EXCLUDE_RE.search(before) or _OTHER_NUMBER_LABEL_RE.search(before):
250
- return False
251
- if foreign:
252
- # A comma-delimited name/address entry needs a labelled phone nearby;
253
- # a +number alone could be an increment in a financial table.
254
- address = re.search(r'(?:^|,)[ \t]*[^\W\d_][^,\n]{1,120},'
255
- r'[^\n]{0,160}\d[^\n]{0,80},[ \t]*\Z', before)
256
- return bool(address and any(
257
- _SHORT_PHONE_LABEL_RE.search(nearby[max(0,m.start()-80):m.start()])
258
- for m in _PHONE_RE.finditer(nearby) if m[0].startswith('+') and _phone_ok(m[0])))
259
- standalone = not before.strip() and not after.strip()
260
- lead = text[max(0, start-400):start]
261
- if (standalone and re.search(r'\b(?:infolini[^\W\d_]*|helpline)\b', lead, re.I)
262
- and not _CONTACT_EXCLUDE_RE.search(lead)):
263
- return True
264
- if (standalone and re.search(r'\bnr\.?[ \t]+telefonu\b', nearby, re.I)
265
- and re.search(r'\b(?:pok[oó]j|pokoju)\b', nearby, re.I)
266
- and re.search(r'\bnazwisko\b', nearby, re.I)):
267
- return True
268
- # Email/name/role records and phone-led service directories repeat formatted
269
- # values. A lone staff title beside a number is insufficient evidence.
270
- phones = [m for m in _PHONE_LINE_RE.finditer(nearby)
271
- if _pl_national_ok(_digits(m[0])) and not _is_amount(nearby, *m.span())]
272
- roles = list(_STAFF_ROLE_RE.finditer(nearby))
273
- if len(phones) < 2 or len(roles) < 2:
274
- return False
275
- return bool((re.search(r'\[PII\]', before[-100:] + after[:100]) and
276
- re.search(r'[^\W\d_]', before[-100:]))
277
- or (not before.strip() and re.match(r'[ \t]+[^\W\d_]', after))
278
- or _STAFF_ROLE_RE.search(before[-100:]))
279
-
280
-
281
- # Amounts can look like phones or checksum-valid national IDs. Keep the
282
- # currency adjacent to the number, allowing a decimal, multiplier and line wrap.
283
- _MONEY_GAP = r"[ \t]*(?:\n[ \t]*)?"
284
- _CURRENCY = r"(?:PLN|z[łl](?:ot(?:ych|ego|emu|ymi|ym|y|e))?|EUR(?:O)?|USD|GBP|CHF)\b|[%€$£]"
285
- _MONEY_AFTER_RE = re.compile(
286
- r"(?:[,.][0-9]+)?" + _MONEY_GAP
287
- + r"(?:(?:tys\.?|mln|mld|bln)\b\.?" + _MONEY_GAP + r")?"
288
- + r"(?:" + _CURRENCY + r")", re.I,
289
- )
290
- _MONEY_BEFORE_RE = re.compile(r"(?:\b(?:PLN|EUR|USD|GBP|CHF)|[€$£])" + _MONEY_GAP + r"$", re.I)
291
-
292
-
293
- def _is_amount(text: str, start: int, end: int) -> bool:
294
- return bool(_MONEY_AFTER_RE.match(text, end) or _MONEY_BEFORE_RE.search(text[max(0, start - 32):start]))
295
-
296
-
297
- def _digits(s: str) -> str:
298
- return re.sub(r"\D", "", s)
299
-
300
-
301
- def _pesel_ok(d: str) -> bool:
302
- if len(d) != 11 or not d.isdigit():
303
- return False
304
- weights = (1, 3, 7, 9, 1, 3, 7, 9, 1, 3)
305
- check = sum(w * int(x) for w, x in zip(weights, d[:-1]))
306
- if str((10 - check % 10) % 10) != d[-1]:
307
- return False
308
- yy, mm, dd = int(d[0:2]), int(d[2:4]), int(d[4:6])
309
- century = {0: 1900, 1: 2000, 2: 2100, 3: 2200, 4: 1800}.get(mm // 20)
310
- if century is None:
311
- return False
312
- try:
313
- dt.date(century + yy, mm % 20, dd)
314
- except ValueError:
315
- return False
316
- return True
317
-
318
-
319
- def _nip_ok(d: str) -> bool:
320
- if len(d) != 10 or not d.isdigit():
321
- return False
322
- weights = (6, 5, 7, 2, 3, 4, 5, 6, 7)
323
- rem = sum(w * int(x) for w, x in zip(weights, d[:-1])) % 11
324
- return rem != 10 and rem == int(d[-1])
325
-
326
-
327
- def _regon_ok(d: str) -> bool:
328
- if not d.isdigit() or len(d) not in (9, 14):
329
- return False
330
- weights = ((8, 9, 2, 3, 4, 5, 6, 7) if len(d) == 9
331
- else (2, 4, 8, 5, 0, 9, 7, 3, 6, 1, 2, 4, 8))
332
- rem = sum(w * int(x) for w, x in zip(weights, d[:-1])) % 11
333
- if rem == 10:
334
- rem = 0
335
- return rem == int(d[-1])
336
-
337
-
338
- def _iban_ok(raw: str) -> bool:
339
- # Do not assemble an alphanumeric account from neighbouring prose words.
340
- # Compact and ordinary four-character printed groups remain supported.
341
- groups = re.split(r'[ \t-]+', raw)
342
- if len(groups) > 1 and any(re.search(r'[A-Za-z]{5}', group) for group in groups):
343
- return False
344
- compact = re.sub(r"[\s-]+", "", raw).upper()
345
- if compact.isdigit() and len(compact) == 26:
346
- compact = "PL" + compact
347
- if not re.fullmatch(r"[A-Z]{2}[0-9]{2}[A-Z0-9]+", compact):
348
- return False
349
- if len(compact) != _IBAN_LENGTHS.get(compact[:2]) or not 2 <= int(compact[2:4]) <= 98:
350
- return False
351
- if compact.startswith("PL") and not compact[2:].isdigit():
352
- return False
353
- rearranged = compact[4:] + compact[:4]
354
- nums = "".join(str(ord(c) - 55) if c.isalpha() else c for c in rearranged)
355
- return int(nums) % 97 == 1
356
-
357
-
358
- def _tag(start, end, tag):
359
- return tag
360
-
361
-
362
- def _replace_epuap(text: str, *, mask=_tag) -> tuple[str, int]:
363
- last_end, count = None, 0
364
-
365
- def replace(m):
366
- nonlocal last_end, count
367
- labelled = _EPUAP_LABEL_RE.search(text, max(0, m.start()-64), m.start())
368
- continued = last_end is not None and re.fullmatch(r'[ \t]*[;,][ \t]*|[ \t]+(?:lub|albo|i|oraz)[ \t]+', text[last_end:m.start()], re.I)
369
- if not labelled and not continued:
370
- return m[0]
371
- last_end = m.end()
372
- count += 1
373
- return mask(m.start(), m.end(), PII_TAG)
374
-
375
- out = _EPUAP_RE.sub(replace, text)
376
- return out, count
377
-
378
-
379
- def _replace_documents(text: str, *, mask=_tag) -> tuple[str, int]:
380
- n = 0
381
-
382
- def replace(m):
383
- nonlocal n
384
- number = re.sub(r"[ \t-]", "", m["number"]).upper()
385
- passport = m["label"].lower().startswith("paszport")
386
- if passport:
387
- short_diplomatic = ('dyplomatyczn' in m['label'].lower()
388
- and re.search(r'\b(?:nr|numer)\b', m['label'], re.I)
389
- and re.fullmatch(r'\d{4,5}', number))
390
- if not short_diplomatic and not re.fullmatch(r"[A-Z]{2}[0-9OIL]{7}|[A-Z][0-9]{6,9}|[0-9]{6,12}", number):
391
- return m[0]
392
- elif not re.fullmatch(r"[A-Z]{3}[0-9OIL]{6}", number):
393
- return m[0]
394
- n += 1
395
- return m["label"] + mask(m.start('number'), m.end('number'), PII_TAG)
396
-
397
- # Passport detection is label/format based; no MRZ check digit is present here.
398
- return _DOCUMENT_RE.sub(replace, text), n
399
-
400
-
401
- def _pl_national_ok(d: str) -> bool:
402
- return len(d) == 9 and d.isdigit() and d[:2] in _PL_PREFIX
403
-
404
-
405
- def _phone_ok(raw: str, short: bool = False) -> bool:
406
- s = raw.strip()
407
- if _VANITY_PHONE_RE.fullmatch(s):
408
- return short
409
- if s.startswith('/') or s.endswith('/'):
410
- return False
411
- s = re.sub(r'^\(\+', '+', s)
412
- s = re.sub(r'^\(00\)[ \t]*', '00', s)
413
- if re.fullmatch(r"\d{4}[-./]\d{2}[-./]\d{2}", s):
414
- return False
415
- if re.fullmatch(r'\(?(?:[01]?\d|2[0-3])[.:][0-5]\d[ \t]*[–—-][ \t]*(?:[01]?\d|2[0-3])[.:][0-5]\d\)?', s):
416
- return False
417
- if re.fullmatch(r"\d{2}-\d{3}", s): # postal code
418
- return False
419
- # Ministry / court file numbers: BPRM.4820.2.3.2020, LUB-OMK.601.1.2024.3
420
- if s.count(".") >= 3 or (s.count(".") >= 1 and re.search(r"(?<!\d)20\d{2}(?!\d)", s)):
421
- return False
422
- if re.search(r"(?<!\d)\d{1,2}[-./]\d{1,2}[-./](?:19|20)\d{2}(?!\d)", s):
423
- return False
424
- d = _digits(raw)
425
- if short and re.fullmatch(r'[2-9]\d{2}-[2-9]\d{2}-\d{4}', s):
426
- return True
427
- if short and s.startswith('(0)'):
428
- return 7 <= len(d) <= 12
429
- # ponytail: label + shape + length, not a country numbering-plan validator.
430
- if short and re.match(r'^\(0?\d{2,4}(?:-\d{1,2})?\)', s):
431
- return 8 <= len(d) <= 15
432
- if s.startswith(('+', '00')):
433
- international = _digits(s.replace('(0)', ''))
434
- if s.startswith('00'):
435
- international = international[2:]
436
- if not international.startswith('48'):
437
- # ponytail: explicit prefix + length, not a global numbering-plan
438
- # validator. Add country metadata if review finds false positives.
439
- return (7 if '(0)' in s else 8) <= len(international) <= 15 and international[0] != '0'
440
- if d.startswith("00"):
441
- d = d[2:]
442
- if d.startswith("48") and len(d) >= 11:
443
- rest = d[2:]
444
- if rest.startswith("0"):
445
- rest = rest[1:]
446
- return _pl_national_ok(rest)
447
- if d.startswith("0") and len(d) == 11 and d[:2] in {"01", "02", "07"}:
448
- return True
449
- if d.startswith("0") and len(d) >= 10:
450
- return _pl_national_ok(d.lstrip("0")) or (short and len(d) <= 12)
451
- return (_pl_national_ok(d)
452
- or (short and 5 <= len(d) <= 8 and d[0] != '0')
453
- or (short and 9 <= len(d) <= 12 and bool(re.fullmatch(r'\d{2,4}(?:[ \t-]\d{2,4}){2,3}', s)))
454
- or (short and 9 <= len(d) <= 12 and bool(re.fullmatch(r'\d{2,4}\.\d{6,8}', s)))
455
- or (short and 9 <= len(d) <= 12 and d.startswith('0')))
456
-
457
-
458
- def _replace_checked(text: str, pattern: re.Pattern, tag: str, ok,
459
- label: re.Pattern | None = None, *, mask=_tag) -> tuple[str, int]:
460
- n = 0
461
-
462
- def _sub(m):
463
- nonlocal n
464
- if label is not None and not label.search(text, max(0, m.start() - 64), m.start()):
465
- return m.group(0)
466
- if pattern is _PESEL_RE and re.search(r'[/?&][^\s]*\Z', text[max(0, m.start()-500):m.start()]):
467
- return m.group(0) # Bare URL path/query digits are not personal identifiers.
468
- if not ok(m.group(0)) or (pattern not in (_EMAIL_RE, _EMAIL_WRAP_RE, _EMAIL_FRAGMENT_RE)
469
- and _is_amount(text, m.start(), m.end())):
470
- return m.group(0)
471
- n += 1
472
- return mask(m.start(), m.end(), tag)
473
-
474
- return pattern.sub(_sub, text), n
475
-
476
-
477
- def _replace_phones(text: str, *, mask=_tag) -> tuple[str, int]:
478
- n = 0
479
- out = []
480
- pos = 0
481
- last_phone_end = None
482
- while True:
483
- m = _PHONE_RE.search(text, pos)
484
- if not m:
485
- out.append(text[pos:])
486
- break
487
- raw = m[0]
488
- end = m.end()
489
- replacement = raw
490
- line_end = text.find('\n', m.start(), end)
491
- if line_end >= 0 and re.fullmatch(r'\d{1,3}', text[m.start():line_end]):
492
- next_end = text.find('\n', line_end+1, end)
493
- if _directory_context(text, line_end+1, next_end if next_end >= 0 else end):
494
- # A flattened table's room cell is not a phone country prefix.
495
- out.append(text[pos:line_end+1])
496
- pos = line_end+1
497
- continue
498
- short = bool(_SHORT_PHONE_LABEL_RE.search(text[max(0, m.start()-100):m.start()]))
499
- short = short or (re.fullmatch(r'116[ \t]?\d{3}', raw)
500
- and _phone_context(text, m.start(), raw))
501
- short = short or _phone_list_context(text, m.start())
502
- # A bare five-digit continuation followed by a place/name can be a
503
- # postal address. It needs its own phone label to override that ambiguity.
504
- postal = re.fullmatch(r'\d{5}', raw) and re.match(r'[ \t]+[^\W\d_]', text[end:])
505
- if (last_phone_end is not None and not postal
506
- and re.fullmatch(r"[ \t\n,;]{1,12}|[ \t]+(?:lub|albo)[ \t]+", text[last_phone_end:m.start()], re.I)):
507
- short = True
508
- if (last_phone_end is not None
509
- and re.fullmatch(r'(?:[ \t]+(?:w sprawie\b|\((?:w godzinach|dostępny)\b)'
510
- r'|[ \t]*[–—-][ \t]+)[^\d\n.!?]{1,200}\n[ \t\n]{0,8}',
511
- text[last_phone_end:m.start()], re.I)
512
- and _pl_national_ok(_digits(raw))):
513
- short = True
514
- if (short or _phone_context(text, m.start(), raw)
515
- or _directory_context(text, m.start(), line_end if line_end >= 0 else end)):
516
- if (_is_amount(text, m.start(), end)
517
- and re.fullmatch(r'\d{1,3}(?:\.[ \t]*\d{3})+', raw)):
518
- out.extend((text[pos:m.start()], raw))
519
- pos = end
520
- continue
521
- # Stop before a new line or opening hours, but only after a complete
522
- # phone. Look past the greedy match's last digit to recognize HH:MM.
523
- for gap in _PHONE_BREAK_RE.finditer(text, m.start(), end + 6):
524
- if gap.start() >= end:
525
- break
526
- # Foreign lengths vary: a valid-looking prefix may still be an
527
- # incomplete wrapped number. Only a section marker ends it.
528
- if (raw.startswith(('+', '00')) and not re.match(r'(?:\+|00)[ \t]*48', raw)
529
- and gap[0] == '\n'
530
- and not re.match(r'\d{1,2}[.)](?!\d)', text[gap.end():])):
531
- continue
532
- prefix = text[m.start():gap.start()].rstrip(". \t")
533
- if _phone_ok(prefix) and not _is_amount(text, m.start(), gap.start()):
534
- end = m.start() + len(prefix)
535
- raw = prefix
536
- replacement = raw
537
- break
538
- if _is_amount(text, m.start(), end):
539
- out.extend((text[pos:m.start()], raw))
540
- pos = end
541
- continue
542
- # A suffix range repeats the final extension digits, not a second
543
- # complete phone. Only accept it after a valid full base number.
544
- extension = re.fullmatch(r"(.+?)[/-](\d{1,3})", raw)
545
- parenthesized_extension = re.fullmatch(r'(.+?)[ \t]+\(\d{1,5}', raw)
546
- if not (text[end:end+1] == ')' and parenthesized_extension
547
- and _phone_ok(parenthesized_extension[1])):
548
- parenthesized_extension = None
549
- pair = re.fullmatch(r"(.+?)[ \t]+[–—-][ \t]+(.+)", raw)
550
- shared = re.match(r"\(\d{2,4}\)[ \t]*", pair[1]) if pair else None
551
- full_range = (pair and _phone_ok(pair[1], short)
552
- and _phone_ok((shared[0] if shared else '') + pair[2], short))
553
- if (_phone_ok(raw, short) or (extension and _phone_ok(extension[1]))
554
- or parenthesized_extension or full_range):
555
- if raw.count('(') > raw.count(')') and text[end:end+1] == ')':
556
- end += 1
557
- suffix = _PHONE_EXTENSION_RE.match(text, end)
558
- if suffix and not _is_amount(text, suffix.start(), suffix.end()):
559
- end = suffix.end()
560
- start = m.start()
561
- # Parentheses enclosing prose are punctuation, not phone syntax.
562
- if raw.startswith('(+') and raw.count('(') > raw.count(')') and text[end-1:end] != ')':
563
- start += 1
564
- replacement = text[m.start():start] + mask(start, end, PHONE_TAG)
565
- n += 1
566
- # ponytail: split only pairs (<=22 digits); longer lists need label
567
- # context to distinguish them from accounts. Never redact ID tails.
568
- elif 18 <= len(_digits(raw)) <= 22 and "." not in raw:
569
- for gap in re.finditer(r"[ \t]*/[ \t]*|[ \t\n]+", raw):
570
- if _phone_ok(raw[:gap.start()]) and _phone_ok(raw[gap.end():]):
571
- replacement = (mask(m.start(), m.start()+gap.start(), PHONE_TAG)
572
- + gap[0] + mask(m.start()+gap.end(), end, PHONE_TAG))
573
- n += 2
574
- break
575
- out.extend((text[pos:m.start()], replacement))
576
- if replacement != raw:
577
- last_phone_end = end
578
- pos = end
579
- return "".join(out), n
580
-
581
-
582
- def _replace_extensions(text: str, *, mask=_tag) -> tuple[str, int]:
583
- count = 0
584
-
585
- def replace(m):
586
- nonlocal count
587
- before = text[max(0, m.start()-500):m.start()]
588
- # Only a telephone followed by extension/name entries establishes scope.
589
- heading = re.search(r'\btel(?:efon)?[.: \t]*\[Telefon\]'
590
- r'(?P<entries>(?:\s*wewn?\.?[ \t]+\d{1,5}[ \t]+[^\d\n]+)*\s*)\Z', before, re.I)
591
- if not heading or _is_amount(text, m.start('number'), m.end('number')):
592
- return m[0]
593
- count += 1
594
- return m['label'] + mask(m.start('number'), m.end('number'), PHONE_TAG)
595
-
596
- output = re.sub(r'(?P<label>(?:^|\n)[ \t]*wewn?\.?[ \t]+)(?P<number>\d{1,5})(?!\w)',
597
- replace, text, flags=re.I)
598
- return output, count
599
-
600
-
601
- def scrub_pii(text: str, *, spans: list | None = None) -> tuple[str, dict[str, int]]:
602
- """Return (scrubbed_text, counts); optionally append exact original spans.
603
-
604
- Offset tracking is opt-in; corpus ingestion keeps its existing return type
605
- and does not allocate a character map. Unicode offsets count code points.
606
- """
607
- counts = {k: 0 for k in COUNTS}
608
- if not text:
609
- return text, counts
610
- original = text
611
- text = text.translate(_SPACES) # One character per character: offsets survive.
612
- offsets = list(range(len(text))) if spans is not None else None
613
- edits = []
614
-
615
- def mask(start, end, tag):
616
- if spans is not None:
617
- a, b = offsets[start], offsets[end-1] + 1
618
- spans.append(dict(start=a, end=b, text=original[a:b],
619
- label='phone' if tag == PHONE_TAG else 'pii'))
620
- edits.append((start, end, tag))
621
- return tag
622
-
623
- def apply(replacer, *args):
624
- nonlocal text
625
- text, result = replacer(text, *args, mask=mask)
626
- # Each replacement pass uses one coordinate system. Apply its edits
627
- # backwards only after all regex callbacks have finished.
628
- for start, end, tag in reversed(edits):
629
- offsets[start:end] = [offsets[start]] * len(tag)
630
- edits.clear()
631
- return result
632
-
633
- # Longest / most specific first so a 26-digit account is not sliced
634
- # into REGON / PESEL / NIP / phone. Checksums live in the replace callback.
635
- def pins(value, *, mask):
636
- def replace(m):
637
- if _is_amount(value, m.start('number'), m.end('number')):
638
- return m[0]
639
- counts['pin'] += 1
640
- return m['label'] + mask(m.start('number'), m.end('number'), PII_TAG)
641
- return _PIN_RE.sub(replace, value), None
642
- apply(pins)
643
- foreign = apply(_replace_checked, _IBAN_RE, PII_TAG, _iban_ok)
644
- bare = apply(_replace_checked, _ACCOUNT_RE, PII_TAG, _iban_ok)
645
- counts["account"] = foreign + bare
646
- counts['electronic_address'] = apply(_replace_checked, _EDELIVERY_RE, PII_TAG, lambda _: True)
647
- counts['electronic_address'] += apply(_replace_epuap)
648
- counts['krs'] = apply(_replace_checked, _KRS_RE, PII_TAG, lambda _: True, _KRS_LABEL_RE)
649
- counts["document"] = apply(_replace_documents)
650
- def labelled_ids(value, *, mask):
651
- def replace(m):
652
- if len(_digits(m['number'])) < 7 or _is_amount(value, m.start('number'), m.end()):
653
- return m[0]
654
- counts[m['kind'].lower()] += 1
655
- return m['label'] + mask(m.start('number'), m.end('number'), PII_TAG)
656
- return _LABELLED_ID_RE.sub(replace, value), None
657
- apply(labelled_ids)
658
- n14 = apply(_replace_checked, _REGON14_RE, PII_TAG, _regon_ok, _REGON_LABEL_RE)
659
- n9 = apply(_replace_checked, _REGON9_RE, PII_TAG, _regon_ok, _REGON_LABEL_RE)
660
- counts["regon"] += n14 + n9
661
- n_dash = apply(_replace_checked, _NIP_DASH_RE, PII_TAG, lambda s: _nip_ok(_digits(s)), _NIP_LABEL_RE)
662
- n_plain = apply(_replace_checked, _NIP_RE, PII_TAG, lambda s: _nip_ok(_digits(s)), _NIP_LABEL_RE)
663
- counts["nip"] += n_dash + n_plain
664
- counts["email"] = apply(_replace_checked, _EMAIL_WRAP_RE, PII_TAG,
665
- lambda s: not _EMAIL_RE.fullmatch(s.splitlines()[0].rstrip('. \t')))
666
- counts["email"] += apply(_replace_checked, _EMAIL_RE, PII_TAG, lambda _: True)
667
- counts["email"] += apply(_replace_checked, _EMAIL_FRAGMENT_RE, PII_TAG,
668
- lambda _: True, _EMAIL_LABEL_RE)
669
- counts["phone"] = apply(_replace_phones)
670
- counts["phone"] += apply(_replace_checked, _SERVICE_PHONE_RE, PHONE_TAG,
671
- lambda _: True, _SERVICE_PHONE_LABEL_RE)
672
- counts['phone'] += apply(_replace_extensions)
673
- # Contact context takes precedence over coincidental PESEL checksums in
674
- # foreign phone numbers; explicitly labelled identifiers were handled first.
675
- bare_pesel = apply(_replace_checked, _PESEL_RE, PII_TAG, _pesel_ok)
676
- counts['pesel'] += bare_pesel
677
- return text, counts
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/sources.py CHANGED
@@ -156,7 +156,7 @@ SOURCES = {
156
  "src/fetch_sejm_interpellations.py (interpellations + "
157
  "writtenQuestions, terms 7–10). Header chrome stripped into "
158
  "meta; attachment-only and keyless replies skipped; "
159
- "src/scrub_pii.py applied before jsonl write.",
160
  "domain": "political/written",
161
  "created": "2011-11-08, 2026-09-04",
162
  "is_ocr": False,
@@ -429,8 +429,8 @@ SOURCES = {
429
  "min 400 chars / 80 words, boilerplate/adult/legalish drop, length cap "
430
  "120k chars, CJK-mojibake drop, wikipedia/wikisource/wikimedia + file-host "
431
  "domains excluded, per-domain cap. Phone->[Telefon] / email+national-ID->[PII] "
432
- "via src/scrub_pii.py (in-tree; supersedes the out-of-repo v12b pass); "
433
- "PERSON mentions → [PII] via src/scrub_entities.py on this web shard only. "
434
  "Token counts via tiktoken cl100k.",
435
  "domain": "web",
436
  "created": "2012-01-01, 2024-12-31",
 
156
  "src/fetch_sejm_interpellations.py (interpellations + "
157
  "writtenQuestions, terms 7–10). Header chrome stripped into "
158
  "meta; attachment-only and keyless replies skipped; "
159
+ "PII via SlayerLab/NERGAL, not this repo.",
160
  "domain": "political/written",
161
  "created": "2011-11-08, 2026-09-04",
162
  "is_ocr": False,
 
429
  "min 400 chars / 80 words, boilerplate/adult/legalish drop, length cap "
430
  "120k chars, CJK-mojibake drop, wikipedia/wikisource/wikimedia + file-host "
431
  "domains excluded, per-domain cap. Phone->[Telefon] / email+national-ID->[PII] "
432
+ "PII (phones/emails/IDs, and PERSON on this web shard) was applied "
433
+ "at fetch; the scrubber now lives at SlayerLab/NERGAL, not this repo. "
434
  "Token counts via tiktoken cl100k.",
435
  "domain": "web",
436
  "created": "2012-01-01, 2024-12-31",
src/test_pii_mixed_regressions.py DELETED
@@ -1,49 +0,0 @@
1
- """Synthetic contact-format regressions; human exports are never test inputs."""
2
- import json
3
- from pathlib import Path
4
- import unittest
5
-
6
- from scrub_pii import scrub_pii
7
-
8
-
9
- class MixedRegressionTest(unittest.TestCase):
10
- pass
11
-
12
-
13
- def regression(case):
14
- def check(self):
15
- text, spans = case['text'], []
16
- scrub_pii(text, spans=spans)
17
- for wanted in case['mask']:
18
- self.assertEqual(text[wanted['start']:wanted['end']], wanted['text'])
19
- covered = {i for span in spans if span['label'] == wanted['label']
20
- for i in range(span['start'], span['end'])}
21
- required = {i for i in range(wanted['start'], wanted['end']) if not text[i].isspace()}
22
- self.assertFalse(required-covered, case['name'])
23
- overlapping = {i for span in spans
24
- if required & set(range(span['start'], span['end']))
25
- for i in range(span['start'], span['end']) if not text[i].isspace()}
26
- self.assertFalse(overlapping-set(range(wanted['start'], wanted['end'])), case['name'])
27
- covered = {i for span in spans for i in range(span['start'], span['end'])}
28
- for wanted in case['preserve']:
29
- self.assertEqual(text[wanted['start']:wanted['end']], wanted['text'])
30
- self.assertFalse(covered & set(range(wanted['start'], wanted['end'])), case['name'])
31
- return check
32
-
33
-
34
- fixtures = [json.loads(Path(__file__).with_name(name).read_text()) for name in
35
- ('pii_mixed_regression_cases.json', 'pii_wikivoyage_regression_cases.json')]
36
- assert all(fixture['synthetic'] is True for fixture in fixtures)
37
- cases = [case for fixture in fixtures for case in fixture['cases']]
38
- assert len({case['name'] for case in cases}) == len(cases)
39
- for case in cases:
40
- assert set(case) == {'name', 'text', 'mask', 'preserve'}
41
- assert case['mask'] or case['preserve']
42
- for target in case['mask'] + case['preserve']:
43
- assert 0 <= target['start'] < target['end'] <= len(case['text'])
44
- assert case['text'][target['start']:target['end']] == target['text']
45
- setattr(MixedRegressionTest, 'test_'+case['name'], regression(case))
46
-
47
-
48
- if __name__ == '__main__':
49
- unittest.main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/test_scrub_entities.py DELETED
@@ -1,112 +0,0 @@
1
- """PERSON-only NER replace: allowlist + whole-word guard. No model download."""
2
- import sys
3
- import unittest
4
- from pathlib import Path
5
-
6
- sys.path.insert(0, str(Path(__file__).resolve().parent))
7
-
8
- from scrub_entities import (
9
- NER_SOURCES,
10
- apply_person_spans,
11
- source_allows_ner,
12
- scrub_entities,
13
- )
14
-
15
- SEJM = (
16
- "Marszałek Sejmu Szymon Hołownia otworzył posiedzenie. "
17
- "Głos zabrał poseł Donald Tusk w imieniu Klubu Koalicja Obywatelska."
18
- )
19
- HRUB = "Hrubieszów położony w województwie lubelskim."
20
-
21
-
22
- def _span(label, text, start, end=None):
23
- end = end if end is not None else start + len(text)
24
- return {"label": label, "text": text, "start": start, "end": end, "score": 1.0}
25
-
26
-
27
- class AllowlistTest(unittest.TestCase):
28
- def test_web_sources_allowed(self):
29
- for key in ("european_hplt_v3_pl", "govpl", "samorzad_gov_pl"):
30
- self.assertTrue(source_allows_ner(key), key)
31
- self.assertEqual(
32
- NER_SOURCES,
33
- frozenset({"european_hplt_v3_pl", "govpl", "samorzad_gov_pl"}),
34
- )
35
-
36
- def test_official_sources_blocked(self):
37
- for key in (
38
- "parlamint_pl", "sejm_api", "sejm_interpellations",
39
- "parliamentary", "eurlex", "dziennik_ustaw", "wikipedia",
40
- ):
41
- self.assertFalse(source_allows_ner(key), key)
42
-
43
- def test_blocked_source_does_not_replace_even_with_spans(self):
44
- spans = [_span("PERSON", "Szymon Hołownia", SEJM.index("Szymon Hołownia"))]
45
- out, counts = scrub_entities(SEJM, source="parlamint_pl", spans=spans)
46
- self.assertEqual(out, SEJM)
47
- self.assertIn("Szymon Hołownia", out)
48
- self.assertEqual(counts["person"], 0)
49
-
50
- def test_blocked_sejm_api_same(self):
51
- spans = [_span("PERSON", "Donald Tusk", SEJM.index("Donald Tusk"))]
52
- out, counts = scrub_entities(SEJM, source="sejm_api", spans=spans)
53
- self.assertEqual(out, SEJM)
54
- self.assertEqual(counts["person"], 0)
55
-
56
-
57
- class ApplyPersonSpansTest(unittest.TestCase):
58
- def test_person_becomes_pii_keeps_sentence(self):
59
- text = "Kontakt: Anna Nowak, ul. 3 Maja."
60
- spans = [_span("PERSON", "Anna Nowak", text.index("Anna Nowak"))]
61
- out, n = apply_person_spans(text, spans)
62
- self.assertEqual(n, 1)
63
- self.assertIn("[PII]", out)
64
- self.assertNotIn("Anna Nowak", out)
65
- self.assertIn("Kontakt:", out)
66
- self.assertIn("ul. 3 Maja.", out)
67
-
68
- def test_city_and_org_are_ignored(self):
69
- text = HRUB + " Sony i Ministerstwo Finansów."
70
- spans = [
71
- _span("CITY", "H", 0, 1),
72
- _span("CITY", "bieszów", 3, 10),
73
- _span("ORG", "Sony", text.index("Sony")),
74
- _span("ORG", "Ministerstwo Finansów", text.index("Ministerstwo")),
75
- ]
76
- out, n = apply_person_spans(text, spans)
77
- self.assertEqual(n, 0)
78
- self.assertEqual(out, text)
79
- self.assertIn("Hrubieszów", out)
80
-
81
- def test_gapped_person_subwords_expand_to_whole_word(self):
82
- # Same hole as Hrubieszów: middle letters tagged O.
83
- text = "Hrubieszów"
84
- spans = [
85
- _span("PERSON", "H", 0, 1),
86
- _span("PERSON", "bieszów", 3, 10),
87
- ]
88
- out, n = apply_person_spans(text, spans)
89
- self.assertEqual(n, 1)
90
- self.assertEqual(out, "[PII]")
91
- self.assertNotIn("ru", out)
92
-
93
- def test_partial_person_expands_to_word(self):
94
- text = "Widziałem Kowalskiego wczoraj."
95
- spans = [_span("PERSON", "Kowal", text.index("Kowal"), text.index("Kowal") + 5)]
96
- out, n = apply_person_spans(text, spans)
97
- self.assertEqual(n, 1)
98
- self.assertNotIn("Kowalskiego", out)
99
- self.assertEqual(out, "Widziałem [PII] wczoraj.")
100
-
101
- def test_allowed_source_uses_injected_spans(self):
102
- text = "Zgłosiła to Anna Nowak."
103
- spans = [_span("PERSON", "Anna Nowak", text.index("Anna Nowak"))]
104
- out, counts = scrub_entities(
105
- text, source="european_hplt_v3_pl", spans=spans,
106
- )
107
- self.assertEqual(counts["person"], 1)
108
- self.assertNotIn("Anna Nowak", out)
109
-
110
-
111
- if __name__ == "__main__":
112
- unittest.main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/test_scrub_pii.py DELETED
@@ -1,874 +0,0 @@
1
- """TDD contract for regex PII scrub (email, phone, PESEL/NIP/REGON, account)."""
2
- import sys
3
- import unittest
4
- from pathlib import Path
5
-
6
- sys.path.insert(0, str(Path(__file__).resolve().parent))
7
-
8
- from scrub_pii import scrub_pii
9
-
10
- # Synthetic contact/identifier fixtures; no copied directory entries.
11
- # Email domains use example.com; emergency/service codes retain their semantics.
12
- # Numeric fixtures test syntax/checksums, not whether a number is assigned.
13
- # The IBAN cases use published example numbers.
14
- PESEL = "44051401458"
15
- NIP = "1234563218"
16
- REGON9 = "123456785"
17
- REGON14 = "12345678512347"
18
- IBAN = "PL61109010140000071219812874"
19
-
20
-
21
- class ScrubPiiTest(unittest.TestCase):
22
- def test_email_spacing_on_both_sides_of_at(self):
23
- for value in ('osoba @example.com', 'osoba @ example.com', 'osoba@ example.com',
24
- 'osoba\t@\texample.com', 'osoba\u00a0@\u202fexample.com',
25
- 'osoba @ example.\ncom'):
26
- with self.subTest(value=value):
27
- text, spans = 'E-mail: '+value+'.', []
28
- out, counts = scrub_pii(text, spans=spans)
29
- self.assertEqual(out, 'E-mail: [PII].')
30
- self.assertEqual(counts['email'], 1)
31
- self.assertEqual(spans, [dict(start=8, end=8+len(value), text=value, label='pii')])
32
- self.assertEqual(scrub_pii(out), (out, dict.fromkeys(counts, 0)))
33
- self.assertEqual(scrub_pii('E-mail: osoba @\n')[0], 'E-mail: [PII]\n')
34
- for text in ('osoba\n@example.com', 'osoba @example.com',
35
- 'osoba @example..com', 'osoba @', 'systemd-fsck@.service'):
36
- self.assertEqual(scrub_pii(text)[0], text)
37
-
38
- def test_wikivoyage_repair_guards(self):
39
- for label in ('Telefon komórkowy: ', 'tel.komórkowy: ', 'tel. komórkowy: '):
40
- self.assertEqual(scrub_pii(label+'(53) 05 234567123')[0], label+'[Telefon]')
41
- for text in ('PO Box 11155-3489', 'Telefon: 2026-09-08',
42
- 'Fax:\n- z Polski 12 345 678 PLN',
43
- 'Fax:\n- z Polski 0066 2 234 5613\n\nDane statystyczne\n12 345 678',
44
- 'Tabela +86 351 2345613',
45
- 'Hotel Przykład, ulica Testowa 16, +36 84 234 562 EUR',
46
- 'Hotel Przykład, ulica Testowa 16, kod +36 84 234 562'):
47
- with self.subTest(text=text):
48
- expected = text.replace('0066 2 234 5613', '[Telefon]')
49
- self.assertEqual(scrub_pii(text)[0], expected)
50
-
51
- def test_phone_continuation_preserves_postal_address(self):
52
- for text, expected in (
53
- ('Ulica Testowa, 108, tel: 393 234 5671, 95131 Miasto.',
54
- 'Ulica Testowa, 108, tel: [Telefon], 95131 Miasto.'),
55
- ('tel. +39 393 234 5671, 95131 Miasto.', 'tel. [Telefon], 95131 Miasto.'),
56
- ('tel. 501 234 567, 12345', 'tel. [Telefon], [Telefon]'),
57
- ('tel. 501 234 567, 123 456 sekretariat', 'tel. [Telefon], [Telefon] sekretariat'),
58
- ('tel. 95131 Miasto', 'tel. [Telefon] Miasto'),
59
- ):
60
- with self.subTest(text=text):
61
- self.assertEqual(scrub_pii(text)[0], expected)
62
-
63
- def test_mixed_repair_boundaries(self):
64
- for text, expected in (
65
- ('tel. kwota 500. 100. 200. 300 PLN', 'tel. kwota 500. 100. 200. 300 PLN'),
66
- ('tel. 501 234 567 do 29 marca', 'tel. [Telefon] do 29 marca'),
67
- ('tel. 501 234 567 do 29.12.2026', 'tel. [Telefon] do 29.12.2026'),
68
- ('a@example.com.\nNext.section', '[PII].\nNext.section'),
69
- ('Nakład +27 (0)13 234-5612 EUR', 'Nakład +27 (0)13 234-5612 EUR'),
70
- ('tel. 501 234 567. 123,00 zł', 'tel. [Telefon]. 123,00 zł'),
71
- ('Faks: +33 1 23 45 67 12\n—\nD-60322\nFrankfurt',
72
- 'Faks: [Telefon]\n—\nD-60322\nFrankfurt'),
73
- ('☏ +1 202 555-TEST (8378), +1 202 555-0142', '☏ [Telefon], [Telefon]'),
74
- ('Telefony alarmowe: 997, 112\nDyżurny KPP: 68 123 45 67',
75
- 'Telefony alarmowe: [Telefon], [Telefon]\nDyżurny KPP: [Telefon]'),
76
- ('Infolinię uruchomiono od 22-26.04.br.', 'Infolinię uruchomiono od 22-26.04.br.'),
77
- ('Tel Aviv, s. 499-515.', 'Tel Aviv, s. 499-515.'),
78
- ('równoważne zapisy modelu: 70-20-10', 'równoważne zapisy modelu: 70-20-10'),
79
- ('Sprzęt teleinf. i telekom.\n24 965,3\n11 145,3\n13 693,5',
80
- 'Sprzęt teleinf. i telekom.\n24 965,3\n11 145,3\n13 693,5'),
81
- ):
82
- with self.subTest(text=text):
83
- self.assertEqual(scrub_pii(text)[0], expected)
84
-
85
- def test_labelled_email_fragment_at_line_end(self):
86
- for text, expected in (
87
- ('adres e-mail: j.kowalski@\n\nDalszy tekst.', 'adres e-mail: [PII]\n\nDalszy tekst.'),
88
- ('EMAIL:łukasz@ \r\n', 'EMAIL:[PII] \r\n'),
89
- ('e-mail: osoba@', 'e-mail: [PII]'),
90
- ('osoba@', 'osoba@'),
91
- ('plik: systemd-fsck@.service', 'plik: systemd-fsck@.service'),
92
- ('e-mail: osoba@example..com', 'e-mail: osoba@example..com'),
93
- ('e-mail: osoba@ example.com', 'e-mail: [PII]'),
94
- ):
95
- with self.subTest(text=text):
96
- spans = []
97
- out, counts = scrub_pii(text, spans=spans)
98
- self.assertEqual(out, expected)
99
- self.assertEqual(counts['email'], int(out != text))
100
- for span in reversed(spans):
101
- self.assertEqual(text[span['start']:span['end']], span['text'])
102
- text = text[:span['start']] + '[PII]' + text[span['end']:]
103
- self.assertEqual(text, out)
104
- self.assertEqual(scrub_pii(out), (out, dict.fromkeys(counts, 0)))
105
-
106
- def test_reviewed_directory_contact_and_number_boundaries(self):
107
- cases = [
108
- ('Kontakt: Jan Kowalski: 501 234 567', 'Kontakt: Jan Kowalski: [Telefon]'),
109
- ('Kontakt: a@example.com, (22) 123 45 67', 'Kontakt: [PII], [Telefon]'),
110
- ('Zapisy do piątku 14 marca pod nr 41 234 56 71', 'Zapisy do piątku 14 marca pod nr [Telefon]'),
111
- # Contact headings establish phone context across blank lines.
112
- ('Zapisy pod numerem:\n\n501234567', 'Zapisy pod numerem:\n\n[Telefon]'),
113
- ('Nr telefonu do kontaktu:\n\n13 2345671\n\n502234571',
114
- 'Nr telefonu do kontaktu:\n\n[Telefon]\n\n[Telefon]'),
115
- ('Wszystkie sprawy należy kierować pod numer telefonu:\n\n18 23 45 671',
116
- 'Wszystkie sprawy należy kierować pod numer telefonu:\n\n[Telefon]'),
117
- ('Telefon: 25 23 - 456 - 71- sekretariat\n\n25 23 - 456 - 71 wew. 2 - intendent',
118
- 'Telefon: [Telefon]- sekretariat\n\n[Telefon] - intendent'),
119
- ('Zapisz się:\n\nJan Kowalski: 501 234 567\n\nAnna Nowak: 22 123 45 67',
120
- 'Zapisz się:\n\nJan Kowalski: [Telefon]\n\nAnna Nowak: [Telefon]'),
121
- ('tel. 132345671/699234571', 'tel. [Telefon]/[Telefon]'),
122
- ('tel. 501 234 567 / 22 123 45 67', 'tel. [Telefon] / [Telefon]'),
123
- ('tel. 32 234 56 71 15.00-19.00', 'tel. [Telefon] 15.00-19.00'),
124
- ('tel. 510 234 571 3. 12.01.2026 r. – 18.01.2026 r.',
125
- 'tel. [Telefon] 3. 12.01.2026 r. – 18.01.2026 r.'),
126
- ('tel. 25 2345671 (155)', 'tel. [Telefon]'),
127
- ('tel. 33 2345 671, wewnętrzny 60', 'tel. [Telefon]'),
128
- ('tel. 86 234 56 71\n\nwewn. 122 Jan Kowalski\n\nwewn. 123 Anna Nowak',
129
- 'tel. [Telefon]\n\nwewn. [Telefon] Jan Kowalski\n\nwewn. [Telefon] Anna Nowak'),
130
- ('Kontakt: (32) 234-56-71 lub bezpłatny numer alarmowy: 994',
131
- 'Kontakt: [Telefon] lub bezpłatny numer alarmowy: [Telefon]'),
132
- ('за номером телефону: 452-234-571', 'за номером телефону: [Telefon]'),
133
- ('Imie i nazwisko\nNr. Pokoju\nNr. Telefonu\nJan Kowalski\n4\n501 234 567',
134
- 'Imie i nazwisko\nNr. Pokoju\nNr. Telefonu\nJan Kowalski\n4\n[Telefon]'),
135
- ('Referent Jan Kowalski 501 234 567 a@example.com\n\nPsycholog Anna Nowak 22 123 45 67 b@example.com',
136
- 'Referent Jan Kowalski [Telefon] [PII]\n\nPsycholog Anna Nowak [Telefon] [PII]'),
137
- ('Infolinia pomaga znaleźć odpowiednie wsparcie.\n\n800 234 571\n\nPon-pt 10.00-21.00',
138
- 'Infolinia pomaga znaleźć odpowiednie wsparcie.\n\n[Telefon]\n\nPon-pt 10.00-21.00'),
139
- ('NIP Powiatu Przykładowego: 123-45-63-218\nREGON Powiatu Przykładowego: 123456785',
140
- 'NIP Powiatu Przykładowego: [PII]\nREGON Powiatu Przykładowego: [PII]'),
141
- ]
142
- negatives = [
143
- 'Kontakt: cena 500 100 200 PLN',
144
- 'Telefon: 15.00-19.00',
145
- 'tel. 501 234 567\n\nNowa tabela.\n\n502234571',
146
- 'Statystyki infolinii.\n\n800 234 571\n\nLiczba zgłoszeń',
147
- 'Referent: 501 234 567',
148
- 'wewn. 123 Anna Nowak',
149
- 'Nr. Telefonu\nKod produktu 501 234 567',
150
- 'Imie i nazwisko\nNr. Pokoju\nNr. Telefonu\nKwota 501 234 567 zł',
151
- ]
152
- cases.extend((s, s.replace('501 234 567', '[Telefon]', 1) if s.startswith('tel. ') else s)
153
- for s in negatives)
154
- for text, expected in cases:
155
- with self.subTest(text=text):
156
- spans = []
157
- out, counts = scrub_pii(text, spans=spans)
158
- self.assertEqual(out, expected)
159
- rebuilt = text
160
- for span in sorted(spans, key=lambda s: s['start'], reverse=True):
161
- self.assertEqual(text[span['start']:span['end']], span['text'])
162
- tag = '[Telefon]' if span['label'] == 'phone' else '[PII]'
163
- rebuilt = rebuilt[:span['start']] + tag + rebuilt[span['end']:]
164
- self.assertEqual(rebuilt, out)
165
- self.assertEqual(self._scrub(out), (out, dict.fromkeys(counts, 0)))
166
-
167
- def test_explicit_access_pins(self):
168
- for text, expected in (
169
- ('PIN: \u202a123 456 789#', 'PIN: [PII]'),
170
- ('kod PIN: 1234', 'kod PIN: [PII]'),
171
- ('https://example.org/meet?pin=1234567890123&lang=pl',
172
- 'https://example.org/meet?pin=[PII]&lang=pl'),
173
- ):
174
- out, counts = self._scrub(text)
175
- self.assertEqual(out, expected)
176
- self.assertEqual(counts['pin'], 1)
177
- self.assertEqual(counts['phone'], 0)
178
- self.assertEqual(self._scrub(out), (out, dict.fromkeys(counts, 0)))
179
- for text in ('Kod pocztowy: 00-123', 'ISBN 978-83-60823-07-01',
180
- 'spin=12345678', 'PIN: 1234 PLN', 'PIN: 12345678901234567',
181
- 'PIN: 1234abc', 'PIN: [PII]'):
182
- self.assertEqual(self._scrub(text)[0], text)
183
-
184
- def test_shared_contact_lists_and_phone_ranges(self):
185
- cases = [
186
- ('Numery kontaktowe:\n\nMIASTO ALFA – 85 234 56 71,\n\nMIASTO BETA – 86 234 56 72,\n\nMIASTO GAMMA – 87 234 56 73.',
187
- 'Numery kontaktowe:\n\nMIASTO ALFA – [Telefon],\n\nMIASTO BETA – [Telefon],\n\nMIASTO GAMMA – [Telefon].'),
188
- ('Telefony zaufania (Polska, numery bezpłatne):\n 116 111 – Telefon Zaufania dla Dzieci i Młodzieży (czynny codziennie, możliwość kontaktu także przez czat)\n 800 23 4567 – Centrum Wsparcia',
189
- 'Telefony zaufania (Polska, numery bezpłatne):\n [Telefon] – Telefon Zaufania dla Dzieci i Młodzieży (czynny codziennie, możliwość kontaktu także przez czat)\n [Telefon] – Centrum Wsparcia'),
190
- ('Numery kontaktowe:\n\nGdańsk: 58 123 45 67\n\nKraków: 12 345 67 89',
191
- 'Numery kontaktowe:\n\nGdańsk: [Telefon]\n\nKraków: [Telefon]'),
192
- ('Telefony zaufania:\n• 116 123 – Wsparcie dorosłych\n\n• 800 123 456 – Pomoc',
193
- 'Telefony zaufania:\n• [Telefon] – Wsparcie dorosłych\n\n• [Telefon] – Pomoc'),
194
- ('Tel.: (420) 222 345 671 – 222 345 672', 'Tel.: [Telefon]'),
195
- ('Tel. (420) 222 111 222 - 222 111 333 wew. 42', 'Tel. [Telefon]'),
196
- ('tel. 58 123 45 67 — 58 123 45 68', 'tel. [Telefon]'),
197
- ('Numery kontaktowe:\n\nGdańsk: 58 123 45 67\n\nWarunki korzystania.\n\nKraków: 12 345 67 89',
198
- 'Numery kontaktowe:\n\nGdańsk: [Telefon]\n\nWarunki korzystania.\n\nKraków: 12 345 67 89'),
199
- ('Telefony zaufania:\n116 123 – ' + 'Opis usługi. ' * 8 + '500 123 456 zgłoszeń',
200
- 'Telefony zaufania:\n[Telefon] – ' + 'Opis usługi. ' * 8 + '500 123 456 zgłoszeń'),
201
- ]
202
- negatives = [
203
- 'Tabela (420) 222 111 222 – 222 111 333',
204
- 'tel. (420) 222 111 222 – 222 111 333 EUR',
205
- 'Numery kontaktowe:\n\nKody taryfowe\n250300000\n250410000',
206
- 'Numery kontaktowe:\n\nGdańsk: 500 123 456 zł',
207
- 'Numery kontaktowe:\n\nKod: 501234567',
208
- 'Numery kontaktowe:\n\nWarunki korzystania z usługi.\n\nGdańsk: 58 123 45 67',
209
- 'Telefony zaufania:\n\nStatystyki\n800 123 456 – Liczba zgłoszeń',
210
- 'W artykule opisano numery kontaktowe:\n\nGdańsk: 58 123 45 67',
211
- 'Telefony zaufania:\n\n116 123 zł – Koszt programu',
212
- 'Numery kontaktowe:\n\n250300000\n250410000',
213
- 'Numery kontaktowe (20260908):',
214
- ]
215
- cases.extend((text, text) for text in negatives)
216
- for text, expected in cases:
217
- with self.subTest(text=text):
218
- spans = []
219
- out, counts = scrub_pii(text, spans=spans)
220
- self.assertEqual(out, expected)
221
- self.assertEqual(counts['phone'], expected.count('[Telefon]'))
222
- self.assertEqual((out, counts), self._scrub(text))
223
- rebuilt = text
224
- end = len(text)
225
- for span in sorted(spans, key=lambda s: s['start'], reverse=True):
226
- self.assertLessEqual(span['end'], end)
227
- self.assertEqual(text[span['start']:span['end']], span['text'])
228
- rebuilt = rebuilt[:span['start']] + '[Telefon]' + rebuilt[span['end']:]
229
- end = span['start']
230
- self.assertEqual(rebuilt, out)
231
- self.assertEqual(self._scrub(out), (out, dict.fromkeys(counts, 0)))
232
-
233
- def test_contact_values_review_regressions(self):
234
- cases = [
235
- ('tel. (03141) 23456', 'tel. [Telefon]'),
236
- ('tel. (03143) 2-34-56', 'tel. [Telefon]'),
237
- ('numer bezpłatny: +1-202-555-0142', 'numer bezpłatny: [Telefon]'),
238
- ('Toll Free: 888-555-0142, Phone: 207-555-0143',
239
- 'Toll Free: [Telefon], Phone: [Telefon]'),
240
- ('Straż pożarna (Lánglovagok/Пожежна служба): 101\n'
241
- 'Policja (Rendőrség/Поліція): 102\n'
242
- 'Pogotowie (Mentőautó/Швидка допомога): 103',
243
- 'Straż pożarna (Lánglovagok/Пожежна служба): [Telefon]\n'
244
- 'Policja (Rendőrség/Поліція): [Telefon]\n'
245
- 'Pogotowie (Mentőautó/Швидка допомога): [Telefon]'),
246
- ('tel. 112', 'tel. [Telefon]'),
247
- ('lost&found@example.com.', '[PII].'),
248
- ('Lostandfound@sub.example.com.', '[PII].'),
249
- ('☏ +36 20 234-5671. 08:00–21:00.', '☏ [Telefon]. 08:00–21:00.'),
250
- ('☏ +33 558234567. 12:00-02:00.', '☏ [Telefon]. 12:00-02:00.'),
251
- ('telefon (+4 0723456712 - +4 to kod).', 'telefon ([Telefon] - +4 to kod).'),
252
- ('tel. (+32 22345671)', 'tel. [Telefon]'),
253
- ]
254
- negatives = ['Tabela (03141) 23456', 'Phone: 207-555-0143 USD',
255
- 'Toll Free: opis produktu 207-555-0143', 'numer bezpłatny: 2020-01-15',
256
- 'Policja: 102 zł', 'Policja zatrzymała 102 osoby', 'Kod: 101',
257
- 'Pogotowie: budynek 103', 'Policja:\n\n102',
258
- 'phonebook 207-555-0143', 'systemd-fsck@.service.8.gz']
259
- cases.extend((text, text) for text in negatives)
260
- for text, expected in cases:
261
- with self.subTest(text=text):
262
- spans = []
263
- out, counts = scrub_pii(text, spans=spans)
264
- self.assertEqual(out, expected)
265
- self.assertEqual((out, counts), self._scrub(text))
266
- rebuilt = text
267
- for span in sorted(spans, key=lambda s: s['start'], reverse=True):
268
- self.assertEqual(text[span['start']:span['end']], span['text'])
269
- tag = '[Telefon]' if span['label'] == 'phone' else '[PII]'
270
- rebuilt = rebuilt[:span['start']] + tag + rebuilt[span['end']:]
271
- self.assertEqual(rebuilt, out)
272
- self.assertEqual(self._scrub(out), (out, dict.fromkeys(counts, 0)))
273
-
274
- def test_contact_challenge_phone_misses(self):
275
- for text, expected in (
276
- ('Biuro, +39 0964 234567, faks: +39 0964 234567.',
277
- 'Biuro, [Telefon], faks: [Telefon].'),
278
- ('Tel.+39.030.234561 · Fax+39.030.2345671.',
279
- 'Tel.[Telefon] · Fax[Telefon].'),
280
- ('Tel: (0) 611 2345. Tel: (0) 611 2346.',
281
- 'Tel: [Telefon]. Tel: [Telefon].'),
282
- ('Biuro, +44 20 7946 0958; fax: +44 20 7946 0959',
283
- 'Biuro, [Telefon]; fax: [Telefon]'),
284
- ('Tel: (0) 611 2345 wew. 42', 'Tel: [Telefon]'),
285
- ('Tabela +39 0964 234567', 'Tabela +39 0964 234567'),
286
- ('Tabela (0) 611 2345', 'Tabela (0) 611 2345'),
287
- ('Tel. 01.03.2020', 'Tel. 01.03.2020'),
288
- ('Kwota +39 0964 234567 EUR, faks: wymagany',
289
- 'Kwota +39 0964 234567 EUR, faks: wymagany'),
290
- ('Tabela +39 0964 234567\n\nfaks: +39 0964 234567',
291
- 'Tabela +39 0964 234567\n\nfaks: [Telefon]'),
292
- ('Kod +39 0964 234567, faks: +39 0964 234567',
293
- 'Kod +39 0964 234567, faks: [Telefon]'),
294
- ):
295
- with self.subTest(text=text):
296
- spans = []
297
- out, counts = scrub_pii(text, spans=spans)
298
- self.assertEqual(out, expected)
299
- self.assertEqual((out, counts), self._scrub(text))
300
- rebuilt = text
301
- for span in sorted(spans, key=lambda s: s['start'], reverse=True):
302
- self.assertEqual(text[span['start']:span['end']], span['text'])
303
- rebuilt = rebuilt[:span['start']] + '[Telefon]' + rebuilt[span['end']:]
304
- self.assertEqual(rebuilt, out)
305
- self.assertEqual(self._scrub(out), (out, dict.fromkeys(counts, 0)))
306
-
307
- def test_redaction_placeholders_do_not_become_phone_cues(self):
308
- for padding in range(25, 40):
309
- text = 'tel. 501 234 567' + ' x' * padding + ' 602 345 678'
310
- once, _ = self._scrub(text)
311
- twice, counts = self._scrub(once)
312
- self.assertEqual(twice, once)
313
- self.assertEqual(sum(counts.values()), 0)
314
- for marker in ('[Telefon]', '[PII]'):
315
- text = marker + ' - opis 602 345 678'
316
- self.assertEqual(self._scrub(text)[0], text)
317
- for gap in ('\n\n', ' - opis\n\n'):
318
- text = marker + gap + '602 345 678'
319
- self.assertEqual(self._scrub(text)[0], text)
320
- self.assertEqual(self._scrub('Telefon: ' + text)[0], 'Telefon: ' + text)
321
- self.assertEqual(self._scrub('[Telefon] nowy tel. 602345678')[0],
322
- '[Telefon] nowy tel. [Telefon]')
323
-
324
- def test_explicit_passport_variants_and_qualified_ids(self):
325
- for label, number in (
326
- ('paszport dyplomatyczny nr ', '1234'),
327
- ('Paszport dyplomatyczny nr ', 'D000001234'),
328
- ('Nr paszportu: ', 'D9001234'),
329
- ('Nr paszportu: ', 'C2001234'),
330
- ('Numer paszportu: ', 'D 001234'),
331
- ('NIP Gminy: ', '123-456-32-18'),
332
- ('REGON Gminy: ', '123456785'),
333
- ):
334
- with self.subTest(label=label, number=number):
335
- self.assertEqual(self._scrub(label+number+'.')[0], label+'[PII].')
336
- for text in ('Paszport wydany w 2017 roku', 'Paszport 2017',
337
- 'paszport dyplomatyczny 2020', 'Model D9001234',
338
- 'NIP firmy jest wymagany; kod 1234563218'):
339
- self.assertEqual(self._scrub(text)[0], text)
340
-
341
- def test_foreign_phone_cues_and_parenthesized_country_codes(self):
342
- for label, number in (
343
- ('Faks', '+32 22345671'),
344
- ('faksem ', '(+32 22345671)'),
345
- ('tel. ', '(+34) 965234571'),
346
- ('tel. ', '(420) 222 345 671'),
347
- ('telefon ', '(32-2) 234 56 71'),
348
- ('faks ', '(49-69) 23 45-671/672'),
349
- ('Faks: ', '(00) 49 69 23/45 -6 71'),
350
- ):
351
- with self.subTest(label=label, number=number):
352
- self.assertEqual(self._scrub(label+number)[0], label+'[Telefon]')
353
- for text in ('Tabela (420) 222 345 671', 'Tabela +32 22345671',
354
- 'tel. (420) 222 345 671 EUR'):
355
- self.assertEqual(self._scrub(text)[0], text)
356
-
357
- def test_electronic_addresses_and_krs(self):
358
- for text, expected, kind in (
359
- ('Adres do e-Doręczeń: AE:PL-12345-67890-ABCDE-12.',
360
- 'Adres do e-Doręczeń: [PII].', 'electronic_address'),
361
- ('E-PUAP: /przyklad123/SkrytkaESP', 'E-PUAP: [PII]', 'electronic_address'),
362
- ('EPUAP Urzędu /urzad/SkrytkaESP; /urzad/skrytka; /urzad/inna',
363
- 'EPUAP Urzędu [PII]; [PII]; [PII]', 'electronic_address'),
364
- ('Elektroniczna Skrzynka Podawcza na platformie E-PUAP: /urzad/skrytka',
365
- 'Elektroniczna Skrzynka Podawcza na platformie E-PUAP: [PII]', 'electronic_address'),
366
- ('KRS: 651234; KRS 0000123457.', 'KRS: [PII]; KRS [PII].', 'krs'),
367
- ):
368
- with self.subTest(text=text):
369
- out, counts = self._scrub(text)
370
- self.assertEqual(out, expected)
371
- self.assertGreater(counts[kind], 0)
372
- self.assertEqual(self._scrub(out), (out, dict.fromkeys(counts, 0)))
373
- for text in ('Ścieżka /usr/local', 'E-PUAP: https://example.com/usr/local',
374
- 'KRS wymagany, kod 651234', 'KRS 1234567890123',
375
- 'KRS 123456 789012 345678', 'KRS 651234 zł',
376
- 'ORCID: 0000-0001-2345-6789', 'AE:PL-12345-67890-ABCDE-120'):
377
- with self.subTest(text=text):
378
- self.assertEqual(self._scrub(text)[0], text)
379
-
380
- def test_extension_and_continuation_after_confirmed_phone(self):
381
- for text, expected in (
382
- ('tel. 22 234 56 71 lub 234 56 72 wew. 402, pokój nr 14',
383
- 'tel. [Telefon] lub [Telefon], pokój nr 14'),
384
- ('tel. 00966 2345671, wew. 109, fax. 00966 234 5672',
385
- 'tel. [Telefon], fax. [Telefon]'),
386
- ('tel. 25/234 56 71 wew. 48 pokój nr 9', 'tel. [Telefon] pokój nr 9'),
387
- ('tel. 501234567 albo 1234567', 'tel. [Telefon] albo [Telefon]'),
388
- ('wew. 402', 'wew. 402'),
389
- ('tel. 501234567 pokój nr 14', 'tel. [Telefon] pokój nr 14'),
390
- ('tel. 501234567 lub kwota 1234567 zł', 'tel. [Telefon] lub kwota 1234567 zł'),
391
- ('tel. 501234567 wew. 402 zł', 'tel. [Telefon] wew. 402 zł'),
392
- ('tel. 501234567 wew. 1234567', 'tel. [Telefon] wew. 1234567'),
393
- ):
394
- with self.subTest(text=text):
395
- self.assertEqual(self._scrub(text)[0], expected)
396
-
397
- def test_email_domain_requires_nonempty_labels(self):
398
- for text in ('systemd-fsck@.service.8.gz', 'x@-example.com', 'x@example-.com',
399
- 'x@example..com'):
400
- with self.subTest(text=text):
401
- self.assertEqual(self._scrub(text)[0], text)
402
- self.assertEqual(self._scrub('a@sub-domain.example.com.')[0], '[PII].')
403
-
404
- def test_foreign_phone_line_wrapping(self):
405
- self.assertEqual(self._scrub('tel. +49\n711\n234\n5671')[0], 'tel. [Telefon]')
406
- self.assertEqual(self._scrub('tel. +49 711 234 5671\n2. Szkoła')[0],
407
- 'tel. [Telefon]\n2. Szkoła')
408
-
409
- def test_short_phone_lists_and_foreign_trunk_numbers(self):
410
- for raw, expected in (
411
- ('tel. 523-45-61, 523-45-62; 517 234', 'tel. [Telefon], [Telefon]; [Telefon]'),
412
- ('Tel. 09191 234567', 'Tel. [Telefon]'),
413
- ('tel. (032) 23 45 67', 'tel. [Telefon]'),
414
- ('Numer telefonu: 79 234 567', 'Numer telefonu: [Telefon]'),
415
- ('tel. 501234567, kod 1234567', 'tel. [Telefon], kod 1234567'),
416
- ('HAL Id: tel. 01279041', 'HAL Id: tel. 01279041'),
417
- ):
418
- with self.subTest(raw=raw):
419
- self.assertEqual(self._scrub(raw)[0], expected)
420
-
421
- def test_extended_phone_formats(self):
422
- for number in ("74/234 56 71", "095/ 23 45 671", "261-234-571",
423
- "47 234 56 71", "826-45-67", "51 23 45",
424
- "+49 (0)711 234 56 76", "+39 057123451",
425
- "+32 22345671", "+1 202-555-0144", "00966 2345671",
426
- "12 23 45 671-673", "+251 11 234 56 71/72"):
427
- with self.subTest(number=number):
428
- out, counts = self._scrub('tel. ' + number)
429
- self.assertEqual(out, 'tel. [Telefon]')
430
- self.assertEqual(counts['phone'], 1)
431
- self.assertEqual(sum(counts.values()), 1)
432
-
433
- def test_short_numbers_require_immediate_phone_label(self):
434
- for text in ("Tabela 826-45-67", "tel. opis tabeli 1234567",
435
- "tel. 501234567 kwota 1234567 zł", "tel. 2020-01-15"):
436
- with self.subTest(text=text):
437
- self.assertIn(text.split(' ')[-1], self._scrub(text)[0])
438
-
439
- def test_labelled_damaged_identifiers(self):
440
- for label, number, kind in (("PESEL: ", "44051401457", "pesel"),
441
- ("PESEL:\n", "44O514O1457", "pesel"),
442
- ("NIP: ", "123-456-32-19", "nip"),
443
- ("REGON: ", "123456786", "regon"),
444
- ("Dowód osobisty: ", "ABA400000", "document"),
445
- ("Numer paszportu: ", "120012345", "document")):
446
- with self.subTest(label=label, number=number):
447
- out, counts = self._scrub(label + number + '. Koniec.')
448
- self.assertEqual(out, label + '[PII]. Koniec.')
449
- self.assertEqual(counts[kind], 1)
450
-
451
- def test_identifier_context_does_not_eat_prose_or_long_accounts(self):
452
- self.assertEqual(self._scrub('PESEL: 44051401457 i coś dalej')[0],
453
- 'PESEL: [PII] i coś dalej')
454
- for text in ("PESEL wymagany, kod 44051401457", "NIP brak 1234563219",
455
- "REGON\n\n123456786", "PESEL 12345678901234567890",
456
- "Paszport wydany w 2017 roku", "Model ABA400000"):
457
- with self.subTest(text=text):
458
- self.assertEqual(self._scrub(text)[0], text)
459
-
460
- def test_registration_contact_cues(self):
461
- for label in ("Zapisy pod numerem: ", "Rejestracja: pod numerem ",
462
- "Kontakt pod nr. ", "SZYBKI KONTAKTTel. kontaktowy: "):
463
- with self.subTest(label=label):
464
- out, counts = self._scrub(label + "501 234 567")
465
- self.assertEqual(out, label + "[Telefon]")
466
- self.assertEqual(counts['phone'], 1)
467
-
468
- def test_contact_cues_do_not_match_other_number_fields(self):
469
- for text in ("Sprawa pod numerem 501234567", "Hotel: 501234567",
470
- "Umowa pod numerem 501234567", "Sprawa pod numerem:\n\n501234567",
471
- "Zapisy pod numerem: 501234567 zł",
472
- "Zapisy dotyczą sprawy pod numerem 501234567"):
473
- with self.subTest(text=text):
474
- self.assertEqual(self._scrub(text)[0], text)
475
-
476
- def test_phone_stops_before_opening_hours(self):
477
- for phone in ("513 234 571", "+48 513 234 571", "22 123 45 67"):
478
- for hours in (" (9:00-15:00)", " 09:00–15:00", "\t(19:30-20:00)",
479
- " 15.00 - 19.00", " (9.00 – 15.00)"):
480
- with self.subTest(phone=phone, hours=hours):
481
- text = f"Telefon: {phone}{hours} mail: a@example.com"
482
- out, counts = self._scrub(text)
483
- self.assertEqual(out, f"Telefon: [Telefon]{hours} mail: [PII]")
484
- self.assertEqual(counts['phone'], 1)
485
-
486
- def test_national_ids_require_explicit_adjacent_labels(self):
487
- for label, number, kind in (
488
- ("REGON: ", REGON9, "regon"),
489
- ("nr REGON ", REGON9, "regon"),
490
- ("numer regon:\n", REGON14, "regon"),
491
- ("REGON nr: ", REGON9, "regon"),
492
- ("NIP = ", NIP, "nip"),
493
- ("numer NIP:\n", "PL123-45-63-218", "nip"),
494
- ):
495
- with self.subTest(label=label):
496
- out, counts = self._scrub(label + number)
497
- self.assertEqual(out, label + "[PII]")
498
- self.assertEqual(counts[kind], 1)
499
-
500
- def test_tariff_codes_are_not_regons(self):
501
- # Real EUR-Lex commodity codes happen to pass the REGON checksum.
502
- text = "WYKAZ A\n250410000 |\n250490000 |\n250860000 |"
503
- out, counts = self._scrub(text)
504
- self.assertEqual(counts['regon'], 0)
505
- self.assertEqual(out, text)
506
-
507
- def test_numeric_tables_are_not_phones(self):
508
- for text in ("Podatek od towarów i usług\n132 165 000\nPodatek akcyzowy\n62 600 000",
509
- "Kwota w EUR\nPrzeniesiona kwota\n+552 977 761",
510
- "CJK 𠎠 132000 203A0 0xF0 0xA0", "Kod 501234567",
511
- "Kod 123456785", "Tabela\n250.000.000\n13.853.000\n1"):
512
- with self.subTest(text=text):
513
- self.assertEqual(self._scrub(text)[0], text)
514
-
515
- def test_phone_stops_before_next_section(self):
516
- for phone in ("601 234 571", "222-345-671", "+48 601 234 571"):
517
- text = f"tel. {phone}\n2. Szkoła oferuje zajęcia."
518
- out, counts = self._scrub(text)
519
- self.assertEqual(out, "tel. [Telefon]\n2. Szkoła oferuje zajęcia.")
520
- self.assertEqual(counts['phone'], 1)
521
-
522
- def test_glued_phone_label_and_international_prefix(self):
523
- for text, expected in (("Telefon58 234 56 71", "Telefon[Telefon]"),
524
- ("☎ 501 234 567", "☎ [Telefon]"),
525
- ("Kontakt +48 501 234 567", "Kontakt [Telefon]"),
526
- ("Kontakt 0048 501 234 567", "Kontakt [Telefon]")):
527
- self.assertEqual(self._scrub(text)[0], expected)
528
-
529
- def test_phone_context_is_bounded(self):
530
- for text in ("Telefon jest wymagany.\n\nKod 501234567",
531
- "tel. kod: 501234567",
532
- "telefon " + "tekst " * 20 + "501234567"):
533
- with self.subTest(text=text):
534
- self.assertEqual(self._scrub(text)[0], text)
535
-
536
- def test_labels_do_not_reach_across_words_or_paragraphs(self):
537
- for text in (f"Kod {NIP}", f"NIP wymagany, kod produktu {NIP}",
538
- f"REGON przedsiębiorcy. Kod {REGON9}",
539
- f"REGON\n\n{REGON9}", f"NIP " + " " * 80 + NIP,
540
- f"antyREGON: {REGON9}", f"REGONXYZ: {REGON9}",
541
- f"Kod {REGON14}"):
542
- with self.subTest(text=text):
543
- out, counts = self._scrub(text)
544
- self.assertEqual(counts['nip'] + counts['regon'], 0)
545
- self.assertNotIn('[PII]', out)
546
-
547
- def test_foreign_phone_is_not_a_polish_national_id(self):
548
- # Synthetic checksum-collision formats formerly became '+49 (0)[PII]' / '+39 [PII]'.
549
- for text in ("faks: +49 (0)711 234 56 76", "tel. +39 057123451"):
550
- with self.subTest(text=text):
551
- out, counts = self._scrub(text)
552
- self.assertEqual(out, 'faks: [Telefon]' if text.startswith('faks') else 'tel. [Telefon]')
553
- self.assertEqual(counts['nip'] + counts['regon'], 0)
554
-
555
- def test_polish_format_gaps(self):
556
- cases = [
557
- ("tel. 501\u00a0234\u00a0567", "tel. [Telefon]", "phone"),
558
- ("tel. 501\u202f234\u2009567", "tel. [Telefon]", "phone"),
559
- ("NIP: 123-45-63-218", "NIP: [PII]", "nip"),
560
- ("NIP: PL1234563218", "NIP: [PII]", "nip"),
561
- ("NIP: PL123-456-32-18", "NIP: [PII]", "nip"),
562
- ("Kontakt: łukasz@example.com", "Kontakt: [PII]", "email"),
563
- ("Kontakt: żaneta@żółw.example.com", "Kontakt: [PII]", "email"),
564
- ]
565
- for raw, expected, kind in cases:
566
- with self.subTest(raw=raw):
567
- out, counts = self._scrub(raw)
568
- self.assertEqual(out, expected)
569
- self.assertEqual(counts[kind], 1)
570
- self.assertEqual(self._scrub(out), (out, dict.fromkeys(counts, 0)))
571
-
572
- def test_adjacent_phones(self):
573
- for separator in (" ", " ", "\t", "\n"):
574
- text = f"tel. 501 234 567{separator}22 123 45 67"
575
- out, counts = self._scrub(text)
576
- self.assertEqual(out, f"tel. [Telefon]{separator}[Telefon]")
577
- self.assertEqual(counts["phone"], 2)
578
-
579
- def test_foreign_ibans(self):
580
- # Published example IBANs; numeric and alphanumeric BBANs, various lengths.
581
- for iban in ("DE89370400440532013000", "GB82WEST12345698765432",
582
- "FR1420041010050500013M02606", "NO9386011117947",
583
- "UA213223130000026007233566001"):
584
- for raw in (iban, iban.lower(), " ".join(iban[i:i+4] for i in range(0, len(iban), 4))):
585
- with self.subTest(raw=raw):
586
- out, counts = self._scrub(f"Rachunek: {raw} do wpłat.")
587
- self.assertEqual(out, "Rachunek: [PII] do wpłat.")
588
- self.assertEqual(counts["account"], 1)
589
- self.assertEqual(sum(counts.values()), 1)
590
-
591
- def test_invalid_ibans_are_not_accounts(self):
592
- for raw in ("DE88370400440532013000", "DE8937040044053201300",
593
- "DE893704004405320130000", "ZZ89370400440532013000"):
594
- with self.subTest(raw=raw):
595
- out, counts = self._scrub(raw)
596
- self.assertEqual(out, raw)
597
- self.assertEqual(counts["account"], 0)
598
-
599
- def test_labelled_identity_documents(self):
600
- for label, number in (("Dowód osobisty: ", "ABA300000"),
601
- ("numer dowodu ", "ABA 300000"),
602
- ("dowodu osobistego nr ", "aba-300000"),
603
- ("Paszport nr: ", "AB1234567"),
604
- ("paszportu serii ", "AB 1234567")):
605
- with self.subTest(label=label):
606
- out, counts = self._scrub(label + number + ".")
607
- self.assertEqual(out, label + "[PII].")
608
- self.assertEqual(counts["document"], 1)
609
-
610
- def test_conservative_identifier_policy(self):
611
- for text in ("Model ABA300000, kod AB1234567", "jan (małpa) example.com",
612
- "Numer 12345678901234567890"):
613
- with self.subTest(text=text):
614
- self.assertEqual(self._scrub(text)[0], text)
615
-
616
- def test_numeric_clusters_are_not_partially_scrubbed(self):
617
- for text in ("Konto: 501 234 567 8901 2345 6789 0123",
618
- "wersja 3.79.25.482243121", "cena 500 100 200 PLN",
619
- "współrzędne 52.1234567890 N", "data 2020 - 01 - 15 rok",
620
- "faktura 1234 5678 9012 3456", "alarmowe:\n112\n997\n999"):
621
- with self.subTest(text=text):
622
- self.assertEqual(self._scrub(text)[0], text)
623
-
624
- def test_monetary_amounts_survive(self):
625
- # Real legal-text failures plus checksum-valid numbers that resemble IDs.
626
- for text in ("grzywny do 500\u00a0000\u00a0000 złotych",
627
- "kwoty 159\u00a0179\u00a0632,2 mln zł",
628
- "grzywny do 250 000 000\n złotych",
629
- "wydatki 293.474.478 mln zł",
630
- "kwota 123456785 zł", "kwota 1234563218 PLN",
631
- "kwota 500 100 200 tys. złotych", "kwota 500 100 200,50 EUR",
632
- "kwota 500 100 200 złotego", "USD 500 100 200", "$500 100 200"):
633
- with self.subTest(text=text):
634
- out, counts = self._scrub(text)
635
- self.assertEqual(out, text.replace('\u00a0', ' '))
636
- self.assertEqual(sum(counts.values()), 0)
637
-
638
- def test_money_context_does_not_hide_contacts(self):
639
- for text, expected in (
640
- ("Cena 100 zł, tel. 501 234 567", "Cena 100 zł, tel. [Telefon]"),
641
- ("tel. 501 234 567, cena 100 zł", "tel. [Telefon], cena 100 zł"),
642
- ("tel. 501 234 567.\nCena 100 zł", "tel. [Telefon].\nCena 100 zł"),
643
- ("Kontakt euro@example.com", "Kontakt [PII]"),
644
- ):
645
- with self.subTest(text=text):
646
- self.assertEqual(self._scrub(text)[0], expected)
647
-
648
- def _scrub(self, text):
649
- return scrub_pii(text)
650
-
651
- def test_email_becomes_pii(self):
652
- out, counts = self._scrub("Pisz na jan.kowalski@example.com dziś.")
653
- self.assertIn("[PII]", out)
654
- self.assertNotIn("jan.kowalski@example.com", out)
655
- self.assertEqual(counts["email"], 1)
656
- self.assertIn("Pisz na", out)
657
- self.assertIn("dziś.", out)
658
-
659
- def test_mobile_and_grouped_phone_become_telefon(self):
660
- out, counts = self._scrub("Zadzwoń 501 234 567 albo 501-234-567.")
661
- self.assertEqual(out.count("[Telefon]"), 2)
662
- self.assertNotIn("501", out)
663
- self.assertEqual(counts["phone"], 2)
664
-
665
- def test_leading_zero_landline(self):
666
- out, counts = self._scrub("Siedziba: tel. 022 123 45 67 w Warszawie.")
667
- self.assertIn("[Telefon]", out)
668
- self.assertNotIn("022", out)
669
- self.assertEqual(counts["phone"], 1)
670
-
671
- def test_plus48_paren(self):
672
- out, counts = self._scrub("Kontakt: +48 (22) 123-45-67.")
673
- self.assertIn("[Telefon]", out)
674
- self.assertNotIn("+48", out)
675
- self.assertNotIn("123-45-67", out)
676
- self.assertEqual(counts["phone"], 1)
677
-
678
- def test_dzwon_label_family(self):
679
- out, counts = self._scrub("dzwoń: 601234567 lub tel. 602-234-567")
680
- self.assertEqual(counts["phone"], 2)
681
- self.assertNotIn("601234567", out)
682
- self.assertNotIn("602-234-567", out)
683
-
684
- def test_newline_over_span(self):
685
- out, counts = self._scrub("tel.\n+48\n501\n234\n567\nproszę dzwonić")
686
- self.assertIn("[Telefon]", out)
687
- self.assertEqual(counts["phone"], 1)
688
- self.assertNotIn("501", out)
689
-
690
- def test_foreign_uk_bare(self):
691
- out, counts = self._scrub("London office, tel. 020 7946 0958 weekday mornings.")
692
- self.assertIn("[Telefon]", out)
693
- self.assertNotIn("7946", out)
694
- self.assertEqual(counts["phone"], 1)
695
-
696
- def test_pesel_nip_regon_iban(self):
697
- text = (
698
- f"PESEL {PESEL}, NIP {NIP}, REGON {REGON9}, REGON {REGON14}, "
699
- f"konto {IBAN}."
700
- )
701
- out, counts = self._scrub(text)
702
- self.assertNotIn(PESEL, out)
703
- self.assertNotIn(NIP, out)
704
- self.assertNotIn(REGON14, out)
705
- self.assertNotIn(IBAN, out)
706
- self.assertEqual(out.count("[PII]"), 5)
707
- self.assertEqual(counts["pesel"], 1)
708
- self.assertEqual(counts["nip"], 1)
709
- self.assertEqual(counts["regon"], 2)
710
- self.assertEqual(counts["account"], 1)
711
-
712
- def test_nip_with_dashes(self):
713
- out, counts = self._scrub("NIP 123-456-32-18 na fakturze.")
714
- self.assertIn("[PII]", out)
715
- self.assertNotIn("123-456-32-18", out)
716
- self.assertEqual(counts["nip"], 1)
717
-
718
- def test_invalid_eleven_digits_are_not_pesel(self):
719
- # Same length as PESEL, fails checksum — statute / case-like numbers stay.
720
- bogus = "44051401457"
721
- out, counts = self._scrub(f"Sygnatura {bogus} pozostaje.")
722
- self.assertIn(bogus, out)
723
- self.assertEqual(counts["pesel"], 0)
724
-
725
- def test_dates_and_case_numbers_survive(self):
726
- text = "Wyrok z 2018-03-22, sygn. II K 336/17, art. 4 pkt 2."
727
- out, counts = self._scrub(text)
728
- self.assertEqual(out, text)
729
- self.assertEqual(sum(counts.values()), 0)
730
-
731
- def test_official_names_stay(self):
732
- text = "Poseł Jan Kowalski złożył interpelację w Sejmie RP."
733
- out, counts = self._scrub(text)
734
- self.assertEqual(out, text)
735
- self.assertEqual(sum(counts.values()), 0)
736
-
737
- def test_idempotent(self):
738
- once, _ = self._scrub(f"mail a@example.com tel +48 501 234 567 PESEL {PESEL}")
739
- twice, counts = self._scrub(once)
740
- self.assertEqual(once, twice)
741
- self.assertEqual(sum(counts.values()), 0)
742
-
743
- def test_postal_code_survives_but_labelled_krs_is_redacted(self):
744
- text = "Kod 02-123 Warszawa, KRS 0000123456, kwota 500,00 zł."
745
- out, counts = self._scrub(text)
746
- self.assertEqual(out, 'Kod 02-123 Warszawa, KRS [PII], kwota 500,00 zł.')
747
- self.assertEqual(counts["phone"], 0)
748
- self.assertEqual(counts['krs'], 1)
749
-
750
- def test_kw_and_postal_range_survive(self):
751
- text = "KW KR1P/00012345/6, kod 00-950, okres 2020-2024."
752
- out, counts = self._scrub(text)
753
- self.assertEqual(out, text)
754
- self.assertEqual(counts["phone"], 0)
755
-
756
- def test_newline_phone_does_not_consume_unrelated_text(self):
757
- text = "tel.\nW sprawie art. 5\nproszę dzwonić 501 234 567."
758
- out, counts = self._scrub(text)
759
- self.assertIn("W sprawie art. 5", out)
760
- self.assertIn("[Telefon]", out)
761
- self.assertEqual(counts["phone"], 1)
762
- self.assertNotIn("501", out)
763
-
764
- def test_iban_without_pl_prefix(self):
765
- bare_iban = "61109010140000071219812874"
766
- out, counts = self._scrub(f"Rachunek nr {bare_iban}")
767
- self.assertNotIn(bare_iban, out)
768
- self.assertEqual(counts["account"], 1)
769
- self.assertEqual(counts["phone"], 0)
770
-
771
- def test_spaced_iban_and_nip_prefixes(self):
772
- spaced = "61 1090 1014 0000 0712 1981 2874"
773
- text = f"nr rachunku: {spaced}; NIP:{NIP}; NIP-{NIP}."
774
- out, counts = self._scrub(text)
775
- self.assertNotIn("1090", out)
776
- self.assertNotIn(NIP, out)
777
- self.assertEqual(counts["account"], 1)
778
- self.assertEqual(counts["nip"], 2)
779
- self.assertEqual(counts["phone"], 0)
780
-
781
- def test_execution_order_precedence(self):
782
- text = f"Przelew na {IBAN}."
783
- out, counts = self._scrub(text)
784
- self.assertNotIn("611090", out)
785
- self.assertEqual(counts["account"], 1)
786
- self.assertEqual(counts["pesel"], 0)
787
- self.assertEqual(counts["phone"], 0)
788
- self.assertEqual(counts["regon"], 0)
789
-
790
- def test_complex_email_formats(self):
791
- addr = "jan.k+alert@example.com"
792
- out, counts = self._scrub(f"Kontakt: {addr}")
793
- self.assertNotIn(addr, out)
794
- self.assertEqual(counts["email"], 1)
795
- nested = "jan.kowalski+test@subdomain.example.com"
796
- out, counts = self._scrub(nested)
797
- self.assertNotIn(nested, out)
798
- self.assertEqual(counts["email"], 1)
799
-
800
- def test_pii_inside_brackets_or_quotes(self):
801
- out, counts = self._scrub(f'("email: jan@example.com", PESEL: "{PESEL}")')
802
- self.assertNotIn("jan@example.com", out)
803
- self.assertNotIn(PESEL, out)
804
- self.assertEqual(counts["email"], 1)
805
- self.assertEqual(counts["pesel"], 1)
806
-
807
- def test_iban_with_mixed_dashes_and_spaces(self):
808
- # Same MOD-97 number as IBAN, invoice-style PL + space + hyphen groups.
809
- mixed_iban = "PL 61-1090-1014-0000-0712-1981-2874"
810
- out, counts = self._scrub(f"Rachunek: {mixed_iban}")
811
- self.assertNotIn("1090", out)
812
- self.assertNotIn("0712", out)
813
- self.assertEqual(counts["account"], 1)
814
- self.assertEqual(counts["phone"], 0)
815
-
816
- def test_nip_and_regon_with_colons_and_newlines(self):
817
- text = f"NIP:\n{NIP}\nREGON:\n{REGON9}"
818
- out, counts = self._scrub(text)
819
- self.assertNotIn(NIP, out)
820
- self.assertNotIn(REGON9, out)
821
- self.assertEqual(counts["nip"], 1)
822
- self.assertEqual(counts["regon"], 1)
823
- self.assertIn("NIP:", out)
824
- self.assertIn("REGON:", out)
825
-
826
- def test_postal_code_does_not_trigger_phone(self):
827
- text = "Adres: ul. Wiejska 4, 00-902 Warszawa."
828
- out, counts = self._scrub(text)
829
- self.assertEqual(out, text)
830
- self.assertEqual(counts["phone"], 0)
831
-
832
- def test_newline_phone_is_bounded(self):
833
- text = "tel.\n\n\nW sprawie umowy proszę dzwonić pod 501 234 567."
834
- out, counts = self._scrub(text)
835
- self.assertIn("W sprawie umowy", out)
836
- self.assertEqual(counts["phone"], 1)
837
- self.assertNotIn("501", out)
838
-
839
- def test_datetime_stamps_are_not_phones(self):
840
- # HPLT leftover: DD-MM-YYYY HH:MM looks like a leading-0 landline.
841
- text = "wpis - 08-03-2020 13:27 | 08-07-2014 16:15:00 na liście."
842
- out, counts = self._scrub(text)
843
- self.assertEqual(out, text)
844
- self.assertEqual(counts["phone"], 0)
845
-
846
- def test_en_dash_grouped_phone(self):
847
- out, counts = self._scrub("sekretariat tel. 65 234–56-71 od poniedziałku")
848
- self.assertIn("[Telefon]", out)
849
- self.assertNotIn("234", out)
850
- self.assertEqual(counts["phone"], 1)
851
-
852
- def test_ministry_file_numbers_are_not_phones(self):
853
- # Real Sejm sample FPs: dotted znak / attachment stems look like landlines.
854
- text = (
855
- "decyzja (znak: BPRM.4820.2.3.2020). "
856
- "pismem znak: DF.III.8200.12.2020.PP. "
857
- "Zalacznik do pisma LUB-OMK.601.1.2024.3.pdf"
858
- )
859
- out, counts = self._scrub(text)
860
- self.assertEqual(out, text)
861
- self.assertEqual(counts["phone"], 0)
862
-
863
- def test_iban_takes_precedence_over_substring_matches(self):
864
- text = f"Numer konta do wpłaty: {IBAN}"
865
- out, counts = self._scrub(text)
866
- self.assertEqual(counts["account"], 1)
867
- self.assertEqual(counts["pesel"], 0)
868
- self.assertEqual(counts["phone"], 0)
869
- self.assertEqual(counts["regon"], 0)
870
- self.assertEqual(counts["nip"], 0)
871
-
872
-
873
- if __name__ == "__main__":
874
- unittest.main()