diff --git a/app/src/debug/AndroidManifest.xml b/app/src/debug/AndroidManifest.xml
index 3425a4f78f..3d111d4d6d 100644
--- a/app/src/debug/AndroidManifest.xml
+++ b/app/src/debug/AndroidManifest.xml
@@ -4,5 +4,10 @@
+
+
diff --git a/app/src/debug/java/helium314/keyboard/latin/bench/AutocorrectBenchReceiver.kt b/app/src/debug/java/helium314/keyboard/latin/bench/AutocorrectBenchReceiver.kt
new file mode 100644
index 0000000000..a4da104c00
--- /dev/null
+++ b/app/src/debug/java/helium314/keyboard/latin/bench/AutocorrectBenchReceiver.kt
@@ -0,0 +1,177 @@
+// SPDX-License-Identifier: GPL-3.0-only
+package helium314.keyboard.latin.bench
+
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import android.os.SystemClock
+import android.util.Log
+import androidx.core.content.edit
+import com.android.inputmethod.latin.utils.BinaryDictionaryUtils
+import helium314.keyboard.event.Event
+import helium314.keyboard.keyboard.Key
+import helium314.keyboard.keyboard.Keyboard
+import helium314.keyboard.keyboard.KeyboardId
+import helium314.keyboard.keyboard.KeyboardLayoutSet
+import helium314.keyboard.keyboard.KeyboardSwitcher
+import helium314.keyboard.keyboard.internal.keyboard_parser.floris.KeyCode
+import helium314.keyboard.latin.DictionaryFacilitator
+import helium314.keyboard.latin.DictionaryFacilitatorImpl
+import helium314.keyboard.latin.NgramContext
+import helium314.keyboard.latin.Suggest
+import helium314.keyboard.latin.SuggestedWords
+import helium314.keyboard.latin.WordComposer
+import helium314.keyboard.latin.common.Constants
+import helium314.keyboard.latin.settings.Settings
+import helium314.keyboard.latin.utils.JniUtils
+import helium314.keyboard.latin.utils.SubtypeSettings
+import helium314.keyboard.latin.utils.getSecondaryLocales
+import helium314.keyboard.latin.utils.prefs
+import java.io.File
+import java.util.Locale
+import java.util.concurrent.TimeUnit
+import kotlin.concurrent.thread
+import kotlin.math.roundToInt
+
+/**
+ * Debug builds only. Replays typed words through the shown keyboard, the native decoder and [Suggest], and writes
+ * what auto-correction would commit. Driven by tools/autocorrect_bench/bench.py, which also describes the formats.
+ *
+ * Uses its own dictionaries without learned history, contacts and apps, so a run does not depend on earlier typing.
+ */
+class AutocorrectBenchReceiver : BroadcastReceiver() {
+ override fun onReceive(context: Context, intent: Intent) {
+ val dir = context.getExternalFilesDir(null) ?: return
+ val threshold = intent.getStringExtra("threshold")?.toFloat() ?: THRESHOLD_DEFAULT
+ // words committed before the cases, they set the confidence of each language like while typing
+ val history = intent.getStringExtra("history").orEmpty().split(' ').filter { it.isNotEmpty() }
+ val appContext = context.applicationContext
+ val output = File(dir, "bench_out.tsv")
+ output.delete()
+ // not the shown keyboard: that one is shifted after a sentence end, and the decoder gets other results with it
+ val keyboard = runCatching { unshiftedKeyboard() }.onFailure { Log.e(TAG, "no keyboard", it) }.getOrNull()
+ thread(name = "autocorrect-bench") {
+ val result = try {
+ requireNotNull(keyboard) { "show the keyboard first" }
+ run(appContext, keyboard, File(dir, "bench_in.tsv").readLines(), threshold, history)
+ } catch (e: Exception) {
+ Log.e(TAG, "bench failed", e)
+ "#error\t$e\n"
+ }
+ // the host waits for the file, so it must appear complete
+ val partial = File(dir, "bench_out.tmp")
+ partial.writeText(result)
+ partial.renameTo(output)
+ }
+ }
+
+ private fun unshiftedKeyboard(): Keyboard {
+ val field = KeyboardSwitcher::class.java.getDeclaredField("mKeyboardLayoutSet").apply { isAccessible = true }
+ return (field.get(KeyboardSwitcher.getInstance()) as KeyboardLayoutSet).getKeyboard(KeyboardId.ELEMENT_ALPHABET)
+ }
+
+ private fun run(context: Context, keyboard: Keyboard, lines: List, threshold: Float,
+ history: List): String {
+ val prefs = context.prefs()
+ val overrides = mapOf(Settings.PREF_AUTO_CORRECTION to true)
+ val previous = overrides.keys.associateWith { if (prefs.contains(it)) prefs.getBoolean(it, false) else null }
+ val hadThreshold = prefs.contains(Settings.PREF_AUTO_CORRECT_THRESHOLD)
+ val previousThreshold = prefs.getFloat(Settings.PREF_AUTO_CORRECT_THRESHOLD, THRESHOLD_DEFAULT)
+ val facilitator: DictionaryFacilitator = DictionaryFacilitatorImpl()
+ try {
+ // the score limit used by Suggest is derived from these settings
+ prefs.edit {
+ overrides.forEach { putBoolean(it.key, it.value) }
+ putFloat(Settings.PREF_AUTO_CORRECT_THRESHOLD, threshold)
+ }
+ Thread.sleep(SETTINGS_RELOAD_MILLIS)
+ val locale = keyboard.mId.locale
+ facilitator.resetDictionaries(context, locale, false, false, false, "", null)
+ facilitator.waitForLoadingMainDictionaries(30, TimeUnit.SECONDS)
+ require(facilitator.hasAtLeastOneInitializedMainDictionary()) { "no main dictionary for $locale" }
+ val suggest = Suggest(facilitator).apply { setAutoCorrectionThreshold(threshold) }
+ val keys = keyboard.sortedKeys.filter { it.code > 0 && Character.isLetter(it.code) }
+
+ history.forEach { facilitator.adjustConfidences(it, false) }
+ val confidences = facilitator.localesAndConfidences()
+
+ val result = StringBuilder()
+ val settings = Settings.getValues()
+ val extraLocales = getSecondaryLocales(SubtypeSettings.getSelectedSubtype(prefs).extraValue)
+ result.append("#meta\tlocales=${(listOf(locale) + extraLocales).joinToString(",")}" +
+ "\tgestureLib=${JniUtils.sHaveNativeGestureLib}\tconfidences=$confidences\temojis=${settings.mSuggestEmojis}\tmultiword=${!settings.mDisableMultiWordSuggestions}\tthreshold=$threshold\tkeyboard=${keyboard.mId.mWidth}x${keyboard.mOccupiedHeight}" +
+ "\tkeyWidth=${keyboard.mMostCommonKeyWidth}\n")
+ var keyPresses = 0
+ val start = SystemClock.elapsedRealtimeNanos()
+ for (line in lines) {
+ if (line.isBlank() || line.startsWith("#")) continue
+ val case = runCase(suggest, keyboard, keys, line)
+ keyPresses += case.substringAfter('\t').substringBefore('\t').length
+ result.append(case).append('\n')
+ }
+ val millis = (SystemClock.elapsedRealtimeNanos() - start) / 1_000_000.0
+ result.append("#time\t${"%.2f".format(Locale.ROOT, millis / keyPresses.coerceAtLeast(1))}\n")
+ result.append("#done\n")
+ return result.toString()
+ } finally {
+ facilitator.closeDictionaries()
+ prefs.edit {
+ previous.forEach { (key, value) -> if (value == null) remove(key) else putBoolean(key, value) }
+ if (hadThreshold) putFloat(Settings.PREF_AUTO_CORRECT_THRESHOLD, previousThreshold)
+ else remove(Settings.PREF_AUTO_CORRECT_THRESHOLD)
+ }
+ }
+ }
+
+ // input: id \t previous words (space separated, may be empty) \t text \t offsets "dx:dy,..." (in key sizes)
+ private fun runCase(suggest: Suggest, keyboard: Keyboard, keys: List, line: String): String {
+ val (id, previous, text, offsetText) = line.split('\t')
+ val offsets = offsetText.split(',').map { pair -> pair.split(':').map { it.toFloat() } }
+ val previousWords = previous.split(' ').filter { it.isNotEmpty() }.reversed()
+ val ngramContext = if (previousWords.isEmpty()) NgramContext.BEGINNING_OF_SENTENCE
+ else NgramContext(*previousWords.take(3).map { NgramContext.WordInfo(it) }.toTypedArray())
+
+ val composer = WordComposer()
+ composer.restartCombining("")
+ composer.setCapitalizedModeAtStartComposingTime(
+ if (previousWords.isEmpty() && text.first().isUpperCase()) WordComposer.CAPS_MODE_AUTO_SHIFTED
+ else WordComposer.CAPS_MODE_OFF)
+ var words: SuggestedWords? = null
+ text.forEachIndexed { index, char ->
+ val (dx, dy) = offsets[index]
+ val (code, x, y) = tap(keys, char, dx, dy)
+ val event = Event.createSoftwareKeypressEvent(code, KeyCode.NOT_SPECIFIED, 0, x, y, false)
+ composer.applyProcessedEvent(composer.processEvent(event))
+ // after each letter, like while typing: the decoder keeps state between the calls
+ words = suggest.getSuggestedWords(composer, ngramContext, keyboard,
+ Settings.getValues().mSettingsValuesForSuggestion, true, SuggestedWords.INPUT_STYLE_TYPING, 0)
+ }
+ val suggested = words!!
+ val typed = composer.getTypedWord()
+ val committed = if (suggested.mWillAutoCorrect) suggested.getWord(SuggestedWords.INDEX_OF_AUTO_CORRECTION) else typed
+ val candidates = (0 until minOf(suggested.size(), 6)).joinToString("|") {
+ val info = suggested.getInfo(it)
+ val normalized = BinaryDictionaryUtils.calcNormalizedScore(typed, info.mWord, info.mScore)
+ "${info.mWord}~${info.mSourceDict.mDictType}:${info.mSourceDict.mLocale?.language.orEmpty()}~${info.mScore}~${info.mKindAndFlags}~$normalized"
+ }
+ return "$id\t$typed\t$committed\t$candidates"
+ }
+
+ // the touch point is the key center moved by the offset, and the typed letter is the key it lands on
+ private fun tap(keys: List, char: Char, dx: Float, dy: Float): Triple {
+ val intended = keys.firstOrNull { Character.toLowerCase(it.code) == char.lowercaseChar().code }
+ ?: return Triple(char.code, Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE)
+ val x = (intended.x + intended.width / 2 + dx * intended.width).roundToInt()
+ val y = (intended.y + intended.height / 2 + dy * intended.height).roundToInt()
+ // nearest letter, so a point on space or shift still gives a letter
+ val hit = keys.minBy { it.squaredDistanceToEdge(x, y) }
+ val code = if (char.isUpperCase()) Character.toUpperCase(hit.code) else Character.toLowerCase(hit.code)
+ return Triple(code, x, y)
+ }
+
+ private companion object {
+ const val TAG = "AutocorrectBench"
+ const val THRESHOLD_DEFAULT = 0.067f
+ const val SETTINGS_RELOAD_MILLIS = 500L
+ }
+}
diff --git a/app/src/main/java/helium314/keyboard/latin/DictionaryFacilitatorImpl.kt b/app/src/main/java/helium314/keyboard/latin/DictionaryFacilitatorImpl.kt
index 7b057e06aa..4785d8067d 100644
--- a/app/src/main/java/helium314/keyboard/latin/DictionaryFacilitatorImpl.kt
+++ b/app/src/main/java/helium314/keyboard/latin/DictionaryFacilitatorImpl.kt
@@ -1321,12 +1321,12 @@ private class DictionaryGroup(
// might need some more tuning
fun getWeightForLocale(groups: List, step: Float): Float {
- if (groups.size == 1) return 1f
- if (confidence < 2) return 1f - step * (MAX_CONFIDENCE - confidence)
- for (group in groups) {
- if (group !== this && group.confidence >= confidence) return 1f - step / 2f
- }
- return 1f
+ // The most likely language (the first one when tied) must keep the full weight: below 0.99 the native
+ // decoder doesn't correct a missing space or a letter typed instead of space, and searches less.
+ // Only one: a second dictionary searched fully has so many candidates that it wins over the right ones.
+ if (groups.maxBy { it.confidence } === this) return 1f
+ if (confidence < MAX_CONFIDENCE) return 1f - step * (MAX_CONFIDENCE - confidence)
+ return 1f - step / 2f
}
// --------------- Blacklist -------------------
diff --git a/app/src/main/java/helium314/keyboard/latin/LikelySlip.kt b/app/src/main/java/helium314/keyboard/latin/LikelySlip.kt
new file mode 100644
index 0000000000..61287164b5
--- /dev/null
+++ b/app/src/main/java/helium314/keyboard/latin/LikelySlip.kt
@@ -0,0 +1,44 @@
+// SPDX-License-Identifier: GPL-3.0-only
+package helium314.keyboard.latin
+
+import java.util.Locale
+
+/**
+ * The decoder weighs every difference by key distance and word frequency, so it often prefers a neighbor key
+ * replacement over a more likely explanation ("novles" -> "nobles" instead of "novels"). These explanations need
+ * no other letter than the typed ones, so such a candidate wins if the decoder rates it nearly as high.
+ * Measured with tools/autocorrect_bench.
+ */
+object LikelySlip {
+ // shorter words have too many such candidates, see ShortWordGuard
+ const val MIN_LENGTH = 4
+
+ // how much of the first candidate's score the likely one needs
+ const val MIN_SCORE_RATIO = 0.7f
+
+ fun isBetterExplanation(typed: String, first: String, firstScore: Int, other: String, otherScore: Int): Boolean =
+ typed.length >= MIN_LENGTH && otherScore > 0 && otherScore >= firstScore * MIN_SCORE_RATIO
+ && explains(typed, other) && !explains(typed, first)
+
+ /** Whether [typed] is [word] with two neighboring letters swapped or with one letter typed twice, case is ignored */
+ fun explains(typed: String, word: String): Boolean {
+ val a = typed.lowercase(Locale.ROOT)
+ val b = word.lowercase(Locale.ROOT)
+ return isSwapOfNeighbors(a, b) || isDoubledLetter(a, b)
+ }
+
+ private fun isSwapOfNeighbors(typed: String, word: String): Boolean {
+ if (typed.length != word.length) return false
+ val i = typed.indices.firstOrNull { typed[it] != word[it] } ?: return false
+ return i + 1 < typed.length && typed[i] == word[i + 1] && typed[i + 1] == word[i]
+ && typed.substring(i + 2) == word.substring(i + 2)
+ && typed[i].isLetter() && typed[i + 1].isLetter()
+ }
+
+ private fun isDoubledLetter(typed: String, word: String): Boolean {
+ if (typed.length != word.length + 1) return false
+ // the first difference is where the extra letter is, or the end
+ val i = word.indices.firstOrNull { typed[it] != word[it] } ?: word.length
+ return i > 0 && typed[i] == typed[i - 1] && typed[i].isLetter() && typed.removeRange(i, i + 1) == word
+ }
+}
diff --git a/app/src/main/java/helium314/keyboard/latin/Suggest.kt b/app/src/main/java/helium314/keyboard/latin/Suggest.kt
index 556326c272..6783f72ba2 100644
--- a/app/src/main/java/helium314/keyboard/latin/Suggest.kt
+++ b/app/src/main/java/helium314/keyboard/latin/Suggest.kt
@@ -127,6 +127,8 @@ class Suggest(private val mDictionaryFacilitator: DictionaryFacilitator) {
makeFirstTwoSuggestionsNonEmoji(suggestionsContainer)
promoteMissingApostropheContraction(typedWordString.dropLast(trailingSingleQuotesCount),
typedWordFirstOccurrenceWordInfo, suggestionsContainer)
+ promoteLikelySlip(typedWordString.dropLast(trailingSingleQuotesCount),
+ typedWordFirstOccurrenceWordInfo, suggestionsContainer)
promoteExactShortcut(suggestionsContainer)
val (allowsToBeAutoCorrected, hasAutoCorrection) = shouldBeAutoCorrected(
@@ -390,6 +392,13 @@ class Suggest(private val mDictionaryFacilitator: DictionaryFacilitator) {
return true to true
}
+ // With several languages, a word of one language is easily split into short words of another one
+ // ("hotovogratulujem" -> "hot of of rat you men"). Such a split stays available as suggestion.
+ if (firstSuggestion.mWord.count { it == ' ' } > 1 && !firstSuggestion.isKindOf(SuggestedWordInfo.KIND_WHITELIST)
+ && mDictionaryFacilitator.localesAndConfidences() != null) { // null for a single language
+ return true to false
+ }
+
if (!AutoCorrectionUtils.suggestionExceedsThreshold(firstSuggestion, consideredWord, mAutoCorrectionThreshold)) {
// Score is too low for autocorrect — but for long words, the normalized score
// formula penalizes proportionally (weight = 1 - editDist/len), so a single typo
@@ -732,6 +741,26 @@ class Suggest(private val mDictionaryFacilitator: DictionaryFacilitator) {
if (index > 0) candidates.add(0, candidates.removeAt(index))
}
+ /**
+ * Moves a candidate that explains an unknown typed word much better than the first one to the front,
+ * see [LikelySlip]. Only the next two candidates are considered. Dictionary replacements, shortcuts, contractions
+ * and the user's own words stay first.
+ */
+ // public for testing
+ fun promoteLikelySlip(typed: String, typedWordInfo: SuggestedWordInfo?, candidates: MutableList) {
+ val first = candidates.firstOrNull() ?: return
+ if (typedWordInfo != null || first.isKindOf(SuggestedWordInfo.KIND_WHITELIST)
+ || first.isKindOf(SuggestedWordInfo.KIND_SHORTCUT) || first.mWord.contains('\'')) return
+ // the user's own words stay first
+ val dictType = first.mSourceDict.mDictType
+ if (dictType == Dictionary.TYPE_USER || dictType == Dictionary.TYPE_USER_HISTORY) return
+ val index = (1..minOf(2, candidates.lastIndex)).firstOrNull {
+ val other = candidates[it]
+ LikelySlip.isBetterExplanation(typed, first.mWord, first.mScore, other.mWord, other.mScore)
+ } ?: return
+ candidates.add(0, candidates.removeAt(index))
+ }
+
/** Whether [word] is [typed] written in all caps. A single capital letter like "I" does not count. */
private fun isAllCapsVariant(typed: String, word: String): Boolean =
word != typed && word.equals(typed, ignoreCase = true)
diff --git a/app/src/test/java/helium314/keyboard/latin/DictionaryGroupTest.kt b/app/src/test/java/helium314/keyboard/latin/DictionaryGroupTest.kt
index 23b3562b73..fac7d4c388 100644
--- a/app/src/test/java/helium314/keyboard/latin/DictionaryGroupTest.kt
+++ b/app/src/test/java/helium314/keyboard/latin/DictionaryGroupTest.kt
@@ -15,6 +15,35 @@ import java.util.Locale
class DictionaryGroupTest {
+ @Test
+ fun testWeightForLocale() {
+ val dictGroupClass = Class.forName("helium314.keyboard.latin.DictionaryGroup")
+ val constructor = dictGroupClass.declaredConstructors.first { it.parameterCount == 4 }
+ constructor.isAccessible = true
+ val confidence = dictGroupClass.getDeclaredField("confidence").apply { isAccessible = true }
+ val weight = dictGroupClass.getDeclaredMethod("getWeightForLocale", List::class.java, Float::class.java)
+ weight.isAccessible = true
+ fun weights(vararg confidences: Int): List {
+ val groups = confidences.map { value ->
+ constructor.newInstance(Locale.ENGLISH, null, emptyMap(), null)
+ .also { confidence.setInt(it, value) }
+ }
+ return groups.map { weight.invoke(it, groups, 0.15f) as Float }
+ }
+
+ // a single language and the leading one keep the full weight
+ assertEquals(listOf(1f), weights(0))
+ assertEquals(listOf(1f, 1f - 0.15f), weights(2, 1))
+ assertEquals(listOf(1f, 1f - 0.15f * 2), weights(1, 0))
+ assertEquals(listOf(1f, 1f - 0.15f / 2), weights(21, 19))
+ assertEquals(listOf(1f - 0.15f / 2, 1f, 1f - 0.15f * 2), weights(2, 17, 0))
+ // when tied, only the first one does
+ assertEquals(listOf(1f, 1f - 0.15f), weights(1, 1))
+ assertEquals(listOf(1f, 1f - 0.15f * 2), weights(0, 0))
+ assertEquals(listOf(1f, 1f - 0.15f / 2), weights(7, 7))
+ assertEquals(listOf(1f - 0.15f, 1f, 1f - 0.15f / 2), weights(1, 2, 2))
+ }
+
@Test
fun testCloseDict_MainDict() {
val dictGroupClass = Class.forName("helium314.keyboard.latin.DictionaryGroup")
diff --git a/app/src/test/java/helium314/keyboard/latin/LikelySlipTest.kt b/app/src/test/java/helium314/keyboard/latin/LikelySlipTest.kt
new file mode 100644
index 0000000000..37b1f31205
--- /dev/null
+++ b/app/src/test/java/helium314/keyboard/latin/LikelySlipTest.kt
@@ -0,0 +1,38 @@
+// SPDX-License-Identifier: GPL-3.0-only
+package helium314.keyboard.latin
+
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class LikelySlipTest {
+ @Test
+ fun swapsAndDoubledLettersExplainTheTypedWord() {
+ for ((typed, word) in listOf("novles" to "novels", "noce" to "once", "Paek" to "peak", "peka" to "peak",
+ "marrked" to "marked", "showw" to "show", "mmoney" to "money", "monney" to "Money", "tooo" to "too")) {
+ assertTrue("$typed -> $word", LikelySlip.explains(typed, word))
+ }
+ }
+
+ @Test
+ fun otherDifferencesDoNot() {
+ for ((typed, word) in listOf("novles" to "nobles", "novels" to "novels", "marked" to "marred",
+ "show" to "shows", "tols" to "tolls", "marrked" to "married", "abcd" to "cbad", "a12b" to "a21b",
+ "x11y" to "x1y", "word" to "wor", "" to "", "a" to "", "ab" to "ab c")) {
+ assertFalse("$typed -> $word", LikelySlip.explains(typed, word))
+ }
+ }
+
+ @Test
+ fun onlyNearlyAsLikelyCandidatesWin() {
+ fun better(typed: String, first: String, firstScore: Int, other: String, otherScore: Int) =
+ LikelySlip.isBetterExplanation(typed, first, firstScore, other, otherScore)
+ assertTrue(better("novles", "nobles", 345934, "novels", 279162))
+ assertFalse(better("novles", "nobles", 345934, "novels", 200000)) // decoder is much less sure
+ assertFalse(better("fwe", "fee", 500000, "few", 500000)) // too short
+ assertFalse(better("fomr", "form", 500000, "from", 500000)) // the first one explains it too
+ assertFalse(better("novles", "nobles", -100000, "novels", -90000)) // scores without any confidence
+ assertTrue(better("novles", "nobles", -100000, "novels", 1000))
+ assertTrue(better("novles", "nobles", Int.MAX_VALUE, "novels", Int.MAX_VALUE))
+ }
+}
diff --git a/app/src/test/java/helium314/keyboard/latin/SuggestTest.kt b/app/src/test/java/helium314/keyboard/latin/SuggestTest.kt
index 635889dc46..043b533b1f 100644
--- a/app/src/test/java/helium314/keyboard/latin/SuggestTest.kt
+++ b/app/src/test/java/helium314/keyboard/latin/SuggestTest.kt
@@ -411,6 +411,42 @@ class SuggestTest {
assertEquals(listOf("Noe"), candidates.map { it.mWord })
}
+ @Test fun `no autocorrect into three or more words with several languages`() {
+ val en = Locale.ENGLISH
+ fun corrects(word: String) = shouldBeAutoCorrected("hotovogratulujem", listOf(suggestion(word, 1500000, en)),
+ null, null, en, thresholdVeryAggressive).last()
+ val longSplit = "hot of rat you"
+ assertEquals(true, corrects(longSplit))
+ languagesAndConfidences = "en 1, sk 1"
+ try {
+ assertEquals(false, corrects(longSplit))
+ assertEquals(true, corrects("hotovo gratulujem"))
+ } finally {
+ languagesAndConfidences = null
+ }
+ }
+
+ @Test fun `likely slip is promoted only over dictionary words for an unknown typed word`() {
+ val en = Locale.ENGLISH
+ fun candidates(first: SuggestedWords.SuggestedWordInfo = suggestion("nobles", 345934, en)) =
+ mutableListOf(first, suggestion("movies", 283794, en), suggestion("novels", 279162, en))
+ fun promoted(typedInfo: SuggestedWords.SuggestedWordInfo?, list: MutableList) =
+ list.also { Suggest.promoteLikelySlip("novles", typedInfo, it) }.map { it.mWord }
+
+ assertEquals(listOf("novels", "nobles", "movies"), promoted(null, candidates()))
+ // the typed word is valid
+ assertEquals(listOf("nobles", "movies", "novels"), promoted(suggestion("novles", 100, en), candidates()))
+ // dictionary replacements and the user's own words stay first
+ assertEquals("nobles", promoted(null, candidates(suggestion("nobles", 345934, en, shortcut = true))).first())
+ assertEquals("nobles", promoted(null, candidates(exactShortcut("nobles", 345934, en))).first())
+ val personal = SuggestedWords.SuggestedWordInfo("nobles", "", 345934, SuggestedWords.SuggestedWordInfo.KIND_CORRECTION,
+ TestDict(en, Dictionary.TYPE_USER_HISTORY), 0, 0)
+ assertEquals("nobles", promoted(null, candidates(personal)).first())
+ // nothing to promote
+ assertEquals(emptyList(), promoted(null, mutableListOf()))
+ assertEquals(listOf("nobles"), promoted(null, mutableListOf(suggestion("nobles", 345934, en))))
+ }
+
@Test fun `missing apostrophe contraction is moved first, so auto-correct commits it`() {
val candidates = mutableListOf(suggestion("did", 1000000, Locale.ENGLISH), suggestion("didn't", 900000, Locale.ENGLISH))
Suggest.promoteMissingApostropheContraction("didnt", null, candidates)
@@ -538,6 +574,7 @@ class SuggestTest {
}
private var currentTypingLocale = Locale.ENGLISH
+private var languagesAndConfidences: String? = null // null for a single language
/** A shortcut whose key was typed exactly, as flagged by the native dictionary */
fun exactShortcut(word: String, score: Int, locale: Locale, dictType: String = Dictionary.TYPE_USER) = SuggestedWordInfo(word, "",
@@ -565,6 +602,8 @@ class ShadowFacilitator {
@Implementation
fun getCurrentLocale(): Locale = currentTypingLocale
@Implementation
+ fun localesAndConfidences(): String? = languagesAndConfidences
+ @Implementation
fun hasAtLeastOneInitializedMainDictionary() = true // otherwise no autocorrect
}
diff --git a/tools/autocorrect_bench/.gitignore b/tools/autocorrect_bench/.gitignore
new file mode 100644
index 0000000000..ea93687fe2
--- /dev/null
+++ b/tools/autocorrect_bench/.gitignore
@@ -0,0 +1,2 @@
+out/
+__pycache__/
diff --git a/tools/autocorrect_bench/README.md b/tools/autocorrect_bench/README.md
new file mode 100644
index 0000000000..ef91ee0bb0
--- /dev/null
+++ b/tools/autocorrect_bench/README.md
@@ -0,0 +1,76 @@
+# Auto-correction benchmark
+
+Reproducible measurement of auto-correction, for the loop: measure, change, measure on new cases.
+
+A debug-only receiver (`app/src/debug/.../bench/AutocorrectBenchReceiver.kt`) replays touch points through the
+unshifted keyboard, the native decoder and `Suggest`, and reports what space would commit. It uses its own
+dictionaries without learned history, contacts and apps. The same seed and code give identical scores.
+Checked against real taps on Waydroid (2026-11-30): 39 of 40 committed words matched.
+
+## Setup
+
+- Waydroid session (or `--serial`) with the debug app installed and selected as keyboard.
+- The keyboard was shown once since the app started (open any text field).
+- Profile: English (US) selected without a multilingual language (or the ones given with `--locales`), emoji and
+ multi-word suggestions on. `bench.py` refuses to run otherwise, `--any-profile` skips the check.
+- The word list for generating cases is downloaded once to `~/.cache/autocorrect_bench/`.
+
+## Loop
+
+```sh
+B="python3 tools/autocorrect_bench/bench.py"
+$B run --suite fixed --seed 1 --label base-fixed # hand written cases, fixed_cases.tsv
+$B run --label base # new generated cases, note the printed seed
+$B show base --stage ranked_low # why cases fail, with candidates and scores
+# change the code, build, install
+$B run --seed --label change
+$B compare base change
+# a rule tuned on one seed must also win on seeds it has not seen: run before and after on a new one
+```
+
+Without `--seed`, each run takes a new one, so the cases are rewritten every iteration. Results are saved in `out/`
+(not committed) with all candidates, so re-ranking rules can be tried on them without a device.
+`--threshold` runs another auto-correction aggressiveness.
+
+## Cases
+
+- Typos: one or two neighbor key slips (touch point just past the key border), swapped, missing, extra and doubled
+ letters, short words, a missing space or a letter hit instead of it, typos after a likely previous word.
+ Typos that are dictionary words are skipped.
+- Keep: common to rare words that must not change.
+- Slovak (`--suite slovak`): typos, words typed without accents, missing space, correct words.
+- Fixed: common misspellings, apostrophes, slang, names, romanized Malayalam and Hindi.
+
+`ok%` is the committed word. For misses, `no_sugg`: the word is not among the first candidates, `low`: it is
+ranked below another word, `gated`: it is first but the auto-correct decision said no.
+
+The mix of typo types is not that of real typing (substitutions and omissions are more frequent than swaps there),
+so compare per category, not only the total.
+
+## Gotchas
+
+- Never use the keyboard on screen for the replay: with the auto-shifted keyboard the same input scored 78%
+ instead of 90%.
+- Compare runs of the same suite, seed and word list only.
+
+## Multilingual
+
+Set the second language on the keyboard, then pass `--locales en_US,sk`. `--history "words"` feeds committed words
+first, which sets the confidence of each language like typing does. Measure fresh (no history, a tie), after words of
+each language, with `--suite generated` (English) and `--suite slovak`.
+
+Learned (2026-11-30, English + Slovak):
+- Below a language weight of 0.99 the native decoder corrects no missing space and searches less.
+- Giving both tied languages the full weight halved the English result: only the leading one gets it.
+- The experimental Slovak list has 97 of the 100 most frequent English words, many at its top frequency, and no
+ bigrams. After 21 English words the confidences were 21 and 19. With English leading, about 90% of the failed
+ English typos came from Slovak entries (a Slovak word chosen, or the typo counted as valid).
+
+## Open
+
+- Multilingual with English leading: typos 76% (seed 2003), English alone about 91% (seed 1003). Needs a cleaner
+ Slovak word list; not tried with another second language.
+- No missing space is found for the language that is not leading.
+- Unknown words meant to stay are often changed: 57 of 169 in the fixed set (names, slang, other languages).
+- Swaps in 3 letter words are often not suggested at all ("yuo", "fwe").
+- Shift lock typing uses the shifted keyboard, gestures: not measured.
diff --git a/tools/autocorrect_bench/bench.py b/tools/autocorrect_bench/bench.py
new file mode 100644
index 0000000000..393aadb171
--- /dev/null
+++ b/tools/autocorrect_bench/bench.py
@@ -0,0 +1,436 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-3.0-only
+"""Reproducible auto-correction benchmark, run on Waydroid or a device with the debug app. See README.md."""
+
+import argparse
+import hashlib
+import json
+import random
+import re
+import subprocess
+import sys
+import tempfile
+import time
+import unicodedata
+import urllib.request
+from collections import Counter, defaultdict
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+OUT = HERE / "out"
+CACHE = Path.home() / ".cache" / "autocorrect_bench"
+WORDLIST_URL = "https://codeberg.org/Helium314/aosp-dictionaries/raw/branch/main/wordlists/main_en_US.combined"
+PACKAGE = "com.leanbitlab.leantype.debug"
+RECEIVER = f"{PACKAGE}/helium314.keyboard.latin.bench.AutocorrectBenchReceiver"
+REMOTE = f"/sdcard/Android/data/{PACKAGE}/files"
+# the settings results are comparable in
+PROFILE = ("emojis=true", "multiword=true")
+DEFAULT_SERIAL = "192.168.240.112:5555"
+
+QWERTY = ("qwertyuiop", "asdfghjkl", "zxcvbnm")
+ROW_SHIFT = (0.0, 0.5, 1.5)
+ROW_HEIGHT = 1.35 # key height relative to key width
+POSITIONS = {c: (ROW_SHIFT[r] + i, r * ROW_HEIGHT) for r, row in enumerate(QWERTY) for i, c in enumerate(row)}
+NEIGHBORS = {a: [b for b, (bx, by) in POSITIONS.items() if a != b and abs(ax - bx) <= 1.1 and abs(ay - by) <= 1.4]
+ for a, (ax, ay) in POSITIONS.items()}
+
+
+SLOVAK_URL = WORDLIST_URL.replace("main_en_US", "main_sk__experimental")
+
+
+def load_wordlist(name="en_US", url=WORDLIST_URL):
+ """words as (word, frequency) sorted by frequency, and bigrams as word -> following words"""
+ path = CACHE / f"{name}.combined"
+ if not path.exists():
+ CACHE.mkdir(parents=True, exist_ok=True)
+ urllib.request.urlretrieve(url, path)
+ words, bigrams, current = {}, defaultdict(list), None
+ for line in path.read_text(encoding="utf-8").splitlines():
+ if line.lstrip().startswith("word="):
+ fields = dict(f.split("=", 1) for f in line.strip().split(",") if "=" in f)
+ current = fields["word"]
+ if fields.get("possibly_offensive") == "true" or fields.get("not_a_word") == "true":
+ current = None
+ continue
+ words[current] = int(fields["f"])
+ elif line.startswith(" bigram=") and current:
+ bigrams[current].append(line.strip().split(",")[0].split("=", 1)[1])
+ digest = hashlib.sha256(path.read_bytes()).hexdigest()[:12]
+ return sorted(words.items(), key=lambda w: (-w[1], w[0])), bigrams, digest
+
+
+class Generator:
+ def __init__(self, seed):
+ self.rng = random.Random(seed)
+ ranked, self.bigrams, self.digest = load_wordlist()
+ self.valid = {w.lower() for w, _ in ranked}
+ plain = [w for w, _ in ranked if re.fullmatch(r"[a-z]+", w)]
+ self.common = plain[:3000]
+ self.medium = plain[3000:20000]
+ self.rare = plain[20000:80000]
+
+ def jitter(self, text):
+ """normal touch noise that stays on the typed key"""
+ def one(sigma):
+ return max(-0.42, min(0.42, self.rng.gauss(0, sigma)))
+ return [(one(0.17), one(0.15)) for _ in text]
+
+ def slip(self, offsets, index, typed, intended):
+ """touch point between the two keys, just on the side of the typed one: 0.5 is the border, 1 the center"""
+ (ix, iy), (tx, ty) = POSITIONS[intended], POSITIONS[typed]
+ share = self.rng.uniform(0.54, 0.78)
+ dx = (ix - tx) * (1 - share) + self.rng.gauss(0, 0.05)
+ dy = (iy - ty) / ROW_HEIGHT * (1 - share) + self.rng.gauss(0, 0.05)
+ offsets[index] = (max(-0.45, min(0.45, dx)), max(-0.45, min(0.45, dy)))
+
+ # every typo returns (typed, offsets) or None if the word does not fit
+ def sub(self, word, count=1):
+ spots = [i for i, c in enumerate(word) if c in POSITIONS]
+ if len(spots) < count:
+ return None
+ typed, changes = list(word), []
+ for i in self.rng.sample(spots, count):
+ typed[i] = self.rng.choice(NEIGHBORS[word[i]])
+ changes.append((i, typed[i], word[i]))
+ text = "".join(typed)
+ offsets = self.jitter(text)
+ for change in changes:
+ self.slip(offsets, *change)
+ return text, offsets
+
+ def transpose(self, word):
+ spots = [i for i in range(len(word) - 1) if word[i] != word[i + 1]]
+ if not spots:
+ return None
+ i = self.rng.choice(spots)
+ text = word[:i] + word[i + 1] + word[i] + word[i + 2:]
+ return text, self.jitter(text)
+
+ def omit(self, word):
+ i = self.rng.randrange(1, len(word))
+ text = word[:i] + word[i + 1:]
+ return text, self.jitter(text)
+
+ def insert(self, word):
+ i = self.rng.randrange(1, len(word) + 1)
+ base = word[i - 1]
+ if base not in NEIGHBORS:
+ return None
+ extra = self.rng.choice(NEIGHBORS[base])
+ text = word[:i] + extra + word[i:]
+ offsets = self.jitter(text)
+ self.slip(offsets, i, extra, base)
+ return text, offsets
+
+ def double(self, word):
+ i = self.rng.randrange(len(word))
+ text = word[:i] + word[i] + word[i:]
+ return text, self.jitter(text)
+
+ def cases(self, per_typo=60, per_keep=80):
+ cases = []
+
+ def add(category, previous, typed, expected, offsets=None):
+ cases.append({"id": f"{category}-{len(cases)}", "category": category, "previous": previous,
+ "typed": typed, "expected": expected,
+ "offsets": offsets or self.jitter(typed)})
+
+ def typos(category, make, pool, minimum, count):
+ made = 0
+ while made < count:
+ word = self.rng.choice(pool)
+ if len(word) < minimum:
+ continue
+ result = make(word)
+ if result is None:
+ continue
+ typed, offsets = result
+ # a typo that gives another word cannot be told apart without context
+ if typed in self.valid:
+ continue
+ add(category, "", typed, word, offsets)
+ made += 1
+
+ for name, make, minimum in (("sub1", self.sub, 4), ("sub2", lambda w: self.sub(w, 2), 7),
+ ("transpose", self.transpose, 4), ("omit", self.omit, 5),
+ ("insert", self.insert, 4), ("double", self.double, 4)):
+ typos(f"{name}.common", make, self.common, minimum, per_typo)
+ typos(f"{name}.medium", make, self.medium, minimum, per_typo // 2)
+ for name, make in (("sub1", self.sub), ("transpose", self.transpose)):
+ typos(f"short.{name}", make, [w for w in self.common[:600] if len(w) == 3], 3, per_typo // 2)
+
+ # typos after a word the dictionary knows to come before the intended one
+ pairs = [(first, second) for first, followers in sorted(self.bigrams.items()) for second in followers
+ if re.fullmatch(r"[a-z]{4,}", second) and re.fullmatch(r"[A-Za-z]+", first)]
+ made = 0
+ while made < per_typo:
+ first, second = self.rng.choice(pairs)
+ make = self.rng.choice((self.sub, self.transpose, self.omit, self.insert))
+ result = make(second)
+ if result and result[0] not in self.valid:
+ add("context", first, result[0], second, result[1])
+ made += 1
+
+ # space missed, or the key above it hit instead
+ for category, joiner in (("space.missing", ""), ("space.hit_letter", None)):
+ for _ in range(per_typo // 2):
+ first, second = self.rng.choice(self.common[:800]), self.rng.choice(self.common[:800])
+ between = self.rng.choice("cvbnm") if joiner is None else joiner
+ text = first + between + second
+ if text in self.valid:
+ continue
+ offsets = self.jitter(text)
+ if between:
+ offsets[len(first)] = (self.rng.gauss(0, 0.15), self.rng.uniform(0.3, 0.45))
+ add(category, "", text, f"{first} {second}", offsets)
+
+ # correctly typed words must stay
+ for category, pool in (("keep.common", self.common), ("keep.medium", self.medium), ("keep.rare", self.rare)):
+ for word in self.rng.sample(pool, per_keep):
+ add(category, "", word, word)
+ return cases
+
+
+def slovak_cases(generator, per_typo=60, per_keep=80):
+ """typos and correct words in Slovak, for the second language of the multilingual setup"""
+ ranked, _, _ = load_wordlist("sk", SLOVAK_URL)
+ everything = {w.lower() for w, _ in ranked} | generator.valid
+ # the Slovak list also has most English words: leave those out, they test nothing Slovak
+ own = [w for w, _ in ranked if w.islower() and w.isalpha() and w not in generator.valid]
+ plain = [w for w in own if w.isascii()]
+ cases = []
+
+ def add(category, typed, expected):
+ cases.append({"id": f"{category}-{len(cases)}", "category": category, "previous": "", "typed": typed,
+ "expected": expected, "offsets": offsets or generator.jitter(typed)})
+
+ for name, make, minimum in (("sub1", generator.sub, 4), ("transpose", generator.transpose, 4),
+ ("omit", generator.omit, 5), ("double", generator.double, 4)):
+ made = 0
+ while made < per_typo:
+ word = generator.rng.choice(plain[:3000])
+ result = make(word) if len(word) >= minimum else None
+ if result and result[0] not in everything:
+ offsets = result[1]
+ add(f"{name}.slovak", result[0], word)
+ made += 1
+ offsets = None
+ # typed without accents, like most people do
+ accented = [(unicodedata.normalize("NFD", w).encode("ascii", "ignore").decode(), w)
+ for w in own[:60000] if not w.isascii()]
+ accented = [(bare, w) for bare, w in accented if len(bare) == len(w) >= 4 and bare not in everything]
+ for bare, word in generator.rng.sample(accented, min(per_typo, len(accented))):
+ add("accents.slovak", bare, word)
+ for _ in range(per_typo // 2):
+ first, second = generator.rng.choice(plain[:600]), generator.rng.choice(plain[:600])
+ if first + second not in everything:
+ add("space.slovak", first + second, f"{first} {second}")
+ for word in generator.rng.sample(plain[:20000], per_keep):
+ add("keep.slovak", word, word)
+ return cases
+
+
+def fixed_cases(generator):
+ """hand written cases from fixed_cases.tsv: category, previous words, typed, expected"""
+ cases = []
+ for number, line in enumerate((HERE / "fixed_cases.tsv").read_text(encoding="utf-8").splitlines()):
+ if not line.strip() or line.startswith("#"):
+ continue
+ category, previous, typed, expected = line.split("\t")
+ cases.append({"id": f"{category}-f{number}", "category": category, "previous": previous,
+ "typed": typed, "expected": expected, "offsets": generator.jitter(typed)})
+ return cases
+
+
+def adb(serial, *args, check=True):
+ return subprocess.run(["adb", "-s", serial, *args], capture_output=True, text=True, check=check).stdout
+
+
+def replay(serial, cases, threshold, history=""):
+ """returns {id: (typed, committed, candidates)} and the header written by the app"""
+ with tempfile.TemporaryDirectory() as tmp:
+ source = Path(tmp) / "bench_in.tsv"
+ source.write_text("".join(
+ "\t".join((c["id"], c["previous"], c["typed"],
+ ",".join(f"{x:.3f}:{y:.3f}" for x, y in c["offsets"]))) + "\n" for c in cases),
+ encoding="utf-8")
+ adb(serial, "shell", "mkdir", "-p", REMOTE)
+ adb(serial, "push", str(source), f"{REMOTE}/bench_in.tsv")
+ adb(serial, "shell", "rm", "-f", f"{REMOTE}/bench_out.tsv")
+ extra = ["--es", "threshold", str(threshold)] if threshold is not None else []
+ if history:
+ if not re.fullmatch(r"[\w ]+", history):
+ sys.exit("history: words and spaces only")
+ extra += ["--es", "history", f"'{history}'"]
+ adb(serial, "shell", "am", "broadcast", "-n", RECEIVER, *extra)
+ deadline = time.time() + 600
+ while "bench_out.tsv" not in adb(serial, "shell", "ls", REMOTE, check=False):
+ if time.time() > deadline:
+ sys.exit("no result: is the debug app the active keyboard? check logcat -s AutocorrectBench")
+ time.sleep(1)
+ target = Path(tmp) / "bench_out.tsv"
+ adb(serial, "pull", f"{REMOTE}/bench_out.tsv", str(target))
+ lines = target.read_text(encoding="utf-8").split("\n")
+ if lines[0].startswith("#error"):
+ sys.exit(f"app: {lines[0]}")
+ if "#done" not in lines:
+ sys.exit("incomplete result")
+ results = {}
+ for line in lines[1:]:
+ if line and not line.startswith("#"):
+ identifier, typed, committed, candidates = line.split("\t")
+ results[identifier] = (typed, committed, [c.rsplit("~", 4) for c in candidates.split("|")])
+ timing = next((f"\tmsPerKey={line.split(chr(9))[1]}" for line in lines if line.startswith("#time")), "")
+ return results, lines[0] + timing
+
+
+def score(case, typed, committed, candidates):
+ """outcome, and for a missed typo where the pipeline lost the expected word"""
+ expected = case["expected"]
+ if case["category"].startswith("keep"):
+ return ("ok", "") if committed == typed else ("false_correction", "")
+ if committed == expected:
+ return "ok", ""
+ others = [c[0] for c in candidates if c[0] != typed]
+ if others and others[0] == expected:
+ stage = "not_committed" # ranked first, but the auto-correct decision said no
+ elif expected in others:
+ stage = "ranked_low"
+ else:
+ stage = "not_suggested"
+ return ("missed" if committed == typed else "wrong"), stage
+
+
+def summarize(rows):
+ table = defaultdict(Counter)
+ for row in rows:
+ group = row["category"].split(".")[0]
+ for key in (row["category"], "TOTAL keep" if group == "keep" else "TOTAL typo"):
+ table[key][row["outcome"]] += 1
+ if row["stage"]:
+ table[key][row["stage"]] += 1
+ if row["top3"]:
+ table[key]["top3"] += 1
+ table[key]["n"] += 1
+ return table
+
+
+def print_summary(table):
+ print(f"{'category':22}{'n':>5}{'ok%':>7}{'top3%':>7}{'missed':>7}{'wrong':>6}{'false':>6}"
+ f"{'no_sugg':>8}{'low':>5}{'gated':>6}")
+ for name in sorted(table, key=lambda k: (k.startswith("TOTAL"), k)):
+ c = table[name]
+ top3 = f"{100 * c['top3'] / c['n']:7.1f}" if not name.endswith("keep") and not name.startswith("keep") else " " * 7
+ print(f"{name:22}{c['n']:5}{100 * c['ok'] / c['n']:7.1f}{top3}{c['missed']:7}{c['wrong']:6}"
+ f"{c['false_correction']:6}{c['not_suggested']:8}{c['ranked_low']:5}{c['not_committed']:6}")
+
+
+def git_state():
+ def git(*args):
+ return subprocess.run(["git", "-C", str(HERE), *args], capture_output=True, text=True).stdout.strip()
+ return git("rev-parse", "--short", "HEAD") + ("+changes" if git("status", "--porcelain", "--", "../../app") else "")
+
+
+def next_seed():
+ seeds = [json.loads(p.read_text())["seed"] for p in OUT.glob("*.json")]
+ return max(seeds, default=1000) + 1
+
+
+def run(args):
+ seed = args.seed if args.seed is not None else next_seed()
+ generator = Generator(seed)
+ suites = {"fixed": lambda: fixed_cases(generator), "generated": generator.cases,
+ "slovak": lambda: slovak_cases(generator)}
+ cases = suites[args.suite]()
+ results, header = replay(args.serial, cases, args.threshold, args.history)
+ profile = (f"locales={args.locales}", *PROFILE)
+ missing = [setting for setting in profile if setting not in header.split("\t")]
+ if missing and not args.any_profile:
+ sys.exit(f"keyboard settings differ from the benchmark profile, expected {missing}: {header}")
+ rows = []
+ for case in cases:
+ typed, committed, candidates = results[case["id"]]
+ outcome, stage = score(case, typed, committed, candidates)
+ others = [c[0] for c in candidates if c[0] != typed]
+ rows.append({**{k: case[k] for k in ("id", "category", "previous", "expected")}, "typed": typed,
+ "committed": committed, "outcome": outcome, "stage": stage,
+ "top3": case["expected"] in others[:3], "candidates": candidates})
+ OUT.mkdir(exist_ok=True)
+ label = args.label or f"{args.suite}-s{seed}"
+ (OUT / f"{label}.json").write_text(json.dumps(
+ {"suite": args.suite, "seed": seed, "code": git_state(), "wordlist": generator.digest,
+ "history": args.history,
+ "device": header, "rows": rows}, ensure_ascii=False, indent=0))
+ print(f"{label}: suite={args.suite} seed={seed} code={git_state()}\n{header}")
+ print_summary(summarize(rows))
+ print(f"saved {OUT / label}.json")
+
+
+def load(label):
+ path = Path(label) if label.endswith(".json") else OUT / f"{label}.json"
+ return json.loads(path.read_text())
+
+
+def compare(args):
+ before, after = load(args.before), load(args.after)
+ if (before["suite"], before["seed"], before["wordlist"]) != (after["suite"], after["seed"], after["wordlist"]):
+ sys.exit("the runs used different cases")
+ old = {r["id"]: r for r in before["rows"]}
+ worse, better = [], []
+ for row in after["rows"]:
+ previous = old[row["id"]]
+ pair = (previous["outcome"], row["outcome"])
+ if pair[0] == pair[1]:
+ continue
+ # leaving a typo is less harmful than replacing it with another word
+ rank = {"ok": 0, "missed": 1, "wrong": 2, "false_correction": 2}
+ (worse if rank[pair[1]] > rank[pair[0]] else better).append((previous, row))
+ print(f"{before['code']} -> {after['code']}: {len(better)} better, {len(worse)} worse")
+ for title, changes in (("WORSE", worse), ("BETTER", better)):
+ for previous, row in changes[: args.limit]:
+ print(f"{title:6} {row['category']:18} [{row['previous']}] {row['typed']} (want {row['expected']}): "
+ f"{previous['committed']} -> {row['committed']}")
+
+
+def show(args):
+ rows = [r for r in load(args.run)["rows"] if r["outcome"] != "ok"
+ and re.search(args.category, r["category"]) and (not args.stage or r["stage"] == args.stage)
+ and (not args.outcome or r["outcome"] == args.outcome)]
+ print(f"{len(rows)} failures")
+ for r in rows[: args.limit]:
+ candidates = " ".join(f"{w}/{d}/{s}/{int(k) & 0xff}/{float(n):.2f}" for w, d, s, k, n in r["candidates"][:4])
+ print(f"{r['category']:18} [{r['previous']}] {r['typed']} want {r['expected']} got {r['committed']} "
+ f"{r['stage']} :: {candidates}")
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ commands = parser.add_subparsers(dest="command", required=True)
+ p = commands.add_parser("run", help="generate cases, replay them in the app, save and summarize the result")
+ p.add_argument("--suite", choices=("generated", "fixed", "slovak"), default="generated")
+ p.add_argument("--locales", default="en_US", help="languages the keyboard must be set to, e.g. en_US,sk")
+ p.add_argument("--history", default="", help="words committed before the cases, to set language confidence")
+ p.add_argument("--seed", type=int, help="default: one higher than any saved run, so the cases are new")
+ p.add_argument("--threshold", type=float, help="auto-correction threshold, default 0.067 (the app's default)")
+ p.add_argument("--serial", default=DEFAULT_SERIAL)
+ p.add_argument("--label")
+ p.add_argument("--any-profile", action="store_true", help="run with other languages or settings than the profile")
+ p.set_defaults(func=run)
+ p = commands.add_parser("compare", help="cases that changed between two runs of the same suite and seed")
+ p.add_argument("before")
+ p.add_argument("after")
+ p.add_argument("--limit", type=int, default=30)
+ p.set_defaults(func=compare)
+ p = commands.add_parser("show", help="failures of a run: word/dictionary/score/kind/normalized score")
+ p.add_argument("run")
+ p.add_argument("--category", default="")
+ p.add_argument("--stage", choices=("not_suggested", "ranked_low", "not_committed"))
+ p.add_argument("--outcome", choices=("missed", "wrong", "false_correction"))
+ p.add_argument("--limit", type=int, default=20)
+ p.set_defaults(func=show)
+ args = parser.parse_args()
+ args.func(args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/autocorrect_bench/fixed_cases.tsv b/tools/autocorrect_bench/fixed_cases.tsv
new file mode 100644
index 0000000000..c7d241f933
--- /dev/null
+++ b/tools/autocorrect_bench/fixed_cases.tsv
@@ -0,0 +1,226 @@
+# category | previous words | typed | expected (keep.* : expected = typed)
+misspelling teh the
+misspelling adn and
+misspelling hte the
+misspelling waht what
+misspelling taht that
+misspelling yuo you
+misspelling thier their
+misspelling recieve receive
+misspelling definately definitely
+misspelling seperate separate
+misspelling occured occurred
+misspelling untill until
+misspelling wich which
+misspelling becuase because
+misspelling freind friend
+misspelling beleive believe
+misspelling tommorow tomorrow
+misspelling tomorow tomorrow
+misspelling adress address
+misspelling goverment government
+misspelling neccessary necessary
+misspelling accomodate accommodate
+misspelling wierd weird
+misspelling acheive achieve
+misspelling begining beginning
+misspelling calender calendar
+misspelling enviroment environment
+misspelling foward forward
+misspelling happend happened
+misspelling realy really
+misspelling truely truly
+misspelling writting writing
+misspelling arguement argument
+misspelling publically publicly
+misspelling mispell misspell
+misspelling embarass embarrass
+apostrophe dont don't
+apostrophe cant can't
+apostrophe doesnt doesn't
+apostrophe isnt isn't
+apostrophe didnt didn't
+apostrophe wont won't
+apostrophe im I'm
+apostrophe ive I've
+apostrophe youre you're
+apostrophe thats that's
+apostrophe couldnt couldn't
+apostrophe wouldnt wouldn't
+apostrophe shouldnt shouldn't
+apostrophe havent haven't
+apostrophe arent aren't
+apostrophe wasnt wasn't
+apostrophe theyre they're
+apostrophe whats what's
+case when i I
+case and im I'm
+keep.slang omg omg
+keep.slang lol lol
+keep.slang idk idk
+keep.slang brb brb
+keep.slang btw btw
+keep.slang tbh tbh
+keep.slang smh smh
+keep.slang imo imo
+keep.slang ikr ikr
+keep.slang fyi fyi
+keep.slang afk afk
+keep.slang gg gg
+keep.slang wtf wtf
+keep.slang thx thx
+keep.slang pls pls
+keep.slang plz plz
+keep.slang ya ya
+keep.slang yeah yeah
+keep.slang yep yep
+keep.slang nope nope
+keep.slang nah nah
+keep.slang gonna gonna
+keep.slang wanna wanna
+keep.slang gotta gotta
+keep.slang kinda kinda
+keep.slang sorta sorta
+keep.slang lemme lemme
+keep.slang gimme gimme
+keep.slang dunno dunno
+keep.slang ain't ain't
+keep.slang bruh bruh
+keep.slang bro bro
+keep.slang sis sis
+keep.slang fam fam
+keep.slang lit lit
+keep.slang vibe vibe
+keep.slang yolo yolo
+keep.slang selfie selfie
+keep.slang emoji emoji
+keep.slang hashtag hashtag
+keep.slang wifi wifi
+keep.slang bluetooth bluetooth
+keep.slang app app
+keep.slang apps apps
+keep.slang email email
+keep.slang gmail gmail
+keep.slang google google
+keep.slang youtube youtube
+keep.slang whatsapp whatsapp
+keep.slang instagram instagram
+keep.slang tiktok tiktok
+keep.slang netflix netflix
+keep.slang spotify spotify
+keep.slang uber uber
+keep.slang paypal paypal
+keep.slang github github
+keep.slang linux linux
+keep.slang debian debian
+keep.slang android android
+keep.slang iphone iphone
+keep.slang ipad ipad
+keep.slang chatgpt chatgpt
+keep.slang crypto crypto
+keep.slang blockchain blockchain
+keep.slang kotlin kotlin
+keep.slang gradle gradle
+keep.slang json json
+keep.slang yaml yaml
+keep.slang regex regex
+keep.slang async async
+keep.slang config config
+keep.slang repo repo
+keep.slang changelog changelog
+keep.slang lmao lmao
+keep.slang rofl rofl
+keep.slang haha haha
+keep.slang hahaha hahaha
+keep.slang hmm hmm
+keep.slang hmmm hmmm
+keep.slang umm umm
+keep.slang uhh uhh
+keep.slang ooh ooh
+keep.slang aww aww
+keep.slang yay yay
+keep.slang ugh ugh
+keep.slang meh meh
+keep.slang sup sup
+keep.slang yo yo
+keep.slang hiya hiya
+keep.slang cya cya
+keep.slang ttyl ttyl
+keep.slang asap asap
+keep.slang eta eta
+keep.slang diy diy
+keep.slang faq faq
+keep.slang pdf pdf
+keep.slang url url
+keep.slang usb usb
+keep.slang gpu gpu
+keep.slang cpu cpu
+keep.slang ssd ssd
+keep.names rohan rohan
+keep.names priya priya
+keep.names rahul rahul
+keep.names anjali anjali
+keep.names ananya ananya
+keep.names vivek vivek
+keep.names meera meera
+keep.names nikhil nikhil
+keep.names deepa deepa
+keep.names suresh suresh
+keep.names lakshmi lakshmi
+keep.names aisha aisha
+keep.names omar omar
+keep.names fatima fatima
+keep.names yuki yuki
+keep.names hiroshi hiroshi
+keep.names mei mei
+keep.names chen chen
+keep.names priyanka priyanka
+keep.names siobhan siobhan
+keep.names niamh niamh
+keep.names aoife aoife
+keep.names saoirse saoirse
+keep.names xander xander
+keep.names kaitlyn kaitlyn
+keep.names jayden jayden
+keep.names bengaluru bengaluru
+keep.names kochi kochi
+keep.names thrissur thrissur
+keep.names kozhikode kozhikode
+keep.names chennai chennai
+keep.names mumbai mumbai
+keep.names pune pune
+keep.names hyderabad hyderabad
+keep.foreign namaste namaste
+keep.foreign chalo chalo
+keep.foreign accha accha
+keep.foreign theek theek
+keep.foreign yaar yaar
+keep.foreign bhai bhai
+keep.foreign chai chai
+keep.foreign biryani biryani
+keep.foreign dosa dosa
+keep.foreign sambar sambar
+keep.foreign machan machan
+keep.foreign enthaa enthaa
+keep.foreign sheri sheri
+keep.foreign alle alle
+keep.validpair its its
+keep.validpair were were
+keep.validpair well well
+keep.validpair ill ill
+keep.validpair hell hell
+keep.validpair shell shell
+keep.validpair wed wed
+keep.validpair id id
+keep.validpair lets lets
+keep.validpair hers hers
+keep.validpair ours ours
+keep.validpair yours yours
+keep.validpair whose whose
+keep.validpair fir fir
+keep.validpair form form
+keep.validpair from from
+keep.validpair tin tin
+keep.validpair ten ten
+keep.validpair bit bit
+keep.validpair but but