From 2e60cb27008d2ed8c778df757f99616927dd82e5 Mon Sep 17 00:00:00 2001 From: billlyzhaoyh Date: Thu, 26 Nov 2026 16:26:34 +0000 Subject: [PATCH 1/3] fix(app): unpack each model pack on its own, so a broken speaker pack can't stop transcription The resolver unpacked every verified speech pack into one shared cache folder. One pack that failed to unpack (a corrupt entry, a full disk) stopped every import, recovery and recording, speakers on or off. Each pack now unpacks into its own folder, verified-models/pack-/, like the LLM pack's llm-/: - Transcription verifies `asr` packs only, picks one whose zip lists the model's files (each carries Silero VAD), and unpacks only that pack. - The speaker step resolves the `diarization` pack on its own (`resolve_verified_speaker_dir`). No pack gives the "isn't installed" note; one that can't be unpacked gives "Speakers couldn't be labelled". - Stop resolves only the speaker pack, so it no longer re-hashes the transcription packs. - The old shared folders (64-hex names) are removed when resolving. The engine gains `Diarizer`, which needs only the speaker models, and `speaker_model_files()`; SherpaEngine's diarize hands off to it. Tests sign packs with the committed test key through a dev-dependency on tools/modelpack-sign. The `diarize = true` resolver test is replaced by the speaker resolver's `Ok(None)` case. Closes #38 --- app/src-tauri/Cargo.lock | 143 +++++++++++- app/src-tauri/Cargo.toml | 4 +- app/src-tauri/src/commands.rs | 114 ++++++++-- app/src-tauri/src/models.rs | 416 +++++++++++++++++++++++----------- app/src-tauri/src/recorder.rs | 12 +- engine/src/lib.rs | 11 +- engine/src/sherpa.rs | 146 +++++++----- 7 files changed, 624 insertions(+), 222 deletions(-) diff --git a/app/src-tauri/Cargo.lock b/app/src-tauri/Cargo.lock index e9d3472..0eb7868 100644 --- a/app/src-tauri/Cargo.lock +++ b/app/src-tauri/Cargo.lock @@ -85,6 +85,56 @@ dependencies = [ "libc", ] +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + [[package]] name = "anyhow" version = "1.0.102" @@ -462,12 +512,58 @@ dependencies = [ "inout 0.2.6", ] +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + [[package]] name = "cmov" version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + [[package]] name = "combine" version = "4.6.7" @@ -1038,6 +1134,7 @@ checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" dependencies = [ "curve25519-dalek", "ed25519", + "rand_core", "serde", "sha2 0.10.9", "subtle", @@ -1975,6 +2072,12 @@ version = "2.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + [[package]] name = "itoa" version = "1.0.18" @@ -2143,10 +2246,10 @@ dependencies = [ "engine", "hound", "modelpack", + "modelpack-sign", "objc2-core-audio", "serde", "serde_json", - "sha2 0.10.9", "sysinfo", "tauri", "tauri-build", @@ -2360,6 +2463,21 @@ dependencies = [ "thiserror 2.0.18", ] +[[package]] +name = "modelpack-sign" +version = "0.1.0" +dependencies = [ + "anyhow", + "base64 0.22.1", + "clap", + "ed25519-dalek", + "modelpack", + "rand_core", + "serde_json", + "walkdir", + "zip 2.4.2", +] + [[package]] name = "muda" version = "0.19.2" @@ -2757,6 +2875,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "option-ext" version = "0.2.0" @@ -4028,6 +4152,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "sync_wrapper" version = "1.0.2" @@ -4906,6 +5041,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "uuid" version = "1.23.3" diff --git a/app/src-tauri/Cargo.toml b/app/src-tauri/Cargo.toml index 305a8af..b96b68d 100644 --- a/app/src-tauri/Cargo.toml +++ b/app/src-tauri/Cargo.toml @@ -17,6 +17,9 @@ ed25519-dalek = { version = "2", features = ["pem"] } [dev-dependencies] ed25519-dalek = { version = "2", features = ["pem"] } +# The pack producer, so tests can sign packs with the committed test key. Tests +# only: never linked into the app. +modelpack-sign = { path = "../../tools/modelpack-sign" } [dependencies] # In-process engine via a PATH dependency — NOT a registry fetch. Pulls @@ -44,7 +47,6 @@ serde_json = "1" # Verified-pack resolution: extract verified packs' `weights.bin` zips into a # content-addressed cache. Network-free (scanned by the zero-egress gate). zip = "2" -sha2 = "0.10" # In-app recording: microphone capture (CoreAudio / WASAPI / ALSA backends), # WAV writing, and local-time file names. All network-free. diff --git a/app/src-tauri/src/commands.rs b/app/src-tauri/src/commands.rs index 62ed713..3fcc674 100644 --- a/app/src-tauri/src/commands.rs +++ b/app/src-tauri/src/commands.rs @@ -2,7 +2,7 @@ //! leaves the machine and no network call is made. use engine::{ - decode_to_16k_mono_with_progress, merge, AsrSegment, EngineConfig, SherpaEngine, + decode_to_16k_mono_with_progress, merge, AsrSegment, Diarizer, EngineConfig, SherpaEngine, TranscriptionEngine, }; use serde::Serialize; @@ -52,37 +52,53 @@ pub(crate) fn finish_transcript( NewTranscript { transcript, speakers_labelled, note } } +/// Speakers were asked for, but no speaker-detection pack is installed. +#[derive(Debug)] +struct NoSpeakerPack; + +impl std::fmt::Display for NoSpeakerPack { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("no speaker-detection pack is installed") + } +} + +impl std::error::Error for NoSpeakerPack {} + /// The note for a transcript whose speakers couldn't be labelled because of `e`. fn unlabelled_note(e: &anyhow::Error) -> String { - match e.downcast_ref::() { - Some(engine::EngineError::ModelNotFound(_)) => NO_SPEAKER_PACK.to_string(), - _ => format!("Speakers couldn't be labelled, so this transcript has none. ({e})"), + if e.is::() { + NO_SPEAKER_PACK.to_string() + } else { + format!("Speakers couldn't be labelled, so this transcript has none. ({e})") } } -/// The engine to label speakers with. Building it checks for the speaker -/// models, so build it before reading any audio. -/// -/// `cfg.models_dir` is a models dir resolved for transcription. The resolver -/// composes every verified pack into it, so the speaker models are there only -/// if their pack is installed; if not, this fails with -/// [`engine::EngineError::ModelNotFound`]. -pub(crate) fn speaker_engine(cfg: &EngineConfig) -> anyhow::Result { - let mut cfg = cfg.clone(); - cfg.diarize = true; - SherpaEngine::new(&cfg) +/// The diarizer to label speakers with, from the speaker-detection pack. Get +/// it before reading any audio: it fails fast when the pack is missing. +pub(crate) fn speaker_diarizer(app: &AppHandle, num_threads: i32) -> anyhow::Result { + diarizer_for(resolve_speaker_dir(app), num_threads) } -/// Diarize `samples` with `engine` (from [`speaker_engine`]) and attach +/// The diarizer for a resolved speaker-models folder; `Ok(None)` means no +/// speaker-detection pack is installed. +fn diarizer_for( + dir: Result, String>, + num_threads: i32, +) -> anyhow::Result { + let dir = dir.map_err(anyhow::Error::msg)?.ok_or(NoSpeakerPack)?; + Diarizer::new(dir, num_threads) +} + +/// Diarize `samples` with `diarizer` (from [`speaker_diarizer`]) and attach /// speakers to the transcribed `segments`. pub(crate) fn label_speakers( - engine: &SherpaEngine, + diarizer: &Diarizer, samples: &[f32], sample_rate: u32, segments: &[AsrSegment], num_speakers: Option, ) -> anyhow::Result { - let spans = engine.diarize(samples, sample_rate, num_speakers)?; + let spans = diarizer.diarize(samples, sample_rate, num_speakers)?; Ok(merge::merge(segments, &spans)) } @@ -151,6 +167,18 @@ pub(crate) fn resolve_models_dir( models::resolve_verified_models_dir(app, asr_model) } +/// Resolve the speaker-detection models' folder, or `None` when no verified +/// speaker-detection pack is installed (debug-only raw override: the override +/// folder, if it holds the speaker models). Blocking: may unpack the pack. +pub(crate) fn resolve_speaker_dir(app: &AppHandle) -> Result, String> { + #[cfg(debug_assertions)] + if let Some(raw) = debug_models_dir_override() { + let present = engine::speaker_model_files().iter().all(|file| raw.join(file).is_file()); + return Ok(present.then_some(raw)); + } + models::resolve_verified_speaker_dir(app) +} + /// Transcribe an audio file (wav/mp3/m4a/mp4/flac/ogg…) into the project's JSON /// contract. /// @@ -186,10 +214,9 @@ pub async fn transcribe( tauri::async_runtime::spawn_blocking(move || { // Resolve the models dir, enforcing verified-pack trust (debug-only raw // override: see `debug_models_dir_override`). Transcription models - // only: speakers are labelled as a separate step below, so missing - // speaker models, or a failure to load or run them, don't cost the - // transcript. (Resolving still unpacks every verified pack, so a pack - // that fails to unpack stops this too: #38.) + // only: speakers are labelled as a separate step below, from their own + // pack, so a speaker pack that is missing or fails to unpack, load or + // run doesn't cost the transcript. cfg.models_dir = resolve_models_dir(&resolve_app, cfg.asr_model)?; // Timed from model load to the finished transcript: what the person @@ -216,8 +243,8 @@ pub async fn transcribe( let segments = sherpa.transcribe(&samples, sample_rate, &progress).map_err(|e| e.to_string())?; let label = diarize.then_some(|| { - let eng = speaker_engine(&cfg)?; - label_speakers(&eng, &samples, sample_rate, &segments, num_speakers) + let diarizer = speaker_diarizer(&run_app, cfg.num_threads)?; + label_speakers(&diarizer, &samples, sample_rate, &segments, num_speakers) }); let result = finish_transcript(&run_app, &segments, label, Vec::new()); crate::device::record_run( @@ -233,3 +260,42 @@ pub async fn transcribe( .await .map_err(|e| format!("transcription task failed: {e}"))? } + +#[cfg(test)] +mod tests { + use super::*; + use crate::models::resolve_verified_speaker_dir_in; + use crate::models::tests::{broken_speaker_pack, copy_fixture_pack, fixtures_context, unique_tmp}; + use modelpack::PublicKey; + use std::path::Path; + + /// The speaker step's note says why a transcript has no speakers: the pack + /// isn't installed, or it couldn't be used. + #[test] + fn the_speaker_step_says_why_a_transcript_has_no_speakers() { + let (pem, versions) = fixtures_context(); + let pubkey = PublicKey::SpkiPem(&pem); + let packs = unique_tmp("note-packs"); + copy_fixture_pack("asr-small-en", &packs); + let cache_base = unique_tmp("note-cache"); + let note = |packs: &Path| { + let dir = resolve_verified_speaker_dir_in(packs, &cache_base, &pubkey, &versions); + let err = diarizer_for(dir, 4).err().expect("no speaker models to label with"); + unlabelled_note(&err) + }; + + assert_eq!( + note(&packs), + "The speaker-detection pack isn't installed, so this transcript has no speakers. Add it on the Models page." + ); + broken_speaker_pack(&packs); + let broken = note(&packs); + assert!( + broken.starts_with("Speakers couldn't be labelled, so this transcript has none. ("), + "got: {broken}" + ); + + let _ = std::fs::remove_dir_all(&packs); + let _ = std::fs::remove_dir_all(&cache_base); + } +} diff --git a/app/src-tauri/src/models.rs b/app/src-tauri/src/models.rs index 60953f9..d4bc709 100644 --- a/app/src-tauri/src/models.rs +++ b/app/src-tauri/src/models.rs @@ -14,7 +14,6 @@ use std::path::{Component, Path, PathBuf}; use modelpack::{compare_semver, verify_model_pack_reader, PublicKey}; use serde::Serialize; use serde_json::Value; -use sha2::{Digest, Sha256}; use tauri::Manager; /// Committed dev/test SPKI key; never the production signing key (release @@ -46,6 +45,10 @@ fn engine_versions() -> BTreeMap { /// The manifest `task` of a language-model pack (a GGUF for llama.cpp). const LLM_TASK: &str = "llm"; +/// The manifest `task` of a transcription pack (ASR models + Silero VAD). +const ASR_TASK: &str = "asr"; +/// The manifest `task` of the speaker-detection pack (segmentation + embedding). +const DIARIZATION_TASK: &str = "diarization"; /// The verified/rejected status of a single model pack, surfaced to the UI. #[derive(Debug, Clone, Serialize)] @@ -217,16 +220,6 @@ pub fn import_model_pack(app: tauri::AppHandle, src_dir: String) -> Result String { - let digest = Sha256::digest(bytes); - let mut out = String::with_capacity(digest.len() * 2); - for b in digest { - out.push_str(&format!("{b:02x}")); - } - out -} - /// True iff `name` (a zip entry path) stays within the extraction root: no /// absolute paths, no `..` components, no root/prefix components. Defends /// against zip path-traversal ("zip slip") regardless of `ZipArchive::extract`'s @@ -280,13 +273,6 @@ fn extract_zip_into(weights: &Path, dest: &Path) -> Result<(), String> { Ok(()) } -/// True iff `path` is a readable zip archive. -fn is_zip_file(path: &Path) -> bool { - std::fs::File::open(path) - .map(|f| zip::ZipArchive::new(std::io::BufReader::new(f)).is_ok()) - .unwrap_or(false) -} - /// The `sha256` string of the (already verified) manifest in `dir`. fn manifest_sha256(dir: &Path) -> Result { let bytes = std::fs::read(dir.join("manifest.json")) @@ -337,100 +323,165 @@ fn verified_packs( out } -/// Verified-pack resolver. Enumerates `packs_dir`, VERIFIES every -/// pack, extracts ONLY verified speech packs' `weights.bin` zips into a content- -/// addressed cache under `cache_base`, and returns the cache dir IFF it provides -/// every model file the engine requires for `(asr_model, diarize)`. Fails closed -/// at every step: no verified pack, or any missing required file, is an `Err`. -/// Language-model packs (`task: "llm"`) are left out; see [`resolve_verified_llm_in`]. -/// -/// The cache dir is keyed by the SHA-256 of the verified packs' `sha256` manifest -/// strings (sorted ascending, `\n`-joined), so the same verified set always maps -/// to the same dir and re-extraction is skipped via a `.complete` marker. -/// -/// The app relies on the dir holding EVERY verified pack's files: it resolves -/// for transcription only, and `commands::speaker_engine` then finds the speaker -/// models there if their pack is installed. Caching packs separately (#38) must -/// keep that working. -pub fn resolve_verified_models_dir_in( +/// True iff the zip at `weights` lists every one of `files`. Reads only the +/// zip's directory, so choosing a pack never unpacks the others. +fn zip_lists(weights: &Path, files: &[String]) -> bool { + let Ok(file) = std::fs::File::open(weights) else { + return false; + }; + let Ok(archive) = zip::ZipArchive::new(std::io::BufReader::new(file)) else { + return false; + }; + let names: std::collections::HashSet<&str> = archive.file_names().collect(); + files.iter().all(|f| names.contains(f.as_str())) +} + +/// The verified packs of `task` in `packs_dir` (see [`verified_packs`]). +fn verified_packs_of( packs_dir: &Path, - cache_base: &Path, pubkey: &PublicKey<'_>, engine_versions: &BTreeMap, - asr_model: engine::AsrModel, - diarize: bool, -) -> Result { - let verified_dirs: Vec = - verified_packs(packs_dir, pubkey, engine_versions, |task| task != LLM_TASK) - .into_iter() - .filter(|(_, status)| status.task != LLM_TASK) - .map(|(dir, _)| dir) - .collect(); - if verified_dirs.is_empty() { - return Err(format!( - "no verified model pack found in {}", - packs_dir.display() - )); + task: &str, +) -> Vec<(PathBuf, PackStatus)> { + verified_packs(packs_dir, pubkey, engine_versions, |t| t == task) + .into_iter() + .filter(|(_, status)| status.task == task) + .collect() +} + +/// The pack among `packs` that holds every one of `files`: the highest +/// version, ties going to the last directory name. +fn pick_pack(packs: Vec<(PathBuf, PackStatus)>, files: &[String]) -> Option { + let mut packs: Vec<(PathBuf, PackStatus)> = packs + .into_iter() + .filter(|(dir, _)| zip_lists(&dir.join("weights.bin"), files)) + .collect(); + packs.sort_by(|a, b| compare_semver(&a.1.version, &b.1.version).then(a.0.cmp(&b.0))); + packs.pop().map(|(dir, _)| dir) +} + +/// Unpack the zip at `weights` into `dest` unless a `.complete` marker says a +/// previous run already did; a partial folder from an interrupted run is +/// cleared first. +fn unpack_once(weights: &Path, dest: &Path) -> Result<(), String> { + let complete_marker = dest.join(".complete"); + if complete_marker.exists() { + return Ok(()); } + if dest.exists() { + std::fs::remove_dir_all(dest) + .map_err(|e| format!("clearing partial cache {}: {e}", dest.display()))?; + } + std::fs::create_dir_all(dest) + .map_err(|e| format!("creating cache dir {}: {e}", dest.display()))?; + extract_zip_into(weights, dest)?; + std::fs::write(&complete_marker, b"") + .map_err(|e| format!("writing completion marker {}: {e}", complete_marker.display())) +} - let mut sha_list: Vec = Vec::new(); - for dir in &verified_dirs { - sha_list.push(manifest_sha256(dir)?); +/// The verified speech pack `pack`, unpacked into its own content-addressed +/// cache folder, `cache_base/verified-models/pack-/`, and +/// checked to hold every one of `files`. +fn unpacked_pack(pack: &Path, cache_base: &Path, files: &[String]) -> Result { + let dest = cache_base + .join("verified-models") + .join(format!("pack-{}", manifest_sha256(pack)?)); + unpack_once(&pack.join("weights.bin"), &dest)?; + let missing: Vec<&String> = files.iter().filter(|rel| !dest.join(rel).exists()).collect(); + if !missing.is_empty() { + return Err(format!("verified pack {} is missing {missing:?}", pack.display())); } - sha_list.sort(); - let combined_key = sha256_hex(sha_list.join("\n").as_bytes()); + Ok(dest) +} - let composed = cache_base.join("verified-models").join(&combined_key); - let complete_marker = composed.join(".complete"); - if !complete_marker.exists() { - // Fresh extraction: clear any partial dir, recreate, extract each - // verified pack's zip-valid weights.bin (skip non-zip packs). - if composed.exists() { - std::fs::remove_dir_all(&composed) - .map_err(|e| format!("clearing partial cache {}: {e}", composed.display()))?; - } - std::fs::create_dir_all(&composed) - .map_err(|e| format!("creating cache dir {}: {e}", composed.display()))?; - for dir in &verified_dirs { - let weights = dir.join("weights.bin"); - // A non-zip weights.bin contributes no files — skip rather than abort. - if !is_zip_file(&weights) { - continue; - } - extract_zip_into(&weights, &composed)?; +/// Remove the folders of the old layout, where every verified speech pack was +/// unpacked into one shared folder named by a 64-hex hash of the whole set. +/// Best effort: nothing uses them any more. +fn remove_old_shared_caches(cache_base: &Path) { + let Ok(entries) = std::fs::read_dir(cache_base.join("verified-models")) else { + return; + }; + for entry in entries.filter_map(|e| e.ok()) { + let name = entry.file_name(); + let name = name.to_string_lossy(); + if name.len() == 64 && name.bytes().all(|b| b.is_ascii_hexdigit()) && entry.path().is_dir() { + let _ = std::fs::remove_dir_all(entry.path()); } - std::fs::write(&complete_marker, b"") - .map_err(|e| format!("writing completion marker {}: {e}", complete_marker.display()))?; } +} - // Fail closed unless EVERY required file is present. - let missing: Vec = engine::required_model_files(asr_model, diarize) - .into_iter() - .filter(|rel| !composed.join(rel).exists()) - .collect(); - if !missing.is_empty() { - return Err(format!( - "no verified pack provides the required model file(s): {missing:?}" - )); +/// Verified transcription-pack resolver. Enumerates `packs_dir`, VERIFIES every +/// `task: "asr"` pack, picks one holding every model file the engine requires +/// for `asr_model` (each ASR pack carries Silero VAD too), and unpacks only that +/// pack into its own cache folder (see [`unpacked_pack`]). Fails closed: no +/// verified pack, or none providing the required files, is an `Err`. Other +/// packs, the speaker-detection pack included, are never unpacked here, so one +/// that fails to unpack can't stop transcription (#38). +/// +/// Also removes the old shared cache folders (see [`remove_old_shared_caches`]). +pub fn resolve_verified_models_dir_in( + packs_dir: &Path, + cache_base: &Path, + pubkey: &PublicKey<'_>, + engine_versions: &BTreeMap, + asr_model: engine::AsrModel, +) -> Result { + remove_old_shared_caches(cache_base); + let files = engine::required_model_files(asr_model, false); + let packs = verified_packs_of(packs_dir, pubkey, engine_versions, ASR_TASK); + if packs.is_empty() { + return Err(format!("no verified model pack found in {}", packs_dir.display())); } - Ok(composed) + let pack = pick_pack(packs, &files).ok_or_else(|| { + format!("no verified pack provides the required model file(s): {files:?}") + })?; + unpacked_pack(&pack, cache_base, &files) } /// AppHandle wrapper around [`resolve_verified_models_dir_in`]. -/// Resolves for transcription; the speaker step finds the speaker models in the -/// same dir (see [`resolve_verified_models_dir_in`]). pub fn resolve_verified_models_dir( app: &tauri::AppHandle, asr_model: engine::AsrModel, ) -> Result { let packs = packs_dir(app)?; - let cache_base = app - .path() - .app_data_dir() - .map_err(|e| format!("cannot resolve app data dir: {e}"))?; + let cache_base = app_cache_base(app)?; let pubkey = PublicKey::SpkiPem(vendor_pubkey_pem()); let versions = engine_versions(); - resolve_verified_models_dir_in(&packs, &cache_base, &pubkey, &versions, asr_model, false) + resolve_verified_models_dir_in(&packs, &cache_base, &pubkey, &versions, asr_model) +} + +/// Verified speaker-detection-pack resolver: the cache folder of a verified +/// `task: "diarization"` pack holding [`engine::speaker_model_files`], unpacked +/// on its own (see [`unpacked_pack`]). `Ok(None)` when no verified pack +/// provides them; `Err` when the pack can't be unpacked. +pub fn resolve_verified_speaker_dir_in( + packs_dir: &Path, + cache_base: &Path, + pubkey: &PublicKey<'_>, + engine_versions: &BTreeMap, +) -> Result, String> { + let files = engine::speaker_model_files(); + let packs = verified_packs_of(packs_dir, pubkey, engine_versions, DIARIZATION_TASK); + match pick_pack(packs, &files) { + Some(pack) => unpacked_pack(&pack, cache_base, &files).map(Some), + None => Ok(None), + } +} + +/// AppHandle wrapper around [`resolve_verified_speaker_dir_in`]. +pub fn resolve_verified_speaker_dir(app: &tauri::AppHandle) -> Result, String> { + let packs = packs_dir(app)?; + let cache_base = app_cache_base(app)?; + let pubkey = PublicKey::SpkiPem(vendor_pubkey_pem()); + let versions = engine_versions(); + resolve_verified_speaker_dir_in(&packs, &cache_base, &pubkey, &versions) +} + +/// Where verified packs are unpacked: the per-user app-data dir. +fn app_cache_base(app: &tauri::AppHandle) -> Result { + app.path() + .app_data_dir() + .map_err(|e| format!("cannot resolve app data dir: {e}")) } /// Verified LLM-pack resolver. Enumerates `packs_dir`, VERIFIES every pack, and @@ -448,11 +499,7 @@ pub fn resolve_verified_llm_in( pubkey: &PublicKey<'_>, engine_versions: &BTreeMap, ) -> Result { - let mut llm_packs: Vec<(PathBuf, PackStatus)> = - verified_packs(packs_dir, pubkey, engine_versions, |task| task == LLM_TASK) - .into_iter() - .filter(|(_, status)| status.task == LLM_TASK) - .collect(); + let mut llm_packs = verified_packs_of(packs_dir, pubkey, engine_versions, LLM_TASK); llm_packs.sort_by(|a, b| compare_semver(&a.1.version, &b.1.version).then(a.0.cmp(&b.0))); let Some((dir, status)) = llm_packs.pop() else { return Err(format!( @@ -464,18 +511,7 @@ pub fn resolve_verified_llm_in( let dest = cache_base .join("verified-models") .join(format!("llm-{}", manifest_sha256(&dir)?)); - let complete_marker = dest.join(".complete"); - if !complete_marker.exists() { - if dest.exists() { - std::fs::remove_dir_all(&dest) - .map_err(|e| format!("clearing partial cache {}: {e}", dest.display()))?; - } - std::fs::create_dir_all(&dest) - .map_err(|e| format!("creating cache dir {}: {e}", dest.display()))?; - extract_zip_into(&dir.join("weights.bin"), &dest)?; - std::fs::write(&complete_marker, b"") - .map_err(|e| format!("writing completion marker {}: {e}", complete_marker.display()))?; - } + unpack_once(&dir.join("weights.bin"), &dest)?; let ggufs: Vec = std::fs::read_dir(&dest) .map_err(|e| format!("reading cache dir {}: {e}", dest.display()))? @@ -502,21 +538,18 @@ pub fn resolve_verified_llm_in( #[allow(dead_code)] // Spike S5: not called by the app yet; P2 (local notes) will use it. pub fn resolve_verified_llm(app: &tauri::AppHandle) -> Result { let packs = packs_dir(app)?; - let cache_base = app - .path() - .app_data_dir() - .map_err(|e| format!("cannot resolve app data dir: {e}"))?; + let cache_base = app_cache_base(app)?; let pubkey = PublicKey::SpkiPem(vendor_pubkey_pem()); let versions = engine_versions(); resolve_verified_llm_in(&packs, &cache_base, &pubkey, &versions) } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; use std::fs; - fn repo_root() -> PathBuf { + pub(crate) fn repo_root() -> PathBuf { // CARGO_MANIFEST_DIR = /app/src-tauri Path::new(env!("CARGO_MANIFEST_DIR")) .ancestors() @@ -525,7 +558,7 @@ mod tests { .to_path_buf() } - fn fixtures_context() -> (String, BTreeMap) { + pub(crate) fn fixtures_context() -> (String, BTreeMap) { let fixtures = repo_root().join("fixtures/modelpack"); let v: Value = serde_json::from_str(&fs::read_to_string(fixtures.join("context.json")).unwrap()) @@ -621,7 +654,7 @@ mod tests { assert!(status.reason.unwrap().contains("weights hash mismatch")); } - fn unique_tmp(tag: &str) -> PathBuf { + pub(crate) fn unique_tmp(tag: &str) -> PathBuf { std::env::temp_dir().join(format!( "podcast-resolver-{tag}-{}-{:?}", std::process::id(), @@ -649,7 +682,6 @@ mod tests { &pubkey, &versions, engine::AsrModel::SmallEn, - false, ) .expect("committed verified pack must resolve"); @@ -669,7 +701,6 @@ mod tests { &pubkey, &versions, engine::AsrModel::SmallEn, - false, ) .expect("second resolve must succeed"); assert_eq!(dir, dir2, "resolver must be deterministic / idempotent"); @@ -703,7 +734,6 @@ mod tests { &pubkey, &versions, engine::AsrModel::SmallEn, - false, ) .expect_err("an unsigned pack must not be trusted"); assert!( @@ -715,35 +745,156 @@ mod tests { let _ = fs::remove_dir_all(&cache_base); } - /// DIARIZE-MISSING: the asr-only fixture pack provides no seg/emb model, so - /// resolving with `diarize=true` fails closed naming the missing file(s). + /// A zip holding `files` (path, bytes), stored uncompressed. + fn zip_of(files: &[(&str, &[u8])]) -> Vec { + use std::io::Write; + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let stored = zip::write::SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Stored); + for (name, bytes) in files { + zip.start_file(*name, stored).unwrap(); + zip.write_all(bytes).unwrap(); + } + zip.finish().unwrap().into_inner() + } + + /// Write `packs//` as a pack of `weights`, signed with the committed + /// test key, declaring `task`. + fn signed_pack(packs: &Path, name: &str, task: &str, weights: &[u8]) -> PathBuf { + use ed25519_dalek::pkcs8::DecodePrivateKey; + let pem = + fs::read_to_string(repo_root().join("fixtures/modelpack/keys/test-private.pkcs8.pem")) + .unwrap(); + let key = ed25519_dalek::SigningKey::from_pkcs8_pem(&pem).unwrap(); + let meta = modelpack_sign::PackMeta { + id: format!("test/{name}"), + version: "1.0.0".into(), + engine: "sherpa-onnx".into(), + engine_min_version: "1.13.2".into(), + task: task.into(), + license: "MIT".into(), + attribution: "Test pack".into(), + }; + let sha = modelpack::sha256_hex_reader(weights).unwrap(); + let signature = modelpack_sign::sign_manifest(&key, &meta, &sha); + let dir = packs.join(name); + fs::create_dir_all(&dir).unwrap(); + fs::write(dir.join("weights.bin"), weights).unwrap(); + let manifest = modelpack_sign::build_manifest_json(&meta, &sha, &signature); + fs::write(dir.join("manifest.json"), manifest.to_string()).unwrap(); + dir + } + + /// A speaker-detection pack that verifies but can't be unpacked: its + /// segmentation model's bytes were changed after zipping, so the entry + /// fails its CRC check. + pub(crate) fn broken_speaker_pack(packs: &Path) -> PathBuf { + let mut weights = zip_of(&[ + (engine::SEG_MODEL, b"segmentation model bytes"), + (engine::EMB_MODEL, b"embedding model bytes"), + ]); + let at = weights + .windows(b"segmentation model bytes".len()) + .position(|w| w == b"segmentation model bytes") + .unwrap(); + weights[at] ^= 0x01; + signed_pack(packs, "speakers-broken", "diarization", &weights) + } + + /// #38: a speaker pack that fails to unpack doesn't stop transcription. #[test] - fn resolve_verified_models_dir_in_fails_closed_when_diarization_models_missing() { + fn a_speaker_pack_that_fails_to_unpack_does_not_stop_transcription_models_resolving() { let (pem, versions) = fixtures_context(); let pubkey = PublicKey::SpkiPem(&pem); - let packs = repo_root().join("fixtures/modelpack/packs"); - let cache_base = unique_tmp("diarize"); - let _ = fs::remove_dir_all(&cache_base); + let packs = unique_tmp("broken-speakers-packs"); + copy_fixture_pack("asr-small-en", &packs); + broken_speaker_pack(&packs); + let cache_base = unique_tmp("broken-speakers-cache"); - let err = resolve_verified_models_dir_in( + let dir = resolve_verified_models_dir_in( &packs, &cache_base, &pubkey, &versions, engine::AsrModel::SmallEn, - true, ) - .expect_err("asr-only pack must not satisfy diarization"); - assert!( - err.contains("required model file") && err.contains("pyannote-segmentation"), - "expected missing seg/emb error, got: {err}" + .expect("transcription models must resolve"); + + for rel in engine::required_model_files(engine::AsrModel::SmallEn, false) { + assert!(dir.join(&rel).is_file(), "{rel} missing under {}", dir.display()); + } + let err = resolve_verified_speaker_dir_in(&packs, &cache_base, &pubkey, &versions) + .expect_err("the broken speaker pack can't be unpacked"); + assert!(err.contains("extracting zip entry"), "got: {err}"); + let _ = fs::remove_dir_all(&packs); + let _ = fs::remove_dir_all(&cache_base); + } + + /// The speaker models resolve from the speaker-detection pack on its own; + /// a packs folder without one has none. + #[test] + fn speaker_models_resolve_from_the_speaker_pack_alone() { + let (pem, versions) = fixtures_context(); + let pubkey = PublicKey::SpkiPem(&pem); + let packs = unique_tmp("speakers-packs"); + let weights = zip_of(&[(engine::SEG_MODEL, b""), (engine::EMB_MODEL, b"")]); + signed_pack(&packs, "speakers", "diarization", &weights); + let cache_base = unique_tmp("speakers-cache"); + + let dir = resolve_verified_speaker_dir_in(&packs, &cache_base, &pubkey, &versions) + .expect("the speaker pack must unpack") + .expect("the speaker pack provides the speaker models"); + assert!(dir.join(engine::SEG_MODEL).is_file()); + assert!(dir.join(engine::EMB_MODEL).is_file()); + + let asr_only = unique_tmp("speakers-asr-only-packs"); + copy_fixture_pack("asr-small-en", &asr_only); + assert_eq!( + resolve_verified_speaker_dir_in(&asr_only, &cache_base, &pubkey, &versions), + Ok(None) ); + for dir in [&packs, &asr_only, &cache_base] { + let _ = fs::remove_dir_all(dir); + } + } + + /// Resolving removes the old layout's shared cache folders (named by a + /// 64-hex hash) and keeps the per-pack and LLM ones. + #[test] + fn resolving_removes_the_old_shared_cache_folders() { + let (pem, versions) = fixtures_context(); + let pubkey = PublicKey::SpkiPem(&pem); + let packs = unique_tmp("old-cache-packs"); + copy_fixture_pack("asr-small-en", &packs); + let cache_base = unique_tmp("old-cache"); + let cached = cache_base.join("verified-models"); + let hash = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + let old = cached.join(hash); + let other_pack = cached.join(format!("pack-{hash}")); + let llm = cached.join(format!("llm-{hash}")); + for dir in [&old, &other_pack, &llm] { + fs::create_dir_all(dir).unwrap(); + fs::write(dir.join("silero_vad.onnx"), b"").unwrap(); + } + resolve_verified_models_dir_in( + &packs, + &cache_base, + &pubkey, + &versions, + engine::AsrModel::SmallEn, + ) + .expect("transcription models must resolve"); + + assert!(!old.exists(), "the old shared folder must be removed"); + assert!(other_pack.exists(), "a per-pack folder must stay"); + assert!(llm.exists(), "an LLM folder must stay"); + let _ = fs::remove_dir_all(&packs); let _ = fs::remove_dir_all(&cache_base); } /// Copy the committed fixture pack `name` into `packs//`. - fn copy_fixture_pack(name: &str, packs: &Path) -> PathBuf { + pub(crate) fn copy_fixture_pack(name: &str, packs: &Path) -> PathBuf { let src = repo_root().join("fixtures/modelpack/packs").join(name); let dest = packs.join(name); fs::create_dir_all(&dest).unwrap(); @@ -843,7 +994,6 @@ mod tests { &pubkey, &versions, engine::AsrModel::SmallEn, - false, ); let _ = tx.send(r); }); diff --git a/app/src-tauri/src/recorder.rs b/app/src-tauri/src/recorder.rs index 01f5793..e57b214 100644 --- a/app/src-tauri/src/recorder.rs +++ b/app/src-tauri/src/recorder.rs @@ -42,7 +42,7 @@ use serde::Serialize; use tauri::{AppHandle, Emitter, Manager}; use crate::commands::{ - finish_transcript, label_speakers, resolve_models_dir, speaker_engine, NewTranscript, + finish_transcript, label_speakers, resolve_models_dir, speaker_diarizer, NewTranscript, }; use crate::system; @@ -1394,13 +1394,11 @@ fn label_recording( done: &Finished, num_speakers: Option, ) -> anyhow::Result { - let mut cfg = done.cfg.clone(); - // Resolved again, so a pack added while recording counts. - cfg.models_dir = resolve_models_dir(app, cfg.asr_model).map_err(anyhow::Error::msg)?; - // Before reading the recording, which takes about 230 MB per hour. - let eng = speaker_engine(&cfg)?; + // Resolved at Stop, so a pack added while recording counts, and before + // reading the recording, which takes about 230 MB per hour. + let diarizer = speaker_diarizer(app, done.cfg.num_threads)?; let (samples, sr) = load_wav_16k_mono(&done.path)?; - label_speakers(&eng, &samples, sr, &done.segments, num_speakers) + label_speakers(&diarizer, &samples, sr, &done.segments, num_speakers) } /// Remove a finished recording's notes file once the transcript holding the diff --git a/engine/src/lib.rs b/engine/src/lib.rs index fcfb2a9..a7e7850 100644 --- a/engine/src/lib.rs +++ b/engine/src/lib.rs @@ -16,7 +16,7 @@ pub mod vocab; pub use decode::{decode_to_16k_mono, decode_to_16k_mono_with_progress, probe_duration_s}; pub use resample::StreamResampler; -pub use sherpa::{Recognizer, SherpaEngine, Vad, VadProfile}; +pub use sherpa::{Diarizer, Recognizer, SherpaEngine, Vad, VadProfile}; pub use vocab::{SkippedLine, Vocabulary}; /// A progress update emitted during the pipeline so the UI can render a @@ -367,12 +367,17 @@ pub fn required_model_files(asr_model: AsrModel, diarize: bool) -> Vec { let mut files = asr_model.asr_files(); files.push(VAD_MODEL.to_string()); if diarize { - files.push(SEG_MODEL.to_string()); - files.push(EMB_MODEL.to_string()); + files.extend(speaker_model_files()); } files } +/// The RELATIVE model-file paths diarization needs: what [`Diarizer::new`] +/// checks for, and what a speaker-detection pack must provide. +pub fn speaker_model_files() -> Vec { + vec![SEG_MODEL.to_string(), EMB_MODEL.to_string()] +} + #[derive(Debug, thiserror::Error)] pub enum EngineError { #[error("model file not found: {0}")] diff --git a/engine/src/sherpa.rs b/engine/src/sherpa.rs index cfdf2ad..db0500e 100644 --- a/engine/src/sherpa.rs +++ b/engine/src/sherpa.rs @@ -555,64 +555,36 @@ fn round3(x: f64) -> f64 { (x * 1000.0).round() / 1000.0 } -impl TranscriptionEngine for SherpaEngine { - fn transcribe( - &self, - samples: &[f32], - sample_rate: u32, - progress: &ProgressSink<'_>, - ) -> anyhow::Result> { - // Model load (esp. the ~600 MB Parakeet encoder) is a real wait; surface - // it as its own "loading" step. - progress(Progress::new("loading", 0, 0, crate::PROGRESS_DECODE_END)); - let recognizer = Recognizer { inner: self.build_recognizer()?, sample_rate }; - let chunks: Vec<(usize, std::borrow::Cow<'_, [f32]>)> = - if self.asr_model.decodes_pieces() { - // Parakeet decodes every sample, in ~15 s pieces cut at the - // quietest moment: VAD gating deleted a third of the words on - // room-mic meetings (docs/research/room-mic-capture-2026-11.md). - let mut edges = vec![0]; - edges.extend(energy_cuts(samples, sample_rate, PIECE_S, PIECE_SEARCH_S)); - edges.push(samples.len()); - progress(Progress::new("segmenting", 1, 1, crate::PROGRESS_VAD_END)); - edges - .windows(2) - .filter(|w| w[1] > w[0]) - .map(|w| (w[0], std::borrow::Cow::Borrowed(&samples[w[0]..w[1]]))) - .collect() - } else { - // Whisper must stay under its 30 s window, the autoregressive - // models have short output budgets, and Cohere invents text - // over silence: these keep the (levelled) VAD. - self.vad_chunks(samples, sample_rate, progress) - .context("VAD chunking")? - .into_iter() - .map(|(s, c)| (s, std::borrow::Cow::Owned(c))) - .collect() - }; - - let total = chunks.len() as u32; - let mut segments = Vec::new(); - for (k, (start_sample, chunk)) in chunks.iter().enumerate() { - // One tick per VAD chunk, filling [PROGRESS_VAD_END, - // PROGRESS_TRANSCRIBE_END] and leaving headroom for diarize/done. - let done = (k + 1) as u32; - let span = crate::PROGRESS_TRANSCRIBE_END - crate::PROGRESS_VAD_END; - let frac = if total > 0 { - crate::PROGRESS_VAD_END + span * (done as f32 / total as f32) - } else { - crate::PROGRESS_TRANSCRIBE_END - }; - progress(Progress::new("transcribing", done, total, frac)); +/// Speaker diarization (pyannote segmentation + 3D-Speaker embeddings + +/// FastClustering), bound to a folder holding only the speaker models: the +/// verified speaker-detection pack is unpacked on its own, apart from the +/// transcription models. +pub struct Diarizer { + models_dir: PathBuf, + num_threads: i32, +} - if let Some(seg) = recognizer.decode_utterance(*start_sample, chunk) { - segments.push(seg); +impl Diarizer { + /// Bind to `models_dir`, checking up front that it holds every + /// [`crate::speaker_model_files`] file. + pub fn new(models_dir: impl AsRef, num_threads: i32) -> anyhow::Result { + let models_dir = models_dir.as_ref().to_path_buf(); + for rel in crate::speaker_model_files() { + let p = models_dir.join(&rel); + if !p.exists() { + return Err(EngineError::ModelNotFound(p).into()); } } - Ok(segments) + Ok(Self { models_dir, num_threads }) } - fn diarize( + fn model_path(&self, rel: impl AsRef) -> String { + self.models_dir.join(rel).to_string_lossy().into_owned() + } + + /// Diarize 16 kHz mono `samples` into speaker spans. `num_speakers = None` + /// auto-detects. + pub fn diarize( &self, samples: &[f32], sample_rate: u32, @@ -674,6 +646,74 @@ impl TranscriptionEngine for SherpaEngine { } } +impl TranscriptionEngine for SherpaEngine { + fn transcribe( + &self, + samples: &[f32], + sample_rate: u32, + progress: &ProgressSink<'_>, + ) -> anyhow::Result> { + // Model load (esp. the ~600 MB Parakeet encoder) is a real wait; surface + // it as its own "loading" step. + progress(Progress::new("loading", 0, 0, crate::PROGRESS_DECODE_END)); + let recognizer = Recognizer { inner: self.build_recognizer()?, sample_rate }; + let chunks: Vec<(usize, std::borrow::Cow<'_, [f32]>)> = + if self.asr_model.decodes_pieces() { + // Parakeet decodes every sample, in ~15 s pieces cut at the + // quietest moment: VAD gating deleted a third of the words on + // room-mic meetings (docs/research/room-mic-capture-2026-11.md). + let mut edges = vec![0]; + edges.extend(energy_cuts(samples, sample_rate, PIECE_S, PIECE_SEARCH_S)); + edges.push(samples.len()); + progress(Progress::new("segmenting", 1, 1, crate::PROGRESS_VAD_END)); + edges + .windows(2) + .filter(|w| w[1] > w[0]) + .map(|w| (w[0], std::borrow::Cow::Borrowed(&samples[w[0]..w[1]]))) + .collect() + } else { + // Whisper must stay under its 30 s window, the autoregressive + // models have short output budgets, and Cohere invents text + // over silence: these keep the (levelled) VAD. + self.vad_chunks(samples, sample_rate, progress) + .context("VAD chunking")? + .into_iter() + .map(|(s, c)| (s, std::borrow::Cow::Owned(c))) + .collect() + }; + + let total = chunks.len() as u32; + let mut segments = Vec::new(); + for (k, (start_sample, chunk)) in chunks.iter().enumerate() { + // One tick per VAD chunk, filling [PROGRESS_VAD_END, + // PROGRESS_TRANSCRIBE_END] and leaving headroom for diarize/done. + let done = (k + 1) as u32; + let span = crate::PROGRESS_TRANSCRIBE_END - crate::PROGRESS_VAD_END; + let frac = if total > 0 { + crate::PROGRESS_VAD_END + span * (done as f32 / total as f32) + } else { + crate::PROGRESS_TRANSCRIBE_END + }; + progress(Progress::new("transcribing", done, total, frac)); + + if let Some(seg) = recognizer.decode_utterance(*start_sample, chunk) { + segments.push(seg); + } + } + Ok(segments) + } + + fn diarize( + &self, + samples: &[f32], + sample_rate: u32, + num_speakers: Option, + ) -> anyhow::Result> { + let diarizer = Diarizer { models_dir: self.models_dir.clone(), num_threads: self.num_threads }; + diarizer.diarize(samples, sample_rate, num_speakers) + } +} + #[cfg(test)] mod new_tests { use super::*; From af16e5ef2ea23f1fe5429e56a11186cbf12d7b3a Mon Sep 17 00:00:00 2001 From: billlyzhaoyh Date: Thu, 26 Nov 2026 17:07:14 +0000 Subject: [PATCH 2/3] refactor: simplify the per-pack resolver and speaker step MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From /simplify on #40. - `verified_packs` takes the task and returns verified packs newest first; `verified_packs_of` and `pick_pack` are gone. Transcription stops at the newest pack whose zip lists its files, opening fewer zips. The speaker step takes the newest verified speaker pack, so one missing its files says "Speakers couldn't be labelled (…)" rather than "isn't installed". - One `unpacked(pack, cache_base, prefix)` serves speech packs (`pack-`) and the LLM pack (`llm-`), and the LLM resolver shares the newest-first rule. - `with_installed` builds the packs folder, cache folder, key and engine versions once for the three AppHandle wrappers; `packs_dir` reuses `app_cache_base`. - Engine: `transcription_model_files(asr_model)` sits beside `speaker_model_files()`; `required_model_files` combines them. `SherpaEngine::new` and `Diarizer::new` share `require_files` and `model_path`, and `Diarizer` moves below the trait impl so the impl's diff stays small. - The recorder's `Finished` keeps only `num_threads`, not a whole config; the debug override's file check is shared (`holds_all`). --- app/src-tauri/src/commands.rs | 16 ++-- app/src-tauri/src/models.rs | 163 ++++++++++++++-------------------- app/src-tauri/src/recorder.rs | 7 +- engine/src/lib.rs | 11 ++- engine/src/sherpa.rs | 162 +++++++++++++++++---------------- 5 files changed, 175 insertions(+), 184 deletions(-) diff --git a/app/src-tauri/src/commands.rs b/app/src-tauri/src/commands.rs index 3fcc674..4f64118 100644 --- a/app/src-tauri/src/commands.rs +++ b/app/src-tauri/src/commands.rs @@ -123,6 +123,12 @@ fn debug_models_dir_override() -> Option { std::env::var("KINDTECH_MODELS_DIR").ok().map(std::path::PathBuf::from) } +/// Whether every one of `files` (relative paths) is a file under `dir`. +#[cfg(debug_assertions)] +fn holds_all(dir: &std::path::Path, files: Vec) -> bool { + files.iter().all(|file| dir.join(file).is_file()) +} + /// Report a usable raw-model override to the frontend in development builds. /// /// This keeps the import preflight honest when developers run with @@ -139,10 +145,7 @@ pub fn debug_asr_model_override() -> Option { (engine::AsrModel::SmallEn, "small.en"), (engine::AsrModel::MediumEn, "medium.en"), ] { - if engine::required_model_files(model, false) - .iter() - .all(|file| dir.join(file).is_file()) - { + if holds_all(&dir, engine::transcription_model_files(model)) { return Some(name.to_string()); } } @@ -170,11 +173,10 @@ pub(crate) fn resolve_models_dir( /// Resolve the speaker-detection models' folder, or `None` when no verified /// speaker-detection pack is installed (debug-only raw override: the override /// folder, if it holds the speaker models). Blocking: may unpack the pack. -pub(crate) fn resolve_speaker_dir(app: &AppHandle) -> Result, String> { +fn resolve_speaker_dir(app: &AppHandle) -> Result, String> { #[cfg(debug_assertions)] if let Some(raw) = debug_models_dir_override() { - let present = engine::speaker_model_files().iter().all(|file| raw.join(file).is_file()); - return Ok(present.then_some(raw)); + return Ok(holds_all(&raw, engine::speaker_model_files()).then_some(raw)); } models::resolve_verified_speaker_dir(app) } diff --git a/app/src-tauri/src/models.rs b/app/src-tauri/src/models.rs index d4bc709..7a8bf76 100644 --- a/app/src-tauri/src/models.rs +++ b/app/src-tauri/src/models.rs @@ -156,11 +156,7 @@ fn packs_dir(app: &tauri::AppHandle) -> Result { if let Ok(dir) = std::env::var("KINDTECH_PACKS_DIR") { return Ok(PathBuf::from(dir)); } - let base = app - .path() - .app_data_dir() - .map_err(|e| format!("cannot resolve app data dir: {e}"))?; - Ok(base.join("packs")) + Ok(app_cache_base(app)?.join("packs")) } /// List + verify every pack in the packs dir. Returns an empty list (not an @@ -296,30 +292,31 @@ fn declared_task(dir: &Path) -> Option { value.get("task").and_then(Value::as_str).map(str::to_string) } -/// Verify every pack directory in `packs_dir` whose declared task passes -/// `wanted`, returning the verified ones. Packs with an unreadable manifest are -/// still verified (and so rejected). +/// Verify every pack directory in `packs_dir` that declares `task`, returning +/// the verified ones, newest first: highest version, ties going to the last +/// directory name. Packs with an unreadable manifest are still verified (and so +/// rejected). fn verified_packs( packs_dir: &Path, pubkey: &PublicKey<'_>, engine_versions: &BTreeMap, - wanted: impl Fn(&str) -> bool, + task: &str, ) -> Vec<(PathBuf, PackStatus)> { let mut out: Vec<(PathBuf, PackStatus)> = match std::fs::read_dir(packs_dir) { Ok(entries) => entries .filter_map(|e| e.ok()) .map(|e| e.path()) .filter(|p| p.is_dir()) - .filter(|p| declared_task(p).is_none_or(|t| wanted(&t))) + .filter(|p| declared_task(p).is_none_or(|t| t == task)) .map(|p| { let status = verify_pack_dir(&p, pubkey, engine_versions); (p, status) }) - .filter(|(_, status)| status.verified) + .filter(|(_, status)| status.verified && status.task == task) .collect(), Err(_) => Vec::new(), }; - out.sort_by(|a, b| a.0.cmp(&b.0)); + out.sort_by(|a, b| compare_semver(&b.1.version, &a.1.version).then(b.0.cmp(&a.0))); out } @@ -336,57 +333,35 @@ fn zip_lists(weights: &Path, files: &[String]) -> bool { files.iter().all(|f| names.contains(f.as_str())) } -/// The verified packs of `task` in `packs_dir` (see [`verified_packs`]). -fn verified_packs_of( - packs_dir: &Path, - pubkey: &PublicKey<'_>, - engine_versions: &BTreeMap, - task: &str, -) -> Vec<(PathBuf, PackStatus)> { - verified_packs(packs_dir, pubkey, engine_versions, |t| t == task) - .into_iter() - .filter(|(_, status)| status.task == task) - .collect() -} - -/// The pack among `packs` that holds every one of `files`: the highest -/// version, ties going to the last directory name. -fn pick_pack(packs: Vec<(PathBuf, PackStatus)>, files: &[String]) -> Option { - let mut packs: Vec<(PathBuf, PackStatus)> = packs - .into_iter() - .filter(|(dir, _)| zip_lists(&dir.join("weights.bin"), files)) - .collect(); - packs.sort_by(|a, b| compare_semver(&a.1.version, &b.1.version).then(a.0.cmp(&b.0))); - packs.pop().map(|(dir, _)| dir) -} - -/// Unpack the zip at `weights` into `dest` unless a `.complete` marker says a -/// previous run already did; a partial folder from an interrupted run is -/// cleared first. -fn unpack_once(weights: &Path, dest: &Path) -> Result<(), String> { +/// `pack` unpacked into its own content-addressed cache folder, +/// `cache_base/verified-models/-/`. A `.complete` +/// marker skips the unpack on later runs; a partial folder from an interrupted +/// run is cleared first. +fn unpacked(pack: &Path, cache_base: &Path, prefix: &str) -> Result { + let dest = cache_base + .join("verified-models") + .join(format!("{prefix}-{}", manifest_sha256(pack)?)); let complete_marker = dest.join(".complete"); if complete_marker.exists() { - return Ok(()); + return Ok(dest); } if dest.exists() { - std::fs::remove_dir_all(dest) + std::fs::remove_dir_all(&dest) .map_err(|e| format!("clearing partial cache {}: {e}", dest.display()))?; } - std::fs::create_dir_all(dest) + std::fs::create_dir_all(&dest) .map_err(|e| format!("creating cache dir {}: {e}", dest.display()))?; - extract_zip_into(weights, dest)?; + extract_zip_into(&pack.join("weights.bin"), &dest)?; std::fs::write(&complete_marker, b"") - .map_err(|e| format!("writing completion marker {}: {e}", complete_marker.display())) + .map_err(|e| format!("writing completion marker {}: {e}", complete_marker.display()))?; + Ok(dest) } -/// The verified speech pack `pack`, unpacked into its own content-addressed -/// cache folder, `cache_base/verified-models/pack-/`, and -/// checked to hold every one of `files`. -fn unpacked_pack(pack: &Path, cache_base: &Path, files: &[String]) -> Result { - let dest = cache_base - .join("verified-models") - .join(format!("pack-{}", manifest_sha256(pack)?)); - unpack_once(&pack.join("weights.bin"), &dest)?; +/// The verified speech pack `pack`, unpacked (see [`unpacked`]) into +/// `verified-models/pack-/` and checked to hold every one of +/// `files`. +fn unpacked_speech_pack(pack: &Path, cache_base: &Path, files: &[String]) -> Result { + let dest = unpacked(pack, cache_base, "pack")?; let missing: Vec<&String> = files.iter().filter(|rel| !dest.join(rel).exists()).collect(); if !missing.is_empty() { return Err(format!("verified pack {} is missing {missing:?}", pack.display())); @@ -412,8 +387,8 @@ fn remove_old_shared_caches(cache_base: &Path) { /// Verified transcription-pack resolver. Enumerates `packs_dir`, VERIFIES every /// `task: "asr"` pack, picks one holding every model file the engine requires -/// for `asr_model` (each ASR pack carries Silero VAD too), and unpacks only that -/// pack into its own cache folder (see [`unpacked_pack`]). Fails closed: no +/// for `asr_model` (each ASR pack carries Silero VAD too), newest first, and +/// unpacks only that pack into its own cache folder (see [`unpacked_speech_pack`]). Fails closed: no /// verified pack, or none providing the required files, is an `Err`. Other /// packs, the speaker-detection pack included, are never unpacked here, so one /// that fails to unpack can't stop transcription (#38). @@ -427,15 +402,17 @@ pub fn resolve_verified_models_dir_in( asr_model: engine::AsrModel, ) -> Result { remove_old_shared_caches(cache_base); - let files = engine::required_model_files(asr_model, false); - let packs = verified_packs_of(packs_dir, pubkey, engine_versions, ASR_TASK); + let files = engine::transcription_model_files(asr_model); + let packs = verified_packs(packs_dir, pubkey, engine_versions, ASR_TASK); if packs.is_empty() { return Err(format!("no verified model pack found in {}", packs_dir.display())); } - let pack = pick_pack(packs, &files).ok_or_else(|| { - format!("no verified pack provides the required model file(s): {files:?}") - })?; - unpacked_pack(&pack, cache_base, &files) + // The zip's directory names its files, so this unpacks nothing. + let (pack, _) = packs + .into_iter() + .find(|(dir, _)| zip_lists(&dir.join("weights.bin"), &files)) + .ok_or_else(|| format!("no verified pack provides the required model file(s): {files:?}"))?; + unpacked_speech_pack(&pack, cache_base, &files) } /// AppHandle wrapper around [`resolve_verified_models_dir_in`]. @@ -443,47 +420,51 @@ pub fn resolve_verified_models_dir( app: &tauri::AppHandle, asr_model: engine::AsrModel, ) -> Result { - let packs = packs_dir(app)?; - let cache_base = app_cache_base(app)?; - let pubkey = PublicKey::SpkiPem(vendor_pubkey_pem()); - let versions = engine_versions(); - resolve_verified_models_dir_in(&packs, &cache_base, &pubkey, &versions, asr_model) + with_installed(app, |packs, cache, key, versions| { + resolve_verified_models_dir_in(packs, cache, key, versions, asr_model) + }) } -/// Verified speaker-detection-pack resolver: the cache folder of a verified -/// `task: "diarization"` pack holding [`engine::speaker_model_files`], unpacked -/// on its own (see [`unpacked_pack`]). `Ok(None)` when no verified pack -/// provides them; `Err` when the pack can't be unpacked. +/// Verified speaker-detection-pack resolver: the newest verified +/// `task: "diarization"` pack, unpacked on its own (see +/// [`unpacked_speech_pack`]) and checked to hold [`engine::speaker_model_files`]. +/// `Ok(None)` when no verified speaker pack is installed; `Err` when it can't be +/// unpacked or lacks those files. pub fn resolve_verified_speaker_dir_in( packs_dir: &Path, cache_base: &Path, pubkey: &PublicKey<'_>, engine_versions: &BTreeMap, ) -> Result, String> { - let files = engine::speaker_model_files(); - let packs = verified_packs_of(packs_dir, pubkey, engine_versions, DIARIZATION_TASK); - match pick_pack(packs, &files) { - Some(pack) => unpacked_pack(&pack, cache_base, &files).map(Some), - None => Ok(None), - } + let newest = verified_packs(packs_dir, pubkey, engine_versions, DIARIZATION_TASK).into_iter().next(); + newest + .map(|(pack, _)| unpacked_speech_pack(&pack, cache_base, &engine::speaker_model_files())) + .transpose() } /// AppHandle wrapper around [`resolve_verified_speaker_dir_in`]. pub fn resolve_verified_speaker_dir(app: &tauri::AppHandle) -> Result, String> { - let packs = packs_dir(app)?; - let cache_base = app_cache_base(app)?; - let pubkey = PublicKey::SpkiPem(vendor_pubkey_pem()); - let versions = engine_versions(); - resolve_verified_speaker_dir_in(&packs, &cache_base, &pubkey, &versions) + with_installed(app, resolve_verified_speaker_dir_in) } -/// Where verified packs are unpacked: the per-user app-data dir. +/// The per-user app-data dir: where packs are installed and unpacked. fn app_cache_base(app: &tauri::AppHandle) -> Result { app.path() .app_data_dir() .map_err(|e| format!("cannot resolve app data dir: {e}")) } +/// Run a `_in` resolver against this app's packs folder, cache folder, trusted +/// vendor key and engine versions. +fn with_installed( + app: &tauri::AppHandle, + resolve: impl FnOnce(&Path, &Path, &PublicKey<'_>, &BTreeMap) -> Result, +) -> Result { + let packs = packs_dir(app)?; + let cache_base = app_cache_base(app)?; + resolve(&packs, &cache_base, &PublicKey::SpkiPem(vendor_pubkey_pem()), &engine_versions()) +} + /// Verified LLM-pack resolver. Enumerates `packs_dir`, VERIFIES every pack, and /// takes the verified `task: "llm"` pack with the highest version (ties: last /// directory name). Its `weights.bin` zip is streamed into @@ -499,19 +480,15 @@ pub fn resolve_verified_llm_in( pubkey: &PublicKey<'_>, engine_versions: &BTreeMap, ) -> Result { - let mut llm_packs = verified_packs_of(packs_dir, pubkey, engine_versions, LLM_TASK); - llm_packs.sort_by(|a, b| compare_semver(&a.1.version, &b.1.version).then(a.0.cmp(&b.0))); - let Some((dir, status)) = llm_packs.pop() else { + let newest = verified_packs(packs_dir, pubkey, engine_versions, LLM_TASK).into_iter().next(); + let Some((dir, status)) = newest else { return Err(format!( "no verified LLM model pack found in {}", packs_dir.display() )); }; - let dest = cache_base - .join("verified-models") - .join(format!("llm-{}", manifest_sha256(&dir)?)); - unpack_once(&dir.join("weights.bin"), &dest)?; + let dest = unpacked(&dir, cache_base, "llm")?; let ggufs: Vec = std::fs::read_dir(&dest) .map_err(|e| format!("reading cache dir {}: {e}", dest.display()))? @@ -537,11 +514,7 @@ pub fn resolve_verified_llm_in( /// AppHandle wrapper around [`resolve_verified_llm_in`]. #[allow(dead_code)] // Spike S5: not called by the app yet; P2 (local notes) will use it. pub fn resolve_verified_llm(app: &tauri::AppHandle) -> Result { - let packs = packs_dir(app)?; - let cache_base = app_cache_base(app)?; - let pubkey = PublicKey::SpkiPem(vendor_pubkey_pem()); - let versions = engine_versions(); - resolve_verified_llm_in(&packs, &cache_base, &pubkey, &versions) + with_installed(app, resolve_verified_llm_in) } #[cfg(test)] @@ -549,7 +522,7 @@ pub(crate) mod tests { use super::*; use std::fs; - pub(crate) fn repo_root() -> PathBuf { + fn repo_root() -> PathBuf { // CARGO_MANIFEST_DIR = /app/src-tauri Path::new(env!("CARGO_MANIFEST_DIR")) .ancestors() diff --git a/app/src-tauri/src/recorder.rs b/app/src-tauri/src/recorder.rs index e57b214..3007da3 100644 --- a/app/src-tauri/src/recorder.rs +++ b/app/src-tauri/src/recorder.rs @@ -1324,7 +1324,8 @@ pub fn resume_recording(app: AppHandle) -> Result<(), String> { struct Finished { path: PathBuf, - cfg: EngineConfig, + /// Threads the recording's engine used; speaker labelling uses as many. + num_threads: i32, segments: Vec, /// Seconds of the record that couldn't be transcribed. unread_s: f64, @@ -1356,7 +1357,7 @@ fn finish(app: &AppHandle, discarding: bool) -> Result { let mut segments = active.segments.lock().unwrap().clone(); segments.sort_by(|a, b| a.start.partial_cmp(&b.start).unwrap_or(std::cmp::Ordering::Equal)); let unread_s = active.unread.load(Ordering::Relaxed) as f64 / SAMPLE_RATE as f64; - Ok(Finished { path: active.path, cfg: active.cfg, segments, unread_s }) + Ok(Finished { path: active.path, num_threads: active.cfg.num_threads, segments, unread_s }) } /// Stop recording and build the transcript from the record's pieces, with @@ -1396,7 +1397,7 @@ fn label_recording( ) -> anyhow::Result { // Resolved at Stop, so a pack added while recording counts, and before // reading the recording, which takes about 230 MB per hour. - let diarizer = speaker_diarizer(app, done.cfg.num_threads)?; + let diarizer = speaker_diarizer(app, done.num_threads)?; let (samples, sr) = load_wav_16k_mono(&done.path)?; label_speakers(&diarizer, &samples, sr, &done.segments, num_speakers) } diff --git a/engine/src/lib.rs b/engine/src/lib.rs index a7e7850..2dd4e56 100644 --- a/engine/src/lib.rs +++ b/engine/src/lib.rs @@ -364,14 +364,21 @@ pub const EMB_MODEL: &str = "3dspeaker_speech_campplus_sv_en_voxceleb_16k.onnx"; /// [`SherpaEngine::new`]'s existence check and the verified-pack resolver, so /// the two can never drift. pub fn required_model_files(asr_model: AsrModel, diarize: bool) -> Vec { - let mut files = asr_model.asr_files(); - files.push(VAD_MODEL.to_string()); + let mut files = transcription_model_files(asr_model); if diarize { files.extend(speaker_model_files()); } files } +/// The RELATIVE model-file paths transcription needs (the ASR model's files and +/// Silero VAD): what a transcription pack must provide. +pub fn transcription_model_files(asr_model: AsrModel) -> Vec { + let mut files = asr_model.asr_files(); + files.push(VAD_MODEL.to_string()); + files +} + /// The RELATIVE model-file paths diarization needs: what [`Diarizer::new`] /// checks for, and what a speaker-detection pack must provide. pub fn speaker_model_files() -> Vec { diff --git a/engine/src/sherpa.rs b/engine/src/sherpa.rs index db0500e..8810e59 100644 --- a/engine/src/sherpa.rs +++ b/engine/src/sherpa.rs @@ -261,12 +261,7 @@ impl SherpaEngine { let dir = &cfg.models_dir; // Build the required list from the shared source of truth so the // diarization models are required ONLY when `cfg.diarize`. - for rel in crate::required_model_files(cfg.asr_model, cfg.diarize) { - let p = dir.join(&rel); - if !p.exists() { - return Err(EngineError::ModelNotFound(p).into()); - } - } + require_files(dir, crate::required_model_files(cfg.asr_model, cfg.diarize))?; if let Some(h) = &cfg.hotwords { if !h.file.exists() { return Err(EngineError::ModelNotFound(h.file.clone()).into()); @@ -288,7 +283,7 @@ impl SherpaEngine { } fn model_path(&self, rel: impl AsRef) -> String { - self.models_dir.join(rel).to_string_lossy().into_owned() + model_path(&self.models_dir, rel) } fn build_recognizer(&self) -> anyhow::Result { @@ -555,6 +550,74 @@ fn round3(x: f64) -> f64 { (x * 1000.0).round() / 1000.0 } +impl TranscriptionEngine for SherpaEngine { + fn transcribe( + &self, + samples: &[f32], + sample_rate: u32, + progress: &ProgressSink<'_>, + ) -> anyhow::Result> { + // Model load (esp. the ~600 MB Parakeet encoder) is a real wait; surface + // it as its own "loading" step. + progress(Progress::new("loading", 0, 0, crate::PROGRESS_DECODE_END)); + let recognizer = Recognizer { inner: self.build_recognizer()?, sample_rate }; + let chunks: Vec<(usize, std::borrow::Cow<'_, [f32]>)> = + if self.asr_model.decodes_pieces() { + // Parakeet decodes every sample, in ~15 s pieces cut at the + // quietest moment: VAD gating deleted a third of the words on + // room-mic meetings (docs/research/room-mic-capture-2026-11.md). + let mut edges = vec![0]; + edges.extend(energy_cuts(samples, sample_rate, PIECE_S, PIECE_SEARCH_S)); + edges.push(samples.len()); + progress(Progress::new("segmenting", 1, 1, crate::PROGRESS_VAD_END)); + edges + .windows(2) + .filter(|w| w[1] > w[0]) + .map(|w| (w[0], std::borrow::Cow::Borrowed(&samples[w[0]..w[1]]))) + .collect() + } else { + // Whisper must stay under its 30 s window, the autoregressive + // models have short output budgets, and Cohere invents text + // over silence: these keep the (levelled) VAD. + self.vad_chunks(samples, sample_rate, progress) + .context("VAD chunking")? + .into_iter() + .map(|(s, c)| (s, std::borrow::Cow::Owned(c))) + .collect() + }; + + let total = chunks.len() as u32; + let mut segments = Vec::new(); + for (k, (start_sample, chunk)) in chunks.iter().enumerate() { + // One tick per VAD chunk, filling [PROGRESS_VAD_END, + // PROGRESS_TRANSCRIBE_END] and leaving headroom for diarize/done. + let done = (k + 1) as u32; + let span = crate::PROGRESS_TRANSCRIBE_END - crate::PROGRESS_VAD_END; + let frac = if total > 0 { + crate::PROGRESS_VAD_END + span * (done as f32 / total as f32) + } else { + crate::PROGRESS_TRANSCRIBE_END + }; + progress(Progress::new("transcribing", done, total, frac)); + + if let Some(seg) = recognizer.decode_utterance(*start_sample, chunk) { + segments.push(seg); + } + } + Ok(segments) + } + + fn diarize( + &self, + samples: &[f32], + sample_rate: u32, + num_speakers: Option, + ) -> anyhow::Result> { + let diarizer = Diarizer { models_dir: self.models_dir.clone(), num_threads: self.num_threads }; + diarizer.diarize(samples, sample_rate, num_speakers) + } +} + /// Speaker diarization (pyannote segmentation + 3D-Speaker embeddings + /// FastClustering), bound to a folder holding only the speaker models: the /// verified speaker-detection pack is unpacked on its own, apart from the @@ -569,17 +632,12 @@ impl Diarizer { /// [`crate::speaker_model_files`] file. pub fn new(models_dir: impl AsRef, num_threads: i32) -> anyhow::Result { let models_dir = models_dir.as_ref().to_path_buf(); - for rel in crate::speaker_model_files() { - let p = models_dir.join(&rel); - if !p.exists() { - return Err(EngineError::ModelNotFound(p).into()); - } - } + require_files(&models_dir, crate::speaker_model_files())?; Ok(Self { models_dir, num_threads }) } fn model_path(&self, rel: impl AsRef) -> String { - self.models_dir.join(rel).to_string_lossy().into_owned() + model_path(&self.models_dir, rel) } /// Diarize 16 kHz mono `samples` into speaker spans. `num_speakers = None` @@ -646,72 +704,22 @@ impl Diarizer { } } -impl TranscriptionEngine for SherpaEngine { - fn transcribe( - &self, - samples: &[f32], - sample_rate: u32, - progress: &ProgressSink<'_>, - ) -> anyhow::Result> { - // Model load (esp. the ~600 MB Parakeet encoder) is a real wait; surface - // it as its own "loading" step. - progress(Progress::new("loading", 0, 0, crate::PROGRESS_DECODE_END)); - let recognizer = Recognizer { inner: self.build_recognizer()?, sample_rate }; - let chunks: Vec<(usize, std::borrow::Cow<'_, [f32]>)> = - if self.asr_model.decodes_pieces() { - // Parakeet decodes every sample, in ~15 s pieces cut at the - // quietest moment: VAD gating deleted a third of the words on - // room-mic meetings (docs/research/room-mic-capture-2026-11.md). - let mut edges = vec![0]; - edges.extend(energy_cuts(samples, sample_rate, PIECE_S, PIECE_SEARCH_S)); - edges.push(samples.len()); - progress(Progress::new("segmenting", 1, 1, crate::PROGRESS_VAD_END)); - edges - .windows(2) - .filter(|w| w[1] > w[0]) - .map(|w| (w[0], std::borrow::Cow::Borrowed(&samples[w[0]..w[1]]))) - .collect() - } else { - // Whisper must stay under its 30 s window, the autoregressive - // models have short output budgets, and Cohere invents text - // over silence: these keep the (levelled) VAD. - self.vad_chunks(samples, sample_rate, progress) - .context("VAD chunking")? - .into_iter() - .map(|(s, c)| (s, std::borrow::Cow::Owned(c))) - .collect() - }; - - let total = chunks.len() as u32; - let mut segments = Vec::new(); - for (k, (start_sample, chunk)) in chunks.iter().enumerate() { - // One tick per VAD chunk, filling [PROGRESS_VAD_END, - // PROGRESS_TRANSCRIBE_END] and leaving headroom for diarize/done. - let done = (k + 1) as u32; - let span = crate::PROGRESS_TRANSCRIBE_END - crate::PROGRESS_VAD_END; - let frac = if total > 0 { - crate::PROGRESS_VAD_END + span * (done as f32 / total as f32) - } else { - crate::PROGRESS_TRANSCRIBE_END - }; - progress(Progress::new("transcribing", done, total, frac)); - - if let Some(seg) = recognizer.decode_utterance(*start_sample, chunk) { - segments.push(seg); - } +/// Fail with [`EngineError::ModelNotFound`] naming the first of `files` +/// (relative to `dir`) that is missing, so a missing file fails with a clear +/// path rather than a deep sherpa error. +fn require_files(dir: &Path, files: Vec) -> Result<(), EngineError> { + for rel in files { + let p = dir.join(&rel); + if !p.exists() { + return Err(EngineError::ModelNotFound(p)); } - Ok(segments) } + Ok(()) +} - fn diarize( - &self, - samples: &[f32], - sample_rate: u32, - num_speakers: Option, - ) -> anyhow::Result> { - let diarizer = Diarizer { models_dir: self.models_dir.clone(), num_threads: self.num_threads }; - diarizer.diarize(samples, sample_rate, num_speakers) - } +/// `rel` under `dir`, as the string sherpa-onnx configs take. +fn model_path(dir: &Path, rel: impl AsRef) -> String { + dir.join(rel).to_string_lossy().into_owned() } #[cfg(test)] From ee9cf7560da3bce2ca2ade81d4c9706fdba2f456 Mon Sep 17 00:00:00 2001 From: billlyzhaoyh Date: Thu, 26 Nov 2026 17:16:05 +0000 Subject: [PATCH 3/3] test(app): sign test packs without the modelpack-sign crate The dev-dependency on tools/modelpack-sign changed the features of crates sherpa-onnx-sys's build uses (rand_core/getrandom, ring, rustls, ureq). On CI's partly matching cache, sherpa-onnx-sys was then rebuilt without re-fetching its prebuilt native library, and the app backend jobs on Linux and Windows failed to find `sherpa-onnx-c-api`. The tests now sign packs with ed25519-dalek (already a dev-dependency) and `modelpack::canonicalize`, encoding the signature with base64, which is already in the tree through `modelpack` with the same features. --- app/src-tauri/Cargo.lock | 143 +----------------------------------- app/src-tauri/Cargo.toml | 6 +- app/src-tauri/src/models.rs | 24 +++--- 3 files changed, 19 insertions(+), 154 deletions(-) diff --git a/app/src-tauri/Cargo.lock b/app/src-tauri/Cargo.lock index 0eb7868..f73fd6b 100644 --- a/app/src-tauri/Cargo.lock +++ b/app/src-tauri/Cargo.lock @@ -85,56 +85,6 @@ dependencies = [ "libc", ] -[[package]] -name = "anstream" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" -dependencies = [ - "anstyle", - "anstyle-parse", - "anstyle-query", - "anstyle-wincon", - "colorchoice", - "is_terminal_polyfill", - "utf8parse", -] - -[[package]] -name = "anstyle" -version = "1.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" - -[[package]] -name = "anstyle-parse" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" -dependencies = [ - "utf8parse", -] - -[[package]] -name = "anstyle-query" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "anstyle-wincon" -version = "3.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" -dependencies = [ - "anstyle", - "once_cell_polyfill", - "windows-sys 0.61.2", -] - [[package]] name = "anyhow" version = "1.0.102" @@ -512,58 +462,12 @@ dependencies = [ "inout 0.2.6", ] -[[package]] -name = "clap" -version = "4.6.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" -dependencies = [ - "clap_builder", - "clap_derive", -] - -[[package]] -name = "clap_builder" -version = "4.6.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" -dependencies = [ - "anstream", - "anstyle", - "clap_lex", - "strsim", -] - -[[package]] -name = "clap_derive" -version = "4.6.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" -dependencies = [ - "heck 0.5.0", - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "clap_lex" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" - [[package]] name = "cmov" version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" -[[package]] -name = "colorchoice" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" - [[package]] name = "combine" version = "4.6.7" @@ -1134,7 +1038,6 @@ checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" dependencies = [ "curve25519-dalek", "ed25519", - "rand_core", "serde", "sha2 0.10.9", "subtle", @@ -2072,12 +1975,6 @@ version = "2.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" -[[package]] -name = "is_terminal_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" - [[package]] name = "itoa" version = "1.0.18" @@ -2240,13 +2137,13 @@ name = "kindtech-transcribe-app" version = "0.3.0" dependencies = [ "anyhow", + "base64 0.22.1", "chrono", "cpal", "ed25519-dalek", "engine", "hound", "modelpack", - "modelpack-sign", "objc2-core-audio", "serde", "serde_json", @@ -2463,21 +2360,6 @@ dependencies = [ "thiserror 2.0.18", ] -[[package]] -name = "modelpack-sign" -version = "0.1.0" -dependencies = [ - "anyhow", - "base64 0.22.1", - "clap", - "ed25519-dalek", - "modelpack", - "rand_core", - "serde_json", - "walkdir", - "zip 2.4.2", -] - [[package]] name = "muda" version = "0.19.2" @@ -2875,12 +2757,6 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" -[[package]] -name = "once_cell_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" - [[package]] name = "option-ext" version = "0.2.0" @@ -4152,17 +4028,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "syn" -version = "3.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - [[package]] name = "sync_wrapper" version = "1.0.2" @@ -5041,12 +4906,6 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" -[[package]] -name = "utf8parse" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" - [[package]] name = "uuid" version = "1.23.3" diff --git a/app/src-tauri/Cargo.toml b/app/src-tauri/Cargo.toml index b96b68d..6c8c28f 100644 --- a/app/src-tauri/Cargo.toml +++ b/app/src-tauri/Cargo.toml @@ -17,9 +17,9 @@ ed25519-dalek = { version = "2", features = ["pem"] } [dev-dependencies] ed25519-dalek = { version = "2", features = ["pem"] } -# The pack producer, so tests can sign packs with the committed test key. Tests -# only: never linked into the app. -modelpack-sign = { path = "../../tools/modelpack-sign" } +# Tests sign packs with the committed test key (ed25519-dalek above). Already in +# the tree through `modelpack`, with the same features. +base64 = "0.22" [dependencies] # In-process engine via a PATH dependency — NOT a registry fetch. Pulls diff --git a/app/src-tauri/src/models.rs b/app/src-tauri/src/models.rs index 7a8bf76..46d9984 100644 --- a/app/src-tauri/src/models.rs +++ b/app/src-tauri/src/models.rs @@ -734,27 +734,33 @@ pub(crate) mod tests { /// Write `packs//` as a pack of `weights`, signed with the committed /// test key, declaring `task`. fn signed_pack(packs: &Path, name: &str, task: &str, weights: &[u8]) -> PathBuf { + use base64::Engine as _; use ed25519_dalek::pkcs8::DecodePrivateKey; + use ed25519_dalek::Signer as _; let pem = fs::read_to_string(repo_root().join("fixtures/modelpack/keys/test-private.pkcs8.pem")) .unwrap(); let key = ed25519_dalek::SigningKey::from_pkcs8_pem(&pem).unwrap(); - let meta = modelpack_sign::PackMeta { - id: format!("test/{name}"), - version: "1.0.0".into(), + let manifest = modelpack::Manifest { + attribution: "Test pack".into(), engine: "sherpa-onnx".into(), engine_min_version: "1.13.2".into(), - task: task.into(), + id: format!("test/{name}"), license: "MIT".into(), - attribution: "Test pack".into(), + sha256: modelpack::sha256_hex_reader(weights).unwrap(), + task: task.into(), + version: "1.0.0".into(), + signature: String::new(), }; - let sha = modelpack::sha256_hex_reader(weights).unwrap(); - let signature = modelpack_sign::sign_manifest(&key, &meta, &sha); + let signature = key.sign(&modelpack::canonicalize(&manifest)); + // `signature` is left out of the serialized manifest; add it back. + let mut json = serde_json::to_value(&manifest).unwrap(); + json["signature"] = + base64::engine::general_purpose::STANDARD.encode(signature.to_bytes()).into(); let dir = packs.join(name); fs::create_dir_all(&dir).unwrap(); fs::write(dir.join("weights.bin"), weights).unwrap(); - let manifest = modelpack_sign::build_manifest_json(&meta, &sha, &signature); - fs::write(dir.join("manifest.json"), manifest.to_string()).unwrap(); + fs::write(dir.join("manifest.json"), json.to_string()).unwrap(); dir }