japan-opendata commited on
Commit
97cc6d4
·
verified ·
1 Parent(s): 8627179

Add model card and helper scripts (pre-release, private)

Browse files
README.md ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - ja
5
+ pipeline_tag: token-classification
6
+ library_name: transformers
7
+ base_model: tohoku-nlp/bert-base-japanese-v3
8
+ datasets:
9
+ - nvidia/Nemotron-PII-Japan
10
+ tags:
11
+ - onnx
12
+ - onnxruntime
13
+ - transformers.js
14
+ - pii
15
+ - pii-detection
16
+ - ner
17
+ - privacy
18
+ - redaction
19
+ - presidio
20
+ - japanese
21
+ widget:
22
+ - text: "担当は山田太郎(電話 090-1234-5678、メール taro.yamada@example.com)です。"
23
+ model-index:
24
+ - name: ja-pii-ner-v1
25
+ results:
26
+ - task:
27
+ type: token-classification
28
+ name: Token Classification
29
+ dataset:
30
+ type: nvidia/Nemotron-PII-Japan
31
+ name: Nemotron-PII-Japan (test split, converted)
32
+ metrics:
33
+ - type: f1
34
+ value: 0.977
35
+ name: Span F1 (micro, exact match)
36
+ - type: precision
37
+ value: 0.9965
38
+ name: Span Precision (micro)
39
+ - type: recall
40
+ value: 0.9582
41
+ name: Span Recall (micro)
42
+ ---
43
+
44
+ # ja-pii-ner-v1 — Japanese PII Detection (Token Classification)
45
+
46
+ A small (111M parameters) encoder model that detects 18 types of personally
47
+ identifiable information (PII) in Japanese text and returns exact character
48
+ spans. CPU-friendly, ONNX included, Apache 2.0. No real personal data was
49
+ used for training or evaluation — all data is synthetic.
50
+
51
+ 日本語の文章から18種類の個人情報を文字位置つきで検出する小規模モデルです。
52
+ 学習と評価に実在の個人情報は使っていません(すべて合成データ)。
53
+
54
+ ## What it does
55
+
56
+ Given Japanese text, the model returns character spans for these labels:
57
+
58
+ PERSON, ORGANIZATION, ADDRESS, POSTAL_CODE, PHONE, EMAIL, DATE_OF_BIRTH,
59
+ MY_NUMBER, BANK_ACCOUNT, CREDIT_CARD, DRIVER_LICENSE, PASSPORT,
60
+ HEALTH_INSURANCE, EMPLOYEE_ID, IP_ADDRESS, URL_PERSONAL, USERNAME, SECRET
61
+
62
+ The model only detects. Masking/replacement is up to you — see `redact.py`
63
+ in this repository for a ready-made helper.
64
+
65
+ ## Quick start
66
+
67
+ With transformers:
68
+
69
+ ```python
70
+ from transformers import pipeline
71
+
72
+ ner = pipeline("token-classification",
73
+ model="japan-opendata/ja-pii-ner-v1",
74
+ aggregation_strategy="simple")
75
+ print(ner("担当は山田太郎(電話 090-1234-5678)です。"))
76
+ ```
77
+
78
+ For production use (span merging, long-document chunking, masking), use the
79
+ bundled single-file helper — no external calls, only `transformers` + `torch`:
80
+
81
+ ```python
82
+ from redact import redact
83
+ redact("連絡先は taro.yamada@example.com です")
84
+ # -> '連絡先は <EMAIL> です'
85
+ ```
86
+
87
+ With ONNX Runtime only (no PyTorch), see `examples/onnx_example.py`.
88
+ For Microsoft Presidio, see `presidio_recognizer.py`: a custom recognizer
89
+ that returns character offsets directly from the model, avoiding the
90
+ spaCy-tokenization alignment problems of the stock TransformersNlpEngine
91
+ for Japanese.
92
+
93
+ ## Evaluation (measured, exact-span match)
94
+
95
+ Test set: the full test split of nvidia/Nemotron-PII-Japan converted to
96
+ character spans (10,001 documents, 43,064 gold spans), plus a separately
97
+ generated no-PII set of 2,068 documents. Threshold-free BIO argmax decoding;
98
+ no tuning was done against the test set.
99
+
100
+ Overall:
101
+
102
+ | Metric | Value |
103
+ |---|---|
104
+ | Precision (micro) | 0.9965 |
105
+ | Recall (micro) | 0.9582 |
106
+ | F1 (micro) | 0.9770 |
107
+ | False-positive rate on no-PII documents | 0.0000 (0 / 2,068 documents) |
108
+
109
+ Per label (Precision / Recall / F1):
110
+
111
+ | Label | P | R | F1 |
112
+ |---|---|---|---|
113
+ | PERSON | 0.9987 | 0.9577 | 0.9778 |
114
+ | ORGANIZATION | 0.9918 | 0.8790 | 0.9320 |
115
+ | ADDRESS | 0.9919 | 0.9610 | 0.9762 |
116
+ | POSTAL_CODE | 1.0000 | 1.0000 | 1.0000 |
117
+ | PHONE | 0.9951 | 0.9562 | 0.9753 |
118
+ | EMAIL | 1.0000 | 1.0000 | 1.0000 |
119
+ | DATE_OF_BIRTH | 1.0000 | 1.0000 | 1.0000 |
120
+ | MY_NUMBER | 1.0000 | 1.0000 | 1.0000 |
121
+ | BANK_ACCOUNT | 1.0000 | 1.0000 | 1.0000 |
122
+ | CREDIT_CARD | 1.0000 | 1.0000 | 1.0000 |
123
+ | HEALTH_INSURANCE | 1.0000 | 1.0000 | 1.0000 |
124
+ | EMPLOYEE_ID | 0.9992 | 0.9990 | 0.9991 |
125
+ | IP_ADDRESS | 0.9984 | 0.9984 | 0.9984 |
126
+ | URL_PERSONAL | 1.0000 | 1.0000 | 1.0000 |
127
+ | USERNAME | 0.9989 | 0.9978 | 0.9984 |
128
+ | SECRET | 0.9620 | 0.8000 | 0.8736 |
129
+
130
+ DRIVER_LICENSE and PASSPORT have no gold spans in this test set (the source
131
+ dataset does not contain them; they are supplied only by our synthetic data),
132
+ so they are not evaluated by the numbers above.
133
+
134
+ CPU speed (Intel i7-11700F, 200 documents, mean per document):
135
+
136
+ | Runtime | ms/doc | docs/sec |
137
+ |---|---|---|
138
+ | PyTorch (fp32) | 813.96 | 1.23 |
139
+ | ONNX (fp32) | 224.16 | 4.46 |
140
+
141
+ The ONNX fp32 export reproduces the PyTorch model exactly on the full test
142
+ set (identical TP/FP/FN on every label).
143
+
144
+ INT8 note: dynamic INT8 quantization was measured (188 MB, 122 ms/doc) but
145
+ is not shipped in v1 — micro F1 dropped to 0.8988, with large recall losses
146
+ on numeric/symbol pattern labels (IP_ADDRESS, URL_PERSONAL, SECRET,
147
+ BANK_ACCOUNT). Static INT8 quantization degraded the model entirely.
148
+ fp32 is the supported configuration.
149
+
150
+ ### Comparison on the same test set
151
+
152
+ az225/privacy-masker-ja-pii-ner-30m was evaluated on the identical test set.
153
+ Only 3 of its labels map 1-to-1 to ours (PERSON, ORGANIZATION, ADDRESS;
154
+ 24,149 gold spans), so the comparison is restricted to those:
155
+
156
+ | Model | P | R | F1 (3 labels) |
157
+ |---|---|---|---|
158
+ | ja-pii-ner-v1 | 0.9947 | 0.9325 | 0.9626 |
159
+ | az225/privacy-masker-ja-pii-ner-30m | 0.6343 | 0.6809 | 0.6568 |
160
+
161
+ Read this with care: the label definitions differ. az225 splits place names
162
+ into a separate LOCATION label; counting LOCATION as ADDRESS raises its
163
+ ADDRESS recall to 0.9821. Its PERSON recall (0.9961) is higher than ours
164
+ (0.9577). The gap above is partly a definitions gap, not only a quality gap.
165
+
166
+ ## Training data
167
+
168
+ - nvidia/Nemotron-PII-Japan (CC BY 4.0, NVIDIA / Elith): 79,998 training
169
+ documents converted from the published parquet files.
170
+ - 25,000 synthetic documents generated by the lab from public parts data:
171
+ place names from Japan Post postal-code data and the Digital Agency
172
+ address registry (PDL 1.0), organization names from the National Tax
173
+ Agency corporate-number registry (PDL 1.0). Generation code and sources
174
+ are published with the companion dataset.
175
+
176
+ Base model: tohoku-nlp/bert-base-japanese-v3. Trained for 3 epochs on
177
+ 104,998 documents.
178
+
179
+ ## Limitations
180
+
181
+ - Trained on synthetic data. Performance on real documents will differ;
182
+ the numbers above are not a guarantee of complete detection.
183
+ - ORGANIZATION recall (0.8790) and SECRET recall (0.8000) are the weakest
184
+ points. Organization names that look like person names, and secrets in
185
+ unusual formats, are the typical misses.
186
+ - DRIVER_LICENSE and PASSPORT are not covered by the public test set and
187
+ are therefore unevaluated (see above).
188
+ - The source dataset is known to contain some missing gold labels; a small
189
+ part of the measured false positives may be unlabeled true PII.
190
+ - Inputs longer than 512 tokens are truncated by the model itself; use the
191
+ chunking in `redact.py` for long documents.
192
+
193
+ ## License
194
+
195
+ Apache 2.0. The training data licenses are listed above; the base model is
196
+ distributed under its own terms by its authors.
examples/onnx_example.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ONNX Runtime だけで ja-pii-ner-v1 を動かす最小例 (PyTorch 不要)。
3
+
4
+ pip install onnxruntime transformers huggingface_hub
5
+ python onnx_example.py
6
+ """
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+
12
+ sys.path.insert(0, str(Path(__file__).parent.parent))
13
+ from offsets_util import get_enc # noqa: E402
14
+
15
+ MODEL_ID = "japan-opendata/ja-pii-ner-v1"
16
+ ONNX_PATH = "onnx/model.onnx"
17
+
18
+
19
+ def main():
20
+ import onnxruntime as ort
21
+ from huggingface_hub import hf_hub_download
22
+ from transformers import AutoConfig, AutoTokenizer
23
+
24
+ config = AutoConfig.from_pretrained(MODEL_ID)
25
+ id2label = config.id2label
26
+ tok = AutoTokenizer.from_pretrained(MODEL_ID)
27
+ onnx_file = hf_hub_download(MODEL_ID, ONNX_PATH)
28
+ sess = ort.InferenceSession(onnx_file, providers=["CPUExecutionProvider"])
29
+ input_names = {i.name for i in sess.get_inputs()}
30
+
31
+ text = "担当は山田太郎(電話 090-1234-5678、メール taro.yamada@example.com)です。"
32
+ enc, offsets, _ = get_enc(tok, text, 512)
33
+ feed = {k: np.array([v], dtype=np.int64) for k, v in enc.items()
34
+ if k in input_names}
35
+ if "token_type_ids" in input_names and "token_type_ids" not in feed:
36
+ feed["token_type_ids"] = np.zeros_like(feed["input_ids"])
37
+ label_ids = sess.run(None, feed)[0][0].argmax(-1).tolist()
38
+
39
+ spans, cur = [], None
40
+ for (a, b), tid in zip(offsets, label_ids):
41
+ if a == b:
42
+ continue
43
+ lab = id2label[tid]
44
+ if lab.startswith("B-"):
45
+ if cur:
46
+ spans.append(cur)
47
+ cur = {"start": a, "end": b, "label": lab[2:]}
48
+ elif lab.startswith("I-") and cur and cur["label"] == lab[2:]:
49
+ cur["end"] = b
50
+ else:
51
+ if cur:
52
+ spans.append(cur)
53
+ cur = None
54
+ if cur:
55
+ spans.append(cur)
56
+ for s in spans:
57
+ print(s["label"], text[s["start"]:s["end"]])
58
+
59
+
60
+ if __name__ == "__main__":
61
+ main()
examples/pipeline_example.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """transformers の pipeline で ja-pii-ner-v1 を動かす最小例。
3
+
4
+ pip install transformers torch
5
+ python pipeline_example.py
6
+
7
+ 注意:pipeline の生出力はサブワード単位の断片です。文字スパンの結合や
8
+ 長文の分割まで含めた実用処理には、リポジトリ同梱の redact.py を使ってください。
9
+ """
10
+ from transformers import pipeline
11
+
12
+ MODEL_ID = "japan-opendata/ja-pii-ner-v1"
13
+
14
+ ner = pipeline("token-classification", model=MODEL_ID,
15
+ aggregation_strategy="simple")
16
+ text = "担当は山田太郎(電話 090-1234-5678、メール taro.yamada@example.com)です。"
17
+ for ent in ner(text):
18
+ print(ent["entity_group"], ent["word"], round(float(ent["score"]), 3))
offsets_util.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """トークナイザのオフセット取得の共通部品。
3
+
4
+ bert-base-japanese-v3 のようなスロートークナイザ (MeCab 系) は offset_mapping を
5
+ 返さないため、NFKC 正規化したテキスト上でトークン表層を順に照合して補完する。
6
+ オフセットは書記素クラスタ単位の位置マップで元の文字列の座標へ逆変換して返すため、
7
+ 全角記号・全角英字・半角カナ結合など NFKC で文字数が変わる箇所でもずれない。
8
+ """
9
+ import unicodedata
10
+
11
+
12
+ def _clusters(text):
13
+ """書記素クラスタの近似分割 (基底文字+結合文字)。"""
14
+ clusters, cur = [], ""
15
+ for ch in text:
16
+ if cur and (unicodedata.combining(ch) or unicodedata.category(ch) in ("Mn", "Me", "Mc") or ch in "\uff9e\uff9f"):
17
+ cur += ch
18
+ else:
19
+ if cur:
20
+ clusters.append(cur)
21
+ cur = ch
22
+ if cur:
23
+ clusters.append(cur)
24
+ return clusters
25
+
26
+
27
+ def nfkc_with_map(text):
28
+ """NFKC 正規化と、正規化後の各文字位置から元の位置への対応表を返す。
29
+
30
+ 戻り値: (norm, start_map, end_map)
31
+ """
32
+ norm_parts, start_map, end_map = [], [], []
33
+ pos = 0
34
+ for cl in _clusters(text):
35
+ n = unicodedata.normalize("NFKC", cl)
36
+ for _ in n:
37
+ start_map.append(pos)
38
+ end_map.append(pos + len(cl))
39
+ norm_parts.append(n)
40
+ pos += len(cl)
41
+ return "".join(norm_parts), start_map, end_map
42
+
43
+
44
+ def get_enc(tok, text, max_len=None):
45
+ """(enc, offsets, base_text) を返す。offsets は元の text に対する座標。"""
46
+ if tok.is_fast:
47
+ enc = tok(text, truncation=max_len is not None, max_length=max_len,
48
+ return_offsets_mapping=True)
49
+ offsets = enc.pop("offset_mapping")
50
+ return enc, offsets, text
51
+ norm, start_map, end_map = nfkc_with_map(text)
52
+ enc = tok(norm, truncation=max_len is not None, max_length=max_len)
53
+ tokens = tok.convert_ids_to_tokens(enc["input_ids"])
54
+ offsets, pos = [], 0
55
+ for t in tokens:
56
+ if t in tok.all_special_tokens:
57
+ offsets.append((0, 0))
58
+ continue
59
+ surface = t[2:] if t.startswith("##") else t
60
+ idx = norm.find(surface, pos)
61
+ if idx < 0:
62
+ offsets.append((0, 0))
63
+ continue
64
+ offsets.append((start_map[idx], end_map[idx + len(surface) - 1]))
65
+ pos = idx + len(surface)
66
+ return enc, offsets, text
presidio_recognizer.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Microsoft Presidio へ ja-pii-ner-v1 を組み込むためのカスタム Recognizer。
3
+
4
+ Presidio 標準の TransformersNlpEngine は spaCy のトークナイズを前段に挟むため、
5
+ 日本語では文字スパンの整合が崩れやすい。本実装はモデルから直接文字オフセットを
6
+ 返すため、その問題を避けられる。
7
+
8
+ 使い方:
9
+ from presidio_analyzer import AnalyzerEngine
10
+ from presidio_recognizer import JaPiiRecognizer
11
+
12
+ analyzer = AnalyzerEngine()
13
+ analyzer.registry.add_recognizer(JaPiiRecognizer())
14
+ results = analyzer.analyze(text="担当は山田太郎です", language="ja")
15
+ """
16
+ import sys
17
+ from pathlib import Path
18
+
19
+ sys.path.insert(0, str(Path(__file__).parent))
20
+ from redact import detect # noqa: E402
21
+
22
+ try:
23
+ from presidio_analyzer import EntityRecognizer, RecognizerResult
24
+ except ImportError as e: # pragma: no cover
25
+ raise ImportError("pip install presidio-analyzer が必要です") from e
26
+
27
+ # 当方ラベル -> Presidio のエンティティ名
28
+ LABEL_MAP = {
29
+ "PERSON": "PERSON",
30
+ "ORGANIZATION": "ORGANIZATION",
31
+ "ADDRESS": "LOCATION",
32
+ "POSTAL_CODE": "LOCATION",
33
+ "PHONE": "PHONE_NUMBER",
34
+ "EMAIL": "EMAIL_ADDRESS",
35
+ "DATE_OF_BIRTH": "DATE_TIME",
36
+ "MY_NUMBER": "JP_MY_NUMBER",
37
+ "BANK_ACCOUNT": "JP_BANK_ACCOUNT",
38
+ "CREDIT_CARD": "CREDIT_CARD",
39
+ "DRIVER_LICENSE": "JP_DRIVER_LICENSE",
40
+ "PASSPORT": "JP_PASSPORT",
41
+ "HEALTH_INSURANCE": "JP_HEALTH_INSURANCE",
42
+ "EMPLOYEE_ID": "EMPLOYEE_ID",
43
+ "IP_ADDRESS": "IP_ADDRESS",
44
+ "URL_PERSONAL": "URL",
45
+ "USERNAME": "USERNAME",
46
+ "SECRET": "SECRET",
47
+ }
48
+
49
+
50
+ class JaPiiRecognizer(EntityRecognizer):
51
+ def __init__(self, supported_language="ja"):
52
+ super().__init__(supported_entities=list(set(LABEL_MAP.values())),
53
+ supported_language=supported_language)
54
+
55
+ def load(self):
56
+ pass
57
+
58
+ def analyze(self, text, entities, nlp_artifacts=None):
59
+ wanted = set(entities) if entities else None
60
+ out = []
61
+ for s in detect(text):
62
+ ent = LABEL_MAP.get(s["label"], s["label"])
63
+ if wanted and ent not in wanted:
64
+ continue
65
+ out.append(RecognizerResult(entity_type=ent, start=s["start"],
66
+ end=s["end"], score=0.85))
67
+ return out
redact.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ja-pii-ner-v1 の単体ヘルパー:日本語テキストから個人情報を検出してマスクする。
3
+
4
+ 依存は transformers と torch のみ。外部通信は一切しない。
5
+ 長い文書は文字単位の重なりつき分割で処理し、結果を元の座標へ戻す。
6
+
7
+ 使い方:
8
+ from redact import redact
9
+ print(redact("連絡先は taro.yamada@example.com です"))
10
+ # -> 連絡先は <EMAIL> です
11
+
12
+ from redact import detect
13
+ spans = detect("担当は山田太郎(090-1234-5678)です")
14
+ """
15
+ import sys
16
+ import unicodedata
17
+ from pathlib import Path
18
+
19
+ sys.path.insert(0, str(Path(__file__).parent))
20
+ from offsets_util import get_enc # noqa: E402
21
+
22
+ MODEL_ID = "japan-opendata/ja-pii-ner-v1"
23
+ CHUNK_CHARS = 1200
24
+ OVERLAP_CHARS = 200
25
+
26
+ _model = None
27
+ _tok = None
28
+ _id2label = None
29
+
30
+
31
+ def _load(model_id=MODEL_ID):
32
+ global _model, _tok, _id2label
33
+ if _model is None:
34
+ import torch # noqa: F401
35
+ from transformers import AutoModelForTokenClassification, AutoTokenizer
36
+ _tok = AutoTokenizer.from_pretrained(model_id)
37
+ _model = AutoModelForTokenClassification.from_pretrained(model_id)
38
+ _model.eval()
39
+ _id2label = _model.config.id2label
40
+ return _model, _tok
41
+
42
+
43
+ def _decode(offsets, label_ids):
44
+ spans, cur = [], None
45
+ for (a, b), tid in zip(offsets, label_ids):
46
+ if a == b:
47
+ continue
48
+ lab = _id2label[tid]
49
+ if lab.startswith("B-"):
50
+ if cur:
51
+ spans.append(cur)
52
+ cur = {"start": a, "end": b, "label": lab[2:]}
53
+ elif lab.startswith("I-") and cur and cur["label"] == lab[2:]:
54
+ cur["end"] = b
55
+ else:
56
+ if cur:
57
+ spans.append(cur)
58
+ cur = None
59
+ if cur:
60
+ spans.append(cur)
61
+ return spans
62
+
63
+
64
+ def _predict_chunk(text):
65
+ import torch
66
+ model, tok = _load()
67
+ enc, offsets, _ = get_enc(tok, text, 512)
68
+ # transformers 5.x では token_type_ids が返らないことがあるため、無い場合は 0 で補う
69
+ feed = {k: torch.tensor([v]) for k, v in enc.items()}
70
+ if "token_type_ids" not in feed:
71
+ feed["token_type_ids"] = torch.zeros_like(feed["input_ids"])
72
+ with torch.no_grad():
73
+ ids = model(**feed).logits.argmax(-1)[0].tolist()
74
+ return _decode(offsets, ids)
75
+
76
+
77
+ def detect(text):
78
+ """スパン一覧 [{start, end, label, text}] を返す。座標は元の text 基準。"""
79
+ if len(text) <= CHUNK_CHARS:
80
+ raw = _predict_chunk(text)
81
+ else:
82
+ raw, pos = [], 0
83
+ while pos < len(text):
84
+ chunk = text[pos:pos + CHUNK_CHARS]
85
+ for s in _predict_chunk(chunk):
86
+ raw.append({"start": s["start"] + pos, "end": s["end"] + pos,
87
+ "label": s["label"]})
88
+ if pos + CHUNK_CHARS >= len(text):
89
+ break
90
+ pos += CHUNK_CHARS - OVERLAP_CHARS
91
+ seen, out = set(), []
92
+ for s in sorted(raw, key=lambda x: (x["start"], x["end"])):
93
+ key = (s["start"], s["end"], s["label"])
94
+ if key in seen:
95
+ continue
96
+ seen.add(key)
97
+ out.append({**s, "text": text[s["start"]:s["end"]]})
98
+ return out
99
+
100
+
101
+ def redact(text, mask=None):
102
+ """検出箇所を <LABEL> (または mask の指定) で置換した文字列を返す。"""
103
+ out, last = [], 0
104
+ for s in detect(text):
105
+ if s["start"] < last:
106
+ continue
107
+ out.append(text[last:s["start"]])
108
+ out.append(mask(s) if callable(mask) else f"<{s['label']}>")
109
+ last = s["end"]
110
+ out.append(text[last:])
111
+ return "".join(out)
112
+
113
+
114
+ if __name__ == "__main__":
115
+ sample = sys.argv[1] if len(sys.argv) > 1 else \
116
+ "担当は山田太郎(電話 090-1234-5678、メール taro.yamada@example.com)です。"
117
+ print(redact(sample))
118
+ for s in detect(sample):
119
+ print(s)