File size: 4,885 Bytes
a916ede
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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