Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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/
Original file line number Diff line number Diff line change
Expand Up @@ -1321,12 +1321,12 @@ private class DictionaryGroup(

// might need some more tuning
fun getWeightForLocale(groups: List<DictionaryGroup>, 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 -------------------
Expand Down
43 changes: 43 additions & 0 deletions app/src/main/java/helium314/keyboard/latin/LikelySlip.kt
Original file line number Diff line number Diff line change
@@ -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
}
}
29 changes: 29 additions & 0 deletions app/src/main/java/helium314/keyboard/latin/Suggest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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<SuggestedWordInfo>) {
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)
Expand Down
29 changes: 29 additions & 0 deletions app/src/test/java/helium314/keyboard/latin/DictionaryGroupTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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<Float> {
val groups = confidences.map { value ->
constructor.newInstance(Locale.ENGLISH, null, emptyMap<String, ExpandableBinaryDictionary>(), 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")
Expand Down
38 changes: 38 additions & 0 deletions app/src/test/java/helium314/keyboard/latin/LikelySlipTest.kt
Original file line number Diff line number Diff line change
@@ -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))
}
}
39 changes: 39 additions & 0 deletions app/src/test/java/helium314/keyboard/latin/SuggestTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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<SuggestedWords.SuggestedWordInfo>) =
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)
Expand Down Expand Up @@ -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, "",
Expand Down Expand Up @@ -565,6 +602,8 @@ class ShadowFacilitator {
@Implementation
fun getCurrentLocale(): Locale = currentTypingLocale
@Implementation
fun localesAndConfidences(): String? = languagesAndConfidences
@Implementation
fun hasAtLeastOneInitializedMainDictionary() = true // otherwise no autocorrect
}

Expand Down
Loading