File size: 14,484 Bytes
590bec9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
"""Nullify PII detection and masking, self-contained inference helper.

Backends:
  "torch" (default): transformers AutoModelForTokenClassification, float32,
      device cuda > mps > cpu.
  "onnx": onnxruntime CPUExecutionProvider, 4 intra-op threads.
Both backends tokenize with tokenizers.Tokenizer.from_file("tokenizer.json")
and run the same constrained BIOES Viterbi decoder.

Long inputs are cut into non-overlapping windows of at most 1,024 tokens at
the last newline inside the budget; a single longer line is cut at the token
limit. Spans are shifted back to full-text offsets.

Usage:
    from nullify import Nullify
    nf = Nullify.from_pretrained("rbsriram/nullify-68m")   # or local path
    spans = nf.detect(text)
    masked = nf.mask(text, profile="default")  # "default" or "all"
"""

import bisect
import json
import math
from pathlib import Path

import numpy as np

MAX_TOKENS = 1024
NAME_LABELS = frozenset(("NAME_GIVEN", "NAME_FAMILY"))
IDENTITY_DROP = frozenset(("DATE", "LOCATION"))


# ---- BIOES schema and constrained Viterbi (numpy path of bioes_decode_fast) ----

def _schema(tags):
    tags = tuple(tags)
    if len(set(tags)) != len(tags) or tags.count('O') != 1:
        raise ValueError('Need one O and unique BIOES tags')
    parsed = []
    groups = {}
    for tag in tags:
        if tag == 'O':
            parsed.append(('O', None))
            continue
        prefix, sep, kind = tag.partition('-')
        if not sep or prefix not in ('B', 'I', 'E', 'S') or not kind:
            raise ValueError('Invalid BIOES tag')
        parsed.append((prefix, kind))
        groups.setdefault(kind, set()).add(prefix)
    if not groups or any(v != set('BIES') for v in groups.values()):
        raise ValueError('Each category needs B, I, E, and S')
    return parsed


def _legal_transition(left, right):
    a, c = left
    b, d = right
    return (b in ('O', 'B', 'S')) if a in ('O', 'E', 'S') else (b in ('I', 'E') and c == d)


def _masks(parsed):
    k = len(parsed)
    full = np.zeros((k, k), dtype=bool)
    for i, right in enumerate(parsed):
        for j, left in enumerate(parsed):
            full[j, i] = _legal_transition(left, right)
    restricted = full.copy()
    for i, (pi, ci) in enumerate(parsed):
        for j, (pj, cj) in enumerate(parsed):
            if restricted[j, i]:
                restricted[j, i] = (pj == 'O' and pi == 'O') or (
                    pj in ('B', 'I') and pi in ('I', 'E') and cj == ci)
    return full, restricted


_scheme_cache = {}


def _scheme(tags):
    tags = tuple(tags)
    if tags in _scheme_cache:
        return _scheme_cache[tags]
    parsed = _schema(tags)
    first_ok = np.array([p in ('O', 'B', 'S') for p, _ in parsed], dtype=bool)
    end_ok = np.array([p in ('O', 'E', 'S') for p, _ in parsed], dtype=bool)
    full, restricted = _masks(parsed)
    scheme = {'parsed': parsed, 'k': len(parsed), 'full': full,
              'restricted': restricted, 'first_ok': first_ok, 'end_ok': end_ok}
    _scheme_cache[tags] = scheme
    return scheme


def _viterbi(a, scheme, boundary_allowed):
    """Hard-legal BIOES Viterbi forward pass, vectorized numpy.

    First maximal legal predecessor wins ties (numpy argmax on ascending tag
    index), matching the reference decoder.
    """
    neg = -math.inf
    legal = np.where(scheme['full'], 0.0, neg)
    legal_r = np.where(scheme['restricted'], 0.0, neg)
    n, k = a.shape
    if n == 0:
        return []
    previous = np.where(scheme['first_ok'], a[0], neg)
    back = np.zeros((n - 1, k), dtype=np.intp)
    for t in range(1, n):
        masked = previous[:, None] + (legal if boundary_allowed[t - 1] else legal_r)
        back[t - 1] = masked.argmax(axis=0)
        previous = masked.max(axis=0) + a[t]
    end = int(np.where(scheme['end_ok'], previous, neg).argmax())
    path = [end]
    for step in reversed(back):
        path.append(int(step[path[-1]]))
    return list(reversed(path))


def _snap_boundaries(text, span):
    """Shift only outer whitespace inward, using exact source-character counts."""
    start, end = span['start'], span['end']
    raw = text[start:end]
    stripped = raw.strip()
    if not stripped:
        return None
    leading = len(raw) - len(raw.lstrip())
    trailing = len(raw) - len(raw.rstrip())
    snapped = {**span, 'start': start + leading, 'end': end - trailing, 'text': stripped}
    assert text[snapped['start']:snapped['end']] == stripped
    return snapped


def _decode(text, offsets, logits, tags, attention_mask, special_tokens_mask):
    """Decode token logits into labeled character spans.

    Span scores are the mean per-token softmax probability of the chosen tag
    over the tokens inside the span (reference formula).
    """
    offsets = list(offsets)
    n = len(offsets)
    tags = tuple(tags)
    scheme = _scheme(tags)
    k = scheme['k']
    if len(logits) != n:
        raise ValueError('Offset/logit length mismatch')
    active = []
    for i, (offset, on, special) in enumerate(zip(offsets, attention_mask, special_tokens_mask)):
        a, b = offset
        if not on or special or (a, b) == (0, 0):
            continue
        active.append(i)
    base = np.asarray(logits, dtype=np.float64)
    rows_arr = np.ascontiguousarray(base[active]) if active else np.empty((0, k))
    rows = [base[i] for i in active]
    boundary_allowed = [offsets[right][0] >= offsets[left][1]
                        for left, right in zip(active, active[1:])]
    path = _viterbi(rows_arr, scheme, boundary_allowed)
    result = []
    start = None
    kind = None
    values = []
    for j, index in enumerate(path):
        tag = tags[index]
        prefix, label = ('O', None) if tag == 'O' else tag.split('-', 1)
        if prefix in ('B', 'S'):
            start = offsets[active[j]][0]
            kind = label
            values = []
        if prefix != 'O':
            row = list(map(float, rows[j]))
            peak = max(row)
            den = sum(math.exp(v - peak) for v in row)
            values.append(math.exp(row[index] - peak) / den)
        if prefix in ('E', 'S'):
            span = {'start': start, 'end': offsets[active[j]][1], 'label': kind,
                    'score': sum(values) / len(values)}
            snapped = _snap_boundaries(text, span)
            if snapped is not None:
                result.append(snapped)
            start = None
            kind = None
            values = []
    return result


# ---- PERSON join (joined mode of sota_name_output.format_spans) ----

def _join_person(text, spans):
    """Merge overlapping, touching, or whitespace-separated name intervals into
    PERSON spans. Other spans stay unchanged. PERSON score is the minimum
    component score (None if any component score is unknown)."""
    names = sorted((s for s in spans if s['label'] in NAME_LABELS),
                   key=lambda s: (s['start'], s['end']))
    groups = []
    for span in names:
        if groups and (span['start'] <= groups[-1]['end']
                       or text[groups[-1]['end']:span['start']].isspace()):
            groups[-1]['end'] = max(groups[-1]['end'], span['end'])
            groups[-1]['components'].append(span)
        else:
            groups.append({'start': span['start'], 'end': span['end'],
                           'components': [span]})
    output = [s for s in spans if s['label'] not in NAME_LABELS]
    for group in groups:
        values = [s.get('score') for s in group['components']]
        output.append({'start': group['start'], 'end': group['end'], 'label': 'PERSON',
                       'text': text[group['start']:group['end']],
                       'score': min(values) if all(v is not None for v in values) else None,
                       'parts': group['components']})
    return sorted(output, key=lambda s: (s['start'], s['end'], s['label']))


# ---- Windowing (same rule as redactionbench_predict.cut_windows) ----

def _cut_windows(text, offsets, max_tokens=MAX_TOKENS):
    """Non-overlapping windows of at most max_tokens tokens over the whole
    encoding (special tokens included). Cuts land at the last newline inside
    the budget; a single longer line is cut at the token limit.
    Returns [(char_start, char_end, token_start, token_end)] covering text."""
    n = len(offsets)
    starts = [s for s, _ in offsets]
    windows = []
    i = 0
    while i < n:
        e = min(i + max_tokens, n)
        if e < n:
            newline = text.rfind("\n", offsets[i][0], offsets[e][0])
            if newline != -1:
                cut = bisect.bisect_right(starts, newline)
                if cut > i:
                    e = cut
        char_start = offsets[i][0]
        char_end = offsets[e][0] if e < n else len(text)
        windows.append((char_start, char_end, i, e))
        i = e
    if not windows and n == 0:
        windows.append((0, len(text), 0, 0))
    return windows


class Nullify:
    """PII detector. Load with Nullify.from_pretrained(...)."""

    def __init__(self, folder, backend="torch"):
        self.folder = Path(folder)
        self.backend = backend
        config = json.loads((self.folder / 'config.json').read_text())
        id2label = config['id2label']
        self.tags = tuple(id2label[str(i)] for i in range(len(id2label)))
        _scheme(self.tags)  # validate tag scheme eagerly
        from tokenizers import Tokenizer
        self._tokenizer = Tokenizer.from_file(str(self.folder / 'tokenizer.json'))
        self._tokenizer.no_padding()
        self._tokenizer.no_truncation()
        if backend == "torch":
            import torch
            from transformers import AutoModelForTokenClassification
            if torch.cuda.is_available():
                device = torch.device("cuda")
            elif torch.backends.mps.is_available():
                device = torch.device("mps")
            else:
                device = torch.device("cpu")
            self._device = device
            self._torch = torch
            self._model = AutoModelForTokenClassification.from_pretrained(
                str(self.folder), dtype=torch.float32).eval().to(device)
        elif backend == "onnx":
            import onnxruntime as ort
            options = ort.SessionOptions()
            options.intra_op_num_threads = 4
            options.inter_op_num_threads = 1
            self._session = ort.InferenceSession(
                str(self.folder / 'onnx' / 'model.onnx'), options,
                providers=['CPUExecutionProvider'])
        else:
            raise ValueError('backend must be "torch" or "onnx"')

    @classmethod
    def from_pretrained(cls, src, backend="torch"):
        """Load from a local folder path, or a Hugging Face repo id."""
        if Path(str(src)).exists():
            folder = Path(str(src))
        else:
            from huggingface_hub import snapshot_download
            folder = Path(snapshot_download(repo_id=str(src)))
        return cls(folder, backend=backend)

    def _encode(self, text):
        e = self._tokenizer.encode(text)
        return (list(e.ids), list(e.attention_mask),
                list(e.special_tokens_mask), [tuple(p) for p in e.offsets])

    def _forward(self, ids, mask):
        if self.backend == "onnx":
            logits = self._session.run(
                ['logits'], {'input_ids': np.asarray([ids], dtype=np.int64),
                             'attention_mask': np.asarray([mask], dtype=np.int64)})[0][0]
            return np.asarray(logits, dtype=np.float32)
        torch = self._torch
        with torch.inference_mode():
            out = self._model(
                input_ids=torch.tensor([ids], dtype=torch.long, device=self._device),
                attention_mask=torch.tensor([mask], dtype=torch.long, device=self._device))
        return out.logits[0].float().cpu().numpy()

    def _parts(self, text):
        """Raw labeled spans (parts mode): decode every window, shift offsets
        back to full-text coordinates, verify every span's text."""
        ids, mask, special, offsets = self._encode(text)
        spans = []
        for char_start, char_end, tok_start, tok_end in _cut_windows(text, offsets):
            w_ids = ids[tok_start:tok_end]
            w_mask = mask[tok_start:tok_end]
            w_special = special[tok_start:tok_end]
            w_offsets = [(a - char_start, b - char_start)
                         for a, b in offsets[tok_start:tok_end]]
            w_text = text[char_start:char_end]
            logits = self._forward(w_ids, w_mask)
            for span in _decode(w_text, w_offsets, logits, self.tags, w_mask, w_special):
                shifted = {**span,
                           'start': span['start'] + char_start,
                           'end': span['end'] + char_start}
                if text[shifted['start']:shifted['end']] != w_text[span['start']:span['end']]:
                    raise ValueError('Window offset shift failed')
                shifted['text'] = text[shifted['start']:shifted['end']]
                spans.append(shifted)
        return sorted(spans, key=lambda s: (s['start'], s['end'], s['label']))

    def detect(self, text, name_output="person"):
        """Detect PII spans. Returns dicts with start, end, label, score, text;
        joined person spans carry label PERSON plus 'parts' (component spans).
        name_output="parts" returns the raw NAME_GIVEN/NAME_FAMILY spans."""
        spans = self._parts(text)
        if name_output == "parts":
            return [{k: v for k, v in s.items()} for s in spans]
        if name_output != "person":
            raise ValueError('name_output must be "person" or "parts"')
        return _join_person(text, spans)

    def mask(self, text, profile="default"):
        """Replace detected spans with "[LABEL]".
        profile="default" leaves DATE and LOCATION visible; "all" masks every
        class."""
        if profile not in ("default", "all"):
            raise ValueError('profile must be "default" or "all"')
        drop = frozenset() if profile == "all" else IDENTITY_DROP
        spans = [s for s in self.detect(text) if s['label'] not in drop]
        out = []
        pos = 0
        for span in sorted(spans, key=lambda s: s['start']):
            if span['start'] < pos:
                continue
            out.append(text[pos:span['start']])
            out.append(f"[{span['label']}]")
            pos = span['end']
        out.append(text[pos:])
        return ''.join(out)