Round 4: rules for spoken forms and joined words, more training text, better wrong-word fixes
Browse files- README.md +26 -18
- config.json +0 -0
- model.onnx +2 -2
- pairs.tsv +0 -0
- tinyfix_tr.py +150 -4
README.md
CHANGED
|
@@ -9,9 +9,10 @@ datasets: [HuggingFaceFW/fineweb-2]
|
|
| 9 |
# TinyFix Turkish
|
| 10 |
|
| 11 |
A small Turkish autocorrect for typed text. It restores Turkish letters (cok → çok), fixes joined or split words (herşey → her şey,
|
| 12 |
-
hiç bir → hiçbir, bende → ben de),
|
|
|
|
| 13 |
|
| 14 |
-
4.84M parameters, 8-bit ONNX file of 5 MB; the word lists next to it take
|
| 15 |
[paperweight/tinyfix](https://huggingface.co/paperweight/tinyfix) (MIT): hashed character pieces, a left and a right GRU, and a scorer that
|
| 16 |
picks between the typed word and up to 8 candidates. This implementation and its training are separate from that project.
|
| 17 |
|
|
@@ -25,7 +26,7 @@ fix("Yanlız kaldım, herşey cok guzel olucak.")
|
|
| 25 |
# 'Yalnız kaldım, her şey çok güzel olacak.'
|
| 26 |
```
|
| 27 |
|
| 28 |
-
Cautious mode
|
| 29 |
|
| 30 |
## Results
|
| 31 |
|
|
@@ -33,36 +34,43 @@ On [Turkish Autocorrect Benchmark](https://huggingface.co/datasets/wite-tech/tur
|
|
| 33 |
|
| 34 |
| Kind of mistake | Cautious: fixed / precision | Full: fixed / precision |
|
| 35 |
|---|---|---|
|
| 36 |
-
| Real mistakes in movie reviews |
|
| 37 |
-
| Call-center style messages (invented) |
|
| 38 |
-
| No Turkish letters |
|
| 39 |
-
| Joined or split words |
|
| 40 |
-
| Everyday misspellings* |
|
| 41 |
-
| Typing slips |
|
|
|
|
| 42 |
| Correct words broken | 3.5 per 10,000 | 5.9 per 10,000 |
|
| 43 |
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
## Limits
|
| 49 |
|
| 50 |
-
- It fixes about half of the real mistakes in the review texts. It is not a grammar corrector and does not rewrite sentences.
|
| 51 |
-
- Misspellings
|
| 52 |
-
- de/da, ki, mi choices are decided from 12 words before and 4 after.
|
| 53 |
- It does not improve speech-recognition transcripts: in our tests the word error rate stayed the same or rose slightly.
|
| 54 |
- Names and foreign words can look like slips. The word lists hold words from the web, including offensive ones and people's names.
|
| 55 |
- The hats (â, î, û) are never added or removed. Suffixes right after a quote mark are left alone.
|
| 56 |
|
| 57 |
## Training data
|
| 58 |
|
| 59 |
-
- Text: FineWeb-2 (Turkish), ODC-By 1.0, about
|
|
|
|
| 60 |
- 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.
|
| 61 |
-
- Thresholds: set on
|
|
|
|
| 62 |
- No customer, personal or call data was used.
|
| 63 |
|
| 64 |
## Files and licences
|
| 65 |
|
| 66 |
- `tinyfix_tr.py`, `model.onnx`, `tools/`: MIT (`LICENSE`).
|
| 67 |
-
- `lexicon.tsv`, `rare.tsv`, `config.json`: word lists and counts from FineWeb-2 text, ODC-By 1.0.
|
| 68 |
- `valid_words.bin`: MPL-2.0 (`LICENSE-MPL-2.0.txt`), derived from hunspell-tr; the program that builds it is in `tools/`.
|
|
|
|
| 9 |
# TinyFix Turkish
|
| 10 |
|
| 11 |
A small Turkish autocorrect for typed text. It restores Turkish letters (cok → çok), fixes joined or split words (herşey → her şey,
|
| 12 |
+
hiç bir → hiçbir, bende → ben de), spoken spellings (yapıyom → yapıyorum), repeated letters, everyday misspellings and, best in full mode, typing slips
|
| 13 |
+
and 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).
|
| 14 |
|
| 15 |
+
4.84M parameters, 8-bit ONNX file of 5 MB; the word lists next to it take 22 MB. The recipe follows
|
| 16 |
[paperweight/tinyfix](https://huggingface.co/paperweight/tinyfix) (MIT): hashed character pieces, a left and a right GRU, and a scorer that
|
| 17 |
picks between the typed word and up to 8 candidates. This implementation and its training are separate from that project.
|
| 18 |
|
|
|
|
| 26 |
# 'Yalnız kaldım, her şey çok güzel olacak.'
|
| 27 |
```
|
| 28 |
|
| 29 |
+
Cautious mode changes the letters of an unknown word only when it is very sure. Full mode changes more, and fixes many more slips.
|
| 30 |
|
| 31 |
## Results
|
| 32 |
|
|
|
|
| 34 |
|
| 35 |
| Kind of mistake | Cautious: fixed / precision | Full: fixed / precision |
|
| 36 |
|---|---|---|
|
| 37 |
+
| Real mistakes in movie reviews | 52% / 93% | 59% / 92% |
|
| 38 |
+
| Call-center style messages (invented) | 62% / 98% | 75% / 99% |
|
| 39 |
+
| No Turkish letters | 91% / 99.8% | 91% / 99.5% |
|
| 40 |
+
| Joined or split words | 85% / 100% | 85% / 98% |
|
| 41 |
+
| Everyday misspellings* | 59% / 100% | 62% / 100% |
|
| 42 |
+
| Typing slips | 24% / 98% | 70% / 96% |
|
| 43 |
+
| Wrong real words, one word, not letter cases | 17 of 88 | 33 of 88 |
|
| 44 |
| Correct words broken | 3.5 per 10,000 | 5.9 per 10,000 |
|
| 45 |
|
| 46 |
+
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
|
| 47 |
+
[turkish_typo_validation](https://huggingface.co/datasets/burakaytan/turkish_typo_validation) with generated noise from another generator, it fixes 29% / 46% of the
|
| 48 |
+
errors with 95% / 90% precision (cautious / full).
|
| 49 |
+
|
| 50 |
+
*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.
|
| 51 |
+
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 as
|
| 52 |
+
indicative. Most of the gain since the first release comes from rules and data made after that.
|
| 53 |
|
| 54 |
## Limits
|
| 55 |
|
| 56 |
+
- 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.
|
| 57 |
+
- Misspellings that are far from the right word, and most wrong real words, are left alone.
|
| 58 |
+
- de/da, ki, mi and wrong-real-word choices are decided from 12 words before and 4 after.
|
| 59 |
- It does not improve speech-recognition transcripts: in our tests the word error rate stayed the same or rose slightly.
|
| 60 |
- Names and foreign words can look like slips. The word lists hold words from the web, including offensive ones and people's names.
|
| 61 |
- The hats (â, î, û) are never added or removed. Suffixes right after a quote mark are left alone.
|
| 62 |
|
| 63 |
## Training data
|
| 64 |
|
| 65 |
+
- 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.
|
| 66 |
+
- 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).
|
| 67 |
- 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.
|
| 68 |
+
- 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.
|
| 69 |
+
- A small list of wrong real words from [Turkish-Spelling-Dictionary](https://huggingface.co/datasets/asimokby/Turkish-Spelling-Dictionary) (MIT).
|
| 70 |
- No customer, personal or call data was used.
|
| 71 |
|
| 72 |
## Files and licences
|
| 73 |
|
| 74 |
- `tinyfix_tr.py`, `model.onnx`, `tools/`: MIT (`LICENSE`).
|
| 75 |
+
- `lexicon.tsv`, `rare.tsv`, `pairs.tsv`, `config.json`: word lists and counts from FineWeb-2 text, ODC-By 1.0.
|
| 76 |
- `valid_words.bin`: MPL-2.0 (`LICENSE-MPL-2.0.txt`), derived from hunspell-tr; the program that builds it is in `tools/`.
|
config.json
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|
model.onnx
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:457b02e80618d8f5fda4310fb71652b9cb4682afbb833720d00f1806f7f6bc39
|
| 3 |
+
size 4949943
|
pairs.tsv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tinyfix_tr.py
CHANGED
|
@@ -178,7 +178,7 @@ class WordSet:
|
|
| 178 |
return all((self.bits[p >> 3] >> (p & 7)) & 1 for p in ((a + i * b) % self.m for i in range(self.k)))
|
| 179 |
|
| 180 |
|
| 181 |
-
class
|
| 182 |
"""mode "cautious" never changes letters of unknown words; "full" does, and fixes many more slips."""
|
| 183 |
def __init__(self, folder=None, mode="cautious", threads=1):
|
| 184 |
import onnxruntime as ort
|
|
@@ -186,7 +186,7 @@ class TinyFixTR:
|
|
| 186 |
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")]
|
| 187 |
rare = {a: int(b) for a, b in (l.rstrip("\n").split("\t") for l in open(j("rare.tsv"), encoding="utf-8"))}
|
| 188 |
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"))
|
| 189 |
-
self.sp, self.keep, self.foreign, self.stems = (set(cfg[k]) for k in ("special", "keep", "foreign", "stems")); self.th = cfg["thresholds"][mode]
|
| 190 |
so = ort.SessionOptions(); so.intra_op_num_threads = threads; so.log_severity_level = 3
|
| 191 |
self.net = ort.InferenceSession(j("model.onnx"), so, providers=["CPUExecutionProvider"]); self.cc, self.pc = {}, {}
|
| 192 |
|
|
@@ -205,6 +205,10 @@ class TinyFixTR:
|
|
| 205 |
h, _, c = w.partition("_")
|
| 206 |
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)
|
| 207 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
def cands(self, w):
|
| 209 |
if w not in self.cc: self.cc[w] = self.lex.candidates(w)
|
| 210 |
return self.cc[w]
|
|
@@ -233,7 +237,7 @@ class TinyFixTR:
|
|
| 233 |
if self.th:
|
| 234 |
off = np.ones((n, KC - 1), bool)
|
| 235 |
for j, (d, i, w, c) in enumerate(b):
|
| 236 |
-
v =
|
| 237 |
for k, (x, kd) in enumerate(c): off[j, k] = self.th.get(f"{KN[kd]}_{v}", 99) >= 99 and COMMON.get(w) != x
|
| 238 |
best = np.where(off.all(1), best, np.where(off, -1e9, sc[:, 1:]).argmax(1))
|
| 239 |
for j, (d, i, w, c) in enumerate(b):
|
|
@@ -245,7 +249,7 @@ class TinyFixTR:
|
|
| 245 |
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
|
| 246 |
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
|
| 247 |
if cap and r[4] == 3 and not r[5]: return False # a capitalised word we don't know is more likely a name
|
| 248 |
-
return r[6] > self.th.get(f"{KN[r[4]]}_{
|
| 249 |
|
| 250 |
def protect(self, text, tk):
|
| 251 |
"""(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."""
|
|
@@ -292,6 +296,148 @@ def up(s): return s.replace("i", "İ").replace("ı", "I").upper()
|
|
| 292 |
BADJ = {"_".join(v) for v in JOINED.values()}
|
| 293 |
|
| 294 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 295 |
def main():
|
| 296 |
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="*")
|
| 297 |
a = ap.parse_args(); f = TinyFixTR(mode=a.mode)
|
|
|
|
| 178 |
return all((self.bits[p >> 3] >> (p & 7)) & 1 for p in ((a + i * b) % self.m for i in range(self.k)))
|
| 179 |
|
| 180 |
|
| 181 |
+
class _Core:
|
| 182 |
"""mode "cautious" never changes letters of unknown words; "full" does, and fixes many more slips."""
|
| 183 |
def __init__(self, folder=None, mode="cautious", threads=1):
|
| 184 |
import onnxruntime as ort
|
|
|
|
| 186 |
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")]
|
| 187 |
rare = {a: int(b) for a, b in (l.rstrip("\n").split("\t") for l in open(j("rare.tsv"), encoding="utf-8"))}
|
| 188 |
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"))
|
| 189 |
+
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]
|
| 190 |
so = ort.SessionOptions(); so.intra_op_num_threads = threads; so.log_severity_level = 3
|
| 191 |
self.net = ort.InferenceSession(j("model.onnx"), so, providers=["CPUExecutionProvider"]); self.cc, self.pc = {}, {}
|
| 192 |
|
|
|
|
| 205 |
h, _, c = w.partition("_")
|
| 206 |
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)
|
| 207 |
|
| 208 |
+
def cls(self, w):
|
| 209 |
+
"""word = seen in the training text; dict = a form only the dictionary builds; non = neither"""
|
| 210 |
+
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"
|
| 211 |
+
|
| 212 |
def cands(self, w):
|
| 213 |
if w not in self.cc: self.cc[w] = self.lex.candidates(w)
|
| 214 |
return self.cc[w]
|
|
|
|
| 237 |
if self.th:
|
| 238 |
off = np.ones((n, KC - 1), bool)
|
| 239 |
for j, (d, i, w, c) in enumerate(b):
|
| 240 |
+
v = self.cls(w)
|
| 241 |
for k, (x, kd) in enumerate(c): off[j, k] = self.th.get(f"{KN[kd]}_{v}", 99) >= 99 and COMMON.get(w) != x
|
| 242 |
best = np.where(off.all(1), best, np.where(off, -1e9, sc[:, 1:]).argmax(1))
|
| 243 |
for j, (d, i, w, c) in enumerate(b):
|
|
|
|
| 249 |
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
|
| 250 |
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
|
| 251 |
if cap and r[4] == 3 and not r[5]: return False # a capitalised word we don't know is more likely a name
|
| 252 |
+
return r[6] > self.th.get(f"{KN[r[4]]}_{self.cls(r[2])}", 99) + (2 if cap else 0)
|
| 253 |
|
| 254 |
def protect(self, text, tk):
|
| 255 |
"""(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."""
|
|
|
|
| 296 |
BADJ = {"_".join(v) for v in JOINED.values()}
|
| 297 |
|
| 298 |
|
| 299 |
+
# ---- extra candidates for unknown words: spoken verb endings, repeated letters, dropped vowels ----
|
| 300 |
+
VOWELS = "aeıioöuü"; BACK, ROUND = set("aıou"), set("oöuü")
|
| 301 |
+
def last_v(s): return next((c for c in reversed(s) if c in VOWELS), "e")
|
| 302 |
+
def ae(s): return "a" if last_v(s) in BACK else "e"
|
| 303 |
+
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")
|
| 304 |
+
PERS = [("yom", "yorum"), ("yon", "yorsun"), ("yosun", "yorsun"), ("yosunuz", "yorsunuz"), ("yoz", "yoruz"), ("yoruzz", "yoruz"), ("yolar", "yorlar"), ("yo", "yor"),
|
| 305 |
+
("yodu", "yordu"), ("yodum", "yordum"), ("yoduk", "yorduk"), ("yosa", "yorsa"), ("yosam", "yorsam"), ("yosan", "yorsan"), ("yosak", "yorsak"), ("yomuş", "yormuş"), ("yomu", "yormu"), ("yoki", "yorki")]
|
| 306 |
+
# future: yapıcam, gelicem, alcam, görücez -> -acağım / -eceğim / -acaksın ... (the vowel before c is often dropped or narrowed)
|
| 307 |
+
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}")]
|
| 308 |
+
VOW = set(VOWELS)
|
| 309 |
+
def spoken(w):
|
| 310 |
+
out = []
|
| 311 |
+
for a, b in PERS:
|
| 312 |
+
if w.endswith(a) and len(w) > len(a) + 2:
|
| 313 |
+
out.append(w[:-len(a)] + b)
|
| 314 |
+
if a[0] == "y" and w[:-len(a)][-1:] not in VOW: out.append(w[:-len(a)] + iu(w[:-len(a)]) + b)
|
| 315 |
+
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)
|
| 316 |
+
if m:
|
| 317 |
+
st, e = m[1], m[4]
|
| 318 |
+
for x in {st, st[:-1] if st[-1:] in "aeıiuü" and len(st) > 2 else st}:
|
| 319 |
+
for suf, tpl in FUT:
|
| 320 |
+
if e == suf:
|
| 321 |
+
for buf in ("", "y"):
|
| 322 |
+
base = x + buf; aa = ae(x); out.append(base + tpl.format(a=aa, i="ı" if aa == "a" else "i"))
|
| 323 |
+
# yiyecek / diyecek: yicem, dicem
|
| 324 |
+
if x in ("y", "yi"): out += ["yiyec" + "eğim", "yiyeceğiz"] if e in "mz" else []
|
| 325 |
+
if x in ("d", "di"): out += ["diyeceğim", "diyeceğiz"] if e in "mz" else []
|
| 326 |
+
if w.endswith(("dim", "tim", "dım", "tım")) and False: pass
|
| 327 |
+
for a, b in (("mıyo", "mıyor"), ("miyo", "miyor"), ("muyo", "muyor"), ("müyo", "müyor"), ("mıyom", "mıyorum"), ("miyom", "miyorum")):
|
| 328 |
+
if w.endswith(a): out.append(w[:-len(a)] + b)
|
| 329 |
+
return out
|
| 330 |
+
|
| 331 |
+
def collapse(w):
|
| 332 |
+
r = [(m.start(), m.end()) for m in re.finditer(r"(.)\1+", w)]
|
| 333 |
+
if not r: return []
|
| 334 |
+
one = re.sub(r"(.)\1+", r"\1", w); two = re.sub(r"(.)\1{2,}", r"\1\1", w); out = [one, two]
|
| 335 |
+
for a, b in r: out.append(w[:a + 1] + w[b:])
|
| 336 |
+
return [x for x in dict.fromkeys(out) if x != w and len(x) > 1]
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
CONS = re.compile("[aeıioöuü]+")
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
class _Rules(_Core):
|
| 343 |
+
def __init__(self, *a, **k):
|
| 344 |
+
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'))}
|
| 345 |
+
self.sk = collections.defaultdict(list)
|
| 346 |
+
if True:
|
| 347 |
+
for w, c in sorted(self.lex.counts.items(), key=lambda q: -q[1])[:40000]:
|
| 348 |
+
if "_" not in w and len(w) > 2: self.sk[CONS.sub("", fold(w))].append(w)
|
| 349 |
+
spmin = 150
|
| 350 |
+
def extra(self, w):
|
| 351 |
+
"""[(candidate, rule name)]"""
|
| 352 |
+
if w in self.rc: return self.rc[w]
|
| 353 |
+
out = []
|
| 354 |
+
if self.rules and "_" not in w and WORD.match(w):
|
| 355 |
+
if w in self.real: out += [(x, "real") for x in self.real[w]]
|
| 356 |
+
if not self.valid(w):
|
| 357 |
+
if w in self.fixed: out.append((self.fixed[w], "fixed"))
|
| 358 |
+
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]
|
| 359 |
+
for x in (collapse(w) if not (w.startswith(("ss", "ll")) ) else []):
|
| 360 |
+
if x in self.lex.counts: out.append((x, "collapse"))
|
| 361 |
+
else:
|
| 362 |
+
fs = [c for c in self.lex.by_fold.get(fold(x), []) if "_" not in c][:2]; out += [(c, "collapse") for c in fs]
|
| 363 |
+
f = fold(w)
|
| 364 |
+
if len(f) >= 4 and sum(c in "aeiou" for c in f) * 3 <= len(f): # dropped vowels: kalrsn, konuşrken
|
| 365 |
+
def sub(c):
|
| 366 |
+
it = iter(fold(c)); return all(x in it for x in f)
|
| 367 |
+
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]
|
| 368 |
+
have = {c for c, _ in self.lex.candidates(w)} if out else set() # already a candidate: keeps its own kind and limit
|
| 369 |
+
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]
|
| 370 |
+
return self.rc[w]
|
| 371 |
+
def cands(self, w):
|
| 372 |
+
if w not in self.cc:
|
| 373 |
+
b = self.lex.candidates(w)
|
| 374 |
+
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
|
| 375 |
+
if sp and sp[0] >= self.spmin:
|
| 376 |
+
self.rc[w] = [(sp[1] + "_" + sp[2], "split")]; self.cc[w] = [(sp[1] + "_" + sp[2], SPACE)]; return self.cc[w]
|
| 377 |
+
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]
|
| 378 |
+
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)]
|
| 379 |
+
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]
|
| 380 |
+
return self.cc[w]
|
| 381 |
+
def ruleof(self, w, c): return next((n for x, n in self.extra(w) if x == c), None)
|
| 382 |
+
def decide(self, r, cap=False):
|
| 383 |
+
n = self.ruleof(r[2], r[3])
|
| 384 |
+
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)
|
| 385 |
+
if n is None or COMMON.get(r[2]) == r[3]: return super().decide(r, cap)
|
| 386 |
+
if cap and n not in ("fixed", "spoken"): return len(r[2]) >= 5 and r[6] > getattr(self, "capgain", 99)
|
| 387 |
+
if n == "split": return not cap or r[6] > 0
|
| 388 |
+
return r[6] > self.th.get("rule_" + n, 99) + (2 if cap else 0)
|
| 389 |
+
def split(self, w):
|
| 390 |
+
"""missed space in an unknown word: best pair of known words seen next to each other"""
|
| 391 |
+
if len(w) < 5 or self.valid(w) or w in self.foreign or any(c in "qwx" for c in w): return None
|
| 392 |
+
best = None
|
| 393 |
+
for i in range(1, len(w)):
|
| 394 |
+
u, v = w[:i], w[i:]
|
| 395 |
+
if len(v) < 2 or (i == 1 and u != "o"): continue
|
| 396 |
+
n = self.big.get(u + " " + v, 0)
|
| 397 |
+
if n and (best is None or n > best[0]): best = (n, u, v)
|
| 398 |
+
return best
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
SPEC = set("çğıöşüÇĞİÖŞÜ")
|
| 402 |
+
class TinyFixTR(_Rules):
|
| 403 |
+
softlen, softgain, capgain = 4, 18, 25
|
| 404 |
+
"""Rules + 'the whole text has no Turkish letters' shift + missed-space split."""
|
| 405 |
+
def __init__(self, *a, **k):
|
| 406 |
+
super().__init__(*a, **k); self.doc = True
|
| 407 |
+
def protect(self, text, tk):
|
| 408 |
+
hard, soft = super().protect(text, tk)
|
| 409 |
+
if self.softgain < 99:
|
| 410 |
+
for i, (w, a, b) in enumerate(tk):
|
| 411 |
+
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)
|
| 412 |
+
return hard, soft
|
| 413 |
+
def shift(self, text, tk):
|
| 414 |
+
if not self.doc or any(c in SPEC for c in text): return 0.0
|
| 415 |
+
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
|
| 416 |
+
def fix(self, texts, detail=False):
|
| 417 |
+
tks = [tokenize(t) for t in texts]; sh = [self.shift(t, k) for t, k in zip(texts, tks)]
|
| 418 |
+
base = self.decide; cur = [0]
|
| 419 |
+
self._sh = 0.0
|
| 420 |
+
if any(sh): return self._fix_shift(texts, tks, sh, detail)
|
| 421 |
+
out = super().fix(texts, detail); return self._space(out, texts, detail)
|
| 422 |
+
def _fix_shift(self, texts, tks, sh, detail):
|
| 423 |
+
groups = {}
|
| 424 |
+
for i, s in enumerate(sh): groups.setdefault(round(s, 2), []).append(i)
|
| 425 |
+
fin = [None] * len(texts); ch = []
|
| 426 |
+
for s, ix in groups.items():
|
| 427 |
+
self._sh = s; o, c = super().fix([texts[i] for i in ix], True); self._sh = 0.0
|
| 428 |
+
for j, i in enumerate(ix): fin[i] = o[j]
|
| 429 |
+
ch += [(ix[r[0]],) + tuple(r[1:]) for r in c]
|
| 430 |
+
return self._space((fin, ch) if detail else fin, texts, detail)
|
| 431 |
+
def decide(self, r, cap=False):
|
| 432 |
+
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
|
| 433 |
+
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
|
| 434 |
+
return super().decide(r, False)
|
| 435 |
+
if self._sh and r[4] == 1 and self.ruleof(r[2], r[3]) is None: r = r[:6] + (r[6] + self._sh,)
|
| 436 |
+
return super().decide(r, cap)
|
| 437 |
+
def _space(self, out, texts, detail): return out
|
| 438 |
+
_sh = 0.0
|
| 439 |
+
|
| 440 |
+
|
| 441 |
def main():
|
| 442 |
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="*")
|
| 443 |
a = ap.parse_args(); f = TinyFixTR(mode=a.mode)
|