speech: gate setup on downloads, Whisper plus Supertonic from mirror
- Commit
c20f1a18b9aea182a26a42ae63ea12417e416c6f- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-14 23:55 UTC (2 months ago)
- Parents
e527132
Diff
library/ml/src/main/java/com/vayunmathur/library/ml/WhisperHandle.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/WhisperHandle.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/WhisperHandle.ktindex 1f58ec0bf0..789f8fee2c 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/WhisperHandle.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/WhisperHandle.kt@@ -98,10 +98,14 @@ class WhisperHandle private constructor(private val source: String) : AutoClosea override fun close() { encoder = null decoder = null- OnnxSessions.close("asset:$assetDir/$ENCODER")- OnnxSessions.close("asset:$assetDir/$DECODER")+ OnnxSessions.close(sessionKey(ENCODER))+ OnnxSessions.close(sessionKey(DECODER)) } + private var sessionPrefix: String = ""++ private fun sessionKey(name: String): String = "$sessionPrefix$assetDir/$name"+ override fun toString(): String = "whisper-base from $source" private fun encode(enc: OrtSession, env: OrtEnvironment, mel: FloatArray): OnnxTensor {@@ -295,6 +299,7 @@ class WhisperHandle private constructor(private val source: String) : AutoClosea return instance } instance.assetDir = path+ instance.sessionPrefix = "asset:" instance.special = special.copyOf() instance.languages = languages.copyOf() instance.suppress = suppress.toSet()@@ -305,6 +310,39 @@ class WhisperHandle private constructor(private val source: String) : AutoClosea return instance } + /**+ * The model in a folder on disk, as a downloaded one is.+ *+ * Same arguments as [inAssets]; sessions open from files instead of APK assets.+ */+ fun inDirectory(+ directory: java.io.File,+ special: IntArray,+ languages: IntArray,+ suppress: IntArray,+ suppressAtBegin: IntArray,+ ): WhisperHandle {+ val instance = WhisperHandle(directory.toString())+ if (special.size != SPECIAL_IDS) {+ Log.e(TAG, "${special.size} special ids, not $SPECIAL_IDS")+ return instance+ }+ instance.assetDir = ""+ instance.sessionPrefix = "file:${directory.absolutePath}/"+ instance.special = special.copyOf()+ instance.languages = languages.copyOf()+ instance.suppress = suppress.toSet()+ instance.suppressAtBegin = suppressAtBegin.toSet()+ instance.encoder = OnnxSessions.open(instance.sessionKey(ENCODER)) {+ java.io.File(directory, ENCODER).readBytes()+ }+ instance.decoder = OnnxSessions.open(instance.sessionKey(DECODER)) {+ java.io.File(directory, DECODER).readBytes()+ }+ if (!instance.isAvailable) Log.e(TAG, "cannot open $directory")+ return instance+ }+ /** One 30 s window cannot say more than this; guards against a runaway loop. */ private const val MAX_NEW_TOKENS = 224
speech/src/main/assets/whisper-base/decoder_model_merged_int8.onnx
diff --git a/speech/src/main/assets/whisper-base/decoder_model_merged_int8.onnx b/speech/src/main/assets/whisper-base/decoder_model_merged_int8.onnxdeleted file mode 100644index abbe80534f..0000000000Binary files a/speech/src/main/assets/whisper-base/decoder_model_merged_int8.onnx and /dev/null differ
speech/src/main/assets/whisper-base/encoder_model_int8.onnx
diff --git a/speech/src/main/assets/whisper-base/encoder_model_int8.onnx b/speech/src/main/assets/whisper-base/encoder_model_int8.onnxdeleted file mode 100644index 2738b5f948..0000000000Binary files a/speech/src/main/assets/whisper-base/encoder_model_int8.onnx and /dev/null differ
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 122f02ea91..0fd2d3a54a 100644--- a/speech/src/main/java/com/vayunmathur/speech/MainActivity.kt+++ b/speech/src/main/java/com/vayunmathur/speech/MainActivity.kt@@ -49,8 +49,12 @@ import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.ui.IconArrowDropDown import com.vayunmathur.library.ui.IconCheck import com.vayunmathur.library.ui.rememberPermissionRequest+import com.vayunmathur.library.downloadservice.InitialModelDownloadChecker+import com.vayunmathur.library.downloadservice.ModelDownloadWorker+import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.speech.domain.SupertonicVoices import com.vayunmathur.speech.platform.SupertonicBundle+import com.vayunmathur.speech.platform.SupertonicModel import com.vayunmathur.speech.service.WhisperRecognitionService import com.vayunmathur.speech.util.SpeechSetupActions import com.vayunmathur.speech.util.SpeechSetupUiState@@ -62,9 +66,14 @@ class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge()+ val ds = DataStoreUtils.getInstance(this) setContent { DynamicTheme {- SetupScreen()+ // Both model bundles download on first launch: Supertonic's plans (~395 MB)+ // and Whisper's exports (~77 MB) stay out of the APK to keep it small.+ InitialModelDownloadChecker(ds, SupertonicModel.FILES + WhisperModel.FILES) {+ SetupScreen()+ } } } }
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 50af6fd0cc..2b0ec6b80c 100644--- a/speech/src/main/java/com/vayunmathur/speech/util/WhisperEngine.kt+++ b/speech/src/main/java/com/vayunmathur/speech/util/WhisperEngine.kt@@ -98,7 +98,7 @@ class WhisperEngine(context: Context) { val cfg = try { GenerationConfig( JSONObject(- app.assets.open("${WhisperModel.DIR}/$GEN_CONFIG").use {+ app.assets.open("${WhisperModel.ASSET_DIR}/$GEN_CONFIG").use { it.bufferedReader().readText() }, ),@@ -108,21 +108,29 @@ class WhisperEngine(context: Context) { return false } val tok = try {- app.assets.open("${WhisperModel.DIR}/$VOCAB").use { WhisperTokenizer.load(it) }+ app.assets.open("${WhisperModel.ASSET_DIR}/$VOCAB").use { WhisperTokenizer.load(it) } } catch (t: Throwable) { Log.e(TAG, "cannot read $VOCAB", t) return false }- // Construction never throws: an absent, compressed or malformed asset, a missing- // `libmodelrunner.so`, ids that do not describe this model, and a device without fp16- // compute all come back unavailable.- val handle = WhisperHandle.inAssets(- app.assets,- cfg.special,- cfg.langToId.values.toIntArray(),- cfg.suppress,- cfg.suppressAtBegin,- )+ // Downloads first (77 MB stays out of the APK); bundled assets as fallback.+ val handle = if (WhisperModel.isDownloaded(app)) {+ WhisperHandle.inDirectory(+ WhisperModel.modelDir(app),+ cfg.special,+ cfg.langToId.values.toIntArray(),+ cfg.suppress,+ cfg.suppressAtBegin,+ )+ } else {+ WhisperHandle.inAssets(+ app.assets,+ cfg.special,+ cfg.langToId.values.toIntArray(),+ cfg.suppress,+ cfg.suppressAtBegin,+ )+ } if (!handle.isAvailable) { Log.e(TAG, "cannot bring up $handle") handle.close()
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 94027637d9..64e49d9955 100644--- a/speech/src/main/java/com/vayunmathur/speech/util/WhisperModel.kt+++ b/speech/src/main/java/com/vayunmathur/speech/util/WhisperModel.kt@@ -1,29 +1,71 @@ 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 /**- * Asset location of the offline **whisper-base** (multilingual, ~99 languages) recogniser.+ * Runtime-download config for the offline **whisper-base** (multilingual, ~99 languages)+ * recogniser. *- * These files used to be a 117 MB runtime download of an ncnn conversion, then two int8 ONNX exports- * bundled in the APK. They are now one 70.6 MiB `whisper_base.maml`, read by [WhisperEngine] through- * `:library:ml` — see `scripts/ml/fetch_whisper.py` for how it is rebuilt from- * `openai/whisper-base`'s pinned checkpoint.+ * Two int8 ONNX exports (`onnx-community/whisper-base`, SHA-verified byte-identical to the+ * copies that shipped in the APK) plus the tokenizer and generation config, mirrored under+ * `data.vayunmathur.com/models/whisper/`. At ~77 MB this stays out of the APK to keep it+ * small. The small `vocab.json`/`generation_config.json` still ship in APK assets (they are+ * kilobytes and version with the app). */ object WhisperModel {- const val DIR = "whisper-base"+ private const val BASE = "https://data.vayunmathur.com/models/whisper/"+ const val DIR = "whisper" - /** The graph, relative to [DIR]. The two `generation_config.json`/`vocab.json` sit beside it. */- const val GRAPH = "whisper_base.maml"+ /** Asset directory holding the small config files. */+ const val ASSET_DIR = "whisper-base"++ const val ENCODER = "encoder_model_int8.onnx"+ const val DECODER = "decoder_model_merged_int8.onnx"++ /** The two exports, SHA-256 pinned (byte-identical to upstream). */+ val FILES: List<ModelDownloadItem> = listOf(+ ModelDownloadItem(+ "${BASE}encoder_model_int8.onnx",+ "$DIR/encoder_model_int8.onnx",+ "Whisper encoder",+ "ca6177401f86a2c6b4dc5f7fc02fbca680678906bd0c22f6d89f0b80f124253f",+ ),+ ModelDownloadItem(+ "${BASE}decoder_model_merged_int8.onnx",+ "$DIR/decoder_model_merged_int8.onnx",+ "Whisper decoder",+ "fa3ef9902734ce5ae6f9ef2bdb2ba9a6c4b5785b09f4f420ce036573dc9d090b",+ ),+ )++ /** Directory [com.vayunmathur.library.ml.WhisperHandle.inDirectory] loads from. */+ fun modelDir(context: Context): File = File(context.getExternalFilesDir(null), DIR)++ /** True once both exports are on disk. */+ fun isDownloaded(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)++ const val VOCAB = "vocab.json"+ const val GEN_CONFIG = "generation_config.json" /**- * True if the bundled model is readable. Barring a corrupt install this is always true; it- * exists so the setup screen can report a broken build rather than silently failing to- * transcribe.+ * True if the recogniser can run: downloads present, or the legacy bundled assets. */- fun isReady(context: Context): Boolean = try {- context.assets.list(DIR)?.contains(GRAPH) == true- } catch (_: Throwable) {- false- }+ fun isReady(context: Context): Boolean =+ isDownloaded(context) || try {+ val entries = context.assets.list(ASSET_DIR)?.toList().orEmpty()+ entries.contains(ENCODER) && entries.contains(DECODER)+ } catch (_: Throwable) {+ false+ } }