wrongkeys 0.1.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
wrongkeys/layouts.py ADDED
@@ -0,0 +1,286 @@
1
+ """Keyboard layout tables.
2
+
3
+ Every layout is described against the 47 character keys of a US ANSI keyboard
4
+ (number row, three letter rows; the space bar is not listed because it is the
5
+ same everywhere). For each physical key a layout gives the text produced
6
+ without Shift and with Shift.
7
+
8
+ All tables were written from memory, not copied from a vendor file. They
9
+ describe the default *Windows / PC* layouts. Apple layouts differ and are not
10
+ covered. AltGr (third level), Caps Lock and ISO-only keys are not modelled.
11
+
12
+ Confidence is recorded per layout in ``Layout.confidence`` and the individual
13
+ keys the author is not sure about are listed in ``Layout.unsure``. Please
14
+ read those notes before relying on a shifted Arabic key or a Hebrew bracket.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from dataclasses import dataclass, field
20
+
21
+ # Physical keys, identified by what they produce on US QWERTY.
22
+ _ROW_LENGTHS = (13, 13, 11, 10)
23
+ US_UNSHIFTED = "`1234567890-=" "qwertyuiop[]\\" "asdfghjkl;'" "zxcvbnm,./"
24
+ US_SHIFTED = "~!@#$%^&*()_+" "QWERTYUIOP{}|" 'ASDFGHJKL:"' "ZXCVBNM<>?"
25
+ KEY_COUNT = len(US_UNSHIFTED)
26
+
27
+ # Placeholder used inside a row string for a key that produces more than one
28
+ # character; the real output is supplied through ``multi``.
29
+ _MULTI = "\u25a1"
30
+
31
+
32
+ @dataclass(frozen=True, eq=False)
33
+ class Layout:
34
+ """One keyboard layout.
35
+
36
+ ``unshifted[i]`` / ``shifted[i]`` are the strings produced by physical key
37
+ ``i`` (usually one character, two for the Arabic lam-alef keys).
38
+ ``compose`` maps a dead-key sequence, as raw key output, to the composed
39
+ character (Greek tonos + vowel).
40
+ """
41
+
42
+ code: str
43
+ name: str
44
+ unshifted: tuple[str, ...]
45
+ shifted: tuple[str, ...]
46
+ confidence: str
47
+ notes: str
48
+ unsure: tuple[tuple[str, str], ...] = ()
49
+ compose: dict[str, str] = field(default_factory=dict)
50
+ # Derived lookup tables.
51
+ char_to_key: dict[str, tuple[int, bool]] = field(default_factory=dict)
52
+ decompose: dict[str, str] = field(default_factory=dict)
53
+ max_output_len: int = 1
54
+
55
+ def output(self, key: int, shift: bool) -> str:
56
+ return (self.shifted if shift else self.unshifted)[key]
57
+
58
+ def typeable(self, ch: str) -> bool:
59
+ """True if ``ch`` (one character) can be produced by this table."""
60
+ if ch in self.char_to_key or ch in self.decompose:
61
+ return True
62
+ return any(ch in out for out in self.char_to_key if len(out) > 1)
63
+
64
+
65
+ def _expand(rows: tuple[str, ...], us: str, multi: dict[str, str], code: str) -> tuple[str, ...]:
66
+ if tuple(len(r) for r in rows) != _ROW_LENGTHS:
67
+ raise ValueError(f"layout {code}: row lengths {[len(r) for r in rows]} != {_ROW_LENGTHS}")
68
+ out = []
69
+ for us_char, ch in zip(us, "".join(rows)):
70
+ if ch == _MULTI:
71
+ if us_char not in multi:
72
+ raise ValueError(f"layout {code}: no multi-character output given for key {us_char!r}")
73
+ out.append(multi[us_char])
74
+ else:
75
+ out.append(ch)
76
+ return tuple(out)
77
+
78
+
79
+ def _make(
80
+ code: str,
81
+ name: str,
82
+ unshifted: tuple[str, ...],
83
+ shifted: tuple[str, ...],
84
+ *,
85
+ confidence: str,
86
+ notes: str,
87
+ unsure: tuple[tuple[str, str], ...] = (),
88
+ multi: dict[str, str] | None = None,
89
+ compose: dict[str, str] | None = None,
90
+ ) -> Layout:
91
+ multi = multi or {}
92
+ compose = dict(compose or {})
93
+ un = _expand(unshifted, US_UNSHIFTED, multi, code)
94
+ sh = _expand(shifted, US_SHIFTED, multi, code)
95
+ char_to_key: dict[str, tuple[int, bool]] = {}
96
+ for shift, layer in ((False, un), (True, sh)):
97
+ for index, out in enumerate(layer):
98
+ if out in char_to_key:
99
+ raise ValueError(f"layout {code}: output {out!r} appears on two keys")
100
+ char_to_key[out] = (index, shift)
101
+ decompose = {}
102
+ for raw, composed in compose.items():
103
+ if composed in char_to_key or composed in decompose:
104
+ raise ValueError(f"layout {code}: composed {composed!r} is ambiguous")
105
+ if any(ch not in char_to_key for ch in raw):
106
+ raise ValueError(f"layout {code}: dead-key sequence {raw!r} is not typeable")
107
+ decompose[composed] = raw
108
+ return Layout(
109
+ code=code,
110
+ name=name,
111
+ unshifted=un,
112
+ shifted=sh,
113
+ confidence=confidence,
114
+ notes=notes,
115
+ unsure=unsure,
116
+ compose=compose,
117
+ char_to_key=char_to_key,
118
+ decompose=decompose,
119
+ max_output_len=max(len(o) for o in char_to_key),
120
+ )
121
+
122
+
123
+ # --------------------------------------------------------------------------
124
+ # English, US QWERTY. Confidence: sure.
125
+ # --------------------------------------------------------------------------
126
+ EN = _make(
127
+ "en",
128
+ "English (US QWERTY)",
129
+ ("`1234567890-=", "qwertyuiop[]\\", "asdfghjkl;'", "zxcvbnm,./"),
130
+ ("~!@#$%^&*()_+", "QWERTYUIOP{}|", 'ASDFGHJKL:"', "ZXCVBNM<>?"),
131
+ confidence="sure",
132
+ notes="US ANSI QWERTY. UK and other English layouts move a few symbols and are not covered.",
133
+ )
134
+
135
+ # --------------------------------------------------------------------------
136
+ # Russian, ЙЦУКЕН (Windows). Confidence: sure for letters and for the
137
+ # shifted number row; this is the layout printed on essentially every PC
138
+ # keyboard sold with Russian legends.
139
+ # --------------------------------------------------------------------------
140
+ RU = _make(
141
+ "ru",
142
+ "Russian (ЙЦУКЕН, Windows)",
143
+ ("ё1234567890-=", "йцукенгшщзхъ\\", "фывапролджэ", "ячсмитьбю."),
144
+ ("Ё!\"№;%:?*()_+", "ЙЦУКЕНГШЩЗХЪ/", "ФЫВАПРОЛДЖЭ", "ЯЧСМИТЬБЮ,"),
145
+ confidence="sure",
146
+ notes="Standard Windows Russian layout. The 'Russian (Typewriter)' variant is not covered.",
147
+ )
148
+
149
+ # --------------------------------------------------------------------------
150
+ # Ukrainian (Windows). Letters: sure. The key left of 1 and the letter ґ:
151
+ # not sure, see ``unsure``.
152
+ # --------------------------------------------------------------------------
153
+ UK = _make(
154
+ "uk",
155
+ "Ukrainian (Windows, Enhanced)",
156
+ ("'1234567890-=", "йцукенгшщзхї\\", "фівапролджє", "ячсмитьбю."),
157
+ ("₴!\"№;%:?*()_+", "ЙЦУКЕНГШЩЗХЇ/", "ФІВАПРОЛДЖЄ", "ЯЧСМИТЬБЮ,"),
158
+ confidence="letters sure; two keys unsure",
159
+ notes=(
160
+ "Letter keys follow the Windows 'Ukrainian (Enhanced)' layout. "
161
+ "The letter ґ is typed with AltGr+г or on the extra ISO key, neither of which is modelled, "
162
+ "so ґ/Ґ pass through convert() unchanged."
163
+ ),
164
+ unsure=(
165
+ ("` ~", "Assumed apostrophe (') unshifted and hryvnia sign (₴) shifted, as in the Enhanced layout. "
166
+ "The older 'Ukrainian' layout may produce different characters on this key."),
167
+ ("ґ", "Not on any modelled key (AltGr / ISO key only). Text containing ґ will not round-trip."),
168
+ ("\\ |", "Assumed backslash and slash as in Russian. Some layouts put ґ here."),
169
+ ),
170
+ )
171
+
172
+ # --------------------------------------------------------------------------
173
+ # Greek (Windows). Letters: sure. Dead keys and Shift+W: fairly sure.
174
+ # The ';' key is the tonos dead key: it is pressed BEFORE the vowel, so
175
+ # 'kalhm;era' is what you get on a US layout when you meant 'καλημέρα'.
176
+ # --------------------------------------------------------------------------
177
+ _TONOS = "\u0384" # ΄ produced by the dead key on its own
178
+ _DIALYTIKA = "\u00a8" # ¨
179
+ _DIALYTIKA_TONOS = "\u0385" # ΅
180
+
181
+ _GREEK_COMPOSE = {}
182
+ for _base, _acc in zip("αεηιουωΑΕΗΙΟΥΩ", "άέήίόύώΆΈΉΊΌΎΏ"):
183
+ _GREEK_COMPOSE[_TONOS + _base] = _acc
184
+ for _base, _acc in zip("ιυΙΥ", "ϊϋΪΫ"):
185
+ _GREEK_COMPOSE[_DIALYTIKA + _base] = _acc
186
+ for _base, _acc in zip("ιυ", "ΐΰ"):
187
+ _GREEK_COMPOSE[_DIALYTIKA_TONOS + _base] = _acc
188
+
189
+ EL = _make(
190
+ "el",
191
+ "Greek (Windows)",
192
+ ("`1234567890-=", ";ςερτυθιοπ[]\\", "ασδφγηξκλ" + _TONOS + "'", "ζχψωβνμ,./"),
193
+ ("~!@#$%^&*()_+", ":" + _DIALYTIKA_TONOS + "ΕΡΤΥΘΙΟΠ{}|", "ΑΣΔΦΓΗΞΚΛ" + _DIALYTIKA + '"', "ΖΧΨΩΒΝΜ<>?"),
194
+ confidence="letters sure; dead keys fairly sure",
195
+ notes=(
196
+ "Final sigma (ς) is its own key (W); sigma (σ) is on S. convert() never turns σ into ς or back: "
197
+ "it reproduces exactly what the keys would have typed. "
198
+ "Accented vowels are typed with a dead key first (';' then the vowel) and are composed/decomposed."
199
+ ),
200
+ unsure=(
201
+ ("; :", "Tonos dead key unshifted (sure). Shifted assumed to be the dialytika dead key."),
202
+ ("W", "Shift+W assumed to be the dialytika-tonos dead key (΅). Some layouts may differ."),
203
+ ("standalone dead key", "A dead key not followed by a vowel is represented as the spacing "
204
+ "characters U+0384 / U+00A8 / U+0385; Windows may emit slightly different ones."),
205
+ ("AltGr", "Euro sign and other AltGr characters are not modelled."),
206
+ ),
207
+ compose=_GREEK_COMPOSE,
208
+ )
209
+
210
+ # --------------------------------------------------------------------------
211
+ # Hebrew (Windows 'Hebrew', based on SI-1452). Letters: sure.
212
+ # Punctuation that moves (q w ' / ` and the mirrored brackets): fairly sure.
213
+ # Hebrew has no capital letters; Shift+letter gives the Latin capital.
214
+ # --------------------------------------------------------------------------
215
+ HE = _make(
216
+ "he",
217
+ "Hebrew (Windows, SI-1452)",
218
+ (";1234567890-=", "/'קראטוןםפ][\\", "שדגכעיחלךף,", "זסבהנמצתץ."),
219
+ ("~!@#$%^&*)(_+", "QWERTYUIOP}{|", 'ASDFGHJKL:"', "ZXCVBNM><?"),
220
+ confidence="letters sure; punctuation fairly sure",
221
+ notes=(
222
+ "Shift+letter produces the Latin capital letter (with Caps Lock off). "
223
+ "Niqqud (vowel points), the sheqel sign and other AltGr / Caps Lock+Shift characters are not modelled. "
224
+ "The newer 'Hebrew (Standard)' SI-1452-2 layout moves some punctuation and is not covered."
225
+ ),
226
+ unsure=(
227
+ ("( ) [ ] { } < >", "Assumed mirrored: the key that types '(' on a US layout produces ')' "
228
+ "and so on for each bracket pair, so that the glyph printed on the key "
229
+ "matches what is seen in right-to-left text."),
230
+ ("` ~", "Assumed ';' unshifted and '~' shifted."),
231
+ ("q w ' /", "Assumed '/', apostrophe, ',' and '.' respectively (unshifted)."),
232
+ ),
233
+ )
234
+
235
+ # --------------------------------------------------------------------------
236
+ # Arabic (101), the standard Windows / PC layout.
237
+ # Unshifted layer: sure (this is what is printed on the keys and it is used
238
+ # for almost all Arabic typing). Shifted layer: written from memory and only
239
+ # moderately certain; see ``unsure``.
240
+ # Four keys produce TWO characters (lam followed by a form of alef).
241
+ # --------------------------------------------------------------------------
242
+ _FATHA, _FATHATAN, _DAMMA, _DAMMATAN = "\u064e", "\u064b", "\u064f", "\u064c"
243
+ _KASRA, _KASRATAN, _SUKUN, _SHADDA, _TATWEEL = "\u0650", "\u064d", "\u0652", "\u0651", "\u0640"
244
+
245
+ AR = _make(
246
+ "ar",
247
+ "Arabic (101, Windows)",
248
+ ("ذ1234567890-=", "ضصثقفغعهخحجد\\", "شسيبلاتنمكط", "ئءؤر" + _MULTI + "ىةوزظ"),
249
+ (
250
+ _SHADDA + "!@#$%^&*)(_+",
251
+ _FATHA + _FATHATAN + _DAMMA + _DAMMATAN + _MULTI + "إ‘÷×؛<>|",
252
+ _KASRA + _KASRATAN + "][" + _MULTI + "أ" + _TATWEEL + "،/:\"",
253
+ "~" + _SUKUN + "}{" + _MULTI + "آ’,.؟",
254
+ ),
255
+ confidence="unshifted sure; shifted layer moderately sure",
256
+ notes=(
257
+ "Digits are the ASCII digits; whether they display as Arabic-Indic digits is a system setting. "
258
+ "The B key types two characters, lam + alef (لا); Shift+T, Shift+G and Shift+B type lam + إ / أ / آ. "
259
+ "Converting Arabic back to key presses is therefore ambiguous: لا may have been typed as B "
260
+ "or as G then H. convert() always assumes the single key; detect() and fix() try both."
261
+ ),
262
+ unsure=(
263
+ ("Shift+Q W E R A S X `", "Diacritics: fatha, fathatan, damma, dammatan, kasra, kasratan, sukun, shadda. "
264
+ "The set is right; the exact key of each is from memory."),
265
+ ("Shift+D F C V", "Assumed ] [ } { in that order."),
266
+ ("Shift+[ ]", "Assumed < and >."),
267
+ ("Shift+U M", "Assumed the curly quotes ‘ and ’."),
268
+ ("Shift+I O", "Assumed ÷ and ×."),
269
+ ("Shift+9 0", "Assumed mirrored: ) then (."),
270
+ ("Shift+Z", "Assumed '~'."),
271
+ ("Shift+L : \"", "Assumed '/', ':' and '\"'."),
272
+ ("Shift+, . ", "Assumed ',' and '.'."),
273
+ ),
274
+ multi={"b": "لا", "T": "لإ", "G": "لأ", "B": "لآ"},
275
+ )
276
+
277
+ LAYOUTS: dict[str, Layout] = {lay.code: lay for lay in (EN, AR, HE, RU, UK, EL)}
278
+
279
+
280
+ def get_layout(code: str) -> Layout:
281
+ """Return the layout for a code such as ``"en"`` or ``"ar"``."""
282
+ try:
283
+ return LAYOUTS[code.lower()]
284
+ except (KeyError, AttributeError):
285
+ known = ", ".join(sorted(LAYOUTS))
286
+ raise ValueError(f"unknown layout {code!r}; known layouts: {known}") from None
wrongkeys/models.py ADDED
@@ -0,0 +1,277 @@
1
+ """Small built-in language models used to judge how plausible a piece of text is.
2
+
3
+ For each language there is
4
+
5
+ * a word list (a few hundred common words, names and the words of about
6
+ forty sample sentences, all written by hand for this project), and
7
+ * a character trigram model with Witten-Bell backoff trained on that same
8
+ material.
9
+
10
+ ``analyze(lang, text)`` returns a score in nats: the log-likelihood of the
11
+ letters under the trigram model minus their log-likelihood under a uniform
12
+ distribution over the alphabet, plus a bonus for dictionary words and
13
+ penalties for characters that do not belong. Positive means "looks like this
14
+ language", negative means "looks like noise". The models are tiny, so the
15
+ score is a rough signal, not a probability.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import math
21
+ from collections import Counter, defaultdict
22
+ from dataclasses import dataclass
23
+ from functools import lru_cache
24
+
25
+ from .data import ar as _ar
26
+ from .data import el as _el
27
+ from .data import en as _en
28
+ from .data import he as _he
29
+ from .data import ru as _ru
30
+ from .data import uk as _uk
31
+
32
+ # Score penalties (nats).
33
+ FOREIGN_PENALTY = 2.5 # a character that is neither a letter of the language nor ordinary punctuation
34
+ INTERNAL_PENALTY = 2.5 # ; : , ! ? glued between two letters, e.g. "ugd;l", or glued in front of a word
35
+ SYMBOL_PENALTY = 0.75 # an ASCII symbol such as ^ * [ ] { } < > | ~ # $ & @ + = /
36
+ DICT_BONUS_BASE = 1.0
37
+ DICT_BONUS_PER_CHAR = 1.0
38
+ DICT_BONUS_MAX = 6.0
39
+ PARTIAL_HIT_FACTOR = 0.5 # word recognised only after stripping a prefix/suffix
40
+
41
+ _NEUTRAL = set(" \t\r\n.,!?;:'\"()-\u2013\u2014\u2026\u00ab\u00bb\u201c\u201d\u201e\u2018\u2019"
42
+ "\u060c\u061b\u061f\u05be\u05f3\u05f4\u00b7\u037e0123456789%")
43
+ _INTERNAL = set(";:,!?\u060c\u061b\u061f")
44
+ _APOSTROPHES = "\u2019\u02bc\u2018"
45
+
46
+ _AR_MARKS = set("\u064b\u064c\u064d\u064e\u064f\u0650\u0651\u0652")
47
+ _TATWEEL = "\u0640"
48
+ _BAD = "\x00" # stands for a misplaced mark; always penalised
49
+
50
+ _GREEK_FOLD = str.maketrans("άέήίόύώϊϋΐΰ", "αεηιουωιυιυ")
51
+ _AR_FOLD = str.maketrans("أإآٱ", "اااا")
52
+
53
+
54
+ def _norm_en(text: str) -> str:
55
+ return text.lower().replace("’", "'")
56
+
57
+
58
+ def _norm_ru(text: str) -> str:
59
+ return text.lower().replace("ё", "е")
60
+
61
+
62
+ def _norm_uk(text: str) -> str:
63
+ text = text.lower()
64
+ for ch in _APOSTROPHES:
65
+ text = text.replace(ch, "'")
66
+ return text
67
+
68
+
69
+ def _norm_el(text: str) -> str:
70
+ return text.lower().translate(_GREEK_FOLD)
71
+
72
+
73
+ def _norm_he(text: str) -> str:
74
+ return text
75
+
76
+
77
+ def _norm_ar(text: str) -> str:
78
+ """Fold alef forms and drop diacritics that sit where a diacritic can sit."""
79
+ text = text.translate(_AR_FOLD)
80
+ if not (_AR_MARKS & set(text)) and _TATWEEL not in text:
81
+ return text
82
+ letters = set(_ar.ALPHABET)
83
+ out: list[str] = []
84
+ run = 0 # consecutive marks
85
+ prev_letter = False
86
+ for ch in text:
87
+ if ch in _AR_MARKS:
88
+ run += 1
89
+ if not prev_letter or run > 2:
90
+ out.append(_BAD)
91
+ continue
92
+ if ch == _TATWEEL:
93
+ if not prev_letter:
94
+ out.append(_BAD)
95
+ continue
96
+ run = 0
97
+ prev_letter = ch in letters
98
+ out.append(ch)
99
+ return "".join(out)
100
+
101
+
102
+ class CharModel:
103
+ """Character trigram model with Witten-Bell interpolated backoff."""
104
+
105
+ def __init__(self, alphabet: str, words: list[str]):
106
+ self.size = len(alphabet) + 1 # letters plus end-of-word
107
+ self.uni: Counter = Counter()
108
+ self.bi: dict[str, Counter] = defaultdict(Counter)
109
+ self.tri: dict[str, Counter] = defaultdict(Counter)
110
+ for word in words:
111
+ padded = "^^" + word + "$"
112
+ for i in range(2, len(padded)):
113
+ ch = padded[i]
114
+ self.uni[ch] += 1
115
+ self.bi[padded[i - 1]][ch] += 1
116
+ self.tri[padded[i - 2:i]][ch] += 1
117
+ self.total = sum(self.uni.values())
118
+ self.bi_totals = {ctx: sum(c.values()) for ctx, c in self.bi.items()}
119
+ self.tri_totals = {ctx: sum(c.values()) for ctx, c in self.tri.items()}
120
+
121
+ def prob(self, a: str, b: str, c: str) -> float:
122
+ p = 1.0 / self.size
123
+ types = len(self.uni)
124
+ p = (self.uni.get(c, 0) + types * p) / (self.total + types)
125
+ ctx = self.bi.get(b)
126
+ if ctx:
127
+ p = (ctx.get(c, 0) + len(ctx) * p) / (self.bi_totals[b] + len(ctx))
128
+ ctx = self.tri.get(a + b)
129
+ if ctx:
130
+ p = (ctx.get(c, 0) + len(ctx) * p) / (self.tri_totals[a + b] + len(ctx))
131
+ return p
132
+
133
+ def llr(self, word: str) -> float:
134
+ """Log-likelihood ratio of ``word`` against uniform letters, in nats."""
135
+ padded = "^^" + word + "$"
136
+ log_size = math.log(self.size)
137
+ total = 0.0
138
+ for i in range(2, len(padded)):
139
+ total += math.log(self.prob(padded[i - 2], padded[i - 1], padded[i])) + log_size
140
+ return total
141
+
142
+
143
+ @dataclass(frozen=True)
144
+ class Analysis:
145
+ score: float # plausibility in nats (see module docstring)
146
+ letters: int # letters of the language found in the text
147
+ words: int # letter runs
148
+ dict_words: int # letter runs recognised by the word list (fully or after affix stripping)
149
+
150
+
151
+ _AR_PREFIXES = ("وال", "بال", "كال", "فال", "لل", "ال", "و", "ف", "ب", "ل", "ك", "س")
152
+ _AR_SUFFIXES = ("هما", "كما", "ها", "هم", "هن", "كم", "نا", "ون", "ين", "ات", "ان", "وا", "ة", "ه", "ك", "ي", "ا", "ت")
153
+ _HE_PREFIXES = ("וה", "שה", "כש", "מה", "וב", "ול", "ה", "ו", "ב", "ל", "מ", "ש", "כ")
154
+ _HE_SUFFIXES = ("ים", "ות", "ה", "י", "ת")
155
+ _EN_SUFFIXES = ("'s", "ing", "ed", "es", "ly", "er", "s", "d")
156
+
157
+
158
+ class Language:
159
+ def __init__(self, code: str, data, normalize, prefixes=(), suffixes=(), apostrophe=False):
160
+ self.code = code
161
+ self.normalize = normalize
162
+ self.alphabet = data.ALPHABET
163
+ self.letters = frozenset(data.ALPHABET)
164
+ self.apostrophe = apostrophe
165
+ self.prefixes = prefixes
166
+ self.suffixes = suffixes
167
+ tokens: list[str] = []
168
+ for source in (data.WORDS, getattr(data, "MORE_WORDS", ""), data.NAMES, data.SENTENCES):
169
+ tokens.extend(self._runs(normalize(source)))
170
+ self.words = frozenset(tokens)
171
+ self.model = CharModel(self.alphabet, tokens)
172
+
173
+ def _is_letter(self, text: str, i: int) -> bool:
174
+ ch = text[i]
175
+ if ch not in self.letters:
176
+ return False
177
+ if ch == "'":
178
+ return 0 < i < len(text) - 1 and text[i - 1] in self.letters and text[i - 1] != "'" \
179
+ and text[i + 1] in self.letters and text[i + 1] != "'"
180
+ return True
181
+
182
+ def _runs(self, text: str) -> list[str]:
183
+ runs, start = [], None
184
+ for i in range(len(text)):
185
+ if self._is_letter(text, i):
186
+ if start is None:
187
+ start = i
188
+ elif start is not None:
189
+ runs.append(text[start:i])
190
+ start = None
191
+ if start is not None:
192
+ runs.append(text[start:])
193
+ return runs
194
+
195
+ def known(self, word: str) -> float:
196
+ """1.0 for a listed word, 0.5 for a listed word plus one common affix, else 0."""
197
+ if word in self.words:
198
+ return 1.0
199
+ for prefix in self.prefixes:
200
+ if word.startswith(prefix) and len(word) - len(prefix) >= 3 and word[len(prefix):] in self.words:
201
+ return PARTIAL_HIT_FACTOR
202
+ for suffix in self.suffixes:
203
+ if word.endswith(suffix) and len(word) - len(suffix) >= 3 and word[:-len(suffix)] in self.words:
204
+ return PARTIAL_HIT_FACTOR
205
+ return 0.0
206
+
207
+ @lru_cache(maxsize=50000)
208
+ def word_score(self, word: str) -> tuple[float, bool]:
209
+ score = self.model.llr(word)
210
+ hit = self.known(word)
211
+ if hit:
212
+ score += hit * min(DICT_BONUS_MAX, DICT_BONUS_BASE + DICT_BONUS_PER_CHAR * len(word))
213
+ return score, bool(hit)
214
+
215
+ def analyze(self, text: str) -> Analysis:
216
+ text = self.normalize(text)
217
+ score = 0.0
218
+ letters = words = dict_words = 0
219
+ n = len(text)
220
+ i = 0
221
+ while i < n:
222
+ if self._is_letter(text, i) or text[i].isalpha():
223
+ # A run of letters. If it contains letters of another script
224
+ # (Latin capitals inside Hebrew, a Ukrainian letter inside
225
+ # Russian) it is not a word of this language at all.
226
+ j = i
227
+ foreign = 0
228
+ while j < n and (self._is_letter(text, j) or text[j].isalpha()):
229
+ foreign += not self._is_letter(text, j)
230
+ j += 1
231
+ words += 1
232
+ if foreign:
233
+ score -= FOREIGN_PENALTY * foreign
234
+ letters += (j - i) - foreign
235
+ else:
236
+ word_score, hit = self.word_score(text[i:j])
237
+ score += word_score
238
+ letters += j - i
239
+ dict_words += hit
240
+ i = j
241
+ continue
242
+ ch = text[i]
243
+ if ch in _NEUTRAL or ch.isspace():
244
+ # Sentence punctuation is followed by a space in ordinary text.
245
+ if ch in _INTERNAL and i < n - 1 and text[i + 1] in self.letters:
246
+ score -= INTERNAL_PENALTY
247
+ elif ch.isascii():
248
+ score -= SYMBOL_PENALTY
249
+ else:
250
+ score -= FOREIGN_PENALTY
251
+ i += 1
252
+ return Analysis(score, letters, words, dict_words)
253
+
254
+
255
+ @lru_cache(maxsize=None)
256
+ def get_language(code: str) -> Language:
257
+ if code == "en":
258
+ return Language("en", _en, _norm_en, suffixes=_EN_SUFFIXES, apostrophe=True)
259
+ if code == "ru":
260
+ return Language("ru", _ru, _norm_ru)
261
+ if code == "uk":
262
+ return Language("uk", _uk, _norm_uk, apostrophe=True)
263
+ if code == "el":
264
+ return Language("el", _el, _norm_el)
265
+ if code == "he":
266
+ return Language("he", _he, _norm_he, prefixes=_HE_PREFIXES, suffixes=_HE_SUFFIXES)
267
+ if code == "ar":
268
+ return Language("ar", _ar, _norm_ar, prefixes=_AR_PREFIXES, suffixes=_AR_SUFFIXES)
269
+ raise ValueError(f"no language model for {code!r}")
270
+
271
+
272
+ LANGUAGE_CODES = ("en", "ar", "he", "ru", "uk", "el")
273
+
274
+
275
+ def analyze(lang: str, text: str) -> Analysis:
276
+ """Plausibility of ``text`` as language ``lang``."""
277
+ return get_language(lang).analyze(text)