mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-25 01:30:06 +08:00
iOS: autocorrect splits merged words, fixes missing apostrophes and homophones, and corrects before punctuation (#2144)
* 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).
This commit is contained in:
@@ -171,6 +171,101 @@ final class AutocorrectEngineTests: XCTestCase {
|
||||
XCTAssertEqual(slots.dropFirst().first?.willAutoReplace, false)
|
||||
}
|
||||
|
||||
/// Types `text` at the keys' centres into a new field, with the typing model's word pairs,
|
||||
/// and returns the field's text.
|
||||
private func typedWithContext(_ text: String, then: ((FullKeyboardEngine) -> Void)? = nil) throws -> String {
|
||||
let field = FixtureTextTarget()
|
||||
field.autocapitalizationType = UITextAutocapitalizationType.none
|
||||
let keys = FullKeyboardEngine(
|
||||
target: field,
|
||||
autocorrect: AutocorrectEngine(checker: SystemTextChecker(), learnedWords: LearnedWordsStore(defaults: defaults))
|
||||
)
|
||||
keys.width = 393
|
||||
keys.clock = { [unowned self] in self.now }
|
||||
keys.letterOdds = try XCTUnwrap(TypingDecoderModel.bundled("en"))
|
||||
keys.configureForField()
|
||||
let saved = engine
|
||||
engine = keys
|
||||
defer { engine = saved }
|
||||
typeWord(text)
|
||||
then?(keys)
|
||||
return field.text
|
||||
}
|
||||
|
||||
/// X (Erick): "the id in this didn't autocorrect to I'd". A word the same letters spell
|
||||
/// with an apostrophe follows the words around it, as on Apple's keyboard: the word
|
||||
/// before decides when it is clear ("yes id" -> "yes I'd", "the id" stays), else the next
|
||||
/// word ("well see" -> "we'll see", "well done" stays).
|
||||
func testContractionsWithoutTheApostropheFollowTheWordsAroundThem() throws {
|
||||
let cases: [(String, String)] = [
|
||||
("id like to go ", "I'd like to go "),
|
||||
("yes id love to ", "yes I'd love to "),
|
||||
("i think id help ", "I think I'd help "),
|
||||
("the id in this ", "the id in this "),
|
||||
("my id is here ", "my id is here "),
|
||||
("ill be there ", "I'll be there "),
|
||||
("shell be here ", "she'll be here "),
|
||||
("the shell is ", "the shell is "),
|
||||
("wed love to ", "we'd love to "),
|
||||
("lets go ", "let's go "),
|
||||
("well see ", "we'll see "),
|
||||
("well done ", "well done "),
|
||||
("as well as ", "as well as "),
|
||||
("till hell freezes over ", "till hell freezes over "),
|
||||
("hell be here ", "he'll be here "),
|
||||
("were going home ", "were going home "),
|
||||
]
|
||||
for (typed, expected) in cases {
|
||||
XCTAssertEqual(try typedWithContext(typed), expected, typed)
|
||||
}
|
||||
// Without the typing model nothing changes ("ill" stays a word).
|
||||
typeWord("ill be there ")
|
||||
XCTAssertEqual(target.text, "ill be there ")
|
||||
}
|
||||
|
||||
/// X (Justin): "It doesn't seem to understand grammar. Its vs it's for instance." The words
|
||||
/// around its/it's, your/you're, there/their/they're and then/than choose between them when
|
||||
/// they're clear, at the word's own space or the next word's.
|
||||
func testSoundAlikeWordsFollowTheWordsAroundThem() throws {
|
||||
let cases: [(String, String)] = [
|
||||
("its a nice day ", "it's a nice day "),
|
||||
("i think its broken ", "I think it's broken "),
|
||||
("the dog wagged its tail ", "the dog wagged its tail "),
|
||||
("winter is on its way ", "winter is on its way "),
|
||||
("your welcome ", "you're welcome "),
|
||||
("i like your car ", "I like your car "),
|
||||
("there going home ", "they're going home "),
|
||||
("their is a dog ", "there is a dog "),
|
||||
("they lost there keys ", "they lost their keys "),
|
||||
("more then that ", "more than that "),
|
||||
("and than we left ", "and then we left "),
|
||||
("youre mother loves you ", "your mother loves you "),
|
||||
]
|
||||
for (typed, expected) in cases {
|
||||
XCTAssertEqual(try typedWithContext(typed), expected, typed)
|
||||
}
|
||||
let own = try typedWithContext("you") { _ in
|
||||
self.tap(.layerSwitch(.numbers))
|
||||
self.tap(.character("'"))
|
||||
self.typeWord("re mother ")
|
||||
}
|
||||
XCTAssertEqual(own, "you're mother ", "an apostrophe you typed yourself stays")
|
||||
}
|
||||
|
||||
/// The next word's space revised the word before: one backspace puts back both as typed,
|
||||
/// and the word you kept stays.
|
||||
func testOneBackspaceTakesARevisionBack() throws {
|
||||
let text = try typedWithContext("well see ") { keys in
|
||||
XCTAssertEqual(keys.target.documentContextBeforeInput, "we'll see ")
|
||||
keys.deleteBackward()
|
||||
XCTAssertEqual(keys.target.documentContextBeforeInput, "well see")
|
||||
let space = keys.layout.key(.space)!.frame
|
||||
keys.touchBegan(id: 1, at: CGPoint(x: space.midX, y: space.midY))
|
||||
keys.touchEnded(id: 1, at: CGPoint(x: space.midX, y: space.midY))
|
||||
}
|
||||
XCTAssertEqual(text, "well see ")
|
||||
}
|
||||
|
||||
func testSpaceDeleteSpaceKeepLoopAndLearnedWordsPersistence() {
|
||||
typeWord("teh")
|
||||
XCTAssertEqual(engine.suggestions.count >= 2, true)
|
||||
@@ -744,6 +839,86 @@ final class AutocorrectEngineTests: XCTestCase {
|
||||
/// left slot. Record typing logs showed that picked what was typed and a space ("th "),
|
||||
/// and kept "th" from being corrected for the rest of the session. The keys take the
|
||||
/// tap now, on row 1's top edge, and Spatial autocorrect keeps the "the" it spells.
|
||||
private func tapCentre(_ letter: Character) {
|
||||
let key = engine.layout.key(.character(String(letter)))!.frame
|
||||
tap(at: CGPoint(x: key.midX, y: key.midY))
|
||||
}
|
||||
|
||||
/// X (Erick, Justin): "Auto correct does not separate two words like apple does." A space
|
||||
/// tapped as the b, n, v or c above the space bar is read as one wherever on the key it
|
||||
/// lands (the system keyboard turns "ofbthe" into "of the" at the key's centre too), and
|
||||
/// a missed space splits the words, with English "i" a capital.
|
||||
func testASpaceTappedAsALetterAboveTheSpaceBarOrMissedSplitsTheWords() throws {
|
||||
try useDecoder()
|
||||
typeTaps("is")
|
||||
typeTaps("this")
|
||||
for letter in ["b", "n", "v", "c"] {
|
||||
for dy: CGFloat in [0, -8, 10] {
|
||||
for ch in "of" { tapCentre(ch) }
|
||||
let key = engine.layout.key(.character(letter))!.frame
|
||||
let point = CGPoint(x: key.midX, y: key.midY + dy)
|
||||
XCTAssertEqual(engine.layout.hitTest(point)?.kind, .character(letter))
|
||||
tap(at: point)
|
||||
typeTaps("the")
|
||||
XCTAssertTrue(target.text.hasSuffix(" of the "), "\(letter) \(dy): \(target.text)")
|
||||
}
|
||||
}
|
||||
typeTaps("iwant")
|
||||
XCTAssertTrue(target.text.hasSuffix(" I want "), target.text)
|
||||
typeTaps("lookat")
|
||||
XCTAssertTrue(target.text.hasSuffix(" look at "), target.text)
|
||||
// A closing mark from the 123 page reads the word's taps as space does.
|
||||
for ch in "ofthe" { tapCentre(ch) }
|
||||
tap(.layerSwitch(.numbers))
|
||||
tap(.character("."))
|
||||
XCTAssertTrue(target.text.hasSuffix(" of the."), target.text)
|
||||
tap(.space)
|
||||
// A word with a bottom-row letter stays one word.
|
||||
for word in ["number", "cabin", "seven", "become"] { typeTaps(word) }
|
||||
XCTAssertTrue(target.text.hasSuffix(" number cabin seven become "), target.text)
|
||||
}
|
||||
|
||||
/// X (Justin): "Space bar accidental taps or lack of taps don't seem to be factored in." A
|
||||
/// space tapped at the space bar's top edge, under a letter the word needed, joins the
|
||||
/// words at the next word's space, as the system keyboard does ("deli ate" -> "delicate");
|
||||
/// one tapped well inside the bar never does, and one backspace puts back both words.
|
||||
func testASpaceTappedAtTheSpaceBarsEdgeForALetterJoinsTheWords() throws {
|
||||
try useDecoder()
|
||||
engine.letterOdds = engine.autocorrect.decoder?.model
|
||||
let space = engine.layout.key(.space)!
|
||||
func edgeSpace(under letter: Character) {
|
||||
let key = engine.layout.key(.character(String(letter)))!.frame
|
||||
let point = CGPoint(x: key.midX, y: space.hitFrame.minY + 1)
|
||||
XCTAssertEqual(engine.layout.hitTest(point)?.kind, .space)
|
||||
tap(at: point)
|
||||
}
|
||||
typeTaps("the")
|
||||
for ch in "deli" { tapCentre(ch) }
|
||||
edgeSpace(under: "c")
|
||||
typeTaps("ate")
|
||||
XCTAssertEqual(target.text, "the delicate ")
|
||||
tap(.delete)
|
||||
XCTAssertEqual(target.text, "the deli ate", "one backspace puts back both words")
|
||||
|
||||
tap(.space)
|
||||
typeTaps("so")
|
||||
for ch in "ha" { tapCentre(ch) }
|
||||
edgeSpace(under: "n")
|
||||
typeTaps("ded")
|
||||
XCTAssertTrue(target.text.hasSuffix(" so handed "), target.text)
|
||||
|
||||
for ch in "deli" { tapCentre(ch) }
|
||||
tap(.space)
|
||||
typeTaps("ate")
|
||||
XCTAssertTrue(target.text.hasSuffix(" deli ate "), "a space inside the bar: \(target.text)")
|
||||
|
||||
// Two words space would fix on their own stay two ("i dkdnt" is "I didn't", never one word).
|
||||
tapCentre("i")
|
||||
edgeSpace(under: "b")
|
||||
typeTaps("didnt")
|
||||
XCTAssertTrue(target.text.hasSuffix(" I didn't "), target.text)
|
||||
}
|
||||
|
||||
func testSpatialAutocorrectReadsAnETappedHighOnTheStripAsThe() throws {
|
||||
try useDecoder()
|
||||
typeTaps("on")
|
||||
|
||||
@@ -1243,6 +1243,56 @@ final class FullKeyboardEngineTests: XCTestCase {
|
||||
XCTAssertEqual(field.text, "hi ther")
|
||||
}
|
||||
|
||||
/// Types a mark from the 123 page; the next space goes back to the letters.
|
||||
private func punctuate(_ mark: String) {
|
||||
if engine.layout.layer == .letters { tap(.layerSwitch(.numbers)) }
|
||||
tap(.character(mark))
|
||||
now += 0.5
|
||||
}
|
||||
|
||||
/// X (Erick): "If I add punctuation after a typo autocorrect does not fix the typo." A
|
||||
/// mark that closes a word fixes it as space does and goes in after the fix, as on Apple's
|
||||
/// keyboard; backspace right after takes both back, as after a space.
|
||||
func testPunctuationAfterATypoFixesItFirst() {
|
||||
for mark in [",", ".", "!", "?", ";", ":", ")", "\""] {
|
||||
target = FixtureTextTarget()
|
||||
target.autocapitalizationType = UITextAutocapitalizationType.none
|
||||
engine = FullKeyboardEngine(target: target, autocorrect: AutocorrectEngine(learnedWords: LearnedWordsStore(defaults: defaults)))
|
||||
engine.width = 393
|
||||
engine.clock = { [unowned self] in self.now }
|
||||
engine.configureForField()
|
||||
type("see teh")
|
||||
punctuate(mark)
|
||||
XCTAssertEqual(target.text, "see the" + mark, mark)
|
||||
type(" ok")
|
||||
XCTAssertEqual(target.text, "see the\(mark) ok", mark)
|
||||
}
|
||||
|
||||
type(" recieve")
|
||||
punctuate(".")
|
||||
XCTAssertTrue(target.text.hasSuffix(" receive."))
|
||||
tap(.delete)
|
||||
XCTAssertTrue(target.text.hasSuffix(" recieve"), "one backspace takes back the mark and the fix")
|
||||
punctuate(".")
|
||||
XCTAssertTrue(target.text.hasSuffix(" recieve."), "the word you kept stays")
|
||||
|
||||
type(" approx")
|
||||
punctuate(".")
|
||||
XCTAssertTrue(target.text.hasSuffix(" approx."), "an abbreviation's period")
|
||||
type(" a")
|
||||
punctuate(",")
|
||||
XCTAssertTrue(target.text.hasSuffix(" a,"))
|
||||
}
|
||||
|
||||
func testPunctuationNeverChangesASwipedWord() throws {
|
||||
let (field, plane) = try swipeKeyboard()
|
||||
plane.engine.autocorrect.loadLexiconEntries([("hello", "Hello, friend")])
|
||||
swipe("hello", on: plane)
|
||||
tap(.layerSwitch(.numbers), on: plane)
|
||||
tap(.character(","), on: plane)
|
||||
XCTAssertEqual(field.text, "hello,", "a swiped word is a reading, not a typo")
|
||||
}
|
||||
|
||||
func testDeleteSwipeWordsMatchOptionDelete() {
|
||||
XCTAssertNil(DeleteWordSwipe.wordLength(before: ""))
|
||||
XCTAssertEqual(DeleteWordSwipe.wordLength(before: "Hello, world. "), 7)
|
||||
@@ -1351,6 +1401,42 @@ final class FullKeyboardEngineTests: XCTestCase {
|
||||
XCTAssertEqual(sentence.text, "Great. thanks Hello", "shift still capitalises")
|
||||
}
|
||||
|
||||
/// X (Eric Jung): "the swipe keyboard has random auto capitalization of words." Shift and
|
||||
/// auto-capitalization around swipes were right (after a period, a return, a comma, a
|
||||
/// delete, a pick); the capitals came from readings: the word list's names and
|
||||
/// abbreviations, which the dictionary knows only capitalised ("kent", "gs"), and "I'm"
|
||||
/// read after a word "I" never follows. A name now needs more evidence than a common word,
|
||||
/// your own words don't, and a contraction follows the word before.
|
||||
func testASwipeMidSentenceGetsNoStrayCapital() throws {
|
||||
let (field, plane) = try swipeKeyboard("Great.")
|
||||
field.autocapitalizationType = .sentences
|
||||
plane.engine.refreshAutoCapitalization()
|
||||
let swipe = try XCTUnwrap(plane.swipe)
|
||||
XCTAssertTrue(plane.engine.swipeReadsAsName("kent"))
|
||||
XCTAssertTrue(plane.engine.swipeReadsAsName("york"))
|
||||
XCTAssertFalse(plane.engine.swipeReadsAsName("many"))
|
||||
XCTAssertFalse(plane.engine.swipeReadsAsName("Kent"), "your own spelling")
|
||||
let close = [SwipeDecoder.Candidate(text: "kent", cost: 10), SwipeDecoder.Candidate(text: "many", cost: 12)]
|
||||
XCTAssertEqual(swipe.ranked(close), ["many", "kent"])
|
||||
let clear = [SwipeDecoder.Candidate(text: "kent", cost: 10), SwipeDecoder.Candidate(text: "many", cost: 20)]
|
||||
XCTAssertEqual(swipe.ranked(clear), ["kent", "many"])
|
||||
|
||||
for word in ["thanks", "for", "the", "help"] { self.swipe(word, on: plane) }
|
||||
tap(.layerSwitch(.numbers), on: plane)
|
||||
tap(.character(","), on: plane)
|
||||
tap(.space, on: plane)
|
||||
for word in ["see", "you", "in", "york"] { self.swipe(word, on: plane) }
|
||||
XCTAssertEqual(field.text, "Great. Thanks for the help, see you in York", "a common name keeps its capital")
|
||||
|
||||
let decoder = swipe.decoder
|
||||
let path = SwipePath.through("im", keys: plane.engine.swipeKeys)
|
||||
let cost = { (previous: String) in
|
||||
decoder.decode(path, keys: plane.engine.swipeKeys, previous: previous, limit: 8).first { $0.text == "I'm" }?.cost
|
||||
}
|
||||
let afterThink = try XCTUnwrap(cost("think")), afterUs = try XCTUnwrap(cost("us"))
|
||||
XCTAssertGreaterThan(afterUs - afterThink, 3, "\"I'm\" after \"think\", hardly after \"us\"")
|
||||
}
|
||||
|
||||
func testDeleteRightAfterASwipeTakesTheWholeWordBack() throws {
|
||||
let (field, plane) = try swipeKeyboard()
|
||||
swipe("hello", on: plane)
|
||||
|
||||
@@ -195,8 +195,16 @@ final class LearnedWordsStore {
|
||||
@MainActor
|
||||
final class AutocorrectEngine {
|
||||
struct AppliedCorrection: Equatable {
|
||||
/// One word backspace puts back as typed (`from`), and what autocorrect made it.
|
||||
struct Change: Equatable {
|
||||
let from: String
|
||||
let to: String
|
||||
}
|
||||
|
||||
let original: String
|
||||
let insertedText: String
|
||||
/// The words in `original` that autocorrect changed; backspace keeps each as typed.
|
||||
let changes: [Change]
|
||||
}
|
||||
|
||||
let checker: TextChecking
|
||||
@@ -240,6 +248,10 @@ final class AutocorrectEngine {
|
||||
var decoder: TypingDecoder? {
|
||||
didSet { if oldValue?.model !== decoder?.model { userWordsBuilt = nil } }
|
||||
}
|
||||
/// The layout language's word list and word pairs (the typing model, whether or not
|
||||
/// Spatial autocorrect is on): English chooses between words the same letters spell with
|
||||
/// and without an apostrophe by the words around them (`contextChoice`). Nil without one.
|
||||
var contextModel: TypingDecoderModel?
|
||||
/// The letter keys for `decoder`, from the current layout.
|
||||
var decoderKeys: TypingDecoder.Keys? {
|
||||
didSet { partner?.decoderKeys = decoderKeys }
|
||||
@@ -326,8 +338,8 @@ final class AutocorrectEngine {
|
||||
lastCorrection = nil
|
||||
}
|
||||
|
||||
func recordAppliedCorrection(original: String, insertedText: String) {
|
||||
lastCorrection = AppliedCorrection(original: original, insertedText: insertedText)
|
||||
func recordAppliedCorrection(original: String, insertedText: String, changes: [AppliedCorrection.Change]) {
|
||||
lastCorrection = AppliedCorrection(original: original, insertedText: insertedText, changes: changes)
|
||||
}
|
||||
|
||||
func consumePendingUndo() -> AppliedCorrection? {
|
||||
@@ -792,6 +804,16 @@ final class AutocorrectEngine {
|
||||
let hasInternalCaps = token.dropFirst().contains(where: \.isUppercase) && !isAllCaps
|
||||
if hasInternalCaps { return nil }
|
||||
|
||||
// A word the same letters spell with an apostrophe ("id", "I'd"), chosen by the word
|
||||
// before when it says so clearly ("yes id" -> "yes I'd", "the id" stays). The next
|
||||
// word may still revise it (`revision(of:before:next:)`).
|
||||
if !isAllCaps, !token.contains("'"), let choice = contextChoice(
|
||||
for: token, previous: Self.previousWord(beforeInput ?? "", token: token), next: nil,
|
||||
startsSentence: Self.startsSentence(before: beforeInput ?? "", token: token)
|
||||
), mayOffer(choice, replacing: token) {
|
||||
return withoutAddedCapitals(choice, typed: token)
|
||||
}
|
||||
|
||||
// 2. Deterministic contractions and common QWERTY transpositions (English only:
|
||||
// Norwegian "i" means "in" and must not become "I").
|
||||
if language.usesEnglishFixes, let fixed = Self.unambiguousFixes[lower] {
|
||||
@@ -804,7 +826,12 @@ final class AutocorrectEngine {
|
||||
// Spatial autocorrect, when on, decides alone: your taps, the word before, and a margin.
|
||||
if let decision = decoderDecision(for: token) {
|
||||
if let replacement = decision.replacement, mayOffer(replacement, replacing: token) {
|
||||
return withoutAddedCapitals(Self.matchCase(of: token, onto: replacement), typed: token)
|
||||
var cased = Self.matchCase(of: token, onto: replacement)
|
||||
// A missed space after English "i" ("iwant") gives "I want", as "i" alone does.
|
||||
if language.usesEnglishFixes, cased.contains(" ") {
|
||||
cased = cased.split(separator: " ").map { $0 == "i" ? "I" : String($0) }.joined(separator: " ")
|
||||
}
|
||||
return withoutAddedCapitals(cased, typed: token)
|
||||
}
|
||||
// A name, day or place its lowercase word list lacks, typed in lowercase, is
|
||||
// capitalised as the dictionary path does ("mary" -> "Mary"), unless
|
||||
@@ -899,6 +926,144 @@ final class AutocorrectEngine {
|
||||
return capitalised
|
||||
}
|
||||
|
||||
// MARK: - Words the context decides
|
||||
|
||||
/// English words chosen by the words around them rather than as typos: the same letters
|
||||
/// with and without an apostrophe ("id" or "I'd", "its" or "it's"), and words that sound
|
||||
/// alike ("your", "there", "then"). "were" and "we're" aren't here: the word pairs can't
|
||||
/// tell them apart, so the strip offers "we're" and space never changes it.
|
||||
static let contextGroups: [[String]] = [
|
||||
["id", "I'd"], ["ill", "I'll"], ["hell", "he'll"], ["shell", "she'll"],
|
||||
["wed", "we'd"], ["lets", "let's"], ["well", "we'll"],
|
||||
["its", "it's"], ["your", "you're"], ["there", "their", "they're"], ["then", "than"],
|
||||
]
|
||||
|
||||
/// The typing model's word pairs barely spell contractions (its books split "I'd" into
|
||||
/// "I" and "'d"), so a contraction is scored as the words it stands for.
|
||||
static let contractionWords: [String: [[String]]] = [
|
||||
"i'd": [["i", "would"], ["i", "had"]], "i'll": [["i", "will"]], "he'll": [["he", "will"]],
|
||||
"she'll": [["she", "will"]], "we'd": [["we", "would"], ["we", "had"]], "let's": [["let", "us"]],
|
||||
"we'll": [["we", "will"]], "it's": [["it", "is"], ["it", "has"]], "you're": [["you", "are"]],
|
||||
"they're": [["they", "are"]],
|
||||
]
|
||||
|
||||
private static let contextGroupOf: [String: [String]] = {
|
||||
var out: [String: [String]] = [:]
|
||||
for group in contextGroups { for word in group { out[word.lowercased()] = group } }
|
||||
return out
|
||||
}()
|
||||
|
||||
/// Nats the better word must win by: with the word before only, and once the next word
|
||||
/// is known too. Changing only an apostrophe needs less than changing letters ("your"
|
||||
/// and "you're"). Tuned on Tatoeba sentences outside the benchmark's held-out ones.
|
||||
static let contextMargin = (previous: 3.0, next: 1.5)
|
||||
static let contextLetterMargin = (previous: 6.0, next: 3.0)
|
||||
/// -ln P of a word the model lacks.
|
||||
private static let contextUnknownCost = 15.0
|
||||
/// How much likelier a sentence starts with a contraction's pronoun ("I'd", "It's") than
|
||||
/// the word list alone says: the pairs have no sentence starts.
|
||||
private static let contextSentenceStart = 3.0
|
||||
/// "will", "would", "had" and "us", which thousands of words follow in the pairs: a next
|
||||
/// word that never follows a contraction's last one of them is evidence against it
|
||||
/// ("till hell freezes", not "till he'll freezes"). "are" and "is" are left out: the
|
||||
/// adjectives after them are too rare for the pairs ("you're funny").
|
||||
private static let contextMissingFollower = 5.0
|
||||
private static let contextRichFollowers: Set<String> = ["will", "would", "had", "us"]
|
||||
|
||||
/// Whether `token`, at the end of `before`, starts a sentence.
|
||||
static func startsSentence(before: String, token: String) -> Bool {
|
||||
let rest = before.hasSuffix(token) ? String(before.dropLast(token.count)) : before
|
||||
return AutoCapitalization.shouldCapitalize(mode: .sentences, before: rest, hasText: true)
|
||||
}
|
||||
|
||||
/// -ln P(`word` | `previous`) + -ln P(`next` | `word`) by the model's pairs, a
|
||||
/// contraction as its words ("I'd like" as "I would like").
|
||||
private func contextCost(_ word: String, previous: String?, next: String?, startsSentence: Bool, model: TypingDecoderModel) -> Double {
|
||||
let unknown = Self.contextUnknownCost
|
||||
let expanded = Self.contractionWords[word.lowercased()]
|
||||
var best = Double.infinity
|
||||
for words in expanded ?? [[word.lowercased()]] {
|
||||
var cost = model.cost(of: words[0], after: previous) ?? unknown
|
||||
for k in words.indices.dropFirst() { cost += model.cost(of: words[k], after: words[k - 1]) ?? unknown }
|
||||
if let next {
|
||||
let last = words[words.count - 1]
|
||||
cost += model.cost(of: next, after: last) ?? unknown
|
||||
if Self.contextRichFollowers.contains(last), !model.hasPair(last, next) {
|
||||
cost += Self.contextMissingFollower
|
||||
}
|
||||
}
|
||||
best = min(best, cost)
|
||||
}
|
||||
return expanded != nil && startsSentence ? best - Self.contextSentenceStart : best
|
||||
}
|
||||
|
||||
/// The word of `word`'s group (`contextGroups`) that the words around it make clearly
|
||||
/// likelier, cased as `word` is, or nil to keep it. English only, with the layout's
|
||||
/// model, and never a word you kept or Hex learned not to change.
|
||||
func contextChoice(for word: String, previous: String?, next: String?, startsSentence: Bool = false) -> String? {
|
||||
guard isEnabled, language.usesEnglishFixes, let model = contextModel, model.language == language.rawValue,
|
||||
let group = Self.contextGroupOf[word.lowercased()] else { return nil }
|
||||
let lower = word.lowercased()
|
||||
guard !suppressedInSession.contains(lower), !learning.rejected.contains(lower), !learnedWords.contains(lower),
|
||||
!lexiconTerms.contains(where: { $0.lowercased() == lower }) else { return nil }
|
||||
let own = contextCost(word, previous: previous, next: next, startsSentence: startsSentence, model: model)
|
||||
var best: (word: String, cost: Double)?
|
||||
for other in group where other.lowercased() != lower {
|
||||
let cost = contextCost(other, previous: previous, next: next, startsSentence: startsSentence, model: model)
|
||||
if cost < best?.cost ?? .infinity { best = (other, cost) }
|
||||
}
|
||||
guard let best else { return nil }
|
||||
let sameLetters = best.word.replacingOccurrences(of: "'", with: "").lowercased() == lower.replacingOccurrences(of: "'", with: "")
|
||||
let margins = sameLetters ? Self.contextMargin : Self.contextLetterMargin
|
||||
guard own - best.cost >= (next == nil ? margins.previous : margins.next) else { return nil }
|
||||
return Self.matchContextCase(of: word, onto: best.word)
|
||||
}
|
||||
|
||||
/// `target` cased as `word` reads: a capital first letter carries over (a sentence's
|
||||
/// start), except the "I" of "I'd" or "I'll", which comes off ("I'd" to "id").
|
||||
private static func matchContextCase(of word: String, onto target: String) -> String {
|
||||
let startsWithI = word.hasPrefix("I'") && word.dropFirst(2).allSatisfy(\.isLowercase)
|
||||
guard let first = word.first, first.isUppercase, !startsWithI, let t = target.first else { return target }
|
||||
return t.uppercased() + target.dropFirst()
|
||||
}
|
||||
|
||||
/// The word before the one being finished, revised now that `next` follows it: "well
|
||||
/// see" becomes "we'll see", as Apple's keyboard decides at the next word. `before` is
|
||||
/// the text up to the end of `word`. Nil to leave it.
|
||||
func revision(of word: String, before: String, next: String, field: KeyboardFieldKind, autocorrectionType: UITextAutocorrectionType?) -> String? {
|
||||
guard field == .text, autocorrectionType != .no, hasDictionary, word.count >= 2 else { return nil }
|
||||
let isAllCaps = word == word.uppercased() && word != word.lowercased() && !word.hasPrefix("I'")
|
||||
guard !isAllCaps, let nextWord = next.split(separator: " ").first.map(String.init) else { return nil }
|
||||
let previous = Self.previousWord(before, token: word)
|
||||
guard let choice = contextChoice(
|
||||
for: word, previous: previous, next: nextWord.lowercased(),
|
||||
startsSentence: Self.startsSentence(before: before, token: word)
|
||||
), mayOffer(choice, after: previous) else { return nil }
|
||||
return addsCapitals || word.first?.isUppercase == true ? choice : choice.lowercased()
|
||||
}
|
||||
|
||||
/// One word in place of `first`, a space tapped near the letter row's edge (`space`) and
|
||||
/// the word being finished (`decoderTaps`), when Spatial autocorrect reads the space as a
|
||||
/// letter ("deli ate" -> "delicate"); nil to keep both. `before` is the text up to the
|
||||
/// end of `first`. `first` and `firstTaps` are as you typed them.
|
||||
func merge(first: String, firstTaps: [CGPoint], space: CGPoint, second: String, before: String) -> String? {
|
||||
guard isEnabled, hasDictionary, let decoder, let keys = decoderKeys, let taps = decoderTaps,
|
||||
decoder.model.language == language.rawValue, !first.contains("'"), !second.contains("'") else { return nil }
|
||||
for word in [first, second] {
|
||||
let lower = word.lowercased()
|
||||
if suppressedInSession.contains(lower) || learning.rejected.contains(lower) || learnedWords.contains(lower)
|
||||
|| Self.shorthandAllowlist.contains(lower) || lexiconTerms.contains(where: { $0.lowercased() == lower }) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
let previous = Self.previousWord(before, token: first)
|
||||
guard let merged = decoder.merge(
|
||||
first: first, firstTaps: firstTaps, space: space, second: second, secondTaps: taps,
|
||||
previous: previous, firstIsValid: knowsAsTyped(first), secondIsValid: knowsAsTyped(second), keys: keys
|
||||
), mayOffer(merged, after: previous) else { return nil }
|
||||
return withoutAddedCapitals(Self.matchCase(of: first, onto: merged), typed: first + second)
|
||||
}
|
||||
|
||||
/// Your own words for Swipe typing: Contacts names and other `UILexicon` terms, one-word
|
||||
/// text replacements, and words you kept twice that may be offered.
|
||||
var ownWords: [String] {
|
||||
@@ -1125,6 +1290,14 @@ final class AutocorrectEngine {
|
||||
"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",
|
||||
|
||||
@@ -124,6 +124,7 @@ final class FullKeyboardEngine {
|
||||
if letterOdds !== oldValue {
|
||||
continuationCache = nil
|
||||
wordStartMass = nil
|
||||
autocorrect.contextModel = letterOdds
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -280,6 +281,7 @@ final class FullKeyboardEngine {
|
||||
suggestionSpaceBefore = nil
|
||||
tokenTaps.removeAll()
|
||||
swipedWord = nil
|
||||
finishedWord = nil
|
||||
autocorrect.clearPendingUndo()
|
||||
cancelAllTouches()
|
||||
rebuildLayout(cause: "field")
|
||||
@@ -296,6 +298,7 @@ final class FullKeyboardEngine {
|
||||
}
|
||||
tokenTaps.removeAll()
|
||||
swipedWord = nil
|
||||
finishedWord = nil
|
||||
autocorrect.clearPendingUndo()
|
||||
refreshAutoCapitalization()
|
||||
refreshSuggestions()
|
||||
@@ -613,6 +616,7 @@ final class FullKeyboardEngine {
|
||||
touches[id] = touch
|
||||
typingLog?.edit("cursor", [TypingLogField("offset", .int(rawSteps))])
|
||||
tokenTaps.removeAll()
|
||||
finishedWord = nil
|
||||
suggestionSpaceBefore = nil
|
||||
target.adjustTextPosition(byCharacterOffset: rawSteps)
|
||||
onSelectionStep?()
|
||||
@@ -727,7 +731,7 @@ final class FullKeyboardEngine {
|
||||
])
|
||||
onLanguageSwipe?(step)
|
||||
} else {
|
||||
typeSpace()
|
||||
typeSpace(at: CGPoint(x: layout.unsplitX(touch.startPoint.x), y: touch.startPoint.y))
|
||||
}
|
||||
case .returnKey:
|
||||
if target.enablesReturnKeyAutomatically == true && !target.hasText {
|
||||
@@ -752,8 +756,10 @@ final class FullKeyboardEngine {
|
||||
// a slide: nothing, and back too. Off the keys: nothing, and the page stays.
|
||||
if let returnLayer = touch.returnLayer {
|
||||
if let under = slideTarget(for: touch, at: point), let character = under.character {
|
||||
autocorrect.clearPendingUndo()
|
||||
insert(character, source: "slide")
|
||||
if !correctWord(endingWith: character) {
|
||||
autocorrect.clearPendingUndo()
|
||||
insert(character, source: "slide")
|
||||
}
|
||||
layerState.switchTo(returnLayer)
|
||||
rebuildLayout(cause: "layer_slide")
|
||||
refreshAutoCapitalization()
|
||||
@@ -856,13 +862,12 @@ final class FullKeyboardEngine {
|
||||
target.deleteBackward()
|
||||
}
|
||||
tokenTaps.removeAll()
|
||||
finishedWord = nil
|
||||
target.insertText(undo.original)
|
||||
autocorrect.suppressAndKeep(undo.original)
|
||||
learning?.record(
|
||||
.undone,
|
||||
typed: undo.insertedText.trimmingCharacters(in: .whitespaces),
|
||||
final: undo.original
|
||||
)
|
||||
for change in undo.changes {
|
||||
autocorrect.suppressAndKeep(change.from)
|
||||
learning?.record(.undone, typed: change.to, final: change.from)
|
||||
}
|
||||
lastSpaceAt = nil
|
||||
didEdit()
|
||||
return
|
||||
@@ -925,11 +930,129 @@ final class FullKeyboardEngine {
|
||||
if layerState.layer == .letters {
|
||||
shift.didType()
|
||||
}
|
||||
autocorrect.clearPendingUndo()
|
||||
insert(text, source: "key", at: point)
|
||||
if !correctWord(endingWith: text) {
|
||||
autocorrect.clearPendingUndo()
|
||||
insert(text, source: "key", at: point)
|
||||
}
|
||||
logState("typed")
|
||||
}
|
||||
|
||||
/// Punctuation that closes a word, as Apple's keyboard treats it: , . ! ? ; : ) and ".
|
||||
static let wordEnders: Set<Character> = [",", ".", "!", "?", ";", ":", ")", "\""]
|
||||
|
||||
/// Punctuation right after a word corrects it as space does ("teh," becomes "the,"), and
|
||||
/// goes in after the fix. Backspace right after takes back both, as after a space ("teh").
|
||||
/// False when there is nothing to fix: the caller types the mark as usual.
|
||||
private func correctWord(endingWith text: String) -> Bool {
|
||||
guard text.count == 1, let mark = text.first, Self.wordEnders.contains(mark), swipedWord == nil else { return false }
|
||||
let before = target.documentContextBeforeInput
|
||||
guard let last = before?.last, last.isLetter, let token = AutocorrectEngine.currentToken(in: before) else { return false }
|
||||
// "approx." and "etc." are abbreviations, not typos.
|
||||
if mark == ".", AutocorrectEngine.abbreviations.contains(token.lowercased()) { return false }
|
||||
learning?.didFinish(word: token)
|
||||
syncLearning()
|
||||
autocorrect.decoderTaps = currentTokenTaps
|
||||
guard finishWord(ending: text) else { return false }
|
||||
finishedWord = nil
|
||||
lastSpaceAt = nil
|
||||
layerState.didInsert(text)
|
||||
rebuildLayoutIfNeeded()
|
||||
didEdit()
|
||||
return true
|
||||
}
|
||||
|
||||
/// The word a space finished, while the next one is typed: that word's space or mark may
|
||||
/// still revise it ("well see" becomes "we'll see"), as Apple's keyboard decides some
|
||||
/// words at the next one.
|
||||
private struct FinishedWord {
|
||||
/// The word as it reads now.
|
||||
var text: String
|
||||
/// As you typed it: one you gave an apostrophe yourself is never revised.
|
||||
var typed: String
|
||||
/// The text before the cursor right after its space.
|
||||
var before: String
|
||||
/// Where its letters were tapped, and its space: a space near the letter row's edge
|
||||
/// may have been a letter, and the next word joins it (`AutocorrectEngine.merge`).
|
||||
var taps: [CGPoint]?
|
||||
var space: CGPoint?
|
||||
}
|
||||
|
||||
private var finishedWord: FinishedWord?
|
||||
|
||||
/// Corrects the word before the cursor as `ending` (a space or a closing mark) finishes
|
||||
/// it, and revises the word before it now that this one follows (`AutocorrectEngine.
|
||||
/// revision`); then types `ending`. One backspace right after puts back what was typed.
|
||||
/// False, typing nothing, when neither changes.
|
||||
private func finishWord(ending: String) -> Bool {
|
||||
let before = target.documentContextBeforeInput ?? ""
|
||||
guard let token = AutocorrectEngine.currentToken(in: before) else { return false }
|
||||
if let finished = finishedWord, before == finished.before + token,
|
||||
let taps = finished.taps, let space = finished.space, field == .text, target.autocorrectionType != .no,
|
||||
let merged = autocorrect.merge(
|
||||
first: finished.typed, firstTaps: taps, space: space, second: token,
|
||||
before: String(finished.before.dropLast())
|
||||
) {
|
||||
let original = finished.text + " " + token
|
||||
for _ in 0..<original.count {
|
||||
target.deleteBackward()
|
||||
}
|
||||
tokenTaps.removeAll()
|
||||
typingLog?.edit("autocorrect", [
|
||||
TypingLogField("from", .string(original)),
|
||||
TypingLogField("to", .string(merged)),
|
||||
TypingLogField("deleted", .string(original)),
|
||||
TypingLogField("inserted", .string(merged + ending)),
|
||||
TypingLogField("merged", .bool(true)),
|
||||
])
|
||||
target.insertText(merged + ending)
|
||||
learning?.record(.autocorrected, typed: token, final: merged)
|
||||
autocorrect.recordAppliedCorrection(
|
||||
original: original, insertedText: merged + ending, changes: [.init(from: token, to: merged)]
|
||||
)
|
||||
swipedWord = nil
|
||||
return true
|
||||
}
|
||||
let fix = autocorrect.replacementOnSpace(beforeInput: before, field: field, autocorrectionType: target.autocorrectionType)
|
||||
let word = fix?.replacement ?? token
|
||||
var revised: (from: String, to: String)?
|
||||
if let finished = finishedWord, before == finished.before + token, !finished.typed.contains("'"),
|
||||
let to = autocorrect.revision(
|
||||
of: finished.text, before: String(finished.before.dropLast()), next: word,
|
||||
field: field, autocorrectionType: target.autocorrectionType
|
||||
) {
|
||||
revised = (finished.text, to)
|
||||
}
|
||||
guard fix != nil || revised != nil else { return false }
|
||||
let original = (revised.map { $0.from + " " } ?? "") + token
|
||||
let inserted = (revised.map { $0.to + " " } ?? "") + word + ending
|
||||
for _ in 0..<original.count {
|
||||
target.deleteBackward()
|
||||
}
|
||||
tokenTaps.removeAll()
|
||||
var fields = [
|
||||
TypingLogField("from", .string(token)),
|
||||
TypingLogField("to", .string(word)),
|
||||
TypingLogField("deleted", .string(original)),
|
||||
TypingLogField("inserted", .string(inserted)),
|
||||
]
|
||||
if ending != " " { fields.append(TypingLogField("ending", .string(ending))) }
|
||||
if let revised { fields.append(TypingLogField("revised", .strings([revised.from, revised.to]))) }
|
||||
typingLog?.edit("autocorrect", fields)
|
||||
target.insertText(inserted)
|
||||
var changes: [AutocorrectEngine.AppliedCorrection.Change] = []
|
||||
if let revised {
|
||||
changes.append(.init(from: revised.from, to: revised.to))
|
||||
learning?.record(.autocorrected, typed: revised.from, final: revised.to)
|
||||
}
|
||||
if fix != nil {
|
||||
changes.append(.init(from: token, to: word))
|
||||
learning?.record(.autocorrected, typed: token, final: word)
|
||||
}
|
||||
autocorrect.recordAppliedCorrection(original: original, insertedText: inserted, changes: changes)
|
||||
swipedWord = nil
|
||||
return true
|
||||
}
|
||||
|
||||
/// The taps of the word being typed when every letter came from a key, else nil.
|
||||
private var currentTokenTaps: [CGPoint]? {
|
||||
let taps = tokenTaps.compactMap { $0 }
|
||||
@@ -945,7 +1068,8 @@ final class FullKeyboardEngine {
|
||||
logState("typed")
|
||||
}
|
||||
|
||||
private func typeSpace() {
|
||||
/// `point` is where the space bar was tapped, as on the unsplit keyboard.
|
||||
private func typeSpace(at point: CGPoint? = nil) {
|
||||
// Space never autocorrects a swiped word: it is a reading, not a typo.
|
||||
let afterSwipe = swipedWord != nil
|
||||
swipedWord = nil
|
||||
@@ -973,6 +1097,7 @@ final class FullKeyboardEngine {
|
||||
target.deleteBackward()
|
||||
target.insertText(". ")
|
||||
tokenTaps.removeAll()
|
||||
finishedWord = nil
|
||||
lastSpaceAt = nil
|
||||
layerState.didInsert(" ")
|
||||
rebuildLayoutIfNeeded()
|
||||
@@ -980,28 +1105,13 @@ final class FullKeyboardEngine {
|
||||
typingLog?.context("space")
|
||||
return
|
||||
}
|
||||
learning?.didFinish(word: AutocorrectEngine.currentToken(in: target.documentContextBeforeInput))
|
||||
let token = AutocorrectEngine.currentToken(in: target.documentContextBeforeInput)
|
||||
let taps = currentTokenTaps
|
||||
learning?.didFinish(word: token)
|
||||
syncLearning()
|
||||
autocorrect.decoderTaps = currentTokenTaps
|
||||
if !afterSwipe, let (original, replacement) = autocorrect.replacementOnSpace(
|
||||
beforeInput: target.documentContextBeforeInput,
|
||||
field: field,
|
||||
autocorrectionType: target.autocorrectionType
|
||||
) {
|
||||
for _ in 0..<original.count {
|
||||
target.deleteBackward()
|
||||
}
|
||||
let inserted = replacement + " "
|
||||
tokenTaps.removeAll()
|
||||
typingLog?.edit("autocorrect", [
|
||||
TypingLogField("from", .string(original)),
|
||||
TypingLogField("to", .string(replacement)),
|
||||
TypingLogField("deleted", .string(original)),
|
||||
TypingLogField("inserted", .string(inserted)),
|
||||
])
|
||||
target.insertText(inserted)
|
||||
autocorrect.recordAppliedCorrection(original: original, insertedText: inserted)
|
||||
learning?.record(.autocorrected, typed: original, final: replacement)
|
||||
autocorrect.decoderTaps = taps
|
||||
if !afterSwipe, finishWord(ending: " ") {
|
||||
rememberFinishedWord(typed: token, taps: taps, space: point)
|
||||
lastSpaceAt = now
|
||||
layerState.didInsert(" ")
|
||||
rebuildLayoutIfNeeded()
|
||||
@@ -1011,13 +1121,34 @@ final class FullKeyboardEngine {
|
||||
}
|
||||
autocorrect.clearPendingUndo()
|
||||
insert(" ", source: "key")
|
||||
if !afterSwipe, let token { rememberFinishedWord(typed: token, taps: taps, space: point) }
|
||||
lastSpaceAt = now
|
||||
typingLog?.context("space")
|
||||
}
|
||||
|
||||
/// The word right before the space just typed, for the next word's revision.
|
||||
private func rememberFinishedWord(typed: String?, taps: [CGPoint]?, space: CGPoint?) {
|
||||
guard let typed, let before = target.documentContextBeforeInput, before.last == " ",
|
||||
let word = AutocorrectEngine.currentToken(in: String(before.dropLast())) else {
|
||||
finishedWord = nil
|
||||
return
|
||||
}
|
||||
// After a split or a merge the word reads other letters than you typed ("of the" for
|
||||
// "ofthe"): it is remembered as it reads, without taps.
|
||||
guard word.filter({ $0 != "'" }).count == typed.count else {
|
||||
finishedWord = FinishedWord(text: word, typed: word, before: before, taps: nil, space: nil)
|
||||
return
|
||||
}
|
||||
finishedWord = FinishedWord(text: word, typed: typed, before: before, taps: taps, space: space)
|
||||
}
|
||||
|
||||
/// `source` names the edit in typing logs; nil when the caller writes its own line.
|
||||
private func insert(_ text: String, source: String?, at point: CGPoint? = nil) {
|
||||
swipedWord = nil
|
||||
// Anything but the next word's letters ends the chance to revise the word before.
|
||||
if !(text.count == 1 && (text.first?.isLetter == true || text == "'")) {
|
||||
finishedWord = nil
|
||||
}
|
||||
if text.count == 1, text.first?.isLetter == true {
|
||||
// Spatial autocorrect reads taps as on the unsplit keyboard (`KeyboardLayout.unsplitX`).
|
||||
tokenTaps.append(point.map { CGPoint(x: layout.unsplitX($0.x), y: $0.y) })
|
||||
@@ -1144,6 +1275,7 @@ final class FullKeyboardEngine {
|
||||
TypingLogField("src", .string("swipe")),
|
||||
])
|
||||
target.insertText(inserted)
|
||||
finishedWord = nil
|
||||
lastSpaceAt = nil
|
||||
layerState.didInsert(inserted)
|
||||
if layerState.layer == .letters { shift.didType() }
|
||||
@@ -1201,9 +1333,14 @@ final class FullKeyboardEngine {
|
||||
if !autoCapitalizes {
|
||||
return autocorrect.isOwnSpelling(word) ? word : word.lowercased()
|
||||
}
|
||||
guard autocorrect.hasDictionary, word == word.lowercased(), word.count >= 2 else { return word }
|
||||
let capitalised = first.uppercased() + word.dropFirst()
|
||||
return autocorrect.checker.isWordValid(capitalised) && !autocorrect.checker.isWordValid(word) ? capitalised : word
|
||||
return swipeReadsAsName(word) ? first.uppercased() + word.dropFirst() : word
|
||||
}
|
||||
|
||||
/// Whether a swipe's reading, as the model spells it (lowercase), is a word the dictionary
|
||||
/// knows only with a capital: a name, day or place ("monday"), or an abbreviation.
|
||||
func swipeReadsAsName(_ word: String) -> Bool {
|
||||
guard autocorrect.hasDictionary, word == word.lowercased(), word.count >= 2, let first = word.first else { return false }
|
||||
return autocorrect.checker.isWordValid(first.uppercased() + word.dropFirst()) && !autocorrect.checker.isWordValid(word)
|
||||
}
|
||||
|
||||
/// Puts another of the swipe's readings in its word's place; the word joins the others.
|
||||
@@ -1277,9 +1414,11 @@ final class FullKeyboardEngine {
|
||||
}
|
||||
|
||||
/// The letter keys Spatial autocorrect scores taps against: this layout's, moved by
|
||||
/// `tapOffsets`. None off the letters page.
|
||||
/// `tapOffsets`. Off the letters page the last letters page's stay: a closing mark from
|
||||
/// the 123 page still reads the word's taps ("ofthe." -> "of the.").
|
||||
private func syncDecoderKeys() {
|
||||
autocorrect.decoderKeys = TypingDecoder.Keys(layout: layout, offsets: tapOffsets)
|
||||
guard let keys = TypingDecoder.Keys(layout: layout, offsets: tapOffsets) else { return }
|
||||
autocorrect.decoderKeys = keys
|
||||
}
|
||||
|
||||
/// Hands the layout and shift to typing logs, which writes a line when either changed.
|
||||
|
||||
@@ -62,6 +62,10 @@ nonisolated struct SwipeDecoder: Sendable {
|
||||
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.
|
||||
@@ -120,6 +124,9 @@ nonisolated struct SwipeDecoder: Sendable {
|
||||
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() {}
|
||||
|
||||
@@ -140,7 +147,7 @@ nonisolated struct SwipeDecoder: Sendable {
|
||||
add(words, cost: { _ in cost }, model: model)
|
||||
}
|
||||
|
||||
mutating func add(_ words: [String], cost: (String) -> Double, model: TypingDecoderModel) {
|
||||
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 }
|
||||
@@ -148,8 +155,16 @@ nonisolated struct SwipeDecoder: Sendable {
|
||||
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
|
||||
@@ -308,7 +323,12 @@ nonisolated struct SwipeDecoder: Sendable {
|
||||
return min(bigram, backoff)
|
||||
}
|
||||
guard id < 0 else { return model(id) }
|
||||
let own = 0.92 + extraWords.costs[-1 - 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
|
||||
}
|
||||
|
||||
|
||||
@@ -36,6 +36,13 @@ final class SwipeTyping {
|
||||
|
||||
/// How long the last swipe's decode took, for Record typing logs and probes.
|
||||
private(set) var lastDecodeTime: TimeInterval?
|
||||
/// Nats more a rare reading the dictionary knows only with a capital costs, unless it is
|
||||
/// one of your own words: the model's lowercase list holds names and abbreviations ("gs",
|
||||
/// "ut", "kent") that a loose swipe of a common word could read as, and they would go in
|
||||
/// capitalised mid-sentence. Common ones ("john", "york", "english") cost nothing more.
|
||||
var nameCost = 4.0
|
||||
/// The model's cost (-ln p) past which such a word counts as rare: about its 2,500th word.
|
||||
static let commonNameCost = 10.0
|
||||
|
||||
var clock: () -> TimeInterval = { CACurrentMediaTime() }
|
||||
|
||||
@@ -65,7 +72,7 @@ final class SwipeTyping {
|
||||
)
|
||||
var extra = SwipeDecoder.ExtraWords()
|
||||
if model.language == KeyboardLanguage.english.rawValue {
|
||||
extra.add(AutocorrectEngine.englishContractions, cost: { SwipeDecoder.costOfContraction($0) }, model: model)
|
||||
extra.add(AutocorrectEngine.englishContractions, cost: { SwipeDecoder.costOfContraction($0) }, model: model, contractions: true)
|
||||
}
|
||||
extra.add(autocorrect.ownWords, cost: SwipeDecoder.ownWordCost, model: model)
|
||||
decoder.extraWords = extra
|
||||
@@ -155,9 +162,24 @@ final class SwipeTyping {
|
||||
let candidates = decoder.decode(
|
||||
points.map(layout.joinedForSwipe), keys: engine.swipeKeys, previous: engine.swipePreviousWord, limit: 8
|
||||
)
|
||||
let words = ranked(candidates)
|
||||
let elapsed = clock() - started
|
||||
lastDecodeTime = elapsed
|
||||
engine.endSwipe(typing: candidates.map(\.text), points: points.count, decodeTime: elapsed)
|
||||
engine.endSwipe(typing: words, points: points.count, decodeTime: elapsed)
|
||||
}
|
||||
|
||||
/// The readings best first once a rare name or abbreviation costs `nameCost` more.
|
||||
func ranked(_ candidates: [SwipeDecoder.Candidate]) -> [String] {
|
||||
let model = decoder.model
|
||||
func rareName(_ text: String) -> Bool {
|
||||
guard engine.swipeReadsAsName(text) else { return false }
|
||||
return model.index(of: text).map { model.unigramCost($0) > Self.commonNameCost } ?? true
|
||||
}
|
||||
return candidates
|
||||
.map { ($0.text, $0.cost + (rareName($0.text) ? nameCost : 0)) }
|
||||
.enumerated()
|
||||
.sorted { $0.element.1 != $1.element.1 ? $0.element.1 < $1.element.1 : $0.offset < $1.offset }
|
||||
.map(\.element.0)
|
||||
}
|
||||
|
||||
// MARK: - The word so far
|
||||
@@ -173,13 +195,13 @@ final class SwipeTyping {
|
||||
let decoder = decoder, keys = engine.swipeKeys, previous = engine.swipePreviousWord
|
||||
let points = swipe.points.map(engine.layout.joinedForSwipe), generation = generation
|
||||
Self.previewQueue.async { [weak self] in
|
||||
let words = decoder.decode(points, keys: keys, previous: previous, limit: 3).map(\.text)
|
||||
let candidates = decoder.decode(points, keys: keys, previous: previous, limit: 3)
|
||||
DispatchQueue.main.async {
|
||||
MainActor.assumeIsolated {
|
||||
guard let self else { return }
|
||||
self.previewInFlight = false
|
||||
guard self.generation == generation, self.active != nil else { return }
|
||||
self.engine.showSwipePreview(words)
|
||||
self.engine.showSwipePreview(self.ranked(candidates))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,6 +142,21 @@ nonisolated final class TypingDecoderModel: @unchecked Sendable {
|
||||
return index(ofCodes: bytes)
|
||||
}
|
||||
|
||||
/// Whether the model has `second` following `first` as a pair.
|
||||
func hasPair(_ first: String, _ second: String) -> Bool {
|
||||
guard let a = index(of: first), let b = index(of: second) else { return false }
|
||||
return bigramCost(a, b) != nil
|
||||
}
|
||||
|
||||
/// -ln P(word | previous) with the decoder's backoff to the unigram (0.92 nats), or nil
|
||||
/// when the model lacks the word.
|
||||
func cost(of word: String, after previous: String?) -> Double? {
|
||||
guard let i = index(of: word) else { return nil }
|
||||
let backoff = 0.92 + unigramCost(i)
|
||||
guard let previous, let a = index(of: previous), let pair = bigramCost(a, i) else { return backoff }
|
||||
return min(pair, backoff)
|
||||
}
|
||||
|
||||
/// The three most probable allowed continuations of a completed word. Scan just its
|
||||
/// mapped bigram row and keep three entries, even for a word with thousands of followers.
|
||||
func nextWords(after previous: String, allowing: (String) -> Bool) -> [String] {
|
||||
@@ -341,6 +356,16 @@ nonisolated struct TypingDecoder {
|
||||
var insertionCost = 7.0
|
||||
var transpositionCost = 5.0
|
||||
var spaceOmissionCost = 6.0
|
||||
/// A tap on the bottom row's upper half read as a space the finger missed ("ofbthe"):
|
||||
/// this, plus `spaceTapWeight` times how much nearer its letter row than the space bar
|
||||
/// it landed (the bar's Gaussian likelihood against the row's). Below the row's centre
|
||||
/// such a tap costs `spaceOmissionCost`.
|
||||
var spaceTapCost = 5.0
|
||||
var spaceTapWeight = 0.25
|
||||
/// A space tap is read as a letter meant on the row above ("deli ate" for "delicate")
|
||||
/// only when the row is at most this many nats less likely than the space bar for it:
|
||||
/// within about the bar's top fifth, a little deeper than the system keyboard merges.
|
||||
var mergeReach = 3.0
|
||||
var maxEdits = 1
|
||||
var beam = 48
|
||||
/// Nats the best reading must beat what you typed by to replace it on space.
|
||||
@@ -369,6 +394,9 @@ nonisolated struct TypingDecoder {
|
||||
static func tuned(for language: String) -> Parameters {
|
||||
var p = Parameters()
|
||||
if language == "en" { p.lmWeight = 1.5 }
|
||||
// Spanish's many one- and two-letter words ("a", "es", "va") make a letter read as
|
||||
// a space too cheap a split ("vaxes" -> "va es"): there, only below the row's centre.
|
||||
if language == "es" { p.spaceTapCost = .infinity }
|
||||
return p
|
||||
}
|
||||
}
|
||||
@@ -379,11 +407,15 @@ nonisolated struct TypingDecoder {
|
||||
var pitch: CGSize
|
||||
/// The bottom letter row's centre, below which a tap may have been meant for space.
|
||||
var bottomRowY: CGFloat
|
||||
/// The space bar's keycap as on the unsplit keyboard (both bars on a split one), or
|
||||
/// nil when unknown: a bottom-row tap above it may have been meant for space.
|
||||
var space: CGRect?
|
||||
|
||||
init(centres: [Character: CGPoint], pitch: CGSize, bottomRowY: CGFloat) {
|
||||
init(centres: [Character: CGPoint], pitch: CGSize, bottomRowY: CGFloat, space: CGRect? = nil) {
|
||||
self.centres = centres
|
||||
self.pitch = pitch
|
||||
self.bottomRowY = bottomRowY
|
||||
self.space = space
|
||||
}
|
||||
|
||||
/// The letter keys of `layout` (nil off the letters page). `offsets` (in points, by
|
||||
@@ -392,6 +424,12 @@ nonisolated struct TypingDecoder {
|
||||
guard layout.layer == .letters else { return nil }
|
||||
var centres: [Character: CGPoint] = [:]
|
||||
var bottom: CGFloat = 0
|
||||
var space: CGRect?
|
||||
for key in layout.keys where key.kind == .space {
|
||||
let minX = layout.unsplitX(key.frame.minX), maxX = layout.unsplitX(key.frame.maxX)
|
||||
let bar = CGRect(x: minX, y: key.frame.minY, width: max(0, maxX - minX), height: key.frame.height)
|
||||
space = space.map { $0.union(bar) } ?? bar
|
||||
}
|
||||
for key in layout.keys {
|
||||
guard let c = key.character, c.count == 1, let letter = c.first, letter.isLetter else { continue }
|
||||
let shift = offsets[letter] ?? .zero
|
||||
@@ -407,7 +445,8 @@ nonisolated struct TypingDecoder {
|
||||
width: layout.isSplit ? SplitGeometry.pitch : layout.letterWidth + m.gap,
|
||||
height: m.keyHeight + m.rowGap
|
||||
),
|
||||
bottomRowY: bottom
|
||||
bottomRowY: bottom,
|
||||
space: space
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -522,7 +561,7 @@ nonisolated struct TypingDecoder {
|
||||
}
|
||||
}
|
||||
if parameters.splits, letters.count >= 3 {
|
||||
readings += splitReadings(costs, taps: taps, keys: keys, prev: prev)
|
||||
readings += splitReadings(costs, taps: taps, letters: letters, keys: keys, prev: prev)
|
||||
}
|
||||
readings.sort { $0.cost < $1.cost }
|
||||
var seen = Set<String>()
|
||||
@@ -687,16 +726,23 @@ nonisolated struct TypingDecoder {
|
||||
}
|
||||
|
||||
/// Two words where the taps had no space, or one meant for space ("seehow", "seenhow").
|
||||
/// Each half is read with substitutions only, which keeps this cheap.
|
||||
private func splitReadings(_ costs: [[Double]], taps: [CGPoint], keys: Keys, prev: Int?) -> [Reading] {
|
||||
/// Each half is read with substitutions only, which keeps this cheap; around a tap on
|
||||
/// the bottom row's upper half read as a space ("ofbthe"), only as the letters typed, so
|
||||
/// a name's middle letter ("rima") is never a space with slips around it.
|
||||
private func splitReadings(_ costs: [[Double]], taps: [CGPoint], letters: [UInt8], keys: Keys, prev: Int?) -> [Reading] {
|
||||
let n = costs.count
|
||||
var out: [Reading] = []
|
||||
func pair(left: Range<Int>, right: Range<Int>, extra: Double) {
|
||||
func pair(left: Range<Int>, right: Range<Int>, extra: Double, exact: Bool = false) {
|
||||
guard !left.isEmpty, !right.isEmpty else { return }
|
||||
let never = neverSuggest
|
||||
let lefts = search(model, costs, range: left, limit: 3, maxEdits: 0, skipping: never.words).filter { canStandAlone($0.0) }
|
||||
func halves(_ range: Range<Int>) -> [(Int, Double)] {
|
||||
guard exact else { return search(model, costs, range: range, limit: 3, maxEdits: 0, skipping: never.words) }
|
||||
guard let word = model.index(ofCodes: Array(letters[range])), !never.words.contains(word) else { return [] }
|
||||
return [(word, range.reduce(0) { $0 + costs[$1][Int(letters[$1])] })]
|
||||
}
|
||||
let lefts = halves(left).filter { canStandAlone($0.0) }
|
||||
guard !lefts.isEmpty else { return }
|
||||
let rights = search(model, costs, range: right, limit: 3, maxEdits: 0, skipping: never.words).filter { canStandAlone($0.0) }
|
||||
let rights = halves(right).filter { canStandAlone($0.0) }
|
||||
for (l, ls) in lefts {
|
||||
let lcost = ls + parameters.lmWeight * lmCost(l, after: prev)
|
||||
for (r, rs) in rights where !never.follows(r, after: l) {
|
||||
@@ -707,13 +753,88 @@ nonisolated struct TypingDecoder {
|
||||
}
|
||||
for k in 1..<n {
|
||||
pair(left: 0..<k, right: k..<n, extra: parameters.spaceOmissionCost)
|
||||
if k < n - 1, taps[k].y > keys.bottomRowY {
|
||||
guard k < n - 1 else { continue }
|
||||
if taps[k].y > keys.bottomRowY {
|
||||
pair(left: 0..<k, right: (k + 1)..<n, extra: parameters.spaceOmissionCost)
|
||||
} else if let extra = spaceCost(of: taps[k], keys: keys) {
|
||||
pair(left: 0..<k, right: (k + 1)..<n, extra: extra, exact: true)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/// The cost of reading a tap on the bottom row's upper half as a space the finger missed,
|
||||
/// or nil when it can't be one: above the space bar, priced by how much nearer the row's
|
||||
/// centre than the bar's it landed.
|
||||
private func spaceCost(of tap: CGPoint, keys: Keys) -> Double? {
|
||||
guard parameters.spaceTapCost.isFinite, let bar = keys.space, bar.width > 0 else { return nil }
|
||||
let slack = keys.pitch.width / 2
|
||||
guard tap.x >= bar.minX - slack, tap.x <= bar.maxX + slack,
|
||||
tap.y > keys.bottomRowY - keys.pitch.height / 2 else { return nil }
|
||||
let sy = Double(keys.pitch.height) * parameters.sigmaY
|
||||
let toBar = (Double(tap.y) - Double(bar.midY)) / sy
|
||||
let toRow = (Double(tap.y) - Double(keys.bottomRowY)) / sy
|
||||
let likelierRow = max(0, 0.5 * (toBar * toBar - toRow * toRow))
|
||||
return parameters.spaceTapCost + parameters.spaceTapWeight * likelierRow
|
||||
}
|
||||
|
||||
/// How much likelier the space bar than the bottom letter row a space tap was, in nats
|
||||
/// (0 when the row is likelier), or nil when it isn't above a bottom-row letter.
|
||||
private func rowCost(of tap: CGPoint, keys: Keys) -> Double? {
|
||||
guard let bar = keys.space, bar.width > 0 else { return nil }
|
||||
let slack = keys.pitch.width / 2
|
||||
guard tap.x >= bar.minX - slack, tap.x <= bar.maxX + slack else { return nil }
|
||||
let sy = Double(keys.pitch.height) * parameters.sigmaY
|
||||
let toBar = (Double(tap.y) - Double(bar.midY)) / sy
|
||||
let toRow = (Double(tap.y) - Double(keys.bottomRowY)) / sy
|
||||
return max(0, 0.5 * (toRow * toRow - toBar * toBar))
|
||||
}
|
||||
|
||||
/// One word where a space was tapped for a letter on the row above ("deli ate" for
|
||||
/// "delicate", "a out" for "about"): the likeliest reading of the first word's taps, the
|
||||
/// space tap as a letter and the second word's taps, when it beats the two words as they
|
||||
/// read by the margin and the tap was near enough the row (`mergeReach`). Nil to keep them.
|
||||
func merge(
|
||||
first: String, firstTaps: [CGPoint], space: CGPoint, second: String, secondTaps: [CGPoint],
|
||||
previous: String?, firstIsValid: Bool, secondIsValid: Bool, keys: Keys
|
||||
) -> String? {
|
||||
guard firstTaps.count == first.count, secondTaps.count == second.count, !second.isEmpty,
|
||||
let firstCodes = model.encode(first.lowercased()), let secondCodes = model.encode(second.lowercased()),
|
||||
let reach = rowCost(of: space, keys: keys), reach <= parameters.mergeReach else { return nil }
|
||||
let taps = firstTaps + [space] + secondTaps
|
||||
let centres = codeCentres(keys)
|
||||
let costs = taps.map { tapCosts($0, centres: centres, keys: keys) }
|
||||
let prev = previous.flatMap { model.index(of: $0) }
|
||||
// The two words as space would leave them: each as typed or its likeliest reading
|
||||
// ("i dkdnt" is "I didn't", never "obedient").
|
||||
func reading(_ codes: [UInt8], at range: Range<Int>, after before: Int?, valid: Bool) -> (cost: Double, word: Int?) {
|
||||
let typed = model.index(ofCodes: codes)
|
||||
var spatial = 0.0
|
||||
for (i, code) in codes.enumerated() { spatial += costs[range.lowerBound + i][Int(code)] }
|
||||
var best = (cost: spatial + parameters.lmWeight * (typed.map { lmCost($0, after: before) }
|
||||
?? (valid ? parameters.unknownValidCost : parameters.unknownCost)), word: typed)
|
||||
for (word, s) in search(model, costs, range: range, limit: 3, maxEdits: parameters.maxEdits, skipping: neverSuggest.words) {
|
||||
let cost = s + parameters.lmWeight * lmCost(word, after: before)
|
||||
if cost < best.cost { best = (cost, word) }
|
||||
}
|
||||
return best
|
||||
}
|
||||
let firstRange = 0..<firstCodes.count
|
||||
let firstReading = reading(firstCodes, at: firstRange, after: prev, valid: firstIsValid)
|
||||
let secondReading = reading(secondCodes, at: (firstCodes.count + 1)..<taps.count, after: firstReading.word, valid: secondIsValid)
|
||||
let split = firstReading.cost + secondReading.cost
|
||||
guard split.isFinite else { return nil }
|
||||
var best: (word: Int, cost: Double)?
|
||||
for (word, spatial) in search(model, costs, range: 0..<costs.count, limit: 3, maxEdits: parameters.maxEdits, skipping: neverSuggest.words)
|
||||
where model.length(word) > max(first.count, second.count) && !neverSuggest.follows(word, after: prev) {
|
||||
let cost = spatial + parameters.lmWeight * lmCost(word, after: prev) + reach
|
||||
if cost < best?.cost ?? .infinity { best = (word, cost) }
|
||||
}
|
||||
guard let best else { return nil }
|
||||
let margin = firstIsValid && secondIsValid ? parameters.validMargin : parameters.autoMargin
|
||||
return split - best.cost >= margin ? model.word(best.word) : nil
|
||||
}
|
||||
|
||||
/// A word that may stand alone in a split: two or more letters, or a common one-letter
|
||||
/// word ("a" and "i" in English; "y", "a", "o" in Spanish).
|
||||
private func canStandAlone(_ i: Int) -> Bool {
|
||||
|
||||
Reference in New Issue
Block a user