From ae4e01c17d6ddd2d4fbf854ecb63b0fd041f9ef3 Mon Sep 17 00:00:00 2001 From: LeanBitLab Date: Mon, 30 Nov 2026 17:57:37 +0530 Subject: [PATCH 1/4] fix(suggest): prefer swapped or doubled letters as the explanation of a typo --- .../helium314/keyboard/latin/LikelySlip.kt | 43 +++++++++++++++++++ .../java/helium314/keyboard/latin/Suggest.kt | 22 ++++++++++ .../keyboard/latin/LikelySlipTest.kt | 38 ++++++++++++++++ .../helium314/keyboard/latin/SuggestTest.kt | 21 +++++++++ 4 files changed, 124 insertions(+) create mode 100644 app/src/main/java/helium314/keyboard/latin/LikelySlip.kt create mode 100644 app/src/test/java/helium314/keyboard/latin/LikelySlipTest.kt 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 000000000..cfb28fa33 --- /dev/null +++ b/app/src/main/java/helium314/keyboard/latin/LikelySlip.kt @@ -0,0 +1,43 @@ +// 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. + */ +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 556326c27..4a0f5e118 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( @@ -732,6 +734,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/LikelySlipTest.kt b/app/src/test/java/helium314/keyboard/latin/LikelySlipTest.kt new file mode 100644 index 000000000..37b1f3120 --- /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 635889dc4..d85193ffd 100644 --- a/app/src/test/java/helium314/keyboard/latin/SuggestTest.kt +++ b/app/src/test/java/helium314/keyboard/latin/SuggestTest.kt @@ -411,6 +411,27 @@ class SuggestTest { assertEquals(listOf("Noe"), candidates.map { it.mWord }) } + @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) From 5a7be3624553d2e90711c2cf0acc6bd547d848c4 Mon Sep 17 00:00:00 2001 From: LeanBitLab Date: Mon, 30 Nov 2026 18:43:34 +0530 Subject: [PATCH 2/4] fix(multilingual): give the leading language full weight when languages are tied A tie weighted every language below 0.99, where the native decoder corrects no missing space and searches less. This was the state after starting to type. --- .../latin/DictionaryFacilitatorImpl.kt | 12 ++++---- .../keyboard/latin/DictionaryGroupTest.kt | 29 +++++++++++++++++++ 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/helium314/keyboard/latin/DictionaryFacilitatorImpl.kt b/app/src/main/java/helium314/keyboard/latin/DictionaryFacilitatorImpl.kt index 7b057e06a..4785d8067 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/test/java/helium314/keyboard/latin/DictionaryGroupTest.kt b/app/src/test/java/helium314/keyboard/latin/DictionaryGroupTest.kt index 23b3562b7..fac7d4c38 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") From ee0a4714fc7fefd4feb0968ef0a0282016b3020f Mon Sep 17 00:00:00 2001 From: LeanBitLab Date: Mon, 30 Nov 2026 18:43:34 +0530 Subject: [PATCH 3/4] fix(multilingual): don't auto-correct a word into three or more words --- .../java/helium314/keyboard/latin/Suggest.kt | 7 +++++++ .../helium314/keyboard/latin/SuggestTest.kt | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/app/src/main/java/helium314/keyboard/latin/Suggest.kt b/app/src/main/java/helium314/keyboard/latin/Suggest.kt index 4a0f5e118..6783f72ba 100644 --- a/app/src/main/java/helium314/keyboard/latin/Suggest.kt +++ b/app/src/main/java/helium314/keyboard/latin/Suggest.kt @@ -392,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 diff --git a/app/src/test/java/helium314/keyboard/latin/SuggestTest.kt b/app/src/test/java/helium314/keyboard/latin/SuggestTest.kt index d85193ffd..043b533b1 100644 --- a/app/src/test/java/helium314/keyboard/latin/SuggestTest.kt +++ b/app/src/test/java/helium314/keyboard/latin/SuggestTest.kt @@ -411,6 +411,21 @@ 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)) = @@ -559,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, "", @@ -586,6 +602,8 @@ class ShadowFacilitator { @Implementation fun getCurrentLocale(): Locale = currentTypingLocale @Implementation + fun localesAndConfidences(): String? = languagesAndConfidences + @Implementation fun hasAtLeastOneInitializedMainDictionary() = true // otherwise no autocorrect } From 1e47a25103c8e56bdc512aed2c08f60b611d48d3 Mon Sep 17 00:00:00 2001 From: LeanBitLab Date: Mon, 30 Nov 2026 19:06:10 +0530 Subject: [PATCH 4/4] chore: ignore the local auto-correction benchmark --- .gitignore | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.gitignore b/.gitignore index 6fd494ff9..504ab9d73 100755 --- a/.gitignore +++ b/.gitignore @@ -104,3 +104,7 @@ CLAUDE.local.md # Python caches __pycache__/ *.pyc + +# local auto-correction benchmark for Waydroid and devices (debug receiver and host scripts) +tools/autocorrect_bench/ +app/src/debug/java/helium314/keyboard/latin/bench/