Maggio33 ppuzio commited on
Commit
a916ede
·
1 Parent(s): a9d134a

Add in-tree PII scrub (no new parquet) (#20)

Browse files

- Add in-tree PII scrub and wire it into HPLT and Sejm fetchers (f02380ada54f72c34dcf195464c6639e840eb731)


Co-authored-by: Paweł Puzio <ppuzio@users.noreply.huggingface.co>

src/clean_hplt_v3.py CHANGED
@@ -16,6 +16,10 @@ import zstandard as zstd
16
  import pyarrow as pa, pyarrow.parquet as pq
17
  import tiktoken
18
 
 
 
 
 
19
  ADDED = "2026-07-14"
20
  SOURCE = "european_hplt_v3_pl"
21
  LICENSE = "CC0-1.0"
@@ -125,6 +129,7 @@ def main():
125
  t0 = time.time()
126
 
127
  drops = {}; regs = {}; doms = {}; dom_counts = {}
 
128
  ids, texts, tokens = [], [], []
129
  read = kept = chars = toks = 0
130
  mt_sum = 0.0
@@ -169,6 +174,11 @@ def main():
169
  reg = o.get("web-register") or {}
170
  rtop, _ = top_register(reg); regs[rtop] = regs.get(rtop, 0) + 1
171
  mt_sum += float(reg.get("MT", 0.0)) if isinstance(reg, dict) else 0.0
 
 
 
 
 
172
  tk = len(ENC.encode(text, disallowed_special=()))
173
  ids.append(f"{out}_{kept}"); texts.append(text); tokens.append(tk)
174
  kept += 1; chars += len(text); toks += tk
@@ -192,6 +202,7 @@ def main():
192
  "mt_prob_mean_kept": round(mt_sum / max(1, kept), 3),
193
  "domains_top_sample": dict(sorted(doms.items(), key=lambda x: -x[1])[:30]),
194
  "secs": round(time.time()-t0, 1),
 
195
  "source_repo": f"HPLT/HPLT3.0 pol_Latn {a.bin_label} via {a.inp}"}
196
  (outd / f"{out}.stats.json").write_text(json.dumps(stats, ensure_ascii=False, indent=2)+"\n", encoding="utf-8")
197
  print("=== STATS ===")
 
16
  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"
25
  LICENSE = "CC0-1.0"
 
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
  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
  "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 ===")
src/fetch_govpl.py CHANGED
@@ -21,18 +21,15 @@ Usage:
21
  from __future__ import annotations
22
  import argparse, json, re, subprocess, sys, threading, time
23
  from concurrent.futures import ThreadPoolExecutor
24
- from html import unescape
25
  from pathlib import Path
26
 
27
  sys.path.insert(0, str(Path(__file__).resolve().parent))
28
  from discover_govpl import BASE, http_get, http_get_url, listing_articles # shared, DRY
 
29
 
30
  KEY = "govpl" # build_dynaword reads <KEY>.jsonl.zst
31
  MIN_CHARS = 200 # same floor as build_dynaword; skip stubs early
32
 
33
- _SCRIPT = re.compile(r"(?is)<(script|style)[^>]*>.*?</\1>")
34
- _BLOCK_END = re.compile(r"(?i)</(p|div|h[1-6]|li|tr|table|ul|ol|blockquote)\s*>|<br\s*/?>")
35
- _TAG = re.compile(r"<[^>]+>")
36
  # Body ends where the editor-content region gives way to gallery/attachments/tags.
37
  _END_MARKER = re.compile(
38
  r'<[^>]+class="[^"]*(?:attachments|art-tags|tags|social|share|gallery|files)[^"]*"'
@@ -40,17 +37,6 @@ _END_MARKER = re.compile(
40
  _EDITOR = re.compile(r'<div class="editor-content"[^>]*>', re.I)
41
 
42
 
43
- def html_to_text(html: str) -> str:
44
- html = _SCRIPT.sub("", html)
45
- html = _BLOCK_END.sub("\n", html)
46
- html = _TAG.sub("", html)
47
- text = unescape(html)
48
- text = re.sub(r"[ \t]+", " ", text)
49
- text = re.sub(r" *\n *", "\n", text)
50
- text = re.sub(r"\n{3,}", "\n\n", text)
51
- return text.strip()
52
-
53
-
54
  def article_body(html: str) -> str:
55
  """Text of the article body. gov.pl pages carry the class twice; pick the
56
  richest editor-content region and cut at the trailing gallery/attachments.
 
21
  from __future__ import annotations
22
  import argparse, json, re, subprocess, sys, threading, time
23
  from concurrent.futures import ThreadPoolExecutor
 
24
  from pathlib import Path
25
 
26
  sys.path.insert(0, str(Path(__file__).resolve().parent))
27
  from discover_govpl import BASE, http_get, http_get_url, listing_articles # shared, DRY
28
+ from html_text import html_to_text
29
 
30
  KEY = "govpl" # build_dynaword reads <KEY>.jsonl.zst
31
  MIN_CHARS = 200 # same floor as build_dynaword; skip stubs early
32
 
 
 
 
33
  # Body ends where the editor-content region gives way to gallery/attachments/tags.
34
  _END_MARKER = re.compile(
35
  r'<[^>]+class="[^"]*(?:attachments|art-tags|tags|social|share|gallery|files)[^"]*"'
 
37
  _EDITOR = re.compile(r'<div class="editor-content"[^>]*>', re.I)
38
 
39
 
 
 
 
 
 
 
 
 
 
 
 
40
  def article_body(html: str) -> str:
41
  """Text of the article body. gov.pl pages carry the class twice; pick the
42
  richest editor-content region and cut at the trailing gallery/attachments.
src/fetch_sejm_api.py CHANGED
@@ -16,6 +16,8 @@ import shutil
16
  import sys
17
  from typing import Any, Iterable
18
 
 
 
19
 
20
  SOURCE_NAME = "sejm_api"
21
  SOURCE_REPOSITORY = "PiotrSty/sejm-speeches-corpus"
@@ -82,6 +84,7 @@ def normalize_source_row(
82
  return None
83
 
84
  text = str(row["text"]).strip()
 
85
  author = str(row.get("speaker", "")).strip()
86
  source_url = str(row.get("source_url", "")).strip()
87
  term = str(row.get("term", "")).strip()
 
16
  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
  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()
src/fetch_sejm_interpellations.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Fetch Sejm interpellations and written questions into a SpeakLeash-style
3
+ .jsonl.zst for build_dynaword.py.
4
+
5
+ Official parliamentary materials, outside copyright under art. 4 pkt 2 pr. aut.,
6
+ 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
14
+ python3 src/fetch_sejm_interpellations.py --out ~/speakleash --terms 10 --max-docs 30
15
+ """
16
+ from __future__ import annotations
17
+ import argparse, json, re, subprocess, sys, time
18
+ from pathlib import Path
19
+ from urllib.error import HTTPError, URLError
20
+ 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"
28
+ UA = {"User-Agent": "polish-dynaword/0.1 (+research; openly-licensed corpus)",
29
+ "Accept": "*/*"}
30
+ MIN_CHARS = 200
31
+ DEFAULT_TERMS = (7, 8, 9, 10) # 1–6 time out; see artifacts/source_findings.md
32
+ COLLECTIONS = ("interpellations", "writtenQuestions")
33
+
34
+ _KIND = {
35
+ ("interpellations", False): "interpellation",
36
+ ("interpellations", True): "interpellation_reply",
37
+ ("writtenQuestions", False): "written_question",
38
+ ("writtenQuestions", True): "written_question_reply",
39
+ }
40
+ _COLLECTION = {
41
+ "interpellation": "interpellations",
42
+ "interpellation_reply": "interpellations",
43
+ "written_question": "writtenQuestions",
44
+ "written_question_reply": "writtenQuestions",
45
+ }
46
+
47
+ _HEAD = re.compile(r"(?is)<head[^>]*>.*?</head>")
48
+ _H1 = re.compile(r"(?is)<h1[^>]*>.*?</h1>")
49
+ _META_P = re.compile(
50
+ r'(?is)<p[^>]*class="[^"]*(?:int-recipient|int-title|intAuthor|'
51
+ r'intDateTresc|intDate)[^"]*"[^>]*>.*?</p>'
52
+ )
53
+ _AUTHOR_P = re.compile(r'(?is)<p[^>]*class="[^"]*intAuthor[^"]*"[^>]*>(.*?)</p>')
54
+ _AUTHOR_LABEL = re.compile(r"^(Zgłaszający|Odpowiadający):\s*", re.I)
55
+ _ATTACH_LINE = re.compile(
56
+ r"(?i)^(?:Treść odpowiedzi znajduje się w załączniku\.?|Załączniki|"
57
+ r"\(podpisane elektronicznie\).*|.*\.pdf)\s*$"
58
+ )
59
+
60
+
61
+ def should_fetch_reply(reply: dict | None) -> bool:
62
+ if not reply:
63
+ return False
64
+ key = reply.get("key")
65
+ if not key:
66
+ return False
67
+ return not reply.get("onlyAttachment")
68
+
69
+
70
+ def body_url(term, collection, num, reply=None) -> str:
71
+ base = f"{API}/sejm/term{term}/{collection}/{num}"
72
+ if reply:
73
+ return f"{base}/reply/{reply['key']}/body"
74
+ return f"{base}/body"
75
+
76
+
77
+ def _author_from_html(html: str) -> str:
78
+ m = _AUTHOR_P.search(html)
79
+ if not m:
80
+ return ""
81
+ return _AUTHOR_LABEL.sub("", html_to_text(m.group(1))).strip()
82
+
83
+
84
+ def extract_body(html: str) -> str:
85
+ html = _HEAD.sub("", html)
86
+ html = _H1.sub("", html)
87
+ html = _META_P.sub("", html)
88
+ text = html_to_text(html)
89
+ lines = [ln for ln in text.splitlines() if not _ATTACH_LINE.match(ln.strip())]
90
+ return "\n".join(lines).strip()
91
+
92
+
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]
100
+ term = item.get("term")
101
+ num = item.get("num")
102
+ author = _author_from_html(html)
103
+ if not author and reply:
104
+ author = (reply.get("from") or "").strip()
105
+ date = (reply or {}).get("receiptDate") or item.get("receiptDate") or ""
106
+ meta = {
107
+ "url": body_url(term, collection, num, reply),
108
+ "term": term,
109
+ "num": num,
110
+ "kind": kind,
111
+ "title": item.get("title") or "",
112
+ "date": date,
113
+ "author": author,
114
+ }
115
+ if reply:
116
+ meta["reply_key"] = reply.get("key") or ""
117
+ return {"text": text, "meta": meta}
118
+
119
+
120
+ def _get(url, tries=4):
121
+ last = None
122
+ for i in range(tries):
123
+ try:
124
+ with urlopen(Request(url, headers=UA), timeout=45) as r:
125
+ return r.read(), dict(r.headers)
126
+ except (HTTPError, URLError, TimeoutError) as e:
127
+ last = e
128
+ if isinstance(e, HTTPError) and e.code in (404, 500):
129
+ break
130
+ time.sleep(1.5 * (i + 1))
131
+ return None, {"error": repr(last)}
132
+
133
+
134
+ def _get_json(url):
135
+ raw, hdrs = _get(url)
136
+ if raw is None:
137
+ return None, hdrs
138
+ return json.loads(raw), hdrs
139
+
140
+
141
+ def iter_listing(term, collection, page_size):
142
+ offset = 0
143
+ while True:
144
+ url = f"{API}/sejm/term{term}/{collection}?limit={page_size}&offset={offset}"
145
+ items, hdrs = _get_json(url)
146
+ if items is None:
147
+ raise RuntimeError(f"list failed after retries: {url} ({hdrs.get('error')})")
148
+ if not items:
149
+ return
150
+ yield from items
151
+ offset += len(items)
152
+ if len(items) < page_size:
153
+ return
154
+
155
+
156
+ def main(argv=None) -> int:
157
+ ap = argparse.ArgumentParser()
158
+ ap.add_argument("--out", default="~/speakleash")
159
+ ap.add_argument("--terms", default="7,8,9,10",
160
+ help="comma-separated Sejm terms (default 7-10)")
161
+ ap.add_argument("--collections", default="interpellations,writtenQuestions")
162
+ ap.add_argument("--page-size", type=int, default=50)
163
+ ap.add_argument("--max-docs", type=int, default=0, help="stop after N kept rows")
164
+ args = ap.parse_args(argv)
165
+
166
+ terms = [int(t) for t in args.terms.split(",") if t.strip()]
167
+ collections = [c.strip() for c in args.collections.split(",") if c.strip()]
168
+ out_dir = Path(args.out).expanduser()
169
+ out_dir.mkdir(parents=True, exist_ok=True)
170
+ jsonl = out_dir / f"{KEY}.jsonl"
171
+
172
+ done = set()
173
+ if jsonl.exists():
174
+ for ln in jsonl.open(encoding="utf-8"):
175
+ try:
176
+ done.add(json.loads(ln)["meta"]["url"])
177
+ except Exception:
178
+ pass
179
+ print(f"resume: {len(done):,} already fetched")
180
+
181
+ kept = seen = skipped = 0
182
+ t0 = time.time()
183
+ with jsonl.open("a", encoding="utf-8") as fo:
184
+ for term in terms:
185
+ for collection in collections:
186
+ print(f"term {term} {collection}", flush=True)
187
+ for item in iter_listing(term, collection, args.page_size):
188
+ jobs = [(False, None)]
189
+ for reply in item.get("replies") or []:
190
+ if should_fetch_reply(reply):
191
+ jobs.append((True, reply))
192
+ for is_reply, reply in jobs:
193
+ url = body_url(term, collection, item.get("num"), reply)
194
+ seen += 1
195
+ if url in done:
196
+ continue
197
+ raw, hdrs = _get(url)
198
+ if raw is None:
199
+ skipped += 1
200
+ print(f" WARN skip {url} {hdrs.get('error')}",
201
+ file=sys.stderr, flush=True)
202
+ continue
203
+ kind = _KIND[(collection, is_reply)]
204
+ rec = normalize_document(
205
+ kind, item, raw.decode("utf-8", "replace"), reply
206
+ )
207
+ done.add(url)
208
+ if rec:
209
+ fo.write(json.dumps(rec, ensure_ascii=False) + "\n")
210
+ kept += 1
211
+ else:
212
+ skipped += 1
213
+ if seen % 200 == 0:
214
+ print(f" seen {seen:,} kept {kept:,} skip {skipped:,} "
215
+ f"{seen / max(time.time() - t0, 1):.1f}/s", flush=True)
216
+ if args.max_docs and kept >= args.max_docs:
217
+ break
218
+ if args.max_docs and kept >= args.max_docs:
219
+ break
220
+ if args.max_docs and kept >= args.max_docs:
221
+ break
222
+ if args.max_docs and kept >= args.max_docs:
223
+ break
224
+
225
+ print(f"fetched {kept:,} new docs ({skipped:,} skipped); compressing...", flush=True)
226
+ subprocess.run(
227
+ ["zstd", "-19", "-f", "--rm", str(jsonl), "-o", str(out_dir / f"{KEY}.jsonl.zst")],
228
+ check=True,
229
+ )
230
+ print(f"wrote {out_dir / (KEY + '.jsonl.zst')} in {round(time.time() - t0)}s")
231
+ return 0
232
+
233
+
234
+ if __name__ == "__main__":
235
+ raise SystemExit(main())
src/html_text.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared HTML → text for fetchers. Block tags become newlines; inline tags drop."""
2
+ from __future__ import annotations
3
+ import re
4
+ from html import unescape
5
+
6
+ _SCRIPT = re.compile(r"(?is)<(script|style)[^>]*>.*?</\1>")
7
+ _BLOCK_END = re.compile(
8
+ r"(?i)</(p|div|h[1-6]|li|tr|table|ul|ol|blockquote)\s*>|<br\s*/?>"
9
+ )
10
+ _TAG = re.compile(r"<[^>]+>")
11
+
12
+
13
+ def html_to_text(html: str) -> str:
14
+ if not html:
15
+ return ""
16
+ html = _SCRIPT.sub("", html)
17
+ html = _BLOCK_END.sub("\n", html)
18
+ html = _TAG.sub("", html)
19
+ text = unescape(html).replace("\r\n", "\n").replace("\r", "\n")
20
+ text = re.sub(r"[ \t]+", " ", text)
21
+ text = re.sub(r" *\n *", "\n", text)
22
+ text = re.sub(r"\n{3,}", "\n\n", text)
23
+ return text.strip()
src/scrub_entities.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Regex PII scrub for Polish web/official text.
2
+
3
+ Replaces emails, phones, PESEL/NIP/REGON 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]. Checksums gate the national IDs so statute and case numbers stay.
7
+
8
+ Call after HTML-to-text, before the parquet is written.
9
+ """
10
+ from __future__ import annotations
11
+ import datetime as dt
12
+ import re
13
+
14
+ PHONE_TAG = "[Telefon]"
15
+ PII_TAG = "[PII]"
16
+ COUNTS = ("email", "phone", "pesel", "nip", "regon", "account")
17
+
18
+ # Mobile + geographic area codes (2-digit national prefix after trunk 0 / +48).
19
+ _PL_PREFIX = {
20
+ "12", "13", "14", "15", "16", "17", "18", "22", "23", "24", "25", "29",
21
+ "32", "33", "34", "39", "41", "42", "43", "44", "45", "46", "48",
22
+ "50", "51", "52", "53", "54", "55", "56", "57", "58", "59",
23
+ "60", "61", "62", "63", "65", "66", "67", "68", "69",
24
+ "70", "71", "72", "73", "74", "75", "76", "77", "78", "79",
25
+ "80", "81", "82", "83", "84", "85", "86", "87", "88", "89",
26
+ "91", "94", "95",
27
+ }
28
+
29
+ _EMAIL_RE = re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b")
30
+ # Optional PL, then 26 digits with short space/tab/hyphen gaps (invoice style).
31
+ _ACCOUNT_RE = re.compile(r"\b(?:PL[ \t-]*)?(?:\d[ \t-]*){25}\d\b", re.I)
32
+ _REGON14_RE = re.compile(r"\b\d{14}\b")
33
+ _PESEL_RE = re.compile(r"\b\d{11}\b")
34
+ _NIP_DASH_RE = re.compile(r"\b\d{3}[-\s]\d{3}[-\s]\d{2}[-\s]\d{2}\b")
35
+ _NIP_RE = re.compile(r"\b\d{10}\b")
36
+ _REGON9_RE = re.compile(r"\b\d{9}\b")
37
+ # Separators are short and local: one newline *or* a few punct/spaces.
38
+ # Letters and blank lines break the match so body text is not swallowed.
39
+ _SEP = r"(?:[ \t.\-()\u2013\u2014]{0,3}|\n)"
40
+ _PHONE_RE = re.compile(
41
+ r"(?<!\d)(?:(?:\+|00)[ \t]*48" + _SEP + r")?"
42
+ r"(?:\(0?\d{2,3}\)" + _SEP + r")?"
43
+ r"\d(?:" + _SEP + r"\d){6,14}"
44
+ )
45
+
46
+
47
+ def _digits(s: str) -> str:
48
+ return re.sub(r"\D", "", s)
49
+
50
+
51
+ def _pesel_ok(d: str) -> bool:
52
+ if len(d) != 11 or not d.isdigit():
53
+ return False
54
+ weights = (1, 3, 7, 9, 1, 3, 7, 9, 1, 3)
55
+ check = sum(w * int(x) for w, x in zip(weights, d[:-1]))
56
+ if str((10 - check % 10) % 10) != d[-1]:
57
+ return False
58
+ yy, mm, dd = int(d[0:2]), int(d[2:4]), int(d[4:6])
59
+ century = {0: 1900, 1: 2000, 2: 2100, 3: 2200, 4: 1800}.get(mm // 20)
60
+ if century is None:
61
+ return False
62
+ try:
63
+ dt.date(century + yy, mm % 20, dd)
64
+ except ValueError:
65
+ return False
66
+ return True
67
+
68
+
69
+ def _nip_ok(d: str) -> bool:
70
+ if len(d) != 10 or not d.isdigit():
71
+ return False
72
+ weights = (6, 5, 7, 2, 3, 4, 5, 6, 7)
73
+ rem = sum(w * int(x) for w, x in zip(weights, d[:-1])) % 11
74
+ return rem != 10 and rem == int(d[-1])
75
+
76
+
77
+ def _regon_ok(d: str) -> bool:
78
+ if not d.isdigit() or len(d) not in (9, 14):
79
+ return False
80
+ weights = ((8, 9, 2, 3, 4, 5, 6, 7) if len(d) == 9
81
+ else (2, 4, 8, 5, 0, 9, 7, 3, 6, 1, 2, 4, 8))
82
+ rem = sum(w * int(x) for w, x in zip(weights, d[:-1])) % 11
83
+ if rem == 10:
84
+ rem = 0
85
+ return rem == int(d[-1])
86
+
87
+
88
+ def _iban_ok(raw: str) -> bool:
89
+ compact = re.sub(r"[\s-]+", "", raw).upper()
90
+ if compact.isdigit() and len(compact) == 26:
91
+ compact = "PL" + compact
92
+ if not re.fullmatch(r"PL\d{26}", compact):
93
+ return False
94
+ rearranged = compact[4:] + compact[:4]
95
+ nums = "".join(str(ord(c) - 55) if c.isalpha() else c for c in rearranged)
96
+ return int(nums) % 97 == 1
97
+
98
+
99
+ def _pl_national_ok(d: str) -> bool:
100
+ return len(d) == 9 and d.isdigit() and d[:2] in _PL_PREFIX
101
+
102
+
103
+ def _phone_ok(raw: str) -> bool:
104
+ s = raw.strip()
105
+ if re.fullmatch(r"\d{4}[-./]\d{2}[-./]\d{2}", s):
106
+ return False
107
+ if re.fullmatch(r"\d{2}-\d{3}", s): # postal code
108
+ return False
109
+ # Ministry / court file numbers: BPRM.4820.2.3.2020, LUB-OMK.601.1.2024.3
110
+ if s.count(".") >= 3 or (s.count(".") >= 1 and re.search(r"20\d{2}", s)):
111
+ return False
112
+ if re.search(r"\d{1,2}[-./]\d{1,2}[-./](?:19|20)\d{2}", s):
113
+ return False
114
+ d = _digits(raw)
115
+ if d.startswith("00"):
116
+ d = d[2:]
117
+ if d.startswith("48") and len(d) >= 11:
118
+ rest = d[2:]
119
+ if rest.startswith("0"):
120
+ rest = rest[1:]
121
+ return _pl_national_ok(rest)
122
+ if d.startswith("0") and len(d) == 11 and d[:2] in {"01", "02", "07"}:
123
+ return True
124
+ if d.startswith("0") and len(d) >= 10:
125
+ return _pl_national_ok(d.lstrip("0"))
126
+ return _pl_national_ok(d)
127
+
128
+
129
+ def _replace_checked(text: str, pattern: re.Pattern, tag: str, ok) -> tuple[str, int]:
130
+ n = 0
131
+
132
+ def _sub(m):
133
+ nonlocal n
134
+ if not ok(m.group(0)):
135
+ return m.group(0)
136
+ n += 1
137
+ return tag
138
+
139
+ return pattern.sub(_sub, text), n
140
+
141
+
142
+ def _replace_phones(text: str) -> tuple[str, int]:
143
+ n = 0
144
+ out = []
145
+ pos = 0
146
+ while True:
147
+ m = _PHONE_RE.search(text, pos)
148
+ if not m:
149
+ out.append(text[pos:])
150
+ break
151
+ if _phone_ok(m.group(0)):
152
+ out.append(text[pos:m.start()])
153
+ out.append(PHONE_TAG)
154
+ n += 1
155
+ pos = m.end()
156
+ else:
157
+ out.append(text[pos:m.start() + 1])
158
+ pos = m.start() + 1
159
+ return "".join(out), n
160
+
161
+
162
+ def scrub_pii(text: str) -> tuple[str, dict[str, int]]:
163
+ """Return (scrubbed_text, per-kind replacement counts). Idempotent."""
164
+ counts = {k: 0 for k in COUNTS}
165
+ if not text:
166
+ return text, counts
167
+
168
+ # Longest / most specific first so a 26-digit account is not sliced
169
+ # into REGON / PESEL / NIP / phone. Checksums live in the replace callback.
170
+ text, counts["account"] = _replace_checked(text, _ACCOUNT_RE, PII_TAG, _iban_ok)
171
+ text, n14 = _replace_checked(text, _REGON14_RE, PII_TAG, _regon_ok)
172
+ text, n9 = _replace_checked(text, _REGON9_RE, PII_TAG, _regon_ok)
173
+ counts["regon"] = n14 + n9
174
+ text, counts["pesel"] = _replace_checked(text, _PESEL_RE, PII_TAG, _pesel_ok)
175
+ text, n_dash = _replace_checked(text, _NIP_DASH_RE, PII_TAG, lambda s: _nip_ok(_digits(s)))
176
+ text, n_plain = _replace_checked(text, _NIP_RE, PII_TAG, _nip_ok)
177
+ counts["nip"] = n_dash + n_plain
178
+ text, counts["email"] = _replace_checked(text, _EMAIL_RE, PII_TAG, lambda _: True)
179
+ text, counts["phone"] = _replace_phones(text)
180
+ return text, counts
src/sources.py CHANGED
@@ -99,6 +99,25 @@ SOURCES = {
99
  "created": "2023-01-01, 2026-07-03",
100
  "is_ocr": False,
101
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  "parlamint_pl": {
103
  "file_key": "parlamint_pl",
104
  "pretty": "ParlaMint-PL (parliamentary debates, 2015-2022)",
@@ -337,7 +356,9 @@ SOURCES = {
337
  "min 400 chars / 80 words, boilerplate/adult/legalish drop, length cap "
338
  "120k chars, CJK-mojibake drop, wikipedia/wikisource/wikimedia + file-host "
339
  "domains excluded, per-domain cap. Phone->[Telefon] / email+national-ID->[PII] "
340
- "PII-scrub (v12b, independent dual-lens verify). Token counts via tiktoken cl100k.",
 
 
341
  "domain": "web",
342
  "created": "2012-01-01, 2024-12-31",
343
  "is_ocr": False,
 
99
  "created": "2023-01-01, 2026-07-03",
100
  "is_ocr": False,
101
  },
102
+ "sejm_interpellations": {
103
+ "file_key": "sejm_interpellations",
104
+ "pretty": "Sejm interpellations and written questions (terms 7–10)",
105
+ "license": "public-domain (official documents)",
106
+ "license_spdx": "LicenseRef-Polish-Official-Documents",
107
+ "traceable": "Official parliamentary materials excluded from copyright "
108
+ "under Polish Copyright Act art. 4(2); reusable under "
109
+ "the Polish Open Data Act arts. 2(12), 5, 14 and 17.",
110
+ "upstream": "https://api.sejm.gov.pl/",
111
+ "provenance": "Fetched from api.sejm.gov.pl HTML body endpoints by "
112
+ "src/fetch_sejm_interpellations.py (interpellations + "
113
+ "writtenQuestions, terms 7–10). Header chrome stripped into "
114
+ "meta; attachment-only and keyless replies skipped; "
115
+ "src/scrub_pii.py applied before jsonl write.",
116
+ "domain": "political/written",
117
+ "created": "2011-11-08, 2026-09-04",
118
+ "is_ocr": False,
119
+ "custom_datasheet": True,
120
+ },
121
  "parlamint_pl": {
122
  "file_key": "parlamint_pl",
123
  "pretty": "ParlaMint-PL (parliamentary debates, 2015-2022)",
 
356
  "min 400 chars / 80 words, boilerplate/adult/legalish drop, length cap "
357
  "120k chars, CJK-mojibake drop, wikipedia/wikisource/wikimedia + file-host "
358
  "domains excluded, per-domain cap. Phone->[Telefon] / email+national-ID->[PII] "
359
+ "via src/scrub_pii.py (in-tree; supersedes the out-of-repo v12b pass); "
360
+ "PERSON mentions → [PII] via src/scrub_entities.py on this web shard only. "
361
+ "Token counts via tiktoken cl100k.",
362
  "domain": "web",
363
  "created": "2012-01-01, 2024-12-31",
364
  "is_ocr": False,
src/test_scrub_entities.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Checksum-valid fixtures (not live identifiers of private people).
11
+ PESEL = "44051401458"
12
+ NIP = "1234563218"
13
+ REGON9 = "123456785"
14
+ REGON14 = "12345678512347"
15
+ IBAN = "PL61109010140000071219812874"
16
+
17
+
18
+ class ScrubPiiTest(unittest.TestCase):
19
+ def _scrub(self, text):
20
+ return scrub_pii(text)
21
+
22
+ def test_email_becomes_pii(self):
23
+ out, counts = self._scrub("Pisz na jan.kowalski@example.com dziś.")
24
+ self.assertIn("[PII]", out)
25
+ self.assertNotIn("jan.kowalski@example.com", out)
26
+ self.assertEqual(counts["email"], 1)
27
+ self.assertIn("Pisz na", out)
28
+ self.assertIn("dziś.", out)
29
+
30
+ def test_mobile_and_grouped_phone_become_telefon(self):
31
+ out, counts = self._scrub("Zadzwoń 501 234 567 albo 501-234-567.")
32
+ self.assertEqual(out.count("[Telefon]"), 2)
33
+ self.assertNotIn("501", out)
34
+ self.assertEqual(counts["phone"], 2)
35
+
36
+ def test_leading_zero_landline(self):
37
+ out, counts = self._scrub("Siedziba: 022 123 45 67 w Warszawie.")
38
+ self.assertIn("[Telefon]", out)
39
+ self.assertNotIn("022", out)
40
+ self.assertEqual(counts["phone"], 1)
41
+
42
+ def test_plus48_paren(self):
43
+ out, counts = self._scrub("Kontakt: +48 (22) 123-45-67.")
44
+ self.assertIn("[Telefon]", out)
45
+ self.assertNotIn("+48", out)
46
+ self.assertNotIn("123-45-67", out)
47
+ self.assertEqual(counts["phone"], 1)
48
+
49
+ def test_dzwon_label_family(self):
50
+ out, counts = self._scrub("dzwoń: 601234567 lub tel. 602-234-567")
51
+ self.assertEqual(counts["phone"], 2)
52
+ self.assertNotIn("601234567", out)
53
+ self.assertNotIn("602-234-567", out)
54
+
55
+ def test_newline_over_span(self):
56
+ out, counts = self._scrub("tel.\n+48\n501\n234\n567\nproszę dzwonić")
57
+ self.assertIn("[Telefon]", out)
58
+ self.assertEqual(counts["phone"], 1)
59
+ self.assertNotIn("501", out)
60
+
61
+ def test_foreign_uk_bare(self):
62
+ out, counts = self._scrub("London office 020 7946 0958 weekday mornings.")
63
+ self.assertIn("[Telefon]", out)
64
+ self.assertNotIn("7946", out)
65
+ self.assertEqual(counts["phone"], 1)
66
+
67
+ def test_pesel_nip_regon_iban(self):
68
+ text = (
69
+ f"PESEL {PESEL}, NIP {NIP}, REGON {REGON9} / {REGON14}, "
70
+ f"konto {IBAN}."
71
+ )
72
+ out, counts = self._scrub(text)
73
+ self.assertNotIn(PESEL, out)
74
+ self.assertNotIn(NIP, out)
75
+ self.assertNotIn(REGON14, out)
76
+ self.assertNotIn(IBAN, out)
77
+ self.assertEqual(out.count("[PII]"), 5)
78
+ self.assertEqual(counts["pesel"], 1)
79
+ self.assertEqual(counts["nip"], 1)
80
+ self.assertEqual(counts["regon"], 2)
81
+ self.assertEqual(counts["account"], 1)
82
+
83
+ def test_nip_with_dashes(self):
84
+ out, counts = self._scrub("NIP 123-456-32-18 na fakturze.")
85
+ self.assertIn("[PII]", out)
86
+ self.assertNotIn("123-456-32-18", out)
87
+ self.assertEqual(counts["nip"], 1)
88
+
89
+ def test_invalid_eleven_digits_are_not_pesel(self):
90
+ # Same length as PESEL, fails checksum — statute / case-like numbers stay.
91
+ bogus = "44051401457"
92
+ out, counts = self._scrub(f"Sygnatura {bogus} pozostaje.")
93
+ self.assertIn(bogus, out)
94
+ self.assertEqual(counts["pesel"], 0)
95
+
96
+ def test_dates_and_case_numbers_survive(self):
97
+ text = "Wyrok z 2018-03-22, sygn. II K 336/17, art. 4 pkt 2."
98
+ out, counts = self._scrub(text)
99
+ self.assertEqual(out, text)
100
+ self.assertEqual(sum(counts.values()), 0)
101
+
102
+ def test_official_names_stay(self):
103
+ text = "Poseł Jan Kowalski złożył interpelację w Sejmie RP."
104
+ out, counts = self._scrub(text)
105
+ self.assertEqual(out, text)
106
+ self.assertEqual(sum(counts.values()), 0)
107
+
108
+ def test_idempotent(self):
109
+ once, _ = self._scrub(f"mail a@b.pl tel +48 501 234 567 PESEL {PESEL}")
110
+ twice, counts = self._scrub(once)
111
+ self.assertEqual(once, twice)
112
+ self.assertEqual(sum(counts.values()), 0)
113
+
114
+ def test_postal_code_and_krs_survive(self):
115
+ text = "Kod 02-123 Warszawa, KRS 0000123456, kwota 500,00 zł."
116
+ out, counts = self._scrub(text)
117
+ self.assertEqual(out, text)
118
+ self.assertEqual(counts["phone"], 0)
119
+ self.assertEqual(sum(counts.values()), 0)
120
+
121
+ def test_kw_and_postal_range_survive(self):
122
+ text = "KW KR1P/00012345/6, kod 00-950, okres 2020-2024."
123
+ out, counts = self._scrub(text)
124
+ self.assertEqual(out, text)
125
+ self.assertEqual(counts["phone"], 0)
126
+
127
+ def test_newline_phone_does_not_consume_unrelated_text(self):
128
+ text = "tel.\nW sprawie art. 5\nproszę dzwonić 501 234 567."
129
+ out, counts = self._scrub(text)
130
+ self.assertIn("W sprawie art. 5", out)
131
+ self.assertIn("[Telefon]", out)
132
+ self.assertEqual(counts["phone"], 1)
133
+ self.assertNotIn("501", out)
134
+
135
+ def test_iban_without_pl_prefix(self):
136
+ bare_iban = "61109010140000071219812874"
137
+ out, counts = self._scrub(f"Rachunek nr {bare_iban}")
138
+ self.assertNotIn(bare_iban, out)
139
+ self.assertEqual(counts["account"], 1)
140
+ self.assertEqual(counts["phone"], 0)
141
+
142
+ def test_spaced_iban_and_nip_prefixes(self):
143
+ spaced = "61 1090 1014 0000 0712 1981 2874"
144
+ text = f"nr rachunku: {spaced}; NIP:{NIP}; NIP-{NIP}."
145
+ out, counts = self._scrub(text)
146
+ self.assertNotIn("1090", out)
147
+ self.assertNotIn(NIP, out)
148
+ self.assertEqual(counts["account"], 1)
149
+ self.assertEqual(counts["nip"], 2)
150
+ self.assertEqual(counts["phone"], 0)
151
+
152
+ def test_execution_order_precedence(self):
153
+ text = f"Przelew na {IBAN}."
154
+ out, counts = self._scrub(text)
155
+ self.assertNotIn("611090", out)
156
+ self.assertEqual(counts["account"], 1)
157
+ self.assertEqual(counts["pesel"], 0)
158
+ self.assertEqual(counts["phone"], 0)
159
+ self.assertEqual(counts["regon"], 0)
160
+
161
+ def test_complex_email_formats(self):
162
+ addr = "jan.k+alert@pwr.edu.pl"
163
+ out, counts = self._scrub(f"Kontakt: {addr}")
164
+ self.assertNotIn(addr, out)
165
+ self.assertEqual(counts["email"], 1)
166
+ nested = "jan.kowalski+test@subdomain.example.pwr.edu.pl"
167
+ out, counts = self._scrub(nested)
168
+ self.assertNotIn(nested, out)
169
+ self.assertEqual(counts["email"], 1)
170
+
171
+ def test_pii_inside_brackets_or_quotes(self):
172
+ out, counts = self._scrub(f'("email: jan@ex.com", PESEL: "{PESEL}")')
173
+ self.assertNotIn("jan@ex.com", out)
174
+ self.assertNotIn(PESEL, out)
175
+ self.assertEqual(counts["email"], 1)
176
+ self.assertEqual(counts["pesel"], 1)
177
+
178
+ def test_iban_with_mixed_dashes_and_spaces(self):
179
+ # Same MOD-97 number as IBAN, invoice-style PL + space + hyphen groups.
180
+ mixed_iban = "PL 61-1090-1014-0000-0712-1981-2874"
181
+ out, counts = self._scrub(f"Rachunek: {mixed_iban}")
182
+ self.assertNotIn("1090", out)
183
+ self.assertNotIn("0712", out)
184
+ self.assertEqual(counts["account"], 1)
185
+ self.assertEqual(counts["phone"], 0)
186
+
187
+ def test_nip_and_regon_with_colons_and_newlines(self):
188
+ text = f"NIP:\n{NIP}\nREGON:\n{REGON9}"
189
+ out, counts = self._scrub(text)
190
+ self.assertNotIn(NIP, out)
191
+ self.assertNotIn(REGON9, out)
192
+ self.assertEqual(counts["nip"], 1)
193
+ self.assertEqual(counts["regon"], 1)
194
+ self.assertIn("NIP:", out)
195
+ self.assertIn("REGON:", out)
196
+
197
+ def test_postal_code_does_not_trigger_phone(self):
198
+ text = "Adres: ul. Wiejska 4, 00-902 Warszawa."
199
+ out, counts = self._scrub(text)
200
+ self.assertEqual(out, text)
201
+ self.assertEqual(counts["phone"], 0)
202
+
203
+ def test_newline_phone_is_bounded(self):
204
+ text = "tel.\n\n\nW sprawie umowy proszę dzwonić pod 501 234 567."
205
+ out, counts = self._scrub(text)
206
+ self.assertIn("W sprawie umowy", out)
207
+ self.assertEqual(counts["phone"], 1)
208
+ self.assertNotIn("501", out)
209
+
210
+ def test_datetime_stamps_are_not_phones(self):
211
+ # HPLT leftover: DD-MM-YYYY HH:MM looks like a leading-0 landline.
212
+ text = "wpis - 08-03-2020 13:27 | 08-07-2014 16:15:00 na liście."
213
+ out, counts = self._scrub(text)
214
+ self.assertEqual(out, text)
215
+ self.assertEqual(counts["phone"], 0)
216
+
217
+ def test_en_dash_grouped_phone(self):
218
+ out, counts = self._scrub("sekretariat tel. 65 544–47-32 od poniedziałku")
219
+ self.assertIn("[Telefon]", out)
220
+ self.assertNotIn("544", out)
221
+ self.assertEqual(counts["phone"], 1)
222
+
223
+ def test_ministry_file_numbers_are_not_phones(self):
224
+ # Real Sejm sample FPs: dotted znak / attachment stems look like landlines.
225
+ text = (
226
+ "decyzja (znak: BPRM.4820.2.3.2020). "
227
+ "pismem znak: DF.III.8200.12.2020.PP. "
228
+ "Zalacznik do pisma LUB-OMK.601.1.2024.3.pdf"
229
+ )
230
+ out, counts = self._scrub(text)
231
+ self.assertEqual(out, text)
232
+ self.assertEqual(counts["phone"], 0)
233
+
234
+ def test_iban_takes_precedence_over_substring_matches(self):
235
+ text = f"Numer konta do wpłaty: {IBAN}"
236
+ out, counts = self._scrub(text)
237
+ self.assertEqual(counts["account"], 1)
238
+ self.assertEqual(counts["pesel"], 0)
239
+ self.assertEqual(counts["phone"], 0)
240
+ self.assertEqual(counts["regon"], 0)
241
+ self.assertEqual(counts["nip"], 0)
242
+
243
+
244
+ if __name__ == "__main__":
245
+ unittest.main()
src/test_sejm_interpellations_contract.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """TDD contract for Sejm interpellations / written-questions ingestion."""
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 fetch_sejm_interpellations import (
9
+ MIN_CHARS,
10
+ normalize_document,
11
+ should_fetch_reply,
12
+ )
13
+
14
+ BODY = (
15
+ "Szanowny Panie Ministrze! " + ("Ogrody działkowe wymagają ochrony prawnej. " * 12)
16
+ )
17
+
18
+ Q_HTML = f"""<!DOCTYPE html>
19
+ <html lang="pl"><head><title>Interpelacja w sprawie ogrodów</title></head>
20
+ <body>
21
+ <h1>Interpelacja nr 1</h1>
22
+ <p class="int-recipient">do ministra rozwoju i technologii</p>
23
+ <p class="int-title">w sprawie sytuacji w rodzinnych ogrodach działkowych</p>
24
+ <p class="intAuthor">Zgłaszający: Katarzyna Osos</p>
25
+ <p class="intDateTresc">Data wpływu: 15-11-2023</p>
26
+ <p>{BODY}</p>
27
+ <p>Podstawa: decyzja (znak: BPRM.4820.2.3.2020).</p>
28
+ </body></html>
29
+ """
30
+
31
+ R_HTML = f"""<!DOCTYPE html>
32
+ <html lang="pl"><head><title>Odpowiedź na interpelację w sprawie ogrodów</title></head>
33
+ <body>
34
+ <h1>Odpowiedź na interpelację nr 8</h1>
35
+ <p class="int-title">w sprawie tzw. specustawy</p>
36
+ <p class="intAuthor">Odpowiadający: minister rodziny Agnieszka Dziemianowicz-Bąk</p>
37
+ <p class="intDate">Warszawa, 22-02-2024</p>
38
+ <p>Szanowny Panie Marszałku, {"odpowiadając informuję jak poniżej. " * 15}</p>
39
+ </body></html>
40
+ """
41
+
42
+ STUB_HTML = """<!DOCTYPE html>
43
+ <html><head><title>Odpowiedź</title></head>
44
+ <body>
45
+ <h1>Odpowiedź na interpelację nr 806</h1>
46
+ <p class="int-title">w sprawie warunków sanitarnych</p>
47
+ <p class="intAuthor">Odpowiadający: sekretarz stanu Krzysztof Kukucki</p>
48
+ <p class="intDate">Warszawa, 20-02-2024</p>
49
+ <p>Treść odpowiedzi znajduje się w załączniku.</p>
50
+ <p>Załączniki</p>
51
+ <p>LUB-OMK.601.1.2024.3.pdf</p>
52
+ </body></html>
53
+ """
54
+
55
+ ITEM = {
56
+ "num": 1,
57
+ "term": 10,
58
+ "title": "Interpelacja w sprawie sytuacji w rodzinnych ogrodach działkowych",
59
+ "receiptDate": "2023-11-15",
60
+ "from": ["277"],
61
+ "to": ["minister rozwoju i technologii"],
62
+ }
63
+
64
+
65
+ class SejmInterpellationsContractTest(unittest.TestCase):
66
+ def test_should_fetch_reply_requires_key_and_html(self):
67
+ self.assertTrue(should_fetch_reply({"key": "D2QJNB", "onlyAttachment": False}))
68
+ self.assertFalse(should_fetch_reply({"key": "X", "onlyAttachment": True}))
69
+ self.assertFalse(should_fetch_reply({"onlyAttachment": False}))
70
+ self.assertFalse(should_fetch_reply({"key": None, "onlyAttachment": False}))
71
+ self.assertFalse(should_fetch_reply({}))
72
+
73
+ def test_question_strips_header_keeps_body_and_file_number(self):
74
+ row = normalize_document("interpellation", ITEM, Q_HTML)
75
+ self.assertIsNotNone(row)
76
+ self.assertEqual(set(row), {"text", "meta"})
77
+ self.assertNotIn("<", row["text"])
78
+ self.assertNotIn("Interpelacja nr 1", row["text"])
79
+ self.assertNotIn("Zgłaszający:", row["text"])
80
+ self.assertNotIn("Data wpływu:", row["text"])
81
+ self.assertNotIn("do ministra rozwoju", row["text"])
82
+ self.assertIn("Ogrody działkowe", row["text"])
83
+ self.assertIn("BPRM.4820.2.3.2020", row["text"]) # not a phone
84
+ self.assertGreaterEqual(len(row["text"]), MIN_CHARS)
85
+ self.assertEqual(row["meta"]["num"], 1)
86
+ self.assertEqual(row["meta"]["term"], 10)
87
+ self.assertEqual(row["meta"]["kind"], "interpellation")
88
+ self.assertEqual(row["meta"]["author"], "Katarzyna Osos")
89
+ self.assertTrue(row["meta"]["url"].endswith("/interpellations/1/body"))
90
+
91
+ def test_reply_strips_header_and_records_key(self):
92
+ reply = {"key": "D2QJNB", "from": "Minister Agnieszka Dziemianowicz-Bąk",
93
+ "receiptDate": "2024-02-22", "onlyAttachment": False}
94
+ item = {**ITEM, "num": 8}
95
+ row = normalize_document("interpellation_reply", item, R_HTML, reply=reply)
96
+ self.assertIsNotNone(row)
97
+ self.assertNotIn("Odpowiedź na interpelację nr 8", row["text"])
98
+ self.assertNotIn("Odpowiadający:", row["text"])
99
+ self.assertNotIn("Warszawa, 22-02-2024", row["text"])
100
+ self.assertIn("Szanowny Panie Marszałku", row["text"])
101
+ self.assertEqual(row["meta"]["kind"], "interpellation_reply")
102
+ self.assertEqual(row["meta"]["reply_key"], "D2QJNB")
103
+ self.assertIn("Dziemianowicz", row["meta"]["author"])
104
+ self.assertTrue(row["meta"]["url"].endswith("/interpellations/8/reply/D2QJNB/body"))
105
+
106
+ def test_attachment_stub_is_rejected(self):
107
+ reply = {"key": "ABC", "from": "X", "receiptDate": "2024-02-20"}
108
+ self.assertIsNone(normalize_document(
109
+ "interpellation_reply", {**ITEM, "num": 806}, STUB_HTML, reply=reply
110
+ ))
111
+
112
+ def test_written_question_url(self):
113
+ item = {**ITEM, "title": "Zapytanie w sprawie świadczeń"}
114
+ row = normalize_document("written_question", item, Q_HTML)
115
+ self.assertTrue(row["meta"]["url"].endswith("/writtenQuestions/1/body"))
116
+ self.assertEqual(row["meta"]["kind"], "written_question")
117
+
118
+
119
+ if __name__ == "__main__":
120
+ unittest.main()