chad-pii 0.1.0__tar.gz

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.
@@ -0,0 +1,4 @@
1
+ __pycache__/
2
+ *.pyc
3
+ build/
4
+ dist/
chad_pii-0.1.0/LICENSE ADDED
@@ -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.
@@ -0,0 +1,106 @@
1
+ Metadata-Version: 2.5
2
+ Name: chad-pii
3
+ Version: 0.1.0
4
+ Summary: Find and redact personal data (names, emails, phones, SSNs, cards, IPs, passports, driver's licenses, API keys, IBANs) with a fine-tuned DistilBERT model plus checksum rules.
5
+ Project-URL: Homepage, https://chadtollison.github.io/redact.html
6
+ Project-URL: Model, https://huggingface.co/ChadTollison/pii-distilbert-v2
7
+ Project-URL: Source, https://github.com/chadtollison/chadtollison.github.io/tree/main/chad-pii
8
+ Author: Michael Chad Tollison
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: data-masking,distilbert,gdpr,ner,pii,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: test
20
+ Requires-Dist: pytest>=7; extra == 'test'
21
+ Description-Content-Type: text/markdown
22
+
23
+ # chad-pii
24
+
25
+ Find and redact personal data in text with one line of Python.
26
+
27
+ ```bash
28
+ pip install chad-pii
29
+ ```
30
+
31
+ ```python
32
+ from chad_pii import redact
33
+
34
+ redact("Hi, I'm Sarah Johnson. Email sarah.j@example.com or call 6626341142.")
35
+ # "Hi, I'm [PERSON]. Email [EMAIL] or call [PHONE]."
36
+ ```
37
+
38
+ It finds **names, emails, phone numbers, Social Security numbers, card
39
+ numbers, IP addresses, passports, driver's licenses, API keys and IBANs**, in
40
+ English and Spanish. A fine-tuned DistilBERT model
41
+ ([ChadTollison/pii-distilbert-v2](https://huggingface.co/ChadTollison/pii-distilbert-v2))
42
+ does the finding, and rules double-check it: card numbers must pass Luhn,
43
+ IBANs their bank checksum, SSNs the SSA format. The rules also catch 10-digit
44
+ US phone numbers with a real area code, valid IBANs and well-known API key
45
+ formats even if the model misses them.
46
+
47
+ The model (about 260 MB) downloads on first use and is cached, so after that
48
+ it works offline. Nothing is sent anywhere.
49
+
50
+ Try it in your browser first: [chadtollison.github.io/redact.html](https://chadtollison.github.io/redact.html)
51
+
52
+ ## Ways to redact
53
+
54
+ ```python
55
+ text = "Call Sarah Johnson at 662-634-1142."
56
+
57
+ redact(text) # Call [PERSON] at [PHONE].
58
+ redact(text, mode="mask") # Call █████████████ at ████████████.
59
+ redact(text, mode="fake") # Call Avery Brooks at (202) 555-0117.
60
+ ```
61
+
62
+ Fake values are harmless on purpose: phones use the 555-01xx range reserved
63
+ for fiction, cards are public test numbers, IPs come from the documentation
64
+ range, and SSNs start with 9, which is never issued.
65
+
66
+ ### Reversible tokens
67
+
68
+ ```python
69
+ from chad_pii import tokenize, restore
70
+
71
+ safe, key = tokenize(text)
72
+ # safe == "Call <PERSON_1> at <PHONE_1>."
73
+ # key == {"<PERSON_1>": "Sarah Johnson", "<PHONE_1>": "662-634-1142"}
74
+
75
+ restore(safe, key) # back to the original
76
+ ```
77
+
78
+ Handy for sending text to another service (an LLM, a ticketing tool) and
79
+ putting the real values back in its reply.
80
+
81
+ ### Just find
82
+
83
+ ```python
84
+ from chad_pii import find
85
+
86
+ for e in find(text):
87
+ print(e.type, e.text, e.start, e.end, round(e.score, 2), e.rule)
88
+ ```
89
+
90
+ `min_score` (default 0.5) sets how sure the model must be. Items caught or
91
+ confirmed by a rule are always returned.
92
+
93
+ ## Command line
94
+
95
+ ```bash
96
+ chad-pii "Call Sarah at 662-634-1142"
97
+ cat notes.txt | chad-pii --mode mask > notes-redacted.txt
98
+ chad-pii --find "My SSN is 123-45-6789"
99
+ ```
100
+
101
+ ## Limits
102
+
103
+ This is a research model. It can miss things or flag things by mistake, so
104
+ please don't rely on it alone for compliance work.
105
+
106
+ MIT licensed. Made by Michael Chad Tollison.
@@ -0,0 +1,84 @@
1
+ # chad-pii
2
+
3
+ Find and redact personal data in text with one line of Python.
4
+
5
+ ```bash
6
+ pip install chad-pii
7
+ ```
8
+
9
+ ```python
10
+ from chad_pii import redact
11
+
12
+ redact("Hi, I'm Sarah Johnson. Email sarah.j@example.com or call 6626341142.")
13
+ # "Hi, I'm [PERSON]. Email [EMAIL] or call [PHONE]."
14
+ ```
15
+
16
+ It finds **names, emails, phone numbers, Social Security numbers, card
17
+ numbers, IP addresses, passports, driver's licenses, API keys and IBANs**, in
18
+ English and Spanish. A fine-tuned DistilBERT model
19
+ ([ChadTollison/pii-distilbert-v2](https://huggingface.co/ChadTollison/pii-distilbert-v2))
20
+ does the finding, and rules double-check it: card numbers must pass Luhn,
21
+ IBANs their bank checksum, SSNs the SSA format. The rules also catch 10-digit
22
+ US phone numbers with a real area code, valid IBANs and well-known API key
23
+ formats even if the model misses them.
24
+
25
+ The model (about 260 MB) downloads on first use and is cached, so after that
26
+ it works offline. Nothing is sent anywhere.
27
+
28
+ Try it in your browser first: [chadtollison.github.io/redact.html](https://chadtollison.github.io/redact.html)
29
+
30
+ ## Ways to redact
31
+
32
+ ```python
33
+ text = "Call Sarah Johnson at 662-634-1142."
34
+
35
+ redact(text) # Call [PERSON] at [PHONE].
36
+ redact(text, mode="mask") # Call █████████████ at ████████████.
37
+ redact(text, mode="fake") # Call Avery Brooks at (202) 555-0117.
38
+ ```
39
+
40
+ Fake values are harmless on purpose: phones use the 555-01xx range reserved
41
+ for fiction, cards are public test numbers, IPs come from the documentation
42
+ range, and SSNs start with 9, which is never issued.
43
+
44
+ ### Reversible tokens
45
+
46
+ ```python
47
+ from chad_pii import tokenize, restore
48
+
49
+ safe, key = tokenize(text)
50
+ # safe == "Call <PERSON_1> at <PHONE_1>."
51
+ # key == {"<PERSON_1>": "Sarah Johnson", "<PHONE_1>": "662-634-1142"}
52
+
53
+ restore(safe, key) # back to the original
54
+ ```
55
+
56
+ Handy for sending text to another service (an LLM, a ticketing tool) and
57
+ putting the real values back in its reply.
58
+
59
+ ### Just find
60
+
61
+ ```python
62
+ from chad_pii import find
63
+
64
+ for e in find(text):
65
+ print(e.type, e.text, e.start, e.end, round(e.score, 2), e.rule)
66
+ ```
67
+
68
+ `min_score` (default 0.5) sets how sure the model must be. Items caught or
69
+ confirmed by a rule are always returned.
70
+
71
+ ## Command line
72
+
73
+ ```bash
74
+ chad-pii "Call Sarah at 662-634-1142"
75
+ cat notes.txt | chad-pii --mode mask > notes-redacted.txt
76
+ chad-pii --find "My SSN is 123-45-6789"
77
+ ```
78
+
79
+ ## Limits
80
+
81
+ This is a research model. It can miss things or flag things by mistake, so
82
+ please don't rely on it alone for compliance work.
83
+
84
+ MIT licensed. Made by Michael Chad Tollison.
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.24"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "chad-pii"
7
+ version = "0.1.0"
8
+ description = "Find and redact personal data (names, emails, phones, SSNs, cards, IPs, passports, driver's licenses, API keys, IBANs) with a fine-tuned DistilBERT model plus checksum rules."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ authors = [{ name = "Michael Chad Tollison" }]
13
+ keywords = ["pii", "redaction", "privacy", "ner", "distilbert", "gdpr", "data-masking"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Topic :: Security",
17
+ "Topic :: Text Processing :: Linguistic",
18
+ "Intended Audience :: Developers",
19
+ ]
20
+ dependencies = ["transformers>=4.40", "torch>=2.6"]
21
+
22
+ [project.optional-dependencies]
23
+ test = ["pytest>=7"]
24
+
25
+ [project.scripts]
26
+ chad-pii = "chad_pii.cli:main"
27
+
28
+ [project.urls]
29
+ Homepage = "https://chadtollison.github.io/redact.html"
30
+ Model = "https://huggingface.co/ChadTollison/pii-distilbert-v2"
31
+ Source = "https://github.com/chadtollison/chadtollison.github.io/tree/main/chad-pii"
32
+
33
+ [tool.hatch.build.targets.wheel]
34
+ packages = ["src/chad_pii"]
@@ -0,0 +1,302 @@
1
+ """Find and redact personal data in text.
2
+
3
+ >>> from chad_pii 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-v2) 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 re
20
+ from dataclasses import dataclass
21
+ from pathlib import Path
22
+ from typing import Dict, List, Optional, Tuple
23
+
24
+ __all__ = ["Entity", "find", "redact", "tokenize", "restore", "MODEL_ID"]
25
+ __version__ = "0.1.0"
26
+
27
+ MODEL_ID = "ChadTollison/pii-distilbert-v2"
28
+ MODES = ("label", "mask", "fake", "token")
29
+
30
+ _pipeline = None
31
+ _pipeline_id = None
32
+
33
+
34
+ @dataclass
35
+ class Entity:
36
+ type: str
37
+ text: str
38
+ start: int
39
+ end: int
40
+ score: float
41
+ rule: Optional[str] = None # why a rule found or confirmed it, if one did
42
+
43
+ def as_dict(self) -> dict:
44
+ return {"type": self.type, "text": self.text, "start": self.start, "end": self.end,
45
+ "score": round(self.score, 4), "rule": self.rule}
46
+
47
+
48
+ # ---------------------------------------------------------------- checks
49
+ AREA_CODES = frozenset((Path(__file__).parent / "area_codes.txt").read_text().split())
50
+ PHONE_RE = re.compile(r"(?:\+?1[\s.-]?)?(?:\(\d{3}\)|\b\d{3})[\s.-]?\d{3}[\s.-]?\d{4}\b")
51
+ IBAN_RE = re.compile(r"\b[A-Z]{2}\d{2}(?: ?[A-Z0-9]{4}){2,7}(?: ?[A-Z0-9]{1,4})?\b")
52
+ API_KEY_RE = re.compile(
53
+ r"\b(?:(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{16,}|sk-(?:proj-)?[A-Za-z0-9_-]{32,}|AKIA[0-9A-Z]{16}"
54
+ r"|gh[pousr]_[A-Za-z0-9]{30,}|xox[abprs]-[A-Za-z0-9-]{20,}|AIza[0-9A-Za-z_-]{35})")
55
+ SHAPES = {
56
+ "EMAIL": re.compile(r"[\w.%+-]+@[\w.-]+\.[^\W\d_]{2,}"),
57
+ "PHONE": PHONE_RE,
58
+ "SSN": re.compile(r"\b\d{3}-\d{2}-\d{4}\b"),
59
+ "CREDIT_CARD": re.compile(r"\b\d{4}(?:[ -]?\d{4}){2}[ -]?\d{1,7}\b"),
60
+ "IP_ADDRESS": re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b"),
61
+ "IBAN": IBAN_RE,
62
+ "API_KEY": API_KEY_RE,
63
+ }
64
+
65
+
66
+ def luhn_ok(s: str) -> bool:
67
+ digits = [int(c) for c in s if c.isdigit()]
68
+ if not 13 <= len(digits) <= 19:
69
+ return False
70
+ total = 0
71
+ for i, d in enumerate(reversed(digits)):
72
+ if i % 2:
73
+ d *= 2
74
+ d -= 9 if d > 9 else 0
75
+ total += d
76
+ return total % 10 == 0
77
+
78
+
79
+ def iban_ok(s: str) -> bool:
80
+ v = re.sub(r"\s+", "", s).upper()
81
+ if not re.fullmatch(r"[A-Z]{2}\d{2}[A-Z0-9]{10,30}", v):
82
+ return False
83
+ return int("".join(str(int(c, 36)) for c in v[4:] + v[:4])) % 97 == 1
84
+
85
+
86
+ def ssn_ok(s: str) -> bool:
87
+ m = re.fullmatch(r"(\d{3})-?(\d{2})-?(\d{4})", s.strip())
88
+ return bool(m) and m[1] not in ("000", "666") and m[1][0] != "9" and m[2] != "00" and m[3] != "0000"
89
+
90
+
91
+ def us_phone_ok(s: str) -> bool:
92
+ d = re.sub(r"\D", "", s)
93
+ if len(d) == 11 and d[0] == "1":
94
+ d = d[1:]
95
+ return len(d) == 10 and d[:3] in AREA_CODES and d[3] in "23456789"
96
+
97
+
98
+ def _valid(e: Entity) -> bool:
99
+ t, s = e.type, e.text
100
+ if t == "CREDIT_CARD":
101
+ return luhn_ok(s)
102
+ if t == "SSN":
103
+ return ssn_ok(s)
104
+ if t == "IBAN":
105
+ return iban_ok(s)
106
+ if t == "PHONE":
107
+ return len(re.sub(r"\D", "", s)) >= 7
108
+ if t == "EMAIL":
109
+ return bool(re.fullmatch(r"[^\s@]+@[^\s@]+\.[^\s@]{2,}", s))
110
+ if t == "IP_ADDRESS":
111
+ parts = s.split(".")
112
+ return len(parts) == 4 and all(p.isdigit() and int(p) <= 255 for p in parts)
113
+ return True
114
+
115
+
116
+ # ---------------------------------------------------------------- model
117
+ def _get_pipeline(model: str):
118
+ global _pipeline, _pipeline_id
119
+ if _pipeline is None or _pipeline_id != model:
120
+ from transformers import AutoTokenizer, pipeline
121
+ tok = AutoTokenizer.from_pretrained(model, model_input_names=["input_ids", "attention_mask"])
122
+ _pipeline = pipeline("token-classification", model=model, tokenizer=tok,
123
+ aggregation_strategy="max", stride=64)
124
+ _pipeline_id = model
125
+ return _pipeline
126
+
127
+
128
+ def _model_entities(text: str, model: str) -> List[Entity]:
129
+ out = []
130
+ for item in _get_pipeline(model)(text):
131
+ s, e = item["start"], item["end"]
132
+ while s < e and text[s].isspace():
133
+ s += 1
134
+ while e > s and text[e - 1].isspace():
135
+ e -= 1
136
+ if e > s:
137
+ out.append(Entity(item["entity_group"], text[s:e], s, e, float(item["score"])))
138
+ # Join a name split into pieces ("José" + "Álvarez").
139
+ joined: List[Entity] = []
140
+ for ent in out:
141
+ prev = joined[-1] if joined else None
142
+ if prev and prev.type == ent.type and text[prev.end:ent.start] in ("", " "):
143
+ prev.end, prev.text = ent.end, text[prev.start:ent.end]
144
+ prev.score = min(prev.score, ent.score)
145
+ else:
146
+ joined.append(ent)
147
+ return joined
148
+
149
+
150
+ def _grow(ents: List[Entity], text: str) -> None:
151
+ """Grow a partly-found item to the full email, phone, card... it is part of."""
152
+ for e in ents:
153
+ rx = SHAPES.get(e.type)
154
+ if not rx:
155
+ continue
156
+ for m in rx.finditer(text):
157
+ if m.start() < e.end and m.end() > e.start:
158
+ e.start, e.end = min(e.start, m.start()), max(e.end, m.end())
159
+ e.text = text[e.start:e.end]
160
+ break
161
+ if e.type in ("SSN", "PHONE"):
162
+ digits = re.sub(r"\D", "", e.text)
163
+ if re.fullmatch(r"\d{3}-\d{2}-\d{4}", e.text.strip()):
164
+ e.type = "SSN"
165
+ elif 10 <= len(digits) <= 11:
166
+ e.type = "PHONE"
167
+
168
+
169
+ def _rules(ents: List[Entity], text: str) -> List[Entity]:
170
+ checks = [("PHONE", PHONE_RE, us_phone_ok, "real US/Canada area code"),
171
+ ("IBAN", IBAN_RE, iban_ok, "IBAN checksum"),
172
+ ("API_KEY", API_KEY_RE, lambda s: True, "known API key format")]
173
+ for typ, rx, ok, why in checks:
174
+ for m in rx.finditer(text):
175
+ if not ok(m.group()):
176
+ continue
177
+ hits = [e for e in ents if e.start < m.end() and e.end > m.start()]
178
+ if not hits:
179
+ ents.append(Entity(typ, m.group(), m.start(), m.end(), 1.0, why))
180
+ for e in hits:
181
+ # A phone rule only overrides the model when the model's own
182
+ # label fails its check (e.g. "card number" that fails Luhn).
183
+ if typ == "PHONE" and e.type != "PHONE" and _valid(e):
184
+ continue
185
+ e.type, e.rule, e.score = typ, why, 1.0
186
+ e.start, e.end = min(e.start, m.start()), max(e.end, m.end())
187
+ e.text = text[e.start:e.end]
188
+ ents.sort(key=lambda e: (e.start, -e.end))
189
+ kept: List[Entity] = []
190
+ for e in ents:
191
+ if kept and e.start < kept[-1].end:
192
+ k = kept[-1]
193
+ if e.end > k.end:
194
+ k.end, k.text = e.end, text[k.start:e.end]
195
+ continue
196
+ kept.append(e)
197
+ return kept
198
+
199
+
200
+ def find(text: str, min_score: float = 0.5, model: str = MODEL_ID) -> List[Entity]:
201
+ """Return the personal data found in `text`, in order.
202
+
203
+ Items the rules found or confirmed are always returned. Others need a model
204
+ confidence of at least `min_score`, and must pass their type's check
205
+ (Luhn for cards, checksum for IBANs, format for SSNs...).
206
+ """
207
+ if not text.strip():
208
+ return []
209
+ ents = _model_entities(text, model)
210
+ _grow(ents, text)
211
+ ents = _rules(ents, text)
212
+ return [e for e in ents if e.rule or (e.score >= min_score and _valid(e))]
213
+
214
+
215
+ # ---------------------------------------------------------------- redaction
216
+ _FIRST = ["Alex", "Jordan", "Taylor", "Morgan", "Casey", "Riley", "Jamie", "Avery", "Quinn", "Rowan", "Drew", "Skyler"]
217
+ _LAST = ["Rivera", "Brooks", "Hayes", "Bennett", "Foster", "Reed", "Parker", "Ellis", "Price", "Shaw", "Lane", "Cole"]
218
+ _CARDS = ["4111 1111 1111 1111", "5500 0000 0000 0004", "3782 822463 10005", "6011 1111 1111 1117"]
219
+ _IBANS = ["GB82 WEST 1234 5698 7654 32", "DE89 3704 0044 0532 0130 00", "FR14 2004 1010 0505 0001 3M02 606"]
220
+
221
+
222
+ def _h(s: str) -> int:
223
+ return int(hashlib.sha256(s.encode()).hexdigest()[:12], 16)
224
+
225
+
226
+ def fake_for(e: Entity) -> str:
227
+ """A realistic but harmless stand-in. The same input always gets the same fake."""
228
+ h = _h(e.type + "|" + e.text)
229
+ first, last = _FIRST[h % 12], _LAST[(h >> 8) % 12]
230
+ same = lambda x: re.sub(r"\s", "", x) == re.sub(r"\s", "", e.text)
231
+ if e.type == "PERSON":
232
+ return f"{first} {last}" if " " in e.text.strip() else first
233
+ if e.type == "EMAIL":
234
+ return f"{first}.{last}@example.com".lower()
235
+ if e.type == "PHONE":
236
+ return f"(202) 555-01{h % 100:02d}" # 555-0100..0199 are reserved for fiction
237
+ if e.type == "SSN":
238
+ return f"9{h % 100:02d}-{(h >> 7) % 90 + 10}-{(h >> 3) % 9000 + 1000}" # SSNs never start with 9
239
+ if e.type == "CREDIT_CARD":
240
+ c = [x for x in _CARDS if not same(x)]
241
+ return c[h % len(c)]
242
+ if e.type == "IP_ADDRESS":
243
+ return f"203.0.113.{h % 254 + 1}" # documentation-only range
244
+ if e.type == "IBAN":
245
+ c = [x for x in _IBANS if not same(x)]
246
+ return c[h % len(c)]
247
+ if e.type == "PASSPORT":
248
+ return f"X{h % 10**8:08d}"
249
+ if e.type == "DRIVER_LICENSE":
250
+ return f"D{h % 10**7:07d}"
251
+ if e.type == "API_KEY":
252
+ return f"sk_example_{h:016x}"[:27]
253
+ return f"[{e.type}]"
254
+
255
+
256
+ def _apply(text: str, ents: List[Entity], mode: str) -> Tuple[str, Dict[str, str]]:
257
+ if mode not in MODES:
258
+ raise ValueError(f"mode must be one of {MODES}")
259
+ key: Dict[str, str] = {}
260
+ tokens: Dict[Tuple[str, str], str] = {}
261
+ counts: Dict[str, int] = {}
262
+ out, pos = [], 0
263
+ for e in ents:
264
+ if mode == "label":
265
+ rep = f"[{e.type}]"
266
+ elif mode == "mask":
267
+ rep = "█" * len(e.text)
268
+ elif mode == "fake":
269
+ rep = fake_for(e)
270
+ else:
271
+ if (e.type, e.text) not in tokens:
272
+ counts[e.type] = counts.get(e.type, 0) + 1
273
+ tokens[(e.type, e.text)] = f"<{e.type}_{counts[e.type]}>"
274
+ key[tokens[(e.type, e.text)]] = e.text
275
+ rep = tokens[(e.type, e.text)]
276
+ out += [text[pos:e.start], rep]
277
+ pos = e.end
278
+ out.append(text[pos:])
279
+ return "".join(out), key
280
+
281
+
282
+ def redact(text: str, mode: str = "label", min_score: float = 0.5, model: str = MODEL_ID) -> str:
283
+ """Return `text` with personal data replaced.
284
+
285
+ mode="label" -> [PHONE] mode="mask" -> ████ mode="fake" -> (202) 555-0142
286
+ mode="token" -> <PHONE_1> (use tokenize() to also get the key back)
287
+ """
288
+ return _apply(text, find(text, min_score, model), mode)[0]
289
+
290
+
291
+ def tokenize(text: str, min_score: float = 0.5, model: str = MODEL_ID) -> Tuple[str, Dict[str, str]]:
292
+ """Replace personal data with tokens like <PERSON_1>. Returns (text, key).
293
+
294
+ Keep the key somewhere safe; restore(text, key) puts the real values back.
295
+ The same value always gets the same token within one call.
296
+ """
297
+ return _apply(text, find(text, min_score, model), "token")
298
+
299
+
300
+ def restore(text: str, key: Dict[str, str]) -> str:
301
+ """Put real values back into tokenized text."""
302
+ return re.sub(r"<[A-Z_]+_\d+>", lambda m: key.get(m.group(), m.group()), text)
@@ -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
@@ -0,0 +1,33 @@
1
+ """chad-pii on the command line.
2
+
3
+ chad-pii "Call Sarah at 662-634-1142" -> Call [PERSON] at [PHONE]
4
+ cat notes.txt | chad-pii --mode mask -> redacts standard input
5
+ chad-pii --find "..." -> lists what it found as JSON
6
+ """
7
+ import argparse
8
+ import json
9
+ import sys
10
+
11
+ from . import MODES, find, redact, tokenize
12
+
13
+
14
+ def main(argv=None):
15
+ ap = argparse.ArgumentParser(prog="chad-pii", description="Find and redact personal data in text.")
16
+ ap.add_argument("text", nargs="?", help="text to redact (default: read standard input)")
17
+ ap.add_argument("--mode", choices=MODES, default="label", help="how to replace what it finds (default: label)")
18
+ ap.add_argument("--min-score", type=float, default=0.5, help="model confidence needed (default: 0.5)")
19
+ ap.add_argument("--find", action="store_true", help="print what it found as JSON instead of redacting")
20
+ a = ap.parse_args(argv)
21
+ text = a.text if a.text is not None else sys.stdin.read()
22
+ if a.find:
23
+ print(json.dumps([e.as_dict() for e in find(text, a.min_score)], indent=2, ensure_ascii=False))
24
+ elif a.mode == "token":
25
+ out, key = tokenize(text, a.min_score)
26
+ print(out)
27
+ print(json.dumps(key, indent=2, ensure_ascii=False), file=sys.stderr)
28
+ else:
29
+ print(redact(text, a.mode, a.min_score))
30
+
31
+
32
+ if __name__ == "__main__":
33
+ main()
@@ -0,0 +1,40 @@
1
+ """Tests that don't need the model: a fake pipeline stands in for it."""
2
+ import chad_pii as cp
3
+
4
+
5
+ def fake_model(found):
6
+ def run(text, model):
7
+ out = []
8
+ for typ, s, score in found:
9
+ i = text.index(s)
10
+ out.append(cp.Entity(typ, s, i, i + len(s), score))
11
+ return out
12
+ return run
13
+
14
+
15
+ def test_checks():
16
+ assert cp.luhn_ok("4111 1111 1111 1111") and not cp.luhn_ok("1234 5678 9012 3456")
17
+ assert cp.iban_ok("GB82 WEST 1234 5698 7654 32") and not cp.iban_ok("GB00 WEST 1234 5698 7654 32")
18
+ assert cp.ssn_ok("123-45-6789") and not cp.ssn_ok("666-45-6789")
19
+ assert cp.us_phone_ok("6626341142") and not cp.us_phone_ok("4567891234")
20
+
21
+
22
+ def test_rules_and_modes(monkeypatch):
23
+ text = "Sarah Johnson: 6626341142, card 1234 5678 9012 3456, key AKIAIOSFODNN7EXAMPLE, IBAN GB82 WEST 1234 5698 7654 32."
24
+ monkeypatch.setattr(cp, "_model_entities", fake_model([("PERSON", "Sarah Johnson", 0.99),
25
+ ("CREDIT_CARD", "1234 5678 9012 3456", 0.9)]))
26
+ found = {(e.type, e.text) for e in cp.find(text)}
27
+ assert found == {("PERSON", "Sarah Johnson"), ("PHONE", "6626341142"),
28
+ ("API_KEY", "AKIAIOSFODNN7EXAMPLE"), ("IBAN", "GB82 WEST 1234 5698 7654 32")} # bad card dropped
29
+ assert cp.redact(text) == "[PERSON]: [PHONE], card 1234 5678 9012 3456, key [API_KEY], IBAN [IBAN]."
30
+ safe, key = cp.tokenize(text)
31
+ assert "<PERSON_1>" in safe and cp.restore(safe, key) == text
32
+ fake = cp.redact(text, mode="fake")
33
+ assert "Sarah" not in fake and "6626341142" not in fake and "GB82 WEST" not in fake
34
+ assert cp.redact(text, mode="mask").startswith("█" * 13 + ":")
35
+
36
+
37
+ def test_grow_partial_email(monkeypatch):
38
+ text = "Email sarah.j@example.com now"
39
+ monkeypatch.setattr(cp, "_model_entities", fake_model([("EMAIL", "sarah.j", 0.8)]))
40
+ assert cp.redact(text) == "Email [EMAIL] now"