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/engine.py ADDED
@@ -0,0 +1,450 @@
1
+ """Detection and repair of text typed with the wrong keyboard layout.
2
+
3
+ The idea: a piece of text is "mistyped" when it is implausible as written
4
+ and becomes plausible after remapping its keys to another layout. Both
5
+ plausibilities come from the small models in ``models.py``.
6
+
7
+ Two entry points share the same per-token evidence:
8
+
9
+ * ``detect(text)`` judges the text as a whole (one layout mistake or none).
10
+ * ``fix(text)`` runs a Viterbi pass over the tokens, so a sentence can be
11
+ partly left alone and partly remapped.
12
+
13
+ All thresholds below were tuned by hand on the development set in
14
+ ``bench/dataset.py``. They are not derived from real-world data.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import math
20
+ import re
21
+ from dataclasses import asdict, dataclass
22
+ from functools import lru_cache
23
+
24
+ from .convert import conversions
25
+ from .layouts import LAYOUTS
26
+ from .models import LANGUAGE_CODES, Analysis, get_language
27
+
28
+ # (typed layout, intended layout). Only pairs that involve English.
29
+ PAIRS: tuple[tuple[str, str], ...] = tuple(
30
+ [("en", code) for code in LANGUAGE_CODES if code != "en"]
31
+ + [(code, "en") for code in LANGUAGE_CODES if code != "en"]
32
+ )
33
+
34
+ # --- tunable constants (nats unless noted) ---------------------------------
35
+ SEGMENT_PENALTY = 6.0 # evidence needed before any run of tokens is remapped
36
+ EDGE_PENALTY = 4.0 # extra evidence needed for a run to start or stop in the middle of a line
37
+ MIN_LETTERS = 4 # a remapped run needs this many letters in words of three or more letters
38
+ SHORT_LETTERS = 6 # runs shorter than this need a dictionary word in the result
39
+ MIN_AVG = 0.0 # the result must score at least this much per letter ...
40
+ MIN_AVG_DICT = -0.3 # ... or this much if it contains at least one listed word
41
+ NO_DICT_EXTRA = 5.0 # extra evidence required when the result contains no listed word
42
+ SINGLE_KEY_PRIOR = 2.0 # Arabic lam-alef: prefer "one key" over "two keys" unless the score disagrees
43
+ CONFIDENCE_SCALE = 10.0 # margin (nats) -> confidence = 1 - exp(-margin / scale)
44
+ # Extra evidence required for specific pairs. The Greek layout is nearly
45
+ # phonetic, so Latin words turn into Greek-looking strings (and back) easily.
46
+ PAIR_PENALTY: dict[tuple[str, str], float] = {("en", "el"): 6.0, ("el", "en"): 3.0}
47
+
48
+ _KEEP = ("", "")
49
+
50
+ _TLDS = (
51
+ "com org net edu gov io dev app ai co me info biz tv uk us de fr es it nl pl ru ua il gr sa eg ae jo lb "
52
+ "cn jp in br ca au ch se no fi eu xyz site online tech"
53
+ ).split()
54
+ _EXTENSIONS = (
55
+ "py js ts jsx tsx html htm css json xml yml yaml toml ini cfg md txt csv pdf doc docx xls xlsx ppt pptx "
56
+ "png jpg jpeg gif svg mp3 mp4 zip tar gz exe dll sh bat ps1 cpp hpp cs java rb go rs php sql log"
57
+ ).split()
58
+ _URL_RE = re.compile(r"^(?:[a-z][a-z0-9+.\-]*://\S+|www\.\S+)$", re.IGNORECASE)
59
+ _DOMAIN_RE = re.compile(
60
+ r"^[a-z0-9_\-]{2,}(?:\.[a-z0-9_\-]+)*\.(?:%s)(?:[/:?#]\S*)?$" % "|".join(_TLDS + _EXTENSIONS), re.IGNORECASE
61
+ )
62
+ _EMAIL_RE = re.compile(r"^[\w.+\-]+@[\w\-]+(?:\.[\w\-]+)+$", re.ASCII)
63
+ # Internationalised top-level domains (in their native script) for the
64
+ # scripts the package handles, plus a few common ones elsewhere. A
65
+ # non-ASCII token counts as a domain only if it ends in one of these or in
66
+ # an ASCII TLD from ``_TLDS``; file extensions do not count for such tokens.
67
+ _IDN_TLDS = (
68
+ # Cyrillic
69
+ "рф рус москва онлайн сайт орг ком дети укр срб бел бг мкд мон қаз ею "
70
+ # Greek
71
+ "ελ ευ "
72
+ # Hebrew
73
+ "ישראל קום "
74
+ # Arabic script
75
+ "السعودية امارات مصر الاردن فلسطين المغرب الجزائر تونس قطر عمان البحرين سورية "
76
+ "عراق السودان ليبيا يمن موريتانيا بھارت ایران پاکستان كوم شبكة موقع "
77
+ # CJK and others
78
+ "中国 中國 香港 台湾 台灣 新加坡 公司 网络 在线 한국 みんな コム ไทย"
79
+ ).split()
80
+ _LABEL = r"[^\W_](?:[^\W_]|-)*" # letters and digits of any script, inner hyphens
81
+ _IDN_DOMAIN_RE = re.compile(
82
+ r"^[^\W_](?:[^\W_]|-)+(?:\.%s)*\.(?:%s)(?:[/:?#]\S*)?$" % (_LABEL, "|".join(map(re.escape, _IDN_TLDS + _TLDS))),
83
+ re.IGNORECASE,
84
+ )
85
+ _IDN_EMAIL_RE = re.compile(r"^[\w.+\-]+@(\S+)$")
86
+ _HANDLE_RE = re.compile(r"^[@#][A-Za-z0-9_]+$")
87
+ _CODE_RE = re.compile(
88
+ r"_|=|\\|\(\)|\{\}|->|::|\|\||</|/>|[A-Za-z0-9]\(|^--?[A-Za-z]|^[A-Za-z]:[\\/]|^~/|^\.{1,2}/|/[\w.\-]+/"
89
+ )
90
+ _TRAILING = ".,;:!?)]}\"'"
91
+ _LEADING = "([{\"'"
92
+ # Inline code: `...` or a fenced block. The opening backtick must start a
93
+ # word and the closing one must end a word, because on several layouts the
94
+ # backtick key is a letter (Russian ё, Arabic ذ).
95
+ _SPAN_RE = re.compile(r"(```.*?```|(?<![^\s(\[{\"'])`[^`\n]+`(?![^\s.,;:!?)\]}\"']))", re.DOTALL)
96
+ _SPACE_RE = re.compile(r"(\s+)")
97
+
98
+
99
+ @dataclass(frozen=True)
100
+ class Guess:
101
+ """Result of :func:`detect`.
102
+
103
+ ``mistyped`` True if the whole text looks typed on the wrong layout.
104
+ ``language`` intended language code if mistyped; otherwise the language
105
+ the text appears to be in as written (None if unknown).
106
+ ``typed_layout`` layout that was active while typing (None if not mistyped).
107
+ ``repaired`` the remapped text if mistyped, otherwise the input unchanged.
108
+ ``confidence`` 0..1, a monotone function of the score margin between the
109
+ best and second-best hypothesis. Not a calibrated probability.
110
+ ``runner_up`` second-best hypothesis: "keep" or a pair such as "en->ru".
111
+ """
112
+
113
+ mistyped: bool
114
+ language: str | None
115
+ typed_layout: str | None
116
+ repaired: str
117
+ confidence: float
118
+ runner_up: str | None
119
+
120
+ def to_dict(self) -> dict:
121
+ return asdict(self)
122
+
123
+
124
+ @dataclass
125
+ class _Token:
126
+ text: str
127
+ kind: str # "space", "protected" or "word"
128
+ keep: float = 0.0 # plausibility as written
129
+ keep_lang: str | None = None
130
+ options: dict | None = None # pair -> (repaired text, Analysis)
131
+
132
+
133
+ def is_protected(token: str) -> bool:
134
+ """True for tokens that are never remapped: URLs, e-mail addresses,
135
+ @handles and #tags, anything containing a digit, and things that look
136
+ like code.
137
+
138
+ Tokens with non-ASCII characters are protected only when they look like
139
+ a web address: a URL with a scheme, a ``www.`` address, a domain such as
140
+ ``яндекс.рф`` whose last label is a known top-level domain (in any
141
+ script, see ``_IDN_TLDS``, or ASCII), or an e-mail address at such a
142
+ domain. Mistyped text that merely contains a period (``ю`` on the
143
+ Russian layout is the ``.`` key) is not protected."""
144
+ core = token.rstrip(_TRAILING).lstrip(_LEADING) or token
145
+ if not token.isascii():
146
+ return bool(_URL_RE.match(core) or _is_idn_domain(core))
147
+ has_alpha = any(ch.isalpha() for ch in token)
148
+ has_digit = any(ch.isdigit() for ch in token)
149
+ if has_digit:
150
+ return True # plain numbers, dates, and mixed tokens such as "mp3" or "v2"
151
+ if not has_alpha:
152
+ return False
153
+ if _URL_RE.match(core) or _DOMAIN_RE.match(core) or _EMAIL_RE.match(core):
154
+ return True
155
+ if _HANDLE_RE.match(core):
156
+ return True
157
+ return bool(_CODE_RE.search(token))
158
+
159
+
160
+ def _is_idn_domain(core: str) -> bool:
161
+ """Domain (optionally with a path) or e-mail address with a known TLD."""
162
+ if _IDN_DOMAIN_RE.match(core):
163
+ return True
164
+ email = _IDN_EMAIL_RE.match(core)
165
+ return bool(email and "/" not in email.group(1) and _IDN_DOMAIN_RE.match(email.group(1)))
166
+
167
+
168
+ def _split(text: str) -> list[_Token]:
169
+ tokens: list[_Token] = []
170
+ for i, part in enumerate(_SPAN_RE.split(text)):
171
+ if not part:
172
+ continue
173
+ if i % 2 == 1:
174
+ tokens.append(_Token(part, "protected"))
175
+ continue
176
+ for j, piece in enumerate(_SPACE_RE.split(part)):
177
+ if not piece:
178
+ continue
179
+ if j % 2 == 1:
180
+ tokens.append(_Token(piece, "space"))
181
+ elif is_protected(piece):
182
+ tokens.append(_Token(piece, "protected"))
183
+ else:
184
+ tokens.append(_Token(piece, "word"))
185
+ return tokens
186
+
187
+
188
+ def _has_letter_of(code: str, text: str) -> bool:
189
+ language = get_language(code)
190
+ return any(ch in language.letters and ch != "'" for ch in language.normalize(text))
191
+
192
+
193
+ @lru_cache(maxsize=20000)
194
+ def _evaluate(text: str) -> tuple[float, str | None, dict]:
195
+ """Evidence for one word token: score as written, and each remap option."""
196
+ keep, keep_lang = 0.0, None
197
+ found = False
198
+ for code in LANGUAGE_CODES:
199
+ if not _has_letter_of(code, text):
200
+ continue
201
+ result = get_language(code).analyze(text)
202
+ if not found or result.score > keep:
203
+ keep, keep_lang, found = result.score, code, True
204
+
205
+ options: dict = {}
206
+ has_alpha = any(ch.isalpha() for ch in text)
207
+ for src, dst in PAIRS:
208
+ layout = LAYOUTS[src]
209
+ if not all(layout.typeable(ch) for ch in text):
210
+ continue
211
+ if src != "en" and has_alpha and not _has_letter_of(src, text):
212
+ # A word typed on a non-Latin layout must contain a letter of that script.
213
+ continue
214
+ target = get_language(dst)
215
+ best: tuple[str, Analysis] | None = None
216
+ best_rank = 0.0
217
+ for index, candidate in enumerate(conversions(text, src, dst)):
218
+ if candidate == text:
219
+ continue
220
+ result = target.analyze(candidate)
221
+ rank = result.score + (SINGLE_KEY_PRIOR if index == 0 else 0.0)
222
+ if best is None or rank > best_rank:
223
+ best, best_rank = (candidate, result), rank
224
+ if best is None or best[1].letters == 0:
225
+ continue
226
+ if not has_alpha and best[1].letters != len(target.normalize(best[0])):
227
+ # Pure punctuation such as "," is a candidate only if every key is a letter in the target.
228
+ continue
229
+ options[(src, dst)] = best
230
+ return keep, keep_lang, options
231
+
232
+
233
+ def _prepare(text: str) -> list[_Token]:
234
+ tokens = _split(text)
235
+ for token in tokens:
236
+ if token.kind == "word":
237
+ token.keep, token.keep_lang, token.options = _evaluate(token.text)
238
+ return tokens
239
+
240
+
241
+ def _accept(tokens: list[_Token], pair: tuple[str, str], whole: bool = False) -> tuple[bool, float]:
242
+ """Decide whether remapping ``tokens`` with ``pair`` is justified.
243
+
244
+ Returns (accepted, net gain in nats after the penalties). With
245
+ ``whole=True`` (used by detect) the remap is also rejected if it would
246
+ badly damage any single word.
247
+ """
248
+ gain = score = worst = 0.0
249
+ letters = solid = dict_words = 0
250
+ for token in tokens:
251
+ if token.kind != "word" or not token.options or pair not in token.options:
252
+ continue
253
+ result = token.options[pair][1]
254
+ if result.letters < 2:
255
+ # Single letters and bare punctuation ride along with their
256
+ # neighbours but never count as evidence for a remap.
257
+ gain += min(0.0, result.score - token.keep)
258
+ continue
259
+ gain += result.score - token.keep
260
+ score += result.score
261
+ letters += result.letters
262
+ dict_words += result.dict_words
263
+ if result.letters >= 3:
264
+ solid += result.letters
265
+ worst = min(worst, result.score - token.keep)
266
+ net = gain - SEGMENT_PENALTY - PAIR_PENALTY.get(pair, 0.0)
267
+ if whole and worst < -2.0 * EDGE_PENALTY:
268
+ # Some word is much more plausible as written: the text is at most partly mistyped.
269
+ return False, net
270
+ if solid < MIN_LETTERS:
271
+ return False, net
272
+ if dict_words == 0:
273
+ net -= NO_DICT_EXTRA
274
+ if letters < SHORT_LETTERS:
275
+ return False, net
276
+ if score < (MIN_AVG_DICT if dict_words else MIN_AVG) * letters:
277
+ return False, net
278
+ return net > 0, net
279
+
280
+
281
+ def _apply(tokens: list[_Token], pair: tuple[str, str]) -> str:
282
+ out = []
283
+ for token in tokens:
284
+ if token.kind == "word" and token.options and pair in token.options:
285
+ out.append(token.options[pair][0])
286
+ else:
287
+ out.append(token.text)
288
+ return "".join(out)
289
+
290
+
291
+ def _confidence(margin: float) -> float:
292
+ return round(max(0.0, min(1.0, 1.0 - math.exp(-max(0.0, margin) / CONFIDENCE_SCALE))), 3)
293
+
294
+
295
+ def _label(pair: tuple[str, str]) -> str:
296
+ return "keep" if pair == _KEEP else f"{pair[0]}->{pair[1]}"
297
+
298
+
299
+ def detect(text: str) -> Guess:
300
+ """Judge whether ``text`` as a whole was typed on the wrong layout.
301
+
302
+ When unsure the answer is "not mistyped". For text that is only partly
303
+ mistyped use :func:`fix`.
304
+ """
305
+ tokens = _prepare(text)
306
+ words = [t for t in tokens if t.kind == "word"]
307
+
308
+ # Language of the text as written: the one most characters score best in.
309
+ votes: dict[str, float] = {}
310
+ for token in words:
311
+ if token.keep_lang:
312
+ votes[token.keep_lang] = votes.get(token.keep_lang, 0.0) + len(token.text)
313
+ as_written = max(votes, key=votes.get) if votes else None
314
+
315
+ candidates = [] # (net gain, accepted, pair, repaired)
316
+ for pair in PAIRS:
317
+ if not any(token.options and pair in token.options for token in words):
318
+ continue
319
+ accepted, net = _accept(tokens, pair, whole=True)
320
+ candidates.append((net, accepted, pair, _apply(tokens, pair)))
321
+ candidates.sort(key=lambda item: item[0], reverse=True)
322
+
323
+ winner = candidates[0] if candidates and candidates[0][1] else None
324
+ if winner is None:
325
+ # Nothing acceptable, or the top-scoring hypothesis failed a sanity check: leave it.
326
+ best_other = candidates[0] if candidates else None
327
+ margin = max(-best_other[0], 1.0) if best_other else SEGMENT_PENALTY
328
+ return Guess(
329
+ mistyped=False,
330
+ language=as_written,
331
+ typed_layout=None,
332
+ repaired=text,
333
+ confidence=_confidence(margin),
334
+ runner_up=_label(best_other[2]) if best_other else None,
335
+ )
336
+ net, _, pair, repaired = winner
337
+ # Runner-up: the best hypothesis that would give a different result.
338
+ second_net, second_label = 0.0, "keep"
339
+ for other in candidates[1:]:
340
+ if other[3] == repaired:
341
+ continue
342
+ if other[0] > 0:
343
+ second_net, second_label = other[0], _label(other[2])
344
+ break
345
+ return Guess(
346
+ mistyped=True,
347
+ language=pair[1],
348
+ typed_layout=pair[0],
349
+ repaired=repaired,
350
+ confidence=_confidence(net - second_net),
351
+ runner_up=second_label,
352
+ )
353
+
354
+
355
+ def _viterbi(words: list[_Token]) -> list[tuple[str, str]]:
356
+ """Best state per word token; a state is "keep" or one layout pair."""
357
+ states = (_KEEP,) + PAIRS
358
+
359
+ def emission(token: _Token, state: tuple[str, str]) -> float:
360
+ if state != _KEEP and token.options and state in token.options:
361
+ result = token.options[state][1]
362
+ return result.score if result.letters >= 2 else min(result.score, token.keep)
363
+ return token.keep
364
+
365
+ def switch(a: tuple[str, str], b: tuple[str, str]) -> float:
366
+ if a == b:
367
+ return 0.0
368
+ # Leaving "keep" or leaving a run in mid-line costs EDGE_PENALTY, so a
369
+ # run prefers to extend to the ends of the line.
370
+ cost = EDGE_PENALTY
371
+ if b != _KEEP:
372
+ cost += SEGMENT_PENALTY + PAIR_PENALTY.get(b, 0.0)
373
+ return cost
374
+
375
+ score = {s: (0.0 if s == _KEEP else -SEGMENT_PENALTY - PAIR_PENALTY.get(s, 0.0)) for s in states}
376
+ back: list[dict] = []
377
+ for index, token in enumerate(words):
378
+ if index:
379
+ new_score, pointers = {}, {}
380
+ for s in states:
381
+ prev = max(states, key=lambda p: score[p] - switch(p, s))
382
+ new_score[s] = score[prev] - switch(prev, s)
383
+ pointers[s] = prev
384
+ score = new_score
385
+ back.append(pointers)
386
+ for s in states:
387
+ score[s] += emission(token, s)
388
+ last = max(states, key=lambda s: score[s]) # ending the line inside a run costs nothing
389
+ path = [last]
390
+ for pointers in reversed(back):
391
+ path.append(pointers[path[-1]])
392
+ path.reverse()
393
+ return path
394
+
395
+
396
+ def fix(text: str) -> str:
397
+ """Repair the parts of ``text`` that were typed on the wrong layout.
398
+
399
+ Works token by token with context, line by line, so a sentence that is
400
+ half right and half mistyped is handled. Code spans and the tokens
401
+ :func:`is_protected` accepts (URLs, domains, e-mail addresses, and for
402
+ ASCII tokens also handles, numbers and code) are never changed. Text that already
403
+ looks right is returned unchanged; so is text the models are unsure about.
404
+ """
405
+ if not text or text.isspace():
406
+ return text
407
+ out_lines = []
408
+ fenced = False
409
+ for line in text.split("\n"):
410
+ if line.count("```") % 2 == 1:
411
+ fenced = not fenced
412
+ out_lines.append(line)
413
+ elif fenced or "```" in line:
414
+ out_lines.append(line)
415
+ else:
416
+ out_lines.append(_fix_line(line))
417
+ return "\n".join(out_lines)
418
+
419
+
420
+ def _fix_line(line: str) -> str:
421
+ tokens = _prepare(line)
422
+ words = [t for t in tokens if t.kind == "word"]
423
+ if not words:
424
+ return line
425
+ path = _viterbi(words)
426
+ state_of = {id(token): state for token, state in zip(words, path)}
427
+
428
+ out: list[str] = []
429
+ i, n = 0, len(tokens)
430
+ while i < n:
431
+ state = state_of.get(id(tokens[i]))
432
+ if state is None or state == _KEEP:
433
+ out.append(tokens[i].text)
434
+ i += 1
435
+ continue
436
+ # Collect the run of word tokens in this state; spaces and protected
437
+ # tokens between them ride along unchanged.
438
+ j, last_word = i, i
439
+ while j < n:
440
+ other = state_of.get(id(tokens[j]))
441
+ if other is not None:
442
+ if other != state:
443
+ break
444
+ last_word = j
445
+ j += 1
446
+ run = tokens[i:last_word + 1]
447
+ accepted, _ = _accept(run, state)
448
+ out.append(_apply(run, state) if accepted else "".join(t.text for t in run))
449
+ i = last_word + 1
450
+ return "".join(out)