tinyzpii 0.1.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.
- tinyzpii/__init__.py +6 -0
- tinyzpii/__main__.py +26 -0
- tinyzpii/align.py +17 -0
- tinyzpii/detector.py +247 -0
- tinyzpii/features.py +144 -0
- tinyzpii/labels.py +81 -0
- tinyzpii/model.py +118 -0
- tinyzpii/rules.py +165 -0
- tinyzpii/weights.npz +0 -0
- tinyzpii-0.1.0.dist-info/METADATA +251 -0
- tinyzpii-0.1.0.dist-info/RECORD +14 -0
- tinyzpii-0.1.0.dist-info/WHEEL +5 -0
- tinyzpii-0.1.0.dist-info/entry_points.txt +2 -0
- tinyzpii-0.1.0.dist-info/top_level.txt +1 -0
tinyzpii/__init__.py
ADDED
tinyzpii/__main__.py
ADDED
|
@@ -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()
|
tinyzpii/align.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Span <-> piece tag conversion."""
|
|
2
|
+
import numpy as np
|
|
3
|
+
|
|
4
|
+
from .labels import LABEL2ID
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def spans_to_tags(starts, ends, spans):
|
|
8
|
+
tags = np.zeros(len(starts), dtype=np.int64)
|
|
9
|
+
for s, e, l in spans:
|
|
10
|
+
i = np.searchsorted(ends, s, side="right") # first piece ending after s
|
|
11
|
+
j = np.searchsorted(starts, e, side="left") # first piece starting at/after e
|
|
12
|
+
if i >= j:
|
|
13
|
+
continue
|
|
14
|
+
k = LABEL2ID[l]
|
|
15
|
+
tags[i] = 1 + 2 * k
|
|
16
|
+
tags[i + 1:j] = 2 + 2 * k
|
|
17
|
+
return tags
|
tinyzpii/detector.py
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""Public API: PIIDetector.detect / redact."""
|
|
2
|
+
import os
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
from . import rules
|
|
8
|
+
from .features import featurize
|
|
9
|
+
from .labels import LABELS, N_LABELS
|
|
10
|
+
from .model import TinyPIIModel
|
|
11
|
+
|
|
12
|
+
HF_REPO = "cnmoro/tinyzpii"
|
|
13
|
+
WEIGHTS = "weights.npz"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class Entity:
|
|
18
|
+
start: int
|
|
19
|
+
end: int
|
|
20
|
+
label: str
|
|
21
|
+
text: str
|
|
22
|
+
score: float # calibrated probability that this exact span and label are correct
|
|
23
|
+
|
|
24
|
+
@property
|
|
25
|
+
def confidence(self):
|
|
26
|
+
"""score as a percentage, e.g. 97.3"""
|
|
27
|
+
return round(100.0 * self.score, 1)
|
|
28
|
+
|
|
29
|
+
def to_dict(self):
|
|
30
|
+
return {"start": self.start, "end": self.end, "label": self.label,
|
|
31
|
+
"text": self.text, "confidence": self.confidence}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _resolve_weights(path):
|
|
35
|
+
if path and os.path.exists(path):
|
|
36
|
+
return path
|
|
37
|
+
env = os.environ.get("TINYZPII_WEIGHTS")
|
|
38
|
+
if env and os.path.exists(env):
|
|
39
|
+
return env
|
|
40
|
+
local = os.path.join(os.path.dirname(__file__), WEIGHTS)
|
|
41
|
+
if os.path.exists(local):
|
|
42
|
+
return local
|
|
43
|
+
try:
|
|
44
|
+
from huggingface_hub import hf_hub_download
|
|
45
|
+
except ImportError as e: # pragma: no cover
|
|
46
|
+
raise RuntimeError("install huggingface_hub to fetch the weights, or pass weights=path") from e
|
|
47
|
+
return hf_hub_download(repo_id=path or HF_REPO, filename=WEIGHTS)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
_CTL = None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _thread_cap():
|
|
54
|
+
"""Cap BLAS to one thread for the duration of a call. Each matmul here is
|
|
55
|
+
small, and an OpenBLAS thread team per call costs ~8x on many-core CPUs.
|
|
56
|
+
The controller is cached: discovering the BLAS libraries is the slow part."""
|
|
57
|
+
global _CTL
|
|
58
|
+
try:
|
|
59
|
+
if _CTL is None:
|
|
60
|
+
from threadpoolctl import ThreadpoolController
|
|
61
|
+
_CTL = ThreadpoolController()
|
|
62
|
+
return _CTL.limit(limits=1, user_api="blas")
|
|
63
|
+
except ImportError: # pragma: no cover
|
|
64
|
+
import contextlib
|
|
65
|
+
return contextlib.nullcontext()
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
_BRIDGE = set("-_.") # not "'": possessives ("Austin's")
|
|
69
|
+
_KEEP_LEAD = set("+@#$(")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _trim(text, sl, el, first, alnum, a, b, label):
|
|
73
|
+
"""Drop boundary punctuation pieces, keeping balanced brackets and leading
|
|
74
|
+
"+", "@", "#" (phone numbers, handles)."""
|
|
75
|
+
while a <= b and not alnum[b]:
|
|
76
|
+
if first[b] == ")" and "(" in text[sl[a]:el[b]]:
|
|
77
|
+
break
|
|
78
|
+
if first[b] == "." and label == "ORG" and b > a: # "Ltda.", "Inc."
|
|
79
|
+
break
|
|
80
|
+
b -= 1
|
|
81
|
+
while a <= b and not alnum[a]:
|
|
82
|
+
if first[a] == "-" and a < b and alnum[a + 1] and sl[a + 1] == el[a]:
|
|
83
|
+
break # negative coordinate
|
|
84
|
+
if first[a] in _KEEP_LEAD and (first[a] != "(" or ")" in text[sl[a]:el[b]]):
|
|
85
|
+
break
|
|
86
|
+
a += 1
|
|
87
|
+
return a, b
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class PIIDetector:
|
|
91
|
+
"""Detect PII in English / Portuguese text.
|
|
92
|
+
|
|
93
|
+
threshold min probability that a piece is PII (lower = higher recall)
|
|
94
|
+
labels restrict output to these labels (default: all)
|
|
95
|
+
use_rules add checksum-validated regex hits (CPF, CNPJ, cards, IBAN, e-mail...)
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
def __init__(self, weights=None, threshold=0.5, labels=None, use_rules=True):
|
|
99
|
+
self.model = TinyPIIModel.from_npz(_resolve_weights(weights))
|
|
100
|
+
self.threshold = threshold
|
|
101
|
+
self.labels = set(labels) if labels else None
|
|
102
|
+
self.use_rules = use_rules
|
|
103
|
+
|
|
104
|
+
def _calibrate(self, raw):
|
|
105
|
+
cx, cy = self.model.calib
|
|
106
|
+
if cx is None:
|
|
107
|
+
return raw
|
|
108
|
+
return float(np.interp(raw, cx, cy))
|
|
109
|
+
|
|
110
|
+
# ------------------------------------------------------------------ core
|
|
111
|
+
def _decode(self, text, f, probs, threshold):
|
|
112
|
+
if len(probs) == 0:
|
|
113
|
+
return []
|
|
114
|
+
p_o = probs[:, 0]
|
|
115
|
+
cls_p = probs[:, 1::2] + probs[:, 2::2] # (T, N_LABELS)
|
|
116
|
+
b_tot = probs[:, 1::2].sum(1)
|
|
117
|
+
i_tot = probs[:, 2::2].sum(1)
|
|
118
|
+
ent = np.flatnonzero((1.0 - p_o) >= threshold).tolist()
|
|
119
|
+
starts, ends = f["starts"], f["ends"]
|
|
120
|
+
glued = np.zeros(len(starts), dtype=bool) # piece touches previous piece
|
|
121
|
+
glued[1:] = starts[1:] == ends[:-1]
|
|
122
|
+
T = len(starts)
|
|
123
|
+
sl, el = starts.tolist(), ends.tolist()
|
|
124
|
+
first = [text[i] for i in sl]
|
|
125
|
+
alnum = np.fromiter((c.isalnum() for c in first), bool, T)
|
|
126
|
+
bridge = np.fromiter((c in _BRIDGE for c in first), bool, T)
|
|
127
|
+
groups = []
|
|
128
|
+
for t in ent:
|
|
129
|
+
if groups and groups[-1][1] == t - 1 and (glued[t] or i_tot[t] >= b_tot[t]):
|
|
130
|
+
groups[-1][1] = t
|
|
131
|
+
elif groups and groups[-1][1] == t - 2 and glued[t] and glued[t - 1] and bridge[t - 1]:
|
|
132
|
+
groups[-1][1] = t # bridge one glued joiner: "sk-live-9f8a", "1234567-8"
|
|
133
|
+
else:
|
|
134
|
+
groups.append([t, t])
|
|
135
|
+
# a value never ends in the middle of a word: grow each span over glued
|
|
136
|
+
# alphanumeric pieces ("123-45-6789", "Ana-Maria"), and over a glued
|
|
137
|
+
# joiner only when an alphanumeric piece follows it
|
|
138
|
+
for g in groups:
|
|
139
|
+
while True:
|
|
140
|
+
i = g[0]
|
|
141
|
+
if i > 0 and glued[i] and alnum[i - 1]:
|
|
142
|
+
g[0] -= 1
|
|
143
|
+
elif i > 1 and glued[i] and bridge[i - 1] and glued[i - 1] and alnum[i - 2]:
|
|
144
|
+
g[0] -= 2
|
|
145
|
+
else:
|
|
146
|
+
break
|
|
147
|
+
while True:
|
|
148
|
+
i = g[1]
|
|
149
|
+
if i + 1 < T and glued[i + 1] and alnum[i + 1]:
|
|
150
|
+
g[1] += 1
|
|
151
|
+
elif i + 2 < T and glued[i + 1] and bridge[i + 1] and glued[i + 2] and alnum[i + 2]:
|
|
152
|
+
g[1] += 2
|
|
153
|
+
else:
|
|
154
|
+
break
|
|
155
|
+
merged = []
|
|
156
|
+
for g in groups:
|
|
157
|
+
if merged and g[0] <= merged[-1][1] + 1 and (g[0] <= merged[-1][1] or glued[g[0]]):
|
|
158
|
+
merged[-1][1] = max(merged[-1][1], g[1])
|
|
159
|
+
else:
|
|
160
|
+
merged.append(g)
|
|
161
|
+
ents = []
|
|
162
|
+
for a, b in merged:
|
|
163
|
+
k = int(cls_p[a:b + 1].sum(0).argmax())
|
|
164
|
+
label = LABELS[k]
|
|
165
|
+
if label not in ("SECRET", "URL"): # these legitimately start/end with symbols
|
|
166
|
+
a, b = _trim(text, sl, el, first, alnum, a, b, label)
|
|
167
|
+
if a > b:
|
|
168
|
+
continue
|
|
169
|
+
s, e = sl[a], el[b]
|
|
170
|
+
raw = float(cls_p[a:b + 1, k].mean())
|
|
171
|
+
ents.append(Entity(s, e, label, text[s:e], self._calibrate(raw)))
|
|
172
|
+
return ents
|
|
173
|
+
|
|
174
|
+
def _merge_rules(self, text, ents):
|
|
175
|
+
hits = rules.find(text)
|
|
176
|
+
if not hits:
|
|
177
|
+
return ents
|
|
178
|
+
# a model span of the same label that fully contains a rule hit is kept
|
|
179
|
+
# (e.g. a whole cookie "auth_token=eyJ..."): it already redacts the value
|
|
180
|
+
hits = [h for h in hits if not any(x.label == h[2] and x.start <= h[0] and h[1] <= x.end
|
|
181
|
+
and (x.end - x.start) > (h[1] - h[0]) for x in ents)]
|
|
182
|
+
keep = [x for x in ents if not any(x.start < e and s < x.end for s, e, _ in hits)]
|
|
183
|
+
keep += [Entity(s, e, l, text[s:e], 0.99) for s, e, l in hits] # checksum / format validated
|
|
184
|
+
keep.sort(key=lambda x: x.start)
|
|
185
|
+
return keep
|
|
186
|
+
|
|
187
|
+
def detect(self, text, threshold=None):
|
|
188
|
+
"""-> list[Entity] sorted by start offset."""
|
|
189
|
+
with _thread_cap():
|
|
190
|
+
return self._detect(text, threshold)
|
|
191
|
+
|
|
192
|
+
def _detect(self, text, threshold=None):
|
|
193
|
+
th = self.threshold if threshold is None else threshold
|
|
194
|
+
f = featurize(text)
|
|
195
|
+
probs = self.model.forward(f)
|
|
196
|
+
ents = self._decode(text, f, probs, th)
|
|
197
|
+
if self.use_rules:
|
|
198
|
+
ents = self._merge_rules(text, ents)
|
|
199
|
+
if self.labels:
|
|
200
|
+
ents = [x for x in ents if x.label in self.labels]
|
|
201
|
+
return ents
|
|
202
|
+
|
|
203
|
+
def detect_batch(self, texts, threshold=None):
|
|
204
|
+
with _thread_cap():
|
|
205
|
+
return [self._detect(t, threshold) for t in texts]
|
|
206
|
+
|
|
207
|
+
def redact(self, text, style="label", threshold=None):
|
|
208
|
+
"""style: "label" -> [PERSON], "mask" -> ****, or a callable(Entity) -> str."""
|
|
209
|
+
ents = self.detect(text, threshold)
|
|
210
|
+
return self.apply(text, ents, style)
|
|
211
|
+
|
|
212
|
+
@staticmethod
|
|
213
|
+
def apply(text, ents, style="label"):
|
|
214
|
+
"""Replace the given entities in text (see redact)."""
|
|
215
|
+
out, last = [], 0
|
|
216
|
+
for x in ents:
|
|
217
|
+
out.append(text[last:x.start])
|
|
218
|
+
if callable(style):
|
|
219
|
+
out.append(style(x))
|
|
220
|
+
elif style == "mask":
|
|
221
|
+
out.append("*" * (x.end - x.start))
|
|
222
|
+
else:
|
|
223
|
+
out.append(f"[{x.label}]")
|
|
224
|
+
last = x.end
|
|
225
|
+
out.append(text[last:])
|
|
226
|
+
return "".join(out)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
_default = None
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def get_detector():
|
|
233
|
+
global _default
|
|
234
|
+
if _default is None:
|
|
235
|
+
_default = PIIDetector()
|
|
236
|
+
return _default
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def detect(text, **kw):
|
|
240
|
+
return get_detector().detect(text, **kw)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def redact(text, **kw):
|
|
244
|
+
return get_detector().redact(text, **kw)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
assert N_LABELS == len(LABELS)
|
tinyzpii/features.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Tokenizer-free featurization.
|
|
2
|
+
|
|
3
|
+
Text is split into *pieces*: maximal runs of word characters, or single
|
|
4
|
+
non-space symbols. Every PII span in practice starts and ends on piece
|
|
5
|
+
boundaries, and there are ~4.5x fewer pieces than characters, so the network
|
|
6
|
+
runs over pieces. Each piece is described only by hashed features (no vocab):
|
|
7
|
+
|
|
8
|
+
word lower-cased piece
|
|
9
|
+
shape case/digit pattern ("Xxxx", "ddd.ddd")
|
|
10
|
+
prefix first 3 chars, suffix last 3 chars
|
|
11
|
+
misc whitespace gap before the piece x length bucket
|
|
12
|
+
trigrams bag of character trigrams inside the piece (handles OOV names,
|
|
13
|
+
accents, typos)
|
|
14
|
+
|
|
15
|
+
All ids index one concatenated embedding table, so inference is one gather.
|
|
16
|
+
"""
|
|
17
|
+
import hashlib
|
|
18
|
+
import re
|
|
19
|
+
import zlib
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
|
|
23
|
+
PIECE_RE = re.compile(r"[^\W_]+|\S")
|
|
24
|
+
|
|
25
|
+
# bucket sizes of each hashed feature (order matters: defines table offsets)
|
|
26
|
+
SIZES = {
|
|
27
|
+
"word": 1 << 16,
|
|
28
|
+
"shape": 1 << 12,
|
|
29
|
+
"prefix": 1 << 13,
|
|
30
|
+
"suffix": 1 << 13,
|
|
31
|
+
"misc": 64,
|
|
32
|
+
"tri": 1 << 15,
|
|
33
|
+
}
|
|
34
|
+
N_SLOTS = 5 # word, shape, prefix, suffix, misc (trigrams are a separate bag)
|
|
35
|
+
OFFSETS = {}
|
|
36
|
+
_o = 0
|
|
37
|
+
for _k, _v in SIZES.items():
|
|
38
|
+
OFFSETS[_k] = _o
|
|
39
|
+
_o += _v
|
|
40
|
+
VOCAB = _o
|
|
41
|
+
|
|
42
|
+
_LEN_BUCKETS = np.array([0, 1, 2, 3, 4, 6, 9, 13, 20]) # -> 0..8 (9 buckets)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class _ShapeTable(dict):
|
|
46
|
+
def __missing__(self, o):
|
|
47
|
+
c = chr(o)
|
|
48
|
+
v = "X" if c.isupper() else "x" if c.isalpha() else "d" if c.isdigit() else c
|
|
49
|
+
self[o] = v
|
|
50
|
+
return v
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
_SHAPE = _ShapeTable()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _h(s, size):
|
|
57
|
+
return zlib.crc32(s.encode("utf-8", "surrogatepass")) % size
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def shape_of(p):
|
|
61
|
+
s = p.translate(_SHAPE)
|
|
62
|
+
if len(s) > 12:
|
|
63
|
+
s = s[:6] + "~" + s[-4:]
|
|
64
|
+
return s
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _gap_type(g):
|
|
68
|
+
if not g:
|
|
69
|
+
return 0
|
|
70
|
+
if "\n" in g:
|
|
71
|
+
return 3 if g.count("\n") > 1 else 2
|
|
72
|
+
if "\t" in g:
|
|
73
|
+
return 4
|
|
74
|
+
return 1 if len(g) == 1 else 5
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def pieces(text):
|
|
78
|
+
"""-> (starts, ends) int arrays of piece char offsets."""
|
|
79
|
+
sp = [(m.start(), m.end()) for m in PIECE_RE.finditer(text)]
|
|
80
|
+
if not sp:
|
|
81
|
+
z = np.zeros(0, dtype=np.int64)
|
|
82
|
+
return z, z
|
|
83
|
+
a = np.array(sp, dtype=np.int64)
|
|
84
|
+
return a[:, 0], a[:, 1]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def featurize(text):
|
|
88
|
+
"""Returns dict with:
|
|
89
|
+
starts, ends : (T,) piece char offsets
|
|
90
|
+
ids : (T, N_SLOTS) int64 global embedding ids
|
|
91
|
+
tri_ids : (M,) int64 global trigram embedding ids
|
|
92
|
+
tri_off : (T,) offsets of each piece's trigrams into tri_ids
|
|
93
|
+
"""
|
|
94
|
+
starts, ends = pieces(text)
|
|
95
|
+
T = len(starts)
|
|
96
|
+
ids = np.empty((T, N_SLOTS), dtype=np.int64)
|
|
97
|
+
if T == 0:
|
|
98
|
+
return {"starts": starts, "ends": ends, "ids": ids,
|
|
99
|
+
"tri_ids": np.zeros(0, dtype=np.int64), "tri_off": np.zeros(0, dtype=np.int64)}
|
|
100
|
+
sl = starts.tolist()
|
|
101
|
+
el = ends.tolist()
|
|
102
|
+
ps = [text[s:e] for s, e in zip(sl, el)]
|
|
103
|
+
W, S, P, X = SIZES["word"], SIZES["shape"], SIZES["prefix"], SIZES["suffix"]
|
|
104
|
+
lows = [p.lower() for p in ps]
|
|
105
|
+
ids[:, 0] = [_h(p, W) for p in lows]
|
|
106
|
+
ids[:, 1] = [_h(shape_of(p), S) for p in ps]
|
|
107
|
+
ids[:, 2] = [_h(p[:3], P) for p in lows]
|
|
108
|
+
ids[:, 3] = [_h(p[-3:], X) for p in lows]
|
|
109
|
+
prev_end = [0] + el[:-1]
|
|
110
|
+
gaps = [_gap_type(text[a:b]) for a, b in zip(prev_end, sl)]
|
|
111
|
+
lens = ends - starts
|
|
112
|
+
lb = np.searchsorted(_LEN_BUCKETS, np.minimum(lens, 20), side="right") - 1
|
|
113
|
+
ids[:, 4] = np.asarray(gaps) * 9 + lb
|
|
114
|
+
ids += np.array([OFFSETS["word"], OFFSETS["shape"], OFFSETS["prefix"],
|
|
115
|
+
OFFSETS["suffix"], OFFSETS["misc"]], dtype=np.int64)
|
|
116
|
+
|
|
117
|
+
# character trigrams inside each piece, with boundary sentinels, vectorized
|
|
118
|
+
o = np.frombuffer(text.encode("utf-32-le", "surrogatepass"), dtype=np.uint32).astype(np.int64)
|
|
119
|
+
# lower-case ASCII letters so the trigram bag is case-insensitive-ish
|
|
120
|
+
o = np.where((o >= 65) & (o <= 90), o + 32, o)
|
|
121
|
+
pid = np.full(len(o) + 2, -1, dtype=np.int64)
|
|
122
|
+
owner = np.repeat(np.arange(T), lens)
|
|
123
|
+
pos = _ranges(starts, lens)
|
|
124
|
+
pid[pos + 1] = owner
|
|
125
|
+
op = np.zeros(len(o) + 2, dtype=np.int64)
|
|
126
|
+
op[1:-1] = o
|
|
127
|
+
prv = np.where(pid[pos] == owner, op[pos], 1) # pid[pos] is char pos-1
|
|
128
|
+
nxt = np.where(pid[pos + 2] == owner, op[pos + 2], 2)
|
|
129
|
+
cur = op[pos + 1]
|
|
130
|
+
tri = (prv * 1000003 + cur * 10007 + nxt) * 2654435761
|
|
131
|
+
tri_ids = (tri % SIZES["tri"]) + OFFSETS["tri"]
|
|
132
|
+
tri_off = np.concatenate([[0], np.cumsum(lens)[:-1]])
|
|
133
|
+
return {"starts": starts, "ends": ends, "ids": ids, "tri_ids": tri_ids, "tri_off": tri_off}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _ranges(starts, lens):
|
|
137
|
+
tot = int(lens.sum())
|
|
138
|
+
rep_start = np.repeat(starts - np.concatenate([[0], np.cumsum(lens)[:-1]]), lens)
|
|
139
|
+
return np.arange(tot) + rep_start
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def schema_hash():
|
|
143
|
+
src = repr(SIZES) + PIECE_RE.pattern + repr(_LEN_BUCKETS.tolist()) + "v1"
|
|
144
|
+
return hashlib.sha1(src.encode()).hexdigest()[:12]
|
tinyzpii/labels.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Unified PII label set and the mappings from each source dataset into it."""
|
|
2
|
+
|
|
3
|
+
LABELS = [
|
|
4
|
+
"PERSON", # given names, surnames, full names
|
|
5
|
+
"ORG", # company / organisation names
|
|
6
|
+
"EMAIL",
|
|
7
|
+
"PHONE", # phone and fax numbers
|
|
8
|
+
"ADDRESS", # street + building number
|
|
9
|
+
"LOCATION", # city, county, state, coordinates
|
|
10
|
+
"POSTCODE", # ZIP / CEP
|
|
11
|
+
"DATE", # dates and dates of birth
|
|
12
|
+
"AGE",
|
|
13
|
+
"ID", # SSN, CPF, RG, passport, licence, tax ids, record numbers...
|
|
14
|
+
"CARD", # credit / debit card numbers, CVV
|
|
15
|
+
"BANK", # account, routing, IBAN, SWIFT
|
|
16
|
+
"URL",
|
|
17
|
+
"NETWORK", # IPv4 / IPv6 / MAC
|
|
18
|
+
"USERNAME",
|
|
19
|
+
"SECRET", # passwords, PINs, API keys, cookies
|
|
20
|
+
]
|
|
21
|
+
LABEL2ID = {l: i for i, l in enumerate(LABELS)}
|
|
22
|
+
N_LABELS = len(LABELS)
|
|
23
|
+
# BIO tags: 0 = O, 1 + 2*i = B-label_i, 2 + 2*i = I-label_i
|
|
24
|
+
N_TAGS = 1 + 2 * N_LABELS
|
|
25
|
+
|
|
26
|
+
NEMOTRON = {
|
|
27
|
+
"first_name": "PERSON", "last_name": "PERSON", "name": "PERSON",
|
|
28
|
+
"company_name": "ORG",
|
|
29
|
+
"email": "EMAIL",
|
|
30
|
+
"phone_number": "PHONE", "fax_number": "PHONE",
|
|
31
|
+
"street_address": "ADDRESS",
|
|
32
|
+
"city": "LOCATION", "county": "LOCATION", "state": "LOCATION", "coordinate": "LOCATION",
|
|
33
|
+
"postcode": "POSTCODE",
|
|
34
|
+
"date": "DATE", "date_of_birth": "DATE", "date_time": "DATE",
|
|
35
|
+
"age": "AGE",
|
|
36
|
+
"ssn": "ID", "tax_id": "ID", "customer_id": "ID", "employee_id": "ID",
|
|
37
|
+
"certificate_license_number": "ID", "medical_record_number": "ID",
|
|
38
|
+
"health_plan_beneficiary_number": "ID", "unique_id": "ID",
|
|
39
|
+
"vehicle_identifier": "ID", "license_plate": "ID", "device_identifier": "ID",
|
|
40
|
+
"biometric_identifier": "ID",
|
|
41
|
+
"credit_debit_card": "CARD", "cvv": "CARD",
|
|
42
|
+
"account_number": "BANK", "bank_routing_number": "BANK", "swift_bic": "BANK",
|
|
43
|
+
"url": "URL",
|
|
44
|
+
"ipv4": "NETWORK", "ipv6": "NETWORK", "mac_address": "NETWORK",
|
|
45
|
+
"user_name": "USERNAME",
|
|
46
|
+
"password": "SECRET", "pin": "SECRET", "api_key": "SECRET", "http_cookie": "SECRET",
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
AI4PRIVACY = {
|
|
50
|
+
"GIVENNAME": "PERSON", "SURNAME": "PERSON",
|
|
51
|
+
"EMAIL": "EMAIL",
|
|
52
|
+
"TELEPHONENUM": "PHONE",
|
|
53
|
+
"STREET": "ADDRESS", "BUILDINGNUM": "ADDRESS",
|
|
54
|
+
"CITY": "LOCATION",
|
|
55
|
+
"ZIPCODE": "POSTCODE",
|
|
56
|
+
"DATE": "DATE",
|
|
57
|
+
"AGE": "AGE",
|
|
58
|
+
"IDCARDNUM": "ID", "DRIVERLICENSENUM": "ID", "PASSPORTNUM": "ID",
|
|
59
|
+
"TAXNUM": "ID", "SOCIALNUM": "ID",
|
|
60
|
+
"CREDITCARDNUMBER": "CARD",
|
|
61
|
+
"USERNAME": "USERNAME", "URL": "URL", "ORGANISATION": "ORG", "ACCOUNTNUM": "BANK",
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
# labels whose adjacent fragments are merged into one span when separated only
|
|
65
|
+
# by a short connector (e.g. "Maria" + " " + "Silva", "Rua X" + ", " + "123")
|
|
66
|
+
MERGEABLE = {"PERSON": {" "}, "ADDRESS": {" ", ", ", ",", " nº ", ", nº ", " n. "}}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def merge_spans(text, spans):
|
|
70
|
+
"""spans: sorted list of [start, end, label]; merges adjacent fragments."""
|
|
71
|
+
out = []
|
|
72
|
+
for s, e, l in sorted(spans):
|
|
73
|
+
if out and out[-1][2] == l and l in MERGEABLE:
|
|
74
|
+
ps, pe, _ = out[-1]
|
|
75
|
+
if s >= pe and text[pe:s] in MERGEABLE[l]:
|
|
76
|
+
out[-1][1] = e
|
|
77
|
+
continue
|
|
78
|
+
if out and s < out[-1][1]: # overlapping: keep the first
|
|
79
|
+
continue
|
|
80
|
+
out.append([s, e, l])
|
|
81
|
+
return out
|
tinyzpii/model.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Piece-level tagger: hashed embeddings -> dilated residual convs -> BIO tags.
|
|
2
|
+
|
|
3
|
+
Trained in torch; inference is a pure numpy forward pass.
|
|
4
|
+
|
|
5
|
+
e = sum(E[ids]) + mean(E[trigrams]) (T, D)
|
|
6
|
+
h = relu(e @ Win + b) (T, H)
|
|
7
|
+
h += relu([h[t-d], h[t], h[t+d]] @ Wk + bk) for d in DILATIONS
|
|
8
|
+
out = h @ Wout + bout (T, N_TAGS)
|
|
9
|
+
"""
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
from .features import N_SLOTS, VOCAB, schema_hash
|
|
13
|
+
from .labels import N_TAGS
|
|
14
|
+
|
|
15
|
+
EMB = 64
|
|
16
|
+
HIDDEN = 128
|
|
17
|
+
DILATIONS = (1, 2, 4, 8, 1, 2)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class TinyPIIModel:
|
|
21
|
+
def __init__(self, w):
|
|
22
|
+
if "E_q" in w: # int8 rows with per-row scale
|
|
23
|
+
self.E = w["E_q"].astype(np.float32) * w["E_s"].astype(np.float32)[:, None]
|
|
24
|
+
else:
|
|
25
|
+
self.E = np.asarray(w["E"], dtype=np.float32)
|
|
26
|
+
self.Win = np.ascontiguousarray(w["Win"], dtype=np.float32)
|
|
27
|
+
self.bin = np.asarray(w["bin"], dtype=np.float32)
|
|
28
|
+
self.dil = [int(d) for d in w["dilations"]]
|
|
29
|
+
self.blocks = [(np.ascontiguousarray(w[f"W{i}"], dtype=np.float32),
|
|
30
|
+
np.asarray(w[f"b{i}"], dtype=np.float32)) for i in range(len(self.dil))]
|
|
31
|
+
self.Wout = np.ascontiguousarray(w["Wout"], dtype=np.float32)
|
|
32
|
+
self.bout = np.asarray(w["bout"], dtype=np.float32)
|
|
33
|
+
# isotonic calibration of span confidence (raw score -> P(correct))
|
|
34
|
+
self.calib = (w["calib_x"], w["calib_y"]) if "calib_x" in w else (None, None)
|
|
35
|
+
|
|
36
|
+
@classmethod
|
|
37
|
+
def from_npz(cls, path):
|
|
38
|
+
with np.load(path) as w:
|
|
39
|
+
d = {k: w[k] for k in w.files}
|
|
40
|
+
if "schema" in d and str(d["schema"]) != schema_hash():
|
|
41
|
+
raise ValueError("weights were trained with a different feature schema")
|
|
42
|
+
return cls(d)
|
|
43
|
+
|
|
44
|
+
def embed(self, f):
|
|
45
|
+
T = len(f["starts"])
|
|
46
|
+
e = self.E[f["ids"]].sum(1)
|
|
47
|
+
if len(f["tri_ids"]):
|
|
48
|
+
tri = np.add.reduceat(self.E[f["tri_ids"]], f["tri_off"], axis=0)
|
|
49
|
+
n = np.diff(np.append(f["tri_off"], len(f["tri_ids"]))).astype(np.float32)
|
|
50
|
+
e += tri / n[:, None]
|
|
51
|
+
return e.reshape(T, -1)
|
|
52
|
+
|
|
53
|
+
def forward(self, f):
|
|
54
|
+
"""f: featurize() output -> (T, N_TAGS) probabilities."""
|
|
55
|
+
T = len(f["starts"])
|
|
56
|
+
if T == 0:
|
|
57
|
+
return np.zeros((0, self.Wout.shape[1]), dtype=np.float32)
|
|
58
|
+
h = np.maximum(self.embed(f) @ self.Win + self.bin, 0.0)
|
|
59
|
+
H = h.shape[1]
|
|
60
|
+
for d, (W, b) in zip(self.dil, self.blocks):
|
|
61
|
+
p = np.zeros((T + 2 * d, H), dtype=np.float32)
|
|
62
|
+
p[d:d + T] = h
|
|
63
|
+
x = np.concatenate([p[:T], h, p[2 * d:]], axis=1)
|
|
64
|
+
h = h + np.maximum(x @ W + b, 0.0)
|
|
65
|
+
z = h @ self.Wout + self.bout
|
|
66
|
+
z -= z.max(1, keepdims=True)
|
|
67
|
+
np.exp(z, out=z)
|
|
68
|
+
z /= z.sum(1, keepdims=True)
|
|
69
|
+
return z
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def torch_model(emb=EMB, hidden=HIDDEN, dilations=DILATIONS, dropout=0.1):
|
|
73
|
+
import torch
|
|
74
|
+
import torch.nn as nn
|
|
75
|
+
import torch.nn.functional as F
|
|
76
|
+
|
|
77
|
+
class Net(nn.Module):
|
|
78
|
+
def __init__(self):
|
|
79
|
+
super().__init__()
|
|
80
|
+
self.E = nn.Embedding(VOCAB, emb)
|
|
81
|
+
nn.init.normal_(self.E.weight, std=0.05)
|
|
82
|
+
self.inp = nn.Linear(emb, hidden)
|
|
83
|
+
self.dil = list(dilations)
|
|
84
|
+
self.convs = nn.ModuleList(nn.Conv1d(hidden, hidden, 3, dilation=d, padding=d)
|
|
85
|
+
for d in dilations)
|
|
86
|
+
self.out = nn.Linear(hidden, N_TAGS)
|
|
87
|
+
self.drop = nn.Dropout(dropout)
|
|
88
|
+
|
|
89
|
+
def forward(self, ids, tri_ids, tri_off):
|
|
90
|
+
# ids (B,T,S); tri_ids/tri_off: flat trigram bags for the B*T pieces
|
|
91
|
+
B, T, _ = ids.shape
|
|
92
|
+
e = self.E(ids).sum(2)
|
|
93
|
+
te = F.embedding_bag(tri_ids, self.E.weight, tri_off, mode="mean")
|
|
94
|
+
e = e + te.view(B, T, -1)
|
|
95
|
+
h = F.relu(self.inp(self.drop(e)))
|
|
96
|
+
h = h.transpose(1, 2)
|
|
97
|
+
for c in self.convs:
|
|
98
|
+
h = h + F.relu(c(self.drop(h)))
|
|
99
|
+
return self.out(h.transpose(1, 2))
|
|
100
|
+
|
|
101
|
+
return Net()
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def export(net, path, extra=None):
|
|
105
|
+
w = {"E": net.E.weight.detach().cpu().numpy().astype(np.float16),
|
|
106
|
+
"Win": net.inp.weight.detach().cpu().numpy().T,
|
|
107
|
+
"bin": net.inp.bias.detach().cpu().numpy(),
|
|
108
|
+
"dilations": np.array(net.dil),
|
|
109
|
+
"Wout": net.out.weight.detach().cpu().numpy().T,
|
|
110
|
+
"bout": net.out.bias.detach().cpu().numpy(),
|
|
111
|
+
"schema": np.array(schema_hash())}
|
|
112
|
+
for i, c in enumerate(net.convs):
|
|
113
|
+
k = c.weight.detach().cpu().numpy() # (out, in, 3): taps t-d, t, t+d
|
|
114
|
+
w[f"W{i}"] = np.concatenate([k[:, :, 0].T, k[:, :, 1].T, k[:, :, 2].T], axis=0)
|
|
115
|
+
w[f"b{i}"] = c.bias.detach().cpu().numpy()
|
|
116
|
+
if extra:
|
|
117
|
+
w.update(extra)
|
|
118
|
+
np.savez_compressed(path, **w)
|
tinyzpii/rules.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""High-precision pattern detectors with checksum validation.
|
|
2
|
+
|
|
3
|
+
These complement the model: anything matched here is near-certainly PII, so
|
|
4
|
+
rule spans take precedence over overlapping model spans.
|
|
5
|
+
"""
|
|
6
|
+
import re
|
|
7
|
+
|
|
8
|
+
_EMAIL = re.compile(r"(?<![\w.+-])[\w.+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}(?![\w-])")
|
|
9
|
+
_URL = re.compile(r"\b(?:https?://|www\.)[^\s<>\"')\]]+[^\s<>\"')\].,;:!?]")
|
|
10
|
+
_IPV4 = re.compile(r"(?<![\d.])(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)(?![\d.]|\.\d)")
|
|
11
|
+
_MAC = re.compile(r"(?<![\w:-])(?:[0-9A-Fa-f]{2}([:-]))(?:[0-9A-Fa-f]{2}\1){4}[0-9A-Fa-f]{2}(?![\w:-])")
|
|
12
|
+
_CPF = re.compile(r"(?<![\d.\-/])\d{3}\.?\d{3}\.?\d{3}-?\d{2}(?![\d\-/]|\.\d)")
|
|
13
|
+
_CNPJ = re.compile(r"(?<![\d.\-/])\d{2}\.?\d{3}\.?\d{3}/?\d{4}-?\d{2}(?![\d\-/]|\.\d)")
|
|
14
|
+
_CARD = re.compile(r"(?<![\d-])(?:\d[ -]?){12,18}\d(?![\d-])")
|
|
15
|
+
_IBAN = re.compile(r"\b[A-Z]{2}\d{2}(?: ?[A-Z0-9]{4}){3,7}(?: ?[A-Z0-9]{1,4})?\b")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
# --- secrets --------------------------------------------------------------
|
|
19
|
+
_KEY_PREFIX = re.compile(
|
|
20
|
+
r"(?<![\w-])(?:"
|
|
21
|
+
r"sk-(?:proj-|ant-(?:api|admin)\d{2}-|svcacct-)?[A-Za-z0-9_\-]{20,}" # OpenAI / Anthropic
|
|
22
|
+
r"|(?:sk|rk|pk)_(?:live|test)_[A-Za-z0-9]{16,}" # Stripe
|
|
23
|
+
r"|(?:AKIA|ASIA|AGPA|AIDA|AROA)[0-9A-Z]{16}" # AWS access key id
|
|
24
|
+
r"|gh[pousr]_[A-Za-z0-9]{30,}|github_pat_\w{40,}" # GitHub
|
|
25
|
+
r"|glpat-[A-Za-z0-9_\-]{20,}" # GitLab
|
|
26
|
+
r"|xox[abposr]-[A-Za-z0-9\-]{10,}" # Slack
|
|
27
|
+
r"|AIza[0-9A-Za-z_\-]{35}" # Google
|
|
28
|
+
r"|hf_[A-Za-z0-9]{30,}" # HuggingFace
|
|
29
|
+
r"|npm_[A-Za-z0-9]{36}" # npm
|
|
30
|
+
r"|SG\.[A-Za-z0-9_\-]{16,}\.[A-Za-z0-9_\-]{16,}" # SendGrid
|
|
31
|
+
r"|eyJ[A-Za-z0-9_\-]{8,}\.eyJ[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}" # JWT
|
|
32
|
+
r")(?![\w-])")
|
|
33
|
+
_PEM = re.compile(r"-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----[\s\S]+?-----END (?:[A-Z]+ )?PRIVATE KEY-----")
|
|
34
|
+
# keyword = value / keyword: value / Bearer value -> group 1 is the secret
|
|
35
|
+
_KEY_ASSIGN = re.compile(
|
|
36
|
+
r"(?i)(?:api[_\-. ]?key|apikey|access[_\-]?key(?:[_\-]?id)?|secret(?:[_\-]?key)?|client[_\-]?secret|"
|
|
37
|
+
r"auth[_\-]?token|access[_\-]?token|refresh[_\-]?token|token|password|passwd|pwd|senha|"
|
|
38
|
+
r"chave(?: (?:da|de) api)?|private[_\-]?key)"
|
|
39
|
+
r"[\w\-]*[\"']?\s*(?:[:=]|=>|\bé\b|\bis\b)\s*[\"'`]?([^\s\"'`,;]{8,})"
|
|
40
|
+
r"|(?i:bearer|basic)\s+([A-Za-z0-9_\-.~+/=]{16,})")
|
|
41
|
+
_HIGH_ENTROPY = re.compile(r"(?<![\w/+=.\-])[A-Za-z0-9_\-+/]{32,}={0,2}(?![\w/+=\-])")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _entropy(s):
|
|
45
|
+
from collections import Counter
|
|
46
|
+
from math import log2
|
|
47
|
+
n = len(s)
|
|
48
|
+
return -sum(c / n * log2(c / n) for c in Counter(s).values())
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def high_entropy_ok(s):
|
|
52
|
+
"""Long random-looking token: letters and digits mixed, high entropy
|
|
53
|
+
(pure hex tops out at 4 bits/char and is left alone: hashes, UUIDs)."""
|
|
54
|
+
has_d = any(c.isdigit() for c in s)
|
|
55
|
+
has_u = any(c.isupper() for c in s)
|
|
56
|
+
has_l = any(c.islower() for c in s)
|
|
57
|
+
return has_d and has_u and has_l and _entropy(s) >= 4.2
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def assign_ok(v):
|
|
61
|
+
"""Value after "password:", "api key is", "Bearer"...: must look like a
|
|
62
|
+
credential, not a word ("your password is correct")."""
|
|
63
|
+
if v.startswith(("http://", "https://")) or v.lower() in _NOT_SECRET:
|
|
64
|
+
return False
|
|
65
|
+
has_d = any(c.isdigit() for c in v)
|
|
66
|
+
mixed = any(c.isupper() for c in v) and any(c.islower() for c in v)
|
|
67
|
+
sym = any(not c.isalnum() for c in v)
|
|
68
|
+
return has_d or mixed or sym
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _digits(s):
|
|
72
|
+
return [int(c) for c in s if c.isdigit()]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def cpf_ok(s):
|
|
76
|
+
d = _digits(s)
|
|
77
|
+
if len(d) != 11 or len(set(d)) == 1:
|
|
78
|
+
return False
|
|
79
|
+
for n in (9, 10):
|
|
80
|
+
v = sum(d[i] * (n + 1 - i) for i in range(n)) * 10 % 11 % 10
|
|
81
|
+
if v != d[n]:
|
|
82
|
+
return False
|
|
83
|
+
return True
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def cnpj_ok(s):
|
|
87
|
+
d = _digits(s)
|
|
88
|
+
if len(d) != 14 or len(set(d)) == 1:
|
|
89
|
+
return False
|
|
90
|
+
for n, w in ((12, [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]), (13, [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2])):
|
|
91
|
+
r = sum(a * b for a, b in zip(d, w)) % 11
|
|
92
|
+
if (0 if r < 2 else 11 - r) != d[n]:
|
|
93
|
+
return False
|
|
94
|
+
return True
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def luhn_ok(s):
|
|
98
|
+
d = _digits(s)
|
|
99
|
+
if not 13 <= len(d) <= 19 or len(set(d)) == 1:
|
|
100
|
+
return False
|
|
101
|
+
tot = 0
|
|
102
|
+
for i, x in enumerate(reversed(d)):
|
|
103
|
+
if i % 2:
|
|
104
|
+
x *= 2
|
|
105
|
+
if x > 9:
|
|
106
|
+
x -= 9
|
|
107
|
+
tot += x
|
|
108
|
+
return tot % 10 == 0
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def iban_ok(s):
|
|
112
|
+
s = s.replace(" ", "")
|
|
113
|
+
if not 15 <= len(s) <= 34:
|
|
114
|
+
return False
|
|
115
|
+
r = s[4:] + s[:4]
|
|
116
|
+
try:
|
|
117
|
+
return int("".join(str(int(c, 36)) for c in r)) % 97 == 1
|
|
118
|
+
except ValueError:
|
|
119
|
+
return False
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
RULES = [
|
|
123
|
+
(_PEM, "SECRET", None),
|
|
124
|
+
(_KEY_PREFIX, "SECRET", None),
|
|
125
|
+
(_KEY_ASSIGN, "SECRET", assign_ok),
|
|
126
|
+
(_EMAIL, "EMAIL", None),
|
|
127
|
+
(_URL, "URL", None),
|
|
128
|
+
(_IPV4, "NETWORK", None),
|
|
129
|
+
(_MAC, "NETWORK", None),
|
|
130
|
+
(_CNPJ, "ID", cnpj_ok),
|
|
131
|
+
(_CPF, "ID", cpf_ok),
|
|
132
|
+
(_CARD, "CARD", luhn_ok),
|
|
133
|
+
(_IBAN, "BANK", iban_ok),
|
|
134
|
+
(_HIGH_ENTROPY, "SECRET", high_entropy_ok),
|
|
135
|
+
]
|
|
136
|
+
_NOT_SECRET = {"required", "optional", "undefined", "null", "none", "your_api_key", "<redacted>", "********"}
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
_GROUPED = {_KEY_ASSIGN} # rules whose capture group (not the whole match) is the value
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def find(text):
|
|
143
|
+
"""-> list of (start, end, label) non-overlapping rule matches.
|
|
144
|
+
Earlier rules in RULES win overlaps (specific formats before generic ones)."""
|
|
145
|
+
taken = []
|
|
146
|
+
for rx, label, check in RULES:
|
|
147
|
+
if label == "EMAIL" and "@" not in text:
|
|
148
|
+
continue
|
|
149
|
+
for m in rx.finditer(text):
|
|
150
|
+
g = 0
|
|
151
|
+
if rx in _GROUPED:
|
|
152
|
+
g = next(i for i in range(1, rx.groups + 1) if m.group(i) is not None)
|
|
153
|
+
if check is not None and not check(m.group(g)):
|
|
154
|
+
continue
|
|
155
|
+
s, e = m.start(g), m.end(g)
|
|
156
|
+
if rx in _GROUPED: # drop sentence punctuation: "password is River54#."
|
|
157
|
+
while e > s and text[e - 1] in ".,;:!?)]}" and (e == len(text) or text[e].isspace()):
|
|
158
|
+
e -= 1
|
|
159
|
+
if e - s < 6 or not check(text[s:e]):
|
|
160
|
+
continue
|
|
161
|
+
if any(s < te and ts < e for ts, te, _ in taken):
|
|
162
|
+
continue
|
|
163
|
+
taken.append((s, e, label))
|
|
164
|
+
taken.sort()
|
|
165
|
+
return taken
|
tinyzpii/weights.npz
ADDED
|
Binary file
|
|
@@ -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.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
tinyzpii/__init__.py,sha256=9x1NbA3YXgdezXeOiaEkewoU4REmCxaF4Y_GY1VUxBo,236
|
|
2
|
+
tinyzpii/__main__.py,sha256=kkV2btdJ9tC1SQvawJpbAnL1PG1McuRSsucEvAzZRdY,939
|
|
3
|
+
tinyzpii/align.py,sha256=4CTIEPh5IvYuJ9GpQGnzgqSmFKIkaRsObgCGuxAPd-k,514
|
|
4
|
+
tinyzpii/detector.py,sha256=sTOH12nBeY6sY2L_X1OlCuaELjwOA6YrSHs1whOJXB0,8848
|
|
5
|
+
tinyzpii/features.py,sha256=wqapwRoKqxzD-XTpQK2nvht3wxRzOhPcgG564o7qFDM,4796
|
|
6
|
+
tinyzpii/labels.py,sha256=8HvUkRHRtLdVlQRV9LCUTk3I2JIStqLPsGfeGKktLfI,3184
|
|
7
|
+
tinyzpii/model.py,sha256=zLkm_zSpKNUosnekujH_0_8Sh0MDjZiyW2MHdZZwG7U,4755
|
|
8
|
+
tinyzpii/rules.py,sha256=jagTWhgHnuP8byJiUCi_HX6Rp8vkyki5VlJU6_o8kb0,6478
|
|
9
|
+
tinyzpii/weights.npz,sha256=FsEOd8EMurVFkAWohD1jaNrU6vcBI8AYyRsTP5hu3gA,8220776
|
|
10
|
+
tinyzpii-0.1.0.dist-info/METADATA,sha256=dUD6WmkesGbkjiRsaK7CuLp179KuxEj0qatmbsCA5H8,11247
|
|
11
|
+
tinyzpii-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
12
|
+
tinyzpii-0.1.0.dist-info/entry_points.txt,sha256=m5O0gq0a03UhvWnwRGTGACb49f6ayIxqjwRq91OSwJk,52
|
|
13
|
+
tinyzpii-0.1.0.dist-info/top_level.txt,sha256=2Uj7-fkWMRdrpDNZ8eVGFZqqj3h62m_F8CQREQWhr60,9
|
|
14
|
+
tinyzpii-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
tinyzpii
|