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.

feat(wake-word): replace Vosk with OpenWakeWord pipeline

Rishabh Bajpaid84d0a632ce0
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 089920e..cb8f878 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -367,9 +367,10 @@ dependencies {
implementation("androidx.camera:camera-lifecycle:$cameraxVersion")
implementation("androidx.camera:camera-view:$cameraxVersion")
- // Open-source, on-device speech recognition used for the optional wake word.
- // The acoustic model is supplied in app/src/main/assets (see docs/wake-word.md).
- implementation("com.alphacephei:vosk-android:0.3.47")
+ // On-device wake word ("Hey Gotcha") via OpenWakeWord ONNX models run with
+ // Microsoft's official ONNX Runtime. The three models live in
+ // app/src/main/assets/openwakeword (see docs/wake-word.md + docs/MODEL_CARD.md).
+ implementation("com.microsoft.onnxruntime:onnxruntime-android:1.26.0")
// Static analysis
detektPlugins("io.gitlab.arturbosch.detekt:detekt-formatting:1.23.6")
diff --git a/app/src/main/assets/licenses/openwakeword-notice.txt b/app/src/main/assets/licenses/openwakeword-notice.txt
new file mode 100644
index 0000000..2d97782
--- /dev/null
+++ b/app/src/main/assets/licenses/openwakeword-notice.txt
@@ -0,0 +1,30 @@
+OpenWakeWord Model Notices
+==========================
+
+This product includes wake-word detection models from the OpenWakeWord
+project (https://github.com/dscripka/openWakeWord).
+
+Models bundled in app/src/main/assets/openwakeword/
+---------------------------------------------
+
+ melspectrogram.onnx
+ Onnx export of the OpenWakeWord melspectrogram front-end.
+ Source: https://github.com/dscripka/openWakeWord (v0.5.1 release assets).
+ License: Apache License 2.0.
+
+ embedding_model.onnx
+ Re-implementation of Google's speech embedding model
+ (https://tfhub.dev/google/speech_embedding/1), as used by OpenWakeWord.
+ Source: https://github.com/dscripka/openWakeWord (v0.5.1 release assets).
+ License: Apache License 2.0.
+
+ hey_gotcha.onnx
+ Custom "Hey Gotcha" classifier head, trained by the Gotcha project on
+ synthetic positive clips (Piper TTS) and OpenWakeWord's standard
+ negative/background datasets (ACAV100M, AudioSet, MIT RIRs, FMA music).
+ Architecture: small fully-connected classifier on top of the frozen
+ speech embedding backbone.
+ License: Apache License 2.0. Trained by Gotcha contributors.
+
+The Apache 2.0 license text is available at:
+ https://www.apache.org/licenses/LICENSE-2.0
diff --git a/app/src/main/assets/openwakeword/embedding_model.onnx b/app/src/main/assets/openwakeword/embedding_model.onnx
new file mode 100644
index 0000000..afde53e
Binary files /dev/null and b/app/src/main/assets/openwakeword/embedding_model.onnx differ
diff --git a/app/src/main/assets/openwakeword/hey_gotcha.onnx b/app/src/main/assets/openwakeword/hey_gotcha.onnx
new file mode 100644
index 0000000..ab77dd5
Binary files /dev/null and b/app/src/main/assets/openwakeword/hey_gotcha.onnx differ
diff --git a/app/src/main/assets/openwakeword/melspectrogram.onnx b/app/src/main/assets/openwakeword/melspectrogram.onnx
new file mode 100644
index 0000000..a3a6035
Binary files /dev/null and b/app/src/main/assets/openwakeword/melspectrogram.onnx differ
diff --git a/app/src/main/assets/vosk-model-small-en-us-0.15/README b/app/src/main/assets/vosk-model-small-en-us-0.15/README
deleted file mode 100644
index a7f7931..0000000
--- a/app/src/main/assets/vosk-model-small-en-us-0.15/README
+++ /dev/null
@@ -1,9 +0,0 @@
-US English model for mobile Vosk applications
-
-Copyright 2020 Alpha Cephei Inc
-
-Accuracy: 10.38 (tedlium test) 9.85 (librispeech test-clean)
-Speed: 0.11xRT (desktop)
-Latency: 0.15s (right context)
-
-
diff --git a/app/src/main/assets/vosk-model-small-en-us-0.15/am/final.mdl b/app/src/main/assets/vosk-model-small-en-us-0.15/am/final.mdl
deleted file mode 100644
index 5596b31..0000000
Binary files a/app/src/main/assets/vosk-model-small-en-us-0.15/am/final.mdl and /dev/null differ
diff --git a/app/src/main/assets/vosk-model-small-en-us-0.15/conf/mfcc.conf b/app/src/main/assets/vosk-model-small-en-us-0.15/conf/mfcc.conf
deleted file mode 100644
index eaa40c5..0000000
--- a/app/src/main/assets/vosk-model-small-en-us-0.15/conf/mfcc.conf
+++ /dev/null
@@ -1,7 +0,0 @@
---sample-frequency=16000
---use-energy=false
---num-mel-bins=40
---num-ceps=40
---low-freq=20
---high-freq=7600
---allow-downsample=true
diff --git a/app/src/main/assets/vosk-model-small-en-us-0.15/conf/model.conf b/app/src/main/assets/vosk-model-small-en-us-0.15/conf/model.conf
deleted file mode 100644
index 9d5b0da..0000000
--- a/app/src/main/assets/vosk-model-small-en-us-0.15/conf/model.conf
+++ /dev/null
@@ -1,10 +0,0 @@
---min-active=200
---max-active=3000
---beam=10.0
---lattice-beam=2.0
---acoustic-scale=1.0
---frame-subsampling-factor=3
---endpoint.silence-phones=1:2:3:4:5:6:7:8:9:10
---endpoint.rule2.min-trailing-silence=0.5
---endpoint.rule3.min-trailing-silence=0.75
---endpoint.rule4.min-trailing-silence=1.0
diff --git a/app/src/main/assets/vosk-model-small-en-us-0.15/graph/Gr.fst b/app/src/main/assets/vosk-model-small-en-us-0.15/graph/Gr.fst
deleted file mode 100644
index 1f292e6..0000000
Binary files a/app/src/main/assets/vosk-model-small-en-us-0.15/graph/Gr.fst and /dev/null differ
diff --git a/app/src/main/assets/vosk-model-small-en-us-0.15/graph/HCLr.fst b/app/src/main/assets/vosk-model-small-en-us-0.15/graph/HCLr.fst
deleted file mode 100644
index 9797b26..0000000
Binary files a/app/src/main/assets/vosk-model-small-en-us-0.15/graph/HCLr.fst and /dev/null differ
diff --git a/app/src/main/assets/vosk-model-small-en-us-0.15/graph/disambig_tid.int b/app/src/main/assets/vosk-model-small-en-us-0.15/graph/disambig_tid.int
deleted file mode 100644
index 762fd5f..0000000
--- a/app/src/main/assets/vosk-model-small-en-us-0.15/graph/disambig_tid.int
+++ /dev/null
@@ -1,17 +0,0 @@
-10015
-10016
-10017
-10018
-10019
-10020
-10021
-10022
-10023
-10024
-10025
-10026
-10027
-10028
-10029
-10030
-10031
diff --git a/app/src/main/assets/vosk-model-small-en-us-0.15/graph/phones/word_boundary.int b/app/src/main/assets/vosk-model-small-en-us-0.15/graph/phones/word_boundary.int
deleted file mode 100644
index df23fd7..0000000
--- a/app/src/main/assets/vosk-model-small-en-us-0.15/graph/phones/word_boundary.int
+++ /dev/null
@@ -1,166 +0,0 @@
-1 nonword
-2 begin
-3 end
-4 internal
-5 singleton
-6 nonword
-7 begin
-8 end
-9 internal
-10 singleton
-11 begin
-12 end
-13 internal
-14 singleton
-15 begin
-16 end
-17 internal
-18 singleton
-19 begin
-20 end
-21 internal
-22 singleton
-23 begin
-24 end
-25 internal
-26 singleton
-27 begin
-28 end
-29 internal
-30 singleton
-31 begin
-32 end
-33 internal
-34 singleton
-35 begin
-36 end
-37 internal
-38 singleton
-39 begin
-40 end
-41 internal
-42 singleton
-43 begin
-44 end
-45 internal
-46 singleton
-47 begin
-48 end
-49 internal
-50 singleton
-51 begin
-52 end
-53 internal
-54 singleton
-55 begin
-56 end
-57 internal
-58 singleton
-59 begin
-60 end
-61 internal
-62 singleton
-63 begin
-64 end
-65 internal
-66 singleton
-67 begin
-68 end
-69 internal
-70 singleton
-71 begin
-72 end
-73 internal
-74 singleton
-75 begin
-76 end
-77 internal
-78 singleton
-79 begin
-80 end
-81 internal
-82 singleton
-83 begin
-84 end
-85 internal
-86 singleton
-87 begin
-88 end
-89 internal
-90 singleton
-91 begin
-92 end
-93 internal
-94 singleton
-95 begin
-96 end
-97 internal
-98 singleton
-99 begin
-100 end
-101 internal
-102 singleton
-103 begin
-104 end
-105 internal
-106 singleton
-107 begin
-108 end
-109 internal
-110 singleton
-111 begin
-112 end
-113 internal
-114 singleton
-115 begin
-116 end
-117 internal
-118 singleton
-119 begin
-120 end
-121 internal
-122 singleton
-123 begin
-124 end
-125 internal
-126 singleton
-127 begin
-128 end
-129 internal
-130 singleton
-131 begin
-132 end
-133 internal
-134 singleton
-135 begin
-136 end
-137 internal
-138 singleton
-139 begin
-140 end
-141 internal
-142 singleton
-143 begin
-144 end
-145 internal
-146 singleton
-147 begin
-148 end
-149 internal
-150 singleton
-151 begin
-152 end
-153 internal
-154 singleton
-155 begin
-156 end
-157 internal
-158 singleton
-159 begin
-160 end
-161 internal
-162 singleton
-163 begin
-164 end
-165 internal
-166 singleton
diff --git a/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/final.dubm b/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/final.dubm
deleted file mode 100644
index db789eb..0000000
Binary files a/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/final.dubm and /dev/null differ
diff --git a/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/final.ie b/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/final.ie
deleted file mode 100644
index 93737bf..0000000
Binary files a/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/final.ie and /dev/null differ
diff --git a/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/final.mat b/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/final.mat
deleted file mode 100644
index c3ec635..0000000
Binary files a/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/final.mat and /dev/null differ
diff --git a/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/global_cmvn.stats b/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/global_cmvn.stats
deleted file mode 100644
index b9d92ef..0000000
--- a/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/global_cmvn.stats
+++ /dev/null
@@ -1,3 +0,0 @@
- [
- 1.682383e+11 -1.1595e+10 -1.521733e+10 4.32034e+09 -2.257938e+10 -1.969666e+10 -2.559265e+10 -1.535687e+10 -1.276854e+10 -4.494483e+09 -1.209085e+10 -5.64008e+09 -1.134847e+10 -3.419512e+09 -1.079542e+10 -4.145463e+09 -6.637486e+09 -1.11318e+09 -3.479773e+09 -1.245932e+08 -1.386961e+09 6.560655e+07 -2.436518e+08 -4.032432e+07 4.620046e+08 -7.714964e+07 9.551484e+08 -4.119761e+08 8.208582e+08 -7.117156e+08 7.457703e+08 -4.3106e+08 1.202726e+09 2.904036e+08 1.231931e+09 3.629848e+08 6.366939e+08 -4.586172e+08 -5.267629e+08 -3.507819e+08 1.679838e+09
- 1.741141e+13 8.92488e+11 8.743834e+11 8.848896e+11 1.190313e+12 1.160279e+12 1.300066e+12 1.005678e+12 9.39335e+11 8.089614e+11 7.927041e+11 6.882427e+11 6.444235e+11 5.151451e+11 4.825723e+11 3.210106e+11 2.720254e+11 1.772539e+11 1.248102e+11 6.691599e+10 3.599804e+10 1.207574e+10 1.679301e+09 4.594778e+08 5.821614e+09 1.451758e+10 2.55803e+10 3.43277e+10 4.245286e+10 4.784859e+10 4.988591e+10 4.925451e+10 5.074584e+10 4.9557e+10 4.407876e+10 3.421443e+10 3.138606e+10 2.539716e+10 1.948134e+10 1.381167e+10 0 ]
diff --git a/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/online_cmvn.conf b/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/online_cmvn.conf
deleted file mode 100644
index 7748a4a..0000000
--- a/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/online_cmvn.conf
+++ /dev/null
@@ -1 +0,0 @@
-# configuration file for apply-cmvn-online, used in the script ../local/run_online_decoding.sh
diff --git a/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/splice.conf b/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/splice.conf
deleted file mode 100644
index 960cd2e..0000000
--- a/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/splice.conf
+++ /dev/null
@@ -1,2 +0,0 @@
---left-context=3
---right-context=3
diff --git a/app/src/main/java/com/gotcha/service/OnnxWakeWordPipeline.kt b/app/src/main/java/com/gotcha/service/OnnxWakeWordPipeline.kt
new file mode 100644
index 0000000..2105f58
--- /dev/null
+++ b/app/src/main/java/com/gotcha/service/OnnxWakeWordPipeline.kt
@@ -0,0 +1,218 @@
+package com.gotcha.service
+
+import ai.onnxruntime.OnnxTensor
+import ai.onnxruntime.OrtEnvironment
+import ai.onnxruntime.OrtSession
+import java.nio.FloatBuffer
+
+/**
+ * Runs the OpenWakeWord detection pipeline over a stream of 16 kHz PCM frames.
+ *
+ * Mirrors the reference streaming implementation in upstream `openWakeWord`
+ * (`openwakeword/model.py` + `openwakeword/utils.py`, Apache-2.0):
+ *
+ * 1. Audio is accumulated in 1280-sample (80 ms) frames.
+ * 2. `melspectrogram.onnx` is run on the most recent 1760 samples and its
+ * output is transformed with `spec / 10 + 2`.
+ * 3. `embedding_model.onnx` turns the latest 76 mel rows into one 96-dim
+ * speech embedding per frame.
+ * 4. `hey_gotcha.onnx` classifies the latest 16 embeddings and emits a score
+ * in [0, 1], which [WakeWordMatcher] turns into a single detection event.
+ *
+ * The first [WARMUP_FRAMES] scored frames are ignored so the feature buffers
+ * fill up before anything can be detected.
+ *
+ * All hot-path arrays are pre-allocated once and reused to keep this listener
+ * allocation-free at steady state (an always-on service cannot tolerate
+ * per-frame GC pressure).
+ */
+@Suppress("UNCHECKED_CAST")
+internal class OnnxWakeWordPipeline(
+ private val env: OrtEnvironment,
+ private val melSession: OrtSession,
+ private val embeddingSession: OrtSession,
+ private val classifierSession: OrtSession,
+ private val matcher: WakeWordMatcher
+) {
+ /** Ring buffer of the most recent raw PCM samples. Size caps at [MEL_WINDOW]. */
+ private val rawSamples = ShortArray(MEL_WINDOW)
+ private var rawStart = 0
+ private var rawCount = 0
+
+ /**
+ * Scratch buffer that holds the current feed's samples plus whatever was
+ * carried over from the previous feed. Bounded by
+ * [MEL_WINDOW] + [FRAME_SIZE], which is the worst case when [feed] is
+ * called with a full [FRAME_SIZE] shortly after a remainder was kept.
+ */
+ private val combined = ShortArray(MEL_WINDOW + FRAME_SIZE)
+ private var combinedLength = 0
+
+ /** Reused destination for each extracted 80 ms frame. */
+ private val frame = ShortArray(FRAME_SIZE)
+
+ private val melBuffer = ArrayDeque<FloatArray>()
+ private val featureBuffer = ArrayDeque<FloatArray>()
+
+ private var remainder = ShortArray(0)
+ private var scoredFrames = 0
+
+ init {
+ prefillFeatures()
+ }
+
+ fun reset() {
+ rawStart = 0
+ rawCount = 0
+ combinedLength = 0
+ remainder = ShortArray(0)
+ scoredFrames = 0
+ melBuffer.clear()
+ featureBuffer.clear()
+ matcher.reset()
+ prefillFeatures()
+ }
+
+ /** Feeds [count] PCM samples and returns true exactly once when the wake word fires. */
+ fun feed(samples: ShortArray, count: Int): Boolean {
+ var detected = false
+
+ // Concatenate remainder + new samples into the reusable combined buffer.
+ combinedLength = 0
+ if (remainder.isNotEmpty()) {
+ System.arraycopy(remainder, 0, combined, 0, remainder.size)
+ combinedLength = remainder.size
+ }
+ System.arraycopy(samples, 0, combined, combinedLength, count)
+ combinedLength += count
+
+ val fullFrames = combinedLength / FRAME_SIZE
+ var offset = 0
+ repeat(fullFrames) {
+ System.arraycopy(combined, offset, frame, 0, FRAME_SIZE)
+ offset += FRAME_SIZE
+ if (processFrame(frame)) detected = true
+ }
+ if (offset < combinedLength) {
+ val leftover = combinedLength - offset
+ // Reuse the remainder array's storage when it fits; otherwise
+ // allocate once here (rare — only after the very first feed).
+ if (remainder.size != leftover) remainder = ShortArray(leftover)
+ System.arraycopy(combined, offset, remainder, 0, leftover)
+ } else if (remainder.isNotEmpty()) {
+ remainder = ShortArray(0)
+ }
+ return detected
+ }
+
+ private fun processFrame(frame: ShortArray): Boolean {
+ // Append the frame to the raw ring buffer.
+ for (sample in frame) {
+ rawSamples[rawStart] = sample
+ rawStart = (rawStart + 1) % MEL_WINDOW
+ if (rawCount < MEL_WINDOW) rawCount++
+ }
+
+ if (!computeMel()) return false
+ if (!computeEmbedding()) return false
+ val score = classify() ?: return false
+
+ scoredFrames++
+ if (scoredFrames <= WARMUP_FRAMES) return false
+ return matcher.onScore(score)
+ }
+
+ private fun computeMel(): Boolean {
+ if (rawCount < FRAME_SIZE) return false
+
+ // Build the mel window from the ring buffer in chronological order.
+ // rawCount <= MEL_WINDOW; the oldest sample lives at rawStart
+ // (modulo the ring) once rawCount == MEL_WINDOW.
+ val length = rawCount.coerceAtMost(MEL_WINDOW)
+ val window = FloatArray(length)
+ val start = if (rawCount < MEL_WINDOW) {
+ 0
+ } else {
+ rawStart // when full, rawStart points at the oldest sample
+ }
+ for (i in 0 until length) {
+ window[i] = rawSamples[(start + i) % MEL_WINDOW].toFloat()
+ }
+
+ val tensor = OnnxTensor.createTensor(
+ env,
+ FloatBuffer.wrap(window),
+ longArrayOf(1L, window.size.toLong())
+ )
+ val rows = try {
+ melSession.run(mapOf(melSession.inputNames.first() to tensor)).use { result ->
+ (result.get(0).value as Array<Array<Array<FloatArray>>>)[0][0]
+ }
+ } finally {
+ tensor.close()
+ }
+ if (rows.isEmpty()) return false
+ for (row in rows) {
+ melBuffer.addLast(FloatArray(MEL_BINS) { row[it] / 10f + 2f })
+ }
+ while (melBuffer.size > MEL_BUFFER_MAX) melBuffer.removeFirst()
+ return true
+ }
+
+ private fun computeEmbedding(): Boolean {
+ if (melBuffer.size < MEL_EMBEDDING_WINDOW) return false
+ val mels = melBuffer.toList()
+ val x = Array(1) { Array(MEL_EMBEDDING_WINDOW) { Array(MEL_BINS) { FloatArray(1) } } }
+ val base = mels.size - MEL_EMBEDDING_WINDOW
+ for (k in 0 until MEL_EMBEDDING_WINDOW) {
+ val row = mels[base + k]
+ for (w in 0 until MEL_BINS) x[0][k][w][0] = row[w]
+ }
+
+ val tensor = OnnxTensor.createTensor(env, x)
+ val embedding = try {
+ embeddingSession.run(mapOf(embeddingSession.inputNames.first() to tensor)).use { result ->
+ (result.get(0).value as Array<Array<Array<FloatArray>>>)[0][0][0].copyOf()
+ }
+ } finally {
+ tensor.close()
+ }
+ featureBuffer.addLast(embedding)
+ while (featureBuffer.size > FEATURE_BUFFER_MAX) featureBuffer.removeFirst()
+ return true
+ }
+
+ private fun classify(): Float? {
+ if (featureBuffer.size < CLASSIFIER_FRAMES) return null
+ val features = featureBuffer.toList()
+ val x = Array(1) { Array(CLASSIFIER_FRAMES) { FloatArray(FEATURE_DIM) } }
+ val base = features.size - CLASSIFIER_FRAMES
+ for (k in 0 until CLASSIFIER_FRAMES) x[0][k] = features[base + k]
+
+ val tensor = OnnxTensor.createTensor(env, x)
+ return try {
+ classifierSession.run(mapOf(classifierSession.inputNames.first() to tensor)).use { result ->
+ (result.get(0).value as Array<FloatArray>)[0][0]
+ }
+ } finally {
+ tensor.close()
+ }
+ }
+
+ private fun prefillFeatures() {
+ repeat(CLASSIFIER_FRAMES) { featureBuffer.addLast(FloatArray(FEATURE_DIM)) }
+ }
+
+ companion object {
+ const val SAMPLE_RATE = 16_000
+ const val FRAME_SIZE = 1280
+ const val MEL_WINDOW = 1760
+ const val MEL_BINS = 32
+ const val MEL_EMBEDDING_WINDOW = 76
+ const val FEATURE_DIM = 96
+ const val CLASSIFIER_FRAMES = 16
+ private const val WARMUP_FRAMES = 5
+ private const val MEL_BUFFER_MAX = 120
+ private const val FEATURE_BUFFER_MAX = 32
+ }
+}
diff --git a/app/src/main/java/com/gotcha/service/WakeWordDetector.kt b/app/src/main/java/com/gotcha/service/WakeWordDetector.kt
index 27d0b6a..a6e84c3 100644
--- a/app/src/main/java/com/gotcha/service/WakeWordDetector.kt
+++ b/app/src/main/java/com/gotcha/service/WakeWordDetector.kt
@@ -1,6 +1,9 @@
package com.gotcha.service
+import ai.onnxruntime.OrtEnvironment
+import ai.onnxruntime.OrtSession
import android.Manifest
+import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.media.AudioFormat
@@ -8,24 +11,20 @@ import android.media.AudioRecord
import android.media.MediaRecorder
import android.util.Log
import androidx.core.content.ContextCompat
-import com.gotcha.BuildConfig
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
-import org.json.JSONObject
-import org.vosk.Model
-import org.vosk.Recognizer
-import java.io.File
import java.io.IOException
import java.util.concurrent.atomic.AtomicBoolean
/**
- * On-device Vosk keyword listener. It owns the microphone only while running.
+ * On-device "Hey Gotcha" keyword listener backed by OpenWakeWord ONNX models.
+ * It owns the microphone only while running.
*
- * The model is loaded and the bundled assets are extracted on an IO coroutine:
- * the small model is tens of megabytes, so doing either on the service's main
- * thread would show up as a ball-service freeze right after boot.
+ * The three ONNX models are read from assets and loaded on an IO coroutine —
+ * model load takes tens of milliseconds, so doing it on the service's main
+ * thread would show up as a ball-service freeze right after start.
*/
class WakeWordDetector(
context: Context,
@@ -34,17 +33,18 @@ class WakeWordDetector(
private val onStarted: () -> Unit = {},
private val onDetected: () -> Unit,
private val onError: (String) -> Unit = {},
- private val modelAssetPath: String = MODEL_ASSET_PATH,
- private val phrase: String = WAKE_PHRASE
+ private val modelAssetDir: String = MODEL_ASSET_DIR,
+ private val classifierModel: String = CLASSIFIER_MODEL
) {
private val appContext = context.applicationContext
private val stateLock = Any()
private val running = AtomicBoolean(false)
private var job: Job? = null
private var recorder: AudioRecord? = null
- private var model: Model? = null
- private var recognizer: Recognizer? = null
- private var matcher = WakeWordMatcher(phrase, DEFAULT_SENSITIVITY)
+ private var melSession: OrtSession? = null
+ private var embeddingSession: OrtSession? = null
+ private var classifierSession: OrtSession? = null
+ private var matcher = WakeWordMatcher(WakeWordMatcher.DEFAULT_SENSITIVITY)
private var generation = 0
@Volatile
@@ -63,7 +63,7 @@ class WakeWordDetector(
if (running.get()) return true
lastError = null
generation++
- matcher = WakeWordMatcher(phrase, sensitivityProvider().coerceIn(0f, 1f))
+ matcher = WakeWordMatcher(sensitivityProvider().coerceIn(0f, 1f))
running.set(true)
val startGeneration = generation
job = scope.launch(Dispatchers.IO) { initializeAndListen(startGeneration) }
@@ -73,20 +73,23 @@ class WakeWordDetector(
fun stop() {
val oldRecorder: AudioRecord?
- val oldRecognizer: Recognizer?
- val oldModel: Model?
+ val oldMel: OrtSession?
+ val oldEmbedding: OrtSession?
+ val oldClassifier: OrtSession?
val oldJob: Job?
synchronized(stateLock) {
running.set(false)
generation++
matcher.reset()
oldRecorder = recorder
- oldRecognizer = recognizer
- oldModel = model
+ oldMel = melSession
+ oldEmbedding = embeddingSession
+ oldClassifier = classifierSession
oldJob = job
recorder = null
- recognizer = null
- model = null
+ melSession = null
+ embeddingSession = null
+ classifierSession = null
job = null
}
oldRecorder?.let {
@@ -97,29 +100,31 @@ class WakeWordDetector(
}
it.release()
}
- oldRecognizer?.close()
- oldModel?.close()
+ closeSessions(oldMel, oldEmbedding, oldClassifier)
oldJob?.cancel()
}
fun isRunning(): Boolean = running.get()
- private suspend fun initializeAndListen() {
- var createdModel: Model? = null
- var createdRecognizer: Recognizer? = null
+ @SuppressLint("MissingPermission")
+ private suspend fun initializeAndListen(generation: Int) {
+ val env = OrtEnvironment.getEnvironment()
+ var createdMel: OrtSession? = null
+ var createdEmbedding: OrtSession? = null
+ var createdClassifier: OrtSession? = null
var createdRecorder: AudioRecord? = null
try {
- val modelDir = copyModelToCache()
- createdModel = Model(modelDir.absolutePath)
- createdRecognizer = Recognizer(createdModel, SAMPLE_RATE, KEYWORD_GRAMMAR)
+ createdMel = loadSession(env, "$modelAssetDir/melspectrogram.onnx")
+ createdEmbedding = loadSession(env, "$modelAssetDir/embedding_model.onnx")
+ createdClassifier = loadSession(env, "$modelAssetDir/$classifierModel")
val bufferSize = AudioRecord.getMinBufferSize(
- SAMPLE_RATE.toInt(),
+ OnnxWakeWordPipeline.SAMPLE_RATE,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT
- ).coerceAtLeast(MIN_BUFFER_BYTES)
+ ).coerceAtLeast(OnnxWakeWordPipeline.FRAME_SIZE * 2)
createdRecorder = AudioRecord(
MediaRecorder.AudioSource.VOICE_RECOGNITION,
- SAMPLE_RATE.toInt(),
+ OnnxWakeWordPipeline.SAMPLE_RATE,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
bufferSize
@@ -129,28 +134,57 @@ class WakeWordDetector(
}
synchronized(stateLock) {
- if (!running.get()) {
- closeResources(createdRecorder, createdRecognizer, createdModel)
+ if (!running.get() || generation != this.generation) {
+ closeSessions(createdMel, createdEmbedding, createdClassifier)
+ createdRecorder.release()
return
}
- model = createdModel
- recognizer = createdRecognizer
+ melSession = createdMel
+ embeddingSession = createdEmbedding
+ classifierSession = createdClassifier
recorder = createdRecorder
}
scope.launch(Dispatchers.Main) { onStarted() }
- listen(createdRecorder, createdRecognizer, bufferSize)
+ listen(
+ generation = generation,
+ env = env,
+ localRecorder = createdRecorder,
+ localMel = createdMel,
+ localEmbedding = createdEmbedding,
+ localClassifier = createdClassifier
+ )
} catch (e: Exception) {
- closeResources(createdRecorder, createdRecognizer, createdModel)
- fail(startupError(e), e)
+ closeSessions(createdMel, createdEmbedding, createdClassifier)
+ createdRecorder?.release()
+ fail(startupError(e), e, generation)
}
}
- private fun listen(localRecorder: AudioRecord, localRecognizer: Recognizer, bufferSize: Int) {
- val buffer = ByteArray(bufferSize)
+ private fun loadSession(env: OrtEnvironment, assetPath: String): OrtSession {
+ val bytes = appContext.assets.open(assetPath).use { it.readBytes() }
+ return env.createSession(bytes)
+ }
+
+ private fun listen(
+ generation: Int,
+ env: OrtEnvironment,
+ localRecorder: AudioRecord,
+ localMel: OrtSession,
+ localEmbedding: OrtSession,
+ localClassifier: OrtSession
+ ) {
+ val frame = ShortArray(OnnxWakeWordPipeline.FRAME_SIZE)
+ val pipeline = OnnxWakeWordPipeline(
+ env = env,
+ melSession = localMel,
+ embeddingSession = localEmbedding,
+ classifierSession = localClassifier,
+ matcher = matcher
+ )
try {
localRecorder.startRecording()
while (running.get()) {
- val count = localRecorder.read(buffer, 0, buffer.size)
+ val count = localRecorder.read(frame, 0, frame.size)
if (count < 0) {
if (running.get()) throw IOException("AudioRecord read failed: $count")
return
@@ -159,14 +193,13 @@ class WakeWordDetector(
var detected = false
synchronized(stateLock) {
- if (!running.get() || recorder !== localRecorder || recognizer !== localRecognizer) {
+ if (!running.get() || recorder !== localRecorder || generation != this.generation) {
return
}
- val isFinal = localRecognizer.acceptWaveForm(buffer, count)
- val json = if (isFinal) localRecognizer.result else localRecognizer.partialResult
- val text = JSONObject(json).optString(if (isFinal) "text" else "partial")
- detected = if (isFinal) matcher.onFinal(text) else matcher.onPartial(text)
- if (detected) running.set(false)
+ if (pipeline.feed(frame, count)) {
+ detected = true
+ running.set(false)
+ }
}
if (detected) {
scope.launch(Dispatchers.Main) { onDetected() }
@@ -174,11 +207,14 @@ class WakeWordDetector(
}
}
} catch (e: Exception) {
- if (running.get()) fail("Wake word listening stopped unexpectedly.", e)
+ if (running.get()) fail("Wake word listening stopped unexpectedly.", e, generation)
}
}
- private fun fail(message: String, cause: Exception? = null) {
+ private fun fail(message: String, cause: Exception? = null, generation: Int) {
+ synchronized(stateLock) {
+ if (generation != this.generation) return
+ }
lastError = message
if (cause != null) Log.w(TAG, message, cause)
stop()
@@ -191,54 +227,16 @@ class WakeWordDetector(
else -> "Wake word could not start."
}
- private fun closeResources(
- oldRecorder: AudioRecord?,
- oldRecognizer: Recognizer?,
- oldModel: Model?
- ) {
- oldRecorder?.release()
- oldRecognizer?.close()
- oldModel?.close()
- }
-
- private fun copyModelToCache(): File {
- val root = File(appContext.cacheDir, "wake-word")
- val versionedRoot = File(root, BuildConfig.VERSION_CODE.toString())
- val destination = File(versionedRoot, modelAssetPath)
- if (File(destination, MODEL_READY_MARKER).isFile) return destination
-
- destination.deleteRecursively()
- copyAssetTree(modelAssetPath, destination)
- File(destination, MODEL_READY_MARKER).writeText("ok")
-
- // Old app versions may carry their own extracted copy. They are pure cache.
- root.listFiles()?.forEach { child ->
- if (child != versionedRoot) child.deleteRecursively()
- }
- return destination
- }
-
- private fun copyAssetTree(assetPath: String, destination: File) {
- val entries = appContext.assets.list(assetPath).orEmpty()
- if (entries.isEmpty()) {
- destination.parentFile?.mkdirs()
- appContext.assets.open(assetPath).use { input ->
- destination.outputStream().use { output -> input.copyTo(output) }
- }
- } else {
- destination.mkdirs()
- entries.forEach { entry -> copyAssetTree("$assetPath/$entry", File(destination, entry)) }
- }
+ private fun closeSessions(mel: OrtSession?, embedding: OrtSession?, classifier: OrtSession?) {
+ mel?.close()
+ embedding?.close()
+ classifier?.close()
}
companion object {
- const val WAKE_PHRASE = "gotcha"
- const val MODEL_ASSET_PATH = "vosk-model-small-en-us-0.15"
- const val DEFAULT_SENSITIVITY = 0.75f
- private const val SAMPLE_RATE = 16_000f
- private const val MIN_BUFFER_BYTES = 8_000
- private const val MODEL_READY_MARKER = ".ready"
- private const val KEYWORD_GRAMMAR = "[\"gotcha\", \"[unk]\"]"
+ const val WAKE_PHRASE = "hey gotcha"
+ const val MODEL_ASSET_DIR = "openwakeword"
+ const val CLASSIFIER_MODEL = "hey_gotcha.onnx"
private const val TAG = "WakeWordDetector"
}
}
diff --git a/app/src/main/java/com/gotcha/service/WakeWordMatcher.kt b/app/src/main/java/com/gotcha/service/WakeWordMatcher.kt
index b2a1d11..b1a2e73 100644
--- a/app/src/main/java/com/gotcha/service/WakeWordMatcher.kt
+++ b/app/src/main/java/com/gotcha/service/WakeWordMatcher.kt
@@ -1,55 +1,54 @@
package com.gotcha.service
/**
- * Converts a stream of Vosk partial/final transcripts into one wake-word event.
+ * Converts the OpenWakeWord classifier score stream into one wake-word event.
*
- * Vosk has no Porcupine-style sensitivity knob, so sensitivity controls how
- * many consecutive recognition updates must contain the phrase. The grammar is
- * already constrained to the wake word and `[unk]`; this streak check is the
- * second layer against a single noisy partial firing a call.
+ * The "Hey Gotcha" model card (docs/MODEL_CARD.md) recommends a threshold of
+ * 0.50 for balanced behavior, 0.65 for high precision and 0.35 for high
+ * sensitivity. The sensitivity slider is mapped onto that range:
+ *
+ * threshold = 0.70 - 0.27 * sensitivity (clamped to [0.10, 0.90])
+ *
+ * so the default sensitivity of 0.75 lands on 0.50. A single 80 ms frame above
+ * the threshold is not enough to trust — [PATIENCE] consecutive qualifying
+ * frames are required, which rejects the occasional one-frame spike without
+ * adding meaningful latency.
*/
internal class WakeWordMatcher(
- private val phrase: String,
sensitivity: Float
) {
- private val requiredConsecutiveMatches = when {
- sensitivity >= HIGH_SENSITIVITY -> 1
- sensitivity >= MEDIUM_SENSITIVITY -> 2
- else -> 3
- }
+ private val threshold: Float = (BASE_THRESHOLD - SENSITIVITY_RANGE * sensitivity.coerceIn(0f, 1f))
+ .coerceIn(MIN_THRESHOLD, MAX_THRESHOLD)
private var consecutiveMatches = 0
- fun onPartial(text: String): Boolean = accept(text)
-
- fun onFinal(text: String): Boolean = accept(text)
-
- fun reset() {
- consecutiveMatches = 0
- }
+ fun threshold(): Float = threshold
- private fun accept(text: String): Boolean {
- if (!containsPhrase(text, phrase)) {
+ fun onScore(score: Float): Boolean {
+ if (score < threshold) {
consecutiveMatches = 0
return false
}
consecutiveMatches++
- if (consecutiveMatches < requiredConsecutiveMatches) return false
- reset()
+ if (consecutiveMatches < PATIENCE) return false
+ consecutiveMatches = 0
return true
}
+ fun reset() {
+ consecutiveMatches = 0
+ }
+
companion object {
- private const val MEDIUM_SENSITIVITY = 0.40f
- private const val HIGH_SENSITIVITY = 0.75f
- private val NON_WORD = Regex("[^a-z0-9]+")
+ /** Balanced threshold from the model card at the default sensitivity. */
+ const val DEFAULT_SENSITIVITY = 0.75f
+ private const val BASE_THRESHOLD = 0.70f
+ private const val SENSITIVITY_RANGE = 0.27f
+ private const val MIN_THRESHOLD = 0.10f
+ private const val MAX_THRESHOLD = 0.90f
- /** Exact-token match, so "gotcha" does not fire inside another word. */
- fun containsPhrase(text: String, phrase: String): Boolean {
- val wanted = phrase.lowercase().trim()
- if (wanted.isEmpty()) return false
- return text.lowercase()
- .split(NON_WORD)
- .any { it == wanted }
- }
+ // 2 frames × 80 ms = 160 ms: enough to reject a one-frame audio spike,
+ // small enough to feel snappy. The Python reference also uses short
+ // patience when callers pass it explicitly.
+ private const val PATIENCE = 2
}
}