various fixes
- Commit
1a2b630a2d11420e40c4d5ddc234fd859bd54b95- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-31 03:00 UTC (4 months ago)
- Parents
7facddd
Diff
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex e798d1fcc3..7a694aae09 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -86,6 +86,7 @@ desugarJdkLibs = "2.1.5" protoc = "4.28.3" vonageVoice = "2.6.0" appauth = "0.11.1"+stripe = "21.12.0" shadow = "9.0.0" [libraries]@@ -213,6 +214,7 @@ kotlin-test = { group = "org.jetbrains.kotlin", name = "kotlin-test", version.re desugar-jdk-libs = { module = "com.android.tools:desugar_jdk_libs", version.ref = "desugarJdkLibs" } vonage-client-sdk-voice = { group = "com.vonage", name = "client-sdk-voice", version.ref = "vonageVoice" } appauth = { group = "net.openid", name = "appauth", version.ref = "appauth" }+stripe-android = { module = "com.stripe:stripe-android", version.ref = "stripe" } [plugins] android-application = { id = "com.android.application", version.ref = "agp" }
keyboard/src/main/java/com/vayunmathur/keyboard/ime/KeyboardService.kt
diff --git a/keyboard/src/main/java/com/vayunmathur/keyboard/ime/KeyboardService.kt b/keyboard/src/main/java/com/vayunmathur/keyboard/ime/KeyboardService.ktindex f4613de752..1b8b63a387 100644--- a/keyboard/src/main/java/com/vayunmathur/keyboard/ime/KeyboardService.kt+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/ime/KeyboardService.kt@@ -201,8 +201,10 @@ class KeyboardService : InputMethodService(), variation == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD || variation == InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD)) || (cls == InputType.TYPE_CLASS_NUMBER && variation == InputType.TYPE_NUMBER_VARIATION_PASSWORD)+ // Phone gets its own dial-pad layout (FUTO phone.yaml); number/datetime share the+ // numeric layout (FUTO number.yaml). Everything else uses letters.+ val isPhone = cls == InputType.TYPE_CLASS_PHONE val isNumeric = cls == InputType.TYPE_CLASS_NUMBER ||- cls == InputType.TYPE_CLASS_PHONE || cls == InputType.TYPE_CLASS_DATETIME kbState.passwordField = isPassword@@ -214,7 +216,11 @@ class KeyboardService : InputMethodService(), variation == InputType.TYPE_TEXT_VARIATION_URI -> TextVariation.URL else -> TextVariation.NORMAL }- kbState.basePage = if (isNumeric) KeyboardPage.NUMERIC else KeyboardPage.LETTERS+ kbState.basePage = when {+ isPhone -> KeyboardPage.PHONE+ isNumeric -> KeyboardPage.NUMERIC+ else -> KeyboardPage.LETTERS+ } kbState.page = kbState.basePage kbState.shift = ShiftState.OFF
keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyButton.kt
diff --git a/keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyButton.kt b/keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyButton.ktindex f68adbca1c..81a77c74ea 100644--- a/keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyButton.kt+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyButton.kt@@ -10,6 +10,7 @@ import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.PressInteraction import androidx.compose.foundation.interaction.collectIsPressedAsState import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.height@@ -65,12 +66,17 @@ fun specialKeyColor(): Color = MaterialTheme.colorScheme.surfaceContainer @Composable fun pressedKeyColor(): Color = MaterialTheme.colorScheme.surfaceBright -/** A letter/symbol key: tap commits, optional long-press commits an alternate. */+/**+ * A letter/symbol key: tap commits, optional long-press commits an alternate. An optional+ * [hint] draws a small secondary label beneath the main one (the ABC/DEF letters on the+ * phone dial-pad, matching FUTO's phone layout).+ */ @Composable fun RowScope.CharKey( label: String, height: Dp, weight: Float = 1f,+ hint: String? = null, onClick: () -> Unit, onLongClick: (() -> Unit)? = null, ) {@@ -91,7 +97,14 @@ fun RowScope.CharKey( ), contentAlignment = Alignment.Center, ) {- Text(text = label, color = MaterialTheme.colorScheme.onSurface, fontSize = 20.sp)+ if (hint != null) {+ Column(horizontalAlignment = Alignment.CenterHorizontally) {+ Text(text = label, color = MaterialTheme.colorScheme.onSurface, fontSize = 18.sp)+ Text(text = hint, color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 9.sp)+ }+ } else {+ Text(text = label, color = MaterialTheme.colorScheme.onSurface, fontSize = 20.sp)+ } // FUTO/AOSP-style preview: while held, balloon the character above the key so // the finger doesn't hide it. clippingEnabled=false lets it float above the // top row (outside the keyboard bounds).
keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyboardScreen.kt
diff --git a/keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyboardScreen.kt b/keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyboardScreen.ktindex d485ca42ff..dc6f7412b6 100644--- a/keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyboardScreen.kt+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/ui/KeyboardScreen.kt@@ -22,6 +22,7 @@ import com.vayunmathur.keyboard.util.ShiftState import com.vayunmathur.library.ui.IconBackspace import com.vayunmathur.library.ui.IconEmoji import com.vayunmathur.library.ui.IconReturn+import com.vayunmathur.library.ui.IconSpaceBar import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Surface import com.vayunmathur.library.ui.Text@@ -47,7 +48,12 @@ fun KeyboardScreen(state: KeyboardState, actions: ImeActions) { .fillMaxWidth() .padding(bottom = bottomPad), ) {- if (state.settings.showSuggestions && state.page != KeyboardPage.EMOJI) {+ // The suggestion strip belongs to text entry only; numeric/phone/emoji pages+ // never compose words, so (like FUTO) they show no strip.+ val textPage = state.page == KeyboardPage.LETTERS ||+ state.page == KeyboardPage.SYMBOLS ||+ state.page == KeyboardPage.MORE_SYMBOLS+ if (state.settings.showSuggestions && textPage) { SuggestionStrip( height = 44.dp, suggestions = state.suggestions,@@ -61,6 +67,8 @@ fun KeyboardScreen(state: KeyboardState, actions: ImeActions) { KeyboardPage.MORE_SYMBOLS -> SymbolPage(state, actions, keyHeight, Layouts.MORE_SYMBOL_ROWS, KeyboardPage.SYMBOLS, "?123") KeyboardPage.NUMERIC -> NumericPage(state, actions, keyHeight)+ KeyboardPage.PHONE -> PhonePage(state, actions, keyHeight)+ KeyboardPage.PHONE_SYMBOLS -> PhoneSymbolsPage(state, actions, keyHeight) KeyboardPage.EMOJI -> EmojiPage( keyHeight = keyHeight, rows = 4,@@ -144,41 +152,153 @@ private fun SymbolPage( } @Composable-private fun RowScope.SymbolKey(c: Char, keyHeight: Dp, actions: ImeActions) {- CharKey(label = c.toString(), height = keyHeight, onClick = { actions.onChar(c.toString()) })+private fun RowScope.SymbolKey(c: Char, keyHeight: Dp, actions: ImeActions, weight: Float = 1f) {+ CharKey(label = c.toString(), height = keyHeight, weight = weight, onClick = { actions.onChar(c.toString()) }) } +/**+ * Numeric page, mirroring FUTO's `number.yaml`: functional operator columns flank three+ * digit columns, and the bottom row uses proportional widths so `0` lands centred under+ * the 2/5/8 column and every row shares the same left/right edges. Column widths are+ * FUTO's fractions — side keys 0.15, digits 0.2333, comma/period 0.1, the two "grow"+ * keys splitting the remainder — used directly as (relative) row weights.+ */ @Composable private fun NumericPage(state: KeyboardState, actions: ImeActions, keyHeight: Dp) {+ val side = 0.15f+ val digit = 0.2333f+ val reg = 0.1f+ val grow = 0.1333f Row(Modifier.fillMaxWidth()) {- SymbolKey('1', keyHeight, actions)- SymbolKey('2', keyHeight, actions)- SymbolKey('3', keyHeight, actions)- RepeatKey(keyHeight, 1f, actions::onBackspace) { IconBackspace() }+ NumFunctionKey("+", side, keyHeight, actions)+ SymbolKey('1', keyHeight, actions, digit)+ SymbolKey('2', keyHeight, actions, digit)+ SymbolKey('3', keyHeight, actions, digit)+ NumFunctionKey("%", side, keyHeight, actions) } Row(Modifier.fillMaxWidth()) {- SymbolKey('4', keyHeight, actions)- SymbolKey('5', keyHeight, actions)- SymbolKey('6', keyHeight, actions)- SymbolKey('+', keyHeight, actions)+ NumFunctionKey("-", side, keyHeight, actions)+ SymbolKey('4', keyHeight, actions, digit)+ SymbolKey('5', keyHeight, actions, digit)+ SymbolKey('6', keyHeight, actions, digit)+ SpecialKey(keyHeight, side, onClick = actions::onSpace) { IconSpaceBar() } } Row(Modifier.fillMaxWidth()) {- SymbolKey('7', keyHeight, actions)- SymbolKey('8', keyHeight, actions)- SymbolKey('9', keyHeight, actions)- SymbolKey('-', keyHeight, actions)+ NumFunctionKey("*", side, keyHeight, actions)+ SymbolKey('7', keyHeight, actions, digit)+ SymbolKey('8', keyHeight, actions, digit)+ SymbolKey('9', keyHeight, actions, digit)+ RepeatKey(keyHeight, side, actions::onBackspace) { IconBackspace() } } Row(Modifier.fillMaxWidth()) {- SpecialKey(keyHeight, 1f, onClick = { actions.setPage(KeyboardPage.LETTERS) }) {+ SpecialKey(keyHeight, side, onClick = { actions.setPage(KeyboardPage.LETTERS) }) { Text("ABC", fontSize = 14.sp) }+ NumFunctionKey(",", reg, keyHeight, actions)+ SpecialKey(keyHeight, grow, onClick = { actions.setPage(KeyboardPage.SYMBOLS) }) {+ Text("?123", fontSize = 14.sp)+ }+ SymbolKey('0', keyHeight, actions, digit)+ NumFunctionKey("=", grow, keyHeight, actions)+ NumFunctionKey(".", reg, keyHeight, actions)+ EnterKey(state, actions, keyHeight, side)+ }+}++/** A character key with functional (dimmer) styling — used for the numeric page operators. */+@Composable+private fun RowScope.NumFunctionKey(label: String, weight: Float, keyHeight: Dp, actions: ImeActions) {+ SpecialKey(keyHeight, weight, onClick = { actions.onChar(label) }) {+ Text(label, fontSize = 20.sp)+ }+}++/**+ * Phone dial-pad, mirroring FUTO's `phone.yaml`: an even 4-column grid with the digits+ * carrying their ABC/DEF letter hints, functional keys (−, space, ⌫) down the right edge,+ * and a toggle to the phone-symbols page. The enter key reflects the field's IME action.+ */+@Composable+private fun PhonePage(state: KeyboardState, actions: ImeActions, keyHeight: Dp) {+ Row(Modifier.fillMaxWidth()) {+ PhoneKey('1', null, keyHeight, actions)+ PhoneKey('2', "ABC", keyHeight, actions)+ PhoneKey('3', "DEF", keyHeight, actions)+ NumFunctionKey("-", 1f, keyHeight, actions)+ }+ Row(Modifier.fillMaxWidth()) {+ PhoneKey('4', "GHI", keyHeight, actions)+ PhoneKey('5', "JKL", keyHeight, actions)+ PhoneKey('6', "MNO", keyHeight, actions)+ SpecialKey(keyHeight, 1f, onClick = actions::onSpace) { IconSpaceBar() }+ }+ Row(Modifier.fillMaxWidth()) {+ PhoneKey('7', "PQRS", keyHeight, actions)+ PhoneKey('8', "TUV", keyHeight, actions)+ PhoneKey('9', "WXYZ", keyHeight, actions)+ RepeatKey(keyHeight, 1f, actions::onBackspace) { IconBackspace() }+ }+ Row(Modifier.fillMaxWidth()) {+ SpecialKey(keyHeight, 1f, onClick = { actions.setPage(KeyboardPage.PHONE_SYMBOLS) }) {+ Text("*#(", fontSize = 16.sp)+ }+ PhoneKey('0', "+", keyHeight, actions)+ CharKey(".", keyHeight, 1f, onClick = { actions.onChar(".") })+ EnterKey(state, actions, keyHeight, 1f)+ }+}++/** A phone-page digit with its dial-pad letter hint (matches FUTO's phone layout). */+@Composable+private fun RowScope.PhoneKey(c: Char, hint: String?, keyHeight: Dp, actions: ImeActions) {+ CharKey(label = c.toString(), height = keyHeight, hint = hint, onClick = { actions.onChar(c.toString()) })+}++/**+ * Phone symbols page, mirroring FUTO's `phone_shift.yaml`: brackets/slash, the dialer+ * pause (`,`) and wait (`;`) keys, `* # +`, and a toggle back to the dial pad.+ */+@Composable+private fun PhoneSymbolsPage(state: KeyboardState, actions: ImeActions, keyHeight: Dp) {+ Row(Modifier.fillMaxWidth()) {+ SymbolKey('(', keyHeight, actions)+ SymbolKey('/', keyHeight, actions)+ SymbolKey(')', keyHeight, actions)+ NumFunctionKey("-", 1f, keyHeight, actions)+ }+ Row(Modifier.fillMaxWidth()) {+ SymbolKey('N', keyHeight, actions)+ PhoneWordKey("Pause", ",", keyHeight, actions)+ SymbolKey(',', keyHeight, actions)+ SpecialKey(keyHeight, 1f, onClick = actions::onSpace) { IconSpaceBar() }+ }+ Row(Modifier.fillMaxWidth()) { SymbolKey('*', keyHeight, actions)- SymbolKey('0', keyHeight, actions)+ PhoneWordKey("Wait", ";", keyHeight, actions) SymbolKey('#', keyHeight, actions)+ RepeatKey(keyHeight, 1f, actions::onBackspace) { IconBackspace() }+ }+ Row(Modifier.fillMaxWidth()) {+ SpecialKey(keyHeight, 1f, onClick = { actions.setPage(KeyboardPage.PHONE) }) {+ Text("123", fontSize = 14.sp)+ }+ SymbolKey('+', keyHeight, actions)+ SymbolKey('.', keyHeight, actions) EnterKey(state, actions, keyHeight, 1f) } } +/**+ * A word-labelled key (Pause/Wait) that commits the dialer control char. Rendered like a+ * normal (raised) key but with small text so the word fits.+ */+@Composable+private fun RowScope.PhoneWordKey(label: String, commit: String, keyHeight: Dp, actions: ImeActions) {+ SpecialKey(keyHeight, 1f, containerColor = charKeyColor(), onClick = { actions.onChar(commit) }) {+ Text(label, fontSize = 13.sp)+ }+}+ @Composable private fun BottomRow( state: KeyboardState,
keyboard/src/main/java/com/vayunmathur/keyboard/util/Layouts.kt
diff --git a/keyboard/src/main/java/com/vayunmathur/keyboard/util/Layouts.kt b/keyboard/src/main/java/com/vayunmathur/keyboard/util/Layouts.ktindex 7a26492ce2..b630dba0b8 100644--- a/keyboard/src/main/java/com/vayunmathur/keyboard/util/Layouts.kt+++ b/keyboard/src/main/java/com/vayunmathur/keyboard/util/Layouts.kt@@ -1,7 +1,7 @@ package com.vayunmathur.keyboard.util /** Which page of keys is currently shown. */-enum class KeyboardPage { LETTERS, SYMBOLS, MORE_SYMBOLS, NUMERIC, EMOJI }+enum class KeyboardPage { LETTERS, SYMBOLS, MORE_SYMBOLS, NUMERIC, PHONE, PHONE_SYMBOLS, EMOJI } /** Shift/caps state for the letter page. */ enum class ShiftState { OFF, SHIFTED, CAPS_LOCK }@@ -58,6 +58,7 @@ object Layouts { KeyboardPage.SYMBOLS -> SYMBOL_ROWS KeyboardPage.MORE_SYMBOLS -> MORE_SYMBOL_ROWS KeyboardPage.NUMERIC -> NUMERIC_ROWS- KeyboardPage.EMOJI -> null+ // Phone/emoji pages are laid out directly by the UI (special keys, hints, grid).+ KeyboardPage.PHONE, KeyboardPage.PHONE_SYMBOLS, KeyboardPage.EMOJI -> null } }
scripts/speech/fetch_piper_model.sh
diff --git a/scripts/speech/fetch_piper_model.sh b/scripts/speech/fetch_piper_model.shnew file mode 100755index 0000000000..41e60bf28f--- /dev/null+++ b/scripts/speech/fetch_piper_model.sh@@ -0,0 +1,45 @@+#!/usr/bin/env bash+#+# Stage an offline Piper (VITS) voice as a single zip for the model mirror. The :speech app+# downloads it at runtime — it is NOT bundled in the APK — from+# https://data.vayunmathur.com/models/piper/voice.zip+# and extracts it (see PiperModel). The zip must contain the voice's CONTENTS at its root:+# <voice>.onnx, tokens.txt, and espeak-ng-data/.+#+# Voices: https://github.com/k2-fsa/sherpa-onnx/releases/tag/tts-models (vits-piper-*)+#+# ./scripts/speech/fetch_piper_model.sh # amy-low (~64 MB)+# ./scripts/speech/fetch_piper_model.sh vits-piper-en_US-kristin-medium+#+set -euo pipefail++VOICE="${1:-vits-piper-en_US-amy-low}"+URL="https://github.com/k2-fsa/sherpa-onnx/releases/download/tts-models/${VOICE}.tar.bz2"+DEST="dist/speech-mirror/piper"++if [ ! -f settings.gradle.kts ]; then+ echo "Run this from the repo root (where settings.gradle.kts is)." >&2+ exit 1+fi+command -v zip >/dev/null || { echo "'zip' is required." >&2; exit 1; }++ABS_DEST="$(pwd)/$DEST"+TMP="$(mktemp -d)"+trap 'rm -rf "$TMP"' EXIT++echo "Downloading ${VOICE}..."+curl -fL "${URL}" -o "${TMP}/voice.tar.bz2"+echo "Extracting..."+tar xjf "$TMP/voice.tar.bz2" -C "$TMP"+# The Piper JSON config isn't needed at runtime (sherpa reads the .onnx metadata + tokens).+rm -f "$TMP/${VOICE}"/*.onnx.json++mkdir -p "${ABS_DEST}"+rm -f "${ABS_DEST}/voice.zip"+# Zip the voice dir's CONTENTS (not the wrapping folder) so entries sit at the zip root.+( cd "${TMP}/${VOICE}" && zip -r -q -X "${ABS_DEST}/voice.zip" . )++echo+echo "Staged ${DEST}/voice.zip"+du -sh "${ABS_DEST}/voice.zip"+echo "Upload it to: https://data.vayunmathur.com/models/piper/voice.zip"
scripts/speech/fetch_sherpa_onnx.sh
diff --git a/scripts/speech/fetch_sherpa_onnx.sh b/scripts/speech/fetch_sherpa_onnx.shnew file mode 100755index 0000000000..4317209ac5--- /dev/null+++ b/scripts/speech/fetch_sherpa_onnx.sh@@ -0,0 +1,36 @@+#!/usr/bin/env bash+#+# Vendor the official sherpa-onnx Android AAR (Apache-2.0) into speech/libs so the :speech+# app can run offline Piper/VITS text-to-speech (com.k2fsa.sherpa.onnx.OfflineTts). The AAR+# bundles libonnxruntime.so for all four ABIs, so :speech does NOT depend on+# onnxruntime-android separately. Referenced from settings.gradle.kts via flatDir and from+# speech/build.gradle.kts as implementation(":sherpa-onnx@aar").+#+# Source: https://github.com/k2-fsa/sherpa-onnx/releases (tag v<VER>).+#+# ./scripts/speech/fetch_sherpa_onnx.sh+#+set -euo pipefail++VER="${SHERPA_ONNX_VERSION:-1.13.4}"+DEST="speech/libs"+OUT="$DEST/sherpa-onnx.aar"+URL="https://github.com/k2-fsa/sherpa-onnx/releases/download/v${VER}/sherpa-onnx-${VER}.aar"++if [ ! -f settings.gradle.kts ]; then+ echo "Run this from the repo root (where settings.gradle.kts is)." >&2+ exit 1+fi++if [ -f "$OUT" ]; then+ echo "sherpa-onnx AAR already present at ${OUT} — nothing to do."+ echo "(delete it and re-run to upgrade; set SHERPA_ONNX_VERSION to pick a version.)"+ exit 0+fi++mkdir -p "${DEST}"+echo "Downloading sherpa-onnx ${VER} AAR (~47 MB)..."+curl -fL "${URL}" -o "${OUT}"++echo "Done:"+du -sh "${OUT}"
scripts/speech/fetch_whisper_model.sh
diff --git a/scripts/speech/fetch_whisper_model.sh b/scripts/speech/fetch_whisper_model.shindex 1a9a060dbc..0db475bd36 100755--- a/scripts/speech/fetch_whisper_model.sh+++ b/scripts/speech/fetch_whisper_model.sh@@ -1,18 +1,18 @@ #!/usr/bin/env bash #-# Fetch the multilingual Whisper-tiny ncnn model (13 files, ~113 MB) and drop them into-# the :speech app assets so they get bundled in the APK and loaded by the ncnn AAR's-# com.vayunmathur.ncnn.Whisper (AssetManager) — no runtime download, no extraction.+# Stage the multilingual Whisper-tiny ncnn model (13 files, ~113 MB) for upload to the model+# mirror. The :speech app downloads these at runtime — they are NOT bundled in the APK — from+# https://data.vayunmathur.com/models/whisper-tiny/<file>+# (see WhisperModel.FILES). Upload the staged files under that path, preserving names. # # Source: nihui/ncnn-android-whisper release tag "models" (pre-converted by nihui).-# The model is committed with the app, so this is only needed to re-fetch / restore it: # # ./scripts/speech/fetch_whisper_model.sh # set -euo pipefail BASE="https://github.com/nihui/ncnn-android-whisper/releases/download/models"-DEST="speech/src/main/assets/whisper-tiny"+DEST="dist/speech-mirror/whisper-tiny" FILES=( whisper_tiny_decoder.ncnn.bin whisper_tiny_decoder.ncnn.param@@ -29,18 +29,15 @@ if [ ! -f settings.gradle.kts ]; then exit 1 fi -if [ "$(ls -1 "$DEST" 2>/dev/null | wc -l | tr -d ' ')" = "13" ]; then- echo "Model already present at ${DEST} (13 files) — nothing to do."- exit 0-fi- mkdir -p "$DEST" for f in "${FILES[@]}"; do- echo "Downloading $f…"- curl -fL "$BASE/$f" -o "$DEST/$f"+ echo "Downloading ${f}..."+ curl -fL "${BASE}/${f}" -o "${DEST}/${f}" done -echo "Done. Bundled ${#FILES[@]} files:"-du -sh "$DEST" echo-echo "Now: ./install dev speech"+echo "Staged ${#FILES[@]} files in ${DEST}"+du -sh "${DEST}"+echo "Upload them to: https://data.vayunmathur.com/models/whisper-tiny/"+echo "SHA-256 (must match WhisperModel.FILES):"+( cd "${DEST}" && shasum -a 256 * 2>/dev/null || sha256sum * )
speech/build.gradle.kts
diff --git a/speech/build.gradle.kts b/speech/build.gradle.ktsindex 386e74daf7..dec7920d8f 100644--- a/speech/build.gradle.kts+++ b/speech/build.gradle.kts@@ -12,16 +12,29 @@ android { defaultConfig { applicationId = "com.vayunmathur.speech" }- androidResources {- // Keep the bundled whisper model uncompressed so the ncnn AAR can open it by- // file descriptor / mmap straight from the APK (compressed assets can't be fd-opened).- noCompress += listOf("bin", "param", "txt")+ packaging {+ jniLibs {+ // Both native AARs (ncnn, sherpa-onnx) may ship libc++_shared.so; take one+ // rather than failing the merge with a duplicate.+ pickFirsts += "**/libc++_shared.so"+ } } } dependencies { // Offline speech-to-text runs in the ncnn AAR (Whisper, com.vayunmathur.ncnn.Whisper);- // the multilingual whisper-tiny model is bundled in assets/whisper-tiny (fetch via- // scripts/speech/fetch_whisper_model.sh) and loaded from the APK by AssetManager.+ // the whisper-tiny model is downloaded at runtime from the mirror (WhisperModel.FILES)+ // and loaded from the filesystem via Whisper(dirPath). implementation(libs.ncnn.android)++ // Offline text-to-speech (Piper/VITS) runs in the sherpa-onnx AAR+ // (com.k2fsa.sherpa.onnx.OfflineTts). The AAR bundles its own libonnxruntime.so, so+ // this module must NOT also depend on onnxruntime-android (duplicate .so). Vendor it+ // with scripts/speech/fetch_sherpa_onnx.sh. The Piper voice model is downloaded at+ // runtime (PiperModel) — only the native code ships in the APK.+ implementation(":sherpa-onnx@aar")++ // Runtime model download (mirror-hosted, SHA-256 pinned) — same infra as Translate.+ implementation(project(":library:downloadservice"))+ implementation(libs.androidx.datastore.preferences) }
speech/libs/sherpa-onnx.aar
diff --git a/speech/libs/sherpa-onnx.aar b/speech/libs/sherpa-onnx.aarnew file mode 100644index 0000000000..ac21b7993fBinary files /dev/null and b/speech/libs/sherpa-onnx.aar differ
speech/src/main/AndroidManifest.xml
diff --git a/speech/src/main/AndroidManifest.xml b/speech/src/main/AndroidManifest.xmlindex 916d538b82..6208f41eb5 100644--- a/speech/src/main/AndroidManifest.xml+++ b/speech/src/main/AndroidManifest.xml@@ -33,7 +33,7 @@ (e.g. Translate) gets fully offline transcription through this. --> <service android:name=".service.WhisperRecognitionService"- android:label="@string/app_name"+ android:label="@string/recognition_service_label" android:permission="android.permission.BIND_RECOGNITION_SERVICE" android:exported="true"> <intent-filter>@@ -43,6 +43,33 @@ android:name="android.speech" android:resource="@xml/recognition_service" /> </service>++ <!-- System text-to-speech engine (offline Piper/VITS via sherpa-onnx). Once selected+ as the device's TTS engine, any app using android.speech.tts.TextToSpeech speaks+ fully on-device. -->+ <service+ android:name=".service.PiperTtsService"+ android:label="@string/tts_engine_label"+ android:exported="true">+ <intent-filter>+ <action android:name="android.intent.action.TTS_SERVICE" />+ <category android:name="android.intent.category.DEFAULT" />+ </intent-filter>+ <meta-data+ android:name="android.speech.tts"+ android:resource="@xml/tts_engine" />+ </service>++ <!-- Framework probe run by the TTS settings to discover installed voices. -->+ <activity+ android:name=".tts.CheckVoiceDataActivity"+ android:exported="true"+ android:theme="@android:style/Theme.NoDisplay">+ <intent-filter>+ <action android:name="android.speech.tts.engine.CHECK_TTS_DATA" />+ <category android:name="android.intent.category.DEFAULT" />+ </intent-filter>+ </activity> </application> </manifest>
speech/src/main/java/com/vayunmathur/speech/MainActivity.kt
diff --git a/speech/src/main/java/com/vayunmathur/speech/MainActivity.kt b/speech/src/main/java/com/vayunmathur/speech/MainActivity.ktindex f8626ea337..b8621705f3 100644--- a/speech/src/main/java/com/vayunmathur/speech/MainActivity.kt+++ b/speech/src/main/java/com/vayunmathur/speech/MainActivity.kt@@ -9,6 +9,7 @@ import android.provider.Settings import android.speech.RecognitionListener import android.speech.RecognizerIntent import android.speech.SpeechRecognizer+import android.speech.tts.TextToSpeech import androidx.activity.ComponentActivity import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.setContent@@ -22,6 +23,9 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf@@ -40,8 +44,14 @@ import com.vayunmathur.library.ui.Scaffold import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TopAppBar import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.speech.service.WhisperRecognitionService+import com.vayunmathur.speech.util.PiperModel import com.vayunmathur.speech.util.WhisperModel+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) {@@ -71,13 +81,18 @@ private fun SetupScreen() { ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED }- val modelReady = WhisperModel.isReady(context)+ val ds = remember { DataStoreUtils.getInstance(context) }+ val modelReady = remember(refresh) { WhisperModel.isReady(context) }+ val ttsModelReady = remember(refresh) { PiperModel.isReady(context) }+ val isTtsDefault = remember(refresh) {+ Settings.Secure.getString(context.contentResolver, "tts_default_synth") == context.packageName+ } val micPermission = rememberLauncherForActivityResult( ActivityResultContracts.RequestPermission() ) { refresh++ } - Scaffold(topBar = { TopAppBar(title = { Text("Speech Recognizer") }) }) { padding ->+ Scaffold(topBar = { TopAppBar(title = { Text("MA Speech") }) }) { padding -> Column( modifier = Modifier .fillMaxSize()@@ -87,22 +102,32 @@ private fun SetupScreen() { verticalArrangement = Arrangement.spacedBy(16.dp), ) { Text(- "Offline, on-device speech recognition (Whisper, ~99 languages) for the whole " +- "system. No internet, no Google — works on GrapheneOS.",+ "Offline, on-device speech (Whisper recognition + Piper voice, ~99 languages) for " ++ "the whole system via MA Speech. Models download once, then everything runs with no internet, " ++ "no Google — works on GrapheneOS.", color = MaterialTheme.colorScheme.onSurfaceVariant, ) - // 1) Bundled offline model+ // 1) Download the offline recognition model StepCard( index = 1,- title = "Offline model",+ title = "Speech recognition model", done = modelReady, body = if (modelReady) {- "The Whisper model is bundled with the app and ready — no download, runs fully offline."+ "The Whisper model is installed — recognition runs fully offline." } else {- "Model missing from this build. Run scripts/speech/fetch_whisper_model.sh and reinstall."+ "Download the multilingual Whisper model (~113 MB) once. Runs offline afterward." },- ) {}+ ) {+ if (!modelReady) {+ ModelDownloadButton(+ label = "Download model (~113 MB)",+ progressOf = { WhisperModel.progress(ds) },+ download = { WhisperModel.download(context, ds) },+ onDone = { refresh++ },+ )+ }+ } // 2) Microphone permission StepCard(@@ -126,7 +151,7 @@ private fun SetupScreen() { body = if (isDefault) { "This app is your device's speech recognizer. Other apps' voice input now runs offline." } else {- "Open voice-input settings and choose \"Speech Recognizer\" as the on-device / " ++ "Open voice-input settings and choose \"MA Speech\" as the on-device / " + "voice-input service so other apps (like Translate) use it." }, ) {@@ -141,6 +166,53 @@ private fun SetupScreen() { // 3) Try it TestSection(enabled = hasMic)++ // 4) Download the offline TTS voice+ StepCard(+ index = 4,+ title = "Text-to-speech voice",+ done = ttsModelReady,+ body = if (ttsModelReady) {+ "The offline Piper voice is installed — apps can speak fully offline."+ } else {+ "Download the Piper voice (~64 MB) once. Runs offline afterward."+ },+ ) {+ if (!ttsModelReady) {+ ModelDownloadButton(+ label = "Download voice (~64 MB)",+ progressOf = { PiperModel.progress(ds) },+ download = {+ PiperModel.download(context, ds)+ // Unzip the voice off the main thread before marking done.+ withContext(Dispatchers.IO) { PiperModel.installIfNeeded(context) }+ },+ onDone = { refresh++ },+ )+ }+ }++ // 5) Set as the device's TTS engine+ StepCard(+ index = 5,+ title = "Set as text-to-speech engine",+ done = isTtsDefault,+ body = if (isTtsDefault) {+ "This app is your device's text-to-speech engine. Other apps' read-aloud now runs offline."+ } else {+ "Open text-to-speech settings and choose \"MA Speech\" as the preferred engine."+ },+ ) {+ OutlinedButton(onClick = {+ runCatching { context.startActivity(Intent("com.android.settings.TTS_SETTINGS")) }+ .onFailure {+ runCatching { context.startActivity(Intent(Settings.ACTION_SETTINGS)) }+ }+ refresh+++ }) { Text("Open text-to-speech settings") }+ }++ TtsTestSection(enabled = ttsModelReady) } } }@@ -166,6 +238,40 @@ private fun StepCard( } } +/**+ * A button that runs a suspending model [download] (progress polled from DataStore via+ * [progressOf]) and calls [onDone] when finished so the caller can refresh its "installed"+ * status. Disabled while downloading.+ */+@Composable+private fun ModelDownloadButton(+ label: String,+ progressOf: () -> Float,+ download: suspend () -> Unit,+ onDone: () -> Unit,+) {+ val scope = rememberCoroutineScope()+ var busy by remember { mutableStateOf(false) }+ var pct by remember { mutableIntStateOf(0) }+ LaunchedEffect(busy) {+ while (busy) {+ pct = (progressOf() * 100f).toInt().coerceIn(0, 100)+ delay(500)+ }+ }+ Button(+ enabled = !busy,+ onClick = {+ busy = true+ scope.launch {+ runCatching { download() }+ busy = false+ onDone()+ }+ },+ ) { Text(if (busy) "Downloading… $pct%" else label) }+}+ @Composable private fun TestSection(enabled: Boolean) { val context = LocalContext.current@@ -212,3 +318,47 @@ private fun TestSection(enabled: Boolean) { } } }++@Composable+private fun TtsTestSection(enabled: Boolean) {+ val context = LocalContext.current+ var status by remember { mutableStateOf("") }+ // Hold the engine across recompositions and release it when leaving the screen.+ val engine = remember { mutableStateOf<TextToSpeech?>(null) }+ DisposableEffect(Unit) {+ onDispose { engine.value?.shutdown(); engine.value = null }+ }++ Card(modifier = Modifier.fillMaxWidth()) {+ Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+ Text("Try the voice", fontWeight = FontWeight.Bold)+ Button(+ enabled = enabled,+ onClick = {+ status = "Loading…"+ engine.value?.shutdown()+ // Force OUR engine (by package) so this tests Piper, not the system default.+ var tts: TextToSpeech? = null+ tts = TextToSpeech(+ context,+ { st ->+ if (st == TextToSpeech.SUCCESS) {+ tts?.setLanguage(java.util.Locale.US)+ tts?.speak(+ "Hello, this is the offline Piper voice.",+ TextToSpeech.QUEUE_FLUSH, null, "sample",+ )+ status = ""+ } else {+ status = "Engine failed to start."+ }+ },+ context.packageName,+ )+ engine.value = tts+ },+ ) { Text("Speak sample") }+ if (status.isNotBlank()) Text(status, color = MaterialTheme.colorScheme.primary)+ }+ }+}
speech/src/main/java/com/vayunmathur/speech/service/PiperTtsService.kt
diff --git a/speech/src/main/java/com/vayunmathur/speech/service/PiperTtsService.kt b/speech/src/main/java/com/vayunmathur/speech/service/PiperTtsService.ktnew file mode 100644index 0000000000..22c3bd7cf2--- /dev/null+++ b/speech/src/main/java/com/vayunmathur/speech/service/PiperTtsService.kt@@ -0,0 +1,115 @@+package com.vayunmathur.speech.service++import android.media.AudioFormat+import android.speech.tts.SynthesisCallback+import android.speech.tts.SynthesisRequest+import android.speech.tts.TextToSpeech+import android.speech.tts.TextToSpeechService+import com.vayunmathur.speech.util.PiperEngine+import kotlin.math.roundToInt++/**+ * System text-to-speech engine backed by offline **Piper (VITS)** via sherpa-onnx. Once+ * selected as the device's TTS engine, any app that uses [android.speech.tts.TextToSpeech]+ * (Translate's read-aloud, TalkBack, ebook readers, …) synthesizes fully on-device — no+ * network, no Google.+ *+ * The bundled voice is English (en-US), so we advertise only that; the framework won't route+ * other languages to us. Synthesis streams PCM to the [SynthesisCallback] as sherpa produces+ * it, so audio starts before a long sentence finishes.+ */+class PiperTtsService : TextToSpeechService() {++ private val engine by lazy { PiperEngine(applicationContext) }++ @Volatile private var stopped = false++ override fun onCreate() {+ super.onCreate()+ // Warm the model (extract-on-first-use + load) off the main thread so the first+ // utterance doesn't stall.+ Thread { engine.preload() }.start()+ }++ override fun onDestroy() {+ engine.close()+ super.onDestroy()+ }++ // --- Language support: English (en-US) only. ---++ override fun onIsLanguageAvailable(lang: String?, country: String?, variant: String?): Int =+ when {+ !lang.equals("eng", ignoreCase = true) -> TextToSpeech.LANG_NOT_SUPPORTED+ country.equals("USA", ignoreCase = true) -> TextToSpeech.LANG_COUNTRY_AVAILABLE+ else -> TextToSpeech.LANG_AVAILABLE+ }++ override fun onLoadLanguage(lang: String?, country: String?, variant: String?): Int =+ onIsLanguageAvailable(lang, country, variant)++ override fun onGetLanguage(): Array<String> = arrayOf("eng", "USA", "")++ override fun onStop() {+ stopped = true+ }++ override fun onSynthesizeText(request: SynthesisRequest, callback: SynthesisCallback) {+ stopped = false+ val text = request.charSequenceText?.toString().orEmpty()++ if (!engine.preload()) {+ callback.error()+ return+ }+ val sampleRate = engine.sampleRate()+ if (sampleRate <= 0) {+ callback.error()+ return+ }+ if (text.isBlank()) {+ // Nothing to say, but the contract still wants a well-formed empty stream.+ callback.start(sampleRate, AudioFormat.ENCODING_PCM_16BIT, 1)+ callback.done()+ return+ }++ // Framework rate is a percentage of normal (100 = 1.0×); sherpa's speed is the same+ // multiplier (larger = faster). Clamp to a sane range.+ val speed = (request.speechRate / 100f).coerceIn(0.3f, 3.0f)++ if (callback.start(sampleRate, AudioFormat.ENCODING_PCM_16BIT, 1) != TextToSpeech.SUCCESS) {+ return+ }++ val maxBytes = callback.maxBufferSize+ val ok = engine.synthesize(text, speed) { samples ->+ if (stopped) return@synthesize false+ val pcm = floatsToPcm16(samples)+ var offset = 0+ while (offset < pcm.size) {+ if (stopped) return@synthesize false+ val n = minOf(maxBytes, pcm.size - offset)+ if (callback.audioAvailable(pcm, offset, n) != TextToSpeech.SUCCESS) {+ return@synthesize false+ }+ offset += n+ }+ true+ }++ if (ok || stopped) callback.done() else callback.error()+ }++ /** Convert Piper's float samples ([-1, 1]) to little-endian 16-bit PCM bytes. */+ private fun floatsToPcm16(samples: FloatArray): ByteArray {+ val out = ByteArray(samples.size * 2)+ var i = 0+ for (s in samples) {+ val v = (s.coerceIn(-1f, 1f) * 32767f).roundToInt()+ out[i++] = (v and 0xFF).toByte()+ out[i++] = ((v shr 8) and 0xFF).toByte()+ }+ return out+ }+}
speech/src/main/java/com/vayunmathur/speech/tts/CheckVoiceDataActivity.kt
diff --git a/speech/src/main/java/com/vayunmathur/speech/tts/CheckVoiceDataActivity.kt b/speech/src/main/java/com/vayunmathur/speech/tts/CheckVoiceDataActivity.ktnew file mode 100644index 0000000000..351eb9cb64--- /dev/null+++ b/speech/src/main/java/com/vayunmathur/speech/tts/CheckVoiceDataActivity.kt@@ -0,0 +1,41 @@+package com.vayunmathur.speech.tts++import android.app.Activity+import android.content.Intent+import android.os.Bundle+import android.speech.tts.TextToSpeech+import com.vayunmathur.speech.util.PiperModel++/**+ * Answers the framework's `CHECK_TTS_DATA` probe: the system TTS settings run this before+ * letting the user pick our engine, to learn which voices are installed. We report en-US as+ * available when the bundled Piper voice is present, otherwise as unavailable.+ */+class CheckVoiceDataActivity : Activity() {+ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)++ val available = ArrayList<String>()+ val unavailable = ArrayList<String>()+ if (PiperModel.isReady(this)) available.add(VOICE) else unavailable.add(VOICE)++ val data = Intent().apply {+ putStringArrayListExtra(TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES, available)+ putStringArrayListExtra(TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES, unavailable)+ }+ setResult(+ if (available.isNotEmpty()) {+ TextToSpeech.Engine.CHECK_VOICE_DATA_PASS+ } else {+ TextToSpeech.Engine.CHECK_VOICE_DATA_FAIL+ },+ data,+ )+ finish()+ }++ private companion object {+ // TTS voice identifier: "<ISO3 language>-<ISO3 country>".+ const val VOICE = "eng-USA"+ }+}
speech/src/main/java/com/vayunmathur/speech/util/PiperEngine.kt
diff --git a/speech/src/main/java/com/vayunmathur/speech/util/PiperEngine.kt b/speech/src/main/java/com/vayunmathur/speech/util/PiperEngine.ktnew file mode 100644index 0000000000..6f105b61bc--- /dev/null+++ b/speech/src/main/java/com/vayunmathur/speech/util/PiperEngine.kt@@ -0,0 +1,100 @@+package com.vayunmathur.speech.util++import android.content.Context+import android.util.Log+import com.k2fsa.sherpa.onnx.OfflineTts+import com.k2fsa.sherpa.onnx.OfflineTtsConfig+import com.k2fsa.sherpa.onnx.OfflineTtsModelConfig+import com.k2fsa.sherpa.onnx.OfflineTtsVitsModelConfig+import java.io.File++/**+ * Thin wrapper around sherpa-onnx's [OfflineTts] running an offline **Piper (VITS)** voice.+ * The voice is downloaded at runtime and extracted by [PiperModel] into filesDir (espeak-ng+ * phonemization needs real file paths); this loads it once and reuses it across syntheses.+ * Not thread-safe; drive it from one worker thread (the TTS framework calls+ * [com.vayunmathur.speech.service.PiperTtsService.onSynthesizeText] serially).+ */+class PiperEngine(private val context: Context) {++ private var tts: OfflineTts? = null+ private var loadFailed = false++ /** Load now (e.g. to warm up off the main thread). Returns true if ready. */+ fun preload(): Boolean = ensure()++ /** Native sample rate of the loaded voice (Hz); 0 if not loaded. */+ fun sampleRate(): Int = tts?.sampleRate() ?: 0++ /**+ * Stream synthesis of [text]. [onChunk] receives PCM float samples ([-1, 1]) as they+ * are produced and returns false to abort (e.g. the caller was stopped). Returns true+ * if synthesis ran, false if the engine couldn't load.+ */+ @Synchronized+ fun synthesize(text: String, speed: Float, onChunk: (FloatArray) -> Boolean): Boolean {+ if (!ensure()) return false+ val engine = tts ?: return false+ return try {+ // sherpa returns 1 to keep going, 0 to stop; it also returns the full audio,+ // which we ignore since we've already streamed it out chunk by chunk.+ engine.generateWithCallback(text, /* sid = */ 0, speed) { samples ->+ if (onChunk(samples)) 1 else 0+ }+ true+ } catch (t: Throwable) {+ Log.e(TAG, "synthesize failed", t)+ false+ }+ }++ @Synchronized+ fun close() {+ try {+ tts?.release()+ } catch (_: Throwable) {+ }+ tts = null+ }++ @Synchronized+ private fun ensure(): Boolean {+ tts?.let { return true }+ if (loadFailed) return false+ // Extract the downloaded voice on first use. Don't latch loadFailed if it simply+ // isn't downloaded yet — a later call can succeed once the model arrives.+ if (!PiperModel.installIfNeeded(context)) return false+ return try {+ val dir = PiperModel.voiceDir(context)+ val onnx = PiperModel.onnxFile(context)+ if (onnx == null) {+ Log.e(TAG, "no .onnx voice model in $dir")+ loadFailed = true+ return false+ }+ val config = OfflineTtsConfig(+ model = OfflineTtsModelConfig(+ vits = OfflineTtsVitsModelConfig(+ model = onnx.absolutePath,+ tokens = File(dir, PiperModel.TOKENS).absolutePath,+ dataDir = File(dir, PiperModel.ESPEAK_DATA).absolutePath,+ ),+ numThreads = 2,+ debug = false,+ provider = "cpu",+ ),+ )+ // null AssetManager → load everything from the filesystem paths above.+ tts = OfflineTts(null, config)+ true+ } catch (t: Throwable) {+ Log.e(TAG, "Piper load failed", t)+ loadFailed = true+ false+ }+ }++ companion object {+ private const val TAG = "PiperEngine"+ }+}
speech/src/main/java/com/vayunmathur/speech/util/PiperModel.kt
diff --git a/speech/src/main/java/com/vayunmathur/speech/util/PiperModel.kt b/speech/src/main/java/com/vayunmathur/speech/util/PiperModel.ktnew file mode 100644index 0000000000..f9d2552bea--- /dev/null+++ b/speech/src/main/java/com/vayunmathur/speech/util/PiperModel.kt@@ -0,0 +1,117 @@+package com.vayunmathur.speech.util++import android.content.Context+import android.util.Log+import com.vayunmathur.library.downloadservice.ModelDownloadItem+import com.vayunmathur.library.downloadservice.downloadModels+import com.vayunmathur.library.util.DataStoreUtils+import java.io.File+import java.util.zip.ZipInputStream++/**+ * Runtime-download config for the offline **Piper (VITS)** text-to-speech voice. The voice+ * is a directory tree (the `.onnx` model, `tokens.txt`, and the large `espeak-ng-data/`+ * phonemizer data), so it's fetched as a single `.zip` from the mirror into+ * `getExternalFilesDir()` and extracted once into [voiceDir]; the archive is then deleted.+ * sherpa-onnx loads it from those real file paths (espeak-ng needs real paths — it can't+ * read from the APK, which is why the voice isn't bundled).+ *+ * Mirror layout (zip the voice dir's *contents* — `<voice>.onnx`, `tokens.txt`,+ * `espeak-ng-data/` at the zip root; `scripts/speech/fetch_piper_model.sh` stages it):+ * https://data.vayunmathur.com/models/piper/voice.zip+ */+object PiperModel {+ const val DIR = "piper"+ const val TOKENS = "tokens.txt"+ const val ESPEAK_DATA = "espeak-ng-data"++ private const val BASE = "https://data.vayunmathur.com/models/piper/"+ private const val ARCHIVE = "$DIR/voice.zip"++ /** The single downloadable archive (extracted app-side into [voiceDir]). */+ val FILES: List<ModelDownloadItem> = listOf(+ ModelDownloadItem("${BASE}voice.zip", ARCHIVE, "Piper voice (TTS)"),+ )++ private fun archive(context: Context): File =+ File(context.getExternalFilesDir(null), ARCHIVE)++ /** The extracted voice directory sherpa-onnx loads from. */+ fun voiceDir(context: Context): File =+ File(context.getExternalFilesDir(null), "$DIR/voice")++ fun onnxFile(context: Context): File? =+ voiceDir(context).listFiles { f -> f.name.endsWith(".onnx") }?.firstOrNull()++ /** True once the voice has been extracted and looks complete. */+ fun isExtracted(context: Context): Boolean {+ val dir = voiceDir(context)+ return dir.isDirectory &&+ onnxFile(context) != null &&+ File(dir, TOKENS).exists() &&+ File(dir, ESPEAK_DATA).isDirectory+ }++ /** True if TTS can run now or after extracting an already-downloaded archive. */+ fun isReady(context: Context): Boolean = isExtracted(context) || archive(context).exists()++ /** Download the voice archive if missing; suspends until complete. */+ suspend fun download(context: Context, ds: DataStoreUtils) = downloadModels(context, ds, FILES)++ /** Averaged 0..1 download progress, read from DataStore. */+ fun progress(ds: DataStoreUtils): Float =+ FILES.map { ds.getDouble("progress_${it.fileName}") ?: 0.0 }.average().toFloat()++ /**+ * Ensure the voice is extracted, unzipping the downloaded archive on first use and then+ * deleting it to save space. Returns true if the voice is ready. Safe to call repeatedly.+ */+ @Synchronized+ fun installIfNeeded(context: Context): Boolean {+ if (isExtracted(context)) return true+ val zip = archive(context)+ if (!zip.exists()) return false+ val dir = voiceDir(context)+ // Extract to a temp dir then swap in, so a crash mid-unzip can't leave a half-written+ // voice that looks installed.+ val tmp = File(context.getExternalFilesDir(null), "$DIR/voice.tmp")+ tmp.deleteRecursively()+ return try {+ unzip(zip, tmp)+ dir.deleteRecursively()+ if (!tmp.renameTo(dir)) throw IllegalStateException("rename $tmp -> $dir failed")+ zip.delete()+ isExtracted(context)+ } catch (t: Throwable) {+ Log.e(TAG, "extracting Piper voice failed", t)+ tmp.deleteRecursively()+ // Drop the (possibly corrupt) archive so it re-downloads next time.+ zip.delete()+ false+ }+ }++ /** Unzip [zip] into [outDir], guarding against Zip-Slip path traversal. */+ private fun unzip(zip: File, outDir: File) {+ outDir.mkdirs()+ val root = outDir.canonicalPath + File.separator+ ZipInputStream(zip.inputStream().buffered()).use { zis ->+ while (true) {+ val entry = zis.nextEntry ?: break+ val out = File(outDir, entry.name)+ if (!out.canonicalPath.startsWith(root)) {+ throw SecurityException("Zip entry escapes target dir: ${entry.name}")+ }+ if (entry.isDirectory) {+ out.mkdirs()+ } else {+ out.parentFile?.mkdirs()+ out.outputStream().use { zis.copyTo(it) }+ }+ zis.closeEntry()+ }+ }+ }++ private const val TAG = "PiperModel"+}
speech/src/main/java/com/vayunmathur/speech/util/WhisperEngine.kt
diff --git a/speech/src/main/java/com/vayunmathur/speech/util/WhisperEngine.kt b/speech/src/main/java/com/vayunmathur/speech/util/WhisperEngine.ktindex f00a6f349f..a156ee9ae8 100644--- a/speech/src/main/java/com/vayunmathur/speech/util/WhisperEngine.kt+++ b/speech/src/main/java/com/vayunmathur/speech/util/WhisperEngine.kt@@ -5,29 +5,31 @@ import android.util.Log import com.vayunmathur.ncnn.Whisper /**- * Thin wrapper around the ncnn AAR [Whisper]: loads the bundled whisper-tiny model- * **directly from the APK assets** (via [Whisper]'s AssetManager constructor — no- * extraction) once, lazily, and transcribes 16 kHz mono PCM. Reused across recognition- * sessions by [com.vayunmathur.speech.service.WhisperRecognitionService]. Not- * thread-safe — call [transcribe] from a single worker thread.+ * Thin wrapper around the ncnn AAR [Whisper]: loads the whisper-tiny model from the+ * runtime-downloaded files (see [WhisperModel]) via [Whisper]'s filesystem-directory+ * constructor, once and lazily, and transcribes 16 kHz mono PCM. Reused across recognition+ * sessions by [com.vayunmathur.speech.service.WhisperRecognitionService]. Not thread-safe —+ * call [transcribe] from a single worker thread. */ class WhisperEngine(private val context: Context) { private var whisper: Whisper? = null private var loadFailed = false - /** Whether the bundled model assets are present. */+ /** Whether the downloaded model files are present. */ fun isModelPresent(): Boolean = WhisperModel.isReady(context) - /** Load the model now (e.g. to warm up off the main thread). */- fun preload() { ensure() }+ /** Load the model now (e.g. to warm up off the main thread). Returns true if ready. */+ fun preload(): Boolean = ensure() @Synchronized private fun ensure(): Boolean { whisper?.let { return true } if (loadFailed) return false+ // Don't try to load a partially-downloaded model; wait until all files are present.+ if (!isModelPresent()) return false return try {- val w = Whisper(context.assets, WhisperModel.DIR)+ val w = Whisper(WhisperModel.modelDir(context).absolutePath) if (w.isAvailable) { whisper = w; true } else { w.close(); loadFailed = true; false } } catch (t: Throwable) { Log.e(TAG, "Whisper load failed", t)
speech/src/main/java/com/vayunmathur/speech/util/WhisperModel.kt
diff --git a/speech/src/main/java/com/vayunmathur/speech/util/WhisperModel.kt b/speech/src/main/java/com/vayunmathur/speech/util/WhisperModel.ktindex 682e91c4c2..fb118540ae 100644--- a/speech/src/main/java/com/vayunmathur/speech/util/WhisperModel.kt+++ b/speech/src/main/java/com/vayunmathur/speech/util/WhisperModel.kt@@ -1,21 +1,58 @@ package com.vayunmathur.speech.util import android.content.Context+import com.vayunmathur.library.downloadservice.ModelDownloadItem+import com.vayunmathur.library.downloadservice.downloadModels+import com.vayunmathur.library.util.DataStoreUtils+import java.io.File /**- * The offline **Whisper tiny** (multilingual, ~99 languages) speech model, converted to- * ncnn by nihui, bundled in the app's assets under `assets/`[DIR] and loaded **directly- * from the APK** by the ncnn AAR's `Whisper(assetManager, DIR)` — no extraction. The- * assets are `noCompress` (see build.gradle) so ncnn mmaps them.+ * Runtime-download config for the offline **Whisper-tiny** (multilingual, ~99 languages)+ * ncnn model. The 13 files are fetched from the self-hosted mirror into+ * `getExternalFilesDir()/`[DIR] and loaded from the filesystem by the ncnn AAR's+ * `Whisper(dirPath)` — nothing ships in the APK. *- * The 13 files are committed with the app so the APK bundles them directly (no download).- * `scripts/speech/fetch_whisper_model.sh` can re-fetch them from the nihui release if ever- * needed.+ * Mirror layout (upload the nihui/ncnn-android-whisper "models" release files under these+ * paths; `scripts/speech/fetch_whisper_model.sh` stages them for upload):+ * https://data.vayunmathur.com/models/whisper-tiny/<file> */ object WhisperModel { const val DIR = "whisper-tiny"+ private const val BASE = "https://data.vayunmathur.com/models/whisper-tiny/" - /** True if the bundled model assets are present. */- fun isReady(context: Context): Boolean =- (context.assets.list(DIR)?.size ?: 0) >= 13+ /** The 13 runtime files, SHA-256 pinned (supply-chain mitigation, verified on download). */+ val FILES: List<ModelDownloadItem> = listOf(+ item("whisper_tiny_decoder.ncnn.bin", "8b5be3db26af79c8d0408e7a07affae07e5464af3e9f5cf1eba503b63cab4dec"),+ item("whisper_tiny_decoder.ncnn.param", "371cc62f8ea86d24ee170732e848dfc9a15a16ba7a3e22a175cb3ceefac3757b"),+ item("whisper_tiny_embed_position.ncnn.bin", "02d1ce594b3917847f0cc333337af4999787bae77823d0655fd5df40177a64f9"),+ item("whisper_tiny_embed_position.ncnn.param", "b5fbfba5ea5c294258bf5cb9f4b6704f459099921e2cdbd1dfdef2c0c14085b4"),+ item("whisper_tiny_embed_token.ncnn.bin", "e33c7db8ebb73eafc2cc791ae77b0e710c9cf54bd14321ae28277cb86b0f4968"),+ item("whisper_tiny_embed_token.ncnn.param", "c1917f8b90e81cede6fe8b82cab7d05d7d6461f9ff04ad58932bd7a62ec38627"),+ item("whisper_tiny_encoder.ncnn.bin", "14b8d453780ca0df7971d12134b4826bb6206624e4217236204183f793dae74a"),+ item("whisper_tiny_encoder.ncnn.param", "675a3141db1ed515f1d08d722ddeb31e2a556b1a7baf35c3dd14a2adf575c058"),+ item("whisper_tiny_fbank.ncnn.bin", "2150c30cbbeb6029f52002ffa666c1c72d83dbf53f463cb8462052055806e891"),+ item("whisper_tiny_fbank.ncnn.param", "9ff0d0da904ea62c9c4d1e806f943df31209bb4df36cebb1a3fea955eaca3ac4"),+ item("whisper_tiny_proj_out.ncnn.bin", "e33c7db8ebb73eafc2cc791ae77b0e710c9cf54bd14321ae28277cb86b0f4968"),+ item("whisper_tiny_proj_out.ncnn.param", "428368e792a833f6efa5905c21e977e7c44ee917ed3a826db1ac67fc7a8bb3c7"),+ item("whisper_vocab.txt", "c3e28c60daa5956c08e02a08e82dc6ef4c8882805db4940d59343638234b6c6e"),+ )++ private fun item(name: String, sha256: String) =+ ModelDownloadItem("$BASE$name", "$DIR/$name", "Whisper $name", sha256)++ /** Directory the ncnn `Whisper(dirPath)` loads from. */+ fun modelDir(context: Context): File = File(context.getExternalFilesDir(null), DIR)++ /** True once every model file is present on disk. */+ fun isReady(context: Context): Boolean {+ val root = context.getExternalFilesDir(null) ?: return false+ return FILES.all { File(root, it.fileName).exists() }+ }++ /** Download any missing files (skips present ones); suspends until complete. */+ suspend fun download(context: Context, ds: DataStoreUtils) = downloadModels(context, ds, FILES)++ /** Averaged 0..1 download progress across the files, read from DataStore. */+ fun progress(ds: DataStoreUtils): Float =+ FILES.map { ds.getDouble("progress_${it.fileName}") ?: 0.0 }.average().toFloat() }
speech/src/main/res/values/strings.xml
diff --git a/speech/src/main/res/values/strings.xml b/speech/src/main/res/values/strings.xmlindex ce007154ae..138385aa41 100644--- a/speech/src/main/res/values/strings.xml+++ b/speech/src/main/res/values/strings.xml@@ -1,4 +1,6 @@ <?xml version="1.0" encoding="utf-8"?> <resources>- <string name="app_name">Speech Recognizer</string>+ <string name="app_name">speech</string>+ <string name="tts_engine_label">MA Speech</string>+ <string name="recognition_service_label">MA Speech</string> </resources>
speech/src/main/res/xml/tts_engine.xml
diff --git a/speech/src/main/res/xml/tts_engine.xml b/speech/src/main/res/xml/tts_engine.xmlnew file mode 100644index 0000000000..4b9c6369bd--- /dev/null+++ b/speech/src/main/res/xml/tts_engine.xml@@ -0,0 +1,3 @@+<?xml version="1.0" encoding="utf-8"?>+<tts-engine xmlns:android="http://schemas.android.com/apk/res/android"+ android:settingsActivity="com.vayunmathur.speech.MainActivity" />
translate/src/main/java/com/vayunmathur/translate/ui/TextTranslateScreen.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/ui/TextTranslateScreen.kt b/translate/src/main/java/com/vayunmathur/translate/ui/TextTranslateScreen.ktindex 6927b9d05b..c08be2c8f0 100644--- a/translate/src/main/java/com/vayunmathur/translate/ui/TextTranslateScreen.kt+++ b/translate/src/main/java/com/vayunmathur/translate/ui/TextTranslateScreen.kt@@ -57,6 +57,13 @@ import kotlinx.coroutines.delay /** Debounce window for live translation as the user types (ms). */ private const val TRANSLATE_DEBOUNCE_MS = 400L +/**+ * Mic button phases. TRANSCRIBING exists because the offline recognizer keeps working for+ * a moment after the mic stops; showing it (and ignoring taps) avoids the "stuck on Stop"+ * / double-start / "recognizer busy" confusion.+ */+private enum class MicState { IDLE, LISTENING, TRANSCRIBING }+ /** * Home screen. The SMaLL-100 model (~1.2 GB) is now auto-installed on open via * [com.vayunmathur.library.downloadservice.InitialModelDownloadChecker] in@@ -84,24 +91,27 @@ fun TextTranslateScreen( val speech: SpeechRecognizerEngine = remember(context) { NativeSpeech().takeIf { it.isAvailable() } ?: AndroidSpeechRecognizer(context) }- var listening by remember { mutableStateOf(false) }+ var micState by remember { mutableStateOf(MicState.IDLE) } var speechError by remember { mutableStateOf<String?>(null) } DisposableEffect(speech) { onDispose { speech.destroy() } } fun startListening() { speechError = null- listening = true+ micState = MicState.LISTENING speech.start( languageCode = sourceLang, onPartial = { inputText = it }, onFinal = {- inputText = it- listening = false+ if (it.isNotBlank()) inputText = it+ micState = MicState.IDLE }, onError = { speechError = it- listening = false+ micState = MicState.IDLE },+ // Mic closed; the model is now transcribing. Only advance from LISTENING so a+ // late callback can't resurrect the button after we're already idle.+ onEndOfSpeech = { if (micState == MicState.LISTENING) micState = MicState.TRANSCRIBING }, ) } @@ -137,24 +147,31 @@ fun TextTranslateScreen( ) }, floatingActionButton = {- // While listening the button is a Stop: tap ends capture (stopListening)- // and the recognizer still delivers its last result via onFinal — it does- // not cancel. Idle, it's a Mic that starts a new session.+ // Idle → Mic (starts). Listening → Stop (ends capture; the recognizer still+ // delivers its last result via onFinal — it does not cancel). Transcribing →+ // a spinner that ignores taps, so the user can't double-start or hit "busy". FloatingActionButton( onClick = {- if (listening) {- speech.stop()- } else {- micPermission.launch(Manifest.permission.RECORD_AUDIO)+ when (micState) {+ MicState.LISTENING -> speech.stop()+ MicState.TRANSCRIBING -> {} // busy finishing; ignore taps+ MicState.IDLE -> micPermission.launch(Manifest.permission.RECORD_AUDIO) } },- containerColor = if (listening) {- MaterialTheme.colorScheme.errorContainer- } else {- MaterialTheme.colorScheme.primaryContainer+ containerColor = when (micState) {+ MicState.LISTENING -> MaterialTheme.colorScheme.errorContainer+ MicState.TRANSCRIBING -> MaterialTheme.colorScheme.surfaceVariant+ MicState.IDLE -> MaterialTheme.colorScheme.primaryContainer }, ) {- if (listening) IconStop() else IconMic()+ when (micState) {+ MicState.LISTENING -> IconStop()+ MicState.TRANSCRIBING -> CircularProgressIndicator(+ modifier = Modifier.size(24.dp),+ strokeWidth = 2.dp,+ )+ MicState.IDLE -> IconMic()+ } } }, ) { padding ->@@ -184,9 +201,14 @@ fun TextTranslateScreen( minLines = 4, ) - if (listening) {+ val micStatus = when (micState) {+ MicState.LISTENING -> "Listening…"+ MicState.TRANSCRIBING -> "Transcribing…"+ MicState.IDLE -> null+ }+ micStatus?.let { Text(- text = "Listening…",+ text = it, color = MaterialTheme.colorScheme.primary, fontWeight = FontWeight.Medium, )
translate/src/main/java/com/vayunmathur/translate/util/SpeechRecognizerEngine.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/util/SpeechRecognizerEngine.kt b/translate/src/main/java/com/vayunmathur/translate/util/SpeechRecognizerEngine.ktindex f7ab8e59f5..044ef81fcf 100644--- a/translate/src/main/java/com/vayunmathur/translate/util/SpeechRecognizerEngine.kt+++ b/translate/src/main/java/com/vayunmathur/translate/util/SpeechRecognizerEngine.kt@@ -19,16 +19,20 @@ interface SpeechRecognizerEngine { fun isAvailable(): Boolean /**- * Begin listening for speech in [languageCode] (ISO-639-1, "auto" allowed —- * falls back to the device default). [onPartial] fires repeatedly with the- * best in-progress hypothesis; [onFinal] fires once with the settled text;- * [onError] reports a human-readable failure.+ * Begin listening for speech in [languageCode] (ISO-639-1, "auto" allowed for+ * on-device auto-detect). [onPartial] fires repeatedly with the best in-progress+ * hypothesis; [onEndOfSpeech] fires when capture ends and transcription begins (so+ * the UI can show a "transcribing" state — offline models finish a beat after the+ * mic stops); [onFinal] fires exactly once with the settled text (possibly blank);+ * [onError] reports a human-readable failure. Exactly one of [onFinal]/[onError]+ * is the terminal callback, so a caller can always reset its UI on either. */ fun start( languageCode: String, onPartial: (String) -> Unit, onFinal: (String) -> Unit, onError: (String) -> Unit,+ onEndOfSpeech: () -> Unit = {}, ) /** Stop listening (keeps the engine usable for a later [start]). */@@ -61,6 +65,7 @@ class NativeSpeech : SpeechRecognizerEngine { onPartial: (String) -> Unit, onFinal: (String) -> Unit, onError: (String) -> Unit,+ onEndOfSpeech: () -> Unit, ) { // No offline model shipped; report unavailable so the caller falls back. onError("Offline speech model not installed")@@ -90,27 +95,40 @@ class AndroidSpeechRecognizer(private val context: Context) : SpeechRecognizerEn onPartial: (String) -> Unit, onFinal: (String) -> Unit, onError: (String) -> Unit,+ onEndOfSpeech: () -> Unit, ) { if (!isAvailable()) { onError("Speech recognition unavailable on this device") return }- // Recreate per session so a previous error state never leaks in.- recognizer?.destroy()- val sr = SpeechRecognizer.createSpeechRecognizer(context).also { recognizer = it }-- val locale = if (languageCode == Languages.AUTO.code) {- Locale.getDefault()- } else {- Locale.forLanguageTag(languageCode)- }+ // Reuse a single recognizer across sessions and cancel any prior/finishing one+ // first. Destroying + recreating per session could rebind the service before its+ // last session was cleared, which surfaced as "recognizer busy" on rapid taps;+ // cancel() resets the service's session synchronously before we start a new one.+ val sr = recognizer ?: SpeechRecognizer.createSpeechRecognizer(context).also { recognizer = it }+ try { sr.cancel() } catch (_: Throwable) {}++ // Captured so the listener's onEndOfSpeech() override can call the callback: an+ // unqualified onEndOfSpeech() inside the override would resolve to the override+ // itself (same name + signature) and recurse.+ val notifyEndOfSpeech = onEndOfSpeech val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply { putExtra( RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM, )- putExtra(RecognizerIntent.EXTRA_LANGUAGE, locale.toLanguageTag())+ // For "auto" source, DON'T pin a language: omitting EXTRA_LANGUAGE lets the+ // recognizer auto-detect (the offline Whisper service supports ~99-language+ // auto-detect, and this mirrors the Speech app's own working demo). Forcing+ // the device locale here was the bug — in a translate app you usually speak a+ // language other than your device locale, so Whisper was pinned to the wrong+ // language and returned nothing → "No speech recognized". Only pin when the+ // user explicitly picked a source language.+ if (languageCode != Languages.AUTO.code) {+ val tag = Locale.forLanguageTag(languageCode).toLanguageTag()+ putExtra(RecognizerIntent.EXTRA_LANGUAGE, tag)+ } putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true) putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1) }@@ -120,7 +138,11 @@ class AndroidSpeechRecognizer(private val context: Context) : SpeechRecognizerEn override fun onBeginningOfSpeech() {} override fun onRmsChanged(rmsdB: Float) {} override fun onBufferReceived(buffer: ByteArray?) {}- override fun onEndOfSpeech() {}++ // Capture has ended; an offline model now transcribes before onResults.+ override fun onEndOfSpeech() {+ notifyEndOfSpeech()+ } override fun onError(error: Int) { onError(describeError(error))@@ -130,8 +152,10 @@ class AndroidSpeechRecognizer(private val context: Context) : SpeechRecognizerEn firstResult(partialResults)?.let(onPartial) } + // Always terminal: deliver the settled text (blank if the model returned+ // nothing usable) so the caller can reliably reset its listening state. override fun onResults(results: Bundle?) {- firstResult(results)?.let(onFinal)+ onFinal(firstResult(results).orEmpty()) } override fun onEvent(eventType: Int, params: Bundle?) {}