Metadata-Version: 2.4
Name: wrongkeys
Version: 0.1.2
Summary: Detect and repair text typed with the wrong keyboard layout (English with Arabic, Hebrew, Russian, Ukrainian, Greek).
Author: wrongkeys contributors
License: MIT
Project-URL: Homepage, https://github.com/RealAoss/wrongkeys
Project-URL: Issues, https://github.com/RealAoss/wrongkeys/issues
Keywords: keyboard,layout,arabic,hebrew,russian,ukrainian,greek,transliteration
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Text Processing :: Linguistic
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# wrongkeys

Detect and repair text that was typed with the wrong keyboard layout active.

You meant to write Arabic, the keyboard was still on English, and you got
`hgsghl ugd;l`. Or you meant English and got a row of Cyrillic letters.
`wrongkeys` maps the key presses back to the layout you meant, and tries to
tell when that is needed and when the text is fine as it is.

Pure Python, standard library only, Python 3.10 or newer. No data files are
downloaded; the small language models are part of the source.

## The problem, one example per language

Each line shows what ended up on screen and what the same key presses give on
the intended layout.

```python
>>> from wrongkeys import fix
>>> fix("hgsghl ugd;l")            # meant Arabic, keyboard was on English
'السلام عليكم'
>>> fix("akuo guko")               # meant Hebrew
'שלום עולם'
>>> fix("ghbdtn? rfr ltkf&")       # meant Russian
'привет, как дела?'
>>> fix("lzre. pf ljgjvjue")       # meant Ukrainian
'дякую за допомогу'
>>> fix("kalhm;era ti k;aneiw")    # meant Greek
'καλημέρα τι κάνεις'
>>> fix("руддщ цщкдв")             # meant English, keyboard was on Russian
'hello world'
>>> fix("اثممخ صخقمي")             # meant English, keyboard was on Arabic
'hello world'
```

Supported pairs: English (US QWERTY) with each of Arabic (101), Hebrew
(SI-1452), Russian (ЙЦУКЕН), Ukrainian and Greek, in both directions.

## Install

```
pip install git+https://github.com/RealAoss/wrongkeys
```

The package is not published on a package index; install it from the
repository as shown. It has no dependencies.

## Python API

### convert(text, src, dst)

A deterministic remap of every character from one layout to another. No
guessing is involved. Shift state is kept, characters the source layout cannot
produce pass through unchanged.

```python
>>> from wrongkeys import convert
>>> convert("ghbdtn", "en", "ru")
'привет'
>>> convert("Привет, мир!", "ru", "en")
'Ghbdtn? vbh!'
>>> convert("akuo", "en", "he")
'שלום'
>>> convert("kalhm;era", "en", "el")     # ';' is the Greek accent dead key
'καλημέρα'
>>> convert("ghbdtn 😀", "en", "ru")     # unknown characters are left alone
'привет 😀'
```

The Arabic `B` key types two characters, lam and alef. Going back from Arabic
to key presses is therefore ambiguous, because the same two letters can also
be typed as `G` then `H`. `convert` always assumes the single key;
`conversions` lists the alternatives:

```python
>>> from wrongkeys import convert, conversions
>>> convert("b", "en", "ar")
'لا'
>>> convert("high", "en", "ar")
'اهلا'
>>> convert("اهلا", "ar", "en")
'hib'
>>> conversions("اهلا", "ar", "en")
['hib', 'high']
```

### detect(text)

Judges the text as a whole and returns a `Guess`.

```python
>>> from wrongkeys import detect
>>> guess = detect("hgsghl ugd;l")
>>> guess.mistyped, guess.typed_layout, guess.language
(True, 'en', 'ar')
>>> guess.repaired
'السلام عليكم'
>>> guess.confidence > 0.9, guess.runner_up
(True, 'keep')
>>> detect("hello world").mistyped
False
>>> detect("id").mistyped          # could be Arabic 'هي', but two letters prove nothing
False
```

Fields of `Guess`:

| field | meaning |
| --- | --- |
| `mistyped` | `True` if the whole text looks typed on the wrong layout |
| `language` | the intended language if mistyped, otherwise the language the text is in as written (`None` if unknown) |
| `typed_layout` | the layout that was active, or `None` |
| `repaired` | the remapped text if mistyped, otherwise the input unchanged |
| `confidence` | 0 to 1, computed from the score margin between the best and the second-best explanation. It is not a calibrated probability. |
| `runner_up` | the second-best explanation: `"keep"` or a pair such as `"en->ru"` |

`detect` answers for the text as a whole. A sentence that is only partly
mistyped is reported as not mistyped; use `fix` for that.

### fix(text)

Repairs the mistyped parts and leaves the rest alone. It works word by word
with context, one line at a time.

```python
>>> from wrongkeys import fix
>>> fix("I said ghbdtn vbh to him")
'I said привет мир to him'
>>> fix("yfgbib vyt yf user@example.com gj;fkeqcnf")
'напиши мне на user@example.com пожалуйста'
>>> fix("pfgecnb `git status` gj;fkeqcnf")
'запусти `git status` пожалуйста'
>>> fix("hello world")
'hello world'
>>> fix("for i in range(10): print(i)")
'for i in range(10): print(i)'
```

These are never changed: URLs that start with a scheme (`https://`) or
`www.`; domain names (two or more characters before the first dot), with
or without a path, whose last label is a known
top-level domain, either ASCII (`.com`, `.ru`, ...) or internationalised in
any script (`яндекс.рф`, `.укр`, `.срб`, `.ελ`, `.ישראל`, `.السعودية`,
`.امارات`, `.مصر`, ...; the list is `_IDN_TLDS` in `engine.py`); e-mail
addresses (non-ASCII ones only at such a domain); code spans in backticks
and fenced code blocks. Among tokens written in ASCII, the following are
never changed as well: `@handles`, `#tags`, anything containing a digit,
file names with a common extension (`main.py`) and tokens that look like
code (`snake_case`, `f(x)`, `a=b`, `--flag`, paths). A domain whose
top-level domain is not on the lists is treated like any other word.

## Command line

```console
$ wrongkeys fix "hgsghl ugd;l"
السلام عليكم
$ wrongkeys fix "I said ghbdtn vbh to him"
I said привет мир to him
$ echo "ghbdtn vbh" | wrongkeys fix
привет мир
$ wrongkeys convert --from en --to he "akuo"
שלום
$ wrongkeys detect "kalhm;era"
mistyped: typed on en, meant el (confidence 0.84, runner-up keep)
καλημέρα
$ wrongkeys detect "hello world"
not mistyped: looks like en (confidence 0.98, runner-up en->ar)
$ wrongkeys detect --json "ghbdtn vbh"
{"mistyped": true, "language": "ru", "typed_layout": "en", "repaired": "привет мир", "confidence": 0.963, "runner_up": "en->ar"}
$ wrongkeys layouts
ar  Arabic (101, Windows)  [unshifted sure; shifted layer moderately sure]
...
```

`fix`, `convert` and `detect` read standard input when no text is given.
Input and output are always UTF-8, also on Windows, so the tool can be used
in pipes there. A UTF-8 byte order mark at the start of standard input (as
saved by Notepad or PowerShell) is dropped; output never has one.
`python -m wrongkeys` works the same way as the `wrongkeys`
command.

## How detection works

There is no third-party data in the package. For each of the six languages it
contains a few hundred common words, some first names and about forty sample
sentences, all written by hand for this project (`src/wrongkeys/data/`). From
that material two things are built at import time:

1. a word list, and
2. a character trigram model with Witten-Bell backoff.

A piece of text gets a plausibility score for a language: the log-likelihood
of its letters under the trigram model, minus the log-likelihood under
uniformly random letters, plus a bonus for words in the word list, minus
penalties for characters that do not belong (letters of another script,
`;` in the middle of a word, and so on). Positive means "looks like this
language", negative means "looks like noise".

Every whitespace-separated token is scored as written and after remapping
with each of the ten layout pairs. A remap is considered only where the
remapped text scores higher than the original by a margin, and several
conservative rules apply on top:

- at least four letters in words of three or more letters must be involved;
- a result shorter than six letters must contain a listed word;
- single letters and bare punctuation never count as evidence;
- English to Greek needs extra evidence, because the Greek layout is close to
  phonetic and Latin words turn into Greek-looking strings easily;
- protected tokens (URLs, numbers, code, see above) are never touched.

`detect` applies this to the whole text. `fix` runs a Viterbi pass over the
tokens of each line with a cost for switching between "keep" and "remap", so
a run of mistyped words inside a correct sentence is found, and a short word
inside a mistyped run is carried along.

For Arabic, both readings of lam-alef (one key or two) are tried and the one
that gives better English is used.

All thresholds were set by hand on the development set described below.

## Layout tables and how sure they are

The tables in `src/wrongkeys/layouts.py` were written from memory. They
describe the default **Windows / PC** layouts. `wrongkeys layouts` prints the
list of uncertain keys; the same notes are in the source.

| layout | sure | not sure |
| --- | --- | --- |
| English, US QWERTY | everything | |
| Russian, ЙЦУКЕН | letters and the shifted number row | |
| Ukrainian | letters | the key left of `1` (assumed `'` and `₴`, as in the "Enhanced" layout); the backslash key; `ґ` is not on any modelled key and passes through unchanged |
| Greek | letters, final sigma on `W`, tonos dead key on `;` | Shift+`;` (assumed dialytika dead key), Shift+`W` (assumed dialytika-tonos dead key), the exact characters a dead key leaves when no vowel follows |
| Hebrew, SI-1452 | letters | the punctuation that moves (`q` `w` `'` `/` and the key left of `1`), and the assumption that `( ) [ ] { } < >` are mirrored |
| Arabic 101 | the whole unshifted layer, including the two-character lam-alef key on `B` | the shifted layer: which key carries which diacritic, the bracket and brace keys on Shift+`D F C V`, Shift+`[ ]`, the quote characters on Shift+`U M`, `÷` and `×` on Shift+`I O`, mirrored parentheses, Shift+`Z` |

Consequences: plain words typed without Shift convert reliably in all five
languages. Text that depends on an uncertain key (Arabic diacritics, Hebrew
brackets, a Ukrainian apostrophe) may convert to the wrong character.

Not modelled at all: AltGr (third-level) characters, Caps Lock, the extra key
of ISO keyboards, Hebrew niqqud, and the newer Hebrew SI-1452-2 layout.

## Evaluation

`bench/dataset.py` is a development set written for this project:
200 phrases per language (60 with four or more words, 70 with two or three
words, 70 single words including ten names and ten very short words), plus
581 items that must be left alone (code, URLs and e-mail addresses, numbers,
short tokens and abbreviations, English words, names and Latin-script text in
other languages, mixed-language sentences). Every phrase is used twice: as
written, where it must not be changed, and remapped to the wrong layout with
`convert`, where it must be repaired. English phrases are mistyped on each of
the five other layouts. Arabic phrases that contain lam-alef are included
twice, typed with the `B` key and typed with `G` `H`.

Run it with:

```
PYTHONPATH=src python bench/run.py
```

Results of a run on 2026-11-24 (Python 3.14, 2026 mistyped items, 1781
correct items). "Exact repair" means `fix()` returned the intended text
character for character. "Wrongly changed" is the share of correct texts that
`fix()` altered.

| | detect precision | detect recall | exact repair | repaired wrongly | correct text wrongly changed |
| --- | --- | --- | --- | --- | --- |
| wrongkeys, all | 100.0% | 88.2% | 88.1% | 0.1% | 0.0% (0 of 1781) |
| wrongkeys, 1 word | 100.0% | 68.0% | 68.0% | 0.0% | 0.0% (0 of 905) |
| wrongkeys, 2-3 words | 100.0% | 97.7% | 97.5% | 0.3% | 0.0% (0 of 469) |
| wrongkeys, 4+ words | 100.0% | 100.0% | 100.0% | 0.0% | 0.0% (0 of 407) |
| naive baseline, all | 79.0% | 90.9% | 88.2% | 2.7% | 27.6% (491 of 1781) |
| naive baseline, 1 word | 61.7% | 95.9% | 94.0% | 1.9% | 46.2% (418 of 905) |
| naive baseline, 2-3 words | 91.2% | 94.2% | 89.5% | 4.7% | 13.6% (64 of 469) |
| naive baseline, 4+ words | 98.2% | 81.5% | 80.1% | 1.5% | 2.2% (9 of 407) |

The baseline is: if the text is ASCII and none of its words is in the English
word list, remap it to the layout whose word list matches most words; if it
is in another script and none of its words is in that language's list, remap
it to English. It repairs about as many mistyped items as `wrongkeys`, and it
damages more than a quarter of the correct texts.

Exact repair by intended language and length (wrongkeys):

| intended | 1 word | 2-3 words | 4+ words | all |
| --- | --- | --- | --- | --- |
| Arabic | 52.8% | 96.3% | 100.0% | 83.7% |
| Greek | 65.7% | 95.6% | 100.0% | 86.5% |
| English | 74.2% | 98.6% | 100.0% | 90.5% |
| Hebrew | 41.4% | 94.3% | 100.0% | 77.5% |
| Russian | 78.6% | 98.6% | 100.0% | 92.0% |
| Ukrainian | 71.4% | 97.1% | 100.0% | 89.0% |

Correct text wrongly changed was 0 in every language and in every leave-alone
category on this set.

The same run also passes the English help text that ships with Python
(`pydoc_data.topics`, technical prose with many code fragments, not written
for this project) through `fix()`: 4 of 10696 lines were wrongly changed
(0.04%), all of them lines of code-like tokens such as `"pdb.Pdb"`, and none
of 3717 distinct words when given alone.

### How to read these numbers

- **They are optimistic.** The development set was written by the same author
  as the word lists, the thresholds were tuned on it, and a second batch of
  vocabulary was added to the word lists after looking at its failures.
  Between 59% and 92% of the distinct words in the development set are in the
  built-in word lists (`bench/run.py` prints the figure per language). Real
  text has a much wider vocabulary.
- **Single words are weak, by design.** A run needs at least four letters in
  words of three or more letters before anything is changed, so one- to
  three-letter inputs are never repaired. Most of the missing single-word
  recall is exactly that: common three-letter words, which are especially
  frequent in Arabic and Hebrew. Lowering the limit repaired more of them
  but started to change correct short words (an English `gym` became an
  Arabic word), so the limit stayed.
- **A zero on 1781 items is not zero.** It bounds the rate of wrongly changed
  text on this kind of input to a fraction of a percent at best, and says
  nothing about text unlike the set. The standard-library check above shows
  the first real failures.

### Blind set

`bench/blind_data.py` was written by someone who never saw the package, its
word lists or the development set: 600 phrases (100 per language, chat
messages, queries, names, slang), 580 leave-alone items in 28 categories, and
74 pairs where the author worked out the mistyped text key by key from their
own knowledge of the layouts. It was run once and the engine was not changed
afterwards. `bench/run.py` prints these numbers.

| | detect precision | detect recall | exact repair | correct text wrongly changed |
|---|---|---|---|---|
| all | 99.6% | 90.8% | 90.3% | 3/1180 (0.3%) |
| 1 word | 99.3% | 77.0% | 77.0% | 1/527 |
| 2-3 words | 99.5% | 94.2% | 93.7% | 1/383 |
| 4+ words | 100.0% | 99.5% | 98.6% | 1/270 |
| naive baseline, all | 62.8% | 90.2% | 78.7% | 320/1180 (27.1%) |

Exact repair by intended language: uk 93, en 93, ru 91, ar 90, he 90, el 85.
Single words: uk 87, en 83, ru 81, he 73, ar 70, el 67.

The three correct texts that were changed, in full:

- the English word `rhythm` (no vowels, so it looks unlike English to the
  trigram model) became Cyrillic;
- an Iraqi-dialect Arabic sentence was turned into Latin letters: the word
  lists are close to standard Arabic and dialect words are missing;
- a line of JavaScript, `const sum = (a, b) => a + b;`, had `sum` and the
  single-letter names remapped to Arabic. Do not run `fix` over source code.

The 74 hand-typed pairs agree with the layout tables in every case, for
lowercase letters only; `fix` repaired 73 of them. Punctuation keys, shifted
layers and the Arabic lam-alef key were not in that check and remain as
uncertain as the layout section says.

## Limits

- **Short text.** One to three letters are never changed. Four- and
  five-letter inputs are changed only if the result is a listed word.
- **Small models.** A few hundred words per language. Rare words, slang,
  dialect, names and technical terms are judged by the trigram model alone,
  which is rough. Expect misses on such text, and occasional wrong repairs on
  unusual Latin-script tokens whose remap happens to look like Arabic or
  Hebrew (seen on identifiers such as `pdb.Pdb`).
- **Words that are valid both ways.** `اهلا` is an Arabic greeting and also
  `high` typed on the Arabic layout; `μετα` is Greek and also `meta`. Such
  text is left as it is.
- **Protected tokens can hide real words.** A mistyped word that happens to
  look like a file name or domain (`something.py`; `ищщл.рф`, which is
  `book/ha` typed on the Russian layout), starts with `@` or `#`
  (the Russian opening quote and `№` are on those keys), or contains a digit
  is left alone. A pair of backticks that starts one word and ends another
  is taken for a code span, although the backtick key is a letter on the
  Russian and Arabic layouts.
- **Mac layouts are not covered.** Apple's Arabic, Hebrew, Russian, Ukrainian
  and Greek layouts differ from the PC ones in several keys.
- **Uncertain keys**, listed in the table above, mostly on shifted layers.
- **Caps Lock and AltGr** are not modelled. A capital letter is always
  treated as Shift plus the key, which is not what Caps Lock does on every
  layout (not verified for Arabic and Hebrew).
- **Only pairs with English.** Russian typed on a Ukrainian layout, or Arabic
  on Hebrew, is not detected. `convert` does handle any pair of the six
  layouts.
- **Languages not covered:** everything else, including other Cyrillic
  languages (Belarusian, Bulgarian, Serbian, Kazakh), Persian and Urdu (which
  use different Arabic-script layouts), Turkish, and non-US Latin layouts
  such as AZERTY, QWERTZ or UK English.
- Not a spell checker: it reproduces what the keys would have typed,
  including your typos.

## Development

```
python -m unittest discover -s tests -v
```

The tests need no network and no installation; they add `src` to the import
path themselves. Every example in this README is executed by
`tests/test_readme.py`.

See [CONTRIBUTING.md](CONTRIBUTING.md) for how to add a layout or correct a
key, and [CHANGELOG.md](CHANGELOG.md) for the history.

## License

MIT, see [LICENSE](LICENSE).
