Round 4: rules for spoken forms and joined words, more training text, better wrong-word fixes
Browse filesFiles changed (5)
- README.md+26-18
- config.json
- model.onnx+2-2
- pairs.tsvAdded
- tinyfix_tr.py+150-4
8 unmodified lines910111212131414151617187 unmodified lines26272828293031321 unmodified line343536363738394041373839404142434445444546464748495051525354555051525657585960616263645965666761686970717273746775768 unmodified lines# TinyFix Turkish
A small Turkish autocorrect for typed text. It restores Turkish letters (cok → çok), fixes joined or split words (herşey → her şey,hiç bir → hiçbir, bende → ben de), everyday misspellings and, in full mode, typing slips. It runs on a CPU in about 1.5 ms per short text.hiç bir → hiçbir, bende → ben de), spoken spellings (yapıyom → yapıyorum), repeated letters, everyday misspellings and, best in full mode, typing slipsand some wrong real words. It runs on a CPU in about 2 ms per short text once its caches are warm (about 5 ms on the first pass).
4.84M parameters, 8-bit ONNX file of 5 MB; the word lists next to it take 21 MB. The recipe follows4.84M parameters, 8-bit ONNX file of 5 MB; the word lists next to it take 22 MB. The recipe follows[paperweight/tinyfix](https://huggingface.co/paperweight/tinyfix) (MIT): hashed character pieces, a left and a right GRU, and a scorer thatpicks between the typed word and up to 8 candidates. This implementation and its training are separate from that project.
7 unmodified lines# 'Yalnız kaldım, her şey çok güzel olacak.'```
Cautious mode never changes the letters of a word it does not know. Full mode does, and fixes many more slips.Cautious mode changes the letters of an unknown word only when it is very sure. Full mode changes more, and fixes many more slips.
## Results
1 unmodified line
| Kind of mistake | Cautious: fixed / precision | Full: fixed / precision ||---|---|---|| Real mistakes in movie reviews | 47% / 94% | 51% / 92% || Call-center style messages (invented) | 50% / 98% | 61% / 98% || No Turkish letters | 88% / 100% | 88% / 99.6% || Joined or split words | 82% / 100% | 82% / 98% || Everyday misspellings* | 56% / 100% | 59% / 100% || Typing slips | 4% / 83% | 49% / 94% || Real mistakes in movie reviews | 52% / 93% | 59% / 92% || Call-center style messages (invented) | 62% / 98% | 75% / 99% || No Turkish letters | 91% / 99.8% | 91% / 99.5% || Joined or split words | 85% / 100% | 85% / 98% || Everyday misspellings* | 59% / 100% | 62% / 100% || Typing slips | 24% / 98% | 70% / 96% || Wrong real words, one word, not letter cases | 17 of 88 | 33 of 88 || Correct words broken | 3.5 per 10,000 | 5.9 per 10,000 |
*This track overlaps the model's own word list: 19 of the 21 items that use listed words are fixed, and 3 (cautious) or 4 (full) of the other 18.The benchmark was made by the people who trained this model; most tracks are generated or invented. On separate web pages that nobody corrected,the cautious mode made 28 changes per 10,000 words and, of 60 changes read, 12 were wrong and 3 were unclear (measured before the last fix for suffixes after quote marks).Mean F0.5 over the error tracks: 85.1 cautious, 91.1 full (the first release of this model had 75.9 and 87.7). On a second set, 1,500 rows of[turkish_typo_validation](https://huggingface.co/datasets/burakaytan/turkish_typo_validation) with generated noise from another generator, it fixes 29% / 46% of theerrors with 95% / 90% precision (cautious / full).
*This track overlaps the model's own word lists: 20 of the 21 items that use listed words are fixed, and 3 (cautious) or 4 (full) of the other 18.The benchmark was made by the people who trained this model; most tracks are generated or invented. Settings were chosen on other data (see below), but the model was developed after its first scores on this test split were seen, so treat the numbers asindicative. Most of the gain since the first release comes from rules and data made after that.
## Limits
- It fixes about half of the real mistakes in the review texts. It is not a grammar corrector and does not rewrite sentences.- Misspellings outside its word list are mostly left alone.- de/da, ki, mi choices are decided from 12 words before and 4 after.- It fixes about half (cautious) to three fifths (full) of the real mistakes in the review texts. It is not a grammar corrector and does not rewrite sentences.- Misspellings that are far from the right word, and most wrong real words, are left alone.- de/da, ki, mi and wrong-real-word choices are decided from 12 words before and 4 after.- It does not improve speech-recognition transcripts: in our tests the word error rate stayed the same or rose slightly.- Names and foreign words can look like slips. The word lists hold words from the web, including offensive ones and people's names.- The hats (â, î, û) are never added or removed. Suffixes right after a quote mark are left alone.
## Training data
- Text: FineWeb-2 (Turkish), ODC-By 1.0, about 120M words after filtering, with official and news pages counted twice. FineWeb-2 is built from Common Crawl.- Text: FineWeb-2 (Turkish), ODC-By 1.0, about 285M words after filtering, with official and news pages counted twice (the last step used 165M of them). FineWeb-2 is built from Common Crawl.- A spoken-form, join and short-form list: partly written by hand, partly from [zemberek-nlp](https://github.com/ahmetaa/zemberek-nlp) (Apache-2.0).- Dictionary: [tdd-ai/hunspell-tr](https://github.com/tdd-ai/hunspell-tr) (MPL-2.0), expanded to 5.75M forms. `valid_words.bin` is made from it.- Thresholds: set on Common Voice sentences (CC0) and GECTurk training sentences (Apache-2.0), partly by hand.- Thresholds: set on GECTurk training sentences (Apache-2.0) and checked by hand; some rules were chosen while looking at the [#Turki$hTweets](https://github.com/atubakoksal/annotated_tweets) set, which was not used for training.- A small list of wrong real words from [Turkish-Spelling-Dictionary](https://huggingface.co/datasets/asimokby/Turkish-Spelling-Dictionary) (MIT).- No customer, personal or call data was used.
## Files and licences
- `tinyfix_tr.py`, `model.onnx`, `tools/`: MIT (`LICENSE`).- `lexicon.tsv`, `rare.tsv`, `config.json`: word lists and counts from FineWeb-2 text, ODC-By 1.0.- `lexicon.tsv`, `rare.tsv`, `pairs.tsv`, `config.json`: word lists and counts from FineWeb-2 text, ODC-By 1.0.- `valid_words.bin`: MPL-2.0 (`LICENSE-MPL-2.0.txt`), derived from hunspell-tr; the program that builds it is in `tools/`.12323version https://git-lfs.github.com/spec/v1oid sha256:fca5af693d0ce8721229cb18e66f96fe3a12843b1fa80add9314b308aa8541e7size 4949942oid sha256:457b02e80618d8f5fda4310fb71652b9cb4682afbb833720d00f1806f7f6bc39size 4949943177 unmodified lines1781791801811811821831841 unmodified line18618718818918919019119212 unmodified lines20520620720820921021121221321422 unmodified lines2372382392362402412422435 unmodified lines24925025124825225325425540 unmodified lines296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443177 unmodified lines return all((self.bits[p >> 3] >> (p & 7)) & 1 for p in ((a + i * b) % self.m for i in range(self.k)))
class TinyFixTR:class _Core: """mode "cautious" never changes letters of unknown words; "full" does, and fixes many more slips.""" def __init__(self, folder=None, mode="cautious", threads=1): import onnxruntime as ort1 unmodified line cfg = json.load(open(j("config.json"), encoding="utf-8")); lex = [l.rstrip("\n").split("\t") for l in open(j("lexicon.tsv"), encoding="utf-8")] rare = {a: int(b) for a, b in (l.rstrip("\n").split("\t") for l in open(j("rare.tsv"), encoding="utf-8"))} self.lex = Lexicon({a: int(b) for a, b in lex}, rare); self.top = math.log1p(int(lex[0][1])); self.accept = WordSet(j("valid_words.bin")) self.sp, self.keep, self.foreign, self.stems = (set(cfg[k]) for k in ("special", "keep", "foreign", "stems")); self.th = cfg["thresholds"][mode] self.folder = folder; self.fixed, self.real = cfg["fixed"], cfg["real"]; self.sp, self.keep, self.foreign, self.stems = (set(cfg[k]) for k in ("special", "keep", "foreign", "stems")); self.th = cfg["thresholds"][mode] so = ort.SessionOptions(); so.intra_op_num_threads = threads; so.log_severity_level = 3 self.net = ort.InferenceSession(j("model.onnx"), so, providers=["CPUExecutionProvider"]); self.cc, self.pc = {}, {}
12 unmodified lines h, _, c = w.partition("_") return w in self.accept if not c else (h in self.accept and (c in ("de", "da", "ki") or (is_clitic(c) and h in self.accept)) and w not in BADJ)
def cls(self, w): """word = seen in the training text; dict = a form only the dictionary builds; non = neither""" return "word" if w in self.lex.counts or w in self.keep or w in self.lex.rare else "dict" if self.valid(w) else "non"
def cands(self, w): if w not in self.cc: self.cc[w] = self.lex.candidates(w) return self.cc[w]22 unmodified lines if self.th: off = np.ones((n, KC - 1), bool) for j, (d, i, w, c) in enumerate(b): v = "word" if self.valid(w) else "non" v = self.cls(w) for k, (x, kd) in enumerate(c): off[j, k] = self.th.get(f"{KN[kd]}_{v}", 99) >= 99 and COMMON.get(w) != x best = np.where(off.all(1), best, np.where(off, -1e9, sc[:, 1:]).argmax(1)) for j, (d, i, w, c) in enumerate(b):5 unmodified lines if r[4] == 3 and not r[5] and (r[2] in self.foreign or any(c in "qwx" for c in r[2])): return False # foreign word if r[4] == 3 and not r[5] and any(r[2][:k] in self.stems for k in range(5, max(6, len(r[2]) - 1))): return False # a term if cap and r[4] == 3 and not r[5]: return False # a capitalised word we don't know is more likely a name return r[6] > self.th.get(f"{KN[r[4]]}_{'word' if r[5] else 'non'}", 99) + (2 if cap else 0) return r[6] > self.th.get(f"{KN[r[4]]}_{self.cls(r[2])}", 99) + (2 if cap else 0)
def protect(self, text, tk): """(never touched, no letter fixes). Never touched: pieces of links, mails, codes, acronyms, number suffixes, foreign lines. No letter fixes: short or repeated unknown words, interjections."""40 unmodified linesBADJ = {"_".join(v) for v in JOINED.values()}
# ---- extra candidates for unknown words: spoken verb endings, repeated letters, dropped vowels ----VOWELS = "aeıioöuü"; BACK, ROUND = set("aıou"), set("oöuü")def last_v(s): return next((c for c in reversed(s) if c in VOWELS), "e")def ae(s): return "a" if last_v(s) in BACK else "e"def iu(s): v = last_v(s); return ("u" if v in ROUND else "ı") if v in BACK else ("ü" if v in ROUND else "i")PERS = [("yom", "yorum"), ("yon", "yorsun"), ("yosun", "yorsun"), ("yosunuz", "yorsunuz"), ("yoz", "yoruz"), ("yoruzz", "yoruz"), ("yolar", "yorlar"), ("yo", "yor"), ("yodu", "yordu"), ("yodum", "yordum"), ("yoduk", "yorduk"), ("yosa", "yorsa"), ("yosam", "yorsam"), ("yosan", "yorsan"), ("yosak", "yorsak"), ("yomuş", "yormuş"), ("yomu", "yormu"), ("yoki", "yorki")]# future: yapıcam, gelicem, alcam, görücez -> -acağım / -eceğim / -acaksın ... (the vowel before c is often dropped or narrowed)FUT = [("m", "{a}c{a}ğ{i}m"), ("n", "{a}c{a}ks{i}n"), ("z", "{a}c{a}ğ{i}z"), ("k", "{a}c{a}k"), ("ksın", "{a}c{a}ks{i}n"), ("ksin", "{a}c{a}ks{i}n"), ("ksınız", "{a}c{a}ks{i}n{i}z"), ("ksiniz", "{a}c{a}ks{i}n{i}z"), ("lar", "{a}c{a}kl{a}r"), ("ler", "{a}c{a}kl{a}r"), ("ktı", "{a}c{a}kt{i}"), ("kti", "{a}c{a}kt{i}")]VOW = set(VOWELS)def spoken(w): out = [] for a, b in PERS: if w.endswith(a) and len(w) > len(a) + 2: out.append(w[:-len(a)] + b) if a[0] == "y" and w[:-len(a)][-1:] not in VOW: out.append(w[:-len(a)] + iu(w[:-len(a)]) + b) m = re.match(r"^(.+?)([ıiuü]?)c([ae])(m|n|z|k|ks[ıi]n|ks[ıi]n[ıi]z|l[ae]r|kt[ıi])$", w) if m: st, e = m[1], m[4] for x in {st, st[:-1] if st[-1:] in "aeıiuü" and len(st) > 2 else st}: for suf, tpl in FUT: if e == suf: for buf in ("", "y"): base = x + buf; aa = ae(x); out.append(base + tpl.format(a=aa, i="ı" if aa == "a" else "i")) # yiyecek / diyecek: yicem, dicem if x in ("y", "yi"): out += ["yiyec" + "eğim", "yiyeceğiz"] if e in "mz" else [] if x in ("d", "di"): out += ["diyeceğim", "diyeceğiz"] if e in "mz" else [] if w.endswith(("dim", "tim", "dım", "tım")) and False: pass for a, b in (("mıyo", "mıyor"), ("miyo", "miyor"), ("muyo", "muyor"), ("müyo", "müyor"), ("mıyom", "mıyorum"), ("miyom", "miyorum")): if w.endswith(a): out.append(w[:-len(a)] + b) return out
def collapse(w): r = [(m.start(), m.end()) for m in re.finditer(r"(.)\1+", w)] if not r: return [] one = re.sub(r"(.)\1+", r"\1", w); two = re.sub(r"(.)\1{2,}", r"\1\1", w); out = [one, two] for a, b in r: out.append(w[:a + 1] + w[b:]) return [x for x in dict.fromkeys(out) if x != w and len(x) > 1]
CONS = re.compile("[aeıioöuü]+")
class _Rules(_Core): def __init__(self, *a, **k): super().__init__(*a, **k); self.rules = True; self.rc = {}; self.big = {a: int(b) for a, b in (l.rstrip('\n').split('\t') for l in open(os.path.join(self.folder, 'pairs.tsv'), encoding='utf-8'))} self.sk = collections.defaultdict(list) if True: for w, c in sorted(self.lex.counts.items(), key=lambda q: -q[1])[:40000]: if "_" not in w and len(w) > 2: self.sk[CONS.sub("", fold(w))].append(w) spmin = 150 def extra(self, w): """[(candidate, rule name)]""" if w in self.rc: return self.rc[w] out = [] if self.rules and "_" not in w and WORD.match(w): if w in self.real: out += [(x, "real") for x in self.real[w]] if not self.valid(w): if w in self.fixed: out.append((self.fixed[w], "fixed")) out += [(x, "spoken") for x in spoken(w) if x in self.lex.counts or x in self.lex.rare or x in self.accept] for x in (collapse(w) if not (w.startswith(("ss", "ll")) ) else []): if x in self.lex.counts: out.append((x, "collapse")) else: fs = [c for c in self.lex.by_fold.get(fold(x), []) if "_" not in c][:2]; out += [(c, "collapse") for c in fs] f = fold(w) if len(f) >= 4 and sum(c in "aeiou" for c in f) * 3 <= len(f): # dropped vowels: kalrsn, konuşrken def sub(c): it = iter(fold(c)); return all(x in it for x in f) out += [(c, "skel") for c in self.sk.get(CONS.sub("", f), [])[:6] if c != w and fold(c)[0] == f[0] and fold(c)[-1] == f[-1] and sub(c)][:2] have = {c for c, _ in self.lex.candidates(w)} if out else set() # already a candidate: keeps its own kind and limit seen = set(); self.rc[w] = [(c, n) for c, n in out if c != w and (c not in have or n in ("fixed", "spoken")) and not (c in have and any(k == FOLD for x, k in self.lex.candidates(w) if x == c)) and not (c in seen or seen.add(c))][:5] return self.rc[w] def cands(self, w): if w not in self.cc: b = self.lex.candidates(w) sp = self.split(w) if self.rules and "_" not in w and WORD.match(w) and w not in COMMON and w not in self.fixed else None if sp and sp[0] >= self.spmin: self.rc[w] = [(sp[1] + "_" + sp[2], "split")]; self.cc[w] = [(sp[1] + "_" + sp[2], SPACE)]; return self.cc[w] if self.rules and w in COMMON and not self.valid(w) and COMMON[w] in self.lex.counts: self.cc[w] = [(COMMON[w], SPACE if "_" in COMMON[w] else EDIT)]; return self.cc[w] x = [(c, EDIT) for c, n in self.extra(w) if n in ("fixed", "spoken", "real") or not any(k in (FOLD, SPACE) for _, k in b)] names = {c for c, _ in x}; self.cc[w] = (x + [q for q in b if q[0] not in names])[:self.lex.kmax + (len(x) > 0)]; self.cc[w] = self.cc[w][:self.lex.kmax] return self.cc[w] def ruleof(self, w, c): return next((n for x, n in self.extra(w) if x == c), None) def decide(self, r, cap=False): n = self.ruleof(r[2], r[3]) if n is None and r[4] == 3 and COMMON.get(r[2]) != r[3] and r[2] in self.keep and r[2] not in self.lex.counts and r[2] not in self.lex.rare: return False # a name or everyday word the model was never taught (işyeri, siber) if n is None or COMMON.get(r[2]) == r[3]: return super().decide(r, cap) if cap and n not in ("fixed", "spoken"): return len(r[2]) >= 5 and r[6] > getattr(self, "capgain", 99) if n == "split": return not cap or r[6] > 0 return r[6] > self.th.get("rule_" + n, 99) + (2 if cap else 0) def split(self, w): """missed space in an unknown word: best pair of known words seen next to each other""" if len(w) < 5 or self.valid(w) or w in self.foreign or any(c in "qwx" for c in w): return None best = None for i in range(1, len(w)): u, v = w[:i], w[i:] if len(v) < 2 or (i == 1 and u != "o"): continue n = self.big.get(u + " " + v, 0) if n and (best is None or n > best[0]): best = (n, u, v) return best
SPEC = set("çğıöşüÇĞİÖŞÜ")class TinyFixTR(_Rules): softlen, softgain, capgain = 4, 18, 25 """Rules + 'the whole text has no Turkish letters' shift + missed-space split.""" def __init__(self, *a, **k): super().__init__(*a, **k); self.doc = True def protect(self, text, tk): hard, soft = super().protect(text, tk) if self.softgain < 99: for i, (w, a, b) in enumerate(tk): if i in soft and WORD.match(w) and len(w) >= self.softlen and text[a:b].islower() and not re.search(r"(.)\1\1", w) and not self.valid(w): soft.discard(i) return hard, soft def shift(self, text, tk): if not self.doc or any(c in SPEC for c in text): return 0.0 n = sum(1 for t, _, _ in tk if WORD.match(t) and len(t) >= 3); return max(0.0, min(3.0, .6 * n - 2.6)) * 1.3 def fix(self, texts, detail=False): tks = [tokenize(t) for t in texts]; sh = [self.shift(t, k) for t, k in zip(texts, tks)] base = self.decide; cur = [0] self._sh = 0.0 if any(sh): return self._fix_shift(texts, tks, sh, detail) out = super().fix(texts, detail); return self._space(out, texts, detail) def _fix_shift(self, texts, tks, sh, detail): groups = {} for i, s in enumerate(sh): groups.setdefault(round(s, 2), []).append(i) fin = [None] * len(texts); ch = [] for s, ix in groups.items(): self._sh = s; o, c = super().fix([texts[i] for i in ix], True); self._sh = 0.0 for j, i in enumerate(ix): fin[i] = o[j] ch += [(ix[r[0]],) + tuple(r[1:]) for r in c] return self._space((fin, ch) if detail else fin, texts, detail) def decide(self, r, cap=False): if self.softgain < 99 and r[4] == 3 and not r[5] and len(r[2]) <= 4 and self.ruleof(r[2], r[3]) is None and r[6] < self.softgain: return False if cap and self.capgain < 99 and r[4] == 3 and not r[5] and self.ruleof(r[2], r[3]) is None and r[6] > self.capgain and len(r[2]) >= 5: # an unknown word that opens a sentence return super().decide(r, False) if self._sh and r[4] == 1 and self.ruleof(r[2], r[3]) is None: r = r[:6] + (r[6] + self._sh,) return super().decide(r, cap) def _space(self, out, texts, detail): return out _sh = 0.0
def main(): ap = argparse.ArgumentParser(description="Turkish autocorrect: reads lines, writes corrected lines."); ap.add_argument("--mode", choices=("cautious", "full"), default="cautious"); ap.add_argument("text", nargs="*") a = ap.parse_args(); f = TinyFixTR(mode=a.mode)README.md+26-18
config.json
model.onnx+2-2
pairs.tsvAdded
tinyfix_tr.py+150-4