From bd36e792559737971a4c479d7d269edcd7b3fa75 Mon Sep 17 00:00:00 2001 From: 4di-hello <4di-hello@users.noreply.github.com> Date: Sat, 28 Nov 2026 12:49:12 +0100 Subject: [PATCH 1/9] Voice input: speed display after each dictation Optional (off by default) in the voice settings: recording time, how long it waited for silence after the last word, recognition time after the recording, when the text was there after the last word, and how many parts were already recognized while speaking. Journal: key findings on top. Co-Authored-By: Claude Opus 5.5 --- .../leantype/voice/VoiceDataClasses.kt | 2 ++ .../keyboard/latin/voice/VoiceInputManager.kt | 35 +++++++++++++++++++ .../settings/screens/VoiceSettingsScreen.kt | 15 ++++++++ app/src/main/res/values-de/strings.xml | 7 ++++ app/src/main/res/values/strings.xml | 7 ++++ 5 files changed, 66 insertions(+) diff --git a/app/src/main/java/com/leanbitlab/leantype/voice/VoiceDataClasses.kt b/app/src/main/java/com/leanbitlab/leantype/voice/VoiceDataClasses.kt index 173325fc62..8dcccac1d4 100644 --- a/app/src/main/java/com/leanbitlab/leantype/voice/VoiceDataClasses.kt +++ b/app/src/main/java/com/leanbitlab/leantype/voice/VoiceDataClasses.kt @@ -98,6 +98,8 @@ object VoiceConstants { const val PREF_VOICE_CUSTOM_PROMPT = "voice_custom_prompt" /** Transcribe the recording in pieces at speech pauses while still recording */ const val PREF_VOICE_TRANSCRIBE_WHILE_SPEAKING = "voice_transcribe_while_speaking" + /** Show after each dictation how long recording, waiting for silence and recognition took */ + const val PREF_VOICE_SHOW_STATS = "voice_show_stats" const val PREF_VOICE_MIC_SENSITIVITY = "voice_mic_sensitivity" const val PREF_VOICE_MAX_DURATION_SECONDS = "voice_max_duration_seconds" const val PREF_VOICE_AUTO_RETRY = "pref_voice_auto_retry" diff --git a/app/src/main/java/helium314/keyboard/latin/voice/VoiceInputManager.kt b/app/src/main/java/helium314/keyboard/latin/voice/VoiceInputManager.kt index ca2ae6a1d9..8349d82f06 100644 --- a/app/src/main/java/helium314/keyboard/latin/voice/VoiceInputManager.kt +++ b/app/src/main/java/helium314/keyboard/latin/voice/VoiceInputManager.kt @@ -126,6 +126,10 @@ class VoiceInputManager( private var processingTimeoutRunnable: Runnable? = null // start of the current recording, the time for processing depends on its length private var recordingStartedAt = 0L + // speed display: when speech was last heard, when recording stopped, how many pieces were transcribed + @Volatile private var lastSpeechAt = 0L + private var recordingStoppedAt = 0L + private var piecesTranscribed = 0 private var needsCapitalStart = true private var sessionEmittedText = "" @@ -552,6 +556,7 @@ class VoiceInputManager( var totalBytesWritten = 0L val sessionStartTime = System.currentTimeMillis() recordingStartedAt = sessionStartTime + lastSpeechAt = 0L var lastSpeechTime = sessionStartTime var hasSpoken = false var ambientNoiseRms = speechRmsThreshold * 0.5 @@ -612,6 +617,7 @@ class VoiceInputManager( val isSpeech = rms > effectiveSpeechThreshold if (isSpeech) { lastSpeechTime = now + lastSpeechAt = now hasSpoken = true } else { ambientNoiseRms = 0.95 * ambientNoiseRms + 0.05 * rms @@ -758,6 +764,7 @@ class VoiceInputManager( fun stopVoice() { Log.i(TAG, "stopVoice() called, state=$state, isOnline=$isCurrentSessionOnline") if (state == VoiceState.RECORDING || state == VoiceState.STARTING_SESSION || state == VoiceState.CONNECTING_PLUGIN) { + recordingStoppedAt = System.currentTimeMillis() updateState(VoiceState.PROCESSING_FINAL) scheduleProcessingTimeout() stopAudioLoop() @@ -1033,6 +1040,7 @@ class VoiceInputManager( return@post } val recognized = text.orEmpty().trim() + piecesTranscribed++ if (recognized.isNotEmpty()) { syncRecognizedText(recognized, isFinal = true) piecewiseContext = (piecewiseContext + " " + recognized).takeLast(PIECE_CONTEXT_CHARS * 2) @@ -1279,6 +1287,11 @@ class VoiceInputManager( } Log.i(TAG, "State transition: $oldState -> $newState") this.state = newState + if (oldState == VoiceState.PROCESSING_FINAL && newState == VoiceState.IDLE) showStats() + if (newState == VoiceState.RECORDING && oldState != VoiceState.RECORDING) { + recordingStoppedAt = 0L + piecesTranscribed = 0 + } // full speed for the plugin only while dictating val dictating = newState == VoiceState.RECORDING || newState == VoiceState.PROCESSING_FINAL mainHandler.post { pluginManager.setDictationPriority(dictating) } @@ -1287,6 +1300,28 @@ class VoiceInputManager( } } + /** + * Speed display after a dictation (setting, off by default): how long the recording ran, how long + * it waited for silence after the last word, and how long recognition took after recording ended. + */ + private fun showStats() { + if (!ims.prefs().getBoolean(VoiceConstants.PREF_VOICE_SHOW_STATS, false)) return + val stoppedAt = recordingStoppedAt + if (stoppedAt <= 0L || recordingStartedAt <= 0L) return + val now = System.currentTimeMillis() + fun seconds(millis: Long) = String.format(java.util.Locale.getDefault(), "%.1f", millis / 1000.0) + val lines = mutableListOf(ims.getString(R.string.voice_stats_recording, seconds(stoppedAt - recordingStartedAt))) + val lastSpeech = lastSpeechAt + if (lastSpeech in recordingStartedAt..stoppedAt) + lines.add(ims.getString(R.string.voice_stats_silence, seconds(stoppedAt - lastSpeech))) + lines.add(ims.getString(R.string.voice_stats_recognition, seconds(now - stoppedAt))) + if (lastSpeech in recordingStartedAt..stoppedAt) + lines.add(ims.getString(R.string.voice_stats_total, seconds(now - lastSpeech))) + if (piecesTranscribed > 0) lines.add(ims.getString(R.string.voice_stats_pieces, piecesTranscribed)) + val text = lines.joinToString("\n") + mainHandler.post { helium314.keyboard.keyboard.KeyboardSwitcher.getInstance().showLongToast(text, 6000) } + } + private fun notifyError(message: String, canRetry: Boolean = true) { mainHandler.post { listener?.onError(message, canRetry) diff --git a/app/src/main/java/helium314/keyboard/settings/screens/VoiceSettingsScreen.kt b/app/src/main/java/helium314/keyboard/settings/screens/VoiceSettingsScreen.kt index 1db2e8608c..ccea726f5e 100644 --- a/app/src/main/java/helium314/keyboard/settings/screens/VoiceSettingsScreen.kt +++ b/app/src/main/java/helium314/keyboard/settings/screens/VoiceSettingsScreen.kt @@ -527,6 +527,20 @@ fun VoiceSettingsScreen( } } + val showStatsSetting = remember(context) { + Setting( + key = VoiceConstants.PREF_VOICE_SHOW_STATS, + title = context.getString(R.string.voice_show_stats_title), + description = context.getString(R.string.voice_show_stats_summary) + ) { + SwitchPreference( + setting = it, + default = false, + icon = R.drawable.ic_settings_advanced + ) + } + } + val customPromptSetting = remember(context) { Setting( key = VoiceConstants.PREF_VOICE_CUSTOM_PROMPT, @@ -850,6 +864,7 @@ fun VoiceSettingsScreen( if (isOfflineVoiceEnabled) { cpuThreadsSetting.Preference() whileSpeakingSetting.Preference() + showStatsSetting.Preference() } customPromptSetting.Preference() if (isOfflineVoiceEnabled) { diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 3ceb25bd6a..6f1ee99d53 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1729,6 +1729,13 @@ Ermöglicht lokale GGUF / llama.cpp-Inferenz für Korrekturlesen und Umschreiben FUTO-Sprachmodelle (ACFT) Durchsuchen Schon beim Sprechen erkennen + Leistungsanzeige + Nach jedem Diktat: Aufnahmezeit, Warten auf Stille nach dem letzten Wort, Erkennungszeit + Aufnahme %s s + Stille abgewartet nach dem letzten Wort %s s + Erkennung nach der Aufnahme %s s + Text da %s s nach dem letzten Wort + %d Teile schon beim Sprechen erkannt Diktat beendet: Das Textfeld hat gewechselt, der Rest wurde nicht eingefügt Auf seiner Seite zeigen diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index afa0dfb00d..061488e376 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -2486,6 +2486,13 @@ New dictionary: None (Plain text) Transcribe while speaking Shorter wait for long dictations + Show speed + After each dictation: recording time, waiting for silence after the last word, recognition time + Recording %s s + waited for silence after the last word %s s + recognition after the recording %s s + text there %s s after the last word + %d parts recognized while speaking Dictation stopped: the text field changed, the rest was not inserted Show in its screen From ab5d05c3984ea29e80876f3b6e232572dd55d006 Mon Sep 17 00:00:00 2001 From: 4di-hello <4di-hello@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:01:48 +0100 Subject: [PATCH 2/9] Voice input: show which model is in use The plugin stores every Whisper model under the same name, so an imported model was only "custom". The file name of the import is now kept and shown in the voice settings (models entry), in the model dialog and in the speed display. Listed models show their name. Journal: voice plugin measurements. Co-Authored-By: Claude Opus 5.5 --- .../keyboard/latin/voice/VoiceInputManager.kt | 5 ++++- .../keyboard/latin/voice/VoiceModelRegistry.kt | 11 +++++++++++ .../settings/dialogs/VoiceModelDownloadDialog.kt | 6 ++++-- .../settings/screens/VoiceSettingsScreen.kt | 13 +++++++++++-- app/src/main/res/values-de/strings.xml | 1 + app/src/main/res/values/strings.xml | 1 + 6 files changed, 32 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/helium314/keyboard/latin/voice/VoiceInputManager.kt b/app/src/main/java/helium314/keyboard/latin/voice/VoiceInputManager.kt index 8349d82f06..aa37ab8b62 100644 --- a/app/src/main/java/helium314/keyboard/latin/voice/VoiceInputManager.kt +++ b/app/src/main/java/helium314/keyboard/latin/voice/VoiceInputManager.kt @@ -1310,7 +1310,10 @@ class VoiceInputManager( if (stoppedAt <= 0L || recordingStartedAt <= 0L) return val now = System.currentTimeMillis() fun seconds(millis: Long) = String.format(java.util.Locale.getDefault(), "%.1f", millis / 1000.0) - val lines = mutableListOf(ims.getString(R.string.voice_stats_recording, seconds(stoppedAt - recordingStartedAt))) + val lines = mutableListOf() + // which model, for comparing (not for cloud recognition) + if (!isCurrentSessionOnline) VoiceModelRegistry.installedWhisperName(ims.prefs())?.let { lines.add(ims.getString(R.string.voice_stats_model, it)) } + lines.add(ims.getString(R.string.voice_stats_recording, seconds(stoppedAt - recordingStartedAt))) val lastSpeech = lastSpeechAt if (lastSpeech in recordingStartedAt..stoppedAt) lines.add(ims.getString(R.string.voice_stats_silence, seconds(stoppedAt - lastSpeech))) diff --git a/app/src/main/java/helium314/keyboard/latin/voice/VoiceModelRegistry.kt b/app/src/main/java/helium314/keyboard/latin/voice/VoiceModelRegistry.kt index f2dc5ae1fe..5f0b69cb5f 100644 --- a/app/src/main/java/helium314/keyboard/latin/voice/VoiceModelRegistry.kt +++ b/app/src/main/java/helium314/keyboard/latin/voice/VoiceModelRegistry.kt @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-3.0-only package helium314.keyboard.latin.voice +import android.content.SharedPreferences import com.leanbitlab.leantype.voice.VoiceConstants data class VoiceModelItem( @@ -16,6 +17,16 @@ data class VoiceModelItem( ) object VoiceModelRegistry { + /** file name of an imported Whisper model (the plugin stores every model under the same name) */ + const val PREF_IMPORTED_WHISPER_FILE = "installed_model_file_${VoiceConstants.ENGINE_WHISPER}" + + /** Name of the Whisper model in use: the listed model, or the file name of an imported one; null if unknown */ + fun installedWhisperName(prefs: SharedPreferences): String? { + val id = prefs.getString("installed_model_${VoiceConstants.ENGINE_WHISPER}", null) ?: return null + whisperModels.firstOrNull { it.id == id }?.let { return it.displayName } + return prefs.getString(PREF_IMPORTED_WHISPER_FILE, null) + } + val whisperModels = listOf( VoiceModelItem( id = "whisper-tiny.en-q5_1", diff --git a/app/src/main/java/helium314/keyboard/settings/dialogs/VoiceModelDownloadDialog.kt b/app/src/main/java/helium314/keyboard/settings/dialogs/VoiceModelDownloadDialog.kt index 0d75b3aa5e..7831667c4e 100644 --- a/app/src/main/java/helium314/keyboard/settings/dialogs/VoiceModelDownloadDialog.kt +++ b/app/src/main/java/helium314/keyboard/settings/dialogs/VoiceModelDownloadDialog.kt @@ -163,7 +163,9 @@ fun VoiceModelDownloadDialog( fontWeight = FontWeight.Medium ) Text( - text = if (isCustomWhisperInstalled) stringResource(R.string.voice_imported_and_ready) else stringResource(R.string.voice_load_external_bin), + text = if (isCustomWhisperInstalled) + listOfNotNull(stringResource(R.string.voice_imported_and_ready), prefs.getString(VoiceModelRegistry.PREF_IMPORTED_WHISPER_FILE, null)).joinToString(": ") + else stringResource(R.string.voice_load_external_bin), style = MaterialTheme.typography.bodySmall, color = if (isCustomWhisperInstalled) MaterialTheme.colorScheme.primary @@ -175,7 +177,7 @@ fun VoiceModelDownloadDialog( if (isCustomWhisperInstalled) { Button( onClick = { - prefs.edit().remove("installed_model_${VoiceConstants.ENGINE_WHISPER}").apply() + prefs.edit().remove("installed_model_${VoiceConstants.ENGINE_WHISPER}").remove(VoiceModelRegistry.PREF_IMPORTED_WHISPER_FILE).apply() pluginManager.deleteModel(VoiceConstants.ENGINE_WHISPER) Toast.makeText(context, context.getString(R.string.voice_custom_model_removed), Toast.LENGTH_SHORT).show() onRefresh() diff --git a/app/src/main/java/helium314/keyboard/settings/screens/VoiceSettingsScreen.kt b/app/src/main/java/helium314/keyboard/settings/screens/VoiceSettingsScreen.kt index ccea726f5e..7dd694aeb0 100644 --- a/app/src/main/java/helium314/keyboard/settings/screens/VoiceSettingsScreen.kt +++ b/app/src/main/java/helium314/keyboard/settings/screens/VoiceSettingsScreen.kt @@ -266,6 +266,12 @@ fun VoiceSettingsScreen( val pfd = context.contentResolver.openFileDescriptor(uri, "r") if (pfd != null) { val size = pfd.statSize + // the plugin keeps only the model, the file name tells which one it is + val fileName = try { + context.contentResolver.query(uri, arrayOf(android.provider.OpenableColumns.DISPLAY_NAME), null, null, null)?.use { + if (it.moveToFirst()) it.getString(0) else null + } + } catch (_: Exception) { null } val request = ModelImportRequest( engineType = VoiceConstants.ENGINE_WHISPER, language = "multilingual", @@ -276,7 +282,9 @@ fun VoiceSettingsScreen( val success = pluginManager.bindAndImport(request) withContext(Dispatchers.Main) { if (success) { - prefs.edit().putString("installed_model_${VoiceConstants.ENGINE_WHISPER}", "custom").apply() + prefs.edit().putString("installed_model_${VoiceConstants.ENGINE_WHISPER}", "custom") + .apply { if (fileName != null) putString(helium314.keyboard.latin.voice.VoiceModelRegistry.PREF_IMPORTED_WHISPER_FILE, fileName) else remove(helium314.keyboard.latin.voice.VoiceModelRegistry.PREF_IMPORTED_WHISPER_FILE) } + .apply() Toast.makeText(context, context.getString(R.string.voice_whisper_import_dispatched), Toast.LENGTH_SHORT).show() } else { Toast.makeText(context, context.getString(R.string.voice_plugin_import_failed), Toast.LENGTH_SHORT).show() @@ -803,7 +811,8 @@ fun VoiceSettingsScreen( Preference( name = stringResource(R.string.voice_manage_download_models), - description = null, + // which model is in use + description = if (whisperState != null) helium314.keyboard.latin.voice.VoiceModelRegistry.installedWhisperName(prefs) else null, icon = R.drawable.sym_keyboard_voice_holo, onClick = { showModelDownloadDialog = true diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 6f1ee99d53..34cfb5e078 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1731,6 +1731,7 @@ Ermöglicht lokale GGUF / llama.cpp-Inferenz für Korrekturlesen und Umschreiben Schon beim Sprechen erkennen Leistungsanzeige Nach jedem Diktat: Aufnahmezeit, Warten auf Stille nach dem letzten Wort, Erkennungszeit + Modell %s Aufnahme %s s Stille abgewartet nach dem letzten Wort %s s Erkennung nach der Aufnahme %s s diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 061488e376..50bb49b5a8 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -2488,6 +2488,7 @@ New dictionary: Shorter wait for long dictations Show speed After each dictation: recording time, waiting for silence after the last word, recognition time + Model %s Recording %s s waited for silence after the last word %s s recognition after the recording %s s From cee44e3e9322308863fbc032c49c497111a43927 Mon Sep 17 00:00:00 2001 From: 4di-hello <4di-hello@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:33:04 +0100 Subject: [PATCH 3/9] Voice input: threads in the speed display, hint for a model imported without name The settings showed nothing for a model imported before its file name was stored. Co-Authored-By: Claude Opus 5.5 --- .../helium314/keyboard/latin/voice/VoiceInputManager.kt | 6 +++++- .../helium314/keyboard/latin/voice/VoiceModelRegistry.kt | 6 ++++++ .../keyboard/settings/screens/VoiceSettingsScreen.kt | 2 +- app/src/main/res/values-de/strings.xml | 2 ++ app/src/main/res/values/strings.xml | 2 ++ 5 files changed, 16 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/helium314/keyboard/latin/voice/VoiceInputManager.kt b/app/src/main/java/helium314/keyboard/latin/voice/VoiceInputManager.kt index aa37ab8b62..62a42f20f2 100644 --- a/app/src/main/java/helium314/keyboard/latin/voice/VoiceInputManager.kt +++ b/app/src/main/java/helium314/keyboard/latin/voice/VoiceInputManager.kt @@ -1312,7 +1312,11 @@ class VoiceInputManager( fun seconds(millis: Long) = String.format(java.util.Locale.getDefault(), "%.1f", millis / 1000.0) val lines = mutableListOf() // which model, for comparing (not for cloud recognition) - if (!isCurrentSessionOnline) VoiceModelRegistry.installedWhisperName(ims.prefs())?.let { lines.add(ims.getString(R.string.voice_stats_model, it)) } + if (!isCurrentSessionOnline) { + val threads = ims.prefs().getString(VoiceConstants.PREF_VOICE_CPU_THREADS, "4")?.toIntOrNull() ?: 4 + val model = VoiceModelRegistry.installedWhisperLabel(ims, ims.prefs())?.let { ims.getString(R.string.voice_stats_model, it) } + lines.add(listOfNotNull(model, ims.getString(R.string.voice_stats_threads, threads)).joinToString(" · ")) + } lines.add(ims.getString(R.string.voice_stats_recording, seconds(stoppedAt - recordingStartedAt))) val lastSpeech = lastSpeechAt if (lastSpeech in recordingStartedAt..stoppedAt) diff --git a/app/src/main/java/helium314/keyboard/latin/voice/VoiceModelRegistry.kt b/app/src/main/java/helium314/keyboard/latin/voice/VoiceModelRegistry.kt index 5f0b69cb5f..5ea4a34dd2 100644 --- a/app/src/main/java/helium314/keyboard/latin/voice/VoiceModelRegistry.kt +++ b/app/src/main/java/helium314/keyboard/latin/voice/VoiceModelRegistry.kt @@ -27,6 +27,12 @@ object VoiceModelRegistry { return prefs.getString(PREF_IMPORTED_WHISPER_FILE, null) } + /** like [installedWhisperName], but a model imported before the name was stored gets a hint instead of nothing */ + fun installedWhisperLabel(context: android.content.Context, prefs: SharedPreferences): String? = + installedWhisperName(prefs) + ?: if (prefs.getString("installed_model_${VoiceConstants.ENGINE_WHISPER}", null) == "custom") + context.getString(helium314.keyboard.latin.R.string.voice_model_imported_unnamed) else null + val whisperModels = listOf( VoiceModelItem( id = "whisper-tiny.en-q5_1", diff --git a/app/src/main/java/helium314/keyboard/settings/screens/VoiceSettingsScreen.kt b/app/src/main/java/helium314/keyboard/settings/screens/VoiceSettingsScreen.kt index 7dd694aeb0..b3745d603b 100644 --- a/app/src/main/java/helium314/keyboard/settings/screens/VoiceSettingsScreen.kt +++ b/app/src/main/java/helium314/keyboard/settings/screens/VoiceSettingsScreen.kt @@ -812,7 +812,7 @@ fun VoiceSettingsScreen( Preference( name = stringResource(R.string.voice_manage_download_models), // which model is in use - description = if (whisperState != null) helium314.keyboard.latin.voice.VoiceModelRegistry.installedWhisperName(prefs) else null, + description = if (whisperState != null) helium314.keyboard.latin.voice.VoiceModelRegistry.installedWhisperLabel(context, prefs) else null, icon = R.drawable.sym_keyboard_voice_holo, onClick = { showModelDownloadDialog = true diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 34cfb5e078..400092f2f3 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1733,6 +1733,8 @@ Ermöglicht lokale GGUF / llama.cpp-Inferenz für Korrekturlesen und Umschreiben Nach jedem Diktat: Aufnahmezeit, Warten auf Stille nach dem letzten Wort, Erkennungszeit Modell %s Aufnahme %s s + %d Threads + Eigenes Modell (einmal neu importieren, dann steht hier der Name) Stille abgewartet nach dem letzten Wort %s s Erkennung nach der Aufnahme %s s Text da %s s nach dem letzten Wort diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 50bb49b5a8..df6cee6437 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -2490,6 +2490,8 @@ New dictionary: After each dictation: recording time, waiting for silence after the last word, recognition time Model %s Recording %s s + %d threads + Own model (import it again to show its name) waited for silence after the last word %s s recognition after the recording %s s text there %s s after the last word From 5154653e0f82f1617a48c45931c5dc8b1a34535b Mon Sep 17 00:00:00 2001 From: 4di-hello <4di-hello@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:43:44 +0100 Subject: [PATCH 4/9] Voice input: thread labels as measured with plugin 1.1.0, FUTO ACFT models recommended 8 threads are usually slower than 4 on the fast cores: every computation step waits for the slowest core. Co-Authored-By: Claude Opus 5.5 --- .../dialogs/VoiceModelDownloadDialog.kt | 19 ++++++++++++++----- app/src/main/res/values-de/strings.xml | 7 ++++--- app/src/main/res/values/strings.xml | 7 ++++--- 3 files changed, 22 insertions(+), 11 deletions(-) diff --git a/app/src/main/java/helium314/keyboard/settings/dialogs/VoiceModelDownloadDialog.kt b/app/src/main/java/helium314/keyboard/settings/dialogs/VoiceModelDownloadDialog.kt index 7831667c4e..3412724b27 100644 --- a/app/src/main/java/helium314/keyboard/settings/dialogs/VoiceModelDownloadDialog.kt +++ b/app/src/main/java/helium314/keyboard/settings/dialogs/VoiceModelDownloadDialog.kt @@ -117,14 +117,23 @@ fun VoiceModelDownloadDialog( horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { - Text( - text = stringResource(R.string.voice_futo_models_title), - style = MaterialTheme.typography.bodyMedium, - fontWeight = FontWeight.Medium, + Column( modifier = Modifier .weight(1f) .padding(end = 8.dp) - ) + ) { + Text( + text = stringResource(R.string.voice_futo_models_title), + style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.Medium + ) + // what worked best in our tests, so nobody has to try all models + Text( + text = stringResource(R.string.voice_futo_models_recommended), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.primary + ) + } OutlinedButton( onClick = { diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 400092f2f3..fe15c7b4c4 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1483,9 +1483,9 @@ Ermöglicht lokale GGUF / llama.cpp-Inferenz für Korrekturlesen und Umschreiben Leistung und Fortschritt CPU-Inferenzthreads 2 Threads (Batteriesparmodus) - 4 Threads (empfohlen) - 6 Threads (Hohe Leistung) - 8 Threads (maximale Geschwindigkeit) + 4 Threads (empfohlen: die schnellen Kerne) + 6 Threads + 8 Threads (alle Kerne, meist langsamer) Wortschatz- und Kontext-Eingabeaufforderung Guide Whisper mit Fachbegriffen, Namen, Slang oder Fachjargon Halten Sie Whisper geladen @@ -1727,6 +1727,7 @@ Ermöglicht lokale GGUF / llama.cpp-Inferenz für Korrekturlesen und Umschreiben Schlagen Sie Teilübereinstimmungen für Text- und Bildverknüpfungen ohne Präfix vor, nachdem Sie mehr als zwei Zeichen eingegeben haben (Verknüpfungen mit Präfix werden auch automatisch vervollständigt). Aufgeklappte Seitenpolsterung FUTO-Sprachmodelle (ACFT) + Empfohlen: in unseren Tests am schnellsten und genauesten (Deutsch, ein Handy), z. B. Multilingual-244: Text 1,5 s nach dem letzten Wort Durchsuchen Schon beim Sprechen erkennen Leistungsanzeige diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index df6cee6437..93c29db5d4 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -2400,9 +2400,9 @@ New dictionary: Performance & Advanced CPU Inference Threads 2 threads (Battery saver) - 4 threads (Recommended) - 6 threads (High performance) - 8 threads (Maximum speed) + 4 threads (recommended: the fast cores) + 6 threads + 8 threads (all cores, usually slower) Vocabulary & Context Prompt Guide Whisper with technical terms, names, slang, or jargon @@ -2419,6 +2419,7 @@ New dictionary: Model import failed: %s Multilingual FUTO Voice Models (ACFT) + Recommended: fastest and most accurate in our tests (German, one phone), e.g. Multilingual-244: text 1.5 s after the last word Browse From 6800925651fe0e83602380aa4ae936e043223b57 Mon Sep 17 00:00:00 2001 From: 4di-hello <4di-hello@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:54:06 +0100 Subject: [PATCH 5/9] Review: speed display only after a finished dictation, no offline info for cloud recognition, standard toast Co-Authored-By: Claude Opus 5.5 --- .../keyboard/latin/voice/VoiceInputManager.kt | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/helium314/keyboard/latin/voice/VoiceInputManager.kt b/app/src/main/java/helium314/keyboard/latin/voice/VoiceInputManager.kt index 62a42f20f2..53028a9400 100644 --- a/app/src/main/java/helium314/keyboard/latin/voice/VoiceInputManager.kt +++ b/app/src/main/java/helium314/keyboard/latin/voice/VoiceInputManager.kt @@ -130,6 +130,8 @@ class VoiceInputManager( @Volatile private var lastSpeechAt = 0L private var recordingStoppedAt = 0L private var piecesTranscribed = 0 + // whether the dictation for the speed display was cloud recognition (cleanupSession resets the flag before) + private var statsOnline = false private var needsCapitalStart = true private var sessionEmittedText = "" @@ -175,6 +177,11 @@ class VoiceInputManager( } // a new session must not let a later Retry resend older audio clearFailedAudio() + // no times of the previous dictation in the speed display + recordingStartedAt = 0L + lastSpeechAt = 0L + recordingStoppedAt = 0L + piecesTranscribed = 0 if (state != VoiceState.IDLE && state != VoiceState.ERROR) { Log.w(TAG, "Resetting previous state $state for new voice session") @@ -765,6 +772,7 @@ class VoiceInputManager( Log.i(TAG, "stopVoice() called, state=$state, isOnline=$isCurrentSessionOnline") if (state == VoiceState.RECORDING || state == VoiceState.STARTING_SESSION || state == VoiceState.CONNECTING_PLUGIN) { recordingStoppedAt = System.currentTimeMillis() + statsOnline = isCurrentSessionOnline updateState(VoiceState.PROCESSING_FINAL) scheduleProcessingTimeout() stopAudioLoop() @@ -784,6 +792,7 @@ class VoiceInputManager( if (pcmBytes.size < 3200) { // Less than 100ms of audio Log.i(TAG, "Online voice audio too short (${pcmBytes.size} bytes), skipping") + recordingStoppedAt = 0L cleanupSession() updateState(VoiceState.IDLE) return @@ -889,6 +898,7 @@ class VoiceInputManager( Log.i(TAG, "cancelVoice() called, state=$state, isOnline=$isCurrentSessionOnline") if (state != VoiceState.IDLE || isRecording.get() || audioThread != null || audioRecord != null) { val wasOffline = !isCurrentSessionOnline + recordingStoppedAt = 0L // cancelled: no speed display cleanupSession() pluginManager.cancelSession() clearComposingText() @@ -1034,6 +1044,7 @@ class VoiceInputManager( // say so instead of silently dropping it android.widget.Toast.makeText(ims, ims.getString(R.string.voice_piecewise_field_changed), android.widget.Toast.LENGTH_LONG).show() pendingPieces.clear() + recordingStoppedAt = 0L pluginManager.cancelSession() cleanupSession() updateState(VoiceState.IDLE) @@ -1312,7 +1323,7 @@ class VoiceInputManager( fun seconds(millis: Long) = String.format(java.util.Locale.getDefault(), "%.1f", millis / 1000.0) val lines = mutableListOf() // which model, for comparing (not for cloud recognition) - if (!isCurrentSessionOnline) { + if (!statsOnline) { val threads = ims.prefs().getString(VoiceConstants.PREF_VOICE_CPU_THREADS, "4")?.toIntOrNull() ?: 4 val model = VoiceModelRegistry.installedWhisperLabel(ims, ims.prefs())?.let { ims.getString(R.string.voice_stats_model, it) } lines.add(listOfNotNull(model, ims.getString(R.string.voice_stats_threads, threads)).joinToString(" · ")) @@ -1326,7 +1337,7 @@ class VoiceInputManager( lines.add(ims.getString(R.string.voice_stats_total, seconds(now - lastSpeech))) if (piecesTranscribed > 0) lines.add(ims.getString(R.string.voice_stats_pieces, piecesTranscribed)) val text = lines.joinToString("\n") - mainHandler.post { helium314.keyboard.keyboard.KeyboardSwitcher.getInstance().showLongToast(text, 6000) } + mainHandler.post { helium314.keyboard.keyboard.KeyboardSwitcher.getInstance().showToast(text, false) } } private fun notifyError(message: String, canRetry: Boolean = true) { From 7b45092727b324cd98ddc8647e5b5fd6e194a5ad Mon Sep 17 00:00:00 2001 From: 4di-hello <4di-hello@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:04:54 +0100 Subject: [PATCH 6/9] Voice input: the imported model's file name as safe display text It comes from whatever app provides the file: no control or direction characters, at most 80 characters. Co-Authored-By: Claude Opus 5.5 --- .../keyboard/latin/voice/VoiceModelRegistry.kt | 10 +++++++++- .../keyboard/settings/screens/VoiceSettingsScreen.kt | 2 +- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/helium314/keyboard/latin/voice/VoiceModelRegistry.kt b/app/src/main/java/helium314/keyboard/latin/voice/VoiceModelRegistry.kt index 5ea4a34dd2..d72cd5bc76 100644 --- a/app/src/main/java/helium314/keyboard/latin/voice/VoiceModelRegistry.kt +++ b/app/src/main/java/helium314/keyboard/latin/voice/VoiceModelRegistry.kt @@ -24,9 +24,17 @@ object VoiceModelRegistry { fun installedWhisperName(prefs: SharedPreferences): String? { val id = prefs.getString("installed_model_${VoiceConstants.ENGINE_WHISPER}", null) ?: return null whisperModels.firstOrNull { it.id == id }?.let { return it.displayName } - return prefs.getString(PREF_IMPORTED_WHISPER_FILE, null) + return prefs.getString(PREF_IMPORTED_WHISPER_FILE, null)?.let { cleanFileName(it) } } + /** + * A file name from the document picker as safe display text: it comes from whatever app provides the + * file, so no control or direction characters (they could reorder what is shown) and a sane length. + */ + fun cleanFileName(name: String): String? = name + .filter { val type = Character.getType(it); type != Character.CONTROL.toInt() && type != Character.FORMAT.toInt() } + .trim().take(80).ifEmpty { null } + /** like [installedWhisperName], but a model imported before the name was stored gets a hint instead of nothing */ fun installedWhisperLabel(context: android.content.Context, prefs: SharedPreferences): String? = installedWhisperName(prefs) diff --git a/app/src/main/java/helium314/keyboard/settings/screens/VoiceSettingsScreen.kt b/app/src/main/java/helium314/keyboard/settings/screens/VoiceSettingsScreen.kt index b3745d603b..c51e48d89d 100644 --- a/app/src/main/java/helium314/keyboard/settings/screens/VoiceSettingsScreen.kt +++ b/app/src/main/java/helium314/keyboard/settings/screens/VoiceSettingsScreen.kt @@ -271,7 +271,7 @@ fun VoiceSettingsScreen( context.contentResolver.query(uri, arrayOf(android.provider.OpenableColumns.DISPLAY_NAME), null, null, null)?.use { if (it.moveToFirst()) it.getString(0) else null } - } catch (_: Exception) { null } + } catch (_: Exception) { null }?.let { helium314.keyboard.latin.voice.VoiceModelRegistry.cleanFileName(it) } val request = ModelImportRequest( engineType = VoiceConstants.ENGINE_WHISPER, language = "multilingual", From 83d81786555fecd7b1b95f78bc9861db54af521a Mon Sep 17 00:00:00 2001 From: 4di-hello <4di-hello@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:14:59 +0100 Subject: [PATCH 7/9] Voice input: model file name cleaning by code points, also in the model dialog Only control characters, line/paragraph separators and direction controls are removed (joiners stay), cut between whole characters; the model dialog showed the stored name unfiltered. Co-Authored-By: Claude Opus 5.5 --- .../latin/voice/VoiceModelRegistry.kt | 19 +++++++++++++++---- .../dialogs/VoiceModelDownloadDialog.kt | 2 +- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/helium314/keyboard/latin/voice/VoiceModelRegistry.kt b/app/src/main/java/helium314/keyboard/latin/voice/VoiceModelRegistry.kt index d72cd5bc76..4e58b34964 100644 --- a/app/src/main/java/helium314/keyboard/latin/voice/VoiceModelRegistry.kt +++ b/app/src/main/java/helium314/keyboard/latin/voice/VoiceModelRegistry.kt @@ -29,11 +29,22 @@ object VoiceModelRegistry { /** * A file name from the document picker as safe display text: it comes from whatever app provides the - * file, so no control or direction characters (they could reorder what is shown) and a sane length. + * file, so no control characters, line breaks or direction overrides (they could reorder what is shown), + * and at most 80 characters, cut between whole characters. */ - fun cleanFileName(name: String): String? = name - .filter { val type = Character.getType(it); type != Character.CONTROL.toInt() && type != Character.FORMAT.toInt() } - .trim().take(80).ifEmpty { null } + fun cleanFileName(name: String): String? { + val sb = StringBuilder() + var i = 0 + while (i < name.length && sb.codePointCount(0, sb.length) < 80) { + val cp = name.codePointAt(i) + val type = Character.getType(cp) + val bidiControl = cp == 0x061C || cp == 0x200E || cp == 0x200F || cp in 0x202A..0x202E || cp in 0x2066..0x2069 + if (type != Character.CONTROL.toInt() && type != Character.LINE_SEPARATOR.toInt() && + type != Character.PARAGRAPH_SEPARATOR.toInt() && !bidiControl) sb.appendCodePoint(cp) + i += Character.charCount(cp) + } + return sb.toString().trim().ifEmpty { null } + } /** like [installedWhisperName], but a model imported before the name was stored gets a hint instead of nothing */ fun installedWhisperLabel(context: android.content.Context, prefs: SharedPreferences): String? = diff --git a/app/src/main/java/helium314/keyboard/settings/dialogs/VoiceModelDownloadDialog.kt b/app/src/main/java/helium314/keyboard/settings/dialogs/VoiceModelDownloadDialog.kt index 3412724b27..b69e376671 100644 --- a/app/src/main/java/helium314/keyboard/settings/dialogs/VoiceModelDownloadDialog.kt +++ b/app/src/main/java/helium314/keyboard/settings/dialogs/VoiceModelDownloadDialog.kt @@ -173,7 +173,7 @@ fun VoiceModelDownloadDialog( ) Text( text = if (isCustomWhisperInstalled) - listOfNotNull(stringResource(R.string.voice_imported_and_ready), prefs.getString(VoiceModelRegistry.PREF_IMPORTED_WHISPER_FILE, null)).joinToString(": ") + listOfNotNull(stringResource(R.string.voice_imported_and_ready), prefs.getString(VoiceModelRegistry.PREF_IMPORTED_WHISPER_FILE, null)?.let { VoiceModelRegistry.cleanFileName(it) }).joinToString(": ") else stringResource(R.string.voice_load_external_bin), style = MaterialTheme.typography.bodySmall, color = if (isCustomWhisperInstalled) From b01b6d17cabec5be6ba0041f1fe93fa931cf1771 Mon Sep 17 00:00:00 2001 From: 4di-hello <4di-hello@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:33:45 +0100 Subject: [PATCH 8/9] Voice input: model import waits for the plugin's result, timeout stops the plugin's recognition - Importing a model shows whether the plugin really has it ready, or why not (not a Whisper file, could not be loaded, plugin stopped during the import); the binding is kept until then, so Android does not end the plugin in the middle of a large import. Older plugins: as before - After the processing timeout the plugin's recognition is cancelled, so it does not hold up the next one - FUTO recommendation says fastest only: a larger model was more accurate in later tests Co-Authored-By: Claude Opus 5.5 --- .../keyboard/latin/voice/VoiceInputManager.kt | 2 + .../latin/voice/VoicePluginManager.kt | 84 +++++++++++++++++++ .../settings/screens/VoiceSettingsScreen.kt | 36 ++++++-- app/src/main/res/values-de/strings.xml | 10 ++- app/src/main/res/values/strings.xml | 10 ++- 5 files changed, 134 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/helium314/keyboard/latin/voice/VoiceInputManager.kt b/app/src/main/java/helium314/keyboard/latin/voice/VoiceInputManager.kt index 53028a9400..337cc43ab1 100644 --- a/app/src/main/java/helium314/keyboard/latin/voice/VoiceInputManager.kt +++ b/app/src/main/java/helium314/keyboard/latin/voice/VoiceInputManager.kt @@ -743,6 +743,8 @@ class VoiceInputManager( Log.w(TAG, "Voice processing timed out (${timeoutMs / 1000}s)") notifyError("Voice processing timed out") val wasOffline = !isCurrentSessionOnline + // stop the plugin's recognition too: it would hold up the next dictation + if (wasOffline) pluginManager.cancelSession() cleanupSession() updateState(VoiceState.ERROR) if (wasOffline) { diff --git a/app/src/main/java/helium314/keyboard/latin/voice/VoicePluginManager.kt b/app/src/main/java/helium314/keyboard/latin/voice/VoicePluginManager.kt index 17573f94a5..c743bb4c7f 100644 --- a/app/src/main/java/helium314/keyboard/latin/voice/VoicePluginManager.kt +++ b/app/src/main/java/helium314/keyboard/latin/voice/VoicePluginManager.kt @@ -361,6 +361,88 @@ class VoicePluginManager(private val context: Context) : IBinder.DeathRecipient } } + /** How an import ended, as far as the plugin tells */ + sealed class ImportResult { + object Ready : ImportResult() + data class Failed(val reason: String) : ImportResult() + /** the plugin process ended during the import: a crash or not enough memory */ + object PluginStopped : ImportResult() + object TimedOut : ImportResult() + object NotConnected : ImportResult() + /** an older plugin that does not report its imports: only the dispatch is known */ + object Unconfirmed : ImportResult() + } + + private data class ImportNote(val done: Int, val importing: Boolean, val failure: String?) + + /** The plugin (1.0.14-plus and later) adds "[imports=N; importing|last=ok|last=failed: reason]" to the state */ + private fun importNote(state: ModelState?): ImportNote? { + val match = IMPORT_NOTE.find(state?.message ?: return null) ?: return null + val status = match.groupValues[2] + return ImportNote( + done = match.groupValues[1].toIntOrNull() ?: return null, + importing = status == "importing", + failure = if (status.startsWith("last=failed")) match.groupValues[3] else null + ) + } + + /** + * Imports a model and waits until the plugin has copied and test-loaded it. The binding is kept + * meanwhile: unbound, Android may end the plugin in the middle of a large import. + */ + suspend fun importAndConfirm(request: ModelImportRequest): ImportResult = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { + val wasConnected = isPluginConnected() + val eng = getOrAwaitEngine() + if (eng == null) { + try { request.file.close() } catch (_: Exception) {} + if (!wasConnected) scheduleIdleUnbindAfterImport() + return@withContext ImportResult.NotConnected + } + val binder = eng.asBinder() + val before = try { importNote(eng.getModelState(VoiceConstants.ENGINE_WHISPER)) } catch (_: Exception) { null } + try { + eng.importModel(request) + } catch (e: DeadObjectException) { + Log.e(TAG, "Voice plugin service died in importModel", e) + handleDisconnection() + return@withContext ImportResult.PluginStopped + } catch (e: Exception) { + Log.e(TAG, "importModel failed", e) + if (!wasConnected) scheduleIdleUnbindAfterImport() + return@withContext ImportResult.NotConnected + } finally { + try { request.file.close() } catch (_: Exception) {} + } + if (before == null) { + scheduleIdleUnbindAfterImport() + return@withContext ImportResult.Unconfirmed + } + try { + val deadline = System.currentTimeMillis() + IMPORT_CONFIRM_TIMEOUT_MS + while (System.currentTimeMillis() < deadline) { + delay(1000L) + mainHandler.post { cancelScheduledUnbind() } + // another binder means the plugin was started anew: its process ended meanwhile + val current = engine + if (current == null || current.asBinder() !== binder) return@withContext ImportResult.PluginStopped + val note = try { + importNote(current.getModelState(VoiceConstants.ENGINE_WHISPER)) + } catch (e: DeadObjectException) { + handleDisconnection() + return@withContext ImportResult.PluginStopped + } catch (e: Exception) { + null + } ?: continue + if (note.importing || note.done <= before.done) continue + Log.i(TAG, "model import finished: ${if (note.failure == null) "ready" else "failed"}") + return@withContext if (note.failure == null) ImportResult.Ready else ImportResult.Failed(note.failure) + } + ImportResult.TimedOut + } finally { + scheduleIdleUnbindAfterImport() + } + } + fun unloadModel(engineType: String) { try { engine?.unloadModel(engineType) @@ -452,6 +534,8 @@ class VoicePluginManager(private val context: Context) : IBinder.DeathRecipient companion object { private const val TAG = "VoicePluginManager" private const val IMPORT_UNBIND_DELAY_MS = 30_000L + private const val IMPORT_CONFIRM_TIMEOUT_MS = 10 * 60_000L + private val IMPORT_NOTE = Regex("""\[imports=(\d+)(?:; (importing|last=ok|last=failed: ([^\]]*)))?]""") private const val UNBIND_RETRY_DELAY_MS = 15_000L } } diff --git a/app/src/main/java/helium314/keyboard/settings/screens/VoiceSettingsScreen.kt b/app/src/main/java/helium314/keyboard/settings/screens/VoiceSettingsScreen.kt index c51e48d89d..c8304fc50d 100644 --- a/app/src/main/java/helium314/keyboard/settings/screens/VoiceSettingsScreen.kt +++ b/app/src/main/java/helium314/keyboard/settings/screens/VoiceSettingsScreen.kt @@ -261,7 +261,8 @@ fun VoiceSettingsScreen( } val whisperPicker = filePicker { uri -> - scope.launch(Dispatchers.IO) { + // not tied to the screen: a large import keeps running (and is reported) when the screen is left + kotlinx.coroutines.CoroutineScope(Dispatchers.IO).launch { try { val pfd = context.contentResolver.openFileDescriptor(uri, "r") if (pfd != null) { @@ -279,16 +280,39 @@ fun VoiceSettingsScreen( sizeBytes = size, file = pfd ) - val success = pluginManager.bindAndImport(request) withContext(Dispatchers.Main) { - if (success) { + Toast.makeText(context, context.getString(R.string.voice_model_importing), Toast.LENGTH_SHORT).show() + } + // waits until the plugin has copied and test-loaded the model, so the outcome can be shown + val result = pluginManager.importAndConfirm(request) + withContext(Dispatchers.Main) { + val ready = result is helium314.keyboard.latin.voice.VoicePluginManager.ImportResult.Ready || + result is helium314.keyboard.latin.voice.VoicePluginManager.ImportResult.Unconfirmed + if (ready) { prefs.edit().putString("installed_model_${VoiceConstants.ENGINE_WHISPER}", "custom") .apply { if (fileName != null) putString(helium314.keyboard.latin.voice.VoiceModelRegistry.PREF_IMPORTED_WHISPER_FILE, fileName) else remove(helium314.keyboard.latin.voice.VoiceModelRegistry.PREF_IMPORTED_WHISPER_FILE) } .apply() - Toast.makeText(context, context.getString(R.string.voice_whisper_import_dispatched), Toast.LENGTH_SHORT).show() - } else { - Toast.makeText(context, context.getString(R.string.voice_plugin_import_failed), Toast.LENGTH_SHORT).show() } + val message = when (result) { + is helium314.keyboard.latin.voice.VoicePluginManager.ImportResult.Ready -> + context.getString(R.string.voice_model_import_ready, fileName ?: "") + is helium314.keyboard.latin.voice.VoicePluginManager.ImportResult.Unconfirmed -> + context.getString(R.string.voice_whisper_import_dispatched) + is helium314.keyboard.latin.voice.VoicePluginManager.ImportResult.Failed -> + context.getString(R.string.voice_model_import_failed_reason, when (result.reason) { + "not a Whisper model file" -> context.getString(R.string.voice_model_import_reason_not_whisper) + "the model could not be loaded" -> context.getString(R.string.voice_model_import_reason_load) + "copying the file failed" -> context.getString(R.string.voice_model_import_reason_copy) + else -> result.reason + }) + is helium314.keyboard.latin.voice.VoicePluginManager.ImportResult.PluginStopped -> + context.getString(R.string.voice_model_import_plugin_stopped) + is helium314.keyboard.latin.voice.VoicePluginManager.ImportResult.TimedOut -> + context.getString(R.string.voice_model_import_timeout) + is helium314.keyboard.latin.voice.VoicePluginManager.ImportResult.NotConnected -> + context.getString(R.string.voice_plugin_import_failed) + } + Toast.makeText(context, message, Toast.LENGTH_LONG).show() updatePluginStatus() } } diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index fe15c7b4c4..16d18a1430 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1496,6 +1496,14 @@ Ermöglicht lokale GGUF / llama.cpp-Inferenz für Korrekturlesen und Umschreiben Entladen Sie sich sofort nach der Sitzung KI-Anbieter und Sprachmodell Whisper-Modellimport versandt + Modell wird importiert … + Modell bereit: %s + Import fehlgeschlagen: %s. Das bisherige Modell bleibt. + keine Whisper-Modelldatei + das Modell ließ sich nicht laden + Kopieren der Datei fehlgeschlagen + Das Sprach-Plugin wurde beim Import beendet (Absturz oder zu wenig Speicher) + Der Import dauert sehr lange. Den Modellstatus später noch einmal prüfen Modellimport fehlgeschlagen:%s Mehrsprachig Vorschlagsleiste ausblenden @@ -1727,7 +1735,7 @@ Ermöglicht lokale GGUF / llama.cpp-Inferenz für Korrekturlesen und Umschreiben Schlagen Sie Teilübereinstimmungen für Text- und Bildverknüpfungen ohne Präfix vor, nachdem Sie mehr als zwei Zeichen eingegeben haben (Verknüpfungen mit Präfix werden auch automatisch vervollständigt). Aufgeklappte Seitenpolsterung FUTO-Sprachmodelle (ACFT) - Empfohlen: in unseren Tests am schnellsten und genauesten (Deutsch, ein Handy), z. B. Multilingual-244: Text 1,5 s nach dem letzten Wort + Empfohlen: in unseren Tests am schnellsten (Deutsch, ein Handy), z. B. Multilingual-244: Text 1,5 s nach dem letzten Wort Durchsuchen Schon beim Sprechen erkennen Leistungsanzeige diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 93c29db5d4..9d05140925 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -2416,10 +2416,18 @@ New dictionary: AI Provider & Voice Model Whisper model import dispatched + Importing the model… + Model ready: %s + Import failed: %s. The previous model stays. + not a Whisper model file + the model could not be loaded + copying the file failed + The voice plugin stopped during the import (crash or not enough memory) + The import is taking very long. Check the model state again later Model import failed: %s Multilingual FUTO Voice Models (ACFT) - Recommended: fastest and most accurate in our tests (German, one phone), e.g. Multilingual-244: text 1.5 s after the last word + Recommended: fastest in our tests (German, one phone), e.g. Multilingual-244: text 1.5 s after the last word Browse From 8fe6990511df81e4d832a26001d6a6542335012c Mon Sep 17 00:00:00 2001 From: 4di-hello <4di-hello@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:41:18 +0100 Subject: [PATCH 9/9] Voice import: binding kept when the settings screen unbinds, refused calls and queued imports handled - unbind() while an import waits for its result is deferred until the import has ended: leaving the screen or pressing Home no longer ends the wait with a wrong "plugin stopped" and no longer drops the binding in the middle of the import - A plugin that refuses the keyboard (SecurityException) is reported as not connected instead of being taken for an older plugin - If another import is still running in the plugin, the result of the one after it is awaited - Import note parsed more tolerantly; "Model ready" never shows an empty name Co-Authored-By: Claude Opus 5.5 --- .../latin/voice/VoicePluginManager.kt | 39 ++++++++++++++++--- .../settings/screens/VoiceSettingsScreen.kt | 2 +- 2 files changed, 34 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/helium314/keyboard/latin/voice/VoicePluginManager.kt b/app/src/main/java/helium314/keyboard/latin/voice/VoicePluginManager.kt index c743bb4c7f..feb4b7d79f 100644 --- a/app/src/main/java/helium314/keyboard/latin/voice/VoicePluginManager.kt +++ b/app/src/main/java/helium314/keyboard/latin/voice/VoicePluginManager.kt @@ -183,7 +183,16 @@ class VoicePluginManager(private val context: Context) : IBinder.DeathRecipient } } + /** Imports waiting for the plugin's result: the binding must stay until they end */ + private val importsWaiting = java.util.concurrent.atomic.AtomicInteger(0) + @Volatile private var unbindAfterImport = false + fun unbind() { + if (importsWaiting.get() > 0) { + // unbound now, Android may end the plugin in the middle of the import: unbind when it is done + unbindAfterImport = true + return + } cancelScheduledUnbind() setDictationPriority(false) if (isBound || isConnecting) { @@ -375,14 +384,14 @@ class VoicePluginManager(private val context: Context) : IBinder.DeathRecipient private data class ImportNote(val done: Int, val importing: Boolean, val failure: String?) - /** The plugin (1.0.14-plus and later) adds "[imports=N; importing|last=ok|last=failed: reason]" to the state */ + /** Plugins that report imports add "[imports=N; importing|last=ok|last=failed: reason]" to the state message */ private fun importNote(state: ModelState?): ImportNote? { val match = IMPORT_NOTE.find(state?.message ?: return null) ?: return null val status = match.groupValues[2] return ImportNote( done = match.groupValues[1].toIntOrNull() ?: return null, importing = status == "importing", - failure = if (status.startsWith("last=failed")) match.groupValues[3] else null + failure = if (status.startsWith("last=failed: ")) status.removePrefix("last=failed: ") else null ) } @@ -399,7 +408,17 @@ class VoicePluginManager(private val context: Context) : IBinder.DeathRecipient return@withContext ImportResult.NotConnected } val binder = eng.asBinder() - val before = try { importNote(eng.getModelState(VoiceConstants.ENGINE_WHISPER)) } catch (_: Exception) { null } + val before = try { + importNote(eng.getModelState(VoiceConstants.ENGINE_WHISPER)) + } catch (e: SecurityException) { + // the plugin refuses this keyboard (e.g. signed with another key): the import would be refused too + Log.e(TAG, "Voice plugin refused the call", e) + try { request.file.close() } catch (_: Exception) {} + if (!wasConnected) scheduleIdleUnbindAfterImport() + return@withContext ImportResult.NotConnected + } catch (_: Exception) { + null + } try { eng.importModel(request) } catch (e: DeadObjectException) { @@ -417,6 +436,9 @@ class VoicePluginManager(private val context: Context) : IBinder.DeathRecipient scheduleIdleUnbindAfterImport() return@withContext ImportResult.Unconfirmed } + // an import still running in the plugin finishes first: ours is the one after it + val target = before.done + if (before.importing) 2 else 1 + importsWaiting.incrementAndGet() try { val deadline = System.currentTimeMillis() + IMPORT_CONFIRM_TIMEOUT_MS while (System.currentTimeMillis() < deadline) { @@ -433,13 +455,18 @@ class VoicePluginManager(private val context: Context) : IBinder.DeathRecipient } catch (e: Exception) { null } ?: continue - if (note.importing || note.done <= before.done) continue + if (note.importing || note.done < target) continue Log.i(TAG, "model import finished: ${if (note.failure == null) "ready" else "failed"}") return@withContext if (note.failure == null) ImportResult.Ready else ImportResult.Failed(note.failure) } ImportResult.TimedOut } finally { - scheduleIdleUnbindAfterImport() + if (importsWaiting.decrementAndGet() == 0 && unbindAfterImport) { + unbindAfterImport = false + mainHandler.post { unbind() } + } else { + scheduleIdleUnbindAfterImport() + } } } @@ -535,7 +562,7 @@ class VoicePluginManager(private val context: Context) : IBinder.DeathRecipient private const val TAG = "VoicePluginManager" private const val IMPORT_UNBIND_DELAY_MS = 30_000L private const val IMPORT_CONFIRM_TIMEOUT_MS = 10 * 60_000L - private val IMPORT_NOTE = Regex("""\[imports=(\d+)(?:; (importing|last=ok|last=failed: ([^\]]*)))?]""") + private val IMPORT_NOTE = Regex("""\[imports=(\d+)(?:; ([^\]]*))?\]""") private const val UNBIND_RETRY_DELAY_MS = 15_000L } } diff --git a/app/src/main/java/helium314/keyboard/settings/screens/VoiceSettingsScreen.kt b/app/src/main/java/helium314/keyboard/settings/screens/VoiceSettingsScreen.kt index c8304fc50d..d9bf8f2302 100644 --- a/app/src/main/java/helium314/keyboard/settings/screens/VoiceSettingsScreen.kt +++ b/app/src/main/java/helium314/keyboard/settings/screens/VoiceSettingsScreen.kt @@ -295,7 +295,7 @@ fun VoiceSettingsScreen( } val message = when (result) { is helium314.keyboard.latin.voice.VoicePluginManager.ImportResult.Ready -> - context.getString(R.string.voice_model_import_ready, fileName ?: "") + context.getString(R.string.voice_model_import_ready, fileName ?: "Whisper") is helium314.keyboard.latin.voice.VoicePluginManager.ImportResult.Unconfirmed -> context.getString(R.string.voice_whisper_import_dispatched) is helium314.keyboard.latin.voice.VoicePluginManager.ImportResult.Failed ->