hex/ios/HEXShared/FullKeyboard/AutocorrectEngine+Dictionaries.swift
Ryan Vogel 6776e90841
iOS keyboard: a word of your own in capitals is offered, never put in for a lowercase one; "i'm" takes its capital (#2391)
* iOS keyboard: a word of your own in capitals is offered, never put in for a lowercase one

What changed: Spatial autocorrect's space and Swipe typing no longer put in one of the
person's own words written with capitals after the first letter (all caps such as "DONT",
or capitals inside), from UILexicon (Contacts, text replacements) or words Hex learned, for
a word typed or swiped without such capitals. The strip still offers it. Space puts in the
next reading that clears the margin, or keeps what was typed; a swipe types the model's
lowercase word of the same letters when there is one ("in" for an own "IN", which takes the
model word's place in the swipe decoder), else its first ordinary reading. Caps lock, words
typed in capitals, names with only a first capital, and the vocabulary list's own spellings
("GitHub") behave as before.

Why: two days of Record typing logs from one tester (build 106/115). An own word in capitals
replaced "don't" three times ("dknt" -> "DONT"; reverted, re-picked or deleted) and three
swipes typed capitalised words from the same list instead of common words. Own words cost
11 nats in both decoders, and the English model prices contractions far lower than that
("don't" 14.4 nats), so the own word won. That model pricing is a separate data change.

Where: AutocorrectEngine+Distance (isOwnCapitals, decisionOfferingOwnCapitals,
readingsOfferingOwnCapitals); AutocorrectEngine.decoderDecision calls it (three lines
changed, none added: the file is at its cap); SwipeTyping.finish orders its readings.

Verified (iPhone 17 Pro simulator, iOS 27.2):
- New cases in AutocorrectEngineTests and FullKeyboardEngineTests fail on the base commit
  ("DONT ZORBIX", "HELO THE") and pass here; AutocorrectEngineTests, FullKeyboardEngineTests
  and SwipeDecoderTests pass (240 tests).
- The tester's touches replayed through the keyboard (792 words and swipes): with no own
  words, identical output for every word. With the five capitalised words Hex put in on his
  phone seeded as his own list: 9 outputs differ; 3 now match what he left ("don't" twice,
  "in"), 2 he had kept in capitals now come out without them (the bar offers them), 2 stay
  wrong (a sloppy swipe, a literal he protected), scorable word errors 38 -> 37 of 680.
- English, Spanish and German held-out gates (iOS replay of #2374's 2,000 sentences each):
  every output identical; en 5.91% WER (82.5% fewer than raw taps, 0.29% correct words
  changed), es 8.91% (77.8%, 0.20%, accents 94.1%), de 6.52% (83.3%, 0.12%), critical cases
  pass. English with 133 all-caps acronyms seeded as own words: 6.21% before and after
  (4 sentences differ, 2 better, 1 worse, 1 wrong either way), 0.31% changed both.

* iOS keyboard: "i'm", "i'll", "i've" and "i'd" typed with the apostrophe take the capital

What changed: with Autocorrect and Auto-capitalization on (the defaults), space after "i'm",
"i'll", "i've" or "i'd" typed with their apostrophe now puts in "I'm", "I'll", "I've", "I'd",
with a straight apostrophe or smart quotes' ’ alike, as "i", "im", "ill", "ive" and "id"
already took theirs. Auto-capitalization off still adds no capital ("i'm" stays), as for "i".

Why: a post on X said Hex "refuses to capitalize I's in sentences". With defaults on
origin/dev, real key taps through the key plane capitalised a lone "i" mid-sentence, at a
sentence start, before a comma, in fields with and without auto-capitalization and beside a
second language, and "im"/"ill"/"ive"/"id" too; but every apostrophe form stayed lowercase.
Nothing handled a token with an apostrophe in English, and with smart quotes the ’ the key
types ends the token, so the word was never seen whole.

Where: AutocorrectEngine+Dictionaries.pronounCapital reads them from the text before the
cursor; replacementOnSpace asks it after text replacements (one line changed, none added).
FullKeyboardEngine.finishWord now deletes, logs and records what the fix replaced
(fix.original), which equals the token in every case before this one.

Verified: a new AutocorrectEngineTests case fails on the base commit ("so i'm in and i'd go
i’ll say i’ve") and passes here; AutocorrectEngineTests, FullKeyboardEngineTests and
SwipeDecoderTests pass; the English, Spanish and German held-out gates give the same output
for every sentence (their scoring is case-blind, and no gate sentence changed).
2026-11-22 12:05:06 -05:00

219 lines
8.2 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 Foundation
/// Autocorrect's built-in word lists (`AutocorrectEngine`).
extension AutocorrectEngine {
/// Valid words where an apostrophe form exists, offered as a suggestion without clobbering the word.
static let suggestOnlyContractions: [String: String] = [
"ill": "I'll",
"id": "I'd",
"were": "we're",
"wed": "we'd",
"well": "we'll",
"its": "it's",
"lets": "let's",
"hell": "he'll",
"shell": "she'll",
]
/// Words a period after them makes an abbreviation ("approx.", "etc."): a period never
/// corrects them.
static let abbreviations: Set<String> = [
"approx", "appt", "apt", "assn", "asst", "ave", "blvd", "cf", "co", "corp", "dept", "dr",
"eg", "est", "etc", "fig", "govt", "ie", "inc", "jr", "lb", "lbs", "ltd", "misc", "mr",
"mrs", "ms", "mt", "no", "nr", "oz", "pp", "prof", "pt", "rd", "sr", "st", "vol", "vs", "wk", "yr",
]
/// Common chat & engineering shorthand that cautious autocorrect never rewrites.
static let shorthandAllowlist: Set<String> = [
"ok", "okay", "ty", "thx", "pls", "plz", "tmrw", "tbh", "idk", "imo", "imho",
"lol", "lmao", "omg", "brb", "btw", "afaik", "fyi", "nvm", "rn", "irl", "jk",
"np", "yw", "smh", "ikr", "ngl", "fr", "gg", "dm", "pr", "prs", "ci", "ui",
"ux", "ios", "macos", "api", "apis", "url", "urls", "json", "sql", "ssh", "cli",
"gpu", "cpu", "ram", "sdk", "hex", "wisp", "seer", "rune", "kit", "gonna",
"wanna", "gotta", "kinda", "sorta", "yeah", "yep", "nope", "nah", "hey", "yo",
]
/// ~125 unambiguous missing-apostrophe contractions and high-frequency QWERTY transpositions.
static let unambiguousFixes: [String: String] = [
// Pronoun & missing-apostrophe contractions
"i": "I",
"im": "I'm",
"ive": "I've",
"dont": "don't",
"cant": "can't",
"wont": "won't",
"didnt": "didn't",
"doesnt": "doesn't",
"isnt": "isn't",
"arent": "aren't",
"wasnt": "wasn't",
"werent": "weren't",
"hasnt": "hasn't",
"havent": "haven't",
"hadnt": "hadn't",
"wouldnt": "wouldn't",
"couldnt": "couldn't",
"shouldnt": "shouldn't",
"mustnt": "mustn't",
"neednt": "needn't",
"youre": "you're",
"youve": "you've",
"youd": "you'd",
"youll": "you'll",
"theyre": "they're",
"theyve": "they've",
"theyd": "they'd",
"theyll": "they'll",
"weve": "we've",
"shes": "she's",
"hes": "he's",
"itll": "it'll",
"thats": "that's",
"theres": "there's",
"heres": "here's",
"wheres": "where's",
"whos": "who's",
"whats": "what's",
"hows": "how's",
"whens": "when's",
"whys": "why's",
"aint": "ain't",
"yall": "y'all",
"oclock": "o'clock",
"maam": "ma'am",
"cmon": "c'mon",
"wouldve": "would've",
"couldve": "could've",
"shouldve": "should've",
"mightve": "might've",
"mustve": "must've",
// High-frequency QWERTY transpositions & fat-finger typos
"teh": "the",
"hte": "the",
"taht": "that",
"thta": "that",
"adn": "and",
"nad": "and",
"wiht": "with",
"iwth": "with",
"waht": "what",
"hwat": "what",
"wich": "which",
"whcih": "which",
"thier": "their",
"theri": "their",
"recieve": "receive",
"definately": "definitely",
"seperate": "separate",
"occured": "occurred",
"untill": "until",
"abotu": "about",
"baout": "about",
"becuase": "because",
"beacuse": "because",
"jsut": "just",
"jstu": "just",
"knwo": "know",
"konw": "know",
"tiem": "time",
"tmie": "time",
"shoudl": "should",
"hsould": "should",
"woudl": "would",
"owuld": "would",
"coudl": "could",
"oculd": "could",
"ahve": "have",
"hvae": "have",
"maek": "make",
"mkae": "make",
"thign": "thing",
"hting": "thing",
"peopel": "people",
"poeple": "people",
"workign": "working",
"goign": "going",
"doign": "doing",
"runnign": "running",
"comign": "coming",
"thnaks": "thanks",
"htanks": "thanks",
"plase": "please",
"pleaes": "please",
"yuor": "your",
"yoru": "your",
"yuo": "you",
"oyu": "you",
"fomr": "from",
"verry": "very",
"evrey": "every",
"realyl": "really",
"realy": "really",
"actualyl": "actually",
"probalby": "probably",
"tomorow": "tomorrow",
"tommorow": "tomorrow",
"tonihgt": "tonight",
"tongiht": "tonight",
"mesasge": "message",
"messgae": "message",
"keybaord": "keyboard",
"keboard": "keyboard",
"iphnoe": "iPhone",
"ipohne": "iPhone",
]
}
extension AutocorrectEngine {
/// French's elided words, which end in an apostrophe before the next word ("l'homme",
/// "qu'il", "jusqu'ici"), commonest first.
static let frenchElisions = ["l", "d", "j", "qu", "n", "c", "s", "m", "t", "jusqu", "lorsqu", "puisqu", "quoiqu", "quelqu", "presqu"]
/// A French word with an elision and a slip on either side of its apostrophe: the word after
/// it is corrected as a word of its own ("l'hpmme" -> "l'homme"), and a head that is no
/// elision becomes the commonest one a key away ("k'homme" -> "l'homme", "qi'il" ->
/// "qu'il"). Nil outside French, when neither side changes, for a word the dictionary knows
/// whole ("aujourd'hui"), and for an apostrophe without a letter on both sides ("l'").
func frenchElisionFix(for token: String) -> String? {
guard language.isFrench,
token.filter({ $0 == "'" }).count == 1, let mark = token.firstIndex(of: "'") else { return nil }
let head = String(token[..<mark])
let tail = String(token[token.index(after: mark)...])
guard !head.isEmpty, !tail.isEmpty, head.allSatisfy(\.isLetter), tail.allSatisfy(\.isLetter),
!checker.isWordValid(token) else { return nil }
var fixedHead = head
let lowerHead = head.lowercased()
if !Self.frenchElisions.contains(lowerHead) {
var best: (word: String, cost: Double)?
for word in Self.frenchElisions {
guard let cost = Self.singleEditKeyboardCost(from: lowerHead, to: word, language: layoutLanguage, letters: layoutLetters),
cost > 0, cost <= 0.65 else { continue }
if best == nil || cost < best!.cost { best = (word, cost) }
}
guard let best else { return nil }
fixedHead = Self.matchCase(of: head, onto: best.word)
}
var fixedTail = tail
if let word = ownReplacement(for: tail), word.allSatisfy(\.isLetter) {
fixedTail = word
}
guard fixedHead != head || fixedTail != tail else { return nil }
return fixedHead + "'" + fixedTail
}
/// "i'm", "i'll", "i've" and "i'd" typed with their apostrophe, at the end of `before`, take
/// the capital "i", "im" and "ive" take (`unambiguousFixes`): (what was typed, its fix), or nil.
/// Smart quotes type ’ there, which ends a token (`currentToken`), so the text is read whole.
func pronounCapital(before: String?) -> (typed: String, replacement: String)? {
guard isEnabled, hasDictionary, addsCapitals, language.usesEnglishFixes, let before else { return nil }
for end in ["m", "ll", "ve", "d"] {
for mark in ["'", "\u{2019}"] where before.hasSuffix("i" + mark + end) {
let typed = "i" + mark + end, previous = before.dropLast(typed.count).last
guard !(previous.map { $0.isLetter || $0.isNumber || $0 == "'" || $0 == "\u{2019}" } ?? false),
!suppressedInSession.contains(typed), !learning.rejected.contains(typed) else { return nil }
return (typed, "I" + mark + end)
}
}
return nil
}
}