File size: 5,791 Bytes
858ec3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Shared label schema, span<->token alignment and evaluation for the PII tagger."""
import json
from collections import Counter, defaultdict

ENTITY_LABELS = ["GIVENNAME", "SURNAME", "TITLE", "DATE", "TIME", "AGE", "SEX", "GENDER",
                 "EMAIL", "TELEPHONENUM", "CITY", "STREET", "BUILDINGNUM", "ZIPCODE",
                 "IDCARDNUM", "PASSPORTNUM", "DRIVERLICENSENUM", "TAXNUM", "SOCIALNUM",
                 "CREDITCARDNUMBER"]
BIO = ["O"] + [f"{p}-{l}" for l in ENTITY_LABELS for p in ("B", "I")]
L2I = {l: i for i, l in enumerate(BIO)}


def read_jsonl(path, limit=None):
    out = []
    with open(path) as f:
        for i, line in enumerate(f):
            if limit and i >= limit:
                break
            out.append(json.loads(line))
    return out


def trim(text, s, e):
    """Trim whitespace from a char span (tokenizers often include a leading space)."""
    while s < e and text[s].isspace():
        s += 1
    while e > s and text[e - 1].isspace():
        e -= 1
    return s, e


def clean_offsets(text, offsets, special_mask):
    """Per token: (raw_start, s, e) with whitespace trimmed and overlapping prefix tokens
    (e.g. a Metaspace '▁' at (0,1) followed by a token also starting at 0) made empty.
    Special tokens -> None."""
    out = []
    for i, ((s, e), sp) in enumerate(zip(offsets, special_mask)):
        if sp:
            out.append(None); continue
        raw = s
        nxt = next((offsets[j] for j in range(i + 1, len(offsets)) if not special_mask[j]), None)
        if nxt is not None and nxt[0] < e and nxt[0] <= s:
            e = s  # overlapping prefix token -> empty
        s, e = trim(text, s, e)
        out.append((raw, s, e))
    return out


def token_labels(text, spans, offsets, special_mask):
    """Assign BIO ids to tokens from char spans. First content token of a span gets B-,
    later ones I-. Whitespace tokens strictly inside the current span get I- (so HF
    pipeline aggregation keeps '138 3648 5027' together); otherwise O."""
    labels, prev = [], None
    spans = sorted(spans)
    for tokinfo in clean_offsets(text, offsets, special_mask):
        if tokinfo is None:
            labels.append(-100); continue
        raw, s, e = tokinfo
        if e <= s:  # whitespace / empty token
            if prev is not None and prev[0] < raw < prev[1]:
                labels.append(L2I[f"I-{prev[2]}"])
            else:
                labels.append(L2I["O"]); prev = None
            continue
        hit = next(((ss, se, lab) for ss, se, lab in spans if s < se and e > ss), None)
        if hit is None:
            labels.append(L2I["O"]); prev = None
        else:
            labels.append(L2I[("I-" if prev == hit else "B-") + hit[2]]); prev = hit
    return labels


def decode_spans(text, offsets, pred_ids, special_mask):
    """BIO token predictions -> char spans [(s, e, label)]. An I- that does not continue
    the current entity starts a new one (lenient)."""
    spans, cur = [], None
    for tokinfo, p in zip(clean_offsets(text, offsets, special_mask), pred_ids):
        if tokinfo is None:
            continue
        raw, s, e = tokinfo
        tag = BIO[p]
        if e <= s:  # whitespace: only an explicit O closes the entity
            if tag == "O" and cur:
                spans.append(cur); cur = None
            continue
        if tag == "O":
            if cur: spans.append(cur); cur = None
            continue
        bi, lab = tag.split("-", 1)
        if cur and lab == cur[2] and bi == "I":
            cur = (cur[0], e, lab)
        else:
            if cur: spans.append(cur)
            cur = (s, e, lab)
    if cur:
        spans.append(cur)
    return spans


def evaluate(examples, preds):
    """examples: list of {text, spans, lang}; preds: list of predicted span lists.
    Returns exact-match entity P/R/F1 (overall, per lang, per label) and char-level redaction P/R."""
    res = {"by_lang": {}, "by_label": {}}
    tp = Counter(); fp = Counter(); fn = Counter()
    ltp = Counter(); lfp = Counter(); lfn = Counter()
    ch = defaultdict(Counter)
    for ex, pr in zip(examples, preds):
        text, lang = ex["text"], ex.get("lang", "?")
        gold = {(*trim(text, s, e), l) for s, e, l in ex["spans"]}
        pred = {(*trim(text, s, e), l) for s, e, l in pr}
        for g in gold:
            (tp if g in pred else fn)[lang] += 1; (ltp if g in pred else lfn)[g[2]] += 1
        for p in pred - gold:
            fp[lang] += 1; lfp[p[2]] += 1
        gchars = {i for s, e, _ in gold for i in range(s, e) if not text[i].isspace()}
        pchars = {i for s, e, _ in pred for i in range(s, e) if not text[i].isspace()}
        ch[lang]["tp"] += len(gchars & pchars); ch[lang]["fp"] += len(pchars - gchars); ch[lang]["fn"] += len(gchars - pchars)

    def prf(t, p_, n):
        P = t / (t + p_) if t + p_ else 0.0; R = t / (t + n) if t + n else 0.0
        return {"precision": round(P, 4), "recall": round(R, 4), "f1": round(2 * P * R / (P + R), 4) if P + R else 0.0, "support": t + n}

    for lang in sorted(set(tp) | set(fn) | set(fp)):
        r = prf(tp[lang], fp[lang], fn[lang])
        c = ch[lang]; r["redact_precision"] = round(c["tp"] / max(1, c["tp"] + c["fp"]), 4); r["redact_recall"] = round(c["tp"] / max(1, c["tp"] + c["fn"]), 4)
        res["by_lang"][lang] = r
    for lab in ENTITY_LABELS:
        if ltp[lab] + lfn[lab] + lfp[lab]:
            res["by_label"][lab] = prf(ltp[lab], lfp[lab], lfn[lab])
    res["overall"] = prf(sum(tp.values()), sum(fp.values()), sum(fn.values()))
    C = Counter()
    for c in ch.values(): C.update(c)
    res["overall"]["redact_precision"] = round(C["tp"] / max(1, C["tp"] + C["fp"]), 4)
    res["overall"]["redact_recall"] = round(C["tp"] / max(1, C["tp"] + C["fn"]), 4)
    return res