Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / keyboard / generate_dictionary.py
generate_dictionary.py108 lines · 4.6 KiBRaw
| 1 | #!/usr/bin/env python3 |
| 2 | """Offline generator: common_words_list.txt -> keyboard/src/main/assets/dict/words_en.txt |
| 3 | |
| 4 | The keyboard shipped with a 330-word "starter" list whose own header asked for it to |
| 5 | be replaced before production. Autocorrect over 330 words does not just underperform, |
| 6 | it actively rewrites correct words into one of the few it knows, so this builds the |
| 7 | real list from the 60k-entry frequency-ordered word list already in the repo (the one |
| 8 | :games:wordmaker uses). |
| 9 | |
| 10 | Output format is the `word<TAB>frequency` form Dictionary.kt already parses, sorted |
| 11 | alphabetically so the asset diffs cleanly. |
| 12 | |
| 13 | Frequency is derived from rank in the source file (which is ordered most-common |
| 14 | first), EXCEPT for profanity, which is emitted with frequency 0. Dictionary.kt treats |
| 15 | frequency 0 as "known word, never offered": typing it is not flagged as a misspelling |
| 16 | and it is not autocorrected away, but it can never be produced as a suggestion or as |
| 17 | an autocorrection of something else. That is the standard IME behaviour and it is the |
| 18 | reason this cannot just be a filtered word list -- dropping the words entirely would |
| 19 | make the keyboard silently "correct" them into something else. |
| 20 | |
| 21 | Only /^[a-z]+$/ entries survive. KeyboardService only appends `Char.isLetter()` |
| 22 | characters to the composing buffer (see the text.length == 1 && text[0].isLetter() |
| 23 | guard), so hyphenated and apostrophised entries could never be matched as one token |
| 24 | and would only be dead weight in the binary-search arrays. |
| 25 | |
| 26 | Usage: python3 scripts/keyboard/generate_dictionary.py |
| 27 | """ |
| 28 | |
| 29 | from pathlib import Path |
| 30 | |
| 31 | REPO = Path(__file__).resolve().parents[2] |
| 32 | SOURCE = REPO / "scripts" / "wordmaker" / "common_words_list.txt" |
| 33 | BAD_WORDS = REPO / "scripts" / "wordmaker" / "bad-words.txt" |
| 34 | OUTPUT = REPO / "keyboard" / "src" / "main" / "assets" / "dict" / "words_en.txt" |
| 35 | |
| 36 | # Single letters are not words and make terrible autocorrect targets ("m" -> every |
| 37 | # two-letter word is within edit distance 1). Only the two real ones survive. |
| 38 | ALLOWED_SINGLE_LETTERS = {"a", "i"} |
| 39 | |
| 40 | HEADER = """\ |
| 41 | # English word list for the offline keyboard. |
| 42 | # Format: one entry per line, "word<TAB>frequency". Higher frequency ranks higher. |
| 43 | # |
| 44 | # Frequency 0 means "known word, never offered": contains() accepts it so the word is |
| 45 | # not treated as a misspelling and is not autocorrected away, but it is never produced |
| 46 | # as a suggestion or as an autocorrection. Profanity is filed this way. |
| 47 | # |
| 48 | # GENERATED FILE -- do not edit by hand. |
| 49 | # Regenerate with: python3 scripts/keyboard/generate_dictionary.py |
| 50 | # Source: scripts/wordmaker/common_words_list.txt (frequency-ordered), filtered to |
| 51 | # /^[a-z]+$/ because KeyboardService only composes Char.isLetter() characters. |
| 52 | """ |
| 53 | |
| 54 | |
| 55 | def load_profanity() -> set[str]: |
| 56 | """Single-token lowercase a-z entries from the shared bad-words list.""" |
| 57 | words = set() |
| 58 | for raw in BAD_WORDS.read_text(encoding="utf-8", errors="replace").splitlines(): |
| 59 | w = raw.strip().lower() |
| 60 | if w and w.isalpha() and w.isascii(): |
| 61 | words.add(w) |
| 62 | return words |
| 63 | |
| 64 | |
| 65 | def main() -> None: |
| 66 | profanity = load_profanity() |
| 67 | |
| 68 | # Rank is position in the source file; first occurrence wins on duplicates. |
| 69 | ranked: dict[str, int] = {} |
| 70 | for rank, raw in enumerate( |
| 71 | SOURCE.read_text(encoding="utf-8", errors="replace").splitlines() |
| 72 | ): |
| 73 | word = raw.strip().lower() |
| 74 | if not word or not word.isascii() or not word.isalpha(): |
| 75 | continue |
| 76 | if len(word) == 1 and word not in ALLOWED_SINGLE_LETTERS: |
| 77 | continue |
| 78 | if word not in ranked: |
| 79 | ranked[word] = rank |
| 80 | |
| 81 | # Re-rank densely over the words that survived filtering. Ranks from the source file |
| 82 | # are sparse here (60k lines in, 42k words out), and using them directly would push |
| 83 | # every word past the cutoff to a negative frequency -- which then reads as the |
| 84 | # "never offered" sentinel and would silently mute a third of the dictionary. |
| 85 | dense = {word: rank for rank, word in enumerate(ranked)} |
| 86 | total = len(dense) |
| 87 | |
| 88 | suppressed = 0 |
| 89 | lines = [] |
| 90 | for word in sorted(dense): |
| 91 | if word in profanity: |
| 92 | freq = 0 |
| 93 | suppressed += 1 |
| 94 | else: |
| 95 | # Rank 0 (most common) gets the highest frequency. Offset by 1 so no |
| 96 | # ordinary word can collide with the 0 sentinel. |
| 97 | freq = total - dense[word] + 1 |
| 98 | lines.append(f"{word}\t{freq}") |
| 99 | |
| 100 | OUTPUT.parent.mkdir(parents=True, exist_ok=True) |
| 101 | OUTPUT.write_text(HEADER + "\n".join(lines) + "\n", encoding="utf-8") |
| 102 | |
| 103 | print(f"wrote {OUTPUT.relative_to(REPO)}") |
| 104 | print(f" {total} words ({suppressed} profanity entries at frequency 0)") |
| 105 | |
| 106 | |
| 107 | if __name__ == "__main__": |
| 108 | main() |