File size: 9,898 Bytes
b5cbcc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
"""置換後データの PII 残存を、独立した検出器(GLiNER-ja)で確認する(監査項目12)。

``pii_detector.py`` と同じ検出器で再走査しても残存は必ず 0 になるため、
学習済み日本語 PII NER ``DataSign/gliner-ja-pii-v1``(Apache-2.0)で
サンプルを走査し、プレースホルダー以外に残っている氏名・電話・住所・
メール・口座番号を数える。``--original`` に置換前の parquet を渡すと、
同じ文書で GLiNER が置換前に検出した実体のうち置換後に消えている割合
(決定的検出器の再現率の目安)も出す。

    uv sync --group pii-check
    uv run python abeja-cc-ja/src/pii_residual_check.py --input <replaced.parquet> --sample 500 --output pii_residual.json

モデルは最大160トークンのため、文書を文字数で分割して重なり付きで走査する。
"""

from __future__ import annotations

import argparse
import json
import random
import time
import unicodedata
from collections import Counter, defaultdict
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

import pyarrow.parquet as pq

from pii_detector import NAME_CONTEXT_WINDOW, TITLE_CONTEXT_RE, _ORG_RE, _same_sentence_window


MODEL_NAME = "DataSign/gliner-ja-pii-v1"
LABELS = ["person name", "phone number", "address", "email address", "account number"]
LABEL_TO_TYPE = {
    "person name": "person_name",
    "phone number": "phone",
    "address": "address",
    "email address": "email",
    "account number": "bank_account",
}
PLACEHOLDER_MARKERS = ("<EMAIL>", "<PHONE>", "<ADDRESS>", "<PERSON_NAME>", "<PERSON_AFFILIATION>", "<MY_NUMBER>", "<CREDIT_CARD>", "<BANK_ACCOUNT>")


def load_model(device: str | None):
    from gliner import GLiNER
    from gliner.data_processing import WordsSplitter

    class JapaneseSplitterNoWS:
        def __init__(self) -> None:
            self._base = WordsSplitter(splitter_type="janome")

        def __call__(self, text: str):
            for token, start, end in self._base(text):
                if token.strip() == "":
                    continue
                yield token, start, end

    model = GLiNER.from_pretrained(MODEL_NAME, max_width=25)
    model.data_processor.words_splitter = JapaneseSplitterNoWS()
    if device:
        try:
            model = model.to(device)
        except Exception:  # noqa: BLE001 - デバイス非対応時はCPUのまま
            pass
    model.eval()
    return model


def chunks(text: str, size: int, overlap: int):
    start = 0
    while start < len(text):
        end = min(len(text), start + size)
        yield start, text[start:end]
        if end == len(text):
            break
        start = end - overlap


def predict(model, text: str, threshold: float, chunk_chars: int, overlap: int) -> list[dict[str, Any]]:
    found: dict[tuple[str, int, int], dict[str, Any]] = {}
    for offset, piece in chunks(text, chunk_chars, overlap):
        for entity in model.predict_entities(piece, LABELS, threshold=threshold):
            key = (entity["label"], offset + entity["start"], offset + entity["end"])
            if key not in found:
                found[key] = {"label": entity["label"], "start": key[1], "end": key[2], "text": entity["text"], "score": round(float(entity["score"]), 3)}
    return sorted(found.values(), key=lambda item: (item["start"], item["end"]))


def is_placeholder(text: str) -> bool:
    return any(marker in text for marker in PLACEHOLDER_MARKERS) or "<" in text


def mask(text: str) -> str:
    return text[:1] + "*" * max(1, len(text) - 1)


def main(argv: list[str] | None = None) -> None:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--input", type=Path, required=True, help="置換後の parquet(url, content)")
    parser.add_argument("--original", type=Path, default=None, help="置換前の parquet(同じ行順)。再現率の目安を出す")
    parser.add_argument("--sample", type=int, default=500)
    parser.add_argument("--seed", type=int, default=20260904)
    parser.add_argument("--threshold", type=float, default=0.5)
    parser.add_argument("--chunk-chars", type=int, default=200)
    parser.add_argument("--overlap", type=int, default=40)
    parser.add_argument("--max-chars", type=int, default=3000, help="1文書あたり走査する最大文字数")
    parser.add_argument("--device", default=None, help="cpu / mps / cuda(既定はGLiNERの既定)")
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args(argv)

    table = pq.read_table(args.input, columns=["url", "content"])
    total = table.num_rows
    rng = random.Random(args.seed)
    indices = sorted(rng.sample(range(total), min(args.sample, total)))
    original = pq.read_table(args.original, columns=["content"]) if args.original else None
    model = load_model(args.device)

    residual_counts: Counter = Counter()
    residual_docs: Counter = Counter()
    examples: dict[str, list[dict[str, Any]]] = defaultdict(list)
    recall_found: Counter = Counter()
    recall_removed: Counter = Counter()
    # 「個人名+所属」の定義(同一文・前後25文字に所属か役職)に該当する人名だけの再現率
    ctx_found = 0
    ctx_removed = 0
    started = time.perf_counter()
    docs_with_residual = 0
    for index in indices:
        row = table.slice(index, 1).to_pylist()[0]
        text = unicodedata.normalize("NFKC", row.get("content") or "")[: args.max_chars]
        entities = [e for e in predict(model, text, args.threshold, args.chunk_chars, args.overlap) if not is_placeholder(e["text"])]
        if entities:
            docs_with_residual += 1
        seen_types = set()
        for entity in entities:
            pii_type = LABEL_TO_TYPE[entity["label"]]
            residual_counts[pii_type] += 1
            seen_types.add(pii_type)
            if len(examples[pii_type]) < 5:
                context = text[max(0, entity["start"] - 25): entity["start"]] + "[" + mask(entity["text"]) + "]" + text[entity["end"]: entity["end"] + 25]
                examples[pii_type].append({"record_index": index, "url": row.get("url"), "score": entity["score"], "context_masked": context.replace("\n", " ")})
        for pii_type in seen_types:
            residual_docs[pii_type] += 1
        if original is not None:
            original_text = unicodedata.normalize("NFKC", original.slice(index, 1).to_pylist()[0].get("content") or "")[: args.max_chars]
            for entity in predict(model, original_text, args.threshold, args.chunk_chars, args.overlap):
                pii_type = LABEL_TO_TYPE[entity["label"]]
                recall_found[pii_type] += 1
                removed = entity["text"] not in text
                if removed:
                    recall_removed[pii_type] += 1
                if pii_type == "person_name":
                    before, after = _same_sentence_window(original_text, entity["start"], entity["end"], NAME_CONTEXT_WINDOW)
                    if _ORG_RE.search(before) or _ORG_RE.search(after) or TITLE_CONTEXT_RE.search(before) or TITLE_CONTEXT_RE.search(after):
                        ctx_found += 1
                        ctx_removed += removed
    elapsed = time.perf_counter() - started
    result = {
        "checked_at_utc": datetime.now(timezone.utc).isoformat(),
        "detector": {"model": MODEL_NAME, "license": "Apache-2.0", "labels": LABELS, "threshold": args.threshold,
                     "chunk_chars": args.chunk_chars, "overlap": args.overlap, "max_chars": args.max_chars},
        "input": str(args.input), "total_records": total, "sampled_records": len(indices), "seed": args.seed,
        "elapsed_s": round(elapsed, 1),
        "residual": {
            "records_with_any_residual": docs_with_residual,
            "records_with_residual_rate": round(docs_with_residual / max(1, len(indices)), 4),
            "by_type_entities": dict(residual_counts),
            "by_type_records": dict(residual_docs),
            "examples_masked": examples,
        },
        "note_ja": "GLiNER-ja が置換後テキストで検出した実体(プレースホルダーを除く)。氏名は公人・著者名・作品中の人名も含むため、残存の要否は目視で判断する。",
    }
    if original is not None:
        result["recall_estimate_person_name_with_affiliation_context"] = {
            "gliner_found_in_original": ctx_found,
            "removed_after_replacement": ctx_removed,
            "removed_rate": round(ctx_removed / ctx_found, 3) if ctx_found else None,
            "note_ja": "GLiNER-ja が検出した人名のうち、同一文・前後25文字に所属か役職がある(=個人名+所属の定義に該当する)ものの置換率。",
        }
        result["recall_estimate"] = {
            pii_type: {"gliner_found_in_original": recall_found[pii_type], "removed_after_replacement": recall_removed[pii_type],
                       "removed_rate": round(recall_removed[pii_type] / recall_found[pii_type], 3) if recall_found[pii_type] else None}
            for pii_type in sorted(recall_found)
        }
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(json.dumps({"sampled": len(indices), "records_with_residual": docs_with_residual, "by_type": dict(residual_counts),
                      "recall_estimate": result.get("recall_estimate"),
                      "recall_person_name_with_affiliation_context": result.get("recall_estimate_person_name_with_affiliation_context"),
                      "elapsed_s": round(elapsed, 1)}, ensure_ascii=False))


if __name__ == "__main__":
    main()