speech: Piper on :library:ml, and ncnn out of the app
- Commit
61e1adb722647fdb7f115294ee2dad16d39133e3- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-28 02:02 UTC (3 months ago)
- Parents
996df39
Diff
library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.ktindex 7cc215a34b..de5c87c09e 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt@@ -80,6 +80,49 @@ internal object MlNative { width: Int, height: Int, ): String?+ /**+ * Bring up Piper (VITS) from its four `.maml` files plus a phoneme dictionary. Returns 0+ * on failure.+ *+ * Five assets because the model is four networks and a lookup table: the text encoder,+ * the normalising flow and the HiFi-GAN vocoder run on the GPU, and the stochastic+ * duration predictor runs on the CPU because it is a bin search and a quadratic solve per+ * phoneme. [dictionary] is the voice's `<lang>-word_id.bin`, built from espeak-ng on the+ * build machine so nothing on-device needs it.+ *+ * [phonemesWide] and [frames] fix the two compiled shapes: a plan records its command+ * buffer once, so the encoder is built for the longest utterance a request may hold and+ * the flow and vocoder for one chunk. The three scales come from the voice's+ * `config.json`.+ *+ * Freed by [destroyPiper], not [destroy] or [destroyOcr].+ */+ external fun createPiper(+ encoder: ByteArray,+ flow: ByteArray,+ vocoder: ByteArray,+ durations: ByteArray,+ dictionary: ByteArray,+ phonemesWide: Int,+ frames: Int,+ sampleRate: Int,+ noise: Float,+ length: Float,+ durationNoise: Float,+ ): Long+ /**+ * Synthesise [text] and return mono samples in `-1..1`, or null on failure.+ *+ * One call per utterance: the phoneme lookup, the encoder, the duration predictor, the+ * alignment, the flow and the chunked vocoder all happen natively.+ *+ * [speed] above one is faster. An empty array means nothing pronounceable, which is not a+ * failure - a string of emoji should say nothing.+ *+ * Two calls with the same text differ. VITS samples both its durations and its prior, and+ * that is what stops it sounding mechanical.+ */+ external fun synthesize(handle: Long, text: String, speed: Float): FloatArray? /** * Detect faces in [pixels] and return them flattened, nine floats per face.@@ -131,4 +174,12 @@ internal object MlNative { * guesses. */ external fun destroyOcr(handle: Long)+ /**+ * Free Piper's three networks, its duration weights and its dictionary. Exactly once per+ * non-zero handle from [createPiper].+ *+ * A third destroy function rather than one that guesses: the three handle types own+ * different things, and passing one to the wrong destroy is undefined.+ */+ external fun destroyPiper(handle: Long) }
library/ml/src/main/java/com/vayunmathur/library/ml/PiperSynthesizer.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/PiperSynthesizer.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/PiperSynthesizer.ktnew file mode 100644index 0000000000..2984b85de6--- /dev/null+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/PiperSynthesizer.kt@@ -0,0 +1,162 @@+package com.vayunmathur.library.ml++import android.util.Log+import java.io.File++/**+ * A Piper voice's inference settings, from its `config.json`.+ *+ * [noise] and [durationNoise] are what make two readings of the same sentence differ; VITS+ * samples both its prior and its durations. [length] is the speaking rate, above one being+ * slower - note that [PiperSynthesizer.synthesize]'s `speed` is the other way round, because+ * a caller asking to go faster should pass a number above one.+ */+data class PiperConfig(+ val sampleRate: Int,+ val noise: Float = 0.667f,+ val length: Float = 1.0f,+ val durationNoise: Float = 0.8f,+)++/**+ * On-device text-to-speech: Piper (VITS) on the Vulkan compute runtime.+ *+ * Replaces the ncnn `Vits` path. The model is four parts, and where each runs is a+ * deliberate choice rather than a convenience:+ *+ * - **Text encoder**, **normalising flow** and **HiFi-GAN vocoder** are compiled plans on the+ * GPU. Together they are 15 million parameters and effectively all of the arithmetic.+ * - **Stochastic duration predictor** runs on the **CPU**. It is 4% of the parameters and+ * produces one number per phoneme, but its work is a ten-bin search and a quadratic solve+ * per position - data-dependent branching, which is what a GPU is worst at.+ *+ * All four were checked numerically against onnxruntime; see+ * `library/ml/src/main/rust/src/nets/vits_*.rs`.+ *+ * # Phonemes+ *+ * espeak-ng is **not** on the device and never was. `scripts/speech/generate_piper_dict.py`+ * runs it on the build machine to turn a word list into a `<lang>-word_id.bin` lookup table,+ * and that table ships with the voice. A word the table lacks is spelled out letter by letter.+ *+ * # Availability+ *+ * The constructor never throws. [isAvailable] is false when `libmodelrunner.so` is missing for+ * this ABI, when a file is absent, or when the device cannot give us a Vulkan device with fp16+ * compute - and then [synthesize] returns an empty array.+ *+ * # Threading+ *+ * Not thread-safe. A caller must hold a lock across [synthesize] and [close]: the handle is+ * freed by [close] and reading it afterwards is a use-after-free.+ */+class PiperSynthesizer(+ directory: File,+ voice: String,+ config: PiperConfig,+ private val maxPhonemes: Int = DEFAULT_MAX_PHONEMES,+ chunkFrames: Int = DEFAULT_CHUNK_FRAMES,+) : AutoCloseable {+ private var handle: Long = 0L++ /** The voice's output rate, so a caller cannot play it at the wrong pitch. */+ val sampleRate: Int = config.sampleRate++ init {+ handle = if (!MlNative.isAvailable) {+ 0L+ } else {+ try {+ val encoder = read(directory, "${voice}_enc_p.maml")+ val flow = read(directory, "${voice}_flow.maml")+ val vocoder = read(directory, "${voice}_dec.maml")+ val durations = read(directory, "${voice}_dp.maml")+ val dictionary = dictionaryOf(directory)+ MlNative.createPiper(+ encoder,+ flow,+ vocoder,+ durations,+ dictionary,+ maxPhonemes,+ chunkFrames,+ config.sampleRate,+ config.noise,+ config.length,+ config.durationNoise,+ )+ } catch (e: Throwable) {+ Log.e(TAG, "cannot open the Piper voice in $directory", e)+ 0L+ }+ }+ }++ /** True if all four networks came up and the dictionary parsed. */+ val isAvailable: Boolean get() = handle != 0L++ /**+ * Synthesise [text] at [speed], where above one is faster.+ *+ * Returns an empty array when there is nothing pronounceable, when the engine is+ * unavailable, or when the pass failed - all three are "no audio" to a caller, and the+ * reason is in logcat under `ModelRunner`.+ *+ * Long text should be split into sentences first: the encoder is compiled for+ * [maxPhonemes] and a longer utterance is refused rather than truncated, because+ * truncating would silently drop the end of a paragraph.+ */+ fun synthesize(text: String, speed: Float = 1.0f): FloatArray {+ if (handle == 0L || text.isBlank()) return FloatArray(0)+ return MlNative.synthesize(handle, text, speed) ?: FloatArray(0)+ }++ /** Free all four networks. Idempotent. */+ override fun close() {+ val live = handle+ handle = 0L+ if (live != 0L) MlNative.destroyPiper(live)+ }++ private companion object {+ private const val TAG = "PiperSynthesizer"++ /**+ * Phonemes the encoder is compiled for.+ *+ * Attention is quadratic in this, but the arena at 400 phonemes measured 2.10 MiB, so+ * the ceiling is set by how long a sentence a caller may pass rather than by memory.+ * 400 phonemes is a long sentence; a paragraph should be split.+ */+ const val DEFAULT_MAX_PHONEMES = 400++ /**+ * Latent frames per vocoder pass, matching `post::speech::CHUNK_FRAMES`.+ *+ * The vocoder's arena grows linearly with the utterance - 7.37 MiB per second of audio+ * - so it runs in chunks. The overlap is exact rather than approximate: the network is+ * convolutional with a bounded receptive field, so every kept sample is identical to+ * what a whole-utterance pass would have produced.+ */+ const val DEFAULT_CHUNK_FRAMES = 128++ fun read(directory: File, name: String): ByteArray {+ val file = File(directory, name)+ require(file.isFile) { "$name is missing from $directory" }+ return file.readBytes()+ }++ /**+ * The voice's `*-word_id.bin`, whatever language it is for.+ *+ * Matched by suffix rather than by name: a voice bundle carries its own language's+ * dictionary, and older bundles also carry the English one for compatibility. Either+ * works, so the first match wins.+ */+ fun dictionaryOf(directory: File): ByteArray {+ val found = directory.listFiles()?.firstOrNull { it.name.endsWith("-word_id.bin") }+ requireNotNull(found) { "no *-word_id.bin in $directory" }+ return found.readBytes()+ }+ }+}
scripts/speech/fetch_piper_model.sh
diff --git a/scripts/speech/fetch_piper_model.sh b/scripts/speech/fetch_piper_model.shindex d4b3ba2481..9ea4ee15cd 100755--- a/scripts/speech/fetch_piper_model.sh+++ b/scripts/speech/fetch_piper_model.sh@@ -1,44 +1,52 @@ #!/usr/bin/env bash #-# Stage an offline Piper (VITS) voice, in ncnn format, as a single zip for the model+# Stage an offline Piper (VITS) voice, in .maml format, 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/<archive>.zip # e.g. voice3.zip (en) or de-low.zip, fr-low.zip … and extracts it (see PiperVoiceRegistry). # # The zip must contain the voice's CONTENTS at its root:-# <voice>_enc_p.ncnn.{param,bin} text encoder-# <voice>_dp.ncnn.{param,bin} duration predictor-# <voice>_flow.ncnn.{param,bin}-# <voice>_dec.ncnn.{param,bin} HiFi-GAN vocoder-# <voice>_emb_g.ncnn.{param,bin} multi-speaker voices only-# <lang>-word_id.bin grapheme-to-phoneme dictionary (en-word_id.bin, de-word_id.bin…)+# <voice>_enc_p.maml text encoder (graph 8)+# <voice>_dp.maml duration predictor (graph 10, read on the CPU)+# <voice>_flow.maml normalising flow (graph 9)+# <voice>_dec.maml HiFi-GAN vocoder (graph 7)+# <lang>-word_id.bin grapheme-to-phoneme dictionary (en-word_id.bin, de-word_id.bin) # config.json sample rate + inference scales #-# This replaces the old sherpa-onnx path: TTS now runs on ncnn via-# com.vayunmathur.ncnn.Vits, so there is no .onnx, no tokens.txt and no espeak-ng-data/.+# TTS runs on :library:ml, our own Vulkan compute runtime, so there is no .onnx on device, no+# tokens.txt and no espeak-ng-data/. espeak-ng is still needed HERE, to build the dictionary.+#+# Multi-speaker voices are NOT supported: they need an `emb_g` embedding network that is not+# converted, and every voice in the registry is single-speaker. # # ----------------------------------------------------------------------------# Converting a checkpoint to the five ncnn nets (do this once, by hand)+# Converting a voice to the four .maml files (once per voice) # ----------------------------------------------------------------------------# 1. git clone https://github.com/OHF-Voice/piper1-gpl-# cd piper1-gpl && git checkout 113931937cf235fc881afd1ca4be209bc6919bc7-# 2. curl -fLO https://raw.githubusercontent.com/nihui/ncnn-android-piper/master/piper1-gpl.patch-# git apply piper1-gpl.patch-# 3. python3 -m venv .venv && source .venv/bin/activate-# python3 -m pip install -e '.[train]' && pip install -U pnnx-# 4. Grab <voice>.ckpt and config.json from-# https://huggingface.co/datasets/rhasspy/piper-checkpoints-# e.g. de/de_DE/thorsten/medium, fr/fr_FR/siwis/medium,-# en/en_US/lessac/low (true 16k low)-# 5. curl -fLO https://raw.githubusercontent.com/nihui/ncnn-android-piper/master/export_ncnn.py-# python3 export_ncnn.py <voice>.ckpt+# Unlike the ncnn path this needs no checkpoint, no patch and no pnnx. Piper publishes ONNX per+# voice and all four modules come out of that one file, because the export keeps its Torch+# module paths and maml_convert.py slices by them (see MODULES in that script):+#+# V=en_GB-alan-low+# B=https://huggingface.co/rhasspy/piper-voices/resolve/main/en/en_GB/alan/low+# curl -fLO $B/$V.onnx && curl -fLO $B/$V.onnx.json+# python3 scripts/ml/maml_convert.py $V.onnx --graph vits_enc -o ${V}_enc_p.maml+# python3 scripts/ml/maml_convert.py $V.onnx --graph vits_dp -o ${V}_dp.maml+# python3 scripts/ml/maml_convert.py $V.onnx --graph vits_flow -o ${V}_flow.maml+# python3 scripts/ml/maml_convert.py $V.onnx --graph vits_dec -o ${V}_dec.maml+# cp $V.onnx.json config.json+#+# The four together are about 31 MB against the 63 MB fp32 ONNX. #-# Then point this script at the directory holding the .ncnn.* files and config.json.+# Each graph has a pinned layer-table digest. A voice whose export differs structurally fails+# the digest rather than converting into something the Rust misreads - if that happens the Rust+# forward pass needs updating, not the pin.+#+# Then point this script at the directory holding the .maml files and config.json. # # --------------------------------------------------------------------------- # ./scripts/speech/fetch_piper_model.sh <converted-dir> [word-list] [lang] [espeak-voice] [quality] [archive-name] #-# <converted-dir> dir with *.ncnn.param/bin and config.json (required)+# <converted-dir> dir with the four *.maml files and config.json (required) # [word-list] file with one word per line (optional, auto-fetched for en) # [lang] ISO-639-1 code, e.g. en, de, fr (default: en) # [espeak-voice] espeak-ng voice for dict, e.g. en-us, de, fr (default: lang)@@ -62,7 +70,7 @@ if [ ! -f settings.gradle.kts ]; then exit 1 fi if [ -z "$SRC" ] || [ ! -d "$SRC" ]; then- echo "Usage: $0 <dir with *.ncnn.param/bin and config.json> [word-list] [lang] [espeak-voice] [quality] [archive]" >&2+ echo "Usage: $0 <dir with *.maml and config.json> [word-list] [lang] [espeak-voice] [quality] [archive]" >&2 echo " e.g. $0 /tmp/de_DE-thorsten-medium /tmp/de-words.txt de de low de-low.zip" >&2 exit 1 fi@@ -96,12 +104,12 @@ TMP="$(mktemp -d)" trap 'rm -rf "$TMP"' EXIT # Identify the voice from the encoder, the same way Vits and PiperModel do.-ENC="$(find "$SRC" -maxdepth 1 -name '*_enc_p.ncnn.param' -print -quit)"+ENC="$(find "$SRC" -maxdepth 1 -name '*_enc_p.maml' -print -quit)" if [ -z "$ENC" ]; then- echo "No *_enc_p.ncnn.param in $SRC — did export_ncnn.py run?" >&2+ echo "No *_enc_p.maml in $SRC - did maml_convert.py run?" >&2 exit 1 fi-VOICE="$(basename "$ENC" _enc_p.ncnn.param)"+VOICE="$(basename "$ENC" _enc_p.maml)" echo "Voice: $VOICE lang=$LANG_CODE espeak=$ESPEAK_VOICE quality=$QUALITY dict=$DICT_FILE archive=$ARCHIVE_NAME" if [ ! -f "$SRC/config.json" ]; then@@ -109,17 +117,12 @@ if [ ! -f "$SRC/config.json" ]; then exit 1 fi -# _emb_g is only present on multi-speaker voices, so it is copied if it exists but not required.+# Four files, one per module, and all four are required. There is no _emb_g: a multi-speaker+# voice needs a speaker-embedding network that is not converted, and PiperEngine refuses one. for net in _enc_p _dp _flow _dec; do- for ext in param bin; do- f="$SRC/${VOICE}${net}.ncnn.${ext}"- [ -f "$f" ] || { echo "Missing $f" >&2; exit 1; }- cp "$f" "$TMP/"- done-done-for ext in param bin; do- f="$SRC/${VOICE}_emb_g.ncnn.${ext}"- [ -f "$f" ] && cp "$f" "$TMP/"+ f="$SRC/${VOICE}${net}.maml"+ [ -f "$f" ] || { echo "Missing $f" >&2; exit 1; }+ cp "$f" "$TMP/" done cp "$SRC/config.json" "$TMP/"
speech/build.gradle.kts
diff --git a/speech/build.gradle.kts b/speech/build.gradle.ktsindex 0139b7f9c9..40f4623795 100644--- a/speech/build.gradle.kts+++ b/speech/build.gradle.kts@@ -18,15 +18,20 @@ android { androidResources { // ORT mmaps the model out of the APK; a deflated asset would have to be inflated to // a 40 MB heap buffer first. Storing them uncompressed costs nothing on download size- // either — int8 weights are already incompressible.+ // either - int8 weights are already incompressible. noCompress += "onnx"+ // Voices are downloaded rather than bundled, so no .maml sits in this APK. The entry+ // is here for the same reason as `onnx`: if a voice is ever bundled, fp16 weights+ // should not be deflated only to be inflated straight back.+ noCompress += "maml" } }- dependencies {- // Text-to-speech (Piper/VITS) runs in the ncnn AAR via com.vayunmathur.ncnn.Vits, which- // is filesystem-only, so voices are extracted to disk before use.- implementation(libs.ncnn.android)+ // Text-to-speech is Piper (VITS) on :library:ml, our own Vulkan compute runtime. Four+ // networks per voice: the text encoder, the flow and the HiFi-GAN vocoder are compiled+ // plans on the GPU, and the stochastic duration predictor runs on the CPU because it is a+ // bin search and a quadratic solve per phoneme. Voices are extracted to disk before use.+ implementation(project(":library:ml")) // Speech-to-text is whisper-tiny int8 ONNX (bundled in assets, see WhisperOnnxEngine). // It is not ncnn: onnx2ncnn has no DynamicQuantizeLinear/MatMulInteger/ConvInteger
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.ktindex 59e06324f5..afec2c9922 100644--- a/speech/src/main/java/com/vayunmathur/speech/service/PiperTtsService.kt+++ b/speech/src/main/java/com/vayunmathur/speech/service/PiperTtsService.kt@@ -14,8 +14,8 @@ import java.util.Locale import kotlin.math.roundToInt /**- * System text-to-speech engine backed by offline **Piper (VITS)** running on ncnn- * ([com.vayunmathur.ncnn.Vits]). Once selected as the device's TTS engine, any app+ * System text-to-speech engine backed by offline **Piper (VITS)** running on the Vulkan+ * compute runtime in `:library:ml`. 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. *
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.ktindex 4f51b3a58c..dff4603b4d 100644--- a/speech/src/main/java/com/vayunmathur/speech/util/PiperEngine.kt+++ b/speech/src/main/java/com/vayunmathur/speech/util/PiperEngine.kt@@ -2,13 +2,15 @@ package com.vayunmathur.speech.util import android.content.Context import android.util.Log-import com.vayunmathur.ncnn.Vits+import com.vayunmathur.library.ml.PiperConfig+import com.vayunmathur.library.ml.PiperSynthesizer+import org.json.JSONObject import java.io.File /**- * Wrapper around the ncnn AAR's [Vits] running offline **Piper (VITS)** voices.+ * Wrapper around [PiperSynthesizer], which runs offline **Piper (VITS)** voices on the Vulkan *- * The original implementation held a single [Vits] instance (en-US Amy medium,+ * compute runtime in `:library:ml`. The original implementation held a single ncnn `Vits` * 22050 Hz) with a `loadFailed` latch. After the multilingual expansion we keep a * bounded LRU cache (max 2 voices, ~50-100 MB per instance on arm64-v8a) keyed by * [PiperVoiceDef.id] so switching languages doesn't pay a cold-load each time and@@ -27,8 +29,8 @@ import java.io.File */ class PiperEngine(private val context: Context) { - /** LRU cache: voice id -> loaded Vits, access-order for eviction. */- private val cache = LinkedHashMap<String, Vits>(2, 0.75f, true)+ /** LRU cache: voice id -> loaded synthesiser, access-order for eviction. */+ private val cache = LinkedHashMap<String, PiperSynthesizer>(2, 0.75f, true) private val failed = mutableMapOf<String, Boolean>() fun preload(): Boolean = ensure()@@ -41,13 +43,13 @@ class PiperEngine(private val context: Context) { /** Native sample rate of the default loaded voice (Hz); 0 if not loaded. */ fun sampleRate(): Int { val defId = PiperVoiceRegistry.DEFAULT.id- return cache[defId]?.sampleRate() ?: cache.values.firstOrNull()?.sampleRate() ?: 0+ return cache[defId]?.sampleRate ?: cache.values.firstOrNull()?.sampleRate ?: 0 } /** Sample rate of a specific loaded voice, 0 if not in cache. */ fun sampleRate(voiceIdOrCode: String): Int { val def = resolveDef(voiceIdOrCode) ?: return 0- return cache[def.id]?.sampleRate() ?: 0+ return cache[def.id]?.sampleRate ?: 0 } @Synchronized@@ -60,7 +62,7 @@ class PiperEngine(private val context: Context) { val def = resolveDef(voiceIdOrCode) ?: return false val engine = cache[def.id] ?: return false return try {- val samples = engine.generate(text, def.speakerId, speed)+ val samples = engine.synthesize(text, speed) if (samples.isEmpty()) return true var offset = 0 while (offset < samples.size) {@@ -139,9 +141,12 @@ class PiperEngine(private val context: Context) { failed[id] = true return false }- val engine = Vits(dir.absolutePath)+ val engine = open(dir) ?: run {+ failed[id] = true+ return false+ } if (!engine.isAvailable) {- Log.e(TAG, "Vits could not load the voice in $dir for $id")+ Log.e(TAG, "the runtime could not load the voice in $dir for $id") try { engine.close() } catch (_: Throwable) {} failed[id] = true return false@@ -163,6 +168,61 @@ class PiperEngine(private val context: Context) { } } + /**+ * Build a synthesiser from a voice directory.+ *+ * The bundle names its four networks `<voice>_{enc_p,dp,flow,dec}.maml`, so the prefix is+ * recovered from whichever encoder is present rather than reconstructed from the registry+ * id - the two have diverged before, which is what the `voiceDirForDef` fallbacks below+ * exist to survive.+ *+ * Returns null, having logged, when the directory is not a voice.+ */+ private fun open(dir: File): PiperSynthesizer? {+ val encoder = dir.listFiles()?.firstOrNull { it.name.endsWith(ENCODER_SUFFIX) }+ if (encoder == null) {+ Log.e(TAG, "no *$ENCODER_SUFFIX in $dir")+ return null+ }+ val voice = encoder.name.removeSuffix(ENCODER_SUFFIX)+ val config = readConfig(dir) ?: return null+ if (config.second > 1) {+ // A multi-speaker voice also ships an `emb_g` network, which is not converted:+ // every voice in the registry is single-speaker. Loading one anyway would speak+ // in whichever voice the embedding defaulted to.+ Log.e(TAG, "$voice has ${config.second} speakers; only single-speaker voices run")+ return null+ }+ return PiperSynthesizer(dir, voice, config.first)+ }++ /**+ * The voice's sample rate, scales and speaker count from its `config.json`.+ *+ * The rate is not defaulted: a voice played at the wrong rate is intelligible but+ * wrongly pitched, which is worse than refusing to load it.+ */+ private fun readConfig(dir: File): Pair<PiperConfig, Int>? = try {+ val json = JSONObject(File(dir, "config.json").readText())+ val audio = json.optJSONObject("audio")+ val rate = audio?.optInt("sample_rate", 0) ?: 0+ if (rate <= 0) {+ Log.e(TAG, "config.json in $dir has no audio.sample_rate")+ return null+ }+ val inference = json.optJSONObject("inference")+ val config = PiperConfig(+ sampleRate = rate,+ noise = inference?.optDouble("noise_scale", 0.667)?.toFloat() ?: 0.667f,+ length = inference?.optDouble("length_scale", 1.0)?.toFloat() ?: 1.0f,+ durationNoise = inference?.optDouble("noise_w", 0.8)?.toFloat() ?: 0.8f,+ )+ config to json.optInt("num_speakers", 1)+ } catch (t: Throwable) {+ Log.e(TAG, "cannot read config.json in $dir", t)+ null+ }+ private fun resolveDef(voiceIdOrCode: String): PiperVoiceDef? { if (voiceIdOrCode.isBlank()) return PiperVoiceRegistry.DEFAULT PiperVoiceRegistry.resolve(@@ -194,7 +254,7 @@ class PiperEngine(private val context: Context) { val bcpRoot = File(vRoot, def.bcp47) if (bcpRoot.isDirectory) { bcpRoot.listFiles()?.firstOrNull { child ->- child.isDirectory && child.listFiles()?.any { it.name.endsWith("_enc_p.ncnn.param") } == true+ child.isDirectory && child.listFiles()?.any { it.name.endsWith("_enc_p.maml") } == true }?.let { return it } } // Broader search: any BCP-47 starting with code@@ -203,7 +263,7 @@ class PiperEngine(private val context: Context) { if (!bcpDir.name.equals(def.bcp47, ignoreCase = true) && !bcpDir.name.lowercase().startsWith(def.code.lowercase())) return@forEach bcpDir.listFiles()?.firstOrNull { child ->- child.isDirectory && child.listFiles()?.any { it.name.endsWith("_enc_p.ncnn.param") } == true+ child.isDirectory && child.listFiles()?.any { it.name.endsWith("_enc_p.maml") } == true }?.let { return it } } }@@ -220,5 +280,8 @@ class PiperEngine(private val context: Context) { companion object { private const val TAG = "PiperEngine" private const val MAX_CACHED = 2++ /** How the bundle names the text encoder, and so how the voice prefix is found. */+ private const val ENCODER_SUFFIX = "_enc_p.maml" } }
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.ktindex d7ba8ce4fe..0057d77944 100644--- a/speech/src/main/java/com/vayunmathur/speech/util/PiperModel.kt+++ b/speech/src/main/java/com/vayunmathur/speech/util/PiperModel.kt@@ -26,7 +26,7 @@ object PiperModel { const val DICT = "en-word_id.bin" const val CONFIG = "config.json" - private const val ENCODER_SUFFIX = "_enc_p.ncnn.param"+ private const val ENCODER_SUFFIX = "_enc_p.maml" private val REQUIRED_NETS = listOf("_enc_p", "_dp", "_flow", "_dec") private const val BASE = PiperVoiceRegistry.BASE const val REMOTE_ARCHIVE = PiperVoiceRegistry.LEGACY_REMOTE_ARCHIVE@@ -87,8 +87,7 @@ object PiperModel { val enc = files.firstOrNull { it.name.endsWith(ENCODER_SUFFIX) } ?: return@let false val pref = enc.name.removeSuffix(ENCODER_SUFFIX) REQUIRED_NETS.all { net ->- File(legacyDir, "$pref$net.ncnn.param").exists() &&- File(legacyDir, "$pref$net.ncnn.bin").exists()+ File(legacyDir, "$pref$net.maml").exists() } && dictFile.exists() && File(legacyDir, CONFIG).exists() } catch (_: Throwable) { false
speech/src/main/java/com/vayunmathur/speech/util/PiperVoiceRegistry.kt
diff --git a/speech/src/main/java/com/vayunmathur/speech/util/PiperVoiceRegistry.kt b/speech/src/main/java/com/vayunmathur/speech/util/PiperVoiceRegistry.ktindex cadfaf3b97..f18786629a 100644--- a/speech/src/main/java/com/vayunmathur/speech/util/PiperVoiceRegistry.kt+++ b/speech/src/main/java/com/vayunmathur/speech/util/PiperVoiceRegistry.kt@@ -69,7 +69,7 @@ object PiperVoiceRegistry { const val LEGACY_REMOTE_ARCHIVE = "voice3.zip" const val BASE = "https://data.vayunmathur.com/models/piper/" - private const val ENCODER_SUFFIX = "_enc_p.ncnn.param"+ private const val ENCODER_SUFFIX = "_enc_p.maml" private const val CONFIG = "config.json" private val REQUIRED_NETS = listOf("_enc_p", "_dp", "_flow", "_dec") @@ -815,8 +815,7 @@ object PiperVoiceRegistry { val enc = dir.listFiles()?.firstOrNull { it.name.endsWith(ENCODER_SUFFIX) } ?: return false val prefix = enc.name.removeSuffix(ENCODER_SUFFIX) val netsOk = REQUIRED_NETS.all { net ->- File(dir, "${prefix}${net}.ncnn.param").exists() &&- File(dir, "${prefix}${net}.ncnn.bin").exists()+ File(dir, "${prefix}${net}.maml").exists() } if (!netsOk) return false if (!File(dir, CONFIG).exists()) return false@@ -867,8 +866,7 @@ object PiperVoiceRegistry { val enc = files.firstOrNull { it.name.endsWith(ENCODER_SUFFIX) } ?: return false val prefix = enc.name.removeSuffix(ENCODER_SUFFIX) val netsOk = REQUIRED_NETS.all { net ->- File(dir, "${prefix}${net}.ncnn.param").exists() &&- File(dir, "${prefix}${net}.ncnn.bin").exists()+ File(dir, "${prefix}${net}.maml").exists() } return netsOk && File(dir, CONFIG).exists() }