mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-28 13:02:21 +01:00
* iOS: punctuation after a word fixes its typo, as space does
X (Erick): "If I add punctuation after a typo autocorrect does not fix the typo."
Only space ran autocorrect, so "teh," or "recieve." kept the typo. Now a mark
that closes a word (, . ! ? ; : ) and ") runs the same correction as space,
from the 123 page or a 123 slide, and goes in after the fix ("the,"), as the
system keyboard does. One backspace right after takes back the mark and the fix
("teh"), the same as after a space, and the kept word isn't corrected again.
A period never corrects a common abbreviation (approx., etc., dept.) and a
swiped word is never corrected (it is a reading, not a typo).
Verified: new FullKeyboardEngineTests (testPunctuationAfterATypoFixesItFirst,
testPunctuationNeverChangesASwipedWord) pass on an iOS 27.2 simulator. Autocorrect
benchmark (Spatial autocorrect on): a new 300-sentence punctuation set goes from
12.40% to 7.10% WER and 96 to 177 sentences exactly right; the held-out sets are
unchanged (EN 5.94%, ES 8.61% WER; 79 and 23 correct words broken).
* iOS: contractions typed without the apostrophe follow the words around them
X (Erick): "the id in this didn't autocorrect to I'd". Words that are real words
both with and without an apostrophe (id/I'd, ill/I'll, hell/he'll, shell/she'll,
wed/we'd, lets/let's, well/we'll) were only offered in the strip and never
changed. Now English picks between them with the typing model's word pairs,
scoring a contraction as the words it stands for ("I'd like" as "I would like"),
which the pairs know far better than the contraction itself:
- At the word's own space, when the word before makes it clear ("yes id" ->
"yes I'd", "id like" at a sentence start -> "I'd", "the id" stays).
- At the next word's space or closing mark, the word before is revised when the
next word decides it ("well see" -> "we'll see", "well done" stays), as the
system keyboard does. A contraction whose last word ("will", "would", "had",
"us") the next word never follows is evidence against it, so "till hell
freezes" keeps "hell".
One backspace right after a revision puts back both words as typed and keeps
them. Words you kept, learned words, Contacts names and other languages are
never changed, and nothing changes without the bundled typing model.
"were/we're" stays suggest-only: the pairs can't tell them apart. Undo now
records each changed word (AppliedCorrection.changes), so a revision's undo
keeps both words; a single correction behaves as before.
Margins, the sentence-start bonus (3 nats) and the missing-follower penalty
(5 nats) were tuned on Tatoeba sentences outside the held-out sets.
Verified: AutocorrectEngineTests (testContractionsWithoutTheApostropheFollow
TheWordsAroundThem, testOneBackspaceTakesARevisionBack) and the rest of
AutocorrectEngineTests and FullKeyboardEngineTests pass (113 tests, iOS 27.2
simulator). Benchmark: EN held-out WER 5.94% -> 5.72% with correct words broken
79 -> 79; ES unchanged (8.61%, 23); the contraction set 7.29% -> 5.61%; engine
p95 per letter tap 2.5 ms.
* iOS: its/it's, your/you're, there/their/they're and then/than follow the context
X (Justin): "It doesn't seem to understand grammar. Its vs it's for instance."
Autocorrect never chose between words that sound alike, so "its a nice day",
"your welcome", "their is", "more then that" stayed wrong. These groups now join
the contraction groups from the previous change and are chosen by the typing
model's word pairs at the word's own space or, when the word before can't tell,
revised at the next word's ("its a" -> "it's a", "i think its broken" -> "I think
it's broken", "they lost there keys" -> "they lost their keys", "and than we" ->
"and then we"), with the same undo: one backspace puts back what you typed.
"the dog wagged its tail" and "on its way" stay.
"it's", "you're" and "they're" are scored as "it is"/"it has", "you are", "they
are". The missing-follower penalty now applies only after "will", "would", "had"
and "us": the pairs rarely list the adjectives after "are" ("you're funny"), so
it broke right words there. A word you typed with your own apostrophe is never
changed or revised. The next-word margin for a change of letters (their/there,
then/than) is 3 nats, tuned with the others on Tatoeba sentences outside the
held-out sets.
Verified: AutocorrectEngineTests.testSoundAlikeWordsFollowTheWordsAroundThem and
the rest of AutocorrectEngineTests and FullKeyboardEngineTests pass (114 tests,
iOS 27.2 simulator). Benchmark: EN held-out WER 5.72% -> 5.48% with correct
words broken 79 -> 79; ES unchanged (8.61%, 23); a 200-sentence set with the
wrong homophone typed 14.08% -> 5.86% and one with the right one 6.33% -> 4.08%;
engine p95 per letter tap 2.3 ms.
* iOS: a space tapped as the letter above the space bar splits the words
X (Erick): "Auto correct does not separate two words like apple does
(consistently)." Spatial autocorrect read a letter tap as a missed space only
when it landed below the bottom row's centre line, so "ofbthe", "uscto" or
"oncthe" with the c, v, b or n hit on its upper half stayed one word. The system
keyboard turns "of" + b + "the" into "of the" wherever on the b the tap lands,
its centre included (black-box, iOS 27.2 simulator).
The decoder now knows where the space bar is (TypingDecoder.Keys.space, both
bars as on the unsplit keyboard), and a tap on the bottom row's upper half above
the bar may be a space, priced by the bar's Gaussian likelihood against the
row's (spaceTapCost 5 + spaceTapWeight 0.25 x the difference, in nats). There
both halves must be exactly the letters typed, so an unknown name's middle
letter is never a space with slips around it ("rima" stayed "rima"; without
that rule it became "to a"). Taps below the centre line keep the old reading and
cost. Spanish keeps only the old reading: its one- and two-letter words made
these splits too cheap ("vaxes" -> "va es") and they fixed nothing there. A
missed space after English "i" ("iwant") now gives "I want", as "i" alone does.
Tuned on the dev and targeted sets (held-out sets checked only after).
Verified: AutocorrectEngineTests.testASpaceTappedAsALetterAboveTheSpaceBarOr
MissedSplitsTheWords plus AutocorrectEngineTests, FullKeyboardEngineTests,
KeyboardLayoutTests and SwipeDecoderTests pass (165 tests, iOS 27.2 simulator).
Benchmark: EN held-out WER 5.48% -> 5.47% (correct words broken 79 -> 79); ES
unchanged (8.61%, 23); 300 sentences with a merged pair 9.73% -> 7.40%; engine
p95 per letter tap 1.9 ms.
* iOS: a space tapped at the space bar's edge for a letter joins the words
X (Justin): "Space bar accidental taps or lack of taps don't seem to be factored
in." A letter tap that landed on the space bar typed a space, and nothing ever
joined the two halves ("deli ate", "num er"). The system keyboard (black-box,
iOS 27.2 simulator) merges them at the next word's space when the space tap was
near the bar's top edge ("deli" + space + "ate" -> "Delicate", "a out" ->
"About", "so gs" -> "Songs"), and not when it was well inside the bar.
The engine now remembers the finished word's taps and where its space was
tapped. At the next word's space or closing mark, TypingDecoder.merge reads the
first word's taps, the space tap as a letter on the row above and the second
word's taps as one word; it replaces the two words when it beats them by the
usual margins (7 nats when both are words, 2 otherwise) and the tap was within
mergeReach (3 nats: the row at most that much less likely than the bar under
the space bar's Gaussian, about its top fifth, a little deeper than the system
keyboard). One backspace right after puts back both words and keeps the second.
A merged or split word is remembered as it reads, without taps. Words you kept,
learned words, shorthand, Contacts names and apostrophes are never joined. The
space tap's place now reaches typeSpace (as on the unsplit keyboard).
mergeReach was tuned on the dev and targeted sets (held-out checked after).
Verified: AutocorrectEngineTests.testASpaceTappedAtTheSpaceBarsEdgeForALetter
JoinsTheWords plus AutocorrectEngineTests and FullKeyboardEngineTests pass (120
tests, iOS 27.2 simulator). Benchmark: EN held-out WER 5.47% -> 5.23%, ES 8.61%
-> 8.34%, correct words broken 79 -> 79 and 23 -> 23; 200 sentences with a
letter tapped on the space bar 29.57% -> 16.04%; engine p95 1.9 ms per letter,
0.06 ms per space.
* iOS: no stray capitals from swiped words
X (Eric Jung): "the swipe keyboard has random auto capitalization of words."
Reproduced by swiping 600 held-out sentences word by word through the engine
with the swipe benchmark's finger models. Shift and auto-capitalization around a
swipe were right in every sequence tried (after a period, comma, return, delete,
a strip pick, a host text-change, one-shot shift and caps lock); the capitals
came from the readings themselves:
- The typing model's lowercase word list holds names and abbreviations ("gs",
"ut", "om", "kent"), which the dictionary knows only capitalised, so a loose
swipe of "he" or "it" went in as "Gs" or "Ut" mid-sentence. Such a reading now
costs 4 nats more unless it is common (the model's ~2,500 commonest words:
"york", "english") or one of your own words (Contacts names keep theirs).
The check is shared with the casing (FullKeyboardEngine.swipeReadsAsName) and
applied after decoding, on the main thread, for the swipe and its preview.
- "I'm", "I'd" and "I've" had one fixed cost whatever came before ("with us I'm
Boston"). A contraction is now as much likelier after the word before as its
first word is (SwipeDecoder.ExtraWords.heads, "i" for "I'm", "do" for
"don't"), 3 nats more when the model never has that pair.
Verified: FullKeyboardEngineTests.testASwipeMidSentenceGetsNoStrayCapital plus
AutocorrectEngineTests, FullKeyboardEngineTests and SwipeDecoderTests pass (128
tests, iOS 27.2 simulator). Swipe probe (600 held-out sentences, 3,986 words):
typical fingers words right 3,569 -> 3,578, stray mid-sentence capitals 1 -> 2
(one "I'd" for "if"), contractions right 171 -> 180 of 216; sloppy fingers
2,873 -> 2,888, stray capitals 18 -> 6, contractions 137 -> 145.
* iOS: a space at the bar's edge joins words only when space wouldn't fix them alone
Follow-up to "a space tapped at the space bar's edge for a letter joins the
words" (a005d926). The merge weighed one word against the two words exactly as
typed, so a second half with a slip counted as an unknown word and lost:
"i" + edge space + "dkdnt" became "Obedient", where space turns "dkdnt" into
"didn't" on its own. The two words are now scored as space would leave them:
each as typed or its likeliest reading of its own taps, the second after the
first's.
Verified: AutocorrectEngineTests (testASpaceTappedAtTheSpaceBarsEdgeForALetter
JoinsTheWords now also types "i" + edge space + "didnt" -> "I didn't") and
FullKeyboardEngineTests pass (121 tests, iOS 27.2 simulator). Benchmark: the
broken word on the homophone set is back (correct words broken 4 -> 3); EN
held-out WER 5.23% -> 5.24% (726 -> 727 edits, broken 79), ES unchanged (8.34%,
23), letter-on-space-bar set 16.04% -> 16.38%; engine p95 1.8 ms per letter.
* iOS: a closing mark from the 123 page reads the word's taps
Follow-up to "punctuation after a word fixes its typo, as space does"
(fb6200df). Found in a live check in Messages: "ofthe." became "Oft he." where
space gives "of the" (and the system keyboard "Of the."). Tapping 123 rebuilds
the layout, and off the letters page TypingDecoder.Keys(layout:) is nil, so by
the time the mark finished the word Spatial autocorrect had no keys and the
dictionary's guess was used. The letters page's keys now stay while another page
shows; they are where the word was typed.
Verified: AutocorrectEngineTests (the split test now also types "ofthe" + 123
+ "." -> "of the.") and FullKeyboardEngineTests pass (121 tests, iOS 27.2
simulator). Benchmark: the 300-sentence punctuation set 6.83% -> 3.94% WER,
sentences exactly right 179 -> 230; held-out sets unchanged (EN 5.24%, ES
8.34%; broken 79, 23).
* iOS tests: the space-bar merge test types with the next-letter odds on
testASpaceTappedAtTheSpaceBarsEdgeForALetterJoinsTheWords ran without the
typing model's next-letter odds, which the keyboard always has, and there "a" +
edge space + "out" joined into "about"; with them, as in a live check in
Messages, the two words stay (the 7-nat margin for joining two real words). The
test now sets letterOdds and types "ha" + edge space + "ded" -> "handed", which
joins both ways and on the system keyboard. No code change.
Verified: AutocorrectEngineTests and FullKeyboardEngineTests pass (121 tests,
iOS 27.2 simulator).
526 lines
26 KiB
Swift
526 lines
26 KiB
Swift
import CoreGraphics
|
|
import Foundation
|
|
|
|
/// Experiment (Swipe typing): reads a finger's path across the letter keys as a word.
|
|
///
|
|
/// A shape-matching decoder after SHARK2 (Kristensson and Zhai, 2004) and the template
|
|
/// matching of Gboard's published gesture decoders, written for Hex:
|
|
/// 1. The path is resampled to evenly spaced points in key pitches (a key's width plus a
|
|
/// gap across, a row's height plus a gap down), so a slip of half a key counts the same
|
|
/// either way.
|
|
/// 2. Words come from the typing model's word list, which is sorted letter by letter: the
|
|
/// words starting on a key near where the finger went down are one range of it per
|
|
/// letter. Of those, only words ending on a key near where it lifted, with every key near
|
|
/// the path and an ideal path (the polyline through their keys' centres) about as long,
|
|
/// are scored.
|
|
/// 3. Each is scored on where its ideal path runs against the gesture (location: a quick
|
|
/// point-by-point pass, then dynamic time warping for the best few, which follows a
|
|
/// finger that hurries and slows), on its shape alone (both paths moved to one centre
|
|
/// and size), and on how near the finger went down and lifted to its first and last keys,
|
|
/// 4. and weighed with the model's frequency of the word after the word before.
|
|
///
|
|
/// Nothing is built ahead or kept: each swipe reads the memory-mapped model in place
|
|
/// (`TypingDecoderModel.withCodes`), so the decoder holds no memory between swipes.
|
|
nonisolated struct SwipeDecoder: Sendable {
|
|
/// Tuned on synthetic swipes of the autocorrect benchmark's held-out dev sentences
|
|
/// (English and Spanish; clean, neat, typical and sloppy fingers; experiment folder
|
|
/// 2026-11-20-hex-swipe-typing), never on its test sentences.
|
|
struct Parameters: Equatable, Sendable {
|
|
/// Points the gesture and each word's ideal path are resampled to.
|
|
var samples = 32
|
|
/// Keys this many pitches from where the finger went down (lifted) may start (end)
|
|
/// the word: the nearest few.
|
|
var startRadius = 1.6
|
|
var endRadius = 2.1
|
|
var maxStartKeys = 4
|
|
var maxEndKeys = 8
|
|
/// Every key of a word passes at most this far from the path (pitches).
|
|
var nearRadius = 1.5
|
|
/// How much shorter or longer than the gesture a word's ideal path may be.
|
|
var minLengthRatio = 0.4
|
|
var maxLengthRatio = 1.8
|
|
/// How far from its first and last keys' centres a finger goes down and lifts: most
|
|
/// within the first spread, the rest (`stray`) within the wider second, so a near
|
|
/// miss costs much and a far one no more than the path's shape can make up.
|
|
var startSigma = 0.3
|
|
var endSigma = 0.3
|
|
var startStraySigma = 0.8
|
|
var endStraySigma = 0.9
|
|
var stray = 0.25
|
|
/// Nats per mean squared pitch between the paths, and per mean squared distance
|
|
/// between their shapes (each scaled to a unit box).
|
|
var locationWeight = 40.0
|
|
var shapeWeight = 60.0
|
|
/// Weight of the word model's cost, -ln P(word | word before).
|
|
var lmWeight = 1.1
|
|
/// Words of the quick pass the aligned pass scores again.
|
|
var shortlist = 80
|
|
/// Past this many words, only the likeliest by how near their keys lie to the path
|
|
/// (and their frequency) get the quick pass, which keeps a long, loose swipe fast.
|
|
var prefilter = 1500
|
|
/// How far (a share of the samples) the aligned pass may run ahead or behind.
|
|
var band = 0.1
|
|
/// The shortest path read as a swipe (pitches).
|
|
var minimumLength = 0.6
|
|
/// A contraction ("I'm") whose first word ("I") never follows the word before in the
|
|
/// model's pairs costs this much more: those first words follow thousands of words, so
|
|
/// a missing pair is evidence against it ("with us in", not "with us I'm").
|
|
var contractionMissingPair = 3.0
|
|
|
|
/// -ln of a point landing `squared` (pitches²) from a key's centre, under the mixture
|
|
/// of a tight spread and a stray one; 0 at the centre.
|
|
func cost(_ squared: Double, sigma: Double, stray strayingSigma: Double) -> Double {
|
|
let near = (1 - stray) / (sigma * sigma)
|
|
let far = stray / (strayingSigma * strayingSigma)
|
|
let density = near * exp(-squared / (2 * sigma * sigma)) + far * exp(-squared / (2 * strayingSigma * strayingSigma))
|
|
return log((near + far) / max(density, .leastNormalMagnitude))
|
|
}
|
|
}
|
|
|
|
/// The cost (-ln P) of a common English contraction ("isn't", "we're"), about a word ranked
|
|
/// 1,500th: Google Books splits contractions ("do n't"), so the model's counts for them
|
|
/// are far too low.
|
|
static let contractionCost = 7.5
|
|
|
|
/// The cost of English contraction `word` by how often a chat uses it: the commonest ("I'm",
|
|
/// "don't", "it's") like a word ranked about 300th, common ones at `base`, the rest ("he'll",
|
|
/// "ma'am") about 10,000th.
|
|
static func costOfContraction(_ word: String, base: Double = contractionCost) -> Double {
|
|
let lower = word.lowercased()
|
|
if commonestContractions.contains(lower) { return base - 1.5 }
|
|
if commonContractions.contains(lower) { return base }
|
|
return base + 2
|
|
}
|
|
|
|
private static let commonestContractions: Set<String> = [
|
|
"i'm", "don't", "it's", "i'll", "can't", "that's", "didn't", "you're", "i've", "doesn't",
|
|
]
|
|
private static let commonContractions: Set<String> = [
|
|
"isn't", "there's", "let's", "won't", "what's", "he's", "she's", "wasn't", "i'd", "we're",
|
|
"they're", "haven't", "couldn't", "wouldn't", "aren't", "you'll", "we'll", "shouldn't", "you've",
|
|
]
|
|
/// The cost of one of your own words (as Spatial autocorrect's `userWordCost`).
|
|
static let ownWordCost = 11.0
|
|
|
|
struct Candidate: Equatable, Sendable {
|
|
/// The word as the model spells it: lowercase, with its accents and apostrophes.
|
|
var text: String
|
|
var cost: Double
|
|
}
|
|
|
|
struct Reading: Equatable, Sendable {
|
|
/// Best first.
|
|
var candidates: [Candidate]
|
|
/// Words that passed the key filters and were scored.
|
|
var scored: Int
|
|
}
|
|
|
|
/// Words read beside the model's, each with its own cost (-ln P(word)): words the model
|
|
/// lacks or barely counts, such as English contractions (Google Books splits "don't" into
|
|
/// "do n't", so its "don't" is as rare as "tom"), and your own words.
|
|
struct ExtraWords: Sendable {
|
|
private(set) var codes: [[UInt8]] = []
|
|
private(set) var texts: [String] = []
|
|
private(set) var costs: [Double] = []
|
|
/// The model's index of the same word, for its pairs; nil when it lacks it.
|
|
private(set) var modelIndex: [Int?] = []
|
|
/// A contraction's first word in the model ("i" for "I'm", "do" for "don't"), whose
|
|
/// pairs weigh it after the word before; nil for other words.
|
|
private(set) var heads: [Int?] = []
|
|
|
|
init() {}
|
|
|
|
/// `words` as you'd see them ("I'm", "don't"), each with `cost` unless the model's
|
|
/// own is lower; a word with a letter the model lacks is left out, and a repeat once.
|
|
init(_ words: [String], cost: Double, model: TypingDecoderModel) {
|
|
add(words, cost: cost, model: model)
|
|
}
|
|
|
|
init(_ words: [String], cost: (String) -> Double, model: TypingDecoderModel) {
|
|
add(words, cost: cost, model: model)
|
|
}
|
|
|
|
var isEmpty: Bool { texts.isEmpty }
|
|
var count: Int { texts.count }
|
|
|
|
mutating func add(_ words: [String], cost: Double, model: TypingDecoderModel) {
|
|
add(words, cost: { _ in cost }, model: model)
|
|
}
|
|
|
|
mutating func add(_ words: [String], cost: (String) -> Double, model: TypingDecoderModel, contractions: Bool = false) {
|
|
var seen = Set(codes)
|
|
for word in words {
|
|
guard word.count >= 2, let encoded = model.encode(word.lowercased()), seen.insert(encoded).inserted else { continue }
|
|
codes.append(encoded)
|
|
texts.append(word)
|
|
costs.append(cost(word))
|
|
modelIndex.append(model.index(ofCodes: encoded))
|
|
heads.append(contractions ? Self.head(of: word.lowercased()).flatMap { model.index(of: $0) } : nil)
|
|
}
|
|
}
|
|
|
|
/// A contraction's first word: "do" for "don't", "i" for "I'm".
|
|
static func head(of contraction: String) -> String? {
|
|
if contraction.hasSuffix("n't") { return String(contraction.dropLast(3)) }
|
|
guard let apostrophe = contraction.firstIndex(of: "'") else { return nil }
|
|
return String(contraction[..<apostrophe])
|
|
}
|
|
}
|
|
|
|
let model: TypingDecoderModel
|
|
var parameters: Parameters
|
|
/// Words and two-word expressions never offered (`OffensiveWords`), as for Spatial
|
|
/// autocorrect: never read from a swipe.
|
|
var neverSuggest = TypingDecoder.NeverSuggest()
|
|
var extraWords = ExtraWords() {
|
|
didSet { extraIndices = Set(extraWords.modelIndex.compactMap { $0 }) }
|
|
}
|
|
/// The model's words that `extraWords` also has, read only as extra words.
|
|
private var extraIndices: Set<Int> = []
|
|
|
|
init(model: TypingDecoderModel, parameters: Parameters = Parameters()) {
|
|
self.model = model
|
|
self.parameters = parameters
|
|
}
|
|
|
|
/// The likeliest words for a swipe along `path` (the touch's points, first to last, in
|
|
/// the keys' coordinates), best first; empty when it can't be read as one.
|
|
func decode(_ path: [CGPoint], keys: TypingDecoder.Keys, previous: String? = nil, limit: Int = 4) -> [Candidate] {
|
|
read(path, keys: keys, previous: previous, limit: limit).candidates
|
|
}
|
|
|
|
func read(_ path: [CGPoint], keys: TypingDecoder.Keys, previous: String? = nil, limit: Int = 4) -> Reading {
|
|
let p = parameters
|
|
let none = Reading(candidates: [], scored: 0)
|
|
let pitch = Vec(x: Double(keys.pitch.width), y: Double(keys.pitch.height))
|
|
guard pitch.x > 0, pitch.y > 0, path.count >= 2, limit > 0, p.samples >= 4 else { return none }
|
|
let grid = KeyGrid(keys, model: model, pitch: pitch)
|
|
guard grid.centres.count >= 2, grid.centres.count <= 64 else { return none }
|
|
guard let gesture = Gesture(path, pitch: pitch, samples: p.samples), gesture.length >= p.minimumLength,
|
|
let start = gesture.raw.first, let end = gesture.raw.last else { return none }
|
|
|
|
// 1. The keys the word may start and end on, and how near the path passes each key.
|
|
let keyCount = grid.centres.count
|
|
let near = grid.centres.map { Self.distance(from: $0, toPolyline: gesture.raw) }
|
|
var startCost = [Double](repeating: .infinity, count: keyCount)
|
|
var endCost = [Double](repeating: .infinity, count: keyCount)
|
|
let starts = Self.nearest(grid.centres, to: start, radius: p.startRadius, limit: p.maxStartKeys)
|
|
for (k, squared) in starts { startCost[k] = p.cost(squared, sigma: p.startSigma, stray: p.startStraySigma) }
|
|
var endMask: UInt64 = 0
|
|
for (k, squared) in Self.nearest(grid.centres, to: end, radius: p.endRadius, limit: p.maxEndKeys) {
|
|
endCost[k] = p.cost(squared, sigma: p.endSigma, stray: p.endStraySigma)
|
|
endMask |= 1 << UInt64(k)
|
|
}
|
|
guard !starts.isEmpty, endMask != 0 else { return none }
|
|
|
|
// 2. Words that start on a start key, end on an end key, keep near the path and are
|
|
// about as long: their keys (repeats run together, apostrophes left out). An id is
|
|
// a model word's index, or -1 - n for extra word n.
|
|
var words: [Int32] = []
|
|
var offsets: [Int32] = [0]
|
|
var lengths: [Double] = []
|
|
var sequence: [UInt8] = []
|
|
/// Mean squared distance of each word's keys from the path, for the prefilter.
|
|
var nearness: [Double] = []
|
|
var scratch = [UInt8](repeating: 0, count: 64)
|
|
func consider<Codes: RandomAccessCollection>(_ codes: Codes, id: Int) where Codes.Element == UInt8, Codes.Index == Int {
|
|
var j = codes.endIndex - 1
|
|
while j > codes.startIndex, grid.keyOfCode[Int(codes[j])] == KeyGrid.skip { j -= 1 }
|
|
guard j > codes.startIndex else { return }
|
|
let endKey = grid.keyOfCode[Int(codes[j])]
|
|
guard endKey >= 0, endMask & (1 << UInt64(endKey)) != 0 else { return }
|
|
var count = 0
|
|
var last = -1
|
|
var length = 0.0
|
|
var squares = 0.0
|
|
for c in codes {
|
|
let k = Int(grid.keyOfCode[Int(c)])
|
|
if k == Int(KeyGrid.skip) || k == last { continue }
|
|
guard k >= 0, count < scratch.count, near[k] <= p.nearRadius else { return }
|
|
if last >= 0 { length += Self.distance(grid.centres[last], grid.centres[k]) }
|
|
squares += near[k] * near[k]
|
|
scratch[count] = UInt8(k)
|
|
count += 1
|
|
last = k
|
|
}
|
|
guard count >= 2, startCost[Int(scratch[0])].isFinite else { return }
|
|
let ratio = length / gesture.length
|
|
guard ratio >= p.minLengthRatio, ratio <= p.maxLengthRatio else { return }
|
|
sequence.append(contentsOf: scratch[0..<count])
|
|
words.append(Int32(id))
|
|
lengths.append(length)
|
|
offsets.append(Int32(sequence.count))
|
|
nearness.append(squares / Double(count))
|
|
}
|
|
for (s, _) in starts {
|
|
for code in grid.codesOfKey[s] {
|
|
let (lo, hi) = model.narrow(0, model.wordCount, depth: 0, byte: Int(code))
|
|
guard lo < hi else { continue }
|
|
for i in lo..<hi where !neverSuggest.words.contains(i) && !extraIndices.contains(i) {
|
|
model.withCodes(i) { consider($0, id: i) }
|
|
}
|
|
}
|
|
}
|
|
for n in 0..<extraWords.count {
|
|
consider(extraWords.codes[n], id: -1 - n)
|
|
}
|
|
guard !words.isEmpty else { return none }
|
|
|
|
// 3. A quick point-by-point pass over them all, then the aligned pass for the best.
|
|
let n = p.samples
|
|
var template = [Vec](repeating: Vec(x: 0, y: 0), count: n)
|
|
var vertices = [Vec](repeating: Vec(x: 0, y: 0), count: 64)
|
|
var rows = ([Double](repeating: 0, count: n), [Double](repeating: 0, count: n))
|
|
func spatial(_ c: Int, aligned: Bool) -> Double {
|
|
let from = Int(offsets[c]), to = Int(offsets[c + 1])
|
|
for v in from..<to { vertices[v - from] = grid.centres[Int(sequence[v])] }
|
|
Self.resample(vertices, count: to - from, length: lengths[c], into: &template)
|
|
let location = aligned
|
|
? Self.warpedDistance(gesture.points, template, band: max(1, Int(p.band * Double(n))), rows: &rows)
|
|
: Self.meanSquaredDistance(gesture.points, template)
|
|
let shape = Self.shapeDistance(gesture.shape, template)
|
|
return startCost[Int(sequence[from])] + endCost[Int(sequence[to - 1])]
|
|
+ p.locationWeight * location + p.shapeWeight * shape
|
|
}
|
|
var pool = Array(words.indices)
|
|
if pool.count > p.prefilter {
|
|
let rough = pool.map { c -> Double in
|
|
let from = Int(offsets[c]), to = Int(offsets[c + 1])
|
|
return startCost[Int(sequence[from])] + endCost[Int(sequence[to - 1])]
|
|
+ p.locationWeight * nearness[c] + p.lmWeight * lmCost(Int(words[c]), after: nil)
|
|
}
|
|
pool.sort { rough[$0] < rough[$1] }
|
|
pool.removeLast(pool.count - p.prefilter)
|
|
}
|
|
var quick: [(candidate: Int, cost: Double)] = []
|
|
quick.reserveCapacity(pool.count)
|
|
for c in pool {
|
|
quick.append((c, spatial(c, aligned: false) + p.lmWeight * lmCost(Int(words[c]), after: nil)))
|
|
}
|
|
quick.sort { $0.cost < $1.cost }
|
|
|
|
let previousWord = previous.flatMap { model.index(of: $0.lowercased()) }
|
|
var scored: [(word: Int, cost: Double)] = []
|
|
for (c, _) in quick.prefix(max(limit, p.shortlist)) {
|
|
let word = Int(words[c])
|
|
if word >= 0, neverSuggest.follows(word, after: previousWord) { continue }
|
|
scored.append((word, spatial(c, aligned: true) + p.lmWeight * lmCost(word, after: previousWord)))
|
|
}
|
|
scored.sort { $0.cost < $1.cost }
|
|
var candidates: [Candidate] = []
|
|
for (word, cost) in scored.prefix(limit) {
|
|
candidates.append(Candidate(text: word >= 0 ? model.word(word) : extraWords.texts[-1 - word], cost: cost))
|
|
}
|
|
return Reading(candidates: candidates, scored: words.count)
|
|
}
|
|
|
|
/// -ln P(word | previous) with stupid backoff (0.4) to the unigram, as Spatial autocorrect's;
|
|
/// an extra word's own cost when lower.
|
|
private func lmCost(_ id: Int, after previous: Int?) -> Double {
|
|
func model(_ word: Int) -> Double {
|
|
let backoff = 0.92 + self.model.unigramCost(word)
|
|
guard let previous, let bigram = self.model.bigramCost(previous, word) else { return backoff }
|
|
return min(bigram, backoff)
|
|
}
|
|
guard id < 0 else { return model(id) }
|
|
var own = 0.92 + extraWords.costs[-1 - id]
|
|
// A contraction is as much likelier after the word before as its first word is.
|
|
if let head = extraWords.heads[-1 - id], let previous {
|
|
let alone = 0.92 + self.model.unigramCost(head)
|
|
own += (self.model.bigramCost(previous, head) ?? alone + parameters.contractionMissingPair) - alone
|
|
}
|
|
return extraWords.modelIndex[-1 - id].map { min(own, model($0)) } ?? own
|
|
}
|
|
|
|
// MARK: - Geometry, in key pitches
|
|
|
|
struct Vec: Equatable, Sendable {
|
|
var x: Double
|
|
var y: Double
|
|
}
|
|
|
|
/// The layout's letter keys in pitches, and which key types each of the model's letters:
|
|
/// its own, else its unaccented letter's (é on e); the apostrophe has none and is skipped.
|
|
private struct KeyGrid {
|
|
static let skip: Int8 = -1
|
|
static let missing: Int8 = -2
|
|
var centres: [Vec] = []
|
|
var keyOfCode: [Int8]
|
|
var codesOfKey: [[UInt8]]
|
|
|
|
init(_ keys: TypingDecoder.Keys, model: TypingDecoderModel, pitch: Vec) {
|
|
var index: [Character: Int] = [:]
|
|
for (character, point) in keys.centres.sorted(by: { $0.key < $1.key }) {
|
|
index[character] = centres.count
|
|
centres.append(Vec(x: Double(point.x) / pitch.x, y: Double(point.y) / pitch.y))
|
|
}
|
|
keyOfCode = [Int8](repeating: Self.missing, count: model.characters.count)
|
|
codesOfKey = [[UInt8]](repeating: [], count: centres.count)
|
|
for code in 1..<model.characters.count {
|
|
if UInt8(code) == model.apostropheCode {
|
|
keyOfCode[code] = Self.skip
|
|
continue
|
|
}
|
|
let own = index[model.characters[code]]
|
|
guard let key = own ?? index[model.characters[Int(model.baseCodes[code])]], key < 64 else { continue }
|
|
keyOfCode[code] = Int8(key)
|
|
codesOfKey[key].append(UInt8(code))
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The finger's path in pitches without repeated points, resampled, and its shape.
|
|
private struct Gesture {
|
|
var raw: [Vec] = []
|
|
var length = 0.0
|
|
var points: [Vec]
|
|
var shape: [Vec]
|
|
|
|
init?(_ path: [CGPoint], pitch: Vec, samples: Int) {
|
|
for point in path {
|
|
let v = Vec(x: Double(point.x) / pitch.x, y: Double(point.y) / pitch.y)
|
|
if let last = raw.last {
|
|
let step = SwipeDecoder.distance(last, v)
|
|
guard step > 1e-4 else { continue }
|
|
length += step
|
|
}
|
|
raw.append(v)
|
|
}
|
|
guard raw.count >= 2, length > 0 else { return nil }
|
|
points = [Vec](repeating: Vec(x: 0, y: 0), count: samples)
|
|
SwipeDecoder.resample(raw, count: raw.count, length: length, into: &points)
|
|
shape = SwipeDecoder.normalized(points)
|
|
}
|
|
}
|
|
|
|
@inline(__always) static func distance(_ a: Vec, _ b: Vec) -> Double {
|
|
((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y)).squareRoot()
|
|
}
|
|
|
|
@inline(__always) private static func squared(_ a: Vec, _ b: Vec) -> Double {
|
|
(a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y)
|
|
}
|
|
|
|
/// The keys within `radius` of `point`, nearest first, at most `limit`, with their
|
|
/// squared distances; the nearest two however far.
|
|
private static func nearest(_ centres: [Vec], to point: Vec, radius: Double, limit: Int) -> [(Int, Double)] {
|
|
let sorted = centres.indices.map { ($0, squared(centres[$0], point)) }.sorted { $0.1 < $1.1 }
|
|
var found = Array(sorted.prefix(limit).filter { $0.1 <= radius * radius })
|
|
if found.count < 2 { found = Array(sorted.prefix(min(2, limit))) }
|
|
return found
|
|
}
|
|
|
|
static func distance(from point: Vec, toPolyline line: [Vec]) -> Double {
|
|
var best = Double.infinity
|
|
for i in 1..<line.count {
|
|
let a = line[i - 1], b = line[i]
|
|
let dx = b.x - a.x, dy = b.y - a.y
|
|
let span = dx * dx + dy * dy
|
|
var t = span > 0 ? ((point.x - a.x) * dx + (point.y - a.y) * dy) / span : 0
|
|
t = min(1, max(0, t))
|
|
best = min(best, squared(point, Vec(x: a.x + t * dx, y: a.y + t * dy)))
|
|
}
|
|
return best.squareRoot()
|
|
}
|
|
|
|
/// `count` points of `line` (`length` long) evenly spaced along it into `out`,
|
|
/// first and last included.
|
|
static func resample(_ line: [Vec], count: Int, length: Double, into out: inout [Vec]) {
|
|
let samples = out.count
|
|
out[0] = line[0]
|
|
out[samples - 1] = line[count - 1]
|
|
guard samples > 2 else { return }
|
|
let step = length / Double(samples - 1)
|
|
var segment = 0
|
|
var walked = 0.0
|
|
var span = distance(line[0], line[min(1, count - 1)])
|
|
for i in 1..<(samples - 1) {
|
|
let target = step * Double(i)
|
|
while walked + span < target, segment < count - 2 {
|
|
walked += span
|
|
segment += 1
|
|
span = distance(line[segment], line[segment + 1])
|
|
}
|
|
let a = line[segment], b = line[min(segment + 1, count - 1)]
|
|
let t = span > 0 ? min(1, max(0, (target - walked) / span)) : 0
|
|
out[i] = Vec(x: a.x + t * (b.x - a.x), y: a.y + t * (b.y - a.y))
|
|
}
|
|
}
|
|
|
|
/// The points moved to their centroid and scaled so their bounding box's longer side is 1.
|
|
static func normalized(_ points: [Vec]) -> [Vec] {
|
|
let (centre, scale) = frame(points)
|
|
return points.map { Vec(x: ($0.x - centre.x) * scale, y: ($0.y - centre.y) * scale) }
|
|
}
|
|
|
|
@inline(__always) private static func frame(_ points: [Vec]) -> (Vec, Double) {
|
|
var sx = 0.0, sy = 0.0
|
|
var minX = Double.infinity, maxX = -Double.infinity, minY = Double.infinity, maxY = -Double.infinity
|
|
for v in points {
|
|
sx += v.x
|
|
sy += v.y
|
|
minX = min(minX, v.x)
|
|
maxX = max(maxX, v.x)
|
|
minY = min(minY, v.y)
|
|
maxY = max(maxY, v.y)
|
|
}
|
|
let side = max(maxX - minX, maxY - minY)
|
|
let n = Double(points.count)
|
|
return (Vec(x: sx / n, y: sy / n), side > 1e-6 ? 1 / side : 1)
|
|
}
|
|
|
|
/// Mean squared distance between the gesture's normalized shape and the template's.
|
|
private static func shapeDistance(_ shape: [Vec], _ template: [Vec]) -> Double {
|
|
let (centre, scale) = frame(template)
|
|
var total = 0.0
|
|
for i in shape.indices {
|
|
let t = Vec(x: (template[i].x - centre.x) * scale, y: (template[i].y - centre.y) * scale)
|
|
total += squared(shape[i], t)
|
|
}
|
|
return total / Double(shape.count)
|
|
}
|
|
|
|
private static func meanSquaredDistance(_ a: [Vec], _ b: [Vec]) -> Double {
|
|
var total = 0.0
|
|
for i in a.indices { total += squared(a[i], b[i]) }
|
|
return total / Double(a.count)
|
|
}
|
|
|
|
/// Dynamic time warping of two equally long point lists within a band, symmetric steps
|
|
/// (a diagonal step counts twice), as a mean squared distance.
|
|
private static func warpedDistance(_ a: [Vec], _ b: [Vec], band: Int, rows: inout ([Double], [Double])) -> Double {
|
|
let n = a.count
|
|
for j in 0..<n { rows.0[j] = .infinity }
|
|
for i in 0..<n {
|
|
for j in 0..<n { rows.1[j] = .infinity }
|
|
let lo = max(0, i - band), hi = min(n - 1, i + band)
|
|
for j in lo...hi {
|
|
let c = squared(a[i], b[j])
|
|
var best = i == 0 && j == 0 ? 2 * c : Double.infinity
|
|
if i > 0, j > 0 { best = min(best, rows.0[j - 1] + 2 * c) }
|
|
if i > 0 { best = min(best, rows.0[j] + c) }
|
|
if j > 0 { best = min(best, rows.1[j - 1] + c) }
|
|
rows.1[j] = best
|
|
}
|
|
swap(&rows.0, &rows.1)
|
|
}
|
|
return rows.0[n - 1] / Double(2 * n)
|
|
}
|
|
}
|
|
|
|
extension KeyboardLayout {
|
|
/// A swipe's point where the decoder's keys are (`TypingDecoder.Keys`): on the split
|
|
/// keyboard the right half moves left against the left one (as `unsplitX`) and the middle
|
|
/// between the halves shrinks to one key's gap, so a stroke across it stays one unbroken
|
|
/// stroke, as Gboard joins the halves; elsewhere the point itself.
|
|
func joinedForSwipe(_ point: CGPoint) -> CGPoint {
|
|
guard let split else { return point }
|
|
if point.x <= split.leftEdge { return point }
|
|
if point.x >= split.rightEdge { return CGPoint(x: point.x - split.shift, y: point.y) }
|
|
let across = (point.x - split.leftEdge) / max(1, split.rightEdge - split.leftEdge)
|
|
return CGPoint(x: split.leftEdge + across * SplitGeometry.gap, y: point.y)
|
|
}
|
|
|
|
/// The distance between neighbouring letter keys' centres across: a split half's own pitch.
|
|
var swipePitch: CGFloat { isSplit ? SplitGeometry.pitch : letterWidth + metrics.gap }
|
|
}
|