mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-25 01:30:06 +08:00
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.
This commit is contained in:
@@ -872,6 +872,40 @@ final class AutocorrectEngineTests: XCTestCase {
|
||||
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()
|
||||
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")
|
||||
tapCentre("a")
|
||||
edgeSpace(under: "b")
|
||||
typeTaps("out")
|
||||
XCTAssertTrue(target.text.hasSuffix(" so about "), 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)")
|
||||
}
|
||||
|
||||
func testSpatialAutocorrectReadsAnETappedHighOnTheStripAsThe() throws {
|
||||
try useDecoder()
|
||||
typeTaps("on")
|
||||
|
||||
@@ -1042,6 +1042,28 @@ final class AutocorrectEngine {
|
||||
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] {
|
||||
|
||||
@@ -731,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 {
|
||||
@@ -971,6 +971,10 @@ final class FullKeyboardEngine {
|
||||
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?
|
||||
@@ -982,6 +986,32 @@ final class FullKeyboardEngine {
|
||||
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)?
|
||||
@@ -1038,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
|
||||
@@ -1075,11 +1106,12 @@ final class FullKeyboardEngine {
|
||||
return
|
||||
}
|
||||
let token = AutocorrectEngine.currentToken(in: target.documentContextBeforeInput)
|
||||
let taps = currentTokenTaps
|
||||
learning?.didFinish(word: token)
|
||||
syncLearning()
|
||||
autocorrect.decoderTaps = currentTokenTaps
|
||||
autocorrect.decoderTaps = taps
|
||||
if !afterSwipe, finishWord(ending: " ") {
|
||||
rememberFinishedWord(typed: token)
|
||||
rememberFinishedWord(typed: token, taps: taps, space: point)
|
||||
lastSpaceAt = now
|
||||
layerState.didInsert(" ")
|
||||
rebuildLayoutIfNeeded()
|
||||
@@ -1089,19 +1121,25 @@ final class FullKeyboardEngine {
|
||||
}
|
||||
autocorrect.clearPendingUndo()
|
||||
insert(" ", source: "key")
|
||||
if !afterSwipe, let token { rememberFinishedWord(typed: token) }
|
||||
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?) {
|
||||
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
|
||||
}
|
||||
finishedWord = FinishedWord(text: word, typed: typed, before: before)
|
||||
// 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.
|
||||
|
||||
@@ -362,6 +362,10 @@ nonisolated struct TypingDecoder {
|
||||
/// 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.
|
||||
@@ -774,6 +778,53 @@ nonisolated struct TypingDecoder {
|
||||
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) }
|
||||
let firstIndex = model.index(ofCodes: firstCodes)
|
||||
let secondIndex = model.index(ofCodes: secondCodes)
|
||||
var split = 0.0
|
||||
for (i, code) in firstCodes.enumerated() { split += costs[i][Int(code)] }
|
||||
for (i, code) in secondCodes.enumerated() { split += costs[firstCodes.count + 1 + i][Int(code)] }
|
||||
guard split.isFinite else { return nil }
|
||||
let firstLM = firstIndex.map { lmCost($0, after: prev) } ?? (firstIsValid ? parameters.unknownValidCost : parameters.unknownCost)
|
||||
let secondLM = secondIndex.map { lmCost($0, after: firstIndex) } ?? (secondIsValid ? parameters.unknownValidCost : parameters.unknownCost)
|
||||
split += parameters.lmWeight * (firstLM + secondLM)
|
||||
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