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.
docs(wake-word): document OpenWakeWord swap and bump legal version
Rishabh Bajpaid84ff171caeb
diff --git a/app/src/main/assets/legal/privacy-data-retention.md b/app/src/main/assets/legal/privacy-data-retention.mdindex 035fb64..0b359e6 100644--- a/app/src/main/assets/legal/privacy-data-retention.md+++ b/app/src/main/assets/legal/privacy-data-retention.md@@ -144,4 +144,39 @@ backend that transmits data to a third-party AI provider.9.1 Questions about this policy can be sent to [email protected].+10. OPTIONAL WAKE WORD ("Hey Gotcha")++ 10.1 The wake-word feature is opt-in. When turned on in Settings+ (Settings → Assistive Ball → "Wake word: Hey Gotcha"), the App keeps a+ microphone-type foreground service alive while the Assistive Ball is on+ and no voice call is in progress.++ 10.2 The wake-word listener processes all microphone audio **on-device**+ using the bundled OpenWakeWord models (Apache 2.0, see+ `app/src/main/assets/licenses/openwakeword-notice.txt`). Audio frames+ are fed to the OpenWakeWord pipeline to decide whether the phrase+ "Hey Gotcha" was spoken. No wake-word audio leaves the device — it is+ never sent to the App's servers, to the configured STT provider, or+ to any third party.++ 10.3 The App's own text-to-speech (e.g. reading on-screen text aloud, or+ narrating replies inside a call) can sound similar to the wake word.+ To prevent the listener from triggering a call on the App's own+ speech, the wake-word detector is paused automatically while the+ App's text-to-speech is playing.++ 10.4 A wake-word-triggered call ends itself after the spoken reply+ finishes (so the assistant can answer the wake-word command and+ then go back to listening for the next activation). This+ self-terminating behaviour is local; the App still does not stream+ the wake-word audio anywhere.++ 10.5 For the wake-word listener to remain reliable while the screen is+ off or the device is dozing, the App may ask you to exempt it from+ Android battery optimization. That exemption is voluntary and can+ be revoked at any time through Android Settings.++ 10.6 You can turn the wake-word feature off at any time; when off, the+ App does not retain or process any audio for wake-word purposes.+— END OF DATA RETENTION POLICY —diff --git a/app/src/main/java/com/gotcha/data/SettingsRepository.kt b/app/src/main/java/com/gotcha/data/SettingsRepository.ktindex 8d51d14..883f707 100644--- a/app/src/main/java/com/gotcha/data/SettingsRepository.kt+++ b/app/src/main/java/com/gotcha/data/SettingsRepository.kt@@ -550,4 +550,4 @@ class SettingsRepository(context: Context) {* constant, so non-material edits (typo fixes, formatting) should leave it* unchanged.*/-const val LEGAL_VERSION: String = "1"+const val LEGAL_VERSION: String = "2"diff --git a/docs/MODEL_CARD.md b/docs/MODEL_CARD.mdnew file mode 100644index 0000000..2eb2a7f--- /dev/null+++ b/docs/MODEL_CARD.md@@ -0,0 +1,46 @@+# Model Card & Provenance: "Hey Gotcha" Custom Wake Word++## 1. Recommended Activation Thresholds++| Use Case | Threshold (`0.0 - 1.0`) | Notes / Behavior |+| :--- | :--- | :--- |+| **Balanced / Standard** *(Recommended)* | **`0.50`** | Best balance between high responsiveness and zero false activations. |+| **High Precision / Loud Environments** | **`0.65`** | Requires clear speech; virtually eliminates false triggers in TV/music environments. |+| **High Sensitivity / Far-Field** | **`0.35`** | Useful for distant microphones (> 3-5 meters away). |++### Integration Code Snippet+```python+from openwakeword.model import Model++# Load custom model+oww = Model(wakeword_models=["hey_gotcha.onnx"], inference_framework="onnx")++THRESHOLD = 0.50++# In your audio streaming loop:+prediction = oww.predict(audio_frame_16k_int16)+if prediction["hey_gotcha"] >= THRESHOLD:+ print("Wake word 'Hey Gotcha' detected!")+```++---++## 2. Model Provenance & Licensing Metadata++### Backbone & Architecture+- **Framework**: `openWakeWord` (v0.5.1)+- **Model Backbone**: Binary Deep Neural Network (DNN) trained on openWakeWord 16-frame spectrogram embeddings.+- **Backbone License**: **Apache-2.0**++### Data Provenance+- **Positive Training Data**:+ - **Source**: 30,000 synthetic audio clips generated via **Piper TTS** using the `en_US-libritts_r-medium` voice model.+ - **Target Phrases**: `["hey_gotcha", "hey_gah_chuh"]`+ - **License**: CC-BY-4.0 / Public Domain synthetic speech output.+- **Negative & Background Data Sources**:+ - **ACAV100M Dataset**: Pre-computed 2,000-hour audio feature representations from YouTube/AudioSet (Creative Commons / Open Access).+ - **Room Impulse Responses**: MIT Environmental Impulse Responses (`mit_rirs`).+ - **Background Noise**: AudioSet 16kHz background noise and FMA music.++### Final Model License+- **Distribution License**: **Apache-2.0** (Fully compatible with commercial and open-source applications).diff --git a/docs/wake-word-handoff.md b/docs/wake-word-handoff.mdindex 396afb8..a4dd428 100644--- a/docs/wake-word-handoff.md+++ b/docs/wake-word-handoff.md@@ -1,142 +1,106 @@# Wake Word Handoff## Goal-Add an optional wake word ("Gotcha") to the existing Assistive Ball flow using-Vosk instead of Porcupine, while reusing the current `CallSessionController`-voice-call path.+Add an optional wake word ("Hey Gotcha") to the existing Assistive Ball flow+using [openWakeWord](https://github.com/dscripka/openWakeWord) ONNX models,+while reusing the current `CallSessionController` voice-call path.## Current status-### Already in the current baseline-- Vosk Android dependency in `app/build.gradle.kts`.-- `Settings.wakeWordEnabled` and `Settings.wakeWordSensitivity`, with- persistence in `SettingsRepository`.-- Initial `WakeWordDetector` integration in `AssistiveBallService`:- - listens only while the call controller is idle;+### In production (merged)+- **Engine:** direct Microsoft ONNX Runtime (`com.microsoft.onnxruntime:onnxruntime-android:1.26.0`).+ The detector runs the melspectrogram → speech-embedding → classifier pipeline+ directly, no third-party wrapper.+- **Models:** three Apache-2.0 ONNX models in+ `app/src/main/assets/openwakeword/` (see `docs/wake-word.md`). The+ classifier (`hey_gotcha.onnx`) was trained by the Gotcha project on+ synthetic Piper-TTS positives and OpenWakeWord's standard negatives.+- **Settings:** `Settings.wakeWordEnabled` and `Settings.wakeWordSensitivity`,+ persisted by `SettingsRepository`.+- **Detection integration in `AssistiveBallService`:**+ - listens only while the call controller is idle and both `wakeWordEnabled`+ and `assistiveBallEnabled` are on;- stops for active call states, `stopBall()`, and `onDestroy()`;- on detection, vibrates and starts the existing call flow through- `callController.startWakeWordCall()`.-- `CallSessionController.startWakeWordCall()` plus `autoEndOnReply`, so a- wake-word-triggered call ends after the spoken reply while ordinary calls- keep the existing stay-open behavior.-- `WakeWordBootReceiver` and manifest registration for reboot restart.-- Wake-word toggle in `AssistiveBallScreen`, with `SettingsScreen` passing- `load`/`onSave`.-- `docs/wake-word.md` setup notes.+ `callController.startWakeWordCall()`;+ - pauses while `ttsEngine.isSpeaking` is true so a screen read-aloud that+ contains "gotcha" cannot self-trigger a call;+ - live settings: reacts to `wakeWordSensitivity` changes via+ `settingsChangeNotifier` while idle;+ - surfaces startup errors through the overlay.+- **Auto-end after the task:** `CallSessionController.startWakeWordCall()`+ plus the `autoEndOnReply` flag, so a wake-word-triggered call ends after+ the spoken reply while ordinary calls keep the existing stay-open behavior.+- **Boot restart:** `WakeWordBootReceiver` + manifest registration; only+ fires when both `assistiveBallEnabled` and `wakeWordEnabled` are on.+- **UI:** `AssistiveBallScreen` exposes a "Wake word: Hey Gotcha" toggle+ and a sensitivity slider, plus a battery-optimization education row.+- **Tests:** `WakeWordMatcherTest` covers sensitivity → threshold mapping+ and patience; `SettingsTest` covers wake-word defaults; the+ `CallSessionControllerTest` extension covers `startWakeWordCall` success+ and failure paths.+- **Legal:** `docs/privacy-data-retention.md` documents the wake-word data+ flow (on-device only); `LEGAL_VERSION` bumped to 2 to force re-acceptance.+- **License notice:** `app/src/main/assets/licenses/openwakeword-notice.txt`+ lists the three bundled models and their Apache-2.0 provenance.-### Added in the current uncommitted worktree-- The official `vosk-model-small-en-us-0.15` model is now under- `app/src/main/assets/vosk-model-small-en-us-0.15/`.- - Source: `https://alphacephei.com/vosk/models/vosk-model-small-en-us-0.15.zip`- - Upstream catalog lists it as Apache 2.0.- - Extracted size is about 71 MB; the source zip is about 40 MB.-- New `service/WakeWordMatcher.kt`:- - exact-token phrase matching;- - maps sensitivity to 1/2/3 consecutive matching Vosk updates;- - intended to reduce false triggers from a single noisy partial result.-- `service/WakeWordDetector.kt` is mid-refactor:- - model extraction/loading moved off the main thread;- - recognizer now uses the constrained grammar `["gotcha", "[unk]"]`;- - asset-tree copying was fixed for file leaves;- - cache extraction is versioned by `BuildConfig.VERSION_CODE`;- - callbacks were added for started/detected/error;- - a generation counter was started to avoid stale async initialization after- rapid stop/start, but that refactor is incomplete.+### Architecture pieces intentionally kept engine-agnostic+- `AssistiveBallService` idle-gating, `stopBall()`, `onDestroy()` cleanup.+- `CallSessionController.startWakeWordCall()` + `autoEndOnReply`.+- The `WakeWordBootReceiver` boot path.+- The `Settings` data class and repository.+- The `WakeWordDetector` public surface (`start()`/`stop()`/`isRunning()` ++ `onStarted`/`onDetected`/`onError` callbacks + `sensitivityProvider`).-## Current build state: intentionally paused while red-The earlier synchronous implementation compiled successfully with:+These are reusable if the underlying engine is swapped again (e.g. to a+custom TFLite classifier).-```powershell-./gradlew.bat :app:compileDebugKotlin-```+## Manual device-verification checklist-After the async/sensitivity refactor began, compilation is currently broken.-Known issues:+- [ ] Ball on, microphone granted, wake word on; say "Hey Gotcha" — call+ starts, mic re-arms, agent replies, call auto-ends.+- [ ] Say "Hey Gotcha" during an active call — ignored (idle gate).+- [ ] Screen off — listener still detects (may require battery optimization+ exemption on some OEMs).+- [ ] Reboot — listener resumes via `WakeWordBootReceiver`.+- [ ] TV / music playing near the phone — no false triggers at the balanced+ threshold.+- [ ] Slide sensitivity to "High precision" — stricter triggers, fewer+ false activations.-1. `AssistiveBallService.kt` still constructs `WakeWordDetector` without the- new required `sensitivityProvider` argument.-2. `WakeWordDetector.start()` calls `initializeAndListen(startGeneration)`, but- `initializeAndListen()` has not yet been updated to accept a generation- parameter.-3. The generation guard needs to be carried through initialization, listening,- and failure reporting so an old coroutine cannot install resources or report- an error after a newer start/stop cycle.--Do not assume the worktree is green until the next compile succeeds.+## Risks / notes-## Next implementation steps-1. Finish the `WakeWordDetector` generation refactor:- - change `initializeAndListen()` to accept `generation: Int`;- - assign resources only when `running && generation == this.generation`;- - pass the generation into `listen()`;- - ignore stale listener failures from an old generation.-2. Update `AssistiveBallService` construction:- - pass `sensitivityProvider = { settingsRepository.load().wakeWordSensitivity }`;- - pass `onStarted`, `onDetected`, and `onError` callbacks;- - surface detector startup failures through the existing overlay once, not- repeatedly.-3. Add live settings handling in `AssistiveBallService` with- `settingsChangeNotifier`:- - track `(wakeWordEnabled, wakeWordSensitivity)`;- - stop when disabled;- - restart when sensitivity changes while idle;- - do not interrupt an active call.-4. Add the sensitivity slider to `AssistiveBallScreen` and persist- `wakeWordSensitivity`.-5. Decide whether to add the battery-optimization exemption request:- - manifest permission: `REQUEST_IGNORE_BATTERY_OPTIMIZATIONS`;- - contextual button/education from the Assistive Ball or Permissions page.-6. Add/refresh legal copy:- - explain that wake-word listening uses the microphone while the ball is on- and idle;- - state that Vosk wake-word audio is processed on-device;- - state that only the post-trigger voice command uses the configured STT- provider;- - consider bumping `LEGAL_VERSION` because this is a material privacy change.-7. Add an Apache 2.0 license/notice copy for the bundled Vosk model if the- project intends to commit and redistribute the model asset.-8. Add tests:- - `WakeWordMatcher` exact-token and sensitivity-streak behavior;- - settings persistence for `wakeWordEnabled` / `wakeWordSensitivity`;- - `CallSessionController` wake-word auto-end behavior;- - optionally boot-receiver gating.-9. Run:- - `./gradlew.bat :app:compileDebugKotlin`- - focused unit tests- - `:app:assembleDebug` to verify the 71 MB model packages correctly- - `:app:detekt` if time permits.-10. Device-test the full loop:- - enable ball + microphone + wake word;- - say "Gotcha";- - confirm vibration, call start, mic turn, spoken reply, and auto-end;- - confirm ordinary long-press calls still stay open;- - test screen off, reboot, OEM battery behavior, and mic contention.+- The custom classifier is Apache-2.0 because training data and architecture+ are all Apache-2.0 (OpenWakeWord code + Google speech-embedding backbone+ + Piper-TTS-generated positives + OpenWakeWord's standard negatives).+- The detector runs three small ONNX models continuously; on a modern+ Android device CPU usage is negligible compared to a full ASR engine.+- Real-device false-accept rates must be validated before shipping the+ always-on listener to users; the `Hey Gotcha` phrase is short and can+ sound similar to casual speech in noisy environments. The sensitivity+ slider and confuser-style pronunciation training give users a way to+ trade off misses vs. false triggers.+- Mic contention with the call STT is handled by the idle-gate, but+ device-level validation is recommended.-## Files added or changed across the whole effort-- `app/build.gradle.kts`-- `app/src/main/AndroidManifest.xml`-- `app/src/main/assets/vosk-model-small-en-us-0.15/**` (new, uncommitted)-- `app/src/main/java/com/gotcha/data/SettingsRepository.kt`-- `app/src/main/java/com/gotcha/service/AssistiveBallService.kt`-- `app/src/main/java/com/gotcha/service/CallSessionController.kt`-- `app/src/main/java/com/gotcha/service/WakeWordDetector.kt`-- `app/src/main/java/com/gotcha/service/WakeWordMatcher.kt` (new, uncommitted)-- `app/src/main/java/com/gotcha/tools/WakeWordBootReceiver.kt`-- `app/src/main/java/com/gotcha/ui/AssistiveBallScreen.kt`-- `app/src/main/java/com/gotcha/ui/SettingsScreen.kt`-- `docs/wake-word.md`-- `docs/wake-word-handoff.md`+## Files in the wake-word effort-## Risks / notes-- Vosk avoids Porcupine's commercial APK licensing issue; the selected model is- listed upstream as Apache 2.0.-- The model makes the APK substantially larger.-- Vosk is being used with a constrained keyword grammar rather than unrestricted- transcription, but accuracy and false-positive behavior still require device- testing.-- The current sensitivity model is app-defined (consecutive recognition hits),- not a native Vosk confidence threshold.-- Mic contention is handled by the call-state idle gate, but this still needs- real-device validation.-- The current worktree should be treated as an in-progress checkpoint, not as a- ready-to-run branch.+- `app/build.gradle.kts` — adds ONNX Runtime dep.+- `app/src/main/AndroidManifest.xml` — wake-word boot receiver,+ `REQUEST_IGNORE_BATTERY_OPTIMIZATIONS` permission.+- `app/src/main/assets/openwakeword/{hey_gotcha.onnx,melspectrogram.onnx,embedding_model.onnx}`+- `app/src/main/assets/licenses/openwakeword-notice.txt`+- `app/src/main/assets/legal/privacy-data-retention.md` — wake-word section.+- `app/src/main/java/com/gotcha/data/SettingsRepository.kt` — fields, persistence, `LEGAL_VERSION` bump.+- `app/src/main/java/com/gotcha/audio/TtsEngine.kt` — `isSpeaking` tracking.+- `app/src/main/java/com/gotcha/service/WakeWordDetector.kt` — detector.+- `app/src/main/java/com/gotcha/service/OnnxWakeWordPipeline.kt` — ONNX pipeline.+- `app/src/main/java/com/gotcha/service/WakeWordMatcher.kt` — threshold/patience.+- `app/src/main/java/com/gotcha/service/CallSessionController.kt` — `autoEndOnReply`.+- `app/src/main/java/com/gotcha/service/AssistiveBallService.kt` — idle-gate, TTS guard, live settings.+- `app/src/main/java/com/gotcha/tools/WakeWordBootReceiver.kt` — boot restart.+- `app/src/main/java/com/gotcha/ui/AssistiveBallScreen.kt` — toggle + slider + battery row.+- `app/src/test/java/com/gotcha/service/WakeWordMatcherTest.kt` — unit tests.+- `app/src/test/java/com/gotcha/data/SettingsTest.kt` — wake-word defaults.+- `app/src/test/java/com/gotcha/service/CallSessionControllerTest.kt` — wake-word start paths.+- `docs/wake-word.md`, `docs/wake-word-handoff.md`, `docs/MODEL_CARD.md`.diff --git a/docs/wake-word.md b/docs/wake-word.mdindex f7ac746..26eafbb 100644--- a/docs/wake-word.md+++ b/docs/wake-word.md@@ -1,18 +1,82 @@# Wake Word-Gotcha's optional wake word uses Vosk locally. No audio is sent anywhere while-the listener is waiting; only the existing voice call sends the spoken command-to the configured speech-to-text provider.--The build uses the small English Vosk model at-`app/src/main/assets/vosk-model-small-en-us-0.15`. The model is currently-present in the working tree and was downloaded from the official Vosk model-catalog, which lists it as Apache 2.0. It adds roughly 40 MB of compressed-model data to the app, so decide deliberately before committing it.--The listener is active only when both Assistive Ball and Wake word are enabled,-the microphone permission is granted, and the call state is idle. An unloadable-model or unavailable microphone disables detection without crashing the service.--See `docs/wake-word-handoff.md` for the current implementation checkpoint and-remaining work.+Gotcha's optional wake word is **"Hey Gotcha"**. It listens locally with the+bundled [OpenWakeWord](https://github.com/dscripka/openWakeWord) ONNX models —+no audio leaves the device while the listener is waiting. Only the existing+voice call sends the spoken command to the configured speech-to-text provider.++## Bundled models++Three Apache-2.0 models live under `app/src/main/assets/openwakeword/`:++| File | Role |+| :--- | :--- |+| `hey_gotcha.onnx` | Custom classifier head trained by the Gotcha project on synthetic Piper-TTS positives and OpenWakeWord's standard negative/background data |+| `embedding_model.onnx` | Google's speech-embedding backbone, as used by OpenWakeWord |+| `melspectrogram.onnx` | OpenWakeWord melspectrogram front-end |++Provenance and license details are in+`app/src/main/assets/licenses/openwakeword-notice.txt` and+[`docs/MODEL_CARD.md`](MODEL_CARD.md).++## Pipeline++Per 80 ms (1280-sample) frame @ 16 kHz mono PCM-16, the+`WakeWordDetector` runs:++1. **Melspectrogram** — the most recent 1760 samples → `melspectrogram.onnx` →+ 32-bin mel rows, transformed with `spec / 10 + 2`.+2. **Embedding** — the latest 76 mel rows → `embedding_model.onnx` → one+ 96-dim speech embedding per frame.+3. **Classification** — the last 16 embeddings → `hey_gotcha.onnx` → a score+ in [0, 1].++A `WakeWordMatcher` then maps the user-facing sensitivity slider to the+score threshold (`threshold = 0.70 − 0.27 × sensitivity`) and requires two+consecutive qualifying frames before firing. The default sensitivity of 0.75+corresponds to the model card's balanced threshold of 0.50.++## When the listener runs++- **Wake word enabled** AND **Assistive Ball enabled** AND microphone+ permission granted AND the call state is idle.+- An unloadable model or unavailable microphone disables detection without+ crashing the service.+- The detector is paused while the App's own text-to-speech is playing, so+ the App reading "gotcha" aloud does not self-trigger a call.++## Battery and reliability++OEM battery managers may kill the always-on listener. The Assistive Ball+settings page offers a one-tap link to Android's battery-optimization+exemption request when the wake word is on.++## Play Store disclosure++The wake-word listener keeps the microphone open while the Assistive Ball is+on, which is material for Play Store policy. The current implementation:++- Adds `REQUEST_IGNORE_BATTERY_OPTIMIZATIONS` to the manifest and offers a+ one-tap exemption link in settings — required to receive the Play+ "background audio" carve-out for always-listening apps.+- Documents wake-word data flow in `docs/privacy-data-retention.md`+ (Section 10): audio frames stay on-device; only the post-trigger command+ uses the configured STT provider.++Before publishing, declare the wake-word mic use on the Play Console and+ensure the in-app legal copy is up to date (bump `LEGAL_VERSION` in+`SettingsRepository` whenever the legal docs change so existing users+re-accept).++## Custom training++The bundled classifier was trained on two pronunciation variants+(`hey gotcha`, `hey gah chuh`). To retrain for a different phrase or+accent, follow the [official openWakeWord training+Colab](https://colab.research.google.com/drive/1q1oe2zOyZp7UsB3jJiQ1IFn8z5YfjwEb),+export `model.onnx`, replace `app/src/main/assets/openwakeword/hey_gotcha.onnx`,+and update `WakeWordDetector.CLASSIFIER_MODEL` if the filename changes.++See [`docs/MODEL_CARD.md`](MODEL_CARD.md) for the threshold recommendations and+[`docs/wake-word-handoff.md`](wake-word-handoff.md) for the implementation+checkpoint and ongoing work.