| """PERSON-only NER replace for allowlisted web sources. |
| |
| FastPDN (ArkadiuszPawlak/fastpdn-ner-polish-pii, ONNX) tags person / street / |
| city / org. We replace only PERSON* and expand to the whole word so a |
| HerBERT hole cannot leave `[PII]ru[PII]`. Official and encyclopaedic sources |
| are default-deny — names there are the content. |
| |
| Call after scrub_pii. Needs: pip install huggingface_hub tokenizers onnxruntime |
| """ |
| from __future__ import annotations |
|
|
| import json |
| import re |
| from pathlib import Path |
|
|
| from scrub_pii import PII_TAG |
|
|
| MODEL_ID = "ArkadiuszPawlak/fastpdn-ner-polish-pii" |
| PERSON_LABELS = frozenset({"PERSON", "PERSON_F", "PERSON_L"}) |
| NER_SOURCES = frozenset({ |
| "european_hplt_v3_pl", |
| "govpl", |
| "samorzad_gov_pl", |
| }) |
| _WORD = re.compile(r"[0-9A-Za-zÀ-ÿĄąĆćĘꣳŃńÓóŚśŹźŻż'-]") |
|
|
| _NER = None |
|
|
|
|
| def source_allows_ner(source: str) -> bool: |
| return source in NER_SOURCES |
|
|
|
|
| def _expand(text: str, start: int, end: int) -> tuple[int, int]: |
| while start > 0 and _WORD.match(text[start - 1]): |
| start -= 1 |
| while end < len(text) and _WORD.match(text[end]): |
| end += 1 |
| return start, end |
|
|
|
|
| def apply_person_spans(text: str, spans: list[dict]) -> tuple[str, int]: |
| """Replace PERSON* spans with [PII]. City/org/street spans are ignored.""" |
| kept: list[tuple[int, int]] = [] |
| for s in spans: |
| if s.get("label") not in PERSON_LABELS: |
| continue |
| a, b = _expand(text, int(s["start"]), int(s["end"])) |
| if a < b: |
| kept.append((a, b)) |
| kept.sort() |
| merged: list[tuple[int, int]] = [] |
| for a, b in kept: |
| if merged and a <= merged[-1][1]: |
| merged[-1] = (merged[-1][0], max(merged[-1][1], b)) |
| else: |
| merged.append((a, b)) |
| out = text |
| for a, b in reversed(merged): |
| out = out[:a] + PII_TAG + out[b:] |
| return out, len(merged) |
|
|
|
|
| def load_ner(): |
| import onnxruntime as ort |
| from huggingface_hub import hf_hub_download |
| from tokenizers import Tokenizer |
|
|
| cfg = json.loads(Path(hf_hub_download(MODEL_ID, "config.json")).read_text()) |
| tok = Tokenizer.from_file(hf_hub_download(MODEL_ID, "tokenizer.json")) |
| tok.enable_truncation(max_length=512) |
| sess = ort.InferenceSession( |
| hf_hub_download(MODEL_ID, "model_quantized.onnx"), |
| providers=["CPUExecutionProvider"], |
| ) |
| return { |
| "sess": sess, |
| "tok": tok, |
| "id2label": {int(k): v for k, v in cfg["id2label"].items()}, |
| } |
|
|
|
|
| def _aggregate(text: str, labels: list[str], offsets, scores) -> list[dict]: |
| spans = [] |
| cur = None |
| for lab, (start, end), score in zip(labels, offsets, scores): |
| if start == end or lab == "O" or "-" not in lab: |
| if cur: |
| spans.append(cur) |
| cur = None |
| continue |
| prefix, typ = lab.split("-", 1) |
| if cur and cur["label"] == typ and start <= cur["end"] + 1: |
| cur["end"] = end |
| cur["scores"].append(score) |
| elif prefix == "B" or cur is None or cur["label"] != typ: |
| if cur: |
| spans.append(cur) |
| cur = {"label": typ, "start": start, "end": end, "scores": [score]} |
| else: |
| cur["end"] = end |
| cur["scores"].append(score) |
| if cur: |
| spans.append(cur) |
| return [ |
| { |
| "label": s["label"], |
| "text": text[s["start"]:s["end"]], |
| "score": round(sum(s["scores"]) / len(s["scores"]), 3), |
| "start": s["start"], |
| "end": s["end"], |
| } |
| for s in spans |
| ] |
|
|
|
|
| def predict(ner, text: str) -> list[dict]: |
| import numpy as np |
|
|
| enc = ner["tok"].encode(text) |
| ids = np.array([enc.ids], dtype=np.int64) |
| mask = np.array([enc.attention_mask], dtype=np.int64) |
| logits = ner["sess"].run( |
| None, |
| { |
| "input_ids": ids, |
| "attention_mask": mask, |
| "token_type_ids": np.zeros_like(ids), |
| }, |
| )[0][0] |
| pred = logits.argmax(axis=-1) |
| shift = logits - logits.max(axis=-1, keepdims=True) |
| exp = np.exp(shift) |
| prob = exp / exp.sum(axis=-1, keepdims=True) |
| labels = [ner["id2label"][int(i)] for i in pred] |
| scores = [float(prob[i, int(pred[i])]) for i in range(len(pred))] |
| return _aggregate(text, labels, enc.offsets, scores) |
|
|
|
|
| def _ner(): |
| global _NER |
| if _NER is None: |
| _NER = load_ner() |
| return _NER |
|
|
|
|
| def scrub_entities( |
| text: str, |
| source: str, |
| spans: list[dict] | None = None, |
| ) -> tuple[str, dict[str, int]]: |
| """Return (text, {person: n}). No-op unless source is in NER_SOURCES.""" |
| counts = {"person": 0} |
| if not text or not source_allows_ner(source): |
| return text, counts |
| if spans is None: |
| spans = predict(_ner(), text) |
| out, n = apply_person_spans(text, spans) |
| counts["person"] = n |
| return out, counts |
|
|