hex/ios/HEXShared/Spelling/HexWordList.swift
Ryan Vogel f5819f4c4c
English typing model: names, days, places and newer words (Claude, Monday, ChatGPT) (#2973)
* English typing model: SCOWL's names, days and places join the words

The English builder kept only the spellings SCOWL writes in lowercase, so
en.hextm (iPhone and Android, byte-identical) had no names at all. Swipe reads
only model words, so "Claude" (reported on X), "Monday", "Mary", "London" and
"Christmas" could never be swiped ("clause", "noonday", "marry", "kingdom",
"christenings"), and typos of them were never corrected to them. 4.84% of the
held-out sentences' words were such names; the swipe benchmark skipped them.

- build-typing-model.py (both copies): SCOWL's upper and proper-names lists
  (sizes <= 70) join, each word spelled with one capital first, 3+ letters, in
  lowercase, ranked by its Google Books count. MAX_WORDS en 90,000 -> 100,000,
  whose 400,000-word pool keeps every earlier word (90,000 would drop 8,379).
  en.hextm: 86,247 -> 100,110 words, 417,182 -> 371,883 pairs, same
  3,599,995 bytes. en.capitals (20,464 words) and en.valid rebuilt.
- The 589 bigram shards (323.8 GB) were re-read once over a superset of words;
  with the old rules those counts rebuild c23e9c54 and the old en.capitals and
  en.valid byte for byte. New model b5e83bc1, rebuilt again from the committed
  builder.
- A name the decoder corrects to takes its capital on both platforms
  ("mray" -> "Mary"): TypingWord (Android) and AutocorrectEngine (iOS) now
  capitalise English corrections as they did German's.
- Swipe: English drops the 4-nat rare-name cost (Android SwipeReader.ranked,
  iPhone SwipeTyping.ranked). It existed for the lowercase list's accidental
  names ("kent", "gs"); with real names at real counts it kept "Claude" behind
  "clause" half the time. Removed behavior: English rare names are no longer
  ranked 4 nats lower; other languages keep it. The iPhone test asserting that
  ranking now asserts decoder order for English.
- swipe-bench.py/SwipeReplay --outside: the 208 held-out words (666 swipes)
  1.0.5's model lacked are swiped and scored apart (swipe-outside-en.txt).

Verified (Android host JVM, Studio): quality-gate en 680 -> 583 word errors
(85.50% -> 87.57%), correct words changed 45 -> 48 (Adriano->Adrian x2,
Edmundo->Edmund x2, Liisa->Lisa; Gabor, Fadil now kept), critical 2/2.
Swipe old set typical 96.9 -> 96.8, neat 99.0 -> 99.0, sloppy 82.0 -> 81.4
(first word); the 666 lacked: 0 -> 54.2 / 55.9 / 44.4. Claude vs clause
(20 neat / 20 typical): 20/18 first, clause 20/20. Known trade: a swiped
"marry" gives "Mary" without a word before ("to marry": marry 19/20).
Android unit tests: 399 passed. iPhone gate and suite: pending (simboxes
blocked by Studio swap).

* English typing model: spellings beside the model, and newer words from the news

The model is lowercase and the capitals mechanisms give only a first capital
("Mary"), so "iPhone", "GitHub" or "ChatGPT" had no way to come out right, and
words newer than Google Books (1980-2019) were missing: a swiped "chatgpt"
read "chatbot", "openai" "penal", "iphone" "uphold".

- en.spellings (new, beside en.hextm on both platforms, byte-identical; 299
  lines, 4.6 KB): word<TAB>spelling, sorted by UTF-8 bytes, read in place on
  Android (Capitals.kt Spellings, TypingModel) and iPhone (HexWordList.text,
  AutocorrectEngine+Spellings). A listed word takes its spelling typed in
  lowercase, corrected to, swiped and in the strip; the iPhone strip also shows
  names with their capital. Android dictation keeps Whisper's capitals for
  listed words (KeyboardEngine, Whisper/SentenceEnds).
- build-typing-model.py (both copies): SCOWL's spellings with a capital inside
  that aren't acronyms join with the names (115 in the model: "iPhone",
  "PayPal"); then, after pairs are counted, words the vocabulary lacks from
  the Leipzig Corpora Collection's 2023-2025 English news (CC BY 4.0, pinned
  by URL, date, size, SHA-256 in ENGLISH_NEWS) that 100+ news sites use, 4+
  letters, not acronyms: 243 ("ChatGPT", "OpenAI", "TikTok", "offline"), at
  the count their news share stands for. Hex's own chat words keep no
  spelling ("wifi"). en-extra-words.tsv's "no brand names" rule is replaced.
- Credits: Android credits.txt, iPhone Acknowledgements and its doc.
- Removed behavior: "github" typed without your own words now becomes
  "GitHub" (the model's spelling); NeverSuggestTest expects that.

Why 4 letters: with 3, the news added "Eid", "Isa", "Ole", which took "did"
(x2), "is a" (x2) and "Oleg" (x3) in the gate.

Verified (Android host JVM, Studio): quality-gate en 583 -> 582 word errors
(87.59% fewer than raw taps; 680 before the PR), correct words changed
48 -> 48, critical 2/2. Swipe old set typical/neat/sloppy 96.8/99.0/81.4
(unchanged), the 666 1.0.5 lacked 54.2 -> 54.7 typical. ChatGPT, OpenAI,
GitHub, iPhone 20/20 neat and typical, YouTube 20/19. en.hextm f503d6d1 and
en.spellings 4d244e9b rebuilt from the committed builder. Android unit tests
399 passed. iPhone: build-for-testing succeeds on the Studio; gate and suite
pending (simboxes blocked by Studio swap).

* English typing model: names and newer words need four letters

The iPhone suite on the branch failed testThisIsATestSwipedWithASingleLetterBetween:
an "a" dragged a little too far and back typed "asa". A slid tap reads a word
that starts and ends on its key ("lol" on l), and SCOWL's three-letter names
added such words ("Asa", "Ada", "Ava", "Nan", "Ede"). Three-letter names also
took ordinary words in sloppy swipes ("the" -> "Tyr", "is" -> "Ira"), as
three-letter news words did in the gate ("did" -> "Eid").

- build-typing-model.py (both copies): NAME_LETTERS = 4 for SCOWL's names and
  the news words alike (replaces NEWS_LETTERS). Removed behavior: 138
  three-letter names ("Joe", "Amy", "Jan", "Aug") are no longer model words,
  so they can't be swiped; typed, they keep the capital en.capitals or the
  phone's dictionary gives them, as in 1.0.5. Spellings with a capital inside
  keep three letters ("iOS", "PhD").
- en.hextm 98c8da8f (100,357 words, 370,951 pairs, 3,599,997 bytes),
  en.capitals and en.valid rebuilt from the committed builder; en.spellings
  unchanged (4d244e9b).

Verified: Android quality-gate en 582 -> 582 word errors, 48 changed (680 and
45 before the PR); swipe old set typical/neat/sloppy 96.8/99.0/81.4 ->
96.9/99.0/81.7, the 666 1.0.5 lacked 54.7 -> 54.4 typical; Claude vs clause
20/18 of 20 unchanged; with no name penalty the old set now loses 0 typical
and 25 sloppy swipes (was 9 and 40). Android unit tests 399 passed.
iPhone (simbox, iPhone 18 Pro): typing-gate en 735 (1.0.5 model) -> 633 word
errors, 37 -> 35 changed, names capitalised 418 -> 421; full suite 1014
tests, 0 failures, 5 skipped (it failed 1 before this commit).
2026-11-27 12:27:16 -05:00

161 lines
7.7 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import Darwin
import Foundation
/// One of Hex's own sorted word lists beside a language's typing model, the same files Android
/// ships: `<code>.valid`, the real words outside the model (`build-valid-words.py`), and
/// `<code>.capitals`, how often the books write a word with a capital (`build-capitals.py`).
/// One lowercase NFC spelling per line, alone or followed by a tab and a number (a cost, a
/// percent), sorted by its UTF-8 bytes, newline-terminated. The file is memory-mapped read-only, like the `.hextm` models,
/// and searched in place by bisection: no copy and no set, so a 5 MB list costs only the clean
/// pages its lookups touch, which iOS can drop under pressure.
nonisolated final class HexWordList: @unchecked Sendable {
let byteCount: Int
private let base: UnsafePointer<UInt8>
init?(url: URL) {
let fd = open(url.path, O_RDONLY)
guard fd >= 0 else { return nil }
defer { close(fd) }
var info = stat()
guard fstat(fd, &info) == 0, info.st_size > 0 else { return nil }
let size = Int(info.st_size)
guard let mapped = mmap(nil, size, PROT_READ, MAP_PRIVATE, fd, 0), mapped != MAP_FAILED else { return nil }
let bytes = UnsafePointer(mapped.assumingMemoryBound(to: UInt8.self))
guard bytes[size - 1] == 10 else { munmap(mapped, size); return nil }
base = bytes
byteCount = size
}
deinit {
munmap(UnsafeMutableRawPointer(mutating: base), byteCount)
}
/// Whether the list has `word` (lowercase NFC, as the builder writes them): one bisection over
/// the mapped bytes, nothing allocated for a native string.
func contains(_ word: String) -> Bool {
line(of: word) != nil
}
/// The number after `word`'s tab (a `.capitals` percent, a `.valid` cost), or nil when the
/// list lacks the word or its line has none.
func value(of word: String) -> Int? {
guard let (end, next) = line(of: word), end < next else { return nil }
var value = 0
for i in (end + 1)..<next {
let digit = Int(base[i]) - 48
guard (0...9).contains(digit) else { return nil }
value = value * 10 + digit
}
return value
}
/// The text after `word`'s tab (a `.spellings` spelling), or nil when the list lacks the word
/// or its line has none.
func text(of word: String) -> String? {
guard let (end, next) = line(of: word), end < next else { return nil }
return String(decoding: UnsafeBufferPointer(start: base + end + 1, count: next - end - 1), as: UTF8.self)
}
/// Where `word`'s line ends (its tab or newline) and where its newline is.
private func line(of word: String) -> (end: Int, next: Int)? {
var word = word
return word.withUTF8 { key -> (Int, Int)? in
guard !key.isEmpty else { return nil }
var lo = 0, hi = byteCount
while lo < hi {
// The line holding the middle byte: back to its start, on to its tab or newline.
var start = (lo + hi) / 2
while start > lo, base[start - 1] != 10 { start -= 1 }
var end = start
while base[end] != 10, base[end] != 9 { end += 1 }
var next = end
while base[next] != 10 { next += 1 }
var order = 0
var k = 0
while order == 0, k < key.count, start + k < end {
order = Int(base[start + k]) - Int(key[k])
k += 1
}
if order == 0 { order = (end - start) - key.count }
if order == 0 { return (end, next) }
if order < 0 { lo = next + 1 } else { hi = start }
}
return nil
}
}
/// A language's list in the keyboard's bundle (`kind` "valid" or "capitals"), mapped once per
/// process; nil when the build has none, as `TypingDecoderModel.bundled` finds the model.
@MainActor static func bundled(_ language: String, _ kind: String = "valid") -> HexWordList? {
let name = language + "." + kind
if let cached = loaded[name] { return cached }
var url = Bundle.main.url(forResource: language, withExtension: kind)
if url == nil, let plugins = Bundle.main.builtInPlugInsURL,
let keyboard = Bundle(url: plugins.appendingPathComponent("HEXKeyboard.appex")) {
url = keyboard.url(forResource: language, withExtension: kind)
}
let list = url.flatMap { HexWordList(url: $0) }
loaded[name] = list
return list
}
@MainActor private static var loaded: [String: HexWordList?] = [:]
}
/// A language's own words: its typing model's and its `HexWordList`'s. Where Hex has both, they
/// alone say whether a spelling is a word, not the phone's dictionary, which iOS may not have
/// for the language or may have take any letters for one (iOS 27.2 simulator: `nb_NO`, `pl_PL`).
nonisolated struct HexOwnWords: Sendable {
/// A word the books write with a capital this often is a name: typed all lowercase it is no
/// word, so autocorrect gives it its capital ("paris" -> "Paris", "jean" -> "Jean"), as
/// `UITextChecker` does with a word it knows only capitalised (Android's `TypingWord`: 95).
static let nameShare = 95
let language: String
let model: TypingDecoderModel
let list: HexWordList
/// `<code>.capitals`, when the keyboard ships one: names and other words the books write with
/// a capital, with how often they do (50–100).
var capitals: HexWordList?
/// Whether `word` is one, case-folded ("Żółw" is "żółw"; lists are lowercase) and with ’ read
/// as '; a name typed all lowercase isn't ("paris"), its capitalised form is ("Paris"). The
/// list lookups allocate nothing; folding a word with a capital or a ’ copies it.
func knows(_ word: String) -> Bool {
guard !word.isEmpty else { return true }
let typedLower = !word.contains(where: \.isUppercase)
var lower = typedLower ? word : word.lowercased()
if lower.contains("\u{2019}") { lower = lower.replacingOccurrences(of: "\u{2019}", with: "'") }
let share = capitals?.value(of: lower)
if typedLower, lower.count >= 2, let share, share >= Self.nameShare { return false }
return model.index(of: lower) != nil || list.contains(lower) || share != nil
}
/// Whether `word`, typed all lowercase, is one the books capitalise only part of the time
/// (50–94%: "tom", "mary", also ordinary words or capped as such): the phone's dictionary,
/// where it works, decides whether it is a name (`SystemTextChecker.isWordValid`).
func mayBeName(_ word: String) -> Bool {
guard word.count >= 2, !word.contains(where: \.isUppercase), let share = capitals?.value(of: word) else { return false }
return share < Self.nameShare
}
}
@MainActor
extension AutocorrectEngine {
/// Gives this engine's spelling dictionary the decoder model's language's own words, when the
/// keyboard ships a list for it, or takes them away. Called whenever `decoder` changes.
func useOwnWords(_ model: TypingDecoderModel?) {
guard let system = checker as? SystemTextChecker else { return }
system.ownWords = model.flatMap { model in
HexWordList.bundled(model.language).map {
HexOwnWords(language: model.language, model: model, list: $0, capitals: HexWordList.bundled(model.language, "capitals"))
}
}
}
/// Whether this language has words to correct with: the phone's dictionary, or Hex's own
/// model for it. A missing system dictionary never switches a Hex model off.
var hasWords: Bool {
hasDictionary || decoder?.model.language == language.rawValue
}
}