ja-error-detect-v1: model card, configs and reference implementation
Browse filesFiles changed (6)
- README.mdAdded+82
- config.jsonAdded+43
- examples/infer_error_detect.pyAdded+442
- inference_config.jsonAdded+13
- tokenizer_config.jsonAdded+65
- vocab.txtAdded
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182---license: apache-2.0language:- japipeline_tag: token-classificationbase_model: tohoku-nlp/bert-base-japanese-v3tags:- japanese- error-detection- proofreading- onnx---
# ja-error-detect-v1
日本語の文から、誤りのある箇所(スパン)を検出する小モデルです。修正案は出しません。「どこが怪しいか」を指すところまでが役割で、校正ツールの下検査や、入力支援の警告に組み込む想定の部品です。
検出する誤りは 6 種です。助詞の置換、同音異義語の誤変換、送り仮名の誤り、形の似た漢字への置換、脱字、衍字(余分な文字)。方言、文体差、口語表現は誤りとして扱いません。
## 使い方
閾値(span_mean_err >= 0.80、inference_config.json に同梱)を適用した参照実装が examples/infer_error_detect.py にあります。基本的な使い方は次のとおりです。
```pythonfrom transformers import AutoModelForTokenClassification, AutoTokenizerimport torch
repo = "japan-opendata/ja-error-detect-v1"tok = AutoTokenizer.from_pretrained(repo)model = AutoModelForTokenClassification.from_pretrained(repo)model.eval()
text = "来週の会議は月曜日に行なわれます。"enc = tok(text, return_offsets_mapping=True, return_tensors="pt")offsets = enc.pop("offset_mapping")[0].tolist()with torch.no_grad(): probs = model(**enc).logits.softmax(-1)[0]err_prob = 1.0 - probs[:, 0] # ラベル 0 は正常(O)spans = []cur = Nonefor (s, e), p in zip(offsets, err_prob.tolist()): if s == e: continue if p > 0.5: if cur is None: cur = [s, e, [p]] else: cur[1] = e cur[2].append(p) elif cur is not None: spans.append(cur) cur = Noneif cur is not None: spans.append(cur)kept = [(s, e) for s, e, ps in spans if sum(ps) / len(ps) >= 0.80]print([(text[s:e], s, e) for s, e in kept])```
ONNX 版(onnx/model.onnx、FP32)も同梱しています。PyTorch との予測一致は dev・封印テスト各 200 件で全件一致、CPU 推論は平均的な文で約 20 ms/文(Core i7-11700F)です。
## 実測(封印テスト 5,000 件、閾値は dev で事前に固定)
- 誤りスパン完全一致:Precision 0.9094、Recall 0.8291、F1 0.8674- 種別ごとの F1:送り仮名 0.9573、形の似た漢字 0.9285、助詞 0.8880、脱字 0.8596、同音異義語 0.8436、衍字 0.7686- 正常文への誤検出:検出された 65 スパンを全件人手で確認したところ、29 件は土台の原文に実在した誤り(正常文とされていた側の誤り)で、本当の誤検出は 36 件でした。率にすると、本当の誤検出は 1,000 文字あたり 0.2538 件、文単位で 1.20% です(補正前の機械集計は 0.4582 件、2.13%)
## 測定条件と留保
- 学習データは合成です。FineWeb-2 日本語(ODC-By 1.0)の文に、6 種の誤りをプログラムで注入して作りました。実在の誤りコーパスでは数字は下がる前提で見てください- 弱点は衍字(余分な文字)の検出で、F1 0.7686 と 6 種の中で最も低いです。同音異義語も文脈依存が強く、言い換え可能な箇所では判断が割れます- 本当の誤検出の内訳で多かったのは、正常な助詞の文脈誤判定、外来語・カタカナ語、固有名詞でした。固有名詞の多い文では過検出が増えます- このモデルは「誤りの候補を挙げる」ためのもので、検出箇所が必ず誤りとは限りません。最終判断は人か、後段の校正ロジックで行ってください
## データとライセンス
- 学習データ:FineWeb-2 日本語(ODC-By 1.0)への誤り注入による合成データ。実在の個人情報は含みません- ベースモデル:tohoku-nlp/bert-base-japanese-v3- 本モデルのライセンスは Apache 2.0 です
## リンク
- 開発元: Japan Open Data Lab(https://jpopendata.jp/)12345678910111213141516171819202122232425262728293031323334353637383940414243{
"add_cross_attention": false,
"architectures": [
"BertForTokenClassification"
],
"attention_probs_dropout_prob": 0.1,
"bos_token_id": null,
"classifier_dropout": null,
"dtype": "float32",
"eos_token_id": null,
"hidden_act": "gelu",
"hidden_dropout_prob": 0.1,
"hidden_size": 768,
"id2label": {
"0": "O",
"1": "B-ERR",
"2": "I-ERR"
},
"initializer_range": 0.02,
"intermediate_size": 3072,
"is_decoder": false,
"label2id": {
"B-ERR": 1,
"I-ERR": 2,
"O": 0
},
"layer_norm_eps": 1e-12,
"max_position_embeddings": 512,
"model_type": "bert",
"num_attention_heads": 12,
"num_hidden_layers": 12,
"pad_token_id": 0,
"tie_word_embeddings": true,
"transformers_version": "5.23.0",
"type_vocab_size": 2,
"use_cache": false,
"vocab_size": 32768,
"error_detect_inference": {
"decoding_method": "span_mean_err",
"threshold": 0.8,
"max_length": 256
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442#!/usr/bin/env python"""日本語テキスト誤り検出モデル(ja-error-detect-v1)の参照推論実装。
Hugging Face 形式(PyTorch safetensors / FP32 ONNX)の双方に対応し、文字オフセット整列(BertJapaneseTokenizer での NFKC 逆写像および [UNK] 保護を含む)と確信度閾値(既定: span_mean_err >= 0.80)を適用して誤り文字スパンを検出する。
使い方(Python API): from infer_error_detect import JaErrorDetector detector = JaErrorDetector("path/to/model", backend="onnx") spans = detector.detect("大きな間題が発生した。")
使い方(CLI): python infer_error_detect.py --model-dir path/to/model --backend onnx --text "大きな間題が発生した。""""from __future__ import annotations
import argparseimport jsonimport reimport unicodedatafrom pathlib import Pathfrom typing import Dict, List, Optional, Sequence, Tuple
import numpy as npfrom transformers import AutoConfig, AutoTokenizer
LABELS = ("O", "B-ERR", "I-ERR")ID2LABEL = {0: "O", 1: "B-ERR", 2: "I-ERR"}
def _clusters(text: str) -> List[str]: """書記素クラスタの近似分割(基底文字+結合文字・半角濁点)。""" clusters: List[str] = [] cur = "" for ch in text: if cur and ( unicodedata.combining(ch) or unicodedata.category(ch) in ("Mn", "Me", "Mc") or ch in ("\uff9e", "\uff9f") ): cur += ch else: if cur: clusters.append(cur) cur = ch if cur: clusters.append(cur) return clusters
def _nfkc_with_map(text: str) -> Tuple[str, List[int], List[int]]: """書記素クラスタ単位で NFKC 正規化を行い、元テキスト位置への逆対応表を返す。""" norm_parts: List[str] = [] start_map: List[int] = [] end_map: List[int] = [] pos = 0 for cl in _clusters(text): n = unicodedata.normalize("NFKC", cl) if not n: pos += len(cl) continue for _ in n: start_map.append(pos) end_map.append(pos + len(cl)) norm_parts.append(n) pos += len(cl) return "".join(norm_parts), start_map, end_map
def _encode_slow_bert_japanese( tok, text: str, max_len: int) -> Tuple[dict, List[Tuple[int, int]]]: """BertJapaneseTokenizer (is_fast=False) 向けのオフセット付きエンコード。""" norm, start_map, end_map = _nfkc_with_map(text) specials = sorted(tok.all_special_tokens, key=len, reverse=True) sp_re = ( re.compile("(" + "|".join(re.escape(s) for s in specials) + ")") if specials else None ) segments = sp_re.split(norm) if sp_re else [norm] sp_set = set(specials) unk = tok.unk_token
tokens: List[str] = [] offsets: List[Tuple[int, int]] = [] pos = 0
for seg in segments: if not seg: continue if seg in sp_set: idx = norm.find(seg, pos) if idx >= 0: pos = idx + len(seg) tokens.append(seg) offsets.append((0, 0)) continue
words = tok.word_tokenizer.tokenize(seg, never_split=tok.all_special_tokens) for word in words: idx = norm.find(word, pos) if idx < 0: for sw in tok.subword_tokenizer.tokenize(word): tokens.append(sw) offsets.append((0, 0)) continue
word_start_orig = start_map[idx] word_end_orig = end_map[idx + len(word) - 1] subwords = tok.subword_tokenizer.tokenize(word)
if subwords == [unk]: tokens.append(unk) offsets.append((word_start_orig, word_end_orig)) else: wpos = 0 for sw in subwords: surf = sw[2:] if sw.startswith("##") else sw sub_pos = word.find(surf, wpos) if sub_pos < 0: tokens.append(sw) offsets.append((word_start_orig, word_end_orig)) else: s_ni = idx + sub_pos e_ni = s_ni + len(surf) - 1 tokens.append(sw) offsets.append((start_map[s_ni], end_map[e_ni])) wpos = sub_pos + len(surf)
pos = idx + len(word)
max_body = max(0, max_len - tok.num_special_tokens_to_add(pair=False)) tokens = tokens[:max_body] offsets = offsets[:max_body]
ids = tok.build_inputs_with_special_tokens(tok.convert_tokens_to_ids(tokens)) n_special = len(ids) - len(tokens) if n_special == 2: offsets = [(0, 0)] + offsets + [(0, 0)] elif n_special == 1: offsets = offsets + [(0, 0)] elif n_special > 2: offsets = [(0, 0)] + offsets + [(0, 0)] * (n_special - 1)
enc = {"input_ids": ids, "attention_mask": [1] * len(ids)} if "token_type_ids" in tok.model_input_names: enc["token_type_ids"] = [0] * len(ids) return enc, offsets
def encode_with_offsets( tok, text: str, max_len: int) -> Tuple[dict, List[Tuple[int, int]]]: """Fast / Slow 両トークナイザで (encoding, offset_mapping) を返す。""" if getattr(tok, "is_fast", False): enc = tok( text, return_offsets_mapping=True, truncation=True, max_length=max_len, ) raw_offsets = enc.pop("offset_mapping") return dict(enc), [(int(a), int(b)) for a, b in raw_offsets] return _encode_slow_bert_japanese(tok, text, max_len)
def _softmax(logits: np.ndarray) -> np.ndarray: """数値安定版 softmax(最終軸)。""" x = logits - logits.max(axis=-1, keepdims=True) e = np.exp(x) return e / e.sum(axis=-1, keepdims=True)
def _decode_raw_bio_with_scores( text: str, offsets: List[Tuple[int, int]], pred_ids: Sequence[int], err_probs: Sequence[float],) -> List[Tuple[int, int, float]]: """BIO トークン予測から文字スパンとスパン内トークン平均誤り確率を算出する。""" raw_spans: List[List[object]] = [] cur: List[object] | None = None
for (a, b), tid, err_p in zip(offsets, pred_ids, err_probs): if a >= b: continue if tid == 1: # B-ERR if cur is not None and a == cur[0] and b == cur[1]: cur[1] = max(int(cur[1]), b) cur[2].append(float(err_p)) # type: ignore[union-attr] else: if cur is not None: raw_spans.append(cur) cur = [a, b, [float(err_p)]] elif tid == 2: # I-ERR if cur is not None: cur[1] = max(int(cur[1]), b) cur[2].append(float(err_p)) # type: ignore[union-attr] else: cur = [a, b, [float(err_p)]] else: if cur is not None: raw_spans.append(cur) cur = None
if cur is not None: raw_spans.append(cur)
merged: List[List[object]] = [] for s_obj, e_obj, sc_list in raw_spans: s, e = int(s_obj), int(e_obj) # type: ignore[arg-type] if merged and s < int(merged[-1][1]): # type: ignore[arg-type] merged[-1][1] = max(int(merged[-1][1]), e) # type: ignore[arg-type] merged[-1][2].extend(sc_list) # type: ignore[union-attr] else: merged.append([s, e, list(sc_list)]) # type: ignore[arg-type]
n_text = len(text) out: List[Tuple[int, int, float]] = [] for s_obj, e_obj, sc_list in merged: s = max(0, min(int(s_obj), n_text)) # type: ignore[arg-type] e = max(0, min(int(e_obj), n_text)) # type: ignore[arg-type] while s < e and text[s].isspace(): s += 1 while e > s and text[e - 1].isspace(): e -= 1 if s < e: mean_sc = float(sum(sc_list) / len(sc_list)) # type: ignore[arg-type] out.append((s, e, mean_sc)) return out
def decode_probs_to_spans( text: str, offsets: List[Tuple[int, int]], probs: np.ndarray, decoding_method: str = "span_mean_err", threshold: float = 0.80,) -> Tuple[List[dict], List[int]]: """トークン確率行列 [seq_len, 3] に閾値を適用し、誤りスパンと文字 BIO 配列を返す。""" err_probs = [float(1.0 - probs[ti, 0]) for ti in range(len(offsets))]
if decoding_method == "span_mean_err": pred_ids = probs.argmax(axis=-1).tolist() candidates = _decode_raw_bio_with_scores(text, offsets, pred_ids, err_probs) kept = [(s, e, sc) for s, e, sc in candidates if sc >= threshold] elif decoding_method == "token_err": pred_ids = [ (1 if probs[ti, 1] >= probs[ti, 2] else 2) if err_probs[ti] >= threshold else 0 for ti in range(len(offsets)) ] kept = _decode_raw_bio_with_scores(text, offsets, pred_ids, err_probs) else: raise ValueError(f"未対応の decoding_method です: {decoding_method}")
char_labels = [0] * len(text) spans_out: List[dict] = [] for s, e, sc in kept: char_labels[s] = 1 for k in range(s + 1, e): char_labels[k] = 2 spans_out.append( { "start": int(s), "end": int(e), "text": text[s:e], "score": round(float(sc), 6), } ) return spans_out, char_labels
class JaErrorDetector: """日本語テキスト誤り検出モデル(ONNX Runtime / PyTorch 両対応)。"""
def __init__( self, model_dir: str | Path, backend: str = "onnx", threshold: Optional[float] = None, max_length: Optional[int] = None, providers: Optional[Sequence[str]] = None, local_files_only: bool = False, ) -> None: self.model_dir = str(model_dir) self.backend = backend.lower() if self.backend not in ("onnx", "pytorch"): raise ValueError(f"backend は 'onnx' または 'pytorch' を指定してください: {backend}")
inf_cfg = self._load_inference_config(model_dir, local_files_only=local_files_only) self.decoding_method = str(inf_cfg.get("decoding_method", "span_mean_err")) self.threshold = float( inf_cfg.get("threshold", 0.80) if threshold is None else threshold ) self.max_length = int( inf_cfg.get("max_length", 256) if max_length is None else max_length ) onnx_rel_path = str(inf_cfg.get("onnx_path", "onnx/model.onnx"))
self.tokenizer = AutoTokenizer.from_pretrained( self.model_dir, local_files_only=local_files_only )
if self.backend == "onnx": import onnxruntime as ort
model_path = Path(self.model_dir) / onnx_rel_path if not model_path.exists(): raise FileNotFoundError(f"ONNX モデルが見つかりません: {model_path}") self.session = ort.InferenceSession( str(model_path), providers=list(providers) if providers else ["CPUExecutionProvider"], ) self._ort_inputs = [i.name for i in self.session.get_inputs()] self.pt_model = None else: import torch from transformers import AutoModelForTokenClassification
self._torch = torch self.pt_model = AutoModelForTokenClassification.from_pretrained( self.model_dir, local_files_only=local_files_only, dtype=torch.float32, ).eval() self.session = None self._ort_inputs = []
@staticmethod def _load_inference_config( model_dir: str | Path, local_files_only: bool = False ) -> Dict[str, object]: base = Path(model_dir) inf_file = base / "inference_config.json" if inf_file.exists(): return json.loads(inf_file.read_text(encoding="utf-8")) cfg_file = base / "config.json" if cfg_file.exists(): cfg = json.loads(cfg_file.read_text(encoding="utf-8")) if isinstance(cfg.get("error_detect_inference"), dict): return dict(cfg["error_detect_inference"]) try: cfg = AutoConfig.from_pretrained( str(model_dir), local_files_only=local_files_only ) extra = getattr(cfg, "error_detect_inference", None) if isinstance(extra, dict): return dict(extra) except Exception: pass return { "decoding_method": "span_mean_err", "threshold": 0.80, "max_length": 256, "onnx_path": "onnx/model.onnx", }
def _predict_probs(self, enc: dict) -> np.ndarray: if self.backend == "onnx": ids = np.asarray([enc["input_ids"]], dtype=np.int64) feed: Dict[str, np.ndarray] = {} for name in self._ort_inputs: if name in enc: feed[name] = np.asarray([enc[name]], dtype=np.int64) elif name == "token_type_ids": feed[name] = np.zeros_like(ids, dtype=np.int64) else: raise KeyError(f"未対応の ONNX 入力名です: {name}") logits = self.session.run(None, feed)[0][0].astype(np.float32) # type: ignore[union-attr] return _softmax(logits)
torch = self._torch kw = { "input_ids": torch.tensor([enc["input_ids"]], dtype=torch.long), "attention_mask": torch.tensor([enc["attention_mask"]], dtype=torch.long), } if "token_type_ids" in enc: kw["token_type_ids"] = torch.tensor( [enc["token_type_ids"]], dtype=torch.long ) with torch.no_grad(): logits = self.pt_model(**kw).logits[0].float().numpy() # type: ignore[misc] return _softmax(logits)
def detect_with_details(self, text: str) -> dict: """誤りスパン一覧に加え、文字単位 BIO ラベル列や閾値情報も返す。""" if not text: return { "text": text, "spans": [], "char_labels": [], "decoding_method": self.decoding_method, "threshold": self.threshold, } enc, offsets = encode_with_offsets(self.tokenizer, text, max_len=self.max_length) probs = self._predict_probs(enc) spans, char_ids = decode_probs_to_spans( text, offsets, probs, decoding_method=self.decoding_method, threshold=self.threshold, ) return { "text": text, "spans": spans, "char_labels": [ID2LABEL[i] for i in char_ids], "decoding_method": self.decoding_method, "threshold": self.threshold, }
def detect(self, text: str) -> List[dict]: """設定閾値を適用した誤り文字スパン一覧のみを返す。""" return self.detect_with_details(text)["spans"]
def main() -> int: ap = argparse.ArgumentParser( description="ja-error-detect-v1 誤りスパン検出 CLI" ) ap.add_argument("--model-dir", required=True, help="Hugging Face 形式ディレクトリ") ap.add_argument("--backend", default="onnx", choices=["onnx", "pytorch"]) ap.add_argument("--threshold", type=float, default=None) ap.add_argument("--local-files-only", action="store_true") ap.add_argument("--text", required=True, help="検査対象の日本語文") args = ap.parse_args()
detector = JaErrorDetector( args.model_dir, backend=args.backend, threshold=args.threshold, local_files_only=args.local_files_only, ) out = detector.detect_with_details(args.text) print(json.dumps(out, ensure_ascii=False, indent=2)) return 0
if __name__ == "__main__": raise SystemExit(main())12345678910111213{
"task": "token-classification",
"labels": [
"O",
"B-ERR",
"I-ERR"
],
"decoding_method": "span_mean_err",
"threshold": 0.8,
"max_length": 256,
"onnx_path": "onnx/model.onnx",
"threshold_source": "dev_tuned_fixed"
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465{
"added_tokens_decoder": {
"0": {
"content": "[PAD]",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"1": {
"content": "[UNK]",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"2": {
"content": "[CLS]",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"3": {
"content": "[SEP]",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"4": {
"content": "[MASK]",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
}
},
"backend": "custom",
"cls_token": "[CLS]",
"do_lower_case": false,
"do_subword_tokenize": true,
"do_word_tokenize": true,
"is_local": false,
"jumanpp_kwargs": null,
"local_files_only": false,
"mask_token": "[MASK]",
"mecab_kwargs": {
"mecab_dic": "unidic_lite"
},
"model_max_length": 512,
"never_split": null,
"pad_token": "[PAD]",
"sep_token": "[SEP]",
"subword_tokenizer_type": "wordpiece",
"sudachi_kwargs": null,
"tokenizer_class": "BertJapaneseTokenizer",
"unk_token": "[UNK]",
"word_tokenizer_type": "mecab"
}README.mdAdded+82
config.jsonAdded+43
examples/infer_error_detect.pyAdded+442
inference_config.jsonAdded+13
tokenizer_config.jsonAdded+65
vocab.txtAdded