"""Regex PII scrub for Polish web/official text. Replaces emails, phones, PESEL/NIP/REGON and account numbers in place so sentence structure survives. Names of public officials are left untouched — that is intentional, not a gap. Phones map to [Telefon]; everything else to [PII]. Checksums gate the national IDs so statute and case numbers stay. Call after HTML-to-text, before the parquet is written. """ from __future__ import annotations import datetime as dt import re PHONE_TAG = "[Telefon]" PII_TAG = "[PII]" COUNTS = ("email", "phone", "pesel", "nip", "regon", "account") # Mobile + geographic area codes (2-digit national prefix after trunk 0 / +48). _PL_PREFIX = { "12", "13", "14", "15", "16", "17", "18", "22", "23", "24", "25", "29", "32", "33", "34", "39", "41", "42", "43", "44", "45", "46", "48", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "91", "94", "95", } _EMAIL_RE = re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b") # Optional PL, then 26 digits with short space/tab/hyphen gaps (invoice style). _ACCOUNT_RE = re.compile(r"\b(?:PL[ \t-]*)?(?:\d[ \t-]*){25}\d\b", re.I) _REGON14_RE = re.compile(r"\b\d{14}\b") _PESEL_RE = re.compile(r"\b\d{11}\b") _NIP_DASH_RE = re.compile(r"\b\d{3}[-\s]\d{3}[-\s]\d{2}[-\s]\d{2}\b") _NIP_RE = re.compile(r"\b\d{10}\b") _REGON9_RE = re.compile(r"\b\d{9}\b") # Separators are short and local: one newline *or* a few punct/spaces. # Letters and blank lines break the match so body text is not swallowed. _SEP = r"(?:[ \t.\-()\u2013\u2014]{0,3}|\n)" _PHONE_RE = re.compile( r"(? str: return re.sub(r"\D", "", s) def _pesel_ok(d: str) -> bool: if len(d) != 11 or not d.isdigit(): return False weights = (1, 3, 7, 9, 1, 3, 7, 9, 1, 3) check = sum(w * int(x) for w, x in zip(weights, d[:-1])) if str((10 - check % 10) % 10) != d[-1]: return False yy, mm, dd = int(d[0:2]), int(d[2:4]), int(d[4:6]) century = {0: 1900, 1: 2000, 2: 2100, 3: 2200, 4: 1800}.get(mm // 20) if century is None: return False try: dt.date(century + yy, mm % 20, dd) except ValueError: return False return True def _nip_ok(d: str) -> bool: if len(d) != 10 or not d.isdigit(): return False weights = (6, 5, 7, 2, 3, 4, 5, 6, 7) rem = sum(w * int(x) for w, x in zip(weights, d[:-1])) % 11 return rem != 10 and rem == int(d[-1]) def _regon_ok(d: str) -> bool: if not d.isdigit() or len(d) not in (9, 14): return False weights = ((8, 9, 2, 3, 4, 5, 6, 7) if len(d) == 9 else (2, 4, 8, 5, 0, 9, 7, 3, 6, 1, 2, 4, 8)) rem = sum(w * int(x) for w, x in zip(weights, d[:-1])) % 11 if rem == 10: rem = 0 return rem == int(d[-1]) def _iban_ok(raw: str) -> bool: compact = re.sub(r"[\s-]+", "", raw).upper() if compact.isdigit() and len(compact) == 26: compact = "PL" + compact if not re.fullmatch(r"PL\d{26}", compact): return False rearranged = compact[4:] + compact[:4] nums = "".join(str(ord(c) - 55) if c.isalpha() else c for c in rearranged) return int(nums) % 97 == 1 def _pl_national_ok(d: str) -> bool: return len(d) == 9 and d.isdigit() and d[:2] in _PL_PREFIX def _phone_ok(raw: str) -> bool: s = raw.strip() if re.fullmatch(r"\d{4}[-./]\d{2}[-./]\d{2}", s): return False if re.fullmatch(r"\d{2}-\d{3}", s): # postal code return False # Ministry / court file numbers: BPRM.4820.2.3.2020, LUB-OMK.601.1.2024.3 if s.count(".") >= 3 or (s.count(".") >= 1 and re.search(r"20\d{2}", s)): return False if re.search(r"\d{1,2}[-./]\d{1,2}[-./](?:19|20)\d{2}", s): return False d = _digits(raw) if d.startswith("00"): d = d[2:] if d.startswith("48") and len(d) >= 11: rest = d[2:] if rest.startswith("0"): rest = rest[1:] return _pl_national_ok(rest) if d.startswith("0") and len(d) == 11 and d[:2] in {"01", "02", "07"}: return True if d.startswith("0") and len(d) >= 10: return _pl_national_ok(d.lstrip("0")) return _pl_national_ok(d) def _replace_checked(text: str, pattern: re.Pattern, tag: str, ok) -> tuple[str, int]: n = 0 def _sub(m): nonlocal n if not ok(m.group(0)): return m.group(0) n += 1 return tag return pattern.sub(_sub, text), n def _replace_phones(text: str) -> tuple[str, int]: n = 0 out = [] pos = 0 while True: m = _PHONE_RE.search(text, pos) if not m: out.append(text[pos:]) break if _phone_ok(m.group(0)): out.append(text[pos:m.start()]) out.append(PHONE_TAG) n += 1 pos = m.end() else: out.append(text[pos:m.start() + 1]) pos = m.start() + 1 return "".join(out), n def scrub_pii(text: str) -> tuple[str, dict[str, int]]: """Return (scrubbed_text, per-kind replacement counts). Idempotent.""" counts = {k: 0 for k in COUNTS} if not text: return text, counts # Longest / most specific first so a 26-digit account is not sliced # into REGON / PESEL / NIP / phone. Checksums live in the replace callback. text, counts["account"] = _replace_checked(text, _ACCOUNT_RE, PII_TAG, _iban_ok) text, n14 = _replace_checked(text, _REGON14_RE, PII_TAG, _regon_ok) text, n9 = _replace_checked(text, _REGON9_RE, PII_TAG, _regon_ok) counts["regon"] = n14 + n9 text, counts["pesel"] = _replace_checked(text, _PESEL_RE, PII_TAG, _pesel_ok) text, n_dash = _replace_checked(text, _NIP_DASH_RE, PII_TAG, lambda s: _nip_ok(_digits(s))) text, n_plain = _replace_checked(text, _NIP_RE, PII_TAG, _nip_ok) counts["nip"] = n_dash + n_plain text, counts["email"] = _replace_checked(text, _EMAIL_RE, PII_TAG, lambda _: True) text, counts["phone"] = _replace_phones(text) return text, counts