ja-pii-ner-v1 / examples /onnx_example.py
japan-opendata's picture
Add model card and helper scripts (pre-release, private)
97cc6d4 verified
Raw History Blame Contribute Delete
1.98 kB
#!/usr/bin/env python3
"""ONNX Runtime だけで ja-pii-ner-v1 を動かす最小例 (PyTorch 不要)。
pip install onnxruntime transformers huggingface_hub
python onnx_example.py
"""
import sys
from pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file__).parent.parent))
from offsets_util import get_enc # noqa: E402
MODEL_ID = "japan-opendata/ja-pii-ner-v1"
ONNX_PATH = "onnx/model.onnx"
def main():
import onnxruntime as ort
from huggingface_hub import hf_hub_download
from transformers import AutoConfig, AutoTokenizer
config = AutoConfig.from_pretrained(MODEL_ID)
id2label = config.id2label
tok = AutoTokenizer.from_pretrained(MODEL_ID)
onnx_file = hf_hub_download(MODEL_ID, ONNX_PATH)
sess = ort.InferenceSession(onnx_file, providers=["CPUExecutionProvider"])
input_names = {i.name for i in sess.get_inputs()}
text = "担当は山田太郎(電話 090-1234-5678、メール taro.yamada@example.com)です。"
enc, offsets, _ = get_enc(tok, text, 512)
feed = {k: np.array([v], dtype=np.int64) for k, v in enc.items()
if k in input_names}
if "token_type_ids" in input_names and "token_type_ids" not in feed:
feed["token_type_ids"] = np.zeros_like(feed["input_ids"])
label_ids = sess.run(None, feed)[0][0].argmax(-1).tolist()
spans, cur = [], None
for (a, b), tid in zip(offsets, label_ids):
if a == b:
continue
lab = id2label[tid]
if lab.startswith("B-"):
if cur:
spans.append(cur)
cur = {"start": a, "end": b, "label": lab[2:]}
elif lab.startswith("I-") and cur and cur["label"] == lab[2:]:
cur["end"] = b
else:
if cur:
spans.append(cur)
cur = None
if cur:
spans.append(cur)
for s in spans:
print(s["label"], text[s["start"]:s["end"]])
if __name__ == "__main__":
main()