LegacyTools's picture
v0.2.0
524ee48 verified
Raw History Blame Contribute Delete
7.39 kB
#!/usr/bin/env python3
"""safe-privacy-detect-ja-70m の実行スクリプト(参考実装)。
日本語の本文を 1 つ受け取り、6 つの対象それぞれについて、その内容が「人について文面に明記されているか」を返す。
文章は生成しない。本文を出力やログに書かない。
返す状態:
DETECTED / NOT_DETECTED / ABSTAIN モデルの判定(確率が最大のラベル)
OUT_OF_SCOPE 規則による判定(未対応の対象、空に近い本文、日本語でない本文、長すぎる本文)
FAILED 実行時エラー、時間切れ
使い方:
echo "本文" | python predict.py # 6 対象すべて
echo "本文" | python predict.py --targets name health
python predict.py --text-file input.txt --pretty
Python から:
from predict import Detector
detector = Detector(".")
result = detector.predict("本文")
"""
from __future__ import annotations
import argparse
import json
import sys
import time
import unicodedata
from pathlib import Path
import numpy as np
TARGETS = ("name", "health", "crime", "honseki", "union", "belief")
LABELS = ("DETECTED", "NOT_DETECTED", "ABSTAIN")
MAX_CHARS = 800
MAX_TOKENS = 512
MIN_JAPANESE_RATIO = 0.30
DEFAULT_TIMEOUT_MS = 1000.0
JAPANESE_EXTRA = "ー々〆ヶ"
def is_japanese(ch: str) -> bool:
"""ひらがな・カタカナ・漢字(NFKC 正規化後の文字で判定する)。"""
code = ord(ch)
return (
0x3040 <= code <= 0x30FF # ひらがな、カタカナ
or 0x4E00 <= code <= 0x9FFF # 漢字
or 0x3400 <= code <= 0x4DBF # 漢字(拡張 A)
or 0xF900 <= code <= 0xFAFF # 互換漢字
or ch in JAPANESE_EXTRA
)
def out_of_scope_reason(text: str) -> str | None:
"""本文が対象外なら理由を返す。対象内なら None。判定仕様 §5 の規則 2〜4。
文字: Unicode の区分が L(文字)か M(結合記号)のもの。
数字: 区分 N。割合の計算から除く。
記号・空白: それ以外(P、S、Z、C)。
"""
normalized = unicodedata.normalize("NFKC", text).strip()
letters = [ch for ch in normalized if unicodedata.category(ch)[0] in ("L", "M")]
digits = [ch for ch in normalized if unicodedata.category(ch)[0] == "N"]
if not letters and not digits:
return "empty"
if not letters:
return "not_japanese"
if sum(is_japanese(ch) for ch in letters) / len(letters) < MIN_JAPANESE_RATIO:
return "not_japanese"
if len(normalized) > MAX_CHARS:
return "too_long"
return None
class Detector:
"""ONNX Runtime(CPU)でモデルを動かす。1 つ作って使い回す。"""
def __init__(self, model_dir: str | Path = ".", threads: int = 4) -> None:
import onnxruntime as ort
from transformers import AutoTokenizer
model_dir = Path(model_dir)
config = json.loads((model_dir / "config.json").read_text(encoding="utf-8"))
info = config["sensitive_info"]
if tuple(info["targets"]) != TARGETS or tuple(info["labels"]) != LABELS:
raise ValueError("config.json の対象・ラベルの並びが、このスクリプトの想定と違います。")
self.temperature = np.array([info["temperature"][t] for t in TARGETS], dtype=np.float64)[:, None]
self.tokenizer = AutoTokenizer.from_pretrained(model_dir)
options = ort.SessionOptions()
options.intra_op_num_threads = threads
options.inter_op_num_threads = 1
self.session = ort.InferenceSession(
str(model_dir / "onnx" / "model.onnx"), options, providers=["CPUExecutionProvider"]
)
def probabilities(self, text: str) -> np.ndarray:
"""校正後の確率。形は [6 対象, 3 ラベル]。"""
enc = self.tokenizer(text, truncation=True, max_length=MAX_TOKENS, return_tensors="np")
feed = {"input_ids": enc["input_ids"].astype(np.int64), "attention_mask": enc["attention_mask"].astype(np.int64)}
logits = self.session.run(None, feed)[0].astype(np.float64).reshape(len(TARGETS), len(LABELS))
scaled = logits / self.temperature
scaled = scaled - scaled.max(axis=1, keepdims=True)
exp = np.exp(scaled)
return exp / exp.sum(axis=1, keepdims=True)
def predict(self, text: str, targets: tuple[str, ...] | list[str] = TARGETS,
timeout_ms: float = DEFAULT_TIMEOUT_MS) -> dict:
"""対象ごとの結果を返す。本文は結果に含めない。"""
results = {t: {"status": "OUT_OF_SCOPE", "reason": "unsupported_target"} for t in targets if t not in TARGETS}
supported = [t for t in targets if t in TARGETS]
if not supported:
return results
if not isinstance(text, str):
return {**results, **{t: {"status": "FAILED", "reason": "text_is_not_string"} for t in supported}}
reason = out_of_scope_reason(text)
if reason is not None:
return {**results, **{t: {"status": "OUT_OF_SCOPE", "reason": reason} for t in supported}}
started = time.perf_counter()
try:
probs = self.probabilities(text)
except Exception as exc: # 実行時エラーは FAILED として返す。本文は含めない
return {**results, **{t: {"status": "FAILED", "reason": type(exc).__name__} for t in supported}}
elapsed_ms = (time.perf_counter() - started) * 1000
if elapsed_ms > timeout_ms:
return {**results, **{t: {"status": "FAILED", "reason": "timeout"} for t in supported}}
for target in supported:
row = probs[TARGETS.index(target)]
results[target] = {
"status": LABELS[int(row.argmax())],
"probabilities": {label: round(float(p), 4) for label, p in zip(LABELS, row)},
}
return results
def main() -> None:
ap = argparse.ArgumentParser(description="個人情報・機微情報が明記されているかを判定する")
ap.add_argument("--model-dir", type=Path, default=Path(__file__).resolve().parent)
ap.add_argument("--targets", nargs="+", default=list(TARGETS))
ap.add_argument("--text-file", type=Path, help="本文のファイル(省略すると標準入力)")
ap.add_argument("--threads", type=int, default=4)
ap.add_argument("--timeout-ms", type=float, default=DEFAULT_TIMEOUT_MS)
ap.add_argument("--pretty", action="store_true")
args = ap.parse_args()
try:
text = args.text_file.read_text(encoding="utf-8") if args.text_file else sys.stdin.read()
except (OSError, UnicodeDecodeError) as exc:
raise SystemExit(f"本文を読めません: {type(exc).__name__}") from exc
text = text.rstrip("\n")
try:
detector = Detector(args.model_dir, args.threads)
except Exception as exc:
failed = {t: {"status": "FAILED", "reason": f"load_error:{type(exc).__name__}"} for t in args.targets}
sys.stdout.write(json.dumps(failed, ensure_ascii=False) + "\n")
raise SystemExit(1) from exc
result = detector.predict(text, args.targets, args.timeout_ms)
sys.stdout.write(json.dumps(result, ensure_ascii=False, indent=2 if args.pretty else None) + "\n")
if __name__ == "__main__":
main()