tinyfix-turkish / tinyfix_tr.py
ekremcet's picture
Release TinyFix Turkish (17.8M char Seq2Seq, 19.5 MB int8 ONNX)
60c8076 verified
Raw History Blame Contribute Delete
9.22 kB
"""TinyFix Turkish — Pure character-level Seq2Seq Transformer autocorrect (ONNX Runtime).
Zero dictionary files, zero regex rules. Runs on CPU via dynamic int8 ONNX
(encoder_int8.onnx + decoder_step_int8.onnx, 19.5 MB total).
"""
from __future__ import annotations
import json
import os
import re
from pathlib import Path
from typing import Dict, List, Optional, Sequence, Tuple
import numpy as np
import onnxruntime as ort
SENT_SPLIT_RE = re.compile(r"(?<=[.!?…\n])(\s+)")
class CharByteVocab:
"""320-token UTF-8 byte-fallback + single-token Turkish character vocabulary."""
def __init__(self, cfg: Dict):
self.pad_id: int = int(cfg["pad_id"])
self.bos_id: int = int(cfg["bos_id"])
self.eos_id: int = int(cfg["eos_id"])
self.unk_id: int = int(cfg["unk_id"])
self.byte_offset: int = int(cfg["byte_offset"])
self.extra_offset: int = int(cfg["extra_offset"])
extra_chars: str = cfg["extra_chars"]
self.char_to_id: Dict[str, int] = {
ch: self.extra_offset + i for i, ch in enumerate(extra_chars)
}
self.id_to_char: Dict[int, str] = {
self.extra_offset + i: ch for i, ch in enumerate(extra_chars)
}
def encode(
self,
text: str,
add_bos: bool = False,
add_eos: bool = True,
max_len: int = 360,
) -> List[int]:
ids: List[int] = [self.bos_id] if add_bos else []
limit = max_len - (1 if add_eos else 0)
for ch in text:
cid = self.char_to_id.get(ch)
if cid is not None:
ids.append(cid)
else:
for b in ch.encode("utf-8"):
ids.append(self.byte_offset + b)
if len(ids) >= limit:
ids = ids[:limit]
break
if add_eos:
ids.append(self.eos_id)
return ids
def decode(self, ids: Sequence[int]) -> str:
out: List[str] = []
buf = bytearray()
for raw_i in ids:
i = int(raw_i)
if i == self.eos_id:
break
if i in (self.pad_id, self.bos_id, self.unk_id):
continue
if i >= self.extra_offset:
if buf:
out.append(buf.decode("utf-8", errors="ignore"))
buf.clear()
ch = self.id_to_char.get(i)
if ch is not None:
out.append(ch)
elif self.byte_offset <= i < self.byte_offset + 256:
buf.append(i - self.byte_offset)
if buf:
out.append(buf.decode("utf-8", errors="ignore"))
return "".join(out)
def split_chunks(text: str, max_chars: int = 240) -> List[Tuple[str, str]]:
"""Split arbitrary-length text on sentence boundaries, preserving exact whitespace."""
if len(text) <= max_chars:
return [(text, "")]
parts = SENT_SPLIT_RE.split(text)
segs: List[Tuple[str, str]] = []
for i in range(0, len(parts), 2):
seg = parts[i]
sep = parts[i + 1] if i + 1 < len(parts) else ""
segs.append((seg, sep))
chunks: List[Tuple[str, str]] = []
cur = ""
for seg, sep in segs:
piece = seg + sep
if cur and len(cur) + len(seg) > max_chars:
m = re.search(r"(\s+)$", cur)
if m:
chunks.append((cur[: m.start()], m.group(1)))
else:
chunks.append((cur, ""))
cur = piece
else:
cur += piece
if cur:
m = re.search(r"(\s+)$", cur)
if m:
chunks.append((cur[: m.start()], m.group(1)))
else:
chunks.append((cur, ""))
final: List[Tuple[str, str]] = []
for c, sep in chunks:
if len(c) <= max_chars:
final.append((c, sep))
else:
words = re.split(r"(\s+)", c)
buf = ""
for w in words:
if buf and len(buf) + len(w) > max_chars and not w.isspace():
m = re.search(r"(\s+)$", buf)
if m:
final.append((buf[: m.start()], m.group(1)))
else:
final.append((buf, ""))
buf = w
else:
buf += w
if buf:
final.append((buf, sep))
return final
class TinyFixTR:
"""Turkish autocorrect powered by TinyFix int8 ONNX."""
def __init__(
self,
model_dir: Optional[str | os.PathLike] = None,
mode: str = "full",
tau: Optional[float] = None,
providers: Optional[Sequence[str]] = None,
intra_op_num_threads: int = 4,
):
root = Path(model_dir) if model_dir is not None else Path(__file__).resolve().parent
cfg_path = root / "config.json"
if not cfg_path.exists():
raise FileNotFoundError(f"config.json not found in {root}")
with cfg_path.open("r", encoding="utf-8") as f:
self.config = json.load(f)
self.vocab = CharByteVocab(self.config["vocab"])
inf = self.config["inference"]
self.max_chunk_chars: int = int(inf.get("max_chunk_chars", 240))
self.max_src_tokens: int = int(inf.get("max_src_tokens", 360))
self.max_extra_tokens: int = int(inf.get("max_extra_tokens", 24))
modes = inf.get("modes", {"full": {"tau": 0.0}, "cautious": {"tau": 0.25}})
if tau is not None:
self.tau = float(tau)
elif mode in modes:
self.tau = float(modes[mode]["tau"])
else:
raise ValueError(f"Unknown mode {mode!r}; expected one of {list(modes)}")
enc_path = str(root / inf["encoder_file"])
dec_path = str(root / inf["decoder_file"])
sess_opts = ort.SessionOptions()
sess_opts.intra_op_num_threads = intra_op_num_threads
provs = list(providers) if providers is not None else ["CPUExecutionProvider"]
self.enc_sess = ort.InferenceSession(enc_path, sess_opts, providers=provs)
self.dec_sess = ort.InferenceSession(dec_path, sess_opts, providers=provs)
def _fix_chunk(self, text: str, tau: float) -> Tuple[str, float]:
if not text or not text.strip():
return text, 0.0
ids = self.vocab.encode(text, add_bos=False, add_eos=True, max_len=self.max_src_tokens)
src = np.array([ids], dtype=np.int64)
enc_out = self.enc_sess.run(None, {"src_ids": src})
edit_prob = float(enc_out[0][0])
# Clean-gate shortcut: skip autoregressive decoding when input is already clean
if edit_prob < tau:
return text, edit_prob
src_mask = enc_out[1]
ck0, cv0, ck1, cv1, ck2, cv2 = enc_out[2:]
nh, hd = ck0.shape[1], ck0.shape[3]
sk0 = sv0 = sk1 = sv1 = sk2 = sv2 = np.zeros((1, nh, 0, hd), dtype=np.float32)
cur = np.array([[self.vocab.bos_id]], dtype=np.int64)
out_ids: List[int] = []
max_steps = len(ids) + self.max_extra_tokens
for _ in range(max_steps):
res = self.dec_sess.run(
None,
{
"cur_id": cur,
"src_mask": src_mask,
"sk0": sk0,
"sv0": sv0,
"sk1": sk1,
"sv1": sv1,
"sk2": sk2,
"sv2": sv2,
"ck0": ck0,
"cv0": cv0,
"ck1": ck1,
"cv1": cv1,
"ck2": ck2,
"cv2": cv2,
},
)
logits = res[0]
sk0, sv0, sk1, sv1, sk2, sv2 = res[1:]
nxt = int(np.argmax(logits[0]))
if nxt == self.vocab.eos_id:
break
out_ids.append(nxt)
cur = np.array([[nxt]], dtype=np.int64)
return self.vocab.decode(out_ids), edit_prob
def fix_with_meta(self, text: str, tau: Optional[float] = None) -> Tuple[str, float]:
"""Return (corrected_text, max_chunk_edit_prob)."""
if not text:
return text, 0.0
t = self.tau if tau is None else float(tau)
chunks = split_chunks(text, max_chars=self.max_chunk_chars)
pieces: List[str] = []
max_p = 0.0
for chunk, sep in chunks:
fixed, p = self._fix_chunk(chunk, t)
max_p = max(max_p, p)
pieces.append(fixed + sep)
return "".join(pieces), max_p
def __call__(self, text: str, tau: Optional[float] = None) -> str:
fixed, _ = self.fix_with_meta(text, tau=tau)
return fixed
if __name__ == "__main__":
import sys
fixer = TinyFixTR()
samples = sys.argv[1:] or [
"ben burada düzeltilen birş ey görmedim",
"merhba nslsn, siprşm hala glmdi krgo nrde?",
"Onlar yada biz ve ya bir çok kişi bu bölge de kaldı.",
"urun cok guzel bide kargo cok hizli geldi tesekkurler",
"Kitap bende, yarın getiririm.",
]
for s in samples:
out, p = fixer.fix_with_meta(s)
print(f"[p={p:.2f}] {s} --> {out}")