Download bhed/postprocess.py from MindMapDigital/Bhed-v0.1: direct link, hf CLI and curl.
- Browser
- Download file 17.6 kB
-
https://huggingface.co/MindMapDigital/Bhed-v0.1/resolve/main/bhed/postprocess.py
- Command line
-
hf download hf://MindMapDigital/Bhed-v0.1/bhed/postprocess.py
-
curl -L -o postprocess.py https://huggingface.co/MindMapDigital/Bhed-v0.1/resolve/main/bhed/postprocess.py
17.6 kB
| """ | |
| Deterministic post-processing for the PII redaction model. | |
| The model only proposes WHAT is personal data (a JSON mapping of typed tags to exact strings). | |
| This module decides HOW the text is redacted, so the output can never drop, rewrite or invent words: | |
| 1. parse the model output (JSON mapping; tolerant of v1 "Mapping: {...}" and "TAG = value" formats) | |
| 2. normalise tag types to the 21 allowed types (PAS → PASSPORT, NIF → TAX_ID, ...) | |
| 3. repair merged values ("068271478, account 90615058489" → two values) and drop values not in the input | |
| 4. regex backstop for structured identifiers the model missed (email, phone, PAN, Aadhaar, DNI/NIE, IBAN, SSN, cards, IP...) | |
| 5. replace values in the ORIGINAL text, longest first, renumbering tags per type by first appearance | |
| 6. leak check on the result | |
| Usage: | |
| result = redact(original_text, model_output) | |
| result["sanitized"], result["mapping"], result["flags"] | |
| """ | |
| import json | |
| import re | |
| import unicodedata | |
| ALLOWED_TYPES = ["PER", "ORG", "ADDRESS", "LOC", "MONEY", "NATIONAL_ID", "TAX_ID", "COMPANY_REG", "PASSPORT", | |
| "BANK_ACCOUNT", "CARD", "PHONE", "EMAIL", "DATE", "PROPERTY_ID", "CASE_ID", "VEHICLE_ID", | |
| "ONLINE_ID", "EMPLOYEE_ID", "HEALTH", "SENSITIVE"] | |
| FALLBACK_TYPE = "PII" # redacted anyway, flagged for review | |
| TYPE_ALIASES = { | |
| "PAS": "PASSPORT", "PASS": "PASSPORT", "PASAPORTE": "PASSPORT", | |
| "PERSON": "PER", "NAME": "PER", "PERS": "PER", | |
| "ORGANIZATION": "ORG", "ORGANISATION": "ORG", "COMPANY": "ORG", "ORGANIZACION": "ORG", | |
| "LOCATION": "LOC", "CITY": "LOC", "PLACE": "LOC", "ADDR": "ADDRESS", "DIRECCION": "ADDRESS", | |
| "AMOUNT": "MONEY", "AMT": "MONEY", "CURRENCY": "MONEY", | |
| "ID": "NATIONAL_ID", "NID": "NATIONAL_ID", "DNI": "NATIONAL_ID", "NIE": "NATIONAL_ID", "AADHAAR": "NATIONAL_ID", | |
| "SSN": "NATIONAL_ID", "NINO": "NATIONAL_ID", "CURP": "NATIONAL_ID", | |
| "TAX": "TAX_ID", "NIF": "TAX_ID", "CIF": "TAX_ID", "PAN": "TAX_ID", "GST": "TAX_ID", "GSTIN": "TAX_ID", | |
| "RFC": "TAX_ID", "EIN": "TAX_ID", "UTR": "TAX_ID", "VAT": "TAX_ID", | |
| "CIN": "COMPANY_REG", "LLPIN": "COMPANY_REG", "REG": "COMPANY_REG", "COMPANY_ID": "COMPANY_REG", | |
| "BANK": "BANK_ACCOUNT", "ACCOUNT": "BANK_ACCOUNT", "IBAN": "BANK_ACCOUNT", "ACCT": "BANK_ACCOUNT", "UPI": "BANK_ACCOUNT", | |
| "CLABE": "BANK_ACCOUNT", "ROUTING": "BANK_ACCOUNT", "IFSC": "BANK_ACCOUNT", | |
| "CREDIT_CARD": "CARD", "TEL": "PHONE", "MOBILE": "PHONE", "TELEPHONE": "PHONE", "MAIL": "EMAIL", | |
| "PROPERTY": "PROPERTY_ID", "KHASRA": "PROPERTY_ID", "CADASTRAL": "PROPERTY_ID", "PARCEL": "PROPERTY_ID", | |
| "CASE": "CASE_ID", "NOTICE": "CASE_ID", "DIN": "CASE_ID", "VEHICLE": "VEHICLE_ID", "PLATE": "VEHICLE_ID", | |
| "IP": "ONLINE_ID", "URL": "ONLINE_ID", "USERNAME": "ONLINE_ID", "EMPLOYEE": "EMPLOYEE_ID", "UAN": "EMPLOYEE_ID", | |
| "MEDICAL": "HEALTH", "RELIGION": "SENSITIVE", "CASTE": "SENSITIVE", | |
| } | |
| # (type, pattern) — structured identifiers a regex finds more reliably than any model | |
| BACKSTOP = [ | |
| ("EMAIL", r"[\w.+-]+@[\w-]+\.[\w.]+"), | |
| ("BANK_ACCOUNT", r"\b[\w.-]+@(?:ok\w+|ybl|paytm|upi|ibl|axl)\b"), # UPI IDs | |
| ("TAX_ID", r"\b\d{2}[A-Z]{5}\d{4}[A-Z]\dZ[A-Z0-9]\b"), # GSTIN | |
| ("TAX_ID", r"\b[A-Z]{5}\d{4}[A-Z]\b"), # PAN | |
| ("BANK_ACCOUNT", r"\b[A-Z]{2}\d{2}(?:\s?[A-Z0-9]{4}){3,7}(?:\s?[A-Z0-9]{1,3})?\b"), # IBAN | |
| ("NATIONAL_ID", r"\b[XYZ]?\d{7,8}-?[A-HJ-NP-TV-Z]\b"), # DNI / NIE | |
| ("NATIONAL_ID", r"\b[2-9]\d{3}\s\d{4}\s\d{4}\b"), # Aadhaar (spaced) | |
| ("NATIONAL_ID", r"\b\d{3}-\d{2}-\d{4}\b"), # SSN | |
| ("CARD", r"\b(?:\d{4}[ -]){3}\d{4}\b"), | |
| ("ONLINE_ID", r"\b(?:\d{1,3}\.){3}\d{1,3}\b"), | |
| ("PHONE", r"(?:\+\d{1,3}[ -]?)?\(?\d{2,5}\)?[ -]\d{3,5}[ -]\d{3,5}\b"), | |
| ("PHONE", r"(?<![\w/])[6-9]\d{9}(?![\w/])"), # Indian mobile | |
| (FALLBACK_TYPE, r"(?<![\w/.])\d(?:[ -]?\d){7,}(?![\w/])"), # any other long number | |
| ] | |
| WORD = r"[^\W_]|[\u0900-\u0963\u0966-\u097F]" # Devanagari letters, marks, digits; NOT the danda (U+0964/0965) | |
| TAG_RX = re.compile(r"\[([A-Z_]+?)_(\d+)\]") | |
| # Countries are never personal data under the dataset rules (hard negatives): a LOC that is only a country is dropped. | |
| COUNTRIES = {c.strip().lower() for c in """ | |
| India, Bharat, España, Spain, México, Mexico, Argentina, Colombia, Chile, Perú, Peru, Francia, France, Alemania, Germany, | |
| Portugal, Italia, Italy, Reino Unido, United Kingdom, UK, Inglaterra, England, Estados Unidos, United States, USA, US, | |
| EE.UU., Canadá, Canada, Australia, Singapore, Singapur, Dubai, Dubái, UAE, Emiratos Árabes Unidos, United Arab Emirates, | |
| China, Japan, Japón, Brasil, Brazil, Suiza, Switzerland, Irlanda, Ireland, Países Bajos, Netherlands, Bélgica, Belgium, | |
| Marruecos, Morocco, Nepal, Bangladesh, Pakistan, Sri Lanka, Qatar, Oman, Kuwait, Saudi Arabia, | |
| भारत, कनाडा, दुबई, अमेरिका, ब्रिटेन, इंग्लैंड, ऑस्ट्रेलिया, सिंगापुर, जर्मनी, फ्रांस, नेपाल | |
| """.split(",") if c.strip()} | |
| # Boundary rules: one predicted span that the dataset convention splits into two entities. | |
| BOUNDARY_SPLITS = [ | |
| (re.compile(r"^(?P<a>.+?)\s+में\s+खसरा\s+(?:नंबर|संख्या|नं\.?)\s+(?P<b>\S+)$"), "LOC", "PROPERTY_ID"), | |
| (re.compile(r"^(?P<a>.+?)\s+(?:mein\s+)?khasra\s+(?:no\.?|number)\s+(?P<b>\S+)$", re.I), "LOC", "PROPERTY_ID"), | |
| (re.compile(r"^(?P<a>.+?)\s+(?:with\s+)?survey\s+no\.?\s+(?P<b>\S+)$", re.I), "LOC", "PROPERTY_ID"), | |
| ] | |
| ID_TYPES = {"BANK_ACCOUNT", "NATIONAL_ID", "TAX_ID", "COMPANY_REG", "PASSPORT", "PHONE", "CARD", "CASE_ID", | |
| "EMPLOYEE_ID", "VEHICLE_ID", FALLBACK_TYPE} | |
| SPLIT_LABEL = re.compile(r"\b(?:account|acct|a/c|cuenta|routing|sort code|IFSC)\b|खाता|खाते", re.I) | |
| CONTEXT_CUES = [(re.compile(p, re.I), t) for p, t in [ | |
| (r"\b(?:LLPIN|CIN|company (?:number|no\.?)|Registro Mercantil al|registration no\.?)\W*$", "COMPANY_REG"), | |
| (r"\b(?:passport(?: number| no\.?)?|pasaporte(?: es)?)\W*$|पासपोर्ट(?: नंबर)?\W*$", "PASSPORT"), | |
| (r"\b(?:Aadhaar|DNI|NIE|SSN|NI number|CURP)\W*$|आधार\W*$", "NATIONAL_ID"), | |
| (r"\b(?:PAN|GSTIN|NIF|CIF|RFC|EIN|ITIN|UTR|VAT(?: number)?)\W*$", "TAX_ID"), | |
| (r"\b(?:UAN|employee (?:ID|code)|staff no\.?|número de empleado|n[uú]mero de cliente)\W*$|कर्मचारी कोड\W*$", "EMPLOYEE_ID"), | |
| (r"\b(?:khasra(?: no\.?| number)?|survey no\.?|referencia catastral|title number|parcel)\W*$|खसरा (?:नंबर|संख्या)\W*$", "PROPERTY_ID"), | |
| (r"\b(?:account(?: number)?|routing(?: number)?|sort code|IBAN|CLABE|IFSC|cuenta|UPI)\W*$|खाते?\W*$", "BANK_ACCOUNT"), | |
| (r"\b(?:DIN|notice (?:number|no\.?)|reference|expediente|folio|lien number|claim no\.?)\W*$|नोटिस संख्या\W*$", "CASE_ID"), | |
| ]] | |
| ID_TOKEN = re.compile(r"[A-Z0-9][A-Z0-9./-]*\d[A-Z0-9./-]*(?:[ -]\d[\w-]*)*") | |
| def _nfc(s): | |
| return unicodedata.normalize("NFC", str(s)) | |
| def parse_output(output): | |
| """Model output → list of (raw_tag, value). Accepts a JSON object, 'Mapping: {...}', or 'TAG = value, ...'.""" | |
| text = output.strip() | |
| if "Mapping:" in text: | |
| text = text.split("Mapping:", 1)[1].strip() | |
| start, end = text.find("{"), text.rfind("}") | |
| if start != -1 and end > start: | |
| try: | |
| obj = json.loads(text[start:end + 1]) | |
| if isinstance(obj, dict): | |
| return [(str(k), _nfc(v)) for k, v in obj.items() if str(v).strip()], True | |
| except Exception: | |
| pass | |
| pairs = [] | |
| for part in re.split(r",\s*(?=\[[A-Z_]+_\d+\])", text): | |
| if "=" in part: | |
| k, v = part.split("=", 1) | |
| pairs.append((k.strip(), _nfc(v.strip().rstrip(".").strip('"')))) | |
| return pairs, bool(pairs) | |
| def normalise_type(raw_tag): | |
| t = raw_tag.strip().strip("[]").upper() | |
| t = re.sub(r"_?\d+$", "", t) | |
| if t in ALLOWED_TYPES: | |
| return t, False | |
| if t in TYPE_ALIASES: | |
| return TYPE_ALIASES[t], True | |
| cands = [a for a in ALLOWED_TYPES if a.startswith(t) and len(t) >= 3] | |
| if len(cands) == 1: | |
| return cands[0], True | |
| return FALLBACK_TYPE, True | |
| def _find(value, text): | |
| return value in text | |
| def repair_value(value, text): | |
| """Return the list of exact substrings of `text` that `value` stands for (empty if none).""" | |
| v = value.strip().strip("\"'") | |
| if _find(v, text): | |
| return [v] | |
| for sep in [r",\s*", r";\s*", r"\s+(?:and|y|e|और|aur)\s+", r"\s*/\s*"]: # merged values | |
| parts = [p.strip() for p in re.split(sep, v) if p.strip()] | |
| if len(parts) > 1: | |
| found = [] | |
| for p in parts: | |
| if _find(p, text): | |
| found.append(p) | |
| else: # strip leading label words ("account 9061…" → "9061…") | |
| m = re.search(r"[\w.+@/-]*\d[\w.+@/-]*(?:[ -]\d[\w-]*)*", p) | |
| if m and _find(m.group(0), text): | |
| found.append(m.group(0)) | |
| if found: | |
| return found | |
| compact = re.sub(r"\s+", " ", v) # whitespace drift | |
| if _find(compact, text): | |
| return [compact] | |
| return [] | |
| def expand_to_word(value, text): | |
| """A value that only occurs inside a longer word is widened to the whole word (never leave half a name visible).""" | |
| bound = re.compile(f"(?<!{WORD}){re.escape(value)}(?!{WORD})") | |
| if bound.search(text) or value not in text: | |
| return value | |
| i = text.find(value); j = i + len(value) | |
| while i > 0 and re.match(WORD, text[i - 1]): i -= 1 | |
| while j < len(text) and re.match(WORD, text[j]): j += 1 | |
| return text[i:j] | |
| def split_boundaries(value, typ, text): | |
| """Apply the dataset's boundary conventions to one value → list of (value, type).""" | |
| for rx, ta, tb in BOUNDARY_SPLITS: | |
| m = rx.match(value) | |
| if m and m.group("a") in text and m.group("b") in text: | |
| return [(m.group("a"), ta), (m.group("b"), tb)] | |
| if typ in ID_TYPES and SPLIT_LABEL.search(value): # "068271478, account 90615058489" → two IDs | |
| toks = [t for t in ID_TOKEN.findall(value) if len(re.sub(r"\D", "", t)) >= 4] | |
| if len(toks) >= 2: | |
| return [(t, typ) for t in toks if t in text] | |
| return [(value, typ)] | |
| def type_from_context(value, typ, text): | |
| """For identifier-like values, the label just before the value decides the type (LLPIN → COMPANY_REG, ...).""" | |
| if typ not in ID_TYPES and typ != "ORG": | |
| return typ | |
| i = text.find(value) | |
| if i < 0 or not re.search(r"\d", value): | |
| return typ | |
| before = text[max(0, i - 28):i] | |
| for rx, t in CONTEXT_CUES: | |
| if rx.search(before): | |
| return t | |
| return typ | |
| def _spans(values, text): | |
| """Non-overlapping occurrences of all values, longest first.""" | |
| taken, spans = [False] * len(text), [] | |
| for v in sorted(set(values), key=len, reverse=True): | |
| bound = re.match(WORD, v[0]) and re.match(WORD, v[-1]) | |
| pat = re.compile((f"(?<!{WORD}){re.escape(v)}(?!{WORD})") if bound else re.escape(v)) | |
| for m in pat.finditer(text): | |
| if not any(taken[m.start():m.end()]): | |
| spans.append((m.start(), m.end(), v)) | |
| for i in range(m.start(), m.end()): | |
| taken[i] = True | |
| return sorted(spans), taken | |
| def redact(text, model_output, use_backstop=True): | |
| text = _nfc(text) | |
| pairs, parsed = parse_output(model_output) if model_output else ([], False) | |
| flags = {"parsed": parsed, "renamed_types": [], "unknown_types": [], "split_values": [], "not_in_text": [], | |
| "backstop_added": [], "leaks": []} | |
| value_type = {} | |
| for raw_tag, value in pairs: | |
| typ, changed = normalise_type(raw_tag) | |
| if changed: | |
| (flags["unknown_types"] if typ == FALLBACK_TYPE else flags["renamed_types"]).append(f"{raw_tag}→{typ}") | |
| found = repair_value(value, text) | |
| if not found: | |
| flags["not_in_text"].append(value) | |
| continue | |
| typed = [] | |
| for f in found: | |
| t2 = type_from_context(f, typ, text) | |
| if t2 != typ: | |
| flags.setdefault("type_from_context", []).append(f"{f}: {typ}→{t2}") | |
| typed.append((f, t2)) | |
| typed = [x for f, t in typed for x in split_boundaries(f, t, text)] | |
| if [f for f, _ in typed] != [value]: | |
| flags["split_values"].append({value: [f for f, _ in typed]}) | |
| for f, t in list(typed): | |
| w = expand_to_word(f, text) | |
| if w != f: | |
| flags.setdefault("expanded_to_word", []).append(f"{f}→{w}") | |
| f = w | |
| if t == "LOC" and f.strip().lower() in COUNTRIES: | |
| flags.setdefault("dropped_non_pii", []).append(f) | |
| continue | |
| value_type.setdefault(f, t) | |
| spans, taken = _spans(list(value_type), text) | |
| if use_backstop: | |
| for typ, pat in BACKSTOP: | |
| for m in re.finditer(pat, text): | |
| if not any(taken[m.start():m.end()]): | |
| value_type.setdefault(m.group(0), typ) | |
| flags["backstop_added"].append(f"{typ}:{m.group(0)}") | |
| for i in range(m.start(), m.end()): | |
| taken[i] = True | |
| spans, _ = _spans(list(value_type), text) | |
| counters, value_tag, parts, cursor, entities = {}, {}, [], 0, [] | |
| for s, e, v in spans: | |
| typ = value_type[v] | |
| if v not in value_tag: | |
| counters[typ] = counters.get(typ, 0) + 1 | |
| value_tag[v] = f"[{typ}_{counters[typ]}]" | |
| parts += [text[cursor:s], value_tag[v]] | |
| entities.append({"tag": value_tag[v], "type": typ, "value": v, "start": s, "end": e}) | |
| cursor = e | |
| parts.append(text[cursor:]) | |
| sanitized = "".join(parts) | |
| mapping = {tag: v for v, tag in value_tag.items()} | |
| stripped = TAG_RX.sub(" ", sanitized) | |
| flags["leaks"] = [f"{typ}:{m.group(0)}" for typ, pat in BACKSTOP for m in re.finditer(pat, stripped)] | |
| return {"sanitized": sanitized, "mapping": mapping, "entities": entities, "flags": flags} | |
| def reidentify(text, mapping): | |
| return TAG_RX.sub(lambda m: mapping.get(m.group(0), m.group(0)), text) | |
| # --------------------------------------------------------------------------- # | |
| # Evaluation helpers (strict + lenient) | |
| # --------------------------------------------------------------------------- # | |
| def _char_mask(text, values): | |
| mask = [False] * len(text) | |
| for s, e, _ in _spans(values, text)[0]: | |
| for i in range(s, e): | |
| mask[i] = True | |
| return mask | |
| def score_example(text, model_output, gold_mapping, use_backstop=True): | |
| res = redact(text, model_output, use_backstop) | |
| gold = {(re.sub(r"_\d+\]$", "]", k).strip("[]"), v) for k, v in gold_mapping.items()} | |
| pred = {(e["type"], e["value"]) for e in res["entities"]} | |
| gold_vals = [v for _, v in gold] | |
| # lenient = character overlap, type-agnostic | |
| gmask, pmask = _char_mask(text, gold_vals), _char_mask(text, [e["value"] for e in res["entities"]]) | |
| g_chars, p_chars = sum(gmask), sum(pmask) | |
| overlap = sum(a and b for a, b in zip(gmask, pmask)) | |
| leaked = [v for v in gold_vals if v in res["sanitized"]] | |
| return { | |
| "parsed": res["flags"]["parsed"], | |
| "tp": len(gold & pred), "fp": len(pred - gold), "fn": len(gold - pred), | |
| "fn_items": sorted(gold - pred), "fp_items": sorted(pred - gold), | |
| "gold_chars": g_chars, "pred_chars": p_chars, "overlap_chars": overlap, | |
| "gold_n": len(gold_vals), "leaked": leaked, "no_pii": not gold, | |
| "over_redact": (not gold) and bool(res["entities"]), | |
| "not_in_text": len(res["flags"]["not_in_text"]), "backstop_added": len(res["flags"]["backstop_added"]), | |
| "renamed_types": len(res["flags"]["renamed_types"]), "split_values": len(res["flags"]["split_values"]), | |
| "sanitized": res["sanitized"], | |
| } | |
| def summarise(scores): | |
| n = len(scores) | |
| tp = sum(s["tp"] for s in scores); fp = sum(s["fp"] for s in scores); fn = sum(s["fn"] for s in scores) | |
| p = tp / max(tp + fp, 1); r = tp / max(tp + fn, 1) | |
| gc = sum(s["gold_chars"] for s in scores); pc = sum(s["pred_chars"] for s in scores); oc = sum(s["overlap_chars"] for s in scores) | |
| lp = oc / max(pc, 1); lr = oc / max(gc, 1) | |
| with_pii = [s for s in scores if not s["no_pii"]] | |
| no_pii = [s for s in scores if s["no_pii"]] | |
| gold_n = sum(s["gold_n"] for s in scores) | |
| return { | |
| "n": n, | |
| "parse_ok": sum(s["parsed"] for s in scores) / max(n, 1), | |
| "strict_P": p, "strict_R": r, "strict_F1": 2 * p * r / max(p + r, 1e-9), | |
| "lenient_P": lp, "lenient_R": lr, "lenient_F1": 2 * lp * lr / max(lp + lr, 1e-9), | |
| "redaction_recall": 1 - sum(len(s["leaked"]) for s in scores) / max(gold_n, 1), | |
| "leak_rate": sum(bool(s["leaked"]) for s in with_pii) / max(len(with_pii), 1), | |
| "over_redaction": (sum(s["over_redact"] for s in no_pii) / len(no_pii)) if no_pii else float("nan"), | |
| "values_not_in_text": sum(s["not_in_text"] for s in scores), | |
| "backstop_added": sum(s["backstop_added"] for s in scores), | |
| "faithful": 1.0, # by construction: the text outside tags is the original text | |
| } |