tinyzpii 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.
- tinyzpii-0.1.0/PKG-INFO +251 -0
- tinyzpii-0.1.0/README.md +228 -0
- tinyzpii-0.1.0/pyproject.toml +37 -0
- tinyzpii-0.1.0/setup.cfg +4 -0
- tinyzpii-0.1.0/tests/test_detector.py +110 -0
- tinyzpii-0.1.0/tinyzpii/__init__.py +6 -0
- tinyzpii-0.1.0/tinyzpii/__main__.py +26 -0
- tinyzpii-0.1.0/tinyzpii/align.py +17 -0
- tinyzpii-0.1.0/tinyzpii/detector.py +247 -0
- tinyzpii-0.1.0/tinyzpii/features.py +144 -0
- tinyzpii-0.1.0/tinyzpii/labels.py +81 -0
- tinyzpii-0.1.0/tinyzpii/model.py +118 -0
- tinyzpii-0.1.0/tinyzpii/rules.py +165 -0
- tinyzpii-0.1.0/tinyzpii/weights.npz +0 -0
- tinyzpii-0.1.0/tinyzpii.egg-info/PKG-INFO +251 -0
- tinyzpii-0.1.0/tinyzpii.egg-info/SOURCES.txt +18 -0
- tinyzpii-0.1.0/tinyzpii.egg-info/dependency_links.txt +1 -0
- tinyzpii-0.1.0/tinyzpii.egg-info/entry_points.txt +2 -0
- tinyzpii-0.1.0/tinyzpii.egg-info/requires.txt +14 -0
- tinyzpii-0.1.0/tinyzpii.egg-info/top_level.txt +1 -0
tinyzpii-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tinyzpii
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Blazing-fast, GPU-free, tokenizer-free PII detection and redaction (EN + PT-BR). Pure numpy inference, calibrated confidence, 8 MB bundled weights.
|
|
5
|
+
Author: Carlo Moro
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://huggingface.co/cnmoro/tinyzpii
|
|
8
|
+
Project-URL: Repository, https://github.com/cnmoro/tinyzpii
|
|
9
|
+
Keywords: pii,redaction,anonymization,privacy,ner,lgpd,gdpr,portuguese
|
|
10
|
+
Requires-Python: >=3.9
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
Requires-Dist: numpy>=1.20
|
|
13
|
+
Requires-Dist: threadpoolctl>=3.1
|
|
14
|
+
Provides-Extra: train
|
|
15
|
+
Requires-Dist: torch; extra == "train"
|
|
16
|
+
Requires-Dist: pyarrow; extra == "train"
|
|
17
|
+
Requires-Dist: datasets; extra == "train"
|
|
18
|
+
Provides-Extra: teacher
|
|
19
|
+
Requires-Dist: gliner2; extra == "teacher"
|
|
20
|
+
Requires-Dist: transformers; extra == "teacher"
|
|
21
|
+
Provides-Extra: hub
|
|
22
|
+
Requires-Dist: huggingface_hub>=0.20; extra == "hub"
|
|
23
|
+
|
|
24
|
+
# tinyzpii
|
|
25
|
+
|
|
26
|
+
A **GPU-free, tokenizer-free PII detector** for English and Brazilian
|
|
27
|
+
Portuguese. A sibling of [tinyzchunk](https://github.com/cnmoro/tinyzchunk):
|
|
28
|
+
trained once on a GPU, shipped as **numpy-only** inference with **8 MB of
|
|
29
|
+
bundled weights**. No torch, no transformers, no tokenizer, no download.
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install git+https://github.com/cnmoro/tinyzpii
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from tinyzpii import PIIDetector
|
|
37
|
+
|
|
38
|
+
det = PIIDetector()
|
|
39
|
+
text = "Meu nome é Carlos Eduardo Pereira, CPF 529.982.247-25, tel (31) 99876-5432."
|
|
40
|
+
|
|
41
|
+
for e in det.detect(text):
|
|
42
|
+
print(e.label, e.text, f"{e.confidence}%")
|
|
43
|
+
# PERSON Carlos Eduardo Pereira 99.5%
|
|
44
|
+
# ID 529.982.247-25 99.0%
|
|
45
|
+
# PHONE (31) 99876-5432 99.5%
|
|
46
|
+
|
|
47
|
+
det.redact(text)
|
|
48
|
+
# 'Meu nome é [PERSON], CPF [ID], tel [PHONE].'
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
python -m tinyzpii document.txt # redacted text
|
|
53
|
+
python -m tinyzpii document.txt --json # entities with offsets and confidence
|
|
54
|
+
cat log.txt | python -m tinyzpii --mask # **** instead of [LABEL]
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Speed
|
|
58
|
+
|
|
59
|
+
~**2.3 µs per character on a single CPU core** end to end (featurization,
|
|
60
|
+
network, decoding, regex rules), i.e. ~0.44 MB/s per core. A 1 kB message is
|
|
61
|
+
~2 ms.
|
|
62
|
+
|
|
63
|
+
For comparison, the GLiNER2-PII model (205M params) needs ~1,070 µs/char on
|
|
64
|
+
one CPU thread and ~50 µs/char on an RTX 2070 GPU: tinyzpii on one CPU core is
|
|
65
|
+
**~475× faster than it on CPU** and ~20× faster than it on GPU.
|
|
66
|
+
|
|
67
|
+
## Entity types
|
|
68
|
+
|
|
69
|
+
| label | covers |
|
|
70
|
+
|---|---|
|
|
71
|
+
| `PERSON` | first, last and full names |
|
|
72
|
+
| `ORG` | company / organisation names |
|
|
73
|
+
| `EMAIL` | e-mail addresses |
|
|
74
|
+
| `PHONE` | phone and fax numbers (BR, US and international formats) |
|
|
75
|
+
| `ADDRESS` | street + number (+ complement: apto, sala, Apt 12B) |
|
|
76
|
+
| `LOCATION` | city, state/UF, county, coordinates |
|
|
77
|
+
| `POSTCODE` | ZIP / CEP |
|
|
78
|
+
| `DATE` | dates, dates of birth |
|
|
79
|
+
| `AGE` | ages |
|
|
80
|
+
| `ID` | CPF, CNPJ, RG, CNH, SSN, passport, licences, PIS, CNS, plates, record numbers... |
|
|
81
|
+
| `CARD` | credit/debit card numbers, CVV |
|
|
82
|
+
| `BANK` | account, agency, routing, IBAN, SWIFT, PIX keys |
|
|
83
|
+
| `URL` | URLs |
|
|
84
|
+
| `NETWORK` | IPv4, IPv6, MAC |
|
|
85
|
+
| `USERNAME` | user names / handles |
|
|
86
|
+
| `SECRET` | passwords, PINs, API keys, cookies |
|
|
87
|
+
|
|
88
|
+
## API keys and secrets
|
|
89
|
+
|
|
90
|
+
Secrets get a dedicated deterministic layer on top of the model, because a
|
|
91
|
+
missed key is costly:
|
|
92
|
+
|
|
93
|
+
- **Known provider formats**: OpenAI / Anthropic (`sk-…`), AWS access key ids
|
|
94
|
+
(`AKIA…`), GitHub (`ghp_…`, `github_pat_…`), GitLab (`glpat-…`), Slack
|
|
95
|
+
(`xox?-…`), Stripe (`sk_live_…`), Google (`AIza…`), HuggingFace (`hf_…`),
|
|
96
|
+
npm, SendGrid, JWTs and PEM private-key blocks. Detected anywhere, including
|
|
97
|
+
with no context at all.
|
|
98
|
+
- **Keyword assignments**: `api_key = "…"`, `TOKEN=…`, `password: …`,
|
|
99
|
+
`Authorization: Bearer …`, `senha: …`, `minha chave da API é …`. Only the
|
|
100
|
+
value is tagged, and it must look like a credential (has a digit, mixed
|
|
101
|
+
case or a symbol), so "your password is correct" is not flagged.
|
|
102
|
+
- **High-entropy strings**: 32+ chars of mixed upper/lower/digits with
|
|
103
|
+
≥4.2 bits/char of entropy (e.g. AWS secret keys) are flagged even without context.
|
|
104
|
+
- The model itself also tags passwords, PINs, cookies and keys from context.
|
|
105
|
+
|
|
106
|
+
`scripts/probe_secrets.py` checks 14 key formats in 8 contexts (EN/PT, bare,
|
|
107
|
+
`export X=`, JSON, Bearer): **109/112 detected in full**, and **0/9**
|
|
108
|
+
look-alikes (git SHAs, UUIDs, long URLs and paths, placeholders) flagged. The
|
|
109
|
+
3 misses are deliberate: a bare 64-char hex string with no keyword nearby is
|
|
110
|
+
indistinguishable from a SHA-256 hash. With any keyword (`key=`, `token:`,
|
|
111
|
+
`Bearer`) it is detected.
|
|
112
|
+
|
|
113
|
+
## Confidence
|
|
114
|
+
|
|
115
|
+
Every entity has a `confidence` (percent) that is **calibrated**: it is the
|
|
116
|
+
probability that the *exact span and label* are right, fitted with isotonic
|
|
117
|
+
regression on a held-out split. On the test split the expected calibration
|
|
118
|
+
error is **0.003**: of the spans reported at ≥90%, 99% are exactly right,
|
|
119
|
+
and of those reported around 75%, about 70% are.
|
|
120
|
+
|
|
121
|
+
Use it to trade recall for precision without retraining:
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
[e for e in det.detect(text) if e.confidence >= 80]
|
|
125
|
+
PIIDetector(threshold=0.3) # lower piece threshold = higher recall
|
|
126
|
+
PIIDetector(labels=["PERSON", "ID", "EMAIL"])
|
|
127
|
+
PIIDetector(use_rules=False) # model only
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
## How it works
|
|
131
|
+
|
|
132
|
+
```
|
|
133
|
+
text ─► pieces ─► hashed features ─► embeddings ─► 6 dilated residual convs ─► BIO tags ─► spans
|
|
134
|
+
(\w+ runs word, shape, (int8) (96 wide, receptive │
|
|
135
|
+
and symbols) prefix, suffix, field ±18 pieces) ▼
|
|
136
|
+
gap, char trigrams + checksum rules
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
- **Pieces, not characters.** The text is split into maximal word-character
|
|
140
|
+
runs and single symbols. PII boundaries fall on piece boundaries, and
|
|
141
|
+
there are ~4.5× fewer pieces than characters, so the network runs ~4.5×
|
|
142
|
+
less often than a char model would.
|
|
143
|
+
- **Tokenizer-free features.** Each piece is described only by hashed
|
|
144
|
+
features (lower-cased word, case/digit shape like `ddd.ddd.ddd-dd`, 3-char
|
|
145
|
+
prefix/suffix, whitespace gap before it, and a bag of character trigrams),
|
|
146
|
+
so unseen names, typos and accents still get sensible embeddings. All of
|
|
147
|
+
them index a single table, so embedding is one gather.
|
|
148
|
+
- **Network.** 6 dilated residual 1-D convolutions (dilations 1,2,4,8,1,2)
|
|
149
|
+
over the piece sequence, then a softmax over 33 BIO tags. The whole
|
|
150
|
+
document is processed in one pass with no windowing.
|
|
151
|
+
- **Decoding.** Spans are grouped by B/I mass, labelled by summed
|
|
152
|
+
probability (so "Belo Horizonte" never splits into ADDRESS + LOCATION),
|
|
153
|
+
grown over glued alphanumeric pieces (a value never ends mid-word:
|
|
154
|
+
`123-45-6789`, `sk-live-9f8a…`), and trimmed of boundary punctuation.
|
|
155
|
+
- **Rules.** Checksum-validated regexes for CPF, CNPJ, Luhn card numbers and
|
|
156
|
+
IBAN, plus e-mail, URL, IPv4 and MAC, override overlapping model spans.
|
|
157
|
+
|
|
158
|
+
## Evaluation
|
|
159
|
+
|
|
160
|
+
All numbers are from the shipped numpy pipeline (`scripts/eval.py`) on
|
|
161
|
+
held-out documents never seen in training (1,500 per bucket). *Span-F1* needs
|
|
162
|
+
the exact `(start, end, label)`; *char-F1* measures redaction quality: is each
|
|
163
|
+
non-space character inside some PII span, whatever the label.
|
|
164
|
+
|
|
165
|
+
| bucket | span-F1 | char-P | char-R | char-F1 |
|
|
166
|
+
|---|---|---|---|---|
|
|
167
|
+
| ai4privacy openpii, English | 0.974 | 0.992 | 0.998 | 0.995 |
|
|
168
|
+
| ai4privacy openpii, Portuguese | 0.986 | 0.996 | 0.999 | 0.997 |
|
|
169
|
+
| Nemotron-PII (English) | 0.954 | 0.987 | 0.975 | 0.981 |
|
|
170
|
+
| synthetic PT-BR (CPF/RG/PIX/...)\* | 0.985 | 0.998 | 0.999 | 0.998 |
|
|
171
|
+
|
|
172
|
+
\* generated by the same templates as the training synth data (different
|
|
173
|
+
seed), so this bucket is optimistic.
|
|
174
|
+
|
|
175
|
+
Both public datasets are LLM-generated, so there is also a small hand-written
|
|
176
|
+
gold set (`tests/handwritten.txt`) in styles none of the sources use: support
|
|
177
|
+
tickets, court notices, chat messages, logs, medical notes, and plain text with
|
|
178
|
+
many non-PII numbers.
|
|
179
|
+
|
|
180
|
+
| hand-written | span-F1 | char-F1 |
|
|
181
|
+
|---|---|---|
|
|
182
|
+
| Portuguese (20 texts) | 0.927 | 0.975 |
|
|
183
|
+
| English (14 texts) | 0.769 | 0.902 |
|
|
184
|
+
|
|
185
|
+
The remaining errors are mostly debatable conventions (years tagged as DATE,
|
|
186
|
+
`MRN 7734120` vs `7734120`) and a few false positives on bare numbers. Per-label span F1 on
|
|
187
|
+
the main test set: PERSON 0.99, ID 0.99, EMAIL 0.99, POSTCODE 1.00, DATE 0.99,
|
|
188
|
+
LOCATION 0.98, ADDRESS 0.97, CARD 0.97, PHONE 0.96, SECRET 0.95, AGE 0.94,
|
|
189
|
+
BANK 0.91, NETWORK 0.90, **ORG 0.87** (the weakest).
|
|
190
|
+
|
|
191
|
+
### vs. GLiNER2-PII
|
|
192
|
+
|
|
193
|
+
[fastino/gliner2-privacy-filter-PII-multi](https://huggingface.co/fastino/gliner2-privacy-filter-PII-multi)
|
|
194
|
+
was evaluated as a potential teacher (`scripts/eval_teacher.py`, 150 docs per
|
|
195
|
+
bucket, labels mapped to ours):
|
|
196
|
+
|
|
197
|
+
| bucket | GLiNER2 char-F1 | tinyzpii char-F1 |
|
|
198
|
+
|---|---|---|
|
|
199
|
+
| ai4privacy EN | 0.929 | 0.994 |
|
|
200
|
+
| ai4privacy PT | 0.945 | 0.998 |
|
|
201
|
+
| Nemotron EN | 0.682 | 0.982 |
|
|
202
|
+
|
|
203
|
+
This is not a neutral benchmark: tinyzpii was trained on these datasets'
|
|
204
|
+
label conventions and GLiNER2 was not. It is why the teacher was not used for
|
|
205
|
+
distillation: the ~300k gold-labelled documents are a stronger signal than its
|
|
206
|
+
predictions.
|
|
207
|
+
|
|
208
|
+
## Training data
|
|
209
|
+
|
|
210
|
+
- [nvidia/Nemotron-PII](https://huggingface.co/datasets/nvidia/Nemotron-PII): 100k English documents (train split).
|
|
211
|
+
- [ai4privacy/pii-masking-openpii-1.5m](https://huggingface.co/datasets/ai4privacy/pii-masking-openpii-1.5m): English + Portuguese subset (164k EN, 35k PT).
|
|
212
|
+
- 80k synthetic PT-BR documents (`scripts/build_synth_pt.py`) covering
|
|
213
|
+
Brazilian formats (CPF/CNPJ with valid check digits, RG, CEP, CNH, PIS, CNS,
|
|
214
|
+
Mercosul plates, PIX keys, agência/conta), registration forms, letters,
|
|
215
|
+
chats, legal and medical prose, and **hard negatives**: prices, percentages,
|
|
216
|
+
law numbers, order/protocol numbers, extensions, verification codes.
|
|
217
|
+
|
|
218
|
+
Source labels are mapped into the 16 types in `tinyzpii/labels.py`.
|
|
219
|
+
Non-identifying attributes (occupation, gender, religion, and so on) are
|
|
220
|
+
treated as non-PII.
|
|
221
|
+
|
|
222
|
+
## Reproducing
|
|
223
|
+
|
|
224
|
+
```bash
|
|
225
|
+
pip install -e ".[train]"
|
|
226
|
+
python scripts/prepare_data.py # -> data/unified/{train,dev,test}.jsonl
|
|
227
|
+
python scripts/build_synth_pt.py 80000 data/unified/synth_pt.jsonl
|
|
228
|
+
python scripts/build_synth_pt.py 2000 data/unified/synth_pt_test.jsonl 99
|
|
229
|
+
for s in train dev; do python scripts/build_features.py data/unified/$s.jsonl data/feat/$s.npz; done
|
|
230
|
+
python scripts/build_features.py data/unified/synth_pt.jsonl data/feat/synth_pt.npz
|
|
231
|
+
python scripts/train.py --train data/feat/train.npz data/feat/synth_pt.npz \
|
|
232
|
+
--weights 0.85 0.15 --steps 40000 --hidden 96 --out data/w.npz # ~10 min on an RTX 2070
|
|
233
|
+
python scripts/calibrate.py data/w.npz
|
|
234
|
+
python scripts/quantize.py data/w.npz tinyzpii/weights.npz
|
|
235
|
+
python scripts/eval.py --weights tinyzpii/weights.npz --per_label
|
|
236
|
+
python scripts/eval_handwritten.py -v
|
|
237
|
+
pytest tests/
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
## Limitations
|
|
241
|
+
|
|
242
|
+
- English and Portuguese only. Other Latin-script languages will partly work
|
|
243
|
+
through the shared formats, but are untested.
|
|
244
|
+
- The training text is mostly LLM-generated. Real-world text, especially
|
|
245
|
+
number-dense business prose, produces more false positives than the
|
|
246
|
+
benchmark numbers suggest. Filter by `confidence` if precision matters.
|
|
247
|
+
- `ORG` is the weakest type. Public institutions are only partly covered.
|
|
248
|
+
- It detects PII; it does not guarantee anonymisation. Review before relying
|
|
249
|
+
on it for compliance (LGPD/GDPR).
|
|
250
|
+
|
|
251
|
+
License: Apache-2.0.
|
tinyzpii-0.1.0/README.md
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
# tinyzpii
|
|
2
|
+
|
|
3
|
+
A **GPU-free, tokenizer-free PII detector** for English and Brazilian
|
|
4
|
+
Portuguese. A sibling of [tinyzchunk](https://github.com/cnmoro/tinyzchunk):
|
|
5
|
+
trained once on a GPU, shipped as **numpy-only** inference with **8 MB of
|
|
6
|
+
bundled weights**. No torch, no transformers, no tokenizer, no download.
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
pip install git+https://github.com/cnmoro/tinyzpii
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
```python
|
|
13
|
+
from tinyzpii import PIIDetector
|
|
14
|
+
|
|
15
|
+
det = PIIDetector()
|
|
16
|
+
text = "Meu nome é Carlos Eduardo Pereira, CPF 529.982.247-25, tel (31) 99876-5432."
|
|
17
|
+
|
|
18
|
+
for e in det.detect(text):
|
|
19
|
+
print(e.label, e.text, f"{e.confidence}%")
|
|
20
|
+
# PERSON Carlos Eduardo Pereira 99.5%
|
|
21
|
+
# ID 529.982.247-25 99.0%
|
|
22
|
+
# PHONE (31) 99876-5432 99.5%
|
|
23
|
+
|
|
24
|
+
det.redact(text)
|
|
25
|
+
# 'Meu nome é [PERSON], CPF [ID], tel [PHONE].'
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
python -m tinyzpii document.txt # redacted text
|
|
30
|
+
python -m tinyzpii document.txt --json # entities with offsets and confidence
|
|
31
|
+
cat log.txt | python -m tinyzpii --mask # **** instead of [LABEL]
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Speed
|
|
35
|
+
|
|
36
|
+
~**2.3 µs per character on a single CPU core** end to end (featurization,
|
|
37
|
+
network, decoding, regex rules), i.e. ~0.44 MB/s per core. A 1 kB message is
|
|
38
|
+
~2 ms.
|
|
39
|
+
|
|
40
|
+
For comparison, the GLiNER2-PII model (205M params) needs ~1,070 µs/char on
|
|
41
|
+
one CPU thread and ~50 µs/char on an RTX 2070 GPU: tinyzpii on one CPU core is
|
|
42
|
+
**~475× faster than it on CPU** and ~20× faster than it on GPU.
|
|
43
|
+
|
|
44
|
+
## Entity types
|
|
45
|
+
|
|
46
|
+
| label | covers |
|
|
47
|
+
|---|---|
|
|
48
|
+
| `PERSON` | first, last and full names |
|
|
49
|
+
| `ORG` | company / organisation names |
|
|
50
|
+
| `EMAIL` | e-mail addresses |
|
|
51
|
+
| `PHONE` | phone and fax numbers (BR, US and international formats) |
|
|
52
|
+
| `ADDRESS` | street + number (+ complement: apto, sala, Apt 12B) |
|
|
53
|
+
| `LOCATION` | city, state/UF, county, coordinates |
|
|
54
|
+
| `POSTCODE` | ZIP / CEP |
|
|
55
|
+
| `DATE` | dates, dates of birth |
|
|
56
|
+
| `AGE` | ages |
|
|
57
|
+
| `ID` | CPF, CNPJ, RG, CNH, SSN, passport, licences, PIS, CNS, plates, record numbers... |
|
|
58
|
+
| `CARD` | credit/debit card numbers, CVV |
|
|
59
|
+
| `BANK` | account, agency, routing, IBAN, SWIFT, PIX keys |
|
|
60
|
+
| `URL` | URLs |
|
|
61
|
+
| `NETWORK` | IPv4, IPv6, MAC |
|
|
62
|
+
| `USERNAME` | user names / handles |
|
|
63
|
+
| `SECRET` | passwords, PINs, API keys, cookies |
|
|
64
|
+
|
|
65
|
+
## API keys and secrets
|
|
66
|
+
|
|
67
|
+
Secrets get a dedicated deterministic layer on top of the model, because a
|
|
68
|
+
missed key is costly:
|
|
69
|
+
|
|
70
|
+
- **Known provider formats**: OpenAI / Anthropic (`sk-…`), AWS access key ids
|
|
71
|
+
(`AKIA…`), GitHub (`ghp_…`, `github_pat_…`), GitLab (`glpat-…`), Slack
|
|
72
|
+
(`xox?-…`), Stripe (`sk_live_…`), Google (`AIza…`), HuggingFace (`hf_…`),
|
|
73
|
+
npm, SendGrid, JWTs and PEM private-key blocks. Detected anywhere, including
|
|
74
|
+
with no context at all.
|
|
75
|
+
- **Keyword assignments**: `api_key = "…"`, `TOKEN=…`, `password: …`,
|
|
76
|
+
`Authorization: Bearer …`, `senha: …`, `minha chave da API é …`. Only the
|
|
77
|
+
value is tagged, and it must look like a credential (has a digit, mixed
|
|
78
|
+
case or a symbol), so "your password is correct" is not flagged.
|
|
79
|
+
- **High-entropy strings**: 32+ chars of mixed upper/lower/digits with
|
|
80
|
+
≥4.2 bits/char of entropy (e.g. AWS secret keys) are flagged even without context.
|
|
81
|
+
- The model itself also tags passwords, PINs, cookies and keys from context.
|
|
82
|
+
|
|
83
|
+
`scripts/probe_secrets.py` checks 14 key formats in 8 contexts (EN/PT, bare,
|
|
84
|
+
`export X=`, JSON, Bearer): **109/112 detected in full**, and **0/9**
|
|
85
|
+
look-alikes (git SHAs, UUIDs, long URLs and paths, placeholders) flagged. The
|
|
86
|
+
3 misses are deliberate: a bare 64-char hex string with no keyword nearby is
|
|
87
|
+
indistinguishable from a SHA-256 hash. With any keyword (`key=`, `token:`,
|
|
88
|
+
`Bearer`) it is detected.
|
|
89
|
+
|
|
90
|
+
## Confidence
|
|
91
|
+
|
|
92
|
+
Every entity has a `confidence` (percent) that is **calibrated**: it is the
|
|
93
|
+
probability that the *exact span and label* are right, fitted with isotonic
|
|
94
|
+
regression on a held-out split. On the test split the expected calibration
|
|
95
|
+
error is **0.003**: of the spans reported at ≥90%, 99% are exactly right,
|
|
96
|
+
and of those reported around 75%, about 70% are.
|
|
97
|
+
|
|
98
|
+
Use it to trade recall for precision without retraining:
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
[e for e in det.detect(text) if e.confidence >= 80]
|
|
102
|
+
PIIDetector(threshold=0.3) # lower piece threshold = higher recall
|
|
103
|
+
PIIDetector(labels=["PERSON", "ID", "EMAIL"])
|
|
104
|
+
PIIDetector(use_rules=False) # model only
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
## How it works
|
|
108
|
+
|
|
109
|
+
```
|
|
110
|
+
text ─► pieces ─► hashed features ─► embeddings ─► 6 dilated residual convs ─► BIO tags ─► spans
|
|
111
|
+
(\w+ runs word, shape, (int8) (96 wide, receptive │
|
|
112
|
+
and symbols) prefix, suffix, field ±18 pieces) ▼
|
|
113
|
+
gap, char trigrams + checksum rules
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
- **Pieces, not characters.** The text is split into maximal word-character
|
|
117
|
+
runs and single symbols. PII boundaries fall on piece boundaries, and
|
|
118
|
+
there are ~4.5× fewer pieces than characters, so the network runs ~4.5×
|
|
119
|
+
less often than a char model would.
|
|
120
|
+
- **Tokenizer-free features.** Each piece is described only by hashed
|
|
121
|
+
features (lower-cased word, case/digit shape like `ddd.ddd.ddd-dd`, 3-char
|
|
122
|
+
prefix/suffix, whitespace gap before it, and a bag of character trigrams),
|
|
123
|
+
so unseen names, typos and accents still get sensible embeddings. All of
|
|
124
|
+
them index a single table, so embedding is one gather.
|
|
125
|
+
- **Network.** 6 dilated residual 1-D convolutions (dilations 1,2,4,8,1,2)
|
|
126
|
+
over the piece sequence, then a softmax over 33 BIO tags. The whole
|
|
127
|
+
document is processed in one pass with no windowing.
|
|
128
|
+
- **Decoding.** Spans are grouped by B/I mass, labelled by summed
|
|
129
|
+
probability (so "Belo Horizonte" never splits into ADDRESS + LOCATION),
|
|
130
|
+
grown over glued alphanumeric pieces (a value never ends mid-word:
|
|
131
|
+
`123-45-6789`, `sk-live-9f8a…`), and trimmed of boundary punctuation.
|
|
132
|
+
- **Rules.** Checksum-validated regexes for CPF, CNPJ, Luhn card numbers and
|
|
133
|
+
IBAN, plus e-mail, URL, IPv4 and MAC, override overlapping model spans.
|
|
134
|
+
|
|
135
|
+
## Evaluation
|
|
136
|
+
|
|
137
|
+
All numbers are from the shipped numpy pipeline (`scripts/eval.py`) on
|
|
138
|
+
held-out documents never seen in training (1,500 per bucket). *Span-F1* needs
|
|
139
|
+
the exact `(start, end, label)`; *char-F1* measures redaction quality: is each
|
|
140
|
+
non-space character inside some PII span, whatever the label.
|
|
141
|
+
|
|
142
|
+
| bucket | span-F1 | char-P | char-R | char-F1 |
|
|
143
|
+
|---|---|---|---|---|
|
|
144
|
+
| ai4privacy openpii, English | 0.974 | 0.992 | 0.998 | 0.995 |
|
|
145
|
+
| ai4privacy openpii, Portuguese | 0.986 | 0.996 | 0.999 | 0.997 |
|
|
146
|
+
| Nemotron-PII (English) | 0.954 | 0.987 | 0.975 | 0.981 |
|
|
147
|
+
| synthetic PT-BR (CPF/RG/PIX/...)\* | 0.985 | 0.998 | 0.999 | 0.998 |
|
|
148
|
+
|
|
149
|
+
\* generated by the same templates as the training synth data (different
|
|
150
|
+
seed), so this bucket is optimistic.
|
|
151
|
+
|
|
152
|
+
Both public datasets are LLM-generated, so there is also a small hand-written
|
|
153
|
+
gold set (`tests/handwritten.txt`) in styles none of the sources use: support
|
|
154
|
+
tickets, court notices, chat messages, logs, medical notes, and plain text with
|
|
155
|
+
many non-PII numbers.
|
|
156
|
+
|
|
157
|
+
| hand-written | span-F1 | char-F1 |
|
|
158
|
+
|---|---|---|
|
|
159
|
+
| Portuguese (20 texts) | 0.927 | 0.975 |
|
|
160
|
+
| English (14 texts) | 0.769 | 0.902 |
|
|
161
|
+
|
|
162
|
+
The remaining errors are mostly debatable conventions (years tagged as DATE,
|
|
163
|
+
`MRN 7734120` vs `7734120`) and a few false positives on bare numbers. Per-label span F1 on
|
|
164
|
+
the main test set: PERSON 0.99, ID 0.99, EMAIL 0.99, POSTCODE 1.00, DATE 0.99,
|
|
165
|
+
LOCATION 0.98, ADDRESS 0.97, CARD 0.97, PHONE 0.96, SECRET 0.95, AGE 0.94,
|
|
166
|
+
BANK 0.91, NETWORK 0.90, **ORG 0.87** (the weakest).
|
|
167
|
+
|
|
168
|
+
### vs. GLiNER2-PII
|
|
169
|
+
|
|
170
|
+
[fastino/gliner2-privacy-filter-PII-multi](https://huggingface.co/fastino/gliner2-privacy-filter-PII-multi)
|
|
171
|
+
was evaluated as a potential teacher (`scripts/eval_teacher.py`, 150 docs per
|
|
172
|
+
bucket, labels mapped to ours):
|
|
173
|
+
|
|
174
|
+
| bucket | GLiNER2 char-F1 | tinyzpii char-F1 |
|
|
175
|
+
|---|---|---|
|
|
176
|
+
| ai4privacy EN | 0.929 | 0.994 |
|
|
177
|
+
| ai4privacy PT | 0.945 | 0.998 |
|
|
178
|
+
| Nemotron EN | 0.682 | 0.982 |
|
|
179
|
+
|
|
180
|
+
This is not a neutral benchmark: tinyzpii was trained on these datasets'
|
|
181
|
+
label conventions and GLiNER2 was not. It is why the teacher was not used for
|
|
182
|
+
distillation: the ~300k gold-labelled documents are a stronger signal than its
|
|
183
|
+
predictions.
|
|
184
|
+
|
|
185
|
+
## Training data
|
|
186
|
+
|
|
187
|
+
- [nvidia/Nemotron-PII](https://huggingface.co/datasets/nvidia/Nemotron-PII): 100k English documents (train split).
|
|
188
|
+
- [ai4privacy/pii-masking-openpii-1.5m](https://huggingface.co/datasets/ai4privacy/pii-masking-openpii-1.5m): English + Portuguese subset (164k EN, 35k PT).
|
|
189
|
+
- 80k synthetic PT-BR documents (`scripts/build_synth_pt.py`) covering
|
|
190
|
+
Brazilian formats (CPF/CNPJ with valid check digits, RG, CEP, CNH, PIS, CNS,
|
|
191
|
+
Mercosul plates, PIX keys, agência/conta), registration forms, letters,
|
|
192
|
+
chats, legal and medical prose, and **hard negatives**: prices, percentages,
|
|
193
|
+
law numbers, order/protocol numbers, extensions, verification codes.
|
|
194
|
+
|
|
195
|
+
Source labels are mapped into the 16 types in `tinyzpii/labels.py`.
|
|
196
|
+
Non-identifying attributes (occupation, gender, religion, and so on) are
|
|
197
|
+
treated as non-PII.
|
|
198
|
+
|
|
199
|
+
## Reproducing
|
|
200
|
+
|
|
201
|
+
```bash
|
|
202
|
+
pip install -e ".[train]"
|
|
203
|
+
python scripts/prepare_data.py # -> data/unified/{train,dev,test}.jsonl
|
|
204
|
+
python scripts/build_synth_pt.py 80000 data/unified/synth_pt.jsonl
|
|
205
|
+
python scripts/build_synth_pt.py 2000 data/unified/synth_pt_test.jsonl 99
|
|
206
|
+
for s in train dev; do python scripts/build_features.py data/unified/$s.jsonl data/feat/$s.npz; done
|
|
207
|
+
python scripts/build_features.py data/unified/synth_pt.jsonl data/feat/synth_pt.npz
|
|
208
|
+
python scripts/train.py --train data/feat/train.npz data/feat/synth_pt.npz \
|
|
209
|
+
--weights 0.85 0.15 --steps 40000 --hidden 96 --out data/w.npz # ~10 min on an RTX 2070
|
|
210
|
+
python scripts/calibrate.py data/w.npz
|
|
211
|
+
python scripts/quantize.py data/w.npz tinyzpii/weights.npz
|
|
212
|
+
python scripts/eval.py --weights tinyzpii/weights.npz --per_label
|
|
213
|
+
python scripts/eval_handwritten.py -v
|
|
214
|
+
pytest tests/
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
## Limitations
|
|
218
|
+
|
|
219
|
+
- English and Portuguese only. Other Latin-script languages will partly work
|
|
220
|
+
through the shared formats, but are untested.
|
|
221
|
+
- The training text is mostly LLM-generated. Real-world text, especially
|
|
222
|
+
number-dense business prose, produces more false positives than the
|
|
223
|
+
benchmark numbers suggest. Filter by `confidence` if precision matters.
|
|
224
|
+
- `ORG` is the weakest type. Public institutions are only partly covered.
|
|
225
|
+
- It detects PII; it does not guarantee anonymisation. Review before relying
|
|
226
|
+
on it for compliance (LGPD/GDPR).
|
|
227
|
+
|
|
228
|
+
License: Apache-2.0.
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "tinyzpii"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Blazing-fast, GPU-free, tokenizer-free PII detection and redaction (EN + PT-BR). Pure numpy inference, calibrated confidence, 8 MB bundled weights."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = { text = "Apache-2.0" }
|
|
12
|
+
authors = [{ name = "Carlo Moro" }]
|
|
13
|
+
keywords = ["pii", "redaction", "anonymization", "privacy", "ner", "lgpd", "gdpr", "portuguese"]
|
|
14
|
+
dependencies = [
|
|
15
|
+
"numpy>=1.20",
|
|
16
|
+
# one small matmul per layer: without a BLAS thread cap, OpenBLAS spins up a
|
|
17
|
+
# full thread team per call, which is ~8x slower on many-core CPUs.
|
|
18
|
+
"threadpoolctl>=3.1",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[project.optional-dependencies]
|
|
22
|
+
train = ["torch", "pyarrow", "datasets"]
|
|
23
|
+
teacher = ["gliner2", "transformers"]
|
|
24
|
+
hub = ["huggingface_hub>=0.20"]
|
|
25
|
+
|
|
26
|
+
[project.urls]
|
|
27
|
+
Homepage = "https://huggingface.co/cnmoro/tinyzpii"
|
|
28
|
+
Repository = "https://github.com/cnmoro/tinyzpii"
|
|
29
|
+
|
|
30
|
+
[project.scripts]
|
|
31
|
+
tinyzpii = "tinyzpii.__main__:main"
|
|
32
|
+
|
|
33
|
+
[tool.setuptools]
|
|
34
|
+
packages = ["tinyzpii"]
|
|
35
|
+
|
|
36
|
+
[tool.setuptools.package-data]
|
|
37
|
+
tinyzpii = ["weights.npz"]
|
tinyzpii-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import random
|
|
3
|
+
import string
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
from tinyzpii import PIIDetector, rules
|
|
8
|
+
|
|
9
|
+
W = os.environ.get("TINYZPII_WEIGHTS")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@pytest.fixture(scope="module")
|
|
13
|
+
def det():
|
|
14
|
+
return PIIDetector(weights=W)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def labels(ents):
|
|
18
|
+
return {(e.text, e.label) for e in ents}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def test_degenerate_inputs(det):
|
|
22
|
+
for t in ["", " ", "\n\n\t", "a", "@", "x" * 200000, "😀" * 50, "\x00abc"]:
|
|
23
|
+
for e in det.detect(t):
|
|
24
|
+
assert t[e.start:e.end] == e.text
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_offsets_are_exact_substrings(det):
|
|
28
|
+
rng = random.Random(0)
|
|
29
|
+
alphabet = string.printable + "áéíóúãõçÁÉÍÓÚÃÕÇ€£"
|
|
30
|
+
for _ in range(50):
|
|
31
|
+
t = "".join(rng.choice(alphabet) for _ in range(rng.randint(0, 400)))
|
|
32
|
+
ents = det.detect(t)
|
|
33
|
+
last = 0
|
|
34
|
+
for e in ents:
|
|
35
|
+
assert 0 <= e.start < e.end <= len(t)
|
|
36
|
+
assert e.start >= last # sorted, non-overlapping
|
|
37
|
+
assert t[e.start:e.end] == e.text
|
|
38
|
+
last = e.end
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def test_redact_roundtrip_shape(det):
|
|
42
|
+
t = "Meu nome é Maria Oliveira e meu CPF é 529.982.247-25."
|
|
43
|
+
r = det.redact(t)
|
|
44
|
+
assert "Maria" not in r and "529.982.247-25" not in r
|
|
45
|
+
assert r.startswith("Meu nome é ")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def test_rules_checksums():
|
|
49
|
+
assert rules.cpf_ok("529.982.247-25")
|
|
50
|
+
assert not rules.cpf_ok("529.982.247-26")
|
|
51
|
+
assert not rules.cpf_ok("111.111.111-11")
|
|
52
|
+
assert rules.cnpj_ok("11.222.333/0001-81")
|
|
53
|
+
assert rules.luhn_ok("4111 1111 1111 1111")
|
|
54
|
+
assert not rules.luhn_ok("4111 1111 1111 1112")
|
|
55
|
+
assert rules.iban_ok("GB82 WEST 1234 5698 7654 32")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@pytest.mark.parametrize("text,expected", [
|
|
59
|
+
("Contact John Smith at john.smith@acme.com or +1 (415) 555-0132.",
|
|
60
|
+
{("John Smith", "PERSON"), ("john.smith@acme.com", "EMAIL"), ("+1 (415) 555-0132", "PHONE")}),
|
|
61
|
+
("Olá, sou a Ana Paula Souza, meu CPF é 529.982.247-25 e moro em Curitiba.",
|
|
62
|
+
{("Ana Paula Souza", "PERSON"), ("529.982.247-25", "ID"), ("Curitiba", "LOCATION")}),
|
|
63
|
+
("Pode me ligar no (11) 98765-4321 ou mandar e-mail para ana@gmail.com",
|
|
64
|
+
{("(11) 98765-4321", "PHONE"), ("ana@gmail.com", "EMAIL")}),
|
|
65
|
+
("Card 4111 1111 1111 1111 was charged; server 192.168.0.12 logged it.",
|
|
66
|
+
{("4111 1111 1111 1111", "CARD"), ("192.168.0.12", "NETWORK")}),
|
|
67
|
+
])
|
|
68
|
+
def test_examples(det, text, expected):
|
|
69
|
+
got = labels(det.detect(text))
|
|
70
|
+
assert expected <= got, got
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def test_no_pii_in_plain_text(det):
|
|
74
|
+
t = ("The quarterly report shows revenue grew 12% to $4.5 million. "
|
|
75
|
+
"O relatório mostra que a receita cresceu 12% no trimestre.")
|
|
76
|
+
assert det.detect(t) == []
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def test_label_filter():
|
|
80
|
+
d = PIIDetector(weights=W, labels=["EMAIL"])
|
|
81
|
+
got = d.detect("John Smith, john@x.com")
|
|
82
|
+
assert [e.label for e in got] == ["EMAIL"]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def test_confidence_is_percentage(det):
|
|
86
|
+
ents = det.detect("Contact Maria Silva at maria@example.com")
|
|
87
|
+
assert ents and all(0.0 <= e.confidence <= 100.0 for e in ents)
|
|
88
|
+
assert all("confidence" in e.to_dict() for e in ents)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@pytest.mark.parametrize("key", [
|
|
92
|
+
"sk-" + "proj-4fT9xQ2mLp8vR3nZ7wYk1HcB6sJd0aEuGiOt5", "AK" + "IAIOSFODNN7EXAMPLE",
|
|
93
|
+
"gh" + "p_16C7e42F292c6912E7710c838347Ae178B4a", "xo" + "xb-2048-1234567890-AbCdEfGhIjKlMnOpQrStUvWx",
|
|
94
|
+
"AI" + "zaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY", "h" + "f_aBcDeFgHiJkLmNoPqRsTuVwXyZ0123456789",
|
|
95
|
+
"ey" + "JhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U",
|
|
96
|
+
])
|
|
97
|
+
@pytest.mark.parametrize("ctx", ["{}", "export TOKEN={}", "Minha chave da API é {} , não compartilhe."])
|
|
98
|
+
def test_api_keys(det, key, ctx):
|
|
99
|
+
t = ctx.format(key)
|
|
100
|
+
i = t.index(key)
|
|
101
|
+
assert any(e.label == "SECRET" and e.start <= i and e.end >= i + len(key) for e in det.detect(t))
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@pytest.mark.parametrize("t", [
|
|
105
|
+
"Fixed in commit 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b, see the changelog.",
|
|
106
|
+
"The token field is required. Set password to your own value.",
|
|
107
|
+
"Please ensure your password is correct.",
|
|
108
|
+
])
|
|
109
|
+
def test_secret_lookalikes(det, t):
|
|
110
|
+
assert not [e for e in det.detect(t) if e.label == "SECRET"]
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""python -m tinyzpii [file] [--json] [--mask] [--threshold 0.5]"""
|
|
2
|
+
import argparse
|
|
3
|
+
import json
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
from . import PIIDetector
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def main():
|
|
10
|
+
ap = argparse.ArgumentParser(prog="tinyzpii")
|
|
11
|
+
ap.add_argument("file", nargs="?")
|
|
12
|
+
ap.add_argument("--json", action="store_true", help="print detected entities as JSON")
|
|
13
|
+
ap.add_argument("--mask", action="store_true", help="mask with **** instead of [LABEL]")
|
|
14
|
+
ap.add_argument("--threshold", type=float, default=0.5)
|
|
15
|
+
ap.add_argument("--weights", default=None)
|
|
16
|
+
a = ap.parse_args()
|
|
17
|
+
text = open(a.file, encoding="utf-8").read() if a.file else sys.stdin.read()
|
|
18
|
+
det = PIIDetector(weights=a.weights, threshold=a.threshold)
|
|
19
|
+
if a.json:
|
|
20
|
+
print(json.dumps([e.to_dict() for e in det.detect(text)], ensure_ascii=False, indent=2))
|
|
21
|
+
else:
|
|
22
|
+
sys.stdout.write(det.redact(text, style="mask" if a.mask else "label"))
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
if __name__ == "__main__":
|
|
26
|
+
main()
|