scrubpii 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- scrubpii/__init__.py +381 -0
- scrubpii/area_codes.txt +1 -0
- scrubpii/cli.py +70 -0
- scrubpii/guard.py +42 -0
- scrubpii/server.py +58 -0
- scrubpii/structured.py +91 -0
- scrubpii-0.3.0.dist-info/METADATA +183 -0
- scrubpii-0.3.0.dist-info/RECORD +11 -0
- scrubpii-0.3.0.dist-info/WHEEL +4 -0
- scrubpii-0.3.0.dist-info/entry_points.txt +2 -0
- scrubpii-0.3.0.dist-info/licenses/LICENSE +21 -0
scrubpii/__init__.py
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
"""Find and redact personal data in text.
|
|
2
|
+
|
|
3
|
+
>>> from scrubpii import redact
|
|
4
|
+
>>> redact("Hi, I'm Sarah Johnson. Call 662-634-1142.")
|
|
5
|
+
"Hi, I'm [PERSON]. Call [PHONE]."
|
|
6
|
+
|
|
7
|
+
A fine-tuned DistilBERT model (ChadTollison/pii-distilbert-v3) finds the
|
|
8
|
+
items, and checksum and format rules double-check them: card numbers must
|
|
9
|
+
pass Luhn, IBANs their bank checksum, SSNs the SSA format. The rules also
|
|
10
|
+
catch 10-digit US phone numbers with a real area code, valid IBANs and
|
|
11
|
+
well-known API key formats even when the model misses them.
|
|
12
|
+
|
|
13
|
+
The model (about 260 MB) downloads from Hugging Face on first use and is
|
|
14
|
+
cached, so later runs work offline.
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import hashlib
|
|
19
|
+
import ipaddress
|
|
20
|
+
import os
|
|
21
|
+
import re
|
|
22
|
+
from dataclasses import dataclass
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Dict, List, Optional, Tuple
|
|
25
|
+
|
|
26
|
+
__all__ = ["Entity", "find", "find_many", "redact", "redact_many", "tokenize", "restore", "fake_for", "MODEL_ID",
|
|
27
|
+
"redact_json", "redact_csv", "redact_dataframe", "Guard"]
|
|
28
|
+
__version__ = "0.3.0"
|
|
29
|
+
|
|
30
|
+
MODEL_ID = "ChadTollison/pii-distilbert-v3"
|
|
31
|
+
MODES = ("label", "mask", "fake", "token")
|
|
32
|
+
SURE = 0.95 # model confidence that overrides a failed format/checksum check
|
|
33
|
+
# Long text is read in windows of this many tokens. The model learned on short
|
|
34
|
+
# texts, and on long documents it finds much more when it reads them in short
|
|
35
|
+
# pieces (finance set: 0.65 F1 with 512-token windows, 0.76 with 128).
|
|
36
|
+
WINDOW = int(os.environ.get("SCRUBPII_WINDOW") or os.environ.get("CHAD_PII_WINDOW") or "128")
|
|
37
|
+
|
|
38
|
+
_pipeline = None
|
|
39
|
+
_pipeline_id = None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass
|
|
43
|
+
class Entity:
|
|
44
|
+
type: str
|
|
45
|
+
text: str
|
|
46
|
+
start: int
|
|
47
|
+
end: int
|
|
48
|
+
score: float
|
|
49
|
+
rule: Optional[str] = None # why a rule found or confirmed it, if one did
|
|
50
|
+
|
|
51
|
+
def as_dict(self) -> dict:
|
|
52
|
+
return {"type": self.type, "text": self.text, "start": self.start, "end": self.end,
|
|
53
|
+
"score": round(self.score, 4), "rule": self.rule}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
# ---------------------------------------------------------------- checks
|
|
57
|
+
AREA_CODES = frozenset((Path(__file__).parent / "area_codes.txt").read_text().split())
|
|
58
|
+
PHONE_RE = re.compile(r"(?:\+?1[\s.-]?)?(?:\(\d{3}\)|\b\d{3})[\s.-]?\d{3}[\s.-]?\d{4}\b")
|
|
59
|
+
IBAN_RE = re.compile(r"\b[A-Z]{2}\d{2}(?: ?[A-Z0-9]{4}){2,7}(?: ?[A-Z0-9]{1,4})?\b")
|
|
60
|
+
API_KEY_RE = re.compile(
|
|
61
|
+
r"\b(?:(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{16,}|sk-(?:proj-)?[A-Za-z0-9_-]{32,}|AKIA[0-9A-Z]{16}"
|
|
62
|
+
r"|gh[pousr]_[A-Za-z0-9]{30,}|xox[abprs]-[A-Za-z0-9-]{20,}|AIza[0-9A-Za-z_-]{35})")
|
|
63
|
+
CARD_RE = re.compile(r"\b[2-6]\d{3}(?:[ -]?\d){9,15}\b")
|
|
64
|
+
SSN_RE = re.compile(r"\b\d{3}([- ])\d{2}\1\d{4}\b")
|
|
65
|
+
SSN_BARE_RE = re.compile(r"(?i)(?:ssn|social security(?: number| no\.?)?)\W{0,12}(\d{9})\b")
|
|
66
|
+
DOB_RE = re.compile(r"(?i)\b(?:born(?: on)?|d\.?o\.?b\.?|date of birth|birth ?date|birthday|fecha de nacimiento|nacid[oa] el)\W{0,4}(\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|sept|oct|nov|dec)[a-z]*\.? \d{1,2}(?:st|nd|rd|th)?,? \d{4}|\d{1,2}(?:st|nd|rd|th)? (?:of )?(?:jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec)[a-z]*\.?,? \d{4}|\d{1,2} de [a-záéíóú]+ de \d{4})")
|
|
67
|
+
IPV6_RE = re.compile(r"(?<![\w:])(?=[0-9A-Fa-f:]*:[0-9A-Fa-f]*:)[0-9A-Fa-f:]{2,39}(?![\w:])")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def ip_ok(s: str) -> bool:
|
|
71
|
+
try:
|
|
72
|
+
ipaddress.ip_address(s)
|
|
73
|
+
return True
|
|
74
|
+
except ValueError:
|
|
75
|
+
return False
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
SHAPES = {
|
|
79
|
+
"EMAIL": re.compile(r"[\w.%+-]+@[\w.-]+\.[^\W\d_]{2,}"),
|
|
80
|
+
"PHONE": PHONE_RE,
|
|
81
|
+
"SSN": re.compile(r"\b\d{3}-\d{2}-\d{4}\b"),
|
|
82
|
+
"CREDIT_CARD": re.compile(r"\b\d{4}(?:[ -]?\d{4}){2}[ -]?\d{1,7}\b"),
|
|
83
|
+
"IP_ADDRESS": re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b"),
|
|
84
|
+
"IBAN": IBAN_RE,
|
|
85
|
+
"API_KEY": API_KEY_RE,
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def luhn_ok(s: str) -> bool:
|
|
90
|
+
digits = [int(c) for c in s if c.isdigit()]
|
|
91
|
+
if not 13 <= len(digits) <= 19:
|
|
92
|
+
return False
|
|
93
|
+
total = 0
|
|
94
|
+
for i, d in enumerate(reversed(digits)):
|
|
95
|
+
if i % 2:
|
|
96
|
+
d *= 2
|
|
97
|
+
d -= 9 if d > 9 else 0
|
|
98
|
+
total += d
|
|
99
|
+
return total % 10 == 0
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def iban_ok(s: str) -> bool:
|
|
103
|
+
v = re.sub(r"\s+", "", s).upper()
|
|
104
|
+
if not re.fullmatch(r"[A-Z]{2}\d{2}[A-Z0-9]{10,30}", v):
|
|
105
|
+
return False
|
|
106
|
+
return int("".join(str(int(c, 36)) for c in v[4:] + v[:4])) % 97 == 1
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def ssn_ok(s: str) -> bool:
|
|
110
|
+
m = re.fullmatch(r"(\d{3})[- ]?(\d{2})[- ]?(\d{4})", s.strip())
|
|
111
|
+
return bool(m) and m[1] not in ("000", "666") and m[1][0] != "9" and m[2] != "00" and m[3] != "0000"
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def us_phone_ok(s: str) -> bool:
|
|
115
|
+
d = re.sub(r"\D", "", s)
|
|
116
|
+
if len(d) == 11 and d[0] == "1":
|
|
117
|
+
d = d[1:]
|
|
118
|
+
return len(d) == 10 and d[:3] in AREA_CODES and d[3] in "23456789"
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _valid(e: Entity) -> bool:
|
|
122
|
+
t, s = e.type, e.text
|
|
123
|
+
if t == "CREDIT_CARD":
|
|
124
|
+
return luhn_ok(s)
|
|
125
|
+
if t == "SSN":
|
|
126
|
+
return ssn_ok(s)
|
|
127
|
+
if t == "IBAN":
|
|
128
|
+
return iban_ok(s)
|
|
129
|
+
if t == "PHONE":
|
|
130
|
+
return len(re.sub(r"\D", "", s)) >= 7
|
|
131
|
+
if t == "EMAIL":
|
|
132
|
+
return bool(re.fullmatch(r"[^\s@]+@[^\s@]+\.[^\s@]{2,}", s))
|
|
133
|
+
if t == "IP_ADDRESS":
|
|
134
|
+
parts = s.split(".")
|
|
135
|
+
return len(parts) == 4 and all(p.isdigit() and int(p) <= 255 for p in parts)
|
|
136
|
+
return True
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
# ---------------------------------------------------------------- model
|
|
140
|
+
def _get_pipeline(model: str):
|
|
141
|
+
global _pipeline, _pipeline_id
|
|
142
|
+
if _pipeline is None or _pipeline_id != model:
|
|
143
|
+
from transformers import AutoTokenizer, pipeline
|
|
144
|
+
tok = AutoTokenizer.from_pretrained(model, model_input_names=["input_ids", "attention_mask"])
|
|
145
|
+
tok.model_max_length = min(tok.model_max_length, WINDOW)
|
|
146
|
+
_pipeline = pipeline("token-classification", model=model, tokenizer=tok,
|
|
147
|
+
aggregation_strategy="max", stride=WINDOW // 4)
|
|
148
|
+
_pipeline_id = model
|
|
149
|
+
return _pipeline
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _model_entities(text: str, model: str, items=None) -> List[Entity]:
|
|
153
|
+
out = []
|
|
154
|
+
for item in (items if items is not None else _get_pipeline(model)(text)):
|
|
155
|
+
s, e = item["start"], item["end"]
|
|
156
|
+
while s < e and text[s].isspace():
|
|
157
|
+
s += 1
|
|
158
|
+
while e > s and text[e - 1].isspace():
|
|
159
|
+
e -= 1
|
|
160
|
+
if e > s:
|
|
161
|
+
out.append(Entity(item["entity_group"], text[s:e], s, e, float(item["score"])))
|
|
162
|
+
# Join a name split into pieces ("José" + "Álvarez").
|
|
163
|
+
joined: List[Entity] = []
|
|
164
|
+
for ent in out:
|
|
165
|
+
prev = joined[-1] if joined else None
|
|
166
|
+
if prev and prev.type == ent.type and text[prev.end:ent.start] in ("", " "):
|
|
167
|
+
prev.end, prev.text = ent.end, text[prev.start:ent.end]
|
|
168
|
+
prev.score = min(prev.score, ent.score)
|
|
169
|
+
else:
|
|
170
|
+
joined.append(ent)
|
|
171
|
+
return joined
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _grow(ents: List[Entity], text: str) -> None:
|
|
175
|
+
"""Grow a partly-found item to the full email, phone, card... it is part of."""
|
|
176
|
+
for e in ents:
|
|
177
|
+
rx = SHAPES.get(e.type)
|
|
178
|
+
if not rx:
|
|
179
|
+
continue
|
|
180
|
+
for m in rx.finditer(text):
|
|
181
|
+
if m.start() < e.end and m.end() > e.start:
|
|
182
|
+
e.start, e.end = min(e.start, m.start()), max(e.end, m.end())
|
|
183
|
+
e.text = text[e.start:e.end]
|
|
184
|
+
break
|
|
185
|
+
if e.type in ("SSN", "PHONE"):
|
|
186
|
+
digits = re.sub(r"\D", "", e.text)
|
|
187
|
+
if re.fullmatch(r"\d{3}-\d{2}-\d{4}", e.text.strip()):
|
|
188
|
+
e.type = "SSN"
|
|
189
|
+
elif 10 <= len(digits) <= 11:
|
|
190
|
+
e.type = "PHONE"
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _rules(ents: List[Entity], text: str) -> List[Entity]:
|
|
194
|
+
checks = [("PHONE", PHONE_RE, us_phone_ok, "real US/Canada area code"),
|
|
195
|
+
("IBAN", IBAN_RE, iban_ok, "IBAN checksum"),
|
|
196
|
+
("API_KEY", API_KEY_RE, lambda s: True, "known API key format"),
|
|
197
|
+
("CREDIT_CARD", CARD_RE, luhn_ok, "card number with valid Luhn checksum"),
|
|
198
|
+
("SSN", SSN_RE, ssn_ok, "valid SSN format"),
|
|
199
|
+
("SSN", SSN_BARE_RE, ssn_ok, "9 digits right after 'SSN'"),
|
|
200
|
+
("EMAIL", SHAPES["EMAIL"], lambda s: True, "email address format"),
|
|
201
|
+
("IP_ADDRESS", SHAPES["IP_ADDRESS"], ip_ok, "valid IP address"),
|
|
202
|
+
("IP_ADDRESS", IPV6_RE, ip_ok, "valid IPv6 address"),
|
|
203
|
+
("DATE_OF_BIRTH", DOB_RE, lambda s: True, "a date right after 'born' or 'DOB'")]
|
|
204
|
+
for typ, rx, ok, why in checks:
|
|
205
|
+
for m in rx.finditer(text):
|
|
206
|
+
g = 1 if rx in (SSN_BARE_RE, DOB_RE) else 0
|
|
207
|
+
ms, me = m.start(g), m.end(g)
|
|
208
|
+
if not ok(m.group(g)):
|
|
209
|
+
continue
|
|
210
|
+
hits = [e for e in ents if e.start < me and e.end > ms]
|
|
211
|
+
if not hits:
|
|
212
|
+
ents.append(Entity(typ, m.group(g), ms, me, 1.0, why))
|
|
213
|
+
for e in hits:
|
|
214
|
+
# Phone, card and SSN rules only relabel the model's find when
|
|
215
|
+
# its own label fails its check (e.g. "card number" that fails Luhn).
|
|
216
|
+
if typ in ("PHONE", "CREDIT_CARD", "SSN", "EMAIL", "IP_ADDRESS") and e.type != typ and _valid(e):
|
|
217
|
+
continue
|
|
218
|
+
e.type, e.rule, e.score = typ, why, 1.0
|
|
219
|
+
e.start, e.end = min(e.start, ms), max(e.end, me)
|
|
220
|
+
e.text = text[e.start:e.end]
|
|
221
|
+
ents.sort(key=lambda e: (e.start, -e.end))
|
|
222
|
+
kept: List[Entity] = []
|
|
223
|
+
for e in ents:
|
|
224
|
+
if kept and e.start < kept[-1].end:
|
|
225
|
+
k = kept[-1]
|
|
226
|
+
if e.end > k.end:
|
|
227
|
+
k.end, k.text = e.end, text[k.start:e.end]
|
|
228
|
+
continue
|
|
229
|
+
kept.append(e)
|
|
230
|
+
return kept
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def find(text: str, min_score: float = 0.5, model: str = MODEL_ID) -> List[Entity]:
|
|
234
|
+
"""Return the personal data found in `text`, in order.
|
|
235
|
+
|
|
236
|
+
Items the rules found or confirmed are always returned. Others need a model
|
|
237
|
+
confidence of at least `min_score`, and must pass their type's check
|
|
238
|
+
(Luhn for cards, checksum for IBANs, format for SSNs...) unless the model
|
|
239
|
+
is at least 95% sure.
|
|
240
|
+
"""
|
|
241
|
+
if not text.strip():
|
|
242
|
+
return []
|
|
243
|
+
return _finish(text, _model_entities(text, model), min_score)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _finish(text: str, ents: List[Entity], min_score: float) -> List[Entity]:
|
|
247
|
+
_grow(ents, text)
|
|
248
|
+
ents = _rules(ents, text)
|
|
249
|
+
# A failed check (Luhn, SSN format ...) drops an item unless the model is
|
|
250
|
+
# very sure: for a redactor, hiding a mistyped card number beats leaking it.
|
|
251
|
+
return [e for e in ents if e.rule or (e.score >= min_score and (e.score >= SURE or _valid(e)))]
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def find_many(texts: List[str], min_score: float = 0.5, model: str = MODEL_ID, batch_size: int = 16) -> List[List[Entity]]:
|
|
255
|
+
"""find() for many texts at once. Batched, so much faster than a loop."""
|
|
256
|
+
texts = list(texts)
|
|
257
|
+
todo = [i for i, t in enumerate(texts) if t and t.strip()]
|
|
258
|
+
out: List[List[Entity]] = [[] for _ in texts]
|
|
259
|
+
if todo:
|
|
260
|
+
results = _get_pipeline(model)([texts[i] for i in todo], batch_size=batch_size)
|
|
261
|
+
for i, items in zip(todo, results):
|
|
262
|
+
out[i] = _finish(texts[i], _model_entities(texts[i], model, items), min_score)
|
|
263
|
+
return out
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
# ---------------------------------------------------------------- redaction
|
|
267
|
+
_FIRST = ["Alex", "Jordan", "Taylor", "Morgan", "Casey", "Riley", "Jamie", "Avery", "Quinn", "Rowan", "Drew", "Skyler"]
|
|
268
|
+
_LAST = ["Rivera", "Brooks", "Hayes", "Bennett", "Foster", "Reed", "Parker", "Ellis", "Price", "Shaw", "Lane", "Cole"]
|
|
269
|
+
_CARDS = ["4111 1111 1111 1111", "5500 0000 0000 0004", "3782 822463 10005", "6011 1111 1111 1117"]
|
|
270
|
+
_STREETS = ["Example Street", "Sample Avenue", "Placeholder Road", "Fictional Lane", "Demo Drive"]
|
|
271
|
+
_IBANS = ["GB82 WEST 1234 5698 7654 32", "DE89 3704 0044 0532 0130 00", "FR14 2004 1010 0505 0001 3M02 606"]
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _h(s: str) -> int:
|
|
275
|
+
return int(hashlib.sha256(s.encode()).hexdigest()[:12], 16)
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def fake_for(e: Entity) -> str:
|
|
279
|
+
"""A realistic but harmless stand-in. The same input always gets the same fake."""
|
|
280
|
+
h = _h(e.type + "|" + e.text)
|
|
281
|
+
first, last = _FIRST[h % 12], _LAST[(h >> 8) % 12]
|
|
282
|
+
same = lambda x: re.sub(r"\s", "", x) == re.sub(r"\s", "", e.text)
|
|
283
|
+
if e.type == "PERSON":
|
|
284
|
+
return f"{first} {last}" if " " in e.text.strip() else first
|
|
285
|
+
if e.type == "EMAIL":
|
|
286
|
+
return f"{first}.{last}@example.com".lower()
|
|
287
|
+
if e.type == "PHONE":
|
|
288
|
+
return f"(202) 555-01{h % 100:02d}" # 555-0100..0199 are reserved for fiction
|
|
289
|
+
if e.type == "SSN":
|
|
290
|
+
return f"9{h % 100:02d}-{(h >> 7) % 90 + 10}-{(h >> 3) % 9000 + 1000}" # SSNs never start with 9
|
|
291
|
+
if e.type == "CREDIT_CARD":
|
|
292
|
+
c = [x for x in _CARDS if not same(x)]
|
|
293
|
+
return c[h % len(c)]
|
|
294
|
+
if e.type == "IP_ADDRESS":
|
|
295
|
+
return f"203.0.113.{h % 254 + 1}" # documentation-only range
|
|
296
|
+
if e.type == "IBAN":
|
|
297
|
+
c = [x for x in _IBANS if not same(x)]
|
|
298
|
+
return c[h % len(c)]
|
|
299
|
+
if e.type == "PASSPORT":
|
|
300
|
+
return f"X{h % 10**8:08d}"
|
|
301
|
+
if e.type == "DRIVER_LICENSE":
|
|
302
|
+
return f"D{h % 10**7:07d}"
|
|
303
|
+
if e.type == "API_KEY":
|
|
304
|
+
return f"sk_example_{h:016x}"[:27]
|
|
305
|
+
if e.type == "ADDRESS":
|
|
306
|
+
return f"{h % 900 + 100} {_STREETS[h % len(_STREETS)]}"
|
|
307
|
+
if e.type == "ID_NUMBER":
|
|
308
|
+
return f"ID-{h % 10**8:08d}"
|
|
309
|
+
if e.type == "DATE_OF_BIRTH":
|
|
310
|
+
return f"01/01/{1950 + h % 50}"
|
|
311
|
+
if e.type == "USERNAME":
|
|
312
|
+
return f"user{h % 10**5:05d}"
|
|
313
|
+
if e.type == "PASSWORD":
|
|
314
|
+
return "********"
|
|
315
|
+
return f"[{e.type}]"
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _apply(text: str, ents: List[Entity], mode: str, key: Optional[Dict[str, str]] = None) -> Tuple[str, Dict[str, str]]:
|
|
319
|
+
if mode not in MODES:
|
|
320
|
+
raise ValueError(f"mode must be one of {MODES}")
|
|
321
|
+
key = {} if key is None else key # token -> real value; reused across calls when given
|
|
322
|
+
tokens: Dict[Tuple[str, str], str] = {}
|
|
323
|
+
counts: Dict[str, int] = {}
|
|
324
|
+
for tok, val in key.items():
|
|
325
|
+
m = re.fullmatch(r"<([A-Z_]+)_(\d+)>", tok)
|
|
326
|
+
if m:
|
|
327
|
+
tokens[(m[1], val)] = tok
|
|
328
|
+
counts[m[1]] = max(counts.get(m[1], 0), int(m[2]))
|
|
329
|
+
out, pos = [], 0
|
|
330
|
+
for e in ents:
|
|
331
|
+
if mode == "label":
|
|
332
|
+
rep = f"[{e.type}]"
|
|
333
|
+
elif mode == "mask":
|
|
334
|
+
rep = "█" * len(e.text)
|
|
335
|
+
elif mode == "fake":
|
|
336
|
+
rep = fake_for(e)
|
|
337
|
+
else:
|
|
338
|
+
if (e.type, e.text) not in tokens:
|
|
339
|
+
counts[e.type] = counts.get(e.type, 0) + 1
|
|
340
|
+
tokens[(e.type, e.text)] = f"<{e.type}_{counts[e.type]}>"
|
|
341
|
+
key[tokens[(e.type, e.text)]] = e.text
|
|
342
|
+
rep = tokens[(e.type, e.text)]
|
|
343
|
+
out += [text[pos:e.start], rep]
|
|
344
|
+
pos = e.end
|
|
345
|
+
out.append(text[pos:])
|
|
346
|
+
return "".join(out), key
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def redact(text: str, mode: str = "label", min_score: float = 0.5, model: str = MODEL_ID) -> str:
|
|
350
|
+
"""Return `text` with personal data replaced.
|
|
351
|
+
|
|
352
|
+
mode="label" -> [PHONE] mode="mask" -> ████ mode="fake" -> (202) 555-0142
|
|
353
|
+
mode="token" -> <PHONE_1> (use tokenize() to also get the key back)
|
|
354
|
+
"""
|
|
355
|
+
return _apply(text, find(text, min_score, model), mode)[0]
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def redact_many(texts: List[str], mode: str = "label", min_score: float = 0.5, model: str = MODEL_ID) -> List[str]:
|
|
359
|
+
"""redact() for many texts at once (batched)."""
|
|
360
|
+
texts = list(texts)
|
|
361
|
+
return [_apply(t, ents, mode)[0] for t, ents in zip(texts, find_many(texts, min_score, model))]
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def tokenize(text: str, min_score: float = 0.5, model: str = MODEL_ID,
|
|
365
|
+
key: Optional[Dict[str, str]] = None) -> Tuple[str, Dict[str, str]]:
|
|
366
|
+
"""Replace personal data with tokens like <PERSON_1>. Returns (text, key).
|
|
367
|
+
|
|
368
|
+
Keep the key somewhere safe; restore(text, key) puts the real values back.
|
|
369
|
+
The same value always gets the same token. Pass the key from an earlier
|
|
370
|
+
call to keep tokens consistent across several texts (e.g. a chat).
|
|
371
|
+
"""
|
|
372
|
+
return _apply(text, find(text, min_score, model), "token", key)
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def restore(text: str, key: Dict[str, str]) -> str:
|
|
376
|
+
"""Put real values back into tokenized text."""
|
|
377
|
+
return re.sub(r"<[A-Z_]+_\d+>", lambda m: key.get(m.group(), m.group()), text)
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
from .structured import redact_csv, redact_dataframe, redact_json # noqa: E402
|
|
381
|
+
from .guard import Guard # noqa: E402
|
scrubpii/area_codes.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
201 202 203 204 205 206 207 208 209 210 212 213 214 215 216 217 218 219 220 223 224 225 226 227 228 229 231 234 235 236 239 240 242 246 248 249 250 251 252 253 254 256 260 262 263 267 269 270 272 274 276 279 281 283 284 289 301 302 303 304 305 306 307 308 309 310 312 313 314 315 316 317 318 319 320 321 323 325 326 327 329 330 331 332 334 336 337 339 340 341 343 345 346 347 350 351 352 354 360 361 363 364 365 367 368 369 380 382 385 386 401 402 403 404 405 406 407 408 409 410 412 413 414 415 416 417 418 419 423 424 425 428 430 431 432 434 435 437 438 440 441 442 443 445 447 448 450 458 463 464 468 469 470 472 473 474 475 478 479 480 484 500 501 502 503 504 505 506 507 508 509 510 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 533 534 539 540 541 544 548 551 557 559 561 562 563 564 566 567 570 571 572 573 574 575 577 579 580 581 582 584 585 586 587 588 600 601 602 603 604 605 606 607 608 609 610 612 613 614 615 616 617 618 619 620 622 623 626 628 629 630 631 633 636 639 640 641 645 646 647 649 650 651 656 657 658 659 660 661 662 667 669 670 671 672 678 680 681 682 683 689 701 702 703 704 705 706 707 708 709 712 713 714 715 716 717 718 719 720 724 725 726 727 728 730 731 732 734 737 740 742 743 747 753 754 757 758 760 762 763 765 769 770 771 772 773 774 775 778 779 780 781 782 784 785 786 787 800 801 802 803 804 805 806 807 808 809 810 812 813 814 815 816 817 818 819 820 825 826 828 829 830 831 832 833 835 838 839 840 843 844 845 847 848 849 850 854 855 856 857 858 859 860 862 863 864 865 866 867 868 870 872 873 876 877 878 879 888 900 901 902 903 904 905 906 907 908 909 910 912 913 914 915 916 917 918 919 920 925 928 929 930 931 934 936 937 938 939 940 941 942 943 945 947 948 949 951 952 954 956 959 970 971 972 973 978 979 980 983 984 985 986 989
|
scrubpii/cli.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""scrubpii on the command line.
|
|
2
|
+
|
|
3
|
+
scrubpii "Call Sarah at 662-634-1142" -> Call [PERSON] at [PHONE]
|
|
4
|
+
cat notes.txt | scrubpii --mode mask -> redacts standard input
|
|
5
|
+
scrubpii --file customers.csv -o safe.csv -> CSV, JSON, JSONL or text files
|
|
6
|
+
scrubpii --find "..." -> what it found, as JSON
|
|
7
|
+
scrubpii serve --port 8000 -> local HTTP API (needs scrubpii[server])
|
|
8
|
+
"""
|
|
9
|
+
import argparse
|
|
10
|
+
import json
|
|
11
|
+
import sys
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from . import MODES, __version__, find, redact, redact_csv, redact_json, tokenize
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _file(path, mode, min_score, columns):
|
|
18
|
+
p = Path(path)
|
|
19
|
+
text = p.read_text(encoding="utf-8")
|
|
20
|
+
ext = p.suffix.lower()
|
|
21
|
+
if ext == ".csv":
|
|
22
|
+
return redact_csv(text, mode, columns, min_score)
|
|
23
|
+
if ext == ".json":
|
|
24
|
+
return json.dumps(redact_json(json.loads(text), mode, columns, min_score), indent=2, ensure_ascii=False) + "\n"
|
|
25
|
+
if ext == ".jsonl":
|
|
26
|
+
lines = [json.loads(l) for l in text.splitlines() if l.strip()]
|
|
27
|
+
return "".join(json.dumps(x, ensure_ascii=False) + "\n" for x in redact_json(lines, mode, columns, min_score))
|
|
28
|
+
return redact(text, mode, min_score)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def main(argv=None):
|
|
32
|
+
argv = sys.argv[1:] if argv is None else argv
|
|
33
|
+
if argv[:1] == ["serve"]:
|
|
34
|
+
sp = argparse.ArgumentParser(prog="scrubpii serve")
|
|
35
|
+
sp.add_argument("--host", default="127.0.0.1")
|
|
36
|
+
sp.add_argument("--port", type=int, default=8000)
|
|
37
|
+
s = sp.parse_args(argv[1:])
|
|
38
|
+
from .server import run
|
|
39
|
+
return run(s.host, s.port)
|
|
40
|
+
ap = argparse.ArgumentParser(prog="scrubpii", description="Find and redact personal data in text.")
|
|
41
|
+
ap.add_argument("text", nargs="?", help="text to redact (default: read standard input)")
|
|
42
|
+
ap.add_argument("--file", help="redact a .csv, .json, .jsonl or text file")
|
|
43
|
+
ap.add_argument("-o", "--output", help="write here instead of standard output")
|
|
44
|
+
ap.add_argument("--columns", help="CSV columns / JSON fields to redact, comma separated (default: all)")
|
|
45
|
+
ap.add_argument("--mode", choices=MODES, default="label", help="how to replace what it finds (default: label)")
|
|
46
|
+
ap.add_argument("--min-score", type=float, default=0.5, help="model confidence needed (default: 0.5)")
|
|
47
|
+
ap.add_argument("--find", action="store_true", help="print what it found as JSON instead of redacting")
|
|
48
|
+
ap.add_argument("--version", action="version", version=f"scrubpii {__version__}")
|
|
49
|
+
a = ap.parse_args(argv)
|
|
50
|
+
cols = a.columns.split(",") if a.columns else None
|
|
51
|
+
if a.file:
|
|
52
|
+
out = _file(a.file, a.mode, a.min_score, cols)
|
|
53
|
+
else:
|
|
54
|
+
text = a.text if a.text is not None else sys.stdin.read()
|
|
55
|
+
if a.find:
|
|
56
|
+
out = json.dumps([e.as_dict() for e in find(text, a.min_score)], indent=2, ensure_ascii=False) + "\n"
|
|
57
|
+
elif a.mode == "token":
|
|
58
|
+
out, key = tokenize(text, a.min_score)
|
|
59
|
+
out += "\n"
|
|
60
|
+
print(json.dumps(key, indent=2, ensure_ascii=False), file=sys.stderr)
|
|
61
|
+
else:
|
|
62
|
+
out = redact(text, a.mode, a.min_score) + "\n"
|
|
63
|
+
if a.output:
|
|
64
|
+
Path(a.output).write_text(out, encoding="utf-8")
|
|
65
|
+
else:
|
|
66
|
+
sys.stdout.write(out)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
if __name__ == "__main__":
|
|
70
|
+
main()
|
scrubpii/guard.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Keep personal data out of prompts you send to an LLM (or any outside service).
|
|
2
|
+
|
|
3
|
+
from scrubpii import Guard
|
|
4
|
+
guard = Guard()
|
|
5
|
+
safe = guard.scrub("Email Sarah Johnson at sarah.j@example.com about her refund")
|
|
6
|
+
# "Email <PERSON_1> at <EMAIL_1> about her refund" -> send this to the model
|
|
7
|
+
reply = llm(safe) # "Dear <PERSON_1>, ..."
|
|
8
|
+
guard.restore(reply) # "Dear Sarah Johnson, ..."
|
|
9
|
+
|
|
10
|
+
The guard remembers its key across calls, so a whole conversation uses the
|
|
11
|
+
same tokens. The key never leaves your process.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from typing import Any, Callable, Dict, Optional
|
|
16
|
+
|
|
17
|
+
from . import MODEL_ID, find, _apply, restore
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Guard:
|
|
21
|
+
def __init__(self, min_score: float = 0.5, model: str = MODEL_ID):
|
|
22
|
+
self.min_score, self.model = min_score, model
|
|
23
|
+
self.key: Dict[str, str] = {}
|
|
24
|
+
|
|
25
|
+
def scrub(self, text: str) -> str:
|
|
26
|
+
"""Swap personal data for tokens like <PERSON_1>."""
|
|
27
|
+
return _apply(text, find(text, self.min_score, self.model), "token", self.key)[0]
|
|
28
|
+
|
|
29
|
+
def restore(self, text: str) -> str:
|
|
30
|
+
"""Put the real values back into text that contains this guard's tokens."""
|
|
31
|
+
return restore(text, self.key)
|
|
32
|
+
|
|
33
|
+
def wrap(self, fn: Callable[[str], str]) -> Callable[[str], str]:
|
|
34
|
+
"""Wrap a text -> text function (e.g. an LLM call): scrub the input, restore the output."""
|
|
35
|
+
def wrapped(prompt: str, *args: Any, **kw: Any) -> str:
|
|
36
|
+
return self.restore(fn(self.scrub(prompt), *args, **kw))
|
|
37
|
+
return wrapped
|
|
38
|
+
|
|
39
|
+
def langchain(self):
|
|
40
|
+
"""Return (scrub, restore) as LangChain runnables: chain = scrub | prompt | llm | parser | restore"""
|
|
41
|
+
from langchain_core.runnables import RunnableLambda
|
|
42
|
+
return RunnableLambda(self.scrub), RunnableLambda(self.restore)
|
scrubpii/server.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""A small HTTP API: pip install "scrubpii[server]" then scrubpii serve
|
|
2
|
+
|
|
3
|
+
POST /redact {"text": "...", "mode": "label|mask|fake|token"} -> {"text": "...", "key": {...}}
|
|
4
|
+
POST /find {"text": "..."} -> {"entities": [...]}
|
|
5
|
+
POST /restore {"text": "...", "key": {...}} -> {"text": "..."}
|
|
6
|
+
GET /health
|
|
7
|
+
Everything runs locally; nothing is sent anywhere.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Dict, Optional
|
|
12
|
+
|
|
13
|
+
from fastapi import FastAPI
|
|
14
|
+
from pydantic import BaseModel
|
|
15
|
+
|
|
16
|
+
from . import MODES, __version__, _apply, find, restore
|
|
17
|
+
|
|
18
|
+
app = FastAPI(title="scrubpii", version=__version__,
|
|
19
|
+
description="Find and redact personal data. Runs locally; nothing leaves this machine.")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class TextIn(BaseModel):
|
|
23
|
+
text: str
|
|
24
|
+
mode: str = "label"
|
|
25
|
+
min_score: float = 0.5
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class RestoreIn(BaseModel):
|
|
29
|
+
text: str
|
|
30
|
+
key: Dict[str, str]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@app.get("/health")
|
|
34
|
+
def health():
|
|
35
|
+
return {"ok": True, "version": __version__}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@app.post("/find")
|
|
39
|
+
def find_route(body: TextIn):
|
|
40
|
+
return {"entities": [e.as_dict() for e in find(body.text, body.min_score)]}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@app.post("/redact")
|
|
44
|
+
def redact_route(body: TextIn):
|
|
45
|
+
if body.mode not in MODES:
|
|
46
|
+
return {"error": f"mode must be one of {MODES}"}
|
|
47
|
+
text, key = _apply(body.text, find(body.text, body.min_score), body.mode)
|
|
48
|
+
return {"text": text, "key": key if body.mode == "token" else None}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@app.post("/restore")
|
|
52
|
+
def restore_route(body: RestoreIn):
|
|
53
|
+
return {"text": restore(body.text, body.key)}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def run(host: str = "127.0.0.1", port: int = 8000):
|
|
57
|
+
import uvicorn
|
|
58
|
+
uvicorn.run(app, host=host, port=port)
|
scrubpii/structured.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Redact structured data: JSON-like objects, CSV text or files, pandas DataFrames.
|
|
2
|
+
|
|
3
|
+
All of them collect every string first and run the model once over the
|
|
4
|
+
batch, which is far faster than redacting value by value.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import csv
|
|
9
|
+
import io
|
|
10
|
+
from typing import Any, Dict, Iterable, List, Optional
|
|
11
|
+
|
|
12
|
+
from . import MODEL_ID, _apply, find_many
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _redact_strings(values: List[str], mode: str, min_score: float, model: str,
|
|
16
|
+
key: Optional[Dict[str, str]]) -> List[str]:
|
|
17
|
+
found = find_many(values, min_score, model)
|
|
18
|
+
return [_apply(v, ents, mode, key)[0] for v, ents in zip(values, found)]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def redact_json(obj: Any, mode: str = "label", fields: Optional[Iterable[str]] = None, min_score: float = 0.5,
|
|
22
|
+
model: str = MODEL_ID, key: Optional[Dict[str, str]] = None) -> Any:
|
|
23
|
+
"""Return a copy of a JSON-like object (dicts, lists, strings) with personal data redacted.
|
|
24
|
+
|
|
25
|
+
fields: only redact string values under these keys (anywhere in the tree).
|
|
26
|
+
Keys themselves and non-string values are left alone.
|
|
27
|
+
"""
|
|
28
|
+
fields = set(fields) if fields else None
|
|
29
|
+
paths, values = [], []
|
|
30
|
+
|
|
31
|
+
def walk(x, path, field):
|
|
32
|
+
if isinstance(x, dict):
|
|
33
|
+
for k, v in x.items():
|
|
34
|
+
walk(v, path + [k], k)
|
|
35
|
+
elif isinstance(x, list):
|
|
36
|
+
for i, v in enumerate(x):
|
|
37
|
+
walk(v, path + [i], field)
|
|
38
|
+
elif isinstance(x, str) and (fields is None or field in fields):
|
|
39
|
+
paths.append(path)
|
|
40
|
+
values.append(x)
|
|
41
|
+
|
|
42
|
+
walk(obj, [], None)
|
|
43
|
+
import copy
|
|
44
|
+
out = copy.deepcopy(obj)
|
|
45
|
+
if key is None and mode == "token":
|
|
46
|
+
key = {}
|
|
47
|
+
for path, new in zip(paths, _redact_strings(values, mode, min_score, model, key)):
|
|
48
|
+
if not path:
|
|
49
|
+
return new
|
|
50
|
+
target = out
|
|
51
|
+
for p in path[:-1]:
|
|
52
|
+
target = target[p]
|
|
53
|
+
target[path[-1]] = new
|
|
54
|
+
return out
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def redact_csv(text: str, mode: str = "label", columns: Optional[Iterable[str]] = None, min_score: float = 0.5,
|
|
58
|
+
model: str = MODEL_ID, key: Optional[Dict[str, str]] = None) -> str:
|
|
59
|
+
"""Redact CSV text. The header row is kept; `columns` limits which columns are redacted."""
|
|
60
|
+
rows = list(csv.reader(io.StringIO(text)))
|
|
61
|
+
if not rows:
|
|
62
|
+
return text
|
|
63
|
+
header, body = rows[0], rows[1:]
|
|
64
|
+
cols = [i for i, h in enumerate(header) if columns is None or h in set(columns)]
|
|
65
|
+
cells = [(r, c) for r in range(len(body)) for c in cols if c < len(body[r]) and body[r][c].strip()]
|
|
66
|
+
if key is None and mode == "token":
|
|
67
|
+
key = {}
|
|
68
|
+
for (r, c), new in zip(cells, _redact_strings([body[r][c] for r, c in cells], mode, min_score, model, key)):
|
|
69
|
+
body[r][c] = new
|
|
70
|
+
buf = io.StringIO()
|
|
71
|
+
csv.writer(buf, lineterminator="\n").writerows([header] + body)
|
|
72
|
+
return buf.getvalue()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def redact_dataframe(df, columns: Optional[Iterable[str]] = None, mode: str = "label", min_score: float = 0.5,
|
|
76
|
+
model: str = MODEL_ID, key: Optional[Dict[str, str]] = None):
|
|
77
|
+
"""Return a copy of a pandas DataFrame with personal data redacted in text columns.
|
|
78
|
+
|
|
79
|
+
columns: which columns to redact (default: every column of strings).
|
|
80
|
+
"""
|
|
81
|
+
out = df.copy()
|
|
82
|
+
if columns is None:
|
|
83
|
+
from pandas.api.types import is_object_dtype, is_string_dtype
|
|
84
|
+
columns = [c for c in out.columns if is_object_dtype(out[c]) or is_string_dtype(out[c])]
|
|
85
|
+
if key is None and mode == "token":
|
|
86
|
+
key = {}
|
|
87
|
+
for c in columns:
|
|
88
|
+
mask = out[c].map(lambda v: isinstance(v, str) and bool(v.strip()))
|
|
89
|
+
vals = out.loc[mask, c].tolist()
|
|
90
|
+
out.loc[mask, c] = _redact_strings(vals, mode, min_score, model, key)
|
|
91
|
+
return out
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: scrubpii
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Find and redact 15 kinds of personal data in English and Spanish text, CSV, JSON and DataFrames, with a fine-tuned DistilBERT model plus checksum rules. Beats Microsoft Presidio on public benchmarks.
|
|
5
|
+
Project-URL: Homepage, https://chadtollison.github.io/redact.html
|
|
6
|
+
Project-URL: Model, https://huggingface.co/ChadTollison/pii-distilbert-v3
|
|
7
|
+
Project-URL: Source, https://github.com/chadtollison/chadtollison.github.io/tree/main/scrubpii
|
|
8
|
+
Author: Michael Chad Tollison
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: data-masking,distilbert,gdpr,ner,pii,presidio,privacy,redaction
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Security
|
|
15
|
+
Classifier: Topic :: Text Processing :: Linguistic
|
|
16
|
+
Requires-Python: >=3.9
|
|
17
|
+
Requires-Dist: torch>=2.6
|
|
18
|
+
Requires-Dist: transformers>=4.40
|
|
19
|
+
Provides-Extra: pandas
|
|
20
|
+
Requires-Dist: pandas>=1.5; extra == 'pandas'
|
|
21
|
+
Provides-Extra: server
|
|
22
|
+
Requires-Dist: fastapi>=0.100; extra == 'server'
|
|
23
|
+
Requires-Dist: uvicorn>=0.20; extra == 'server'
|
|
24
|
+
Provides-Extra: test
|
|
25
|
+
Requires-Dist: fastapi; extra == 'test'
|
|
26
|
+
Requires-Dist: httpx; extra == 'test'
|
|
27
|
+
Requires-Dist: pandas; extra == 'test'
|
|
28
|
+
Requires-Dist: pytest>=7; extra == 'test'
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# scrubpii
|
|
32
|
+
|
|
33
|
+
Find and redact personal data in text with one line of Python.
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install scrubpii
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
from scrubpii import redact
|
|
41
|
+
|
|
42
|
+
redact("Hi, I'm Sarah Johnson. Email sarah.j@example.com or call 6626341142.")
|
|
43
|
+
# "Hi, I'm [PERSON]. Email [EMAIL] or call [PHONE]."
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
It finds **names, addresses, emails, phone numbers, Social Security numbers,
|
|
47
|
+
card numbers, IBANs, passports, driver's licenses, ID numbers, dates of birth,
|
|
48
|
+
usernames, passwords, IP addresses and API keys**, in English and Spanish. A
|
|
49
|
+
fine-tuned DistilBERT model
|
|
50
|
+
([ChadTollison/pii-distilbert-v3](https://huggingface.co/ChadTollison/pii-distilbert-v3))
|
|
51
|
+
does the finding, and rules double-check it: card numbers must pass Luhn,
|
|
52
|
+
IBANs their bank checksum, SSNs the SSA format. The rules also catch what the
|
|
53
|
+
model misses: Luhn-valid card numbers, SSNs, emails, IP addresses, US phone
|
|
54
|
+
numbers with a real area code, valid IBANs, well-known API key formats and
|
|
55
|
+
dates right after "born" or "DOB".
|
|
56
|
+
|
|
57
|
+
## How it compares
|
|
58
|
+
|
|
59
|
+
F1 on held-out public data (full results in
|
|
60
|
+
[benchmarks/compare.md](https://github.com/chadtollison/chadtollison.github.io/blob/main/benchmarks/compare.md)):
|
|
61
|
+
|
|
62
|
+
| Dataset | scrubpii | Microsoft Presidio | spaCy |
|
|
63
|
+
|---|---:|---:|---:|
|
|
64
|
+
| ai4privacy, English | 0.99 | 0.81 | 0.68 |
|
|
65
|
+
| ai4privacy, Spanish | 0.99 | 0.63 | 0.46 |
|
|
66
|
+
| Gretel PII, English | 0.99 | 0.85 | 0.36 |
|
|
67
|
+
| Gretel finance (never trained on) | 0.79 | 0.52 | 0.58 |
|
|
68
|
+
|
|
69
|
+
Presidio is about 4x faster per text.
|
|
70
|
+
|
|
71
|
+
The model (about 260 MB) downloads on first use and is cached, so after that
|
|
72
|
+
it works offline. Nothing is sent anywhere.
|
|
73
|
+
|
|
74
|
+
Try it in your browser first: [chadtollison.github.io/redact.html](https://chadtollison.github.io/redact.html)
|
|
75
|
+
|
|
76
|
+
## Ways to redact
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
text = "Call Sarah Johnson at 662-634-1142."
|
|
80
|
+
|
|
81
|
+
redact(text) # Call [PERSON] at [PHONE].
|
|
82
|
+
redact(text, mode="mask") # Call █████████████ at ████████████.
|
|
83
|
+
redact(text, mode="fake") # Call Avery Brooks at (202) 555-0117.
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Fake values are harmless on purpose: phones use the 555-01xx range reserved
|
|
87
|
+
for fiction, cards are public test numbers, IPs come from the documentation
|
|
88
|
+
range, and SSNs start with 9, which is never issued.
|
|
89
|
+
|
|
90
|
+
### Reversible tokens
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
from scrubpii import tokenize, restore
|
|
94
|
+
|
|
95
|
+
safe, key = tokenize(text)
|
|
96
|
+
# safe == "Call <PERSON_1> at <PHONE_1>."
|
|
97
|
+
# key == {"<PERSON_1>": "Sarah Johnson", "<PHONE_1>": "662-634-1142"}
|
|
98
|
+
|
|
99
|
+
restore(safe, key) # back to the original
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Handy for sending text to another service (an LLM, a ticketing tool) and
|
|
103
|
+
putting the real values back in its reply.
|
|
104
|
+
|
|
105
|
+
### Just find
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
from scrubpii import find
|
|
109
|
+
|
|
110
|
+
for e in find(text):
|
|
111
|
+
print(e.type, e.text, e.start, e.end, round(e.score, 2), e.rule)
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
`min_score` (default 0.5) sets how sure the model must be. Items caught or
|
|
115
|
+
confirmed by a rule are always returned.
|
|
116
|
+
|
|
117
|
+
## Many texts, JSON, CSV and pandas
|
|
118
|
+
|
|
119
|
+
Each of these batches the work, so it's much faster than a loop:
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
from scrubpii import redact_many, redact_json, redact_csv, redact_dataframe
|
|
123
|
+
|
|
124
|
+
redact_many(["Call Sarah at 6626341142", "Email raj@example.com"])
|
|
125
|
+
|
|
126
|
+
redact_json({"user": {"name": "Sarah Johnson", "email": "sarah.j@example.com", "age": 41}})
|
|
127
|
+
# {"user": {"name": "[PERSON]", "email": "[EMAIL]", "age": 41}}
|
|
128
|
+
|
|
129
|
+
redact_csv(open("customers.csv").read(), columns=["name", "email", "notes"])
|
|
130
|
+
|
|
131
|
+
safe_df = redact_dataframe(df, mode="fake") # pip install "scrubpii[pandas]"
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
## Keep personal data out of LLM prompts
|
|
135
|
+
|
|
136
|
+
```python
|
|
137
|
+
from scrubpii import Guard
|
|
138
|
+
|
|
139
|
+
guard = Guard()
|
|
140
|
+
safe = guard.scrub("Write to Sarah Johnson (sarah.j@example.com) about her refund")
|
|
141
|
+
# "Write to <PERSON_1> (<EMAIL_1>) about her refund" <- this is all the LLM sees
|
|
142
|
+
reply = call_your_llm(safe) # "Dear <PERSON_1>, ..."
|
|
143
|
+
guard.restore(reply) # "Dear Sarah Johnson, ..."
|
|
144
|
+
|
|
145
|
+
ask = guard.wrap(call_your_llm) # or wrap the call once
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
The guard keeps one key for the whole conversation, so the same person stays
|
|
149
|
+
`<PERSON_1>` in every turn. With LangChain:
|
|
150
|
+
`scrub, restore = guard.langchain()` then `chain = scrub | prompt | llm | parser | restore`.
|
|
151
|
+
|
|
152
|
+
## HTTP API
|
|
153
|
+
|
|
154
|
+
```bash
|
|
155
|
+
pip install "scrubpii[server]"
|
|
156
|
+
scrubpii serve --port 8000
|
|
157
|
+
curl -X POST localhost:8000/redact -H 'content-type: application/json' \
|
|
158
|
+
-d '{"text": "Call Sarah at 6626341142", "mode": "token"}'
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
Endpoints: `POST /redact`, `POST /find`, `POST /restore`, `GET /health`, with
|
|
162
|
+
interactive docs at `/docs`. It runs on your machine, so nothing is sent anywhere.
|
|
163
|
+
|
|
164
|
+
## Command line
|
|
165
|
+
|
|
166
|
+
```bash
|
|
167
|
+
scrubpii "Call Sarah at 662-634-1142"
|
|
168
|
+
cat notes.txt | scrubpii --mode mask > notes-redacted.txt
|
|
169
|
+
scrubpii --find "My SSN is 123-45-6789"
|
|
170
|
+
scrubpii --file customers.csv --columns name,email -o customers-safe.csv # also .json, .jsonl, .txt
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
## Offline use
|
|
174
|
+
|
|
175
|
+
After the first run the model is cached, and nothing is ever sent anywhere.
|
|
176
|
+
To be sure no network call is attempted, set `HF_HUB_OFFLINE=1`.
|
|
177
|
+
|
|
178
|
+
## Limits
|
|
179
|
+
|
|
180
|
+
This is a research model. It can miss things or flag things by mistake, so
|
|
181
|
+
please don't rely on it alone for compliance work.
|
|
182
|
+
|
|
183
|
+
MIT licensed. Made by Michael Chad Tollison.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
scrubpii/__init__.py,sha256=CiFJzMaD6jg3UKqXZ2xM42Gd8SAEdnn8MEk6VQxT3rE,15996
|
|
2
|
+
scrubpii/area_codes.txt,sha256=bONrZ8CJJaS7FRHVkRyRbDPW9QxqBKXnwrWj5yRmxVk,1807
|
|
3
|
+
scrubpii/cli.py,sha256=0vAr5d0dgDAPWc8CMEMiSdhadpud76_l4pS5naAkwY4,3246
|
|
4
|
+
scrubpii/guard.py,sha256=gnUleaRTW8QZgfqQGadJLNzXFKm_zcFY2P5pCDtSQJQ,1860
|
|
5
|
+
scrubpii/server.py,sha256=ZpPBesy82nyz37jCEZrwszMLWaeanW8a5FzSoYEa8Ws,1655
|
|
6
|
+
scrubpii/structured.py,sha256=jD0vRJT2HlYrpkrOm-vISMcZNaVs9X4b1awpAb5F4cs,3709
|
|
7
|
+
scrubpii-0.3.0.dist-info/METADATA,sha256=2fg9zGrROvsUJwYFkfdcj1x3HQNJlC5pvEiQr-bkBL4,6484
|
|
8
|
+
scrubpii-0.3.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
scrubpii-0.3.0.dist-info/entry_points.txt,sha256=mI67vqWgOt9ZNuhMAIvFG6j3CKgITsJFB5oSj7KKoaY,47
|
|
10
|
+
scrubpii-0.3.0.dist-info/licenses/LICENSE,sha256=81SPqZDJe8gPqYkWuBp85OK3dupu5zrh9Mx8qspOVfg,1078
|
|
11
|
+
scrubpii-0.3.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Michael Chad Tollison
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|