Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,12 @@ 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
// 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 = ""

Expand Down Expand Up @@ -171,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")
Expand Down Expand Up @@ -552,6 +563,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
Expand Down Expand Up @@ -612,6 +624,7 @@ class VoiceInputManager(
val isSpeech = rms > effectiveSpeechThreshold
if (isSpeech) {
lastSpeechTime = now
lastSpeechAt = now
hasSpoken = true
} else {
ambientNoiseRms = 0.95 * ambientNoiseRms + 0.05 * rms
Expand Down Expand Up @@ -730,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) {
Expand Down Expand Up @@ -758,6 +773,8 @@ 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()
statsOnline = isCurrentSessionOnline
updateState(VoiceState.PROCESSING_FINAL)
scheduleProcessingTimeout()
stopAudioLoop()
Expand All @@ -777,6 +794,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
Expand Down Expand Up @@ -882,6 +900,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()
Expand Down Expand Up @@ -1027,12 +1046,14 @@ 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)
return@post
}
val recognized = text.orEmpty().trim()
piecesTranscribed++
if (recognized.isNotEmpty()) {
syncRecognizedText(recognized, isFinal = true)
piecewiseContext = (piecewiseContext + " " + recognized).takeLast(PIECE_CONTEXT_CHARS * 2)
Expand Down Expand Up @@ -1279,6 +1300,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) }
Expand All @@ -1287,6 +1313,35 @@ 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<String>()
// which model, for comparing (not for cloud recognition)
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(" · "))
}
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)))
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().showToast(text, false) }
}

private fun notifyError(message: String, canRetry: Boolean = true) {
mainHandler.post {
listener?.onError(message, canRetry)
Expand Down
Original file line number Diff line number Diff line change
@@ -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(
Expand All @@ -16,6 +17,41 @@ 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)?.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 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? {
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? =
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",
Expand Down
111 changes: 111 additions & 0 deletions app/src/main/java/helium314/keyboard/latin/voice/VoicePluginManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -361,6 +370,106 @@ 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?)

/** 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: ")) status.removePrefix("last=failed: ") 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 (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) {
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
}
// 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) {
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 < 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 {
if (importsWaiting.decrementAndGet() == 0 && unbindAfterImport) {
unbindAfterImport = false
mainHandler.post { unbind() }
} else {
scheduleIdleUnbindAfterImport()
}
}
}

fun unloadModel(engineType: String) {
try {
engine?.unloadModel(engineType)
Expand Down Expand Up @@ -452,6 +561,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+)(?:; ([^\]]*))?\]""")
private const val UNBIND_RETRY_DELAY_MS = 15_000L
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -163,7 +172,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)?.let { VoiceModelRegistry.cleanFileName(it) }).joinToString(": ")
else stringResource(R.string.voice_load_external_bin),
style = MaterialTheme.typography.bodySmall,
color = if (isCustomWhisperInstalled)
MaterialTheme.colorScheme.primary
Expand All @@ -175,7 +186,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()
Expand Down
Loading
Loading