speech: replace sherpa-onnx with ncnn VITS
- Commit
cc4c41d470305a2655d477dd26840844b42850be- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-02 16:12 UTC (4 months ago)
- Parents
7a65950
Diff
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 493c0dec8e..6ce70c106c 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -111,7 +111,7 @@ appauth = "0.11.1" # Own libraries (vayun-mathur, via JitPack) stockfishLibrary = "1.1.0"-ncnnAndroid = "1.6.1"+ncnnAndroid = "1.7.0" # Testing junit = "4.13.2"
proguard-rules.pro
diff --git a/proguard-rules.pro b/proguard-rules.proindex d38735dfcb..0923b23e67 100644--- a/proguard-rules.pro+++ b/proguard-rules.pro@@ -78,15 +78,6 @@ -keep class com.vayunmathur.ncnn.** { *; } -dontwarn com.vayunmathur.ncnn.** -# sherpa-onnx (vendored AAR in speech/libs, offline Piper TTS in :speech) — as above.-# libsherpa-onnx-jni.so FindClass-es com/k2fsa/sherpa/onnx/{GeneratedAudio,WaveData,-# DenoisedAudio,OfflineRecognizerResult,OnlineRecognizerResult,AudioEvent,SpeechSegment,-# KeywordSpotterResult,OfflineSpeakerDiarizationSegment} and builds them from native code,-# so their constructors have no Java-visible caller for R8 to see and get stripped. The-# AAR's bundled proguard.txt is empty (0 bytes), so nothing keeps them but this.--keep class com.k2fsa.sherpa.onnx.** { *; }--dontwarn com.k2fsa.sherpa.onnx.**- # Stockfish (com.github.vayun-mathur:Stockfish-Library, used by :games:chess) — the # native libstockfish.so calls back into Kotlin via JNI. nativeSetOutputCallback looks # up Stockfish$OutputCallback.onOutput(String) by name via GetMethodID, and the lambda
scripts/speech/fetch_piper_model.sh
diff --git a/scripts/speech/fetch_piper_model.sh b/scripts/speech/fetch_piper_model.shindex 41e60bf28f..194294157d 100755--- a/scripts/speech/fetch_piper_model.sh+++ b/scripts/speech/fetch_piper_model.sh@@ -1,45 +1,122 @@ #!/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+# Stage an offline Piper (VITS) voice, in ncnn 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/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/.+# <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+# en-word_id.bin grapheme-to-phoneme dictionary+# config.json sample rate + inference scales #-# Voices: https://github.com/k2-fsa/sherpa-onnx/releases/tag/tts-models (vits-piper-*)+# 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/. #-# ./scripts/speech/fetch_piper_model.sh # amy-low (~64 MB)-# ./scripts/speech/fetch_piper_model.sh vits-piper-en_US-kristin-medium+# ---------------------------------------------------------------------------+# Converting a checkpoint to the five ncnn nets (do this once, by hand)+# ---------------------------------------------------------------------------+# 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+# 5. curl -fLO https://raw.githubusercontent.com/nihui/ncnn-android-piper/master/export_ncnn.py+# python3 export_ncnn.py <voice>.ckpt #+# Then point this script at the directory holding the .ncnn.* files and config.json.+#+# ---------------------------------------------------------------------------+# ./scripts/speech/fetch_piper_model.sh <converted-dir> [word-list]+# --------------------------------------------------------------------------- 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"+SRC="${1:-}"+WORDS="${2:-}" 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+if [ -z "$SRC" ] || [ ! -d "$SRC" ]; then+ echo "Usage: $0 <dir with *.ncnn.param/bin and config.json> [word-list]" >&2+ exit 1+fi command -v zip >/dev/null || { echo "'zip' is required." >&2; exit 1; }+command -v espeak-ng >/dev/null || {+ echo "'espeak-ng' is required to build the phoneme dictionary (build-time only;" >&2+ echo "it is NOT shipped on-device). brew install espeak-ng" >&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+# 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)"+if [ -z "$ENC" ]; then+ echo "No *_enc_p.ncnn.param in $SRC — did export_ncnn.py run?" >&2+ exit 1+fi+VOICE="$(basename "$ENC" _enc_p.ncnn.param)"+echo "Voice: $VOICE"++if [ ! -f "$SRC/config.json" ]; then+ echo "config.json missing from $SRC (needed for the sample rate and phoneme_id_map)." >&2+ exit 1+fi++# _emb_g is only present on multi-speaker voices, so it is copied if it exists but not required.+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/"+done+cp "$SRC/config.json" "$TMP/"++# Phoneme dictionary. Without a word list, fetch CMUdict and strip it to bare words.+if [ -z "$WORDS" ]; then+ echo "Fetching CMUdict for the word list..."+ curl -fL https://raw.githubusercontent.com/Alexir/CMUdict/master/cmudict-0.7b \+ -o "$TMP/cmudict.txt"+ # Drop ;;; comments, take column 1, drop (2)/(3) pronunciation variants, keep+ # alphabetic words only (punctuation entries like !EXCLAMATION-POINT are noise here).+ LC_ALL=C grep -v '^;;;' "$TMP/cmudict.txt" \+ | awk '{print $1}' \+ | sed 's/([0-9]*)$//' \+ | LC_ALL=C grep -E "^[A-Za-z'-]+$" \+ | sort -u > "$TMP/words.txt"+ WORDS="$TMP/words.txt"+fi+echo "Word list: $WORDS ($(wc -l < "$WORDS" | tr -d ' ') lines)"++./scripts/speech/generate_piper_dict.py \+ --config "$TMP/config.json" \+ --words "$WORDS" \+ --voice en-us \+ --out "$TMP/en-word_id.bin" 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" . )+# Zip the CONTENTS (not the wrapping folder) so entries sit at the zip root.+( cd "$TMP" && rm -f cmudict.txt words.txt && zip -r -q -X "${ABS_DEST}/voice.zip" . ) echo echo "Staged ${DEST}/voice.zip" du -sh "${ABS_DEST}/voice.zip"+shasum -a 256 "${ABS_DEST}/voice.zip" echo "Upload it to: https://data.vayunmathur.com/models/piper/voice.zip"+echo "The SHA-256 above must match what the download config pins."
scripts/speech/fetch_sherpa_onnx.sh
diff --git a/scripts/speech/fetch_sherpa_onnx.sh b/scripts/speech/fetch_sherpa_onnx.shdeleted file mode 100755index 4317209ac5..0000000000--- a/scripts/speech/fetch_sherpa_onnx.sh+++ /dev/null@@ -1,36 +0,0 @@-#!/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/generate_piper_dict.py
diff --git a/scripts/speech/generate_piper_dict.py b/scripts/speech/generate_piper_dict.pynew file mode 100755index 0000000000..e5b1e9ad08--- /dev/null+++ b/scripts/speech/generate_piper_dict.py@@ -0,0 +1,194 @@+#!/usr/bin/env python3+"""+Build the `<lang>-word_id.bin` phoneme dictionary that com.vayunmathur.ncnn.Vits uses+instead of a runtime espeak-ng.++espeak-ng is GPL and awkward to vendor into the ncnn AAR (it wants exceptions/RTTI,+which ncnn disables PUBLIC), so phonemisation is done ahead of time here and shipped as+a lookup table. espeak-ng is still needed *on the build machine* — just not on-device.++Format, entries back to back with no header:++ word '\\0' id id id ... '\\xff'++Each id is one byte indexing the voice's `phoneme_id_map` from config.json. Words are+looked up case-insensitively at runtime, so only one case needs storing.++Usage:+ ./scripts/speech/generate_piper_dict.py \\+ --config dist/speech-mirror/piper/config.json \\+ --words cmudict-words.txt \\+ --voice en-us \\+ --out dist/speech-mirror/piper/en-word_id.bin++Word list: one word per line. https://github.com/Alexir/CMUdict `cmudict.0.7a` works+after stripping the pronunciations and the `(2)` variant suffixes; --words - reads stdin.+"""++import argparse+import json+import subprocess+import sys+from pathlib import Path++# Terminates an entry's id list, so it can never be a phoneme id itself.+TERMINATOR = 0xFF++# Reserved by the phonemizer and never looked up from the dictionary.+RESERVED_IDS = {0: "PAD", 1: "BOS", 2: "EOS", 3: "SPACE"}++# espeak-ng is slow to start, so words go through in batches on one invocation.+BATCH = 2000+++def load_phoneme_map(config_path: Path) -> dict:+ """phoneme_id_map maps an IPA symbol to a list of ids; we only ever use the first."""+ with config_path.open(encoding="utf-8") as f:+ config = json.load(f)++ raw = config.get("phoneme_id_map")+ if not raw:+ sys.exit(f"{config_path} has no phoneme_id_map")++ out = {}+ for symbol, ids in raw.items():+ if not ids:+ continue+ value = ids[0]+ if value == TERMINATOR:+ # Would be indistinguishable from the entry terminator.+ sys.exit(f"phoneme {symbol!r} has id 255, which collides with the terminator")+ if not 0 <= value <= 255:+ sys.exit(f"phoneme {symbol!r} has id {value}, which does not fit in a byte")+ out[symbol] = value+ return out+++def phonemize(words: list, voice: str) -> list:+ """One espeak-ng --ipa line per input word, in order."""+ result = []+ for start in range(0, len(words), BATCH):+ chunk = words[start:start + BATCH]+ proc = subprocess.run(+ ["espeak-ng", "-q", "-v", voice, "--ipa", "--stdin"],+ input="\n".join(chunk),+ capture_output=True,+ text=True,+ encoding="utf-8",+ )+ if proc.returncode != 0:+ sys.exit(f"espeak-ng failed: {proc.stderr.strip()}")++ lines = proc.stdout.split("\n")+ if len(lines) < len(chunk):+ sys.exit(+ f"espeak-ng returned {len(lines)} lines for {len(chunk)} words — "+ "a word probably contained whitespace"+ )+ result.extend(line.strip() for line in lines[:len(chunk)])++ print(f" phonemized {min(start + BATCH, len(words))}/{len(words)}", file=sys.stderr)++ return result+++def to_ids(ipa: str, phoneme_map: dict, longest: int):+ """+ Greedy longest-match over the IPA string. Symbols are multi-codepoint often enough+ (dʒ, aɪ, ɔː) that matching one character at a time would mis-segment.++ Returns None if any part of the string is unmappable — a partial pronunciation is+ worse than falling back to spelling the word out, which is what Vits does on a miss.+ """+ ids = []+ i = 0+ while i < len(ipa):+ for width in range(min(longest, len(ipa) - i), 0, -1):+ symbol = ipa[i:i + width]+ if symbol in phoneme_map:+ ids.append(phoneme_map[symbol])+ i += width+ break+ else:+ return None+ return ids or None+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__,+ formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--config", type=Path, required=True, help="Piper voice config.json")+ parser.add_argument("--words", type=Path, required=True, help="word list, one per line, or -")+ parser.add_argument("--voice", default="en-us", help="espeak-ng voice (default: en-us)")+ parser.add_argument("--out", type=Path, required=True, help="output <lang>-word_id.bin")+ args = parser.parse_args()++ phoneme_map = load_phoneme_map(args.config)+ longest = max(len(s) for s in phoneme_map)+ print(f"{len(phoneme_map)} phonemes, longest symbol {longest} chars", file=sys.stderr)++ if str(args.words) == "-":+ raw = sys.stdin.read()+ else:+ raw = args.words.read_text(encoding="utf-8", errors="replace")++ # Deduplicate case-insensitively (lookup is case-insensitive) but keep input order,+ # and drop anything with whitespace since espeak-ng is fed one word per line.+ seen = set()+ words = []+ for line in raw.splitlines():+ word = line.strip()+ if not word or any(c.isspace() for c in word):+ continue+ key = word.lower()+ if key in seen:+ continue+ seen.add(key)+ words.append(word)++ # Digits and single letters are what Vits falls back to when a word is missing, so+ # they have to be present or the fallback produces nothing at all. CMUdict has+ # neither.+ for extra in list("0123456789abcdefghijklmnopqrstuvwxyz"):+ if extra not in seen:+ seen.add(extra)+ words.append(extra)++ print(f"{len(words)} words to phonemize", file=sys.stderr)+ pronunciations = phonemize(words, args.voice)++ args.out.parent.mkdir(parents=True, exist_ok=True)++ stored = set()+ skipped = []+ with args.out.open("wb") as f:+ for word, ipa in zip(words, pronunciations):+ ids = to_ids(ipa, phoneme_map, longest) if ipa else None+ if ids is None:+ skipped.append(word)+ continue+ f.write(word.encode("utf-8"))+ f.write(b"\x00")+ f.write(bytes(ids))+ f.write(bytes([TERMINATOR]))+ stored.add(word.lower())++ print(f"\nwrote {len(stored)} entries to {args.out} "+ f"({args.out.stat().st_size / 1e6:.1f} MB)", file=sys.stderr)++ if skipped:+ print(f"skipped {len(skipped)} unmappable words, e.g. {skipped[:10]}", file=sys.stderr)++ # Vits spells unknown words out character by character, so a gap here means the+ # fallback silently produces nothing for anything containing that character.+ missing = [c for c in "0123456789abcdefghijklmnopqrstuvwxyz" if c not in stored]+ if missing:+ print(f"WARNING: no entry for {missing} — Vits cannot spell out words "+ "containing them", file=sys.stderr)++ if not stored:+ sys.exit("no entries written — check --config and --voice")+++if __name__ == "__main__":+ main()
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex 0c39e627c7..d572cab32a 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -22,11 +22,8 @@ dependencyResolutionManagement { mavenLocal() google() mavenCentral()- // JitPack kept only for Stockfish-Library (games:chess)+ // JitPack for Stockfish-Library (games:chess) and ncnn-android maven("https://jitpack.io")- // sherpa-onnx (offline Piper TTS in :speech) isn't on Maven Central; the official- // Apache-2.0 AAR is vendored into speech/libs by scripts/speech/fetch_sherpa_onnx.sh.- flatDir { dirs("speech/libs") } } }
speech/build.gradle.kts
diff --git a/speech/build.gradle.kts b/speech/build.gradle.ktsindex 23b4eb40b9..52115b8998 100644--- a/speech/build.gradle.kts+++ b/speech/build.gradle.kts@@ -14,28 +14,16 @@ android { defaultConfig { applicationId = "com.vayunmathur.speech" }- 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 whisper-tiny model is downloaded at runtime from the mirror (WhisperModel.FILES)- // and loaded from the filesystem via Whisper(dirPath).+ // Both offline speech engines run in the ncnn AAR: speech-to-text via+ // com.vayunmathur.ncnn.Whisper and text-to-speech (Piper/VITS) via+ // com.vayunmathur.ncnn.Vits. Their models are downloaded at runtime from the mirror+ // (WhisperModel.FILES, PiperModel.FILES) and loaded from the filesystem by path —+ // only native code ships in the APK. 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.aardeleted file mode 100644index ac21b7993f..0000000000Binary files a/speech/libs/sherpa-onnx.aar and /dev/null differ
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 75df449ff7..5792f087ae 100644--- a/speech/src/main/java/com/vayunmathur/speech/service/PiperTtsService.kt+++ b/speech/src/main/java/com/vayunmathur/speech/service/PiperTtsService.kt@@ -13,14 +13,14 @@ import java.util.Locale 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.+ * 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 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.+ * other languages to us. Synthesis is blocking — the whole utterance is generated, then fed+ * to the [SynthesisCallback] in chunks. */ class PiperTtsService : TextToSpeechService() { @@ -161,7 +161,7 @@ class PiperTtsService : TextToSpeechService() { return } - // Framework rate is a percentage of normal (100 = 1.0×); sherpa's speed is the same+ // Framework rate is a percentage of normal (100 = 1.0×); Vits's speed is the same // multiplier (larger = faster). Clamp to a sane range. val speed = (request.speechRate / 100f).coerceIn(0.3f, 3.0f)
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 110d703cf9..e8f5269636 100644--- a/speech/src/main/java/com/vayunmathur/speech/util/PiperEngine.kt+++ b/speech/src/main/java/com/vayunmathur/speech/util/PiperEngine.kt@@ -2,27 +2,21 @@ 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+import com.vayunmathur.ncnn.Vits /**- * 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+ * Thin wrapper around the ncnn AAR's [Vits] running an offline **Piper (VITS)** voice.+ * The voice is downloaded at runtime and extracted by [PiperModel] into filesDir; 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). *- * IMPORTANT: sherpa 1.13.4's generateWithCallback JNI expects a Function1<FloatArray, Int>- * as a *sam* interface, but R8/minify + Kotlin synthetic lambdas cause- * NoSuchMethodError for ExternalSyntheticLambda (see tombstone_00). We use the blocking- * generate() API and chunk the PCM ourselves to avoid the callback JNI path.+ * [Vits.generate] is blocking and returns the whole utterance, so we chunk the PCM+ * ourselves to keep the caller's audioAvailable loop progressive. */ class PiperEngine(private val context: Context) { - private var tts: OfflineTts? = null+ private var tts: Vits? = null private var loadFailed = false /** Load now (e.g. to warm up off the main thread). Returns true if ready. */@@ -33,17 +27,14 @@ class PiperEngine(private val context: Context) { /** * Synthesize [text] into PCM float chunks. [onChunk] receives each chunk and returns- * false to abort. Uses blocking generate() to avoid the crashy callback JNI.+ * false to abort. */ @Synchronized fun synthesize(text: String, speed: Float, onChunk: (FloatArray) -> Boolean): Boolean { if (!ensure()) return false val engine = tts ?: return false return try {- // Blocking synthesis — returns full audio. We then stream it out in 4k-sample- // chunks so the caller's audioAvailable loop still gets progressive output.- val audio = engine.generate(text, /* sid = */ 0, speed)- val samples = audio.samples ?: return false+ val samples = engine.generate(text, /* sid = */ 0, speed) if (samples.isEmpty()) return true var offset = 0 while (offset < samples.size) {@@ -62,7 +53,7 @@ class PiperEngine(private val context: Context) { @Synchronized fun close() { try {- tts?.release()+ tts?.close() } catch (_: Throwable) { } tts = null@@ -79,26 +70,14 @@ class PiperEngine(private val context: Context) { if (!PiperModel.isExtracted(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")+ val engine = Vits(dir.absolutePath)+ if (!engine.isAvailable) {+ Log.e(TAG, "Vits could not load the voice in $dir")+ engine.close() 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)+ tts = engine true } catch (t: Throwable) { Log.e(TAG, "Piper load failed", t)
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 a64d3a248a..d10bd3f263 100644--- a/speech/src/main/java/com/vayunmathur/speech/util/PiperModel.kt+++ b/speech/src/main/java/com/vayunmathur/speech/util/PiperModel.kt@@ -10,20 +10,36 @@ 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+ * is a directory tree, 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).+ * `com.vayunmathur.ncnn.Vits` loads it from those real file paths, which is why the voice+ * isn't bundled in the APK. *- * 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):+ * The VITS graph is exported as five separate ncnn nets, because the alignment between the+ * duration predictor and the flow depends on the predicted durations and can't be expressed+ * as ncnn ops. So the voice directory holds, for a voice named `<voice>`:+ * `<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}` speaker embedding, multi-speaker voices only+ * `en-word_id.bin` grapheme-to-phoneme dictionary+ * `config.json` sample rate + inference scales+ *+ * Mirror layout (zip the voice dir's *contents* 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"+ const val DICT = "en-word_id.bin"+ const val CONFIG = "config.json"++ /** Identifies the voice: whatever precedes this is the `<voice>` prefix. */+ private const val ENCODER_SUFFIX = "_enc_p.ncnn.param"++ /** The nets that every voice has. `_emb_g` is multi-speaker-only, so not required. */+ private val REQUIRED_NETS = listOf("_enc_p", "_dp", "_flow", "_dec") private const val BASE = "https://data.vayunmathur.com/models/piper/" private const val ARCHIVE = "$DIR/voice.zip"@@ -44,31 +60,41 @@ object PiperModel { return File(root, ARCHIVE) } - /** The extracted voice directory sherpa-onnx loads from. */+ /** The extracted voice directory [com.vayunmathur.ncnn.Vits] loads from. */ fun voiceDir(context: Context): File { val root = rootDir(context) ?: return File("$DIR/voice") return File(root, "$DIR/voice") } - fun onnxFile(context: Context): File? {- val dir = voiceDir(context)- val files = dir.listFiles() ?: return null- return files.firstOrNull { it.name.endsWith(".onnx") }+ /**+ * The `<voice>` prefix the net files share, discovered from whichever file ends in+ * `_enc_p.ncnn.param`. Null if the voice isn't extracted. Vits does the same scan+ * natively; this mirrors it so [isExtracted] can verify the rest of the set.+ */+ fun voicePrefix(context: Context): String? {+ val files = voiceDir(context).listFiles() ?: return null+ val encoder = files.firstOrNull { it.name.endsWith(ENCODER_SUFFIX) } ?: return null+ return encoder.name.removeSuffix(ENCODER_SUFFIX) } /** True once the voice has been extracted and looks complete. */ fun isExtracted(context: Context): Boolean { val dir = voiceDir(context)+ val prefix = voicePrefix(context) val result = dir.isDirectory &&- (dir.listFiles()?.any { it.name.endsWith(".onnx") } == true) &&- File(dir, TOKENS).exists() &&- File(dir, ESPEAK_DATA).isDirectory- Log.d(TAG, "isExtracted dir=$dir exists=${dir.exists()} isDir=${dir.isDirectory} root=${rootDir(context)} result=$result")+ prefix != null &&+ REQUIRED_NETS.all { net ->+ File(dir, "$prefix$net.ncnn.param").exists() &&+ File(dir, "$prefix$net.ncnn.bin").exists()+ } &&+ File(dir, DICT).exists() &&+ File(dir, CONFIG).exists()+ Log.d(TAG, "isExtracted dir=$dir exists=${dir.exists()} isDir=${dir.isDirectory} prefix=$prefix root=${rootDir(context)} result=$result") if (!result) { // Also probe the known external absolute path as fallback diagnostic try { val ext = context.getExternalFilesDir(null)- Log.d(TAG, "extDir=$ext tokensExists=${File(dir, TOKENS).exists()} espeakExists=${File(dir, ESPEAK_DATA).exists()} list=${dir.list()?.toList()}")+ Log.d(TAG, "extDir=$ext dictExists=${File(dir, DICT).exists()} configExists=${File(dir, CONFIG).exists()} list=${dir.list()?.toList()}") } catch (t: Throwable) { Log.d(TAG, "isExtracted probe failed", t) }