yungisimon commited on
Commit
30d8c63
·
verified ·
1 Parent(s): 6b99b76

Upload pii_hybrid_decode.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. pii_hybrid_decode.py +142 -0
pii_hybrid_decode.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Self-contained hybrid decode for LiquidAI/pii-detect (v7).
2
+
3
+ The token-classification head locates PII but, like all byte-BPE token classifiers,
4
+ fragments the boundaries of format-bound entities (e.g. it tags `1969` inside a date,
5
+ or `charite.de` inside an email). This module adds an inference-time regex layer — the
6
+ decode the product is meant to use — which roughly DOUBLES exact-match F1 with no loss
7
+ of precision/recall on real text:
8
+
9
+ AUTH types : distinctive, validator-gated formats (email, IBAN, JWT, SSN, MAC, crypto,
10
+ api_key, private_key, connection_string, ip, url, credit_card, swift, imei,
11
+ gps). Regex ADDS these and owns their exact boundaries.
12
+ SNAP types : FP-prone formats (phone, date_of_birth, amount, postal_code). The MODEL
13
+ must fire; regex only EXPANDS its fragment to the full match (no new FPs).
14
+
15
+ Everything else (names, addresses, conditions, medications, org, special-category,
16
+ username, national_id, passport, etc.) is left to the model.
17
+
18
+ Usage:
19
+ import torch
20
+ from transformers import AutoTokenizer, AutoModelForTokenClassification
21
+ from pii_hybrid_decode import predict
22
+ tok = AutoTokenizer.from_pretrained("LiquidAI/pii-detect", trust_remote_code=True)
23
+ model = AutoModelForTokenClassification.from_pretrained("LiquidAI/pii-detect",
24
+ trust_remote_code=True).eval()
25
+ spans = predict("Email [email protected] or call +49 30 4505 1234.", tok, model)
26
+ # -> [{'start':6,'end':22,'type':'contact.email','text':'[email protected]'}, ...]
27
+ """
28
+ from __future__ import annotations
29
+ import re
30
+
31
+ def _luhn_ok(num: str) -> bool:
32
+ ds = [int(c) for c in num if c.isdigit()]
33
+ if not (12 <= len(ds) <= 19): return False
34
+ tot, par = 0, len(ds) % 2
35
+ for i, d in enumerate(ds):
36
+ if i % 2 == par:
37
+ d *= 2; d = d - 9 if d > 9 else d
38
+ tot += d
39
+ return tot % 10 == 0
40
+
41
+ def _iban_ok(s: str) -> bool:
42
+ s = s.replace(" ", "").upper()
43
+ if not re.fullmatch(r"[A-Z]{2}\d{2}[A-Z0-9]{11,30}", s): return False
44
+ r = s[4:] + s[:4]
45
+ return int("".join(str(int(c, 36)) for c in r)) % 97 == 1
46
+
47
+ # (type, pattern, validator) — distinctive formats the regex layer ADDS + owns boundaries
48
+ _AUTH = [
49
+ ("contact.email", re.compile(r"\b[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}\b"), None),
50
+ ("credential.jwt", re.compile(r"\beyJ[A-Za-z0-9_\-]+\.eyJ[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+"), None),
51
+ ("credential.api_key", re.compile(r"\b(?:AKIA[0-9A-Z]{16}|sk-(?:proj-)?[A-Za-z0-9]{20,}|sk-ant-api03-[A-Za-z0-9_\-]{20,}|ghp_[A-Za-z0-9]{36}|AIza[0-9A-Za-z_\-]{35}|xox[baprs]-[A-Za-z0-9\-]{10,}|hf_[A-Za-z0-9]{30,})\b"), None),
52
+ ("credential.private_key", re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH |PGP )?PRIVATE KEY-----"), None),
53
+ ("credential.connection_string", re.compile(r"\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqp)://[^\s:@/]+:[^\s:@/]+@[^\s/]+"), None),
54
+ ("financial.iban", re.compile(r"\b[A-Z]{2}\d{2}(?:[ ]?[A-Z0-9]{4}){2,7}[ ]?[A-Z0-9]{1,3}\b"), _iban_ok),
55
+ ("financial.crypto_wallet", re.compile(r"\b(?:0x[a-fA-F0-9]{40}|bc1[a-z0-9]{25,90}|[13][a-km-zA-HJ-NP-Z1-9]{25,34})\b"), None),
56
+ ("device.mac_address", re.compile(r"\b(?:[0-9A-Fa-f]{2}[:\-]){5}[0-9A-Fa-f]{2}\b"), None),
57
+ ("location.gps_coordinates", re.compile(r"[\-+]?\d{1,3}\.\d{3,}\s*,\s*[\-+]?\d{1,3}\.\d{3,}"), None),
58
+ ("online.url", re.compile(r"\bhttps?://[^\s]+"), None),
59
+ ("identity.ssn", re.compile(r"\b\d{3}-\d{2}-\d{4}\b"), None),
60
+ ("contact.ip_address", re.compile(r"\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b"), None),
61
+ ("financial.credit_card", re.compile(r"\b(?:\d[ \-]?){13,19}\b"), _luhn_ok),
62
+ ("financial.swift_bic", re.compile(r"\b[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}(?:[A-Z0-9]{3})?\b"), None),
63
+ ("device.imei", re.compile(r"\b\d{15}\b"), _luhn_ok),
64
+ ]
65
+ _SNAP = {
66
+ "contact.phone": re.compile(r"(?<!\d)(?:\+?\d{1,3}[ \-.]?)?(?:\(\d{2,4}\)[ \-.]?)?\d{2,4}[ \-.]?\d{3}[ \-.]?\d{3,4}(?!\d)"),
67
+ "identity.date_of_birth": re.compile(r"\b(?:\d{1,2}[\/.\-]\d{1,2}[\/.\-]\d{2,4}|\d{4}[\/.\-]\d{1,2}[\/.\-]\d{1,2}|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\.?\s+\d{1,2},?\s+\d{4}|\d{1,2}\s+(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\.?\s+\d{4})\b"),
68
+ "financial.amount": re.compile(r"(?:[$€£¥]\s?\d[\d.,]*(?:\s?[KMB])?|\b(?:USD|EUR|GBP|JPY|CHF|CAD|AUD)\s?\d[\d.,]*(?:\s?[KMB])?\b|\b\d[\d.,]*\s?(?:USD|EUR|GBP|dollars|euros)\b)"),
69
+ "contact.postal_code": re.compile(r"\b(?:\d{5}(?:-\d{4})?|[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2})\b"),
70
+ }
71
+ _AUTH_TYPES = {t for t, _, _ in _AUTH}
72
+
73
+ def hybrid_spans(text: str, model_spans: list[dict]) -> list[dict]:
74
+ """model_spans: [{'start','end','type'}...] from the token classifier. Returns the
75
+ hybrid-decoded spans (dicts with start/end/type/text)."""
76
+ # 1. AUTH regex spans — built INDEPENDENTLY of the model (regex is authoritative
77
+ # for these distinctive formats; model fragments must not block them).
78
+ auth, claimed = [], [False] * len(text)
79
+ for t, pat, val in _AUTH:
80
+ for mm in pat.finditer(text):
81
+ s, e = mm.start(), mm.end()
82
+ if any(claimed[s:e]): continue
83
+ if val and not val(mm.group(0)): continue
84
+ for i in range(s, e): claimed[i] = True
85
+ auth.append({"start": s, "end": e, "type": t, "text": mm.group(0)})
86
+ # 2. model spans for non-AUTH types; SNAP types expand to overlapping regex match
87
+ out = []
88
+ for m in model_spans:
89
+ t = m["type"]
90
+ if t in _AUTH_TYPES:
91
+ continue # regex owns these
92
+ if t in _SNAP:
93
+ snap = None
94
+ for mm in _SNAP[t].finditer(text):
95
+ if min(mm.end(), m["end"]) > max(mm.start(), m["start"]):
96
+ snap = mm; break
97
+ if snap:
98
+ out.append({"start": snap.start(), "end": snap.end(), "type": t,
99
+ "text": text[snap.start():snap.end()]}); continue
100
+ out.append({"start": m["start"], "end": m["end"], "type": t,
101
+ "text": text[m["start"]:m["end"]]})
102
+ out.extend(auth)
103
+ seen, uniq = set(), []
104
+ for sp in sorted(out, key=lambda s: (s["start"], s["end"])):
105
+ k = (sp["start"], sp["end"], sp["type"])
106
+ if k not in seen:
107
+ seen.add(k); uniq.append(sp)
108
+ return uniq
109
+
110
+ def model_spans(text: str, tok, model):
111
+ import torch
112
+ enc = tok(text, return_offsets_mapping=True, return_tensors="pt", truncation=True, max_length=2048)
113
+ off = enc.pop("offset_mapping")[0].tolist()
114
+ enc = {k: v.to(model.device) for k, v in enc.items()}
115
+ with torch.no_grad():
116
+ ids = model(**enc).logits[0].argmax(-1).tolist()
117
+ id2label = model.config.id2label
118
+ spans, cur = [], None
119
+ for (a, b), i in zip(off, ids):
120
+ lab = id2label[i]
121
+ if b <= a or lab == "O":
122
+ if cur: spans.append(cur); cur = None
123
+ continue
124
+ typ = lab.split("-", 1)[1] if "-" in lab else lab
125
+ if lab[:2] in ("B-", "S-") or cur is None or cur["type"] != typ:
126
+ if cur: spans.append(cur)
127
+ cur = {"start": a, "end": b, "type": typ}
128
+ else:
129
+ cur["end"] = b
130
+ if cur: spans.append(cur)
131
+ # trim leading/trailing whitespace
132
+ for sp in spans:
133
+ while sp["start"] < sp["end"] and text[sp["start"]].isspace(): sp["start"] += 1
134
+ while sp["end"] > sp["start"] and text[sp["end"] - 1].isspace(): sp["end"] -= 1
135
+ return [s for s in spans if s["end"] > s["start"]]
136
+
137
+ def predict(text: str, tok, model, hybrid: bool = True) -> list[dict]:
138
+ ms = model_spans(text, tok, model)
139
+ if not hybrid:
140
+ return [{"start": s["start"], "end": s["end"], "type": s["type"],
141
+ "text": text[s["start"]:s["end"]]} for s in ms]
142
+ return hybrid_spans(text, ms)