Skip to content
Closed
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
5 changes: 5 additions & 0 deletions app/src/debug/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,10 @@
<service
android:name="helium314.keyboard.latin.voice.DebugVoiceEngineService"
android:exported="false" />
<!-- driven by tools/autocorrect_bench; DUMP limits senders to adb and the system -->
<receiver
android:name="helium314.keyboard.latin.bench.AutocorrectBenchReceiver"
android:permission="android.permission.DUMP"
android:exported="true" />
</application>
</manifest>
Original file line number Diff line number Diff line change
@@ -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<String>, threshold: Float,
history: List<String>): 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<Key>, 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<Key>, char: Char, dx: Float, dy: Float): Triple<Int, Int, Int> {
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
}
}
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
44 changes: 44 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,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
}
}
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
Loading
Loading