Add model, code and card
Browse filesFiles changed (11)
- LICENSEAdded+9
- LICENSE-MPL-2.0.txtAdded+373
- README.mdAdded+68
- config.jsonAdded
- lexicon.tsvAdded
- model.onnxAdded+3
- rare.tsvAdded
- tinyfix_tr.pyAdded+301
- tools/expand_hunspell.pyAdded+19
- tools/make_words.pyAdded+8
- valid_words.binAdded+3
123456789MIT License
Copyright (c) 2026 the TinyFix Turkish authors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373Mozilla Public License Version 2.0==================================
1. Definitions--------------
1.1. "Contributor" means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software.
1.2. "Contributor Version" means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution" means Covered Software of a particular Contributor.
1.4. "Covered Software" means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof.
1.5. "Incompatible With Secondary Licenses" means
(a) that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License.
1.6. "Executable Form" means any form of the work other than Source Code Form.
1.7. "Larger Work" means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software.
1.8. "License" means this document.
1.9. "Licensable" means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License.
1.10. "Modifications" means any of the following:
(a) any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or
(b) any new file in Source Code Form that contains any Covered Software.
1.11. "Patent Claims" of a Contributor means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version.
1.12. "Secondary License" means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses.
1.13. "Source Code Form" means the form of the work preferred for making modifications.
1.14. "You" (or "Your") means an individual or a legal entity exercising rights under this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity.
2. License Grants and Conditions--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,non-exclusive license:
(a) under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contributionbecome effective for each Contribution on the date the Contributor firstdistributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted underthis License. No additional rights or licenses will be implied from thedistribution or licensing of Covered Software under this License.Notwithstanding Section 2.1(b) above, no patent license is granted by aContributor:
(a) for any code that a Contributor has removed from Covered Software; or
(b) for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or
(c) under Patent Claims infringed by Covered Software in the absence of its Contributions.
This License does not grant any rights in the trademarks, service marks,or logos of any Contributor (except as may be necessary to comply withthe notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice todistribute the Covered Software under a subsequent version of thisLicense (see Section 10.2) or under the terms of a Secondary License (ifpermitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes itsContributions are its original creation(s) or it has sufficient rightsto grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have underapplicable copyright doctrines of fair use, fair dealing, or otherequivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses grantedin Section 2.1.
3. Responsibilities-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including anyModifications that You create or to which You contribute, must be underthe terms of this License. You must inform recipients that the SourceCode Form of the Covered Software is governed by the terms of thisLicense, and how they can obtain a copy of this License. You may notattempt to alter or restrict the recipients' rights in the Source CodeForm.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,provided that You also comply with the requirements of this License forthe Covered Software. If the Larger Work is a combination of CoveredSoftware with a work governed by one or more Secondary Licenses, and theCovered Software is not Incompatible With Secondary Licenses, thisLicense permits You to additionally distribute such Covered Softwareunder the terms of such Secondary License(s), so that the recipient ofthe Larger Work may, at their option, further distribute the CoveredSoftware under the terms of either this License or such SecondaryLicense(s).
3.4. Notices
You may not remove or alter the substance of any license notices(including copyright notices, patent notices, disclaimers of warranty,or limitations of liability) contained within the Source Code Form ofthe Covered Software, except that You may alter any license notices tothe extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,indemnity or liability obligations to one or more recipients of CoveredSoftware. However, You may do so only on Your own behalf, and not onbehalf of any Contributor. You must make it absolutely clear that anysuch warranty, support, indemnity, or liability obligation is offered byYou alone, and You hereby agree to indemnify every Contributor for anyliability incurred by such Contributor as a result of warranty, support,indemnity or liability terms You offer. You may include additionaldisclaimers of warranty and limitations of liability specific to anyjurisdiction.
4. Inability to Comply Due to Statute or Regulation---------------------------------------------------
If it is impossible for You to comply with any of the terms of thisLicense with respect to some or all of the Covered Software due tostatute, judicial order, or regulation then You must: (a) comply withthe terms of this License to the maximum extent possible; and (b)describe the limitations and the code they affect. Such description mustbe placed in a text file included with all distributions of the CoveredSoftware under this License. Except to the extent prohibited by statuteor regulation, such description must be sufficiently detailed for arecipient of ordinary skill to be able to understand it.
5. Termination--------------
5.1. The rights granted under this License will terminate automaticallyif You fail to comply with any of its terms. However, if You becomecompliant, then the rights granted under this License from a particularContributor are reinstated (a) provisionally, unless and until suchContributor explicitly and finally terminates Your grants, and (b) on anongoing basis, if such Contributor fails to notify You of thenon-compliance by some reasonable means prior to 60 days after You havecome back into compliance. Moreover, Your grants from a particularContributor are reinstated on an ongoing basis if such Contributornotifies You of the non-compliance by some reasonable means, this is thefirst time You have received notice of non-compliance with this Licensefrom such Contributor, and You become compliant prior to 30 days afterYour receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patentinfringement claim (excluding declaratory judgment actions,counter-claims, and cross-claims) alleging that a Contributor Versiondirectly or indirectly infringes any patent, then the rights granted toYou by any and all Contributors for the Covered Software under Section2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, allend user license agreements (excluding distributors and resellers) whichhave been validly granted by You or Your distributors under this Licenseprior to termination shall survive termination.
************************************************************************* ** 6. Disclaimer of Warranty ** ------------------------- ** ** Covered Software is provided under this License on an "as is" ** basis, without warranty of any kind, either expressed, implied, or ** statutory, including, without limitation, warranties that the ** Covered Software is free of defects, merchantable, fit for a ** particular purpose or non-infringing. The entire risk as to the ** quality and performance of the Covered Software is with You. ** Should any Covered Software prove defective in any respect, You ** (not any Contributor) assume the cost of any necessary servicing, ** repair, or correction. This disclaimer of warranty constitutes an ** essential part of this License. No use of any Covered Software is ** authorized under this License except under this disclaimer. ** *************************************************************************
************************************************************************* ** 7. Limitation of Liability ** -------------------------- ** ** Under no circumstances and under no legal theory, whether tort ** (including negligence), contract, or otherwise, shall any ** Contributor, or anyone who distributes Covered Software as ** permitted above, be liable to You for any direct, indirect, ** special, incidental, or consequential damages of any character ** including, without limitation, damages for lost profits, loss of ** goodwill, work stoppage, computer failure or malfunction, or any ** and all other commercial damages or losses, even if such party ** shall have been informed of the possibility of such damages. This ** limitation of liability shall not apply to liability for death or ** personal injury resulting from such party's negligence to the ** extent applicable law prohibits such limitation. Some ** jurisdictions do not allow the exclusion or limitation of ** incidental or consequential damages, so this exclusion and ** limitation may not apply to You. ** *************************************************************************
8. Litigation-------------
Any litigation relating to this License may be brought only in thecourts of a jurisdiction where the defendant maintains its principalplace of business and such litigation shall be governed by laws of thatjurisdiction, without reference to its conflict-of-law provisions.Nothing in this Section shall prevent a party's ability to bringcross-claims or counter-claims.
9. Miscellaneous----------------
This License represents the complete agreement concerning the subjectmatter hereof. If any provision of this License is held to beunenforceable, such provision shall be reformed only to the extentnecessary to make it enforceable. Any law or regulation which providesthat the language of a contract shall be construed against the draftershall not be used to construe this License against a Contributor.
10. Versions of the License---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section10.3, no one other than the license steward has the right to modify orpublish new versions of this License. Each version will be given adistinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the versionof the License under which You originally received the Covered Software,or under the terms of any subsequent version published by the licensesteward.
10.3. Modified Versions
If you create software not governed by this License, and you want tocreate a new license for such software, you may create and use amodified version of this License if you rename the license and removeany references to the name of the license steward (except to note thatsuch modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With SecondaryLicenses
If You choose to distribute Source Code Form that is Incompatible WithSecondary Licenses under the terms of this version of the License, thenotice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particularfile, then You may include the notice in a location (such as a LICENSEfile in a relevant directory) where a recipient would be likely to lookfor such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768---language: [tr]license: mitlibrary_name: onnxtags: [autocorrect, spelling-correction, turkish, onnx]datasets: [HuggingFaceFW/fineweb-2]---
# 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.
4.84M parameters, 8-bit ONNX file of 5 MB; the word lists next to it take 21 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.
## Use
```python# pip install numpy onnxruntime ; download this folderfrom tinyfix_tr import TinyFixTRfix = TinyFixTR() # cautious mode; TinyFixTR(mode="full") fixes morefix("Yanlız kaldım, herşey cok guzel olucak.")# '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.
## Results
On [Turkish Autocorrect Benchmark](https://huggingface.co/datasets/wite-tech/turkish-autocorrect-bench) (test split). Fixed is recall, precision is the share of changes that are right.
| 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% || 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).
## 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 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.- 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.- 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.- `valid_words.bin`: MPL-2.0 (`LICENSE-MPL-2.0.txt`), derived from hunspell-tr; the program that builds it is in `tools/`.123version https://git-lfs.github.com/spec/v1oid sha256:fca5af693d0ce8721229cb18e66f96fe3a12843b1fa80add9314b308aa8541e7size 4949942123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301"""Turkish autocorrect: fixes typing and spelling mistakes, joined or split words, and text typed without Turkish letters.
from tinyfix_tr import TinyFixTR fix = TinyFixTR("path/to/this/folder") # cautious mode; TinyFixTR(folder, mode="full") fixes more fix("Yanlız kaldım, herşey cok guzel olucak.") # -> "Yalnız kaldım, her şey çok güzel olacak."
Needs numpy and onnxruntime only. Recipe after paperweight/tinyfix (MIT); this implementation was written from scratch."""import argparse, collections, hashlib, json, math, os, re, sys, zlibimport numpy as np
LETTERS = "abcçdefgğhıijklmnoöprsştuüvyzqwxâîû"_HAT = str.maketrans("âîû", "aiu")_F = str.maketrans("çğıöşüâîû", "cgiosuaiu")TOK = re.compile(r"[^\W\d_]+(?:['’][^\W\d_]+)?|\d+(?:[.,:]\d+)*(?:['’][^\W\d_]+)?|[^\w\s]")WORD = re.compile(f"^[{LETTERS}]+(?:_[{LETTERS}]+)?$")OPEN = {".", "!", "?", ":", '"', "…"}MI = re.compile(r"^m([ıiuü])(y[ıiuü]m|s[ıiuü]n([ıiuü]z)?|y[ıiuü]z|yd[ıiuü][a-zçğıöşü]*|ym[ıiuü]ş[a-zçğıöşü]*|d[ıiuü]r|l[ae]r)?$")DEKI = {"de", "da", "ki"}# right spelling is two wordsAPART = {("her", "şey"), ("bir", "şey"), ("çok", "şey"), ("hiçbir", "şey"), ("ya", "da"), ("şu", "an"), ("pek", "çok"), ("sağ", "ol"), ("hoş", "geldin"), ("hoş", "geldiniz"), ("hoş", "bulduk"), ("hoşça", "kal"), ("hoşça", "kalın"), ("art", "arda"), ("arka", "arkaya"), ("yan", "yana"), ("ilk", "önce"), ("bir", "an"), ("her", "gün"), ("her", "hangi_x"), ("fark", "etmez"), ("fark", "ettim"), ("fark", "etti"), ("fark", "eder"), ("terk", "etti"), ("yok", "etti"), ("söz", "etti"), ("devam", "etti"), ("kabul", "etti"), ("hiç", "kimse"), ("baş", "başa")}# right spelling is one wordJOINED = {"hiçbir": ("hiç", "bir"), "birçok": ("bir", "çok"), "birkaç": ("bir", "kaç"), "bugün": ("bu", "gün"), "veya": ("ve", "ya"), "herhangi": ("her", "hangi"), "birtakım": ("bir", "takım"), "biraz": ("bir", "az"), "belki": ("bel", "ki"), "çünkü": ("çün", "kü"), "sanki": ("san", "ki"), "mademki": ("madem", "ki"), "oysaki": ("oysa", "ki"), "halbuki": ("halbu", "ki"), "önceden": ("önce", "den"), "ayrıca": ("ayrı", "ca")}PAIRS = {p for p in APART if "_x" not in p[1]} | set(JOINED.values())
def lower(s): # a hat (hâlâ, şikâyet) is optional in practice: dropped for judging, never written or removed in the output return s.replace("İ", "i").replace("I", "ı").lower().replace("i̇", "i").translate(_HAT)
def fold(w): return lower(w).translate(_F)
def is_clitic(t): return t in DEKI or bool(MI.match(t))
def typed_clitic(t): return t in ("te", "ta") or is_clitic(t)
def tokenize(text): """-> list of (token, start, end); token is lowercased, <name>/<num> for names and numbers, or punctuation.""" raw = [] for m in TOK.finditer(text.replace("’", "'")): s = m.group() start = not raw or raw[-1][0] in OPEN if s[0].isdigit(): t = "<num>" elif s[0].isalpha(): low = lower(s) allcaps = len(s) > 1 and s.upper() == s and s != low t = "<name>" if (s[0].isupper() and not start and not allcaps) or "'" in s else low else: t = s raw.append((t, m.start(), m.end())) out = [] for t, a, b in raw: if out and a - out[-1][2] == 1 and text[out[-1][2]] == " " and WORD.match(out[-1][0]) and "_" not in out[-1][0]: p = out[-1][0] if typed_clitic(t) or (p, t) in PAIRS: out[-1] = (p + "_" + t, out[-1][1], b); continue out.append((t, a, b)) return out
NB, NG = 1 << 16, 20
def pieces(w): s = "<" + w + ">" g = ["W" + s] + [s[i:i + n] for n in (3, 4, 2) for i in range(len(s) - n + 1)] ids = [1 + zlib.crc32(x.encode()) % (NB - 1) for x in g[:NG]] return ids + [0] * (NG - len(ids))
AZ = "abcdefghijklmnopqrstuvwxyz"SAME, FOLD, SPACE, EDIT = 0, 1, 2, 3 # how a candidate differs from the typed token
def one_edits(k): out = set() for i in range(len(k) + 1): a, b = k[:i], k[i:] if b: out.add(a + b[1:]) for c in AZ: out.add(a + c + b[1:]) if len(b) > 1: out.add(a + b[1] + b[0] + b[2:]) for c in AZ: out.add(a + c + b) out.discard(k) return out
# everyday misspellings that are more than one edit away or need a nudge: typed -> meantCOMMON = dict(x.split(":") for x in """yanlız:yalnız yalnış:yanlış herkez:herkes süpriz:sürpriz orjinal:orijinal makina:makineşöför:şoför şöfor:şoför egzos:egzoz klavuz:kılavuz kılavuz:kılavuz insiyatif:inisiyatif inisiyatif:inisiyatif kiprik:kirpik kirbit:kibritkarpız:karpuz meyva:meyve acaip:acayip eşşek:eşek ünvan:unvan sarmısak:sarımsak sarmusak:sarımsak döküman:doküman entellektüel:entelektüelespiri:espri traş:tıraş tiraş:tıraş proğram:program pırogram:program ferfune:ferfene mütahit:müteahhit müteahit:müteahhit laboratuar:laboratuvarbilimum:bilumum antreman:antrenman kordalya:kurdele klüp:kulüp kulüb:kulüp ataş:ataç poğça:poğaça poaça:poğaça dershane:dershane gardrop:gardıropgardolap:gardırop restorant:restoran sandöviç:sandviç sandaviç:sandviç stajer:stajyer şarz:şarj deşarz:deşarj aksesuvar:aksesuar kolleksiyon:koleksiyonçünki:çünkü çünkim:çünkü bugünki:bugünkü dünki:dünkü deyil:değil diyil:değil dimi:değil_mi birsürü:bir_sürü nasi:nasıl nası:nasıl gelicek:gelecekolucak:olacak yapıcak:yapacak edicek:edecek gidicem:gideceğim gelicem:geleceğim yapıcam:yapacağım olucam:olacağım geliyom:geliyorum gidiyom:gidiyorumyapıyom:yapıyorum biliyom:biliyorum istiyom:istiyorum ediyom:ediyorum burda:burada şurda:şurada orda:orada nerde:nerede içerde:içeride dışarda:dışarıdabişey:bir_şey bişi:bir_şey birşi:bir_şey hiçbişey:hiçbir_şey herşeyi:her_şeyi hergün:her_gün heryer:her_yer heryerde:her_yerde hiçkimse:hiç_kimsefarketmez:fark_etmez herzaman:her_zaman birgün:bir_gün hoşgeldiniz:hoş_geldiniz hoşgeldin:hoş_geldin hoşçakal:hoşça_kal yada:ya_da""".split())
for _t in {v for v in COMMON.values() if "_" in v}: APART.add(tuple(_t.split("_")))PAIRS |= APART - {("her", "hangi_x")}
class Lexicon: def __init__(self, counts, rare=None, kmax=8): self.counts, self.rare, self.kmax = counts, rare or {}, kmax self.rfold = collections.defaultdict(list) for w in self.rare: self.rfold[fold(w).replace("_", "")].append(w) self.by_fold = collections.defaultdict(list) for w in counts: self.by_fold[fold(w).replace("_", "")].append(w) for k in self.by_fold: self.by_fold[k].sort(key=lambda w: -counts[w])
def candidates(self, w): """-> [(word, kind)], nearest first: same letters apart from Turkish marks or the space, then one edit.""" key = fold(w).replace("_", "") near, far = [], [] m = COMMON.get(w) if m and m != w and m in self.counts: near.append((m, SPACE if "_" in m else EDIT)) for c in self.by_fold.get(key, []): if c != w: near.append((c, FOLD if ("_" in c) == ("_" in w) else SPACE)) if "_" in w: # ki tap / hiç bir j = w.replace("_", "") if j in self.counts and all(c != j for c, _ in near): near.append((j, SPACE)) if len(key) >= 3: for k in one_edits(key): for c in self.by_fold.get(k, [])[:2]: if c != w and ("_" in c) == ("_" in w): far.append((c, EDIT)) # devoiced clitic: kitapta <-> kitap da if "_" not in w and len(w) > 4 and w[-2:] in ("te", "ta"): c = w[:-2] + "_d" + w[-1] if c in self.counts: near.append((c, SPACE)) if w.endswith(("_te", "_ta")): # kitap ta: never right, meant kitapta or kitap da c = w[:-2] + "d" + w[-1] if c in self.counts: near.append((c, EDIT)) if w.endswith(("_de", "_da")) and w[:-3][-1:] in "fstkçşhp": c = w[:-3] + "t" + w[-1] if c in self.counts: near.append((c, SPACE)) far.sort(key=lambda x: -self.counts[x[0]]) if self.rare and w not in self.counts and w not in self.rare and len(near) < 3: # an unknown word may be a rare valid one extra = [(c, FOLD if ("_" in c) == ("_" in w) else SPACE) for c in self.rfold.get(key, []) if c != w] if len(key) >= 4 and not any(c == w for c, _ in extra): for k in one_edits(key): extra += [(c, EDIT) for c in self.rfold.get(k, [])[:1] if c != w and ("_" in c) == ("_" in w)] extra.sort(key=lambda x: (x[1] == EDIT, -self.rare[x[0]])) near = near[:5] + [x for x in extra if x[0] not in {c for c, _ in near}][:3] seen, out = set(), [] for c, k in near[:5] + far: if c not in seen: seen.add(c); out.append((c, k)) if len(out) == self.kmax: break return out
L, RW, KC = 12, 4, 9KN = ["same", "fold", "space", "edit"]
class WordSet: """Bloom filter over the expanded Turkish dictionary (valid_words.bin, MPL-2.0). About 1 in 2,000 unknown words is taken as known.""" def __init__(self, path): raw = np.fromfile(path, np.uint8); self.k, self.m = int(raw[0]), int.from_bytes(raw[1:9].tobytes(), "little"); self.bits = raw[9:] def __contains__(self, w): d = hashlib.blake2b(w.encode(), digest_size=16).digest(); a, b = int.from_bytes(d[:8], "little"), int.from_bytes(d[8:], "little") | 1 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: """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 ort folder = folder or os.path.dirname(os.path.abspath(__file__)); j = lambda n: os.path.join(folder, n) 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] 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 = {}, {}
def __call__(self, text): return self.fix([text])[0] if isinstance(text, str) else self.fix(list(text))
def pieces(self, w): if w not in self.pc: self.pc[w] = [0] * NG if w == "<pad>" else pieces(w) return self.pc[w]
def ctx(self, w): if w in self.sp or self.valid(w) or fold(w).replace("_", "") in self.lex.by_fold: return w return "<unk>"
def valid(self, w): if w in self.lex.counts or w in self.keep: return True 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 cands(self, w): if w not in self.cc: self.cc[w] = self.lex.candidates(w) return self.cc[w]
def score(self, docs, context=None): """docs: list of token lists. -> list of (doc, pos, typed, cand, kind, valid, gain) for every checkable word.""" context = context or docs; jobs = [] for d, tk in enumerate(docs): for i, w in enumerate(tk): if w in self.sp or len(w) < 2 or not WORD.match(w): continue c = self.cands(w) if c: jobs.append((d, i, w, c)) out = [] for s in range(0, len(jobs), 2048): b = jobs[s:s + 2048]; n = len(b) lp = np.zeros((n, L, NG), np.int64); rp = np.zeros((n, RW, NG), np.int64); cp = np.zeros((n, KC, NG), np.int64); f = np.zeros((n, KC, 7), np.float32) for j, (d, i, w, c) in enumerate(b): tk = context[d] for k, x in enumerate(reversed(tk[max(0, i - L):i])): lp[j, L - 1 - k] = self.pieces(self.ctx(x)) for k, x in enumerate((tk + ["</s>"])[i + 1:i + 1 + RW]): rp[j, RW - 1 - k] = self.pieces(self.ctx(x)) lf = lambda x: math.log1p(self.lex.counts.get(x, 0)) / self.top for k, (x, kd) in enumerate([(w, 0)] + c): cp[j, k] = self.pieces(x); f[j, k, kd] = 1; f[j, k, 4] = lf(x); f[j, k, 5] = lf(w); f[j, k, 6] = self.valid(w) sc = self.net.run(None, dict(left=lp, right=rp, cands=cp, feats=f))[0]; sc = np.where(cp[:, :, 0] == 0, -1e4, sc) best = sc[:, 1:].argmax(1) 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" 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): x, kd = c[best[j]]; out.append((d, i, w, x, kd, self.valid(w), float(sc[j, 1 + best[j]] - sc[j, 0]))) return out
def decide(self, r, cap=False): if COMMON.get(r[2]) == r[3]: return r[6] > 0 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)
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.""" hard, soft = set(), set(); words = [t for t, _, _ in tk]; wt = [i for i, t in enumerate(words) if WORD.match(t)] up_ = sum(1 for i in wt if text[tk[i][1]:tk[i][2]] == text[tk[i][1]:tk[i][2]].upper()) / max(len(wt), 1) for i in wt: a, b = tk[i][1], tk[i][2]; w = words[i]; raw = text[a:b]; prev, nxt = text[a - 1:a] if a else "", text[b:b + 1] if w.startswith(("hükümet", "euro")): hard.add(i) elif (prev in "/@_#" and prev) or (nxt in "/@_#" and nxt) or (prev == "." and text[a - 2:a - 1].isalnum()) or (nxt == "." and text[b + 1:b + 2].isalnum()): hard.add(i) elif prev and prev in QUOTES and text[a - 2:a - 1].isalnum(): hard.add(i) # "Kitap"ta, Ankara´da: a suffix after a quote mark elif 1 < len(raw) <= 6 and raw.isupper() and up_ < .6: hard.add(i) elif i and words[i - 1] == "<num>" and len(w) <= 4 and w not in self.lex.counts: hard.add(i) if not self.valid(w) and (len(w) <= 4 or re.search(r"(.)\1\1", w)): soft.add(i) if len(wt) >= 4 and sum(words[i] in self.foreign for i in wt) >= .4 * len(wt): hard |= set(wt) unk = collections.Counter(words[i][:5] for i in wt if len(words[i]) >= 5 and not self.valid(words[i])) for i in wt: if len(words[i]) >= 5 and not self.valid(words[i]) and unk[words[i][:5]] >= 3: soft.add(i) return hard, soft
def fix(self, texts, detail=False): prot = None tk = [tokenize(t) for t in texts]; docs = [[x for x, _, _ in t] for t in tk]; cur = [list(d) for d in docs]; prot = [self.protect(t, k) for t, k in zip(texts, tk)] for _ in range(2): res = self.score(docs, cur); cur = [list(d) for d in docs]; ch = [] for r in res: raw = texts[r[0]][tk[r[0]][r[1]][1]:tk[r[0]][r[1]][2]] if r[1] in prot[r[0]][0] or (r[4] == 3 and r[1] in prot[r[0]][1]): continue if self.decide(r, raw[0].isupper()): cur[r[0]][r[1]] = r[3]; ch.append(r) outs = [list(t) for t in texts]; res = {} for r in ch: res.setdefault(r[0], []).append(r) fin = [] for d, t in enumerate(texts): for r in sorted(res.get(d, []), key=lambda r: -r[1]): _, a, b = tk[d][r[1]]; raw = t[a:b]; n = r[3].replace("_", " ") if len(raw) > 2 and raw == up(raw) and raw != lower(raw): n = up(n) elif raw[0].isupper(): n = up(n[0]) + n[1:] t = t[:a] + n + t[b:] fin.append(t) return (fin, ch) if detail else fin
QUOTES = "'\"”“’‘´`»"def up(s): return s.replace("i", "İ").replace("ı", "I").upper()BADJ = {"_".join(v) for v in JOINED.values()}
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) for l in ([" ".join(a.text)] if a.text else sys.stdin): print(f(l.rstrip("\n")))
if __name__ == "__main__": main()12345678910111213141516171819"""Expand the hunspell-tr dictionary (MPL-2.0, github.com/tdd-ai/hunspell-tr) into one word per line.python tools/expand_hunspell.py HUNSPELL_FOLDER OUT.txt then python tools/make_words.py OUT.txt valid_words.bin"""import os, syssys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))from tinyfix_tr import lower, WORDH, suf = sys.argv[1], {}for l in open(os.path.join(H, "tr_TR.aff"), encoding="utf-8"): p = l.split() if len(p) >= 4 and p[0] == "SFX" and p[2] != "N": suf.setdefault(p[1], []).append((p[2], p[3].split("/")[0]))out = set()for i, l in enumerate(open(os.path.join(H, "tr_TR.dic"), encoding="utf-8")): if i == 0: continue w, _, f = l.strip().partition("/"); w = lower(w); out.add(w) for x in f.split(","): for st, ad in suf.get(x, []): b = w[:-len(st)] if st != "0" and w.endswith(st) else w out.add(b + (lower(ad) if ad != "0" else ""))out = sorted(w for w in out if WORD.match(w))open(sys.argv[2], "w", encoding="utf-8").write("\n".join(out)); print(len(out))12345678"""Build valid_words.bin from the expanded hunspell-tr word list (accept.py). python make_words.py ACCEPT.txt OUT"""import hashlib, sys, numpy as npW = [l.rstrip("\n") for l in open(sys.argv[1], encoding="utf-8")]; W = [w for w in W if w]m, k = 16 * len(W) // 8 * 8, 11; bits = np.zeros(m // 8, np.uint8)for w in W: d = hashlib.blake2b(w.encode(), digest_size=16).digest(); a, b = int.from_bytes(d[:8], "little"), int.from_bytes(d[8:], "little") | 1 for i in range(k): p = (a + i * b) % m; bits[p >> 3] |= 1 << (p & 7)open(sys.argv[2], "wb").write(bytes([k]) + m.to_bytes(8, "little") + bits.tobytes()); print(len(W), m // 8)123version https://git-lfs.github.com/spec/v1oid sha256:a580b99807dac1e4692a5f714688263060c72bad4b311b7bf5ce23a0838efb8asize 11501743LICENSEAdded+9
LICENSE-MPL-2.0.txtAdded+373
README.mdAdded+68
config.jsonAdded
lexicon.tsvAdded
model.onnxAdded+3
rare.tsvAdded
tinyfix_tr.pyAdded+301
tools/expand_hunspell.pyAdded+19
tools/make_words.pyAdded+8
valid_words.binAdded+3