File size: 6,336 Bytes
7ba64dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Harness de scoring — metrique reine : leak rate par type d'entite.

Format d'echange (JSONL, un segment par ligne) :
    {"id": "...", "text": "...", "domain": "juridique", "noise": false,
     "entities": [{"start": 10, "end": 21, "type": "PERSON", "value": "Jean Dupont"}]}

Les predictions suivent le meme format (memes ids, offsets sur le meme texte).

Definitions (voir doc/memory/analyse.md §5.1) :
- Une entite gold est COUVERTE si l'union des spans predits (tous types
  confondus) couvre 100 % de ses caracteres significatifs (espaces/ponctuation
  de bord exclus). Un IBAN masque aux 3/4 est une FUITE, pas un succes partiel.
- leak rate = 1 - (couvertes / total), par type et global.
- partial rate = entites touchees mais pas entierement couvertes (fuites
  quand meme, comptees a part car symptome different : frontieres de spans).
- over-masking = part des caracteres predits qui ne recouvrent aucune entite
  gold (bruit impose au LLM).
- F1 span exact avec normalisation des frontieres (strip ponctuation, espaces
  et titres M./Mme/Me/Dr) + match du type.
"""

import json
from collections import defaultdict
from dataclasses import dataclass

_TITLES = ("M. ", "Mme ", "Me ", "Dr ", "Monsieur ", "Madame ", "Maître ")
_STRIP_CHARS = " \t\n.,;:()[]«»\"'"


@dataclass(frozen=True)
class Span:
    start: int
    end: int
    type: str

    def normalized(self, text: str) -> "Span":
        s, e = self.start, self.end
        while s < e and text[s] in _STRIP_CHARS:
            s += 1
        while e > s and text[e - 1] in _STRIP_CHARS:
            e -= 1
        for t in _TITLES:
            if text[s:e].startswith(t):
                s += len(t)
                break
        return Span(s, e, self.type)


def _significant_chars(text: str, span: Span) -> set[int]:
    n = span.normalized(text)
    return {i for i in range(n.start, n.end) if text[i] not in _STRIP_CHARS}


def load_jsonl(path) -> dict[str, dict]:
    docs = {}
    with open(path, encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if line:
                d = json.loads(line)
                docs[d["id"]] = d
    return docs


def _spans(doc: dict) -> list[Span]:
    return [Span(e["start"], e["end"], e["type"]) for e in doc.get("entities", [])]


def score(gold_docs: dict[str, dict], pred_docs: dict[str, dict]) -> dict:
    per_type = defaultdict(lambda: {"total": 0, "covered": 0, "partial": 0, "missed": 0})
    exact = defaultdict(lambda: {"tp": 0, "fp": 0, "fn": 0})
    overmask_chars = 0
    pred_chars = 0

    for doc_id, gold in gold_docs.items():
        text = gold["text"]
        pred = pred_docs.get(doc_id, {"entities": []})
        gspans, pspans = _spans(gold), _spans(pred)

        pred_cover = set()
        for p in pspans:
            pred_cover |= set(range(p.start, p.end))

        gold_cover = set()
        for g in gspans:
            gold_cover |= set(range(g.start, g.end))

        # leak / partial par entite gold, couverture tous types confondus
        for g in gspans:
            sig = _significant_chars(text, g)
            if not sig:
                continue
            hit = len(sig & pred_cover)
            st = per_type[g.type]
            st["total"] += 1
            if hit == len(sig):
                st["covered"] += 1
            elif hit > 0:
                st["partial"] += 1
            else:
                st["missed"] += 1

        # over-masking : caracteres significatifs predits hors de tout gold
        sig_pred = {i for i in pred_cover if i < len(text) and text[i] not in _STRIP_CHARS}
        pred_chars += len(sig_pred)
        overmask_chars += len(sig_pred - gold_cover)

        # F1 exact (frontieres normalisees + type)
        gset = {(s.normalized(text)) for s in gspans}
        pset = {(s.normalized(text)) for s in pspans}
        for s in gset & pset:
            exact[s.type]["tp"] += 1
        for s in gset - pset:
            exact[s.type]["fn"] += 1
        for s in pset - gset:
            exact[s.type]["fp"] += 1

    report = {"per_type": {}, "global": {}}
    tot = {"total": 0, "covered": 0, "partial": 0, "missed": 0}
    for etype in sorted(per_type):
        st = per_type[etype]
        ex = exact[etype]
        prec = ex["tp"] / (ex["tp"] + ex["fp"]) if ex["tp"] + ex["fp"] else 0.0
        rec = ex["tp"] / (ex["tp"] + ex["fn"]) if ex["tp"] + ex["fn"] else 0.0
        f1 = 2 * prec * rec / (prec + rec) if prec + rec else 0.0
        report["per_type"][etype] = {
            **st,
            "leak_rate": 1 - st["covered"] / st["total"] if st["total"] else 0.0,
            "exact_precision": round(prec, 4),
            "exact_recall": round(rec, 4),
            "exact_f1": round(f1, 4),
        }
        for k in tot:
            tot[k] += st[k]

    report["global"] = {
        **tot,
        "leak_rate": 1 - tot["covered"] / tot["total"] if tot["total"] else 0.0,
        "overmask_rate": overmask_chars / pred_chars if pred_chars else 0.0,
    }
    return report


def format_report(report: dict) -> str:
    lines = [
        f"{'type':<12} {'total':>6} {'covered':>8} {'partial':>8} {'missed':>7} "
        f"{'LEAK':>7} {'P':>6} {'R':>6} {'F1':>6}"
    ]
    for etype, st in report["per_type"].items():
        lines.append(
            f"{etype:<12} {st['total']:>6} {st['covered']:>8} {st['partial']:>8} "
            f"{st['missed']:>7} {st['leak_rate']:>7.2%} {st['exact_precision']:>6.2f} "
            f"{st['exact_recall']:>6.2f} {st['exact_f1']:>6.2f}"
        )
    g = report["global"]
    lines.append("-" * len(lines[0]))
    lines.append(
        f"{'GLOBAL':<12} {g['total']:>6} {g['covered']:>8} {g['partial']:>8} "
        f"{g['missed']:>7} {g['leak_rate']:>7.2%}   over-masking {g['overmask_rate']:.2%}"
    )
    return "\n".join(lines)


def main():
    import argparse

    ap = argparse.ArgumentParser(description="Score des predictions PII vs gold")
    ap.add_argument("gold")
    ap.add_argument("pred")
    ap.add_argument("--json", action="store_true", help="sortie JSON complete")
    args = ap.parse_args()

    report = score(load_jsonl(args.gold), load_jsonl(args.pred))
    if args.json:
        print(json.dumps(report, ensure_ascii=False, indent=2))
    else:
        print(format_report(report))


if __name__ == "__main__":
    main()