Skip to content

Commit a0a2a97

Browse files
committed
fix(suggest): auto-correct typing slips in unknown short words (#1005)
Unknown words of up to 3 letters were not auto-corrected at all, to protect slang and abbreviations. Now a 3 letter word is also corrected if one letter was hit on a neighbor key and the suggestion is confident enough, besides two swapped neighbors. Slang like omg, idk or lol stays, two letter words are unchanged.
1 parent f41856b commit a0a2a97

6 files changed

Lines changed: 156 additions & 61 deletions

File tree

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// SPDX-License-Identifier: GPL-3.0-only
2+
package helium314.keyboard.latin
3+
4+
import helium314.keyboard.keyboard.Keyboard
5+
import java.util.Locale
6+
import kotlin.math.abs
7+
8+
/**
9+
* Protects slang and abbreviations like "omg", "idk" or "db" from auto-correction (see [Suggest]): a short word
10+
* that is in no dictionary is often intended, and some common word is always only one letter away. So it is only
11+
* corrected if the difference looks like a typing slip:
12+
* - two neighboring letters typed in the wrong order, like "teh" for "the"
13+
* - a neighbor key hit instead of the right one, like "hry" for "hey", if the dictionary is confident enough
14+
*/
15+
object ShortWordGuard {
16+
const val LENGTH = 3
17+
18+
// normalized score a neighbor key slip needs, even if the user's auto-correction threshold is lower.
19+
// Measured with the English dictionary: slang like "omg" -> "IMG" reaches up to 0.13, typos start at 0.21
20+
const val MIN_NEIGHBOR_KEY_SCORE = 0.17f
21+
22+
// how far apart the centers of neighbor keys may be, relative to the key size (includes gaps and row stagger)
23+
private const val NEIGHBOR_DISTANCE = 1.3f
24+
25+
fun isTypingSlip(typed: String, word: String, areNeighborKeys: (Char, Char) -> Boolean, score: () -> Float): Boolean =
26+
isSwapOfNeighbors(typed, word)
27+
|| (isNeighborKeySlip(typed, word, areNeighborKeys) && score() >= MIN_NEIGHBOR_KEY_SCORE)
28+
29+
/** Whether [word] is [typed] with two neighboring (different) letters swapped, case is ignored */
30+
fun isSwapOfNeighbors(typed: String, word: String): Boolean {
31+
if (typed.length != LENGTH || word.length != LENGTH) return false
32+
val a = typed.lowercase(Locale.ROOT)
33+
val b = word.lowercase(Locale.ROOT)
34+
val i = a.indices.firstOrNull { a[it] != b[it] } ?: return false
35+
if (i + 1 >= a.length) return false
36+
return a[i] == b[i + 1] && a[i + 1] == b[i] && a.substring(i + 2) == b.substring(i + 2)
37+
&& a.all { it.isLetter() }
38+
}
39+
40+
/** Whether [word] is [typed] with exactly one letter replaced by one on a neighbor key, case is ignored */
41+
fun isNeighborKeySlip(typed: String, word: String, areNeighborKeys: (Char, Char) -> Boolean): Boolean {
42+
if (typed.length != LENGTH || word.length != LENGTH) return false
43+
val a = typed.lowercase(Locale.ROOT)
44+
val b = word.lowercase(Locale.ROOT)
45+
if (!a.all { it.isLetter() } || !b.all { it.isLetter() }) return false
46+
val i = a.indices.singleOrNull { a[it] != b[it] } ?: return false
47+
return areNeighborKeys(a[i], b[i])
48+
}
49+
50+
/** Whether the two letters are on touching keys of [keyboard] */
51+
fun areNeighborKeys(keyboard: Keyboard, first: Char, second: Char): Boolean {
52+
// a shifted keyboard has the upper case letters
53+
fun key(c: Char) = keyboard.getKey(c.code) ?: keyboard.getKey(c.uppercaseChar().code)
54+
val a = key(first) ?: return false
55+
val b = key(second) ?: return false
56+
return areNeighborPositions(
57+
(a.x + a.width / 2) - (b.x + b.width / 2), a.y - b.y, keyboard.mMostCommonKeyWidth, a.height
58+
)
59+
}
60+
61+
fun areNeighborPositions(dx: Int, dy: Int, keyWidth: Int, keyHeight: Int): Boolean =
62+
abs(dx) <= keyWidth * NEIGHBOR_DISTANCE && abs(dy) <= keyHeight * NEIGHBOR_DISTANCE
63+
}

‎app/src/main/java/helium314/keyboard/latin/ShortWordSwap.kt‎

Lines changed: 0 additions & 24 deletions
This file was deleted.

‎app/src/main/java/helium314/keyboard/latin/Suggest.kt‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ class Suggest(private val mDictionaryFacilitator: DictionaryFacilitator) {
145145
suggestionResults,
146146
firstOccurrenceOfTypedWordInSuggestions,
147147
typedWordFirstOccurrenceWordInfo
148-
)
148+
) { first, second -> ShortWordGuard.areNeighborKeys(keyboard, first, second) }
149149
val typedWordInfo = SuggestedWordInfo(capitalizedTypedWord, "", SuggestedWordInfo.MAX_SCORE,
150150
SuggestedWordInfo.KIND_TYPED, typedWordFirstOccurrenceWordInfo?.mSourceDict ?: Dictionary.DICTIONARY_USER_TYPED,
151151
SuggestedWordInfo.NOT_AN_INDEX , SuggestedWordInfo.NOT_A_CONFIDENCE)
@@ -249,7 +249,8 @@ class Suggest(private val mDictionaryFacilitator: DictionaryFacilitator) {
249249
wordComposer: WordComposer,
250250
suggestionResults: SuggestionResults,
251251
firstOccurrenceOfTypedWordInSuggestions: Int,
252-
typedWordInfo: SuggestedWordInfo?
252+
typedWordInfo: SuggestedWordInfo?,
253+
areNeighborKeys: (Char, Char) -> Boolean = { _, _ -> false }
253254
): Pair<Boolean, Boolean> {
254255
val consideredWord = typedWordString.dropLast(trailingSingleQuotesCount)
255256
val firstAndTypedEmptyInfos by lazy { getEmptyWordSuggestions() }
@@ -339,16 +340,17 @@ class Suggest(private val mDictionaryFacilitator: DictionaryFacilitator) {
339340
}
340341
}
341342

342-
// For short words (<= 3 chars) not in the dictionary (e.g. Ab, yt, tg, db),
343-
// prevent single-letter substitution by common dictionary unigrams unless it's a known user history word or contraction.
344-
if (typedWordInfo == null && consideredWord.length <= 3) {
343+
// Short words not in the dictionary (e.g. Ab, yt, tg, idk) are often slang or abbreviations: only
344+
// correct them if there is other evidence than a similar common word, see ShortWordGuard
345+
if (typedWordInfo == null && consideredWord.length <= ShortWordGuard.LENGTH) {
345346
val isExactOrCaseMatch = firstSuggestion.mWord.equals(consideredWord, ignoreCase = true)
346347
val isUserHistory = firstSuggestion.mSourceDict?.mDictType == Dictionary.TYPE_USER_HISTORY
347348
val isWhitelist = firstSuggestion.isKindOf(SuggestedWordInfo.KIND_WHITELIST)
348349
val isShortcut = firstSuggestion.isKindOf(SuggestedWordInfo.KIND_SHORTCUT) && Settings.getValues().mAutoCorrectShortcuts
349-
// two neighboring letters typed in the wrong order, like "teh" for "the", are a typo, not an abbreviation
350-
val isSwap = ShortWordSwap.isSwapOfNeighbors(consideredWord, firstSuggestion.mWord)
351-
if (!isExactOrCaseMatch && !isUserHistory && !isWhitelist && !isShortcut && !isSwap && expectedContraction == null) {
350+
if (!isExactOrCaseMatch && !isUserHistory && !isWhitelist && !isShortcut && expectedContraction == null
351+
&& !ShortWordGuard.isTypingSlip(consideredWord, firstSuggestion.mWord, areNeighborKeys) {
352+
BinaryDictionaryUtils.calcNormalizedScore(consideredWord, firstSuggestion.mWord, firstSuggestion.mScore)
353+
}) {
352354
return true to false
353355
}
354356
}
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
// SPDX-License-Identifier: GPL-3.0-only
2+
package helium314.keyboard.latin
3+
4+
import org.junit.Assert.assertFalse
5+
import org.junit.Assert.assertTrue
6+
import org.junit.Test
7+
8+
class ShortWordGuardTest {
9+
@Test
10+
fun swappedNeighborsAreFound() {
11+
for ((typed, word) in listOf("dsa" to "das", "ihc" to "ich", "dei" to "die", "nud" to "und", "teh" to "the",
12+
"adn" to "and", "Dsa" to "Das", "IHC" to "ich", "eni" to "ein")) {
13+
assertTrue("$typed -> $word", ShortWordGuard.isSwapOfNeighbors(typed, word))
14+
}
15+
}
16+
17+
@Test
18+
fun otherDifferencesAreNoSwap() {
19+
assertFalse(ShortWordGuard.isSwapOfNeighbors("das", "das")) // same word
20+
assertFalse(ShortWordGuard.isSwapOfNeighbors("dsa", "sad")) // not neighbors
21+
assertFalse(ShortWordGuard.isSwapOfNeighbors("das", "dar")) // a different letter
22+
assertFalse(ShortWordGuard.isSwapOfNeighbors("db", "bd")) // only 3 letters
23+
assertFalse(ShortWordGuard.isSwapOfNeighbors("ders", "dres")) // only 3 letters
24+
assertFalse(ShortWordGuard.isSwapOfNeighbors("a1b", "1ab")) // only letters
25+
assertFalse(ShortWordGuard.isSwapOfNeighbors("abc", "bca"))
26+
}
27+
28+
private val neighbors = setOf("re", "ty", "io", "df", "mn")
29+
private fun areNeighbors(a: Char, b: Char) = "$a$b" in neighbors || "$b$a" in neighbors
30+
31+
@Test
32+
fun neighborKeySlipNeedsConfidentSuggestion() {
33+
fun isSlip(typed: String, word: String, score: Float) =
34+
ShortWordGuard.isTypingSlip(typed, word, ::areNeighbors) { score }
35+
// measured on a device with the English dictionary
36+
assertTrue(isSlip("hry", "hey", 0.211f))
37+
assertTrue(isSlip("Yhe", "the", 0.381f))
38+
assertFalse(isSlip("omg", "IMG", 0.105f))
39+
assertFalse(isSlip("idk", "IFK", 0.130f)) // too weak, even where d and f are neighbors
40+
assertFalse(isSlip("lol", "Lil", 0.123f))
41+
assertFalse(isSlip("thx", "the", 0.199f)) // confident enough, but x and e are not neighbors
42+
}
43+
44+
@Test
45+
fun neighborKeySlipIsOneReplacedLetterInThreeLetterWords() {
46+
assertTrue(ShortWordGuard.isNeighborKeySlip("hry", "hey", ::areNeighbors))
47+
assertFalse(ShortWordGuard.isNeighborKeySlip("hay", "hey", ::areNeighbors)) // not neighbors
48+
assertFalse(ShortWordGuard.isNeighborKeySlip("hrt", "hey", ::areNeighbors)) // two letters differ
49+
assertFalse(ShortWordGuard.isNeighborKeySlip("hr", "he", ::areNeighbors)) // two letter words stay
50+
assertFalse(ShortWordGuard.isNeighborKeySlip("hr1", "he1", ::areNeighbors)) // only letters
51+
assertFalse(ShortWordGuard.isNeighborKeySlip("hey", "hey", ::areNeighbors))
52+
}
53+
54+
@Test
55+
fun neighborPositionsIncludeStaggeredRows() {
56+
fun near(dxInKeys: Float, rows: Int) =
57+
ShortWordGuard.areNeighborPositions((dxInKeys * 110).toInt(), rows * 150, 100, 150)
58+
assertTrue(near(1f, 0)) // next key including the gap
59+
assertTrue(near(0.5f, 1))
60+
assertFalse(near(2f, 0))
61+
assertFalse(near(1.5f, 1))
62+
assertFalse(near(0.5f, 2))
63+
}
64+
}
65+

‎app/src/test/java/helium314/keyboard/latin/ShortWordSwapTest.kt‎

Lines changed: 0 additions & 27 deletions
This file was deleted.

‎app/src/test/java/helium314/keyboard/latin/SuggestTest.kt‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -441,6 +441,20 @@ class SuggestTest {
441441
assert(!result.last())
442442
}
443443

444+
@Test fun `unknown short word is only corrected if it looks like a typing slip`() {
445+
val neighbors = { a: Char, b: Char -> "$a$b" in setOf("re", "oi") }
446+
// the pref in shouldBeAutoCorrected below does not reach suggest, so set the (default) threshold here
447+
suggest.setAutoCorrectionThreshold(0.067f)
448+
// the shadow score is score / 1000000, weighted by 2/3 for one wrong letter in three
449+
fun corrects(typed: String, word: String, score: Int, areNeighbors: (Char, Char) -> Boolean = neighbors) =
450+
shouldBeAutoCorrected(typed, listOf(suggestion(word, score, Locale.ENGLISH)), null, null, Locale.ENGLISH,
451+
0.067f, areNeighbors).last()
452+
assert(corrects("hry", "hey", 300000)) // 0.2
453+
assert(!corrects("omg", "img", 180000)) // 0.12: above the user threshold, but too weak for a short word
454+
assert(!corrects("hry", "hey", 900000) { _, _ -> false }) // confident, but not a neighbor key
455+
assert(corrects("teh", "the", 300000) { _, _ -> false }) // swapped letters don't need neighbor keys
456+
}
457+
444458
@Test fun `moving emojis out of the first two places keeps the order of words`() {
445459
val words = mutableListOf(suggestion("\uD83D\uDE00", 900, Locale.ENGLISH), suggestion("one", 800, Locale.ENGLISH),
446460
suggestion("two", 700, Locale.ENGLISH), suggestion("\uD83D\uDE01", 600, Locale.ENGLISH))
@@ -453,7 +467,8 @@ class SuggestTest {
453467
firstSuggestionForEmpty: SuggestedWordInfo?, // first suggestion if typed word would be empty (null if none)
454468
typedWordSuggestionForEmpty: SuggestedWordInfo?, // suggestion for actually typed word if typed word would be empty (null if none)
455469
typingLocale: Locale, // used for checking whether suggestion locale is the same, relevant e.g. for English i -> I shortcut, but we want Polish i
456-
autoCorrectThreshold: Float
470+
autoCorrectThreshold: Float,
471+
areNeighborKeys: (Char, Char) -> Boolean = { _, _ -> false }
457472
): List<Boolean> {
458473
latinIME.prefs().edit { putFloat(Settings.PREF_AUTO_CORRECT_THRESHOLD, autoCorrectThreshold) }
459474
// enable "more autocorrect" so we actually have autocorrect even though we don't set a compatible input type
@@ -479,7 +494,8 @@ class SuggestTest {
479494
WordComposer.getComposerForTest(false),
480495
suggestionResults,
481496
firstOccurrenceOfTypedWordInSuggestions,
482-
typedWordFirstOccurrenceWordInfo
497+
typedWordFirstOccurrenceWordInfo,
498+
areNeighborKeys
483499
).toList()
484500
}
485501
}

0 commit comments

Comments
 (0)