Skip to content

Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.

fix(speech): ask recognizers for their installed variant, fail fast (#122)

Durganshu14afeaf7de00
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 06c475e..b5e761a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,7 +23,10 @@ All notable changes to Gotcha are documented here.
Android 13 and later). On Android 12 and later, a
new "On-device only" switch keeps voice input off the network: if the phone
can't recognise the voice language on the device, voice input stops with a
- message instead of going online. When the phone has no voice for the voice
+ message instead of going online. On Android 13 and later Gotcha asks for the
+ variant of the language the phone has installed, so a phone with only Indian
+ English offline is asked for `en-IN`, not `en-US`. When a recognizer can't
+ take the language at all, voice input stops at once and says why. When the phone has no voice for the voice
language, Gotcha no longer reads the reply with an English voice: it stays
silent and says the voice is missing, without repeating it on every reply.
Settings → Language warns about all of these too.
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index 8b6fcbc..c947d47 100644
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -839,7 +839,11 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), C
return
}
sttEngine.configureAndroid(settings.androidSttService, settings.androidSttOnDeviceOnly)
- val started = sttEngine.startAndroidListening(settings.effectiveVoiceLanguage)
+ // A failure no retry fixes ends listening at once, with the reason.
+ val started = sttEngine.startAndroidListening(settings.effectiveVoiceLanguage) { reason ->
+ _uiState.update { it.copy(isListening = false) }
+ appendUi(MessageKind.ERROR, reason)
+ }
if (started) {
_uiState.update { it.copy(isListening = true) }
} else {
@@ -910,8 +914,6 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), C
}
provider == AudioProvider.ANDROID -> {
transcript = sttEngine.stopAndroidListening()
- val failure = sttEngine.androidFailure
- if (transcript.isBlank() && failure != null) appendUi(MessageKind.ERROR, failure)
}
}
diff --git a/app/src/main/java/com/gotcha/audio/AndroidSpeechInfo.kt b/app/src/main/java/com/gotcha/audio/AndroidSpeechInfo.kt
index 8da1c42..1251967 100644
--- a/app/src/main/java/com/gotcha/audio/AndroidSpeechInfo.kt
+++ b/app/src/main/java/com/gotcha/audio/AndroidSpeechInfo.kt
@@ -4,6 +4,8 @@ import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Build
+import android.os.Handler
+import android.os.Looper
import android.provider.Settings
import android.speech.RecognitionService
import android.speech.RecognitionSupport
@@ -33,6 +35,7 @@ object AndroidSpeechInfo {
/** Secure setting naming the default recognizer; not public API but readable. */
private const val DEFAULT_RECOGNIZER_SETTING = "voice_recognition_service"
private const val PROBE_TIMEOUT_MS = 5000L
+ private const val TAG_TIMEOUT_MS = 1500L
suspend fun probe(context: Context, query: AndroidSpeechQuery): AndroidSpeechStatus {
val tts = probeTts(context, query.ttsEngine, query.language)
@@ -250,6 +253,48 @@ object AndroidSpeechInfo {
}
}
+ /**
+ * Asks [recognizer] which variant of [language] it has installed on the
+ * phone, for [onResult] on the main thread: `en-IN` on a phone whose
+ * offline English is Indian, though [Language.bcp47] says `en-US`. Null
+ * before Android 13, when nothing is installed, or when the recognizer
+ * can't say; the caller then asks for [Language.bcp47]. Main thread only.
+ */
+ fun installedTag(context: Context, recognizer: SpeechRecognizer, language: Language, onResult: (String?) -> Unit) {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return onResult(null)
+ var answered = false
+ val answer = { tag: String? ->
+ if (!answered) {
+ answered = true
+ onResult(tag)
+ }
+ }
+ // Some recognizers never call back; listening must not wait on them.
+ Handler(Looper.getMainLooper()).postDelayed({ answer(null) }, TAG_TIMEOUT_MS)
+ val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
+ .putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
+ try {
+ recognizer.checkRecognitionSupport(
+ intent,
+ context.mainExecutor,
+ object : RecognitionSupportCallback {
+ override fun onSupportResult(support: RecognitionSupport) {
+ answer(pickInstalledTag(language, support.installedOnDeviceLanguages))
+ }
+
+ override fun onError(error: Int) = answer(null)
+ }
+ )
+ } catch (_: Exception) {
+ answer(null)
+ }
+ }
+
+ /** [language] as installed: its own tag when listed, else the first variant of it, else null. */
+ internal fun pickInstalledTag(language: Language, installed: List<String>): String? =
+ installed.firstOrNull { it.replace('_', '-').equals(language.bcp47, ignoreCase = true) }
+ ?: installed.firstOrNull(language::matchesCode)
+
/**
* The message for a recognizer [error] no retry will fix, or null. Without
* it the push-to-talk loop would restart the recognizer forever on a
diff --git a/app/src/main/java/com/gotcha/audio/SttEngine.kt b/app/src/main/java/com/gotcha/audio/SttEngine.kt
index 11b8fbb..b27490e 100644
--- a/app/src/main/java/com/gotcha/audio/SttEngine.kt
+++ b/app/src/main/java/com/gotcha/audio/SttEngine.kt
@@ -19,9 +19,11 @@ import com.gotcha.i18n.Language
import com.gotcha.util.GotchaLog
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import java.io.ByteArrayOutputStream
import java.io.File
+import kotlin.coroutines.resume
/** Result of a single hands-free listening turn ([SttEngine.listenOnceAndroid]). */
sealed class SttOutcome {
@@ -41,6 +43,7 @@ sealed class SttOutcome {
* - API provider: records audio via MediaRecorder, transcribes via API
* - Android provider: uses SpeechRecognizer (live recognition)
*/
+@Suppress("TooManyFunctions")
class SttEngine(
private val context: Context,
apiBaseUrl: String = "",
@@ -93,17 +96,66 @@ class SttEngine(
var androidFailure: String? = null
private set
+ /**
+ * Push-to-talk keeps its recognizer between sessions; set when
+ * [configureAndroid] changes the choice so the next session makes a new one.
+ */
+ @Volatile
+ private var recognizerStale = false
+
+ /** The language tag this push-to-talk session asks for, once known; see [listenWithInstalledTag]. */
+ private var sessionTag: String? = null
+
+ /** Told at once when this push-to-talk session fails for good; see [startAndroidListening]. */
+ private var sessionFailure: ((String) -> Unit)? = null
+
/** Choose Android Built-in's recognizer: [service] (blank = the phone's), or the on-device one. */
fun configureAndroid(service: String, onDeviceOnly: Boolean) {
+ if (service == androidService && onDeviceOnly == androidOnDeviceOnly) return
androidService = service
androidOnDeviceOnly = onDeviceOnly
+ recognizerStale = true
}
- /** The recognizer [configureAndroid] chose, or null with [androidFailure] set. Main thread only. */
- private fun createAndroidRecognizer(): SpeechRecognizer? {
- val recognizer = AndroidSpeechInfo.createRecognizer(context, androidService, androidOnDeviceOnly)
- if (recognizer == null) androidFailure = context.getString(R.string.stt_on_device_unavailable)
- return recognizer
+ /** The recognizer [configureAndroid] chose, or null when on-device recognition isn't there. Main thread only. */
+ private fun createAndroidRecognizer(): SpeechRecognizer? =
+ AndroidSpeechInfo.createRecognizer(context, androidService, androidOnDeviceOnly)
+
+ /**
+ * Start [recognizer] on the variant of [language] it has installed, so a
+ * phone whose offline English is Indian gets `en-IN` rather than the
+ * `en-US` it can't recognise (#122). Asks once per push-to-talk session;
+ * [start] runs on the main thread.
+ */
+ private fun listenWithInstalledTag(recognizer: SpeechRecognizer, language: Language, start: (String) -> Unit) {
+ sessionTag?.let { return start(it) }
+ AndroidSpeechInfo.installedTag(context, recognizer, language) { tag ->
+ val chosen = tag ?: language.bcp47
+ sessionTag = chosen
+ start(chosen)
+ }
+ }
+
+ /**
+ * End push-to-talk on a failure no retry will fix and say why now, not when
+ * the user next taps Stop: the mic would look like it was still listening.
+ * Main thread only.
+ */
+ private fun failSession(message: String) {
+ isContinuousListening = false
+ try {
+ currentRecognizer?.destroy()
+ } catch (_: Exception) {}
+ currentRecognizer = null
+ unmuteBeep()
+ listenGate?.complete(buildFinalTranscript())
+ val notify = sessionFailure
+ if (notify != null) {
+ androidFailure = null
+ notify(message)
+ } else {
+ androidFailure = message
+ }
}
/** The models available from the API (empty if provider is Android). */
@@ -296,10 +348,19 @@ class SttEngine(
// ---- Android STT (SpeechRecognizer) ----
- /** Start Android SpeechRecognizer. User speaks, then calls stopAndroidListening(). */
- fun startAndroidListening(language: Language = Language.ENGLISH): Boolean {
+ /**
+ * Start Android SpeechRecognizer. User speaks, then calls stopAndroidListening().
+ * [onFailure] hears at once, on the main thread, when the session fails in a
+ * way the user has to fix; without it the reason waits in [androidFailure].
+ */
+ fun startAndroidListening(
+ language: Language = Language.ENGLISH,
+ onFailure: ((String) -> Unit)? = null
+ ): Boolean {
if (isContinuousListening) return false
androidFailure = null
+ sessionFailure = onFailure
+ sessionTag = null
if (androidOnDeviceOnly && !AndroidSpeechInfo.hasOnDeviceRecognition(context)) {
androidFailure = context.getString(R.string.stt_on_device_unavailable)
return false
@@ -322,13 +383,18 @@ class SttEngine(
return
}
currentPartialResult = "" // Reset for new segment
+ if (recognizerStale) {
+ recognizerStale = false
+ try {
+ currentRecognizer?.destroy()
+ } catch (_: Exception) {}
+ currentRecognizer = null
+ }
var recognizer = currentRecognizer
if (recognizer == null) {
val newRec = createAndroidRecognizer()
if (newRec == null) {
- isContinuousListening = false
- unmuteBeep()
- listenGate?.complete(buildFinalTranscript())
+ failSession(context.getString(R.string.stt_on_device_unavailable))
return
}
currentRecognizer = newRec
@@ -343,9 +409,9 @@ class SttEngine(
override fun onEndOfSpeech() { GotchaLog.d(TAG) { "onEndOfSpeech" } }
override fun onError(error: Int) {
GotchaLog.d(TAG) { "onError: $error" }
- AndroidSpeechInfo.fatalError(context, error, currentLanguage, androidOnDeviceOnly)?.let { message ->
- androidFailure = message
- isContinuousListening = false
+ AndroidSpeechInfo.fatalError(context, error, currentLanguage, androidOnDeviceOnly)?.let {
+ failSession(it)
+ return
}
if (error == SpeechRecognizer.ERROR_CLIENT ||
error == SpeechRecognizer.ERROR_RECOGNIZER_BUSY ||
@@ -411,9 +477,17 @@ class SttEngine(
}
})
}
+ val active = recognizer ?: return
+ listenWithInstalledTag(active, currentLanguage) { tag ->
+ // Stopped, or replaced, while the recognizer was asked about its languages.
+ if (isContinuousListening && currentRecognizer === active) startCycle(active, tag)
+ }
+ }
+
+ private fun startCycle(recognizer: SpeechRecognizer, tag: String) {
val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
- putExtra(RecognizerIntent.EXTRA_LANGUAGE, currentLanguage.bcp47)
+ putExtra(RecognizerIntent.EXTRA_LANGUAGE, tag)
putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true)
// Prevent auto-stopping on pauses to mimic API-based continuous recording
@@ -427,7 +501,7 @@ class SttEngine(
}
try {
muteBeep()
- recognizer?.startListening(intent)
+ recognizer.startListening(intent)
} catch (_: Exception) {
unmuteBeep()
isContinuousListening = false
@@ -499,6 +573,7 @@ class SttEngine(
try {
val recognizer = createAndroidRecognizer()
if (recognizer == null) {
+ androidFailure = context.getString(R.string.stt_on_device_unavailable)
gate.complete(SttOutcome.Error(SpeechRecognizer.ERROR_CLIENT))
return@withContext
}
@@ -530,9 +605,12 @@ class SttEngine(
override fun onSegmentResults(segmentResults: Bundle) {}
override fun onEndOfSegmentedSession() {}
})
+ val tag = suspendCancellableCoroutine { cont ->
+ AndroidSpeechInfo.installedTag(context, recognizer, language) { if (cont.isActive) cont.resume(it) }
+ } ?: language.bcp47
val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
- putExtra(RecognizerIntent.EXTRA_LANGUAGE, language.bcp47)
+ putExtra(RecognizerIntent.EXTRA_LANGUAGE, tag)
// Best-effort end-of-speech hint; the platform may ignore it.
putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS, silenceTimeoutMs)
}
@@ -552,10 +630,17 @@ class SttEngine(
// ---- Provider-agnostic PTT ----
- /** Start listening with the current provider. Returns false on failure. */
- fun startListening(provider: AudioProvider, language: Language = Language.ENGLISH): Boolean {
+ /**
+ * Start listening with the current provider. Returns false on failure.
+ * [onAndroidFailure] is passed to [startAndroidListening].
+ */
+ fun startListening(
+ provider: AudioProvider,
+ language: Language = Language.ENGLISH,
+ onAndroidFailure: ((String) -> Unit)? = null
+ ): Boolean {
return when {
- provider == AudioProvider.ANDROID -> startAndroidListening(language)
+ provider == AudioProvider.ANDROID -> startAndroidListening(language, onAndroidFailure)
provider.isApiBased() -> startRecording()
else -> false
}
diff --git a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
index 3c535a3..ead116f 100644
--- a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
+++ b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
@@ -825,7 +825,12 @@ class AssistiveBallService : Service() {
screenCompanionPanel.setListening(false)
return
}
- if (sttEngine.startAndroidListening(s.effectiveVoiceLanguage)) {
+ val started = sttEngine.startAndroidListening(s.effectiveVoiceLanguage) { reason ->
+ panelVoiceActive = false
+ screenCompanionPanel.setListening(false)
+ overlay.showError(reason)
+ }
+ if (started) {
panelVoiceActive = true
} else {
overlay.showError(
diff --git a/app/src/main/java/com/gotcha/service/CallSessionController.kt b/app/src/main/java/com/gotcha/service/CallSessionController.kt
index 31de80f..574bde8 100644
--- a/app/src/main/java/com/gotcha/service/CallSessionController.kt
+++ b/app/src/main/java/com/gotcha/service/CallSessionController.kt
@@ -454,7 +454,14 @@ class CallSessionController(
sttEngine.configureAndroid(s.androidSttService, s.androidSttOnDeviceOnly)
val started = sttEngine.startListening(
s.sttProvider,
- currentLanguage()
+ currentLanguage(),
+ onAndroidFailure = { reason ->
+ // A failure no retry fixes: say so now and hand the mic back.
+ if (_state.value == CallState.LISTENING) {
+ _state.value = CallState.READY
+ reportError(reason)
+ }
+ }
)
if (started) {
_state.value = CallState.LISTENING
diff --git a/app/src/test/java/com/gotcha/audio/AndroidSpeechInfoTest.kt b/app/src/test/java/com/gotcha/audio/AndroidSpeechInfoTest.kt
index 17598b7..0227503 100644
--- a/app/src/test/java/com/gotcha/audio/AndroidSpeechInfoTest.kt
+++ b/app/src/test/java/com/gotcha/audio/AndroidSpeechInfoTest.kt
@@ -79,6 +79,14 @@ class AndroidSpeechInfoTest {
assertNull("empty lists say nothing", of())
}
+ @Test
+ fun `the installed variant of a language is picked, its own tag first`() {
+ assertEquals("en-US", AndroidSpeechInfo.pickInstalledTag(Language.ENGLISH, listOf("en-IN", "en-US")))
+ assertEquals("en-IN", AndroidSpeechInfo.pickInstalledTag(Language.ENGLISH, listOf("de-DE", "en-IN")))
+ assertEquals("pt_BR", AndroidSpeechInfo.pickInstalledTag(Language.PORTUGUESE, listOf("pt_BR")))
+ assertNull(AndroidSpeechInfo.pickInstalledTag(Language.RUSSIAN, listOf("en-IN")))
+ }
+
@Test
fun `an online-only recognizer doesn't count when on-device only is on`() {
val online = AndroidSpeechStatus(recognizerAvailability = SpeechAvailability.ONLINE)
diff --git a/app/src/test/java/com/gotcha/audio/SttEngineAndroidSessionTest.kt b/app/src/test/java/com/gotcha/audio/SttEngineAndroidSessionTest.kt
new file mode 100644
index 0000000..6e46042
--- /dev/null
+++ b/app/src/test/java/com/gotcha/audio/SttEngineAndroidSessionTest.kt
@@ -0,0 +1,98 @@
+package com.gotcha.audio
+
+import android.app.Application
+import android.os.Looper
+import android.speech.RecognitionSupport
+import android.speech.RecognizerIntent
+import android.speech.SpeechRecognizer
+import androidx.test.core.app.ApplicationProvider
+import com.gotcha.i18n.Language
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNotSame
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.Shadows.shadowOf
+import org.robolectric.annotation.Config
+import org.robolectric.shadows.ShadowSpeechRecognizer
+
+/** Android Built-in push-to-talk with the recognizer the user picked (#122). */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [34])
+class SttEngineAndroidSessionTest {
+
+ private val application: Application = ApplicationProvider.getApplicationContext()
+ private lateinit var stt: SttEngine
+
+ @Before
+ fun setUp() {
+ stt = SttEngine(application)
+ stt.configureAndroid(service = "", onDeviceOnly = false)
+ }
+
+ private fun idle() = shadowOf(Looper.getMainLooper()).idle()
+
+ private fun latest() = shadowOf(ShadowSpeechRecognizer.getLatestSpeechRecognizer())
+
+ private fun requestedTag() = latest().lastRecognizerIntent?.getStringExtra(RecognizerIntent.EXTRA_LANGUAGE)
+
+ private fun installed(vararg tags: String) =
+ RecognitionSupport.Builder().setInstalledOnDeviceLanguages(tags.toList()).build()
+
+ @Test
+ fun `the installed variant is asked for, not the default tag`() {
+ stt.startAndroidListening(Language.ENGLISH)
+ idle()
+ latest().triggerSupportResult(installed("en-IN"))
+ idle()
+
+ assertEquals("a phone with only Indian English must get en-IN", "en-IN", requestedTag())
+ }
+
+ @Test
+ fun `the default tag is used when the recognizer can't say`() {
+ stt.startAndroidListening(Language.ENGLISH)
+ idle()
+ latest().triggerSupportError(SpeechRecognizer.ERROR_CANNOT_CHECK_SUPPORT)
+ idle()
+
+ assertEquals("en-US", requestedTag())
+ }
+
+ @Test
+ fun `a language the recognizer lacks ends the session at once with the reason`() {
+ var reason: String? = null
+ stt.startAndroidListening(Language.RUSSIAN) { reason = it }
+ idle()
+ latest().triggerSupportResult(installed("en-IN"))
+ idle()
+ val recognizer = latest()
+
+ recognizer.triggerOnError(13) // ERROR_LANGUAGE_UNAVAILABLE
+ idle()
+
+ assertTrue(reason.orEmpty(), reason.orEmpty().contains("Russian"))
+ assertTrue("the failed recognizer is not kept for the next session", recognizer.isDestroyed)
+ assertNull("the reason went to the caller, not left for Stop", stt.androidFailure)
+ }
+
+ @Test
+ fun `a new recognizer choice takes effect on the next session`() {
+ stt.startAndroidListening(Language.ENGLISH)
+ idle()
+ latest().triggerSupportError(SpeechRecognizer.ERROR_CANNOT_CHECK_SUPPORT)
+ idle()
+ val first = ShadowSpeechRecognizer.getLatestSpeechRecognizer()
+ stt.cancelListening(AudioProvider.ANDROID)
+ idle()
+
+ stt.configureAndroid(service = "com.example/.Recognizer", onDeviceOnly = false)
+ stt.startAndroidListening(Language.ENGLISH)
+ idle()
+
+ assertNotSame(first, ShadowSpeechRecognizer.getLatestSpeechRecognizer())
+ }
+}