diff --git a/app/src/main/java/helium314/keyboard/latin/DictionaryFacilitator.kt b/app/src/main/java/helium314/keyboard/latin/DictionaryFacilitator.kt index 052f630d1d..f92ce2d222 100644 --- a/app/src/main/java/helium314/keyboard/latin/DictionaryFacilitator.kt +++ b/app/src/main/java/helium314/keyboard/latin/DictionaryFacilitator.kt @@ -112,6 +112,12 @@ interface DictionaryFacilitator { /** adjust confidences for multilingual typing */ fun adjustConfidences(word: String, wasAutoCapitalized: Boolean) + /** The user replaced the swiped word [replaced] by the suggestion [picked], see GestureWordBias. */ + fun recordGestureCorrection(picked: String, replaced: String) {} + + /** The user kept the swiped [word]. */ + fun recordGestureAccepted(word: String) {} + /** a string with all used locales and their current confidences, null if multilingual typing is not used */ fun localesAndConfidences(): String? diff --git a/app/src/main/java/helium314/keyboard/latin/DictionaryFacilitatorImpl.kt b/app/src/main/java/helium314/keyboard/latin/DictionaryFacilitatorImpl.kt index a407819b19..c40d4dc3db 100644 --- a/app/src/main/java/helium314/keyboard/latin/DictionaryFacilitatorImpl.kt +++ b/app/src/main/java/helium314/keyboard/latin/DictionaryFacilitatorImpl.kt @@ -31,6 +31,7 @@ import helium314.keyboard.latin.dictionary.ExpandableBinaryDictionary import helium314.keyboard.latin.dictionary.UserBinaryDictionary import helium314.keyboard.latin.dictionary.WordConsumer import helium314.keyboard.latin.permissions.PermissionsUtil +import helium314.keyboard.latin.personalization.GestureWordBias import helium314.keyboard.latin.personalization.SessionWordBoost import helium314.keyboard.latin.personalization.UserHistoryDictionary import helium314.keyboard.latin.settings.Settings @@ -134,9 +135,11 @@ class DictionaryFacilitatorImpl : DictionaryFacilitator { } // Persist session word boost data on input finish sessionWordBoost?.flushIfDirty() + gestureWordBias?.flushIfDirty() } private var sessionWordBoost: SessionWordBoost? = null + private var gestureWordBias: GestureWordBias? = null /** Lazily initialize SessionWordBoost when context is available */ private fun getSessionWordBoost(context: Context): SessionWordBoost { @@ -200,6 +203,9 @@ class DictionaryFacilitatorImpl : DictionaryFacilitator { if (sessionWordBoost == null) { sessionWordBoost = SessionWordBoost.getInstance(context) } + if (gestureWordBias == null) { + gestureWordBias = GestureWordBias.getInstance(context) + } val locales = getUsedLocales(newLocale, context) @@ -676,6 +682,9 @@ class DictionaryFacilitatorImpl : DictionaryFacilitator { applySessionBoost(suggestionResults, boost, ngramContext.isBeginningOfSentenceContext) } + // Learn from corrections after swipes: close calls go to the word the user picked before, see GestureWordBias + if (composedData.mIsBatchMode) gestureWordBias?.takeIf { !it.isEmpty }?.let { applyGestureBias(suggestionResults, it) } + includeAtLeastTwoWordSuggestions(suggestionResults, suggestionsArray, composedData.mTypedWord) if (composedData.mTypedWord.isEmpty() && !composedData.mIsBatchMode) { @@ -921,6 +930,32 @@ class DictionaryFacilitatorImpl : DictionaryFacilitator { } } + private fun applyGestureBias(results: SuggestionResults, bias: GestureWordBias) { + val changed = results.mapNotNull { info -> + val adjustment = bias.getAdjustment(info.mWord) + if (adjustment == 0f) null + else info to SuggestedWordInfo( + info.mWord, info.mPrevWordsContext, GestureWordBias.adjustScore(info.mScore, adjustment), + info.mKindAndFlags, info.mSourceDict, info.mIndexOfTouchPointOfSecondWord, info.mAutoCommitFirstWordConfidence + ) + } + for ((old, new) in changed) { + results.remove(old) + results.add(new) + } + } + + override fun recordGestureCorrection(picked: String, replaced: String) { + gestureWordBias?.let { + it.recordCorrection(picked, replaced) + it.flushIfDirty() // corrections are rare and the file is small, so do not wait for onFinishInput + } + } + + override fun recordGestureAccepted(word: String) { + gestureWordBias?.recordAccepted(word) + } + /** * Apply session word boost to suggestion results. * Creates new SuggestedWordInfo objects with boosted scores for words @@ -998,6 +1033,7 @@ class DictionaryFacilitatorImpl : DictionaryFacilitator { override fun removeWord(word: String) { sessionWordBoost?.removeWord(word) + gestureWordBias?.removeWord(word) // Decide once for all groups: blacklist matching ignores case and checks every group, // so a word of one language must not get blacklisted through another language's group. // Blocking ignores case, so a capitalized variant of a valid lowercase word ("Of" for "of") is only @@ -1016,6 +1052,7 @@ class DictionaryFacilitatorImpl : DictionaryFacilitator { override fun clearUserHistoryDictionary(context: Context) { sessionWordBoost?.clear() + gestureWordBias?.clear() for (dictionaryGroup in dictionaryGroups) { dictionaryGroup.getSubDict(Dictionary.TYPE_USER_HISTORY)?.clear() } diff --git a/app/src/main/java/helium314/keyboard/latin/inputlogic/InputLogic.kt b/app/src/main/java/helium314/keyboard/latin/inputlogic/InputLogic.kt index 4ead40cfc4..b14fa7cca5 100644 --- a/app/src/main/java/helium314/keyboard/latin/inputlogic/InputLogic.kt +++ b/app/src/main/java/helium314/keyboard/latin/inputlogic/InputLogic.kt @@ -340,6 +340,15 @@ class InputLogic( return onCodeInput(settingsValues, event, keyboardShiftState, handler) } + // A swiped word replaced by another suggestion is a correction the next swipes should learn from + if (mWordComposer.isBatchMode() && mWordComposer.isComposingWord() && !settingsValues.mIncognitoModeEnabled + && !suggestionInfo.isEmoji && !suggestionInfo.isKindOf(SuggestedWordInfo.KIND_SHORTCUT) + ) { + val replacedWord = mWordComposer.getTypedWord() + if (replacedWord.isNotEmpty() && !replacedWord.equals(rawSuggestion, ignoreCase = true)) + mDictionaryFacilitator.recordGestureCorrection(rawSuggestion, replacedWord) + } + val event = Event.createSuggestionPickedEvent(suggestionInfo) val inputTransaction = InputTransaction( settingsValues, @@ -2304,6 +2313,7 @@ class InputLogic( word, wasAutoCapitalized, ngramContext, timeStampInSeconds, settingsValues.mBlockPotentiallyOffensive ) + if (mWordComposer.isBatchMode()) mDictionaryFacilitator.recordGestureAccepted(word) } private fun stripWordSeparatorsFromEnd(word: String, settingsValues: SettingsValues): String { diff --git a/app/src/main/java/helium314/keyboard/latin/personalization/GestureWordBias.kt b/app/src/main/java/helium314/keyboard/latin/personalization/GestureWordBias.kt new file mode 100644 index 0000000000..9364101620 --- /dev/null +++ b/app/src/main/java/helium314/keyboard/latin/personalization/GestureWordBias.kt @@ -0,0 +1,181 @@ +/* + * SPDX-License-Identifier: GPL-3.0-only + */ +package helium314.keyboard.latin.personalization + +import android.content.Context +import helium314.keyboard.latin.utils.Log +import helium314.keyboard.latin.utils.WordTokenizer +import java.io.File +import java.io.IOException +import java.util.Locale +import java.util.concurrent.ConcurrentHashMap +import kotlin.math.exp +import kotlin.math.min + +/** + * Learns from the corrections a user makes after a swipe: when the first suggestion is replaced by another one, + * the picked word gets a small relative score bonus and the replaced word a small malus in later swipes. + * + * Swipe scores are in the tens of millions, so the additive boost of [SessionWordBoost] cannot change a + * ranking. Here the adjustment is a fraction of the score, capped at [MAX_ADJUSTMENT] in both directions: + * it only decides close calls and never beats a clearly better geometric match. It fades over time. + * + * Thread safety: corrections come from the UI thread, lookups from the suggestion thread. The map is concurrent, + * entries are only changed inside [ConcurrentHashMap.compute], and saving is serialized by [saveLock]. + */ +class GestureWordBias internal constructor(private val file: File) { + private val entries = ConcurrentHashMap() + private val saveLock = Any() + @Volatile private var dirty = false + + data class Entry(var picks: Int, var rejects: Int, var lastMs: Long) + + init { + load() + } + + val isEmpty get() = entries.isEmpty() + val size get() = entries.size + + /** The user replaced the swiped [replaced] by the suggestion [picked]. */ + fun recordCorrection(picked: String, replaced: String) { + val pickedKey = key(picked) ?: return + val replacedKey = key(replaced) ?: return + if (pickedKey == replacedKey) return + val now = System.currentTimeMillis() + entries.compute(pickedKey) { _, e -> (e ?: Entry(0, 0, now)).also { it.picks = min(it.picks + 1, MAX_COUNT); it.lastMs = now } } + entries.compute(replacedKey) { _, e -> (e ?: Entry(0, 0, now)).also { it.rejects = min(it.rejects + 1, MAX_COUNT); it.lastMs = now } } + evictIfNeeded() + dirty = true + } + + /** The user kept the swiped [word]: undoes part of earlier rejections of it. */ + fun recordAccepted(word: String) { + val k = key(word) ?: return + entries.computeIfPresent(k) { _, e -> + if (e.rejects > 0) { + e.rejects-- + dirty = true + } + e + } + } + + /** Relative score change for [word], between -[MAX_ADJUSTMENT] and +[MAX_ADJUSTMENT], 0 for unknown words. */ + fun getAdjustment(word: String): Float { + if (entries.isEmpty()) return 0f + val e = entries[key(word) ?: return 0f] ?: return 0f + val days = (System.currentTimeMillis() - e.lastMs) / MILLIS_PER_DAY.toFloat() + return adjustment(e.picks, e.rejects, days) + } + + fun removeWord(word: String) { + val k = key(word) ?: return + if (entries.remove(k) != null) dirty = true + } + + fun clear() { + entries.clear() + dirty = false + synchronized(saveLock) { file.delete() } + } + + fun flushIfDirty() { + if (!dirty) return + dirty = false + if (!save()) dirty = true // try again at the next flush + } + + /** Normalized lookup key, null for words that cannot be learned (too short, or break the file format). */ + private fun key(word: String): String? { + if (word.any { it == '\t' || it == '\n' || it == '\r' }) return null + val k = WordTokenizer.normalizeForLookup(word).lowercase(Locale.ROOT) + return if (k.length < 2 || k.length > MAX_WORD_LENGTH) null else k + } + + private fun evictIfNeeded() { + while (entries.size > MAX_ENTRIES) { + val oldest = entries.entries.minByOrNull { it.value.lastMs } ?: return + entries.remove(oldest.key) + } + } + + private fun load() { + if (!file.isFile) return + try { + file.forEachLine { line -> + val parts = line.split('\t') + if (parts.size != 4 || parts[0].isEmpty()) return@forEachLine + val picks = parts[1].toIntOrNull()?.coerceIn(0, MAX_COUNT) ?: return@forEachLine + val rejects = parts[2].toIntOrNull()?.coerceIn(0, MAX_COUNT) ?: return@forEachLine + val last = parts[3].toLongOrNull() ?: return@forEachLine + entries[parts[0]] = Entry(picks, rejects, last) + } + val cutoff = System.currentTimeMillis() - MAX_AGE_DAYS * MILLIS_PER_DAY + if (entries.values.removeAll { it.lastMs < cutoff }) dirty = true + while (entries.size > MAX_ENTRIES) evictIfNeeded() + } catch (e: Exception) { // unreadable or malformed file: start over, this data is only a hint + Log.w(TAG, "Failed to load gesture bias, ignoring it", e) + entries.clear() + } + } + + /** Writes to a temporary file and renames it, so a crash cannot leave a half written file. */ + private fun save(): Boolean = synchronized(saveLock) { + try { + file.parentFile?.mkdirs() + val temp = File(file.parentFile, file.name + ".tmp") + temp.bufferedWriter().use { writer -> + for ((word, e) in entries) { + writer.write("$word\t${e.picks}\t${e.rejects}\t${e.lastMs}") + writer.newLine() + } + } + if (!temp.renameTo(file)) { + file.delete() + if (!temp.renameTo(file)) throw IOException("cannot replace ${file.name}") + } + true + } catch (e: Exception) { + Log.w(TAG, "Failed to save gesture bias", e) + false + } + } + + companion object { + private const val TAG = "GestureWordBias" + private const val FILENAME = "gesture_word_bias.dat" + private const val MAX_ENTRIES = 500 + private const val MAX_COUNT = 1000 + private const val MAX_WORD_LENGTH = 64 + private const val MILLIS_PER_DAY = 86_400_000L + private const val MAX_AGE_DAYS = 60L + private const val DECAY_LAMBDA = 0.0495 // half-life of 14 days + const val PICK_STEP = 0.005f + const val REJECT_STEP = 0.01f + const val MAX_ADJUSTMENT = 0.03f + + /** Pure scoring rule, public for testing. */ + fun adjustment(picks: Int, rejects: Int, daysSinceLastUse: Float): Float { + val bonus = min(picks.coerceAtLeast(0) * PICK_STEP, MAX_ADJUSTMENT) + val malus = min(rejects.coerceAtLeast(0) * REJECT_STEP, MAX_ADJUSTMENT) + val decay = exp(-DECAY_LAMBDA * daysSinceLastUse.coerceAtLeast(0f)).toFloat() + return ((bonus - malus) * decay).coerceIn(-MAX_ADJUSTMENT, MAX_ADJUSTMENT) + } + + /** Applies a relative [adjustment] to a score without overflowing, positive scores only (negative ones are junk). */ + fun adjustScore(score: Int, adjustment: Float): Int { + if (score <= 0 || adjustment == 0f) return score + val delta = (score.toLong() * adjustment).toLong() + return (score + delta).coerceIn(1L, Int.MAX_VALUE.toLong()).toInt() + } + + @Volatile + private var instance: GestureWordBias? = null + + fun getInstance(context: Context): GestureWordBias = instance ?: synchronized(this) { + instance ?: GestureWordBias(File(context.filesDir, FILENAME)).also { instance = it } + } + } +} diff --git a/app/src/test/java/helium314/keyboard/latin/personalization/GestureWordBiasTest.kt b/app/src/test/java/helium314/keyboard/latin/personalization/GestureWordBiasTest.kt new file mode 100644 index 0000000000..1735ac075c --- /dev/null +++ b/app/src/test/java/helium314/keyboard/latin/personalization/GestureWordBiasTest.kt @@ -0,0 +1,158 @@ +// SPDX-License-Identifier: GPL-3.0-only +package helium314.keyboard.latin.personalization + +import helium314.keyboard.latin.personalization.GestureWordBias.Companion.MAX_ADJUSTMENT +import helium314.keyboard.latin.personalization.GestureWordBias.Companion.adjustScore +import helium314.keyboard.latin.personalization.GestureWordBias.Companion.adjustment +import java.io.File +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class GestureWordBiasTest { + private val dir = File.createTempFile("gesture_bias", "").also { it.delete(); it.mkdirs() } + private val file = File(dir, "gesture_word_bias.dat") + + @AfterTest fun cleanup() { dir.deleteRecursively() } + + // --- scoring rule --- + + @Test fun `no history means no change`() { + assertEquals(0f, adjustment(0, 0, 0f)) + } + + @Test fun `picks raise and rejects lower the score`() { + assertTrue(adjustment(2, 0, 0f) > 0f) + assertTrue(adjustment(0, 2, 0f) < 0f) + } + + @Test fun `adjustment is capped in both directions, also for corrupt counts`() { + assertEquals(MAX_ADJUSTMENT, adjustment(1000, 0, 0f), 1e-6f) + assertEquals(-MAX_ADJUSTMENT, adjustment(0, 1000, 0f), 1e-6f) + assertEquals(0f, adjustment(-50, 0, 0f), 1e-6f) // negative counts must not invert the sign + assertEquals(MAX_ADJUSTMENT, adjustment(Int.MAX_VALUE, 0, 0f), 1e-6f) + } + + @Test fun `picks and rejects of the same word offset each other`() { + assertEquals(0f, adjustment(2, 1, 0f), 1e-6f) + } + + @Test fun `adjustment fades with time and ignores a clock that went backwards`() { + val fresh = adjustment(4, 0, 0f) + assertEquals(fresh / 4f, adjustment(4, 0, 28f), fresh * 0.02f) // two half-lives + assertEquals(fresh, adjustment(4, 0, -10f), 1e-6f) + } + + @Test fun `a close call flips but a clear lead stays`() { + val bonus = adjustment(2, 0, 0f) + assertTrue(1.0f * (1f + bonus) > 1.003f) // 0.3% gap flips after two picks + assertTrue(1.0f * (1f + MAX_ADJUSTMENT) < 1.10f) // a 10% gap never does + } + + @Test fun `score adjustment does not overflow or touch junk scores`() { + assertEquals(Int.MAX_VALUE, adjustScore(Int.MAX_VALUE, MAX_ADJUSTMENT)) + assertEquals(-2_000_000_000, adjustScore(-2_000_000_000, MAX_ADJUSTMENT)) + assertEquals(0, adjustScore(0, MAX_ADJUSTMENT)) + assertEquals(1, adjustScore(1, -MAX_ADJUSTMENT)) + assertEquals(103_000_000, adjustScore(100_000_000, MAX_ADJUSTMENT)) + assertEquals(97_000_000, adjustScore(100_000_000, -MAX_ADJUSTMENT)) + } + + // --- store --- + + @Test fun `correction raises picked and lowers replaced, case and punctuation insensitive`() { + val bias = GestureWordBias(file) + repeat(3) { bias.recordCorrection("Typing", "ruling") } + assertTrue(bias.getAdjustment("typing") > 0f) + assertTrue(bias.getAdjustment("TYPING") > 0f) + assertTrue(bias.getAdjustment("ruling") < 0f) + assertEquals(0f, bias.getAdjustment("unknown")) + } + + @Test fun `same word, short words and file breaking words are ignored`() { + val bias = GestureWordBias(file) + bias.recordCorrection("Typing", "typing") + bias.recordCorrection("a", "to") + bias.recordCorrection("bad\tword", "other") + bias.recordCorrection("new\nline", "other") + bias.recordCorrection("x".repeat(100), "other") + assertTrue(bias.isEmpty) + } + + @Test fun `accepting a word undoes one rejection and never goes below zero`() { + val bias = GestureWordBias(file) + bias.recordCorrection("typing", "ruling") + bias.recordAccepted("ruling") + assertEquals(0f, bias.getAdjustment("ruling"), 1e-6f) + bias.recordAccepted("ruling") + bias.recordAccepted("never-seen") + assertEquals(0f, bias.getAdjustment("ruling"), 1e-6f) + } + + @Test fun `data survives a restart`() { + val bias = GestureWordBias(file) + repeat(2) { bias.recordCorrection("done", "dio") } + bias.flushIfDirty() + assertFalse(File(dir, "gesture_word_bias.dat.tmp").exists()) + val reloaded = GestureWordBias(file) + assertEquals(bias.getAdjustment("done"), reloaded.getAdjustment("done"), 1e-6f) + assertEquals(bias.getAdjustment("dio"), reloaded.getAdjustment("dio"), 1e-6f) + } + + @Test fun `malformed, hostile and stale lines in the file are skipped or clamped`() { + val now = System.currentTimeMillis() + val old = now - 100L * 86_400_000L + file.writeText( + "good\t2\t0\t$now\n" + + "garbage line\n" + + "neg\t-5\t0\t$now\n" + + "huge\t999999999\t0\t$now\n" + + "nan\tx\t0\t$now\n" + + "stale\t5\t0\t$old\n" + + "\t1\t1\t$now\n" + ) + val bias = GestureWordBias(file) + assertTrue(bias.getAdjustment("good") > 0f) + assertEquals(0f, bias.getAdjustment("neg"), 1e-6f) // clamped to zero, not an inverted sign + assertEquals(MAX_ADJUSTMENT, bias.getAdjustment("huge"), 1e-6f) + assertEquals(0f, bias.getAdjustment("stale")) + assertEquals(3, bias.size) + } + + @Test fun `an unreadable file is ignored`() { + file.mkdirs() // a directory where the file should be + val bias = GestureWordBias(file) + assertTrue(bias.isEmpty) + bias.recordCorrection("done", "dio") // must not throw + bias.flushIfDirty() + } + + @Test fun `store never grows past its limit and drops the oldest`() { + val bias = GestureWordBias(file) + repeat(300) { bias.recordCorrection("pick$it", "reject$it") } + assertTrue(bias.size <= 500) + assertTrue(bias.getAdjustment("pick299") > 0f) // newest kept + } + + @Test fun `remove and clear forget the words and the file`() { + val bias = GestureWordBias(file) + bias.recordCorrection("done", "dio") + bias.flushIfDirty() + bias.removeWord("done") + assertEquals(0f, bias.getAdjustment("done")) + bias.clear() + assertTrue(bias.isEmpty) + assertFalse(file.exists()) + } + + @Test fun `lookups during corrections on another thread do not fail`() { + val bias = GestureWordBias(file) + val writer = Thread { repeat(2000) { bias.recordCorrection("word${it % 50}", "other${it % 50}"); bias.flushIfDirty() } } + writer.start() + repeat(5000) { bias.getAdjustment("word${it % 50}") } + writer.join() + assertTrue(bias.size > 0) + } +}