"""Strip obvious personal details from text before it is stored (usage log, text_v1/). redact(text) -> (scrubbed, counts): each match is replaced by a placeholder such as [EMAIL] or [PHONE], and counts says how many of each were replaced. Regex only: names, addresses and anything written out in words are not caught, so the page never promises that everything personal is removed. Placeholders: [EMAIL] [URL] [SECRET] [IP] [ID] [CARD] [SSN] [PHONE] [HANDLE]. Order matters: e-mail before URL (a bare domain inside an address), keys and IDs before phones and cards (their digit runs would otherwise be split), phones before cards (a 13-digit +86 mobile can pass the Luhn check), long digit runs last. """ from __future__ import annotations import re from collections import Counter # Chinese text has no spaces, so "电话13812345678" must still match: digit and letter lookarounds # instead of \b (Python's \b treats a Chinese character as a word character). _ND = r"(? bool: total, alt = 0, False for ch in reversed(digits): d = int(ch) if alt: d = d * 2 - 9 if d > 4 else d * 2 total += d alt = not alt return total % 10 == 0 def _sub_url(m: re.Match) -> str: s = m.group(0) if "://" not in s and not s.lower().startswith("www."): host, _, path = s.partition("/") labels = host.split(".") if len(labels[-2]) < 2 and len(labels) == 2 or all(len(x) == 1 for x in labels[:-1]): return s # "a.m.in", "x.so": abbreviations, not hosts if labels[-1] in _WORDY_TLDS and not path: return s tail = "" while s and s[-1] in _TRAIL: # keep a closing bracket that belongs to the URL, e.g. ...wiki/Foo_(bar) or ?e=[EMAIL] if s[-1] == ")" and s.count("(") >= s.count(")") or s[-1] == "]" and s.count("[") >= s.count("]"): break tail = s[-1] + tail s = s[:-1] return "[URL]" + tail def _sub_ipv6(m: re.Match) -> str: s = m.group(0) groups = [g for g in s.split(":") if g] # real addresses: 8 groups, or "::" with at least 3 groups and a digit (not C++ "a::b" or a time "10:30:00") if (s.count(":") == 7 and len(groups) == 8) or ("::" in s and len(groups) >= 3 and re.search(r"\d", s) and any(re.search(r"[A-Fa-f]", g) or len(g) == 4 for g in groups)): return "[IP]" return s def _sub_card(m: re.Match) -> str: digits = re.sub(r"\D", "", m.group(0)) return "[CARD]" if 13 <= len(digits) <= 19 and _luhn(digits) else m.group(0) def _sub_intl(m: re.Match) -> str: n = len(re.sub(r"\D", "", m.group(0))) return "[PHONE]" if 8 <= n <= 15 else m.group(0) def _sub_context(m: re.Match) -> str: kw, sep, val = m.group(1), m.group(2), m.group(3) if val.startswith("[") or val.upper() in {"IS", "WAS", "NUMBER", "NO"}: return m.group(0) strong_sep = any(c in sep for c in "::#为是") if not strong_sep and not re.search(r"\d", val): return m.group(0) # "account is overdue", "order history": no digit, no colon -> not an ID if len(val) < 4 and not re.search(r"\d", val): return m.group(0) return kw + sep + "[ID]" # (placeholder, pattern, replacement): replacement is a string or a function returning the new text _RULES = [ ("EMAIL", EMAIL, "[EMAIL]"), ("EMAIL", EMAIL_LOOSE, "[EMAIL]"), ("URL", URL, _sub_url), ("SECRET", SECRET, "[SECRET]"), ("ID", UUID, "[ID]"), ("IP", IPV4, "[IP]"), ("IP", IPV6, _sub_ipv6), ("ID", CN_ID, "[ID]"), ("SSN", SSN, "[SSN]"), ("SSN", SSN_KW, lambda m: m.group(1) + "[SSN]"), ("PHONE", PHONE_CN_MOBILE, "[PHONE]"), ("PHONE", PHONE_INTL, _sub_intl), ("PHONE", PHONE_US, "[PHONE]"), ("PHONE", PHONE_CN_LAND, "[PHONE]"), ("CARD", CARD, _sub_card), ("ID", CONTEXT_ID, _sub_context), ("ID", LONG_DIGITS, "[ID]"), ("ID", TOKEN, "[ID]"), ("HANDLE", HANDLE, "[HANDLE]"), ] def redact(text: str) -> tuple[str, dict]: """(text with personal details replaced by placeholders, {placeholder: count}).""" if not text: return text or "", {} counts: Counter = Counter() for name, pat, repl in _RULES: tag = f"[{name}]" def fn(m, repl=repl, tag=tag): new = repl(m) if callable(repl) else repl if new != m.group(0): counts[name] += new.count(tag) or 1 return new text = pat.sub(fn, text) return text, dict(counts) def scrub(text: str) -> str: return redact(text)[0]