hex/android/benchmark/typing/build-capitals.py
Ryan Vogel be78a0a4dd
Android typing: names and capitals, the strip, and your personal dictionary (#2251)
* Android typing: names stay as typed, and words take the capitals the books give them

Android's word models are lowercase and know only ~100k words, so a name
typed right was a typo to them: Spanish "tom" became "toma", "mary" became
"mar y", English "sami" became "swami", and nothing was ever capitalised
("mary", "monday", German "haus" stayed lowercase). iOS gets both from its
spelling dictionary, which knows names only with a capital (#2091), and
German's nouns from de.capitals (#2169).

Adds a capitals sidecar per model (<lang>.capitals: word<TAB>percent, sorted
UTF-8, memory-mapped and searched in place by Capitals.kt):
- de.capitals: iOS's file, byte for byte.
- en.capitals, es.capitals: new, from the same Google Books v3 1-grams
  (1980-2019, CC BY 3.0) as the models (build-capitals.py). Model words
  written with a capital at least half the time, plus names outside the model
  of three letters or more, capitalised at least 90% of the time and used at
  least once per million words. Two model words run together whose pair is
  ten times as common ("iwant", "apartir") are left out. A word that is also
  an ordinary lowercase word is held at 94%: in English one SCOWL spells in
  lowercase ("united", "china"), in Spanish a model word under 98% ("lima").

The engine uses it in two places:
- A listed name outside the model is a real word (TypingModel.known): the
  literal costs 15 instead of 22 and needs the 7-nat margin, as an English
  SCOWL word already did. Replaces "unknown = typo" for those names.
- On space, a word typed in lowercase that the books write with a capital at
  least 95% of the time takes it ("mary" -> "Mary"); in German also at 50-94%
  after an article or determiner ("das leben" -> "das Leben", "zu leben"
  stays), and a German word the decoder corrects to takes its capital
  ("hsus" -> "Haus"), as iOS's nounCapitalised.

Also: build.gradle.kts verifies the three new files' SHA-256 and stores
.capitals uncompressed so they map from the APK; credits.txt names them.

Verified on the Studio (API 35 emulator, installed debug APK; replay of
2,000 held-out sentences each), word errors before (#2245 head) -> after:
- English 818 (5.90%) -> 770 (5.55%); today's iOS 798 (5.75%)
- Spanish 1,342 (10.09%) -> 1,133 (8.52%); today's iOS 1,205 (9.06%)
- German 774 -> 774, Bokmål 654 -> 654 (capitals don't change words)
Sentences better/worse: English 47/2, Spanish 154/1. The installed APK loads
en/es/de.capitals from its assets (checked with app_process).
testDebugUnitTest: 21 tests, 0 failures, with iOS's name-capital and German
noun cases re-expressed against the shipped lists.

* Android typing: the strip says what space will do, and offers words before and between them

Ports iOS's strip and next-word rules (#2125 and the strip composition in
AutocorrectEngine.suggestions) into the engine, as two calls the keyboard can
show:

- TypingWord.strip(autocorrect) returns typed slots (Suggestion with a Kind):
  what was typed, then what space will put in (Kind.Fix, to highlight) or the
  likeliest candidate, then the runner-up; an unfinished word space leaves
  alone ("th", "beca") gets three candidates instead, so completions keep three
  slots. Candidates in iOS's order: suggest-only English contractions
  ("ill" -> "I'll", "well" -> "we'll"), the likeliest completion of a 1-3
  letter word after the word before (TypingModel.completionsAfter, by the word
  pairs), the decoder's readings (for three letters or more), then completions
  by frequency. Names show with their capital ("Monday"), English "i" as "I".
  Never what was typed again. Autocorrect off: no fix, no readings.
- predictions(before, capitalize) now gives three common first words at a
  sentence's start ("I", "The", "I'm"; "Yo", "El", "La"), clause starters
  after a comma ("I", "but", "and"), the word pairs' next words with the
  language's commonest words filling empty slots, and nothing after a handle,
  path, number, a second space or before a space is typed. Capitalised as
  shift would be (by default at a sentence's start). Replaces the old fill of
  the three commonest words, lowercase, everywhere.
- suggestions() and literalChip() keep their old behaviour until the keyboard
  moves to strip().

Benchmark: the replay counts strip hits as iOS's harness does (word at its
end, next word after the space, word after two letters), from the synthetic
sets' word ends (export_synthetic.py keeps them; synthetic_de_nb.py writes
them).

Verified on the Studio (API 35 emulator, installed debug APK, 2,000 held-out
sentences each). Word errors unchanged (English 770, Spanish 1,133, German
774, Bokmål 654). Strip hits before -> after (word / next / two letters):
- English 12,070 / 2,338 / 3,789 -> 13,180 / 2,349 / 4,390
  (iOS 13,253 / 2,287 / 3,235)
- Spanish 11,603 / 2,116 / 2,606 -> 12,407 / 2,110 / 3,236
  (iOS 12,364 / 2,073 / 2,901)
- German 12,204 / 1,679 / 5,026 -> 12,918 / 1,680 / 5,624
- Bokmål 11,172 / 2,160 / 4,380 -> 11,988 / 2,159 / 4,875
Next-word hits move by -6 (Spanish) and -1 (Bokmål) of ~11k: the common
words now fill as on iOS. Letter latency median 0.09 ms, p95 0.3 ms (the
readings are read on each letter for words of three letters or more).
testDebugUnitTest: 23 tests, 0 failures, with iOS's sentence-starter,
boundary, short-completion, strip and suggest-only cases re-expressed.

* Android typing: your personal dictionary's words and shortcuts

Reads Android's personal dictionary (UserDictionary.Words), the counterpart of
the UILexicon iOS reads (text replacements #2152-#2173, Contacts names), into
a new PersonalWords lexicon the engine uses:

- Text replacements: textReplacement(before) finds the longest shortcut that
  ends the text at a word boundary, digits and dots allowed ("ad2", "s.o"),
  after a bracket or comma ("(myem", "hi,myem"), never the end of a longer
  word ("xmyem"); a shortcut typed with a leading capital (not all caps)
  capitalises the phrase ("Brb" -> "Be right back"), stored capitals stay.
  replacement() and strip() apply a letters-only shortcut too, ahead of chat
  shorthand ("brb" stays only without a shortcut).
- Your words are read by the decoder beside the model's (Lexicon interface;
  SpatialDecoder.search takes either list): a slip in one is read as it
  ("zorbiz" -> "Zorbix"), and one typed right is a known word scored as a
  moderately common one (11 nats), as iOS's UserWords.
- Your word is never corrected into another, and typed in lowercase takes
  the capitals you gave it ("github" -> "GitHub", "kate" -> "Kate"), unless
  it is also an ordinary word ("will", "world" stay lowercase), as iOS's
  vocabulary (#2205) and withoutStrayCapital (#2173, #2218).
- The strip completes your words before the rest of the dictionary's, and
  your own words are offered even when the never-suggest list has them, as
  iOS offers UILexicon terms.

Android lets an enabled input method read the provider with no permission
(denied callers get an empty answer); PersonalWords.read filters entries to
the keyboard's language (and "no" for Bokmål) and reads at most 5,000.
Nothing is written. Gboard and Samsung keep their own lists, so many users
will have none.

Verified on the Studio (API 35 emulator): the replay is unchanged (no
personal words in it): English 770, Spanish 1,133, German 774, Bokmål 654
word errors, same strip hits. testDebugUnitTest: 25 tests, 0 failures, with
iOS's text-replacement, leading-capital, shorthand, own-word, stray-capital
and still-offered cases re-expressed against PersonalWords. Not verified:
reading the real provider (a shell process can't, only the enabled
keyboard), which needs the keyboard wiring.
2026-11-21 16:04:05 -05:00

184 lines
8.4 KiB
Python

#!/usr/bin/env python3
"""Build a keyboard language's capitals sidecar (<lang>.capitals) from Google Books Ngram v3
1-grams (2020-02-17, CC BY 3.0), the corpus its .hextm model was counted from.
python3 build-capitals.py en MODEL.hextm WORKDIR OUTPUT.capitals scowl-2020.12.07.tar.gz
python3 build-capitals.py es MODEL.hextm WORKDIR OUTPUT.capitals
Every shard is streamed (curl | gzip -dc, never stored) and its 1980-2019 counts of all-lowercase
tokens and of tokens with only the first letter capitalised are cached in WORKDIR, so a rerun
resumes and a rule change renders from WORKDIR/counts.tsv in seconds. Tagged tokens ("_") and
other casings are ignored.
Each line is word<TAB>percent (the capitalised share, rounded half up), lowercase, sorted by its
UTF-8 bytes, with a trailing newline, as German's de.capitals:
- a model word whose share is at least 50% over at least 40 uses (the keyboard capitalises
it when typed in lowercase from 95%);
- a word of three letters or more outside the model that the books capitalise at least 90% of
the time and use at least once per million words: names and places ("tom", "olivia",
"tokio"), which the keyboard then takes for real words, as iOS's spelling dictionary does, and
capitalises from 95%. Rarer ones ("goyo", "eby") are more often a typo of a common word. Two model
words run together whose pair is ten times as common ("iwant", "apartir") are left out.
The keyboard capitalises a word typed in lowercase only where iOS's dictionary would know it only
with a capital, so a word that is also an ordinary lowercase word is held at 94% (listed, never
capitalised on its own): in English, one SCOWL (sizes through 70, the lists en.valid comes from)
spells in lowercase ("united", "jersey", "china"); in Spanish, a model word under 98% ("lima",
"granada", "san").
"""
import hashlib, math, multiprocessing, os, re, struct, subprocess, sys, tarfile
BASE = "https://storage.googleapis.com/books/ngrams/books/20200217"
FILES = {"en": ("eng", 24), "es": ("spa", 3)}
LETTERS = {"en": "a-z", "es": "a-zñáéíóúü"}
FIRST_YEAR, LAST_YEAR = 1980, 2019
MIN_TOTAL = 40
SOMETIMES = 50
NAME_SHARE = 90
NAME_PER_MILLION = 1
ALWAYS, HELD = 95, 94
JOINED = 10
MODEL_ALWAYS = {"en": 95, "es": 98}
SCOWL_SHA256 = "5587667caa20c4891390c2d42dbb4d5c4c3f41bee77af1457ece3ba23fb859cc"
def scowl_lowercase(path):
"""SCOWL's lowercase spellings, sizes through 70."""
assert hashlib.sha256(open(path, "rb").read()).hexdigest() == SCOWL_SHA256
words = set()
with tarfile.open(path) 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:
words.update(w for w in archive.extractfile(entry).read().decode("latin-1").split() if w == w.lower())
return words
def model_words(path):
"""The model's words with -ln P(word), and its stored pairs (first, second) with -ln P(second | first)."""
data = open(path, "rb").read()
version, words, pairs, blob, alphabet = struct.unpack_from("<IIIII", data, 4)
assert data[:4] == b"HXTM" and version == 3
letters = {}
for i in range(alphabet):
scalar, code, _, _ = struct.unpack_from("<IBBH", data, 28 + 8 * i)
letters[code] = chr(scalar)
offsets_at = 28 + 8 * alphabet
rows_at = offsets_at + 4 * (words + 1) + words
rows_at += -rows_at % 4
blob_at = rows_at + 4 * (words + 1) + 4 * pairs + pairs
assert blob_at + blob == len(data)
offsets = struct.unpack_from(f"<{words + 1}I", data, offsets_at)
spelled = ["".join(letters[b] for b in data[blob_at + offsets[i]:blob_at + offsets[i + 1]]) for i in range(words)]
unigram = {spelled[i]: data[offsets_at + 4 * (words + 1) + i] / 8 for i in range(words)}
rows = struct.unpack_from(f"<{words + 1}I", data, rows_at)
seconds_at = rows_at + 4 * (words + 1)
seconds = struct.unpack_from(f"<{pairs}I", data, seconds_at)
costs_at = seconds_at + 4 * pairs
pair = {(spelled[a], spelled[seconds[k]]): data[costs_at + k] / 8 for a in range(words) for k in range(rows[a], rows[a + 1])}
return unigram, pair
def joined(word, share, unigram, pair):
"""Whether `word` is two model words run together, as scanned books (and typists) do ("Iwant",
"apartir"): the stored pair is at least JOINED times as common as the word itself (`share` of
the corpus). Those are no names."""
best = 0.0
for k in range(1, len(word)):
a, b = word[:k], word[k:]
if (a, b) in pair:
best = max(best, math.exp(-unigram[a] - pair[(a, b)]))
return best >= JOINED * share
def count_shard(job):
lang, index, url, work = job
out = os.path.join(work, os.path.basename(url) + ".tsv")
if os.path.exists(out):
return out
letters = LETTERS[lang]
token_re = re.compile(f"^[{letters.upper()}{letters}]?[{letters}]+$".encode("utf-8"))
download = subprocess.Popen(["curl", "-sSfL", "--http1.1", "--retry", "8", "--retry-all-errors", url], stdout=subprocess.PIPE)
unzip = subprocess.Popen(["gzip", "-dc"], stdin=download.stdout, stdout=subprocess.PIPE, bufsize=1 << 20)
download.stdout.close()
counts = {}
for line in unzip.stdout:
tab = line.find(b"\t")
token = line[:tab]
if b"_" in token or not token_re.match(token):
continue
total = 0
for field in line[tab + 1:].split(b"\t"):
year, count, _ = field.split(b",", 2)
if FIRST_YEAR <= int(year) <= LAST_YEAR:
total += int(count)
if total >= 4:
counts[token] = counts.get(token, 0) + total
unzip.wait(); download.wait()
if unzip.returncode or download.returncode:
raise RuntimeError(f"{url}: curl {download.returncode}, gzip {unzip.returncode}")
with open(out + ".part", "wb") as f:
for token, count in counts.items():
f.write(token + b"\t" + str(count).encode() + b"\n")
os.replace(out + ".part", out)
print(f"[{index}] {os.path.basename(url)}: {len(counts):,} tokens", flush=True)
return out
def main():
lang, model, work, output = sys.argv[1:5]
lowercase = scowl_lowercase(sys.argv[5]) if lang == "en" else set()
os.makedirs(work, exist_ok=True)
merged = os.path.join(work, "counts.tsv")
if not os.path.exists(merged):
code, n = FILES[lang]
jobs = [(lang, i, f"{BASE}/{code}/1-{i:05d}-of-{n:05d}.gz", work) for i in range(n)]
with multiprocessing.Pool(4) as pool:
paths = pool.map(count_shard, jobs, chunksize=1)
low, cap = {}, {}
for path in paths:
for line in open(path, "rb"):
token, count = line.rstrip(b"\n").split(b"\t")
word = token.decode("utf-8")
key = word.lower()
target = low if word == key else cap
target[key] = target.get(key, 0) + int(count)
with open(merged + ".part", "w", encoding="utf-8") as f:
for key in set(low) | set(cap):
f.write(f"{key}\t{low.get(key, 0)}\t{cap.get(key, 0)}\n")
os.replace(merged + ".part", merged)
unigram, pair = model_words(model)
words = set(unigram)
corpus = 0
for line in open(merged, encoding="utf-8"):
_, lo, ca = line.rstrip("\n").split("\t")
corpus += int(lo) + int(ca)
rows = []
for line in open(merged, encoding="utf-8"):
key, lo, ca = line.rstrip("\n").split("\t")
lo, ca = int(lo), int(ca)
total = lo + ca
if len(key) < 2 or total < MIN_TOTAL:
continue
share = (200 * ca + total) // (2 * total)
if key in words:
if share < SOMETIMES:
continue
if share < MODEL_ALWAYS[lang]:
share = min(share, HELD)
elif (len(key) < 3 or share < NAME_SHARE or total * 1_000_000 < NAME_PER_MILLION * corpus
or joined(key, total / corpus, unigram, pair)):
continue
if key in lowercase:
share = min(share, HELD)
rows.append((key, share))
rows.sort(key=lambda r: r[0].encode("utf-8"))
data = "".join(f"{k}\t{p}\n" for k, p in rows).encode("utf-8")
open(output, "wb").write(data)
inside = sum(1 for k, _ in rows if k in words)
print(f"{len(rows):,} words ({inside:,} in the model, {len(rows) - inside:,} names outside it), "
f"{len(data):,} bytes; {hashlib.sha256(data).hexdigest()}")
if __name__ == "__main__":
main()