mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-27 07:58:01 +01:00
* android typing: a reproducible Brazilian Portuguese model (pt.hextm, pt.valid, pt.capitals), not wired up yet
Google Books has no Portuguese, so the model is counted from sources licensed for commercial use
with attribution only (CC BY 4.0), each file pinned in benchmark/typing/pt-inputs.tsv by URL, fetch
date, size and SHA-256:
- 14 Leipzig Corpora Collection news downloads (only the downloads; the site and API are CC BY-NC),
each sentence given to Brazil or Portugal by its site (.br, .pt, else spelling markers).
- ParlaIbero-BR and -PT v2 (Câmara dos Deputados 2009-2025, Assembleia da República 1995-2025).
build-layout-model.py pt: Brazil's counts (181.5M news words, 138.1M words of speech), news counted
ten times a speech for words and alone for word pairs (with speech pairs in, "obrigado" was followed
by "sr" and "deputado"), less spellings retired in 1990 ("idéia", "vôo") and plain twins 20 times
rarer than an accented one ("nao", "voce", Polish's rule), plus Hex's own chat words
(pt-extra-words.tsv, a draft for a Brazilian speaker to read). 100,029 words, 380,416 pairs, 3.60 MB.
build-valid-words.py pt: Brazil's other lowercase spellings, then Portugal's own spellings from
Portugal's counts ("telemóvel", "receção"), so a Portuguese typist's correct word stays as typed.
build-capitals.py pt: case shares from the same Brazilian counts, held as French's are.
Held-out set: portuguese_set.py makes held-out/pt.tsv.gz exactly as polish_set.py makes Polish's,
from Brazilian contributors' Tatoeba sentences; accent keys and seven critical cases added.
quality-gate.py now takes more than two critical cases (Polish already had five).
The APK pins the three new files (SHA256SUMS, verifyTypingModels); no layout or keyboard code
reads them yet, so nothing a person sees changes.
Verified: a from-scratch rebuild on the Studio in a separate folder gave byte-identical files
(pt.hextm 387bf9b6..., pt.valid b92acc12..., pt.capitals 0210f5bd...); 12,800 of the 12,873
held-out reference words are model or list words; on 5,000 other Brazilian Tatoeba sentences the
model reads 6.54 nats per known word (news only 6.55, speech only 6.90, both alike 6.59).
Not yet run: quality-gate.py pt (it compiles the app with Gradle, which waits for the coordinator).
* android typing: Portuguese words the context decides (é or e, está or esta), and a held accent stays
Step 4 of Portuguese typing. ContextWords gets Portuguese groups: the same letters with and without
an accent ("e"/"é", "esta"/"está", "nos"/"nós", "a"/"à", ...) and a verb beside the noun its accent
makes ("duvida"/"dúvida", "pratica"/"prática", "magoa"/"mágoa"). build-layout-model.py keeps those
verbs in the model (PT_CONTEXT_WORDS, the same words) although the plain-twin rule would leave them
out, so the words around can pick them; the rebuilt pt.hextm, pt.valid and pt.capitals differ only by
those 20 words and the pairs and costs that follow.
A Portuguese word typed with an accent held for it is no longer revised by the next word
(ContextWords.keepsTypedAccent): with the groups alone, the next word turned 26 held "é" into "e"
and 14 "à" into "a" in the clean replay, and correct words changed rose to 0.58%. French and
Italian keep revising a held accent, as before.
Verified with quality-gate.py all on the Studio (host JVM, Gradle --no-daemon, no emulator):
pt 83.75% fewer errors than raw taps (81.23% before), 0.16% of correct words changed (0.09%),
98.30% of unambiguous accents restored (98.31%), 51.98% of ambiguous ones (21.61%), ambiguous harm
0.29% (0.03%), critical cases 7/7 (6/7: "ele e muito bom" -> "ele é muito bom" now passes); PASS.
en, es, de, nb, fr and it: the gate's output identical field for field to origin/dev's.
Known limit, measured on Tatoeba sentences outside the held-out set: of 152 uses of those verbs
typed as written, 38 stay (13 before); 114 still become the noun. Simple pluperfects ("acontecera")
become the future. The held-out set has one such word ("recebera") and none of the verbs.
* android keyboard: Português gets its own layout and typing model, accent holds, swipe and filter
Step 5 of Portuguese typing. Português, dictated or pinned in Keyboard › Keyboard layout, now types
with its own model instead of English's word list standing in (Spoken.Portuguese, "pt"):
- Keys: QWERTY, as English's (KeyboardLetters "pt").
- Holds: iPhone Hex's Portuguese long presses (KeyboardLanguage.swift) on a, e, i, o, u, c and n;
other letters hold nothing, as on iPhone.
- The strip's words between words: "eu", "o", "a" at a sentence's start, "e", "mas", "que" after a
comma, and the commonest words where the pairs know none.
- never-suggest.tsv: Portuguese rows curated from LDNOOBW's pt list (CC BY 4.0, credit extended):
11 slurs (viado, bicha, paneleiro, sapatão...) and 43 swear words with common inflections;
ordinary words on that list (comer, cerveja, burro, saco, transar) and veado (deer) stay.
- Swipe: swipe_paths.py and swipe-bench.py know "pt".
Nederlands, Polski and Русский keep English's word list as a stand-in, as before.
Tests (existing files): InsertionTest now expects Português's layout and typing model;
NeverSuggestTest runs its filter, between-words and swipe checks for pt as for the other six.
Verified on the Studio (host JVM, Gradle --no-daemon, no emulator): testDebugUnitTest passes;
quality-gate.py all: pt PASS (83.75% fewer errors, 0.16% correct words changed, 98.30% accents,
7/7), the other six identical field for field to origin/dev's; swipe-bench.py, typical fingers:
pt 96.3% first word right, 99.5% typed or in the strip over 11,580 swipes, the other six as in the
README table. Not yet checked on an emulator.
* android typing: an infinitive before "-lo" or "-la" is no Portuguese word of its own
Found on the emulator: typing "obrig" offered "obrigá" in the strip. The counter split "obrigá-lo" at
its hyphen, so 569 infinitives written for an enclitic pronoun ("fazê", "ajudá", "tê") were model
words, offered as readings and completions and once read for "te" ("deverias te esquecer" ->
"tê"). build-layout-model.py now skips a word ending in á é ê í ô that "-lo", "-la", "-los" or
"-las" follows; the rebuilt pt.hextm, pt.valid and pt.capitals take other words in their place.
Verified on the Studio (host JVM, Gradle --no-daemon): quality-gate.py all, pt PASS: 83.81% fewer
errors than raw taps (83.75%), 0.16% correct words changed, 98.30% unambiguous accents, 51.98%
ambiguous, harm 0.27% (0.29%), 7/7, and "te" is no longer changed in the clean replay; the other
six identical field for field to origin/dev's. testDebugUnitTest passes. swipe-bench.py: pt 96.3%
first word right, 99.5% typed or in the strip over 11,581 swipes; the other six unchanged.
* android typing: no Portuguese word writes ç before e or i
Found on the emulator: a swiped "voce" offered "voçê" in the strip. Portuguese never writes ç
before e or i, so build-layout-model.py drops such spellings (5 model words: voçê, voçe, conheçe,
tropeçe and a Turkish club's name); the rebuilt pt.hextm, pt.valid and pt.capitals take other words
in their place. The benchmark README also records the emulator check in an outside app.
Verified with quality-gate.py, testDebugUnitTest and swipe-bench.py on the Studio after the merge of
dev that follows (numbers in that merge's pull request update).
169 lines
9.2 KiB
Python
169 lines
9.2 KiB
Python
#!/usr/bin/env python3
|
|
"""Validity lists (<lang>.valid): spellings outside a keyboard model that are still real words, so the
|
|
decoder never splits them into words (iOS asks its spelling dictionary, UITextChecker). One lowercase
|
|
word per line, sorted by UTF-8 bytes, with a trailing newline; only words the model lacks. English's
|
|
lines are the word alone; the others add a tab and the word's cost in eighths of a nat,
|
|
round(8 ln(corpus / count)), as the model stores its words', so a rare word costs what it is.
|
|
|
|
python3 build-valid-words.py en scowl-2020.12.07.tar.gz en.hextm en.valid
|
|
python3 build-valid-words.py {es|de|fr|it} MODEL.hextm WORKDIR OUTPUT.valid [MIN_COUNT]
|
|
python3 build-valid-words.py nb MODEL.hextm WORKDIR OUTPUT.valid [MIN_COUNT]
|
|
python3 build-valid-words.py pt MODEL.hextm WORKDIR OUTPUT.valid [MIN_COUNT]
|
|
|
|
English: SCOWL spellings, sizes through 70. Spanish, German, French and Italian: Google Books Ngram
|
|
v3 1-grams (2020-02-17, CC BY 3.0), 1980-2019, as build-capitals.py counts them into
|
|
WORKDIR/counts.tsv: every spelling of two letters or more the books use at least MIN_COUNT times,
|
|
in lowercase or with a capital. Left out: two model words run together whose pair is ten times as
|
|
common ("apartir", scanned books join them as typists do), in French and Italian an elision
|
|
without its apostrophe that the model has with it ("cest"), so space still puts it back, and in every
|
|
language a spelling that is a model word with an accent changed or left out ("volvere", "brulant"),
|
|
which books misspell as typists do.
|
|
Bokmål: Norsk ordbank's standard full forms (2022 release, CC BY 4.0) that the NB N-gram 2026
|
|
books (language nob, CC0) use at least MIN_COUNT times, 1980-2019.
|
|
Portuguese (Brazil): the spellings build-layout-model.py pt counts (WORKDIR is its SOURCE_CACHE) in
|
|
Brazil's news and parliament at least MIN_COUNT times, less what its model leaves out; then
|
|
Portugal's own spellings, from Portugal's news and parliament (at least PT_PORTUGAL_COUNT times), so
|
|
a Portuguese typist's correct "facto", "acção" or "económico" is a word and stays as typed: one that
|
|
is a model word with other accents only when Portugal writes it that way more than any other, each
|
|
at the cost of its count among Portugal's words.
|
|
"""
|
|
import collections, csv, hashlib, importlib, io, math, os, re, sys, tarfile, unicodedata
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
capitals = importlib.import_module("build-capitals")
|
|
|
|
SCOWL_SHA256 = "5587667caa20c4891390c2d42dbb4d5c4c3f41bee77af1457ece3ba23fb859cc"
|
|
# The fewest uses that make a spelling a word, chosen per language on the typing benchmark
|
|
# against both the rare words it keeps and the typos it lets stand (README.md).
|
|
MIN_COUNT = {"es": 3000, "de": 10000, "fr": 3000, "it": 3000, "nb": 1000, "pt": 10}
|
|
PT_PORTUGAL_COUNT = 20
|
|
ELISIONS = {
|
|
"fr": ["c", "d", "j", "l", "m", "n", "s", "t", "qu", "jusqu", "lorsqu", "puisqu", "quoiqu", "presqu"],
|
|
"it": ["c", "d", "l", "m", "n", "s", "t", "v", "un", "all", "dall", "dell", "nell", "sull", "coll",
|
|
"quest", "quell", "bell", "sant", "tutt", "nessun", "buon"],
|
|
}
|
|
|
|
|
|
def write(output, words):
|
|
"""`words`: a set of spellings, or a dict of spelling to cost."""
|
|
line = (lambda w: f"{w}\t{words[w]}\n") if isinstance(words, dict) else (lambda w: w + "\n")
|
|
data = "".join(line(w) for w in sorted(words, key=lambda w: w.encode("utf-8"))).encode("utf-8")
|
|
Path(output).write_bytes(data)
|
|
print(f"{len(words):,} spellings outside the model, {len(data):,} bytes; {hashlib.sha256(data).hexdigest()}")
|
|
|
|
|
|
def folded(w):
|
|
return "".join(c for c in unicodedata.normalize("NFD", w) if not unicodedata.combining(c))
|
|
|
|
|
|
def cost(count, corpus):
|
|
return min(255, round(8 * math.log(corpus / count)))
|
|
|
|
|
|
def english(source, model, output):
|
|
assert hashlib.sha256(Path(source).read_bytes()).hexdigest() == SCOWL_SHA256
|
|
scored = set(capitals.model_words(model)[0])
|
|
valid = set()
|
|
with tarfile.open(source) as archive:
|
|
for entry in archive:
|
|
m = re.fullmatch(r".*/final/(english|british|american)-(words|contractions|proper-names|upper|abbreviations)\.(\d+)", entry.name)
|
|
if m and int(m[3]) <= 70:
|
|
for w in archive.extractfile(entry).read().decode("latin-1").lower().split():
|
|
if re.fullmatch("[a-z]{2,32}", w) and w not in scored:
|
|
valid.add(w)
|
|
write(output, valid)
|
|
|
|
|
|
def books(lang, model, work, output, least):
|
|
unigram, pair = capitals.model_words(model)
|
|
merged = capitals.merged_counts(lang, work)
|
|
letters = re.compile(f"[{capitals.LETTERS[lang]}]{{2,32}}").fullmatch
|
|
rows, corpus = [], 0
|
|
for line in open(merged, encoding="utf-8"):
|
|
key, lo, ca = line.rstrip("\n").split("\t")
|
|
total = int(lo) + int(ca)
|
|
corpus += total
|
|
if total >= least and key not in unigram and letters(key):
|
|
rows.append((key, total))
|
|
def elided(word, share):
|
|
return any(word.startswith(p) and len(word) > len(p) and p + "'" + word[len(p):] in unigram
|
|
and math.exp(-unigram[p + "'" + word[len(p):]]) >= 10 * share for p in ELISIONS.get(lang, []))
|
|
twins = {folded(w) for w in unigram}
|
|
valid = {k: cost(n, corpus) for k, n in rows if not capitals.joined(k, n / corpus, unigram, pair)
|
|
and not elided(k, n / corpus) and folded(k) not in twins}
|
|
print(f"{lang}: {len(rows) - len(valid):,} run-together or misaccented spellings left out", flush=True)
|
|
write(output, valid)
|
|
|
|
|
|
def norwegian(model, work, output, least):
|
|
layout = importlib.import_module("build-layout-model")
|
|
work = Path(work)
|
|
work.mkdir(parents=True, exist_ok=True)
|
|
bank = work / "ordbank-2022.tar.gz"
|
|
layout.builder.fetch(layout.ORDBANK, str(bank))
|
|
if hashlib.sha256(bank.read_bytes()).hexdigest() != "57d91cb3f17b85befa50a3b56fcaed9800ca665b39486fe97b668add914d5f60":
|
|
raise ValueError("Unexpected Norsk ordbank 2022 release")
|
|
with tarfile.open(bank, "r:gz") as archive, archive.extractfile("fullformsliste.txt") as entry:
|
|
rows = csv.DictReader(io.TextIOWrapper(entry, encoding="latin-1"), delimiter="\t", quoting=csv.QUOTE_NONE)
|
|
forms = {layout.normalize(r["OPPSLAG"]) for r in rows if r["NORMERING"] == "normert" and r["TILDATO"] == "4000"}
|
|
counts = work / "counts.tsv"
|
|
if not counts.exists():
|
|
path = work / "digibok-unigram.jsonl.zst"
|
|
layout.download_nb(layout.NB + "unigram.jsonl.zst", path, 1_269_473_951)
|
|
uni = layout.nb_counts(path, False, layout.WORD.fullmatch)
|
|
counts.with_suffix(".part").write_text("".join(f"{w}\t{n}\n" for w, n in uni.items()), encoding="utf-8")
|
|
counts.with_suffix(".part").replace(counts)
|
|
scored = set(capitals.model_words(model)[0])
|
|
twins = {folded(w) for w in scored}
|
|
rows = [line.rstrip("\n").split("\t") for line in open(counts, encoding="utf-8")]
|
|
corpus = sum(int(n) for _, n in rows)
|
|
valid = {w: cost(int(n), corpus) for w, n in rows
|
|
if int(n) >= least and len(w) >= 2 and w in forms and w not in scored and folded(w) not in twins}
|
|
write(output, valid)
|
|
|
|
|
|
def portuguese(model, work, output, least):
|
|
layout = importlib.import_module("build-layout-model")
|
|
folder = layout.portuguese_counts(work)
|
|
unigram, pair = capitals.model_words(model)
|
|
twins = {folded(w) for w in unigram}
|
|
valid = {}
|
|
# Only spellings written in lowercase at least half the time: not acronyms ("aaualg") or names.
|
|
lowercase = {r: {w for w, (n, low, _) in layout.pt_uni(folder, r).items() if 2 * low >= n} for r in ("br", "pt")}
|
|
brazil, corpus, _, _ = layout.pt_words(folder, "br")
|
|
for w, n in brazil.items():
|
|
if n >= least * layout.PT_WEIGHT["leipzig"] and len(w) >= 2 and w in lowercase["br"] and w not in unigram \
|
|
and folded(w) not in twins \
|
|
and not capitals.joined(w, n / corpus, unigram, pair):
|
|
valid[w] = cost(n, corpus)
|
|
brazilian = len(valid)
|
|
portugal, corpus, _, _ = layout.pt_words(folder, "pt")
|
|
best = {}
|
|
for w, n in portugal.items():
|
|
if n > portugal.get(best.get(folded(w), ""), 0):
|
|
best[folded(w)] = w
|
|
for w, n in portugal.items():
|
|
if n >= PT_PORTUGAL_COUNT * layout.PT_WEIGHT["leipzig"] and len(w) >= 2 and w in lowercase["pt"] \
|
|
and w not in unigram and w not in valid \
|
|
and (folded(w) not in twins or best[folded(w)] == w) \
|
|
and not capitals.joined(w, n / corpus, unigram, pair):
|
|
valid[w] = cost(n, corpus)
|
|
print(f"pt: {brazilian:,} Brazilian and {len(valid) - brazilian:,} Portuguese spellings", flush=True)
|
|
write(output, valid)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
lang = sys.argv[1] if len(sys.argv) > 1 else ""
|
|
if lang == "en" and len(sys.argv) == 5:
|
|
english(*sys.argv[2:5])
|
|
elif lang in ("es", "de", "fr", "it", "nb", "pt") and len(sys.argv) in (5, 6):
|
|
least = int(sys.argv[5]) if len(sys.argv) == 6 else MIN_COUNT[lang]
|
|
if lang == "nb":
|
|
norwegian(sys.argv[2], sys.argv[3], sys.argv[4], least)
|
|
elif lang == "pt":
|
|
portuguese(sys.argv[2], sys.argv[3], sys.argv[4], least)
|
|
else:
|
|
books(lang, sys.argv[2], sys.argv[3], sys.argv[4], least)
|
|
else:
|
|
sys.exit(__doc__)
|