File size: 9,217 Bytes
60c8076 2b9504b 09bb2c2 2b9504b 09bb2c2 2b9504b 09bb2c2 aec3d97 09bb2c2 60c8076 09bb2c2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 | """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}")
|