Download nullify.py from brevitech/nullify-68m: direct link, hf CLI and curl.
- Browser
- Download file 14.5 kB
-
https://huggingface.co/brevitech/nullify-68m/resolve/main/nullify.py
- Command line
-
hf download hf://brevitech/nullify-68m/nullify.py
-
curl -L -o nullify.py https://huggingface.co/brevitech/nullify-68m/resolve/main/nullify.py
14.5 kB
| """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"') | |
| 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) | |