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
63 changes: 63 additions & 0 deletions app/src/main/java/helium314/keyboard/latin/ShortWordGuard.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// SPDX-License-Identifier: GPL-3.0-only
package helium314.keyboard.latin

import helium314.keyboard.keyboard.Keyboard
import java.util.Locale
import kotlin.math.abs

/**
* Protects slang and abbreviations like "omg", "idk" or "db" from auto-correction (see [Suggest]): a short word
* that is in no dictionary is often intended, and some common word is always only one letter away. So it is only
* corrected if the difference looks like a typing slip:
* - two neighboring letters typed in the wrong order, like "teh" for "the"
* - a neighbor key hit instead of the right one, like "hry" for "hey", if the dictionary is confident enough
*/
object ShortWordGuard {
const val LENGTH = 3

// normalized score a neighbor key slip needs, even if the user's auto-correction threshold is lower.
// Measured with the English dictionary: slang like "omg" -> "IMG" reaches up to 0.13, typos start at 0.21
const val MIN_NEIGHBOR_KEY_SCORE = 0.17f

// how far apart the centers of neighbor keys may be, relative to the key size (includes gaps and row stagger)
private const val NEIGHBOR_DISTANCE = 1.3f

fun isTypingSlip(typed: String, word: String, areNeighborKeys: (Char, Char) -> Boolean, score: () -> Float): Boolean =
isSwapOfNeighbors(typed, word)
|| (isNeighborKeySlip(typed, word, areNeighborKeys) && score() >= MIN_NEIGHBOR_KEY_SCORE)

/** Whether [word] is [typed] with two neighboring (different) letters swapped, case is ignored */
fun isSwapOfNeighbors(typed: String, word: String): Boolean {
if (typed.length != LENGTH || word.length != LENGTH) return false
val a = typed.lowercase(Locale.ROOT)
val b = word.lowercase(Locale.ROOT)
val i = a.indices.firstOrNull { a[it] != b[it] } ?: return false
if (i + 1 >= a.length) return false
return a[i] == b[i + 1] && a[i + 1] == b[i] && a.substring(i + 2) == b.substring(i + 2)
&& a.all { it.isLetter() }
}

/** Whether [word] is [typed] with exactly one letter replaced by one on a neighbor key, case is ignored */
fun isNeighborKeySlip(typed: String, word: String, areNeighborKeys: (Char, Char) -> Boolean): Boolean {
if (typed.length != LENGTH || word.length != LENGTH) return false
val a = typed.lowercase(Locale.ROOT)
val b = word.lowercase(Locale.ROOT)
if (!a.all { it.isLetter() } || !b.all { it.isLetter() }) return false
val i = a.indices.singleOrNull { a[it] != b[it] } ?: return false
return areNeighborKeys(a[i], b[i])
}

/** Whether the two letters are on touching keys of [keyboard] */
fun areNeighborKeys(keyboard: Keyboard, first: Char, second: Char): Boolean {
// a shifted keyboard has the upper case letters
fun key(c: Char) = keyboard.getKey(c.code) ?: keyboard.getKey(c.uppercaseChar().code)
val a = key(first) ?: return false
val b = key(second) ?: return false
return areNeighborPositions(
(a.x + a.width / 2) - (b.x + b.width / 2), a.y - b.y, keyboard.mMostCommonKeyWidth, a.height
)
}

fun areNeighborPositions(dx: Int, dy: Int, keyWidth: Int, keyHeight: Int): Boolean =
abs(dx) <= keyWidth * NEIGHBOR_DISTANCE && abs(dy) <= keyHeight * NEIGHBOR_DISTANCE
}
24 changes: 0 additions & 24 deletions app/src/main/java/helium314/keyboard/latin/ShortWordSwap.kt

This file was deleted.

18 changes: 10 additions & 8 deletions app/src/main/java/helium314/keyboard/latin/Suggest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ class Suggest(private val mDictionaryFacilitator: DictionaryFacilitator) {
suggestionResults,
firstOccurrenceOfTypedWordInSuggestions,
typedWordFirstOccurrenceWordInfo
)
) { first, second -> ShortWordGuard.areNeighborKeys(keyboard, first, second) }
val typedWordInfo = SuggestedWordInfo(capitalizedTypedWord, "", SuggestedWordInfo.MAX_SCORE,
SuggestedWordInfo.KIND_TYPED, typedWordFirstOccurrenceWordInfo?.mSourceDict ?: Dictionary.DICTIONARY_USER_TYPED,
SuggestedWordInfo.NOT_AN_INDEX , SuggestedWordInfo.NOT_A_CONFIDENCE)
Expand Down Expand Up @@ -249,7 +249,8 @@ class Suggest(private val mDictionaryFacilitator: DictionaryFacilitator) {
wordComposer: WordComposer,
suggestionResults: SuggestionResults,
firstOccurrenceOfTypedWordInSuggestions: Int,
typedWordInfo: SuggestedWordInfo?
typedWordInfo: SuggestedWordInfo?,
areNeighborKeys: (Char, Char) -> Boolean = { _, _ -> false }
): Pair<Boolean, Boolean> {
val consideredWord = typedWordString.dropLast(trailingSingleQuotesCount)
val firstAndTypedEmptyInfos by lazy { getEmptyWordSuggestions() }
Expand Down Expand Up @@ -339,16 +340,17 @@ class Suggest(private val mDictionaryFacilitator: DictionaryFacilitator) {
}
}

// For short words (<= 3 chars) not in the dictionary (e.g. Ab, yt, tg, db),
// prevent single-letter substitution by common dictionary unigrams unless it's a known user history word or contraction.
if (typedWordInfo == null && consideredWord.length <= 3) {
// Short words not in the dictionary (e.g. Ab, yt, tg, idk) are often slang or abbreviations: only
// correct them if there is other evidence than a similar common word, see ShortWordGuard
if (typedWordInfo == null && consideredWord.length <= ShortWordGuard.LENGTH) {
val isExactOrCaseMatch = firstSuggestion.mWord.equals(consideredWord, ignoreCase = true)
val isUserHistory = firstSuggestion.mSourceDict?.mDictType == Dictionary.TYPE_USER_HISTORY
val isWhitelist = firstSuggestion.isKindOf(SuggestedWordInfo.KIND_WHITELIST)
val isShortcut = firstSuggestion.isKindOf(SuggestedWordInfo.KIND_SHORTCUT) && Settings.getValues().mAutoCorrectShortcuts
// two neighboring letters typed in the wrong order, like "teh" for "the", are a typo, not an abbreviation
val isSwap = ShortWordSwap.isSwapOfNeighbors(consideredWord, firstSuggestion.mWord)
if (!isExactOrCaseMatch && !isUserHistory && !isWhitelist && !isShortcut && !isSwap && expectedContraction == null) {
if (!isExactOrCaseMatch && !isUserHistory && !isWhitelist && !isShortcut && expectedContraction == null
&& !ShortWordGuard.isTypingSlip(consideredWord, firstSuggestion.mWord, areNeighborKeys) {
BinaryDictionaryUtils.calcNormalizedScore(consideredWord, firstSuggestion.mWord, firstSuggestion.mScore)
}) {
return true to false
}
}
Expand Down
65 changes: 65 additions & 0 deletions app/src/test/java/helium314/keyboard/latin/ShortWordGuardTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// 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 ShortWordGuardTest {
@Test
fun swappedNeighborsAreFound() {
for ((typed, word) in listOf("dsa" to "das", "ihc" to "ich", "dei" to "die", "nud" to "und", "teh" to "the",
"adn" to "and", "Dsa" to "Das", "IHC" to "ich", "eni" to "ein")) {
assertTrue("$typed -> $word", ShortWordGuard.isSwapOfNeighbors(typed, word))
}
}

@Test
fun otherDifferencesAreNoSwap() {
assertFalse(ShortWordGuard.isSwapOfNeighbors("das", "das")) // same word
assertFalse(ShortWordGuard.isSwapOfNeighbors("dsa", "sad")) // not neighbors
assertFalse(ShortWordGuard.isSwapOfNeighbors("das", "dar")) // a different letter
assertFalse(ShortWordGuard.isSwapOfNeighbors("db", "bd")) // only 3 letters
assertFalse(ShortWordGuard.isSwapOfNeighbors("ders", "dres")) // only 3 letters
assertFalse(ShortWordGuard.isSwapOfNeighbors("a1b", "1ab")) // only letters
assertFalse(ShortWordGuard.isSwapOfNeighbors("abc", "bca"))
}

private val neighbors = setOf("re", "ty", "io", "df", "mn")
private fun areNeighbors(a: Char, b: Char) = "$a$b" in neighbors || "$b$a" in neighbors

@Test
fun neighborKeySlipNeedsConfidentSuggestion() {
fun isSlip(typed: String, word: String, score: Float) =
ShortWordGuard.isTypingSlip(typed, word, ::areNeighbors) { score }
// measured on a device with the English dictionary
assertTrue(isSlip("hry", "hey", 0.211f))
assertTrue(isSlip("Yhe", "the", 0.381f))
assertFalse(isSlip("omg", "IMG", 0.105f))
assertFalse(isSlip("idk", "IFK", 0.130f)) // too weak, even where d and f are neighbors
assertFalse(isSlip("lol", "Lil", 0.123f))
assertFalse(isSlip("thx", "the", 0.199f)) // confident enough, but x and e are not neighbors
}

@Test
fun neighborKeySlipIsOneReplacedLetterInThreeLetterWords() {
assertTrue(ShortWordGuard.isNeighborKeySlip("hry", "hey", ::areNeighbors))
assertFalse(ShortWordGuard.isNeighborKeySlip("hay", "hey", ::areNeighbors)) // not neighbors
assertFalse(ShortWordGuard.isNeighborKeySlip("hrt", "hey", ::areNeighbors)) // two letters differ
assertFalse(ShortWordGuard.isNeighborKeySlip("hr", "he", ::areNeighbors)) // two letter words stay
assertFalse(ShortWordGuard.isNeighborKeySlip("hr1", "he1", ::areNeighbors)) // only letters
assertFalse(ShortWordGuard.isNeighborKeySlip("hey", "hey", ::areNeighbors))
}

@Test
fun neighborPositionsIncludeStaggeredRows() {
fun near(dxInKeys: Float, rows: Int) =
ShortWordGuard.areNeighborPositions((dxInKeys * 110).toInt(), rows * 150, 100, 150)
assertTrue(near(1f, 0)) // next key including the gap
assertTrue(near(0.5f, 1))
assertFalse(near(2f, 0))
assertFalse(near(1.5f, 1))
assertFalse(near(0.5f, 2))
}
}

27 changes: 0 additions & 27 deletions app/src/test/java/helium314/keyboard/latin/ShortWordSwapTest.kt

This file was deleted.

20 changes: 18 additions & 2 deletions app/src/test/java/helium314/keyboard/latin/SuggestTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,20 @@ class SuggestTest {
assert(!result.last())
}

@Test fun `unknown short word is only corrected if it looks like a typing slip`() {
val neighbors = { a: Char, b: Char -> "$a$b" in setOf("re", "oi") }
// the pref in shouldBeAutoCorrected below does not reach suggest, so set the (default) threshold here
suggest.setAutoCorrectionThreshold(0.067f)
// the shadow score is score / 1000000, weighted by 2/3 for one wrong letter in three
fun corrects(typed: String, word: String, score: Int, areNeighbors: (Char, Char) -> Boolean = neighbors) =
shouldBeAutoCorrected(typed, listOf(suggestion(word, score, Locale.ENGLISH)), null, null, Locale.ENGLISH,
0.067f, areNeighbors).last()
assert(corrects("hry", "hey", 300000)) // 0.2
assert(!corrects("omg", "img", 180000)) // 0.12: above the user threshold, but too weak for a short word
assert(!corrects("hry", "hey", 900000) { _, _ -> false }) // confident, but not a neighbor key
assert(corrects("teh", "the", 300000) { _, _ -> false }) // swapped letters don't need neighbor keys
}

@Test fun `moving emojis out of the first two places keeps the order of words`() {
val words = mutableListOf(suggestion("\uD83D\uDE00", 900, Locale.ENGLISH), suggestion("one", 800, Locale.ENGLISH),
suggestion("two", 700, Locale.ENGLISH), suggestion("\uD83D\uDE01", 600, Locale.ENGLISH))
Expand All @@ -453,7 +467,8 @@ class SuggestTest {
firstSuggestionForEmpty: SuggestedWordInfo?, // first suggestion if typed word would be empty (null if none)
typedWordSuggestionForEmpty: SuggestedWordInfo?, // suggestion for actually typed word if typed word would be empty (null if none)
typingLocale: Locale, // used for checking whether suggestion locale is the same, relevant e.g. for English i -> I shortcut, but we want Polish i
autoCorrectThreshold: Float
autoCorrectThreshold: Float,
areNeighborKeys: (Char, Char) -> Boolean = { _, _ -> false }
): List<Boolean> {
latinIME.prefs().edit { putFloat(Settings.PREF_AUTO_CORRECT_THRESHOLD, autoCorrectThreshold) }
// enable "more autocorrect" so we actually have autocorrect even though we don't set a compatible input type
Expand All @@ -479,7 +494,8 @@ class SuggestTest {
WordComposer.getComposerForTest(false),
suggestionResults,
firstOccurrenceOfTypedWordInSuggestions,
typedWordFirstOccurrenceWordInfo
typedWordFirstOccurrenceWordInfo,
areNeighborKeys
).toList()
}
}
Expand Down
Loading