From 92fd7abd40509fb509aea38d4805084b96b1d19f Mon Sep 17 00:00:00 2001 From: billlyzhaoyh Date: Thu, 26 Nov 2026 09:35:19 +0000 Subject: [PATCH 1/3] fix(app): keep the transcript when speakers can't be labelled on import or recovery With Detect speakers on, `transcribe` resolved models with diarization, so import and crash recovery failed before transcribing when the speaker- detection pack wasn't installed, showing the resolver's file list. A diarization error after transcription also threw the transcript away. `transcribe` now resolves the transcription models only and labels speakers as a separate step, shared with Stop (`label_speakers`). If labelling fails, the transcript comes back without speakers and with a note, in the same shape Stop returns (`NewTranscript`). A missing pack gets a plain note: "The speaker-detection pack isn't installed, so this transcript has no speakers. Add it on the Models page." Stop shows that note too now. The app opens imports and recoveries from the result's `speakersLabelled` and shows its note; a recovery puts it after the usual recovered note. Closes #35 --- app/src-tauri/src/commands.rs | 91 ++++++++++++++++++++++++++++++----- app/src-tauri/src/recorder.rs | 41 ++++++---------- app/src/App.test.tsx | 60 ++++++++++++++++++++++- app/src/App.tsx | 25 ++++++---- app/src/Record.tsx | 6 +-- 5 files changed, 170 insertions(+), 53 deletions(-) diff --git a/app/src-tauri/src/commands.rs b/app/src-tauri/src/commands.rs index 3d8e253..4aa84f6 100644 --- a/app/src-tauri/src/commands.rs +++ b/app/src-tauri/src/commands.rs @@ -1,11 +1,60 @@ //! Tauri IPC commands for transcription. In-process and CPU-only: audio never //! leaves the machine and no network call is made. -use engine::{decode_to_16k_mono_with_progress, process, EngineConfig, SherpaEngine}; +use engine::{ + decode_to_16k_mono_with_progress, merge, AsrSegment, EngineConfig, SherpaEngine, + TranscriptionEngine, +}; +use serde::Serialize; use tauri::{AppHandle, Emitter}; use crate::models; +/// A new transcript, as Import, recovery and Stop return it. +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct NewTranscript { + pub(crate) transcript: engine::Transcript, + /// Whether the transcript carries speaker labels. + pub(crate) speakers_labelled: bool, + /// Something the user should know about the result. + pub(crate) note: Option, +} + +const NO_SPEAKER_PACK: &str = "The speaker-detection pack isn't installed, so this transcript has no speakers. Add it on the Models page."; + +/// The note for a transcript whose speakers couldn't be labelled because of `e`. +pub(crate) fn unlabelled_note(e: impl std::fmt::Display) -> String { + format!("Speakers couldn't be labelled, so this transcript has none. ({e})") +} + +/// Diarize `samples` and attach speakers to the transcribed `segments`. On +/// failure, returns the note to show with the transcript instead. +/// +/// `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. +pub(crate) fn label_speakers( + cfg: &EngineConfig, + samples: &[f32], + sample_rate: u32, + segments: &[AsrSegment], + num_speakers: Option, +) -> Result { + let mut cfg = cfg.clone(); + cfg.diarize = true; + if !engine::required_model_files(cfg.asr_model, true) + .iter() + .all(|file| cfg.models_dir.join(file).is_file()) + { + return Err(NO_SPEAKER_PACK.to_string()); + } + let spans = SherpaEngine::new(&cfg) + .and_then(|eng| eng.diarize(samples, sample_rate, num_speakers)) + .map_err(unlabelled_note)?; + Ok(merge::merge(segments, &spans)) +} + /// Map a frontend model name to an [`engine::AsrModel`], falling back to the /// engine default (`parakeet`) for `None`/unrecognized values. pub(crate) fn parse_asr_model(name: Option<&str>) -> engine::AsrModel { @@ -79,7 +128,8 @@ pub(crate) fn resolve_models_dir( /// via the `transcribe-progress` event. /// /// `diarize` defaults to `false` (speaker-less transcript); `Some(true)` opts -/// in, and `num_speakers = None` then auto-detects. +/// in, and `num_speakers = None` then auto-detects. If labelling fails, the +/// transcript comes back without speakers and with a note saying why. /// /// `model`: `"parakeet"` (default) | `"small.en"` | `"medium.en"`; /// `None`/unrecognized falls back to the default. @@ -92,22 +142,23 @@ pub async fn transcribe( num_speakers: Option, diarize: Option, model: Option, -) -> Result { +) -> Result { // `models_dir` is left UNSET here on purpose: it is resolved INSIDE // spawn_blocking (verified-pack extraction may be large — keep the UI thread // free) and assigned just before `SherpaEngine::new`. let mut cfg = EngineConfig::new(""); - cfg.num_speakers = num_speakers; - cfg.diarize = diarize.unwrap_or(false); cfg.asr_model = parse_asr_model(model.as_deref()); + let diarize = diarize.unwrap_or(false); let resolve_app = app.clone(); let run_app = app.clone(); tauri::async_runtime::spawn_blocking(move || { // Resolve the models dir, enforcing verified-pack trust (debug-only raw - // override: see `debug_models_dir_override`). - cfg.models_dir = resolve_models_dir(&resolve_app, cfg.asr_model, cfg.diarize)?; + // override: see `debug_models_dir_override`). Transcription models + // only: speakers are labelled as a separate step below, so a missing + // or failing speaker pack can't cost the transcript. + cfg.models_dir = resolve_models_dir(&resolve_app, cfg.asr_model, false)?; // Timed from model load to the finished transcript: what the person // waits for, and what the Import estimate learns from. @@ -130,18 +181,34 @@ pub async fn transcribe( )); }) .map_err(|e| e.to_string())?; - let mut transcript = - process(&sherpa, &samples, sample_rate, &cfg, &progress).map_err(|e| e.to_string())?; - crate::vocab::apply(&run_app, &mut transcript); + let segments = + sherpa.transcribe(&samples, sample_rate, &progress).map_err(|e| e.to_string())?; + let mut result = NewTranscript { + transcript: merge::from_asr(&segments), + speakers_labelled: false, + note: None, + }; + if diarize { + progress(engine::Progress::new("diarizing", 0, 1, 0.95)); + match label_speakers(&cfg, &samples, sample_rate, &segments, num_speakers) { + Ok(transcript) => { + result.transcript = transcript; + result.speakers_labelled = true; + } + Err(note) => result.note = Some(note), + } + } + progress(engine::Progress::new("done", 1, 1, 1.0)); + crate::vocab::apply(&run_app, &mut result.transcript); crate::device::record_run( &run_app, crate::device::Run { audio_s: samples.len() as f64 / sample_rate as f64, elapsed_s: started.elapsed().as_secs_f64(), - diarize: cfg.diarize, + diarize, }, ); - Ok(transcript) + Ok(result) }) .await .map_err(|e| format!("transcription task failed: {e}"))? diff --git a/app/src-tauri/src/recorder.rs b/app/src-tauri/src/recorder.rs index 928e7a7..a083cf7 100644 --- a/app/src-tauri/src/recorder.rs +++ b/app/src-tauri/src/recorder.rs @@ -36,12 +36,12 @@ use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use engine::segment::PieceCutter; use engine::sherpa::{PIECE_S, PIECE_SEARCH_S}; use engine::{ - load_wav_16k_mono, merge, AsrSegment, EngineConfig, SherpaEngine, StreamResampler, - TranscriptionEngine, VadProfile, + load_wav_16k_mono, merge, AsrSegment, EngineConfig, SherpaEngine, StreamResampler, VadProfile, }; use serde::Serialize; use tauri::{AppHandle, Emitter, Manager}; +use crate::commands::{label_speakers, resolve_models_dir, unlabelled_note, NewTranscript}; use crate::system; const SAMPLE_RATE: u32 = 16_000; @@ -1214,7 +1214,7 @@ pub async fn start_recording( } let mut cfg = EngineConfig::new(""); cfg.asr_model = crate::commands::parse_asr_model(model.as_deref()); - cfg.models_dir = crate::commands::resolve_models_dir(&app, cfg.asr_model, false)?; + cfg.models_dir = resolve_models_dir(&app, cfg.asr_model, false)?; let engine = SherpaEngine::new(&cfg).map_err(|e| e.to_string())?; let recognizer = engine.recognizer().map_err(|e| e.to_string())?; @@ -1357,16 +1357,6 @@ fn finish(app: &AppHandle, discarding: bool) -> Result { Ok(Finished { path: active.path, cfg: active.cfg, segments, unread_s }) } -#[derive(Serialize)] -#[serde(rename_all = "camelCase")] -pub struct StoppedRecording { - transcript: engine::Transcript, - /// Whether the transcript carries speaker labels. - speakers_labelled: bool, - /// Something the user should know about the result. - note: Option, -} - /// Stop recording and build the transcript from the record's pieces, with /// speaker labels from diarizing the whole recording if `diarize` is set. If labelling /// fails, the transcript is returned without labels and with a note. @@ -1375,7 +1365,7 @@ pub async fn stop_recording( app: AppHandle, diarize: Option, num_speakers: Option, -) -> Result { +) -> Result { tauri::async_runtime::spawn_blocking(move || { let done = finish(&app, false)?; let mut notes = Vec::new(); @@ -1385,21 +1375,19 @@ pub async fn stop_recording( done.unread_s.ceil() as u64 )); } - let mut result = StoppedRecording { + let mut result = NewTranscript { transcript: merge::from_asr(&done.segments), speakers_labelled: false, note: None, }; if diarize.unwrap_or(false) { let _ = app.emit("transcribe-progress", engine::Progress::new("diarizing", 0, 1, 0.95)); - match label_speakers(&app, &done, num_speakers) { + match label_recording(&app, &done, num_speakers) { Ok(transcript) => { result.transcript = transcript; result.speakers_labelled = true; } - Err(e) => notes.push(format!( - "Speakers couldn't be labelled, so this transcript has none. ({e})" - )), + Err(note) => notes.push(note), } } result.note = (!notes.is_empty()).then(|| notes.join(" ")); @@ -1413,19 +1401,18 @@ pub async fn stop_recording( .map_err(|e| format!("recording task failed: {e}"))? } -/// Diarize the whole recording and attach speakers to the record's pieces. -fn label_speakers( +/// Diarize the whole recording and attach speakers to the record's pieces. On +/// failure, returns the note to show with the transcript instead. +fn label_recording( app: &AppHandle, done: &Finished, num_speakers: Option, ) -> Result { let mut cfg = done.cfg.clone(); - cfg.diarize = true; - cfg.models_dir = crate::commands::resolve_models_dir(app, cfg.asr_model, true)?; - let (samples, sr) = load_wav_16k_mono(&done.path).map_err(|e| e.to_string())?; - let eng = SherpaEngine::new(&cfg).map_err(|e| e.to_string())?; - let spans = eng.diarize(&samples, sr, num_speakers).map_err(|e| e.to_string())?; - Ok(merge::merge(&done.segments, &spans)) + // Resolved again, so a pack added while recording counts. + cfg.models_dir = resolve_models_dir(app, cfg.asr_model, false).map_err(unlabelled_note)?; + let (samples, sr) = load_wav_16k_mono(&done.path).map_err(unlabelled_note)?; + label_speakers(&cfg, &samples, sr, &done.segments, num_speakers) } /// Remove a finished recording's notes file once the transcript holding the diff --git a/app/src/App.test.tsx b/app/src/App.test.tsx index 555e1c7..c4df392 100644 --- a/app/src/App.test.tsx +++ b/app/src/App.test.tsx @@ -95,7 +95,7 @@ beforeEach(() => { deleteTranscriptReport = { deleted: ["/recordings/interview.wav"], failed: [] }; pickRecording = () => Promise.resolve("/recordings/interview.wav"); saveSession = () => Promise.resolve(); - transcribe = () => Promise.resolve(transcript); + transcribe = () => Promise.resolve({ transcript, speakersLabelled: false, note: null }); sessions = []; interrupted = []; recoverRecording = () => Promise.resolve({ notes: "Client agreed to mediation." }); @@ -551,6 +551,32 @@ describe("speaker count", () => { expect.objectContaining({ numSpeakers: 2 }), ); }); + + it("opens an import without speakers, and says why, when speakers can't be labelled", async () => { + transcribe = () => + Promise.resolve({ + transcript, + speakersLabelled: false, + note: "The speaker-detection pack isn't installed, so this transcript has no speakers. Add it on the Models page.", + }); + render(); + await screen.findByText("Import your first recording"); + fireEvent.click(screen.getAllByRole("button", { name: /Import recording/ })[0]!); + fireEvent.click(await screen.findByRole("button", { name: "Choose recording" })); + fireEvent.click(await screen.findByTestId("detect-speakers")); + fireEvent.click(await screen.findByRole("button", { name: "Create transcript" })); + + expect( + await screen.findByText( + "The speaker-detection pack isn't installed, so this transcript has no speakers. Add it on the Models page.", + ), + ).toBeInTheDocument(); + expect(invokeMock).toHaveBeenCalledWith("transcribe", expect.objectContaining({ diarize: true })); + expect(screen.getByTestId("paragraph")).toHaveTextContent("The local transcript is ready."); + await waitFor(() => expect(savedNotes()).toHaveLength(1)); + const saved = invokeMock.mock.calls.find(([command]) => command === "save_session")!; + expect((saved[1] as { session: { diarized: boolean } }).session.diarized).toBe(false); + }); }); describe("Record", () => { @@ -896,6 +922,38 @@ describe("Recordings without a transcript", () => { expect(screen.queryByTestId("interrupted-recording")).not.toBeInTheDocument(); }); + it("recovers one without speakers, and says why, when speakers can't be labelled", async () => { + transcribe = () => + Promise.resolve({ + transcript, + speakersLabelled: false, + note: "The speaker-detection pack isn't installed, so this transcript has no speakers. Add it on the Models page.", + }); + interrupted = [LEFT]; + render(); + await screen.findByText("Import your first recording"); + fireEvent.click(screen.getAllByRole("button", { name: /Import recording/ })[0]!); + fireEvent.click(await screen.findByRole("button", { name: "Choose recording" })); + fireEvent.click(await screen.findByTestId("detect-speakers")); + + fireEvent.click(screen.getByRole("button", { name: "Recover transcript" })); + + expect( + await screen.findByText( + "Recovered from a recording that had no transcript. The last moment of audio may be missing. The speaker-detection pack isn't installed, so this transcript has no speakers. Add it on the Models page.", + ), + ).toBeInTheDocument(); + expect(invokeMock).toHaveBeenCalledWith( + "transcribe", + expect.objectContaining({ path: LEFT.audioPath, diarize: true }), + ); + expect(screen.getByTestId("paragraph")).toHaveTextContent("The local transcript is ready."); + await waitFor(() => expect(savedNotes()).toEqual(["Client agreed to mediation."])); + const saved = invokeMock.mock.calls.find(([command]) => command === "save_session")!; + expect((saved[1] as { session: { diarized: boolean } }).session.diarized).toBe(false); + expect(screen.queryByTestId("interrupted-recording")).not.toBeInTheDocument(); + }); + it("starts only one recovery at a time", async () => { let prepared!: (value: unknown) => void; recoverRecording = () => new Promise((resolve) => (prepared = resolve)); diff --git a/app/src/App.tsx b/app/src/App.tsx index e5020d3..00d47cb 100644 --- a/app/src/App.tsx +++ b/app/src/App.tsx @@ -24,7 +24,7 @@ import Library from "./Library"; import Record from "./Record"; import { ImportEstimate, UNCHECKED } from "./Device"; import type { DeviceProfile } from "./Device"; -import type { FinishedRecording } from "./Record"; +import type { FinishedRecording, NewTranscript } from "./Record"; import SpeakerOptions, { requestedSpeakers } from "./SpeakerOptions"; import Sidebar from "./Sidebar"; import type { View } from "./Sidebar"; @@ -487,9 +487,8 @@ export default function App() { async function createTranscript() { if (!selectedPath || !asrModel) return; const path = selectedPath; - const withSpeakers = detectSpeakers; - await transcribeAndOpen(path, (transcript) => - openNewTranscript(transcript, path, withSpeakers), + await transcribeAndOpen(path, (r) => + openNewTranscript(r.transcript, path, r.speakersLabelled, "", r.note), ); } @@ -527,9 +526,15 @@ export default function App() { setRecoveryError({ audioPath: path, message: `Couldn't recover it: ${String(e)}` }); return; } - const withSpeakers = detectSpeakers; - const done = await transcribeAndOpen(path, (transcript) => - openNewTranscript(transcript, path, withSpeakers, notes, RECOVERED_NOTE, true), + const done = await transcribeAndOpen(path, (r) => + openNewTranscript( + r.transcript, + path, + r.speakersLabelled, + notes, + r.note ? `${RECOVERED_NOTE} ${r.note}` : RECOVERED_NOTE, + true, + ), ); if (done) setInterrupted((list) => list.filter((r) => r.audioPath !== path)); } finally { @@ -561,7 +566,7 @@ export default function App() { // Returns whether it got that far; errors go to the status line. async function transcribeAndOpen( path: string, - open: (transcript: Transcript) => Promise, + open: (result: NewTranscript) => Promise, ): Promise { setHistory(null); setCurrentSessionMeta(null); @@ -578,7 +583,7 @@ export default function App() { setProgress(progressView(event.payload, elapsedSec)); }); - const transcript = await invoke("transcribe", { + const result = await invoke("transcribe", { path, diarize: detectSpeakers, numSpeakers, @@ -586,7 +591,7 @@ export default function App() { }); // The backend timed this run; pick up the refined estimate. refreshDevice(); - await open(transcript); + await open(result); return true; } catch (e) { setStatus(`error: ${String(e)}`); diff --git a/app/src/Record.tsx b/app/src/Record.tsx index a6db05c..7b9e918 100644 --- a/app/src/Record.tsx +++ b/app/src/Record.tsx @@ -37,8 +37,8 @@ interface Status { transient: boolean; } -/** What `stop_recording` returns. */ -interface Stopped { +/** What `stop_recording` and `transcribe` return. */ +export interface NewTranscript { transcript: Transcript; speakersLabelled: boolean; /** Something the user should know about the result (e.g. labelling failed). */ @@ -243,7 +243,7 @@ export default function Record({ setProgress(progressView(e.payload, (Date.now() - startedAt) / 1000)), ), ); - const stopped = await invoke("stop_recording", { + const stopped = await invoke("stop_recording", { diarize: detectSpeakers, numSpeakers: requestedSpeakers(detectSpeakers, speakerCount), }); From 97f5c5f8e05ad7b292f0c01e57f43e2fd51224a9 Mon Sep 17 00:00:00 2001 From: billlyzhaoyh Date: Thu, 26 Nov 2026 10:03:44 +0000 Subject: [PATCH 2/3] fix(app): check for speaker models before Stop reads the recording From a Codex review of #37. Stop resolved the models, read the whole recording, and only then found the speaker models missing, holding about 230 MB per hour of audio just to return the note. On main, resolving with speakers on failed before the audio was read. `speaker_engine` now checks for the models and builds the engine; `label_speakers` runs it. Stop calls the first before reading the recording. The comment on `transcribe` no longer claims a failing speaker pack can't cost the transcript: resolving still unpacks every verified pack, so one that fails to unpack stops transcription (#38, already the case on main). --- app/src-tauri/src/commands.rs | 38 ++++++++++++++++++++++------------- app/src-tauri/src/recorder.rs | 8 ++++++-- 2 files changed, 30 insertions(+), 16 deletions(-) diff --git a/app/src-tauri/src/commands.rs b/app/src-tauri/src/commands.rs index 4aa84f6..8997d84 100644 --- a/app/src-tauri/src/commands.rs +++ b/app/src-tauri/src/commands.rs @@ -28,19 +28,13 @@ pub(crate) fn unlabelled_note(e: impl std::fmt::Display) -> String { format!("Speakers couldn't be labelled, so this transcript has none. ({e})") } -/// Diarize `samples` and attach speakers to the transcribed `segments`. On +/// The engine to label speakers with, checked before any audio is read. On /// failure, returns the note to show with the transcript instead. /// /// `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. -pub(crate) fn label_speakers( - cfg: &EngineConfig, - samples: &[f32], - sample_rate: u32, - segments: &[AsrSegment], - num_speakers: Option, -) -> Result { +pub(crate) fn speaker_engine(cfg: &EngineConfig) -> Result { let mut cfg = cfg.clone(); cfg.diarize = true; if !engine::required_model_files(cfg.asr_model, true) @@ -49,9 +43,20 @@ pub(crate) fn label_speakers( { return Err(NO_SPEAKER_PACK.to_string()); } - let spans = SherpaEngine::new(&cfg) - .and_then(|eng| eng.diarize(samples, sample_rate, num_speakers)) - .map_err(unlabelled_note)?; + SherpaEngine::new(&cfg).map_err(unlabelled_note) +} + +/// Diarize `samples` with `engine` (from [`speaker_engine`]) and attach +/// speakers to the transcribed `segments`. On failure, returns the note to +/// show with the transcript instead. +pub(crate) fn label_speakers( + engine: &SherpaEngine, + samples: &[f32], + sample_rate: u32, + segments: &[AsrSegment], + num_speakers: Option, +) -> Result { + let spans = engine.diarize(samples, sample_rate, num_speakers).map_err(unlabelled_note)?; Ok(merge::merge(segments, &spans)) } @@ -156,8 +161,10 @@ 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 a missing - // or failing speaker pack can't cost the transcript. + // 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.) cfg.models_dir = resolve_models_dir(&resolve_app, cfg.asr_model, false)?; // Timed from model load to the finished transcript: what the person @@ -190,7 +197,10 @@ pub async fn transcribe( }; if diarize { progress(engine::Progress::new("diarizing", 0, 1, 0.95)); - match label_speakers(&cfg, &samples, sample_rate, &segments, num_speakers) { + let labelled = speaker_engine(&cfg).and_then(|eng| { + label_speakers(&eng, &samples, sample_rate, &segments, num_speakers) + }); + match labelled { Ok(transcript) => { result.transcript = transcript; result.speakers_labelled = true; diff --git a/app/src-tauri/src/recorder.rs b/app/src-tauri/src/recorder.rs index a083cf7..80a566f 100644 --- a/app/src-tauri/src/recorder.rs +++ b/app/src-tauri/src/recorder.rs @@ -41,7 +41,9 @@ use engine::{ use serde::Serialize; use tauri::{AppHandle, Emitter, Manager}; -use crate::commands::{label_speakers, resolve_models_dir, unlabelled_note, NewTranscript}; +use crate::commands::{ + label_speakers, resolve_models_dir, speaker_engine, unlabelled_note, NewTranscript, +}; use crate::system; const SAMPLE_RATE: u32 = 16_000; @@ -1411,8 +1413,10 @@ fn label_recording( 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, false).map_err(unlabelled_note)?; + // Before reading the recording, which takes about 230 MB per hour. + let eng = speaker_engine(&cfg)?; let (samples, sr) = load_wav_16k_mono(&done.path).map_err(unlabelled_note)?; - label_speakers(&cfg, &samples, sr, &done.segments, num_speakers) + label_speakers(&eng, &samples, sr, &done.segments, num_speakers) } /// Remove a finished recording's notes file once the transcript holding the From 31636150fcfdb38ab170930b91fd710cb18fcca9 Mon Sep 17 00:00:00 2001 From: billlyzhaoyh Date: Thu, 26 Nov 2026 13:44:22 +0000 Subject: [PATCH 3/3] refactor(app): one place builds a new transcript and its speaker note From /simplify on #37; behaviour is unchanged. - `finish_transcript` builds the result for Import, recovery and Stop: labels speakers if asked, applies the vocabulary file, reports progress (at engine::PROGRESS_TRANSCRIBE_END, not a literal 0.95) and turns a labelling error into the note. The speaker-less transcript is built only when it's used. - `speaker_engine` no longer checks for the speaker models itself: `SherpaEngine::new` already does, and its ModelNotFound becomes the "pack isn't installed" note. The speaker step passes anyhow errors up (anyhow was already in the tree through `engine`). - `resolve_models_dir` and `resolve_verified_models_dir` lose their `diarize` flag, which every caller set to false. The resolver's doc says the app relies on its folder holding every verified pack (#38). - App: `FinishedRecording` extends `NewTranscript`, and `openNewTranscript` takes the result instead of six arguments. --- app/src-tauri/Cargo.lock | 1 + app/src-tauri/Cargo.toml | 2 + app/src-tauri/src/commands.rs | 90 +++++++++++++++++++---------------- app/src-tauri/src/models.rs | 10 +++- app/src-tauri/src/recorder.rs | 36 ++++---------- app/src/App.tsx | 26 +++------- app/src/Record.tsx | 13 +---- 7 files changed, 79 insertions(+), 99 deletions(-) diff --git a/app/src-tauri/Cargo.lock b/app/src-tauri/Cargo.lock index e6f9fc2..e9d3472 100644 --- a/app/src-tauri/Cargo.lock +++ b/app/src-tauri/Cargo.lock @@ -2136,6 +2136,7 @@ dependencies = [ name = "kindtech-transcribe-app" version = "0.3.0" dependencies = [ + "anyhow", "chrono", "cpal", "ed25519-dalek", diff --git a/app/src-tauri/Cargo.toml b/app/src-tauri/Cargo.toml index 60e802f..305a8af 100644 --- a/app/src-tauri/Cargo.toml +++ b/app/src-tauri/Cargo.toml @@ -36,6 +36,8 @@ tauri = { version = "2", features = ["protocol-asset"] } tauri-plugin-dialog = "2" tauri-plugin-fs = "2" +# Already in the tree through `engine`. Carries the speaker step's errors. +anyhow = "1.0" serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/app/src-tauri/src/commands.rs b/app/src-tauri/src/commands.rs index 8997d84..62ed713 100644 --- a/app/src-tauri/src/commands.rs +++ b/app/src-tauri/src/commands.rs @@ -23,40 +23,66 @@ pub struct NewTranscript { const NO_SPEAKER_PACK: &str = "The speaker-detection pack isn't installed, so this transcript has no speakers. Add it on the Models page."; +/// Finish a new transcript from the transcribed `segments`: label speakers +/// with `label` if one is given, apply the vocabulary file, and report `done`. +/// If labelling fails, the transcript has no speakers and the note says why, +/// after any `notes` already given. +pub(crate) fn finish_transcript( + app: &AppHandle, + segments: &[AsrSegment], + label: Option anyhow::Result>, + mut notes: Vec, +) -> NewTranscript { + let labelled = label.map(|label| { + let at = engine::PROGRESS_TRANSCRIBE_END; + let _ = app.emit("transcribe-progress", engine::Progress::new("diarizing", 0, 1, at)); + label() + }); + let (mut transcript, speakers_labelled) = match labelled { + Some(Ok(transcript)) => (transcript, true), + Some(Err(e)) => { + notes.push(unlabelled_note(&e)); + (merge::from_asr(segments), false) + } + None => (merge::from_asr(segments), false), + }; + crate::vocab::apply(app, &mut transcript); + let _ = app.emit("transcribe-progress", engine::Progress::new("done", 1, 1, 1.0)); + let note = (!notes.is_empty()).then(|| notes.join(" ")); + NewTranscript { transcript, speakers_labelled, note } +} + /// The note for a transcript whose speakers couldn't be labelled because of `e`. -pub(crate) fn unlabelled_note(e: impl std::fmt::Display) -> String { - format!("Speakers couldn't be labelled, so this transcript has none. ({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})"), + } } -/// The engine to label speakers with, checked before any audio is read. On -/// failure, returns the note to show with the transcript instead. +/// 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. -pub(crate) fn speaker_engine(cfg: &EngineConfig) -> Result { +/// 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; - if !engine::required_model_files(cfg.asr_model, true) - .iter() - .all(|file| cfg.models_dir.join(file).is_file()) - { - return Err(NO_SPEAKER_PACK.to_string()); - } - SherpaEngine::new(&cfg).map_err(unlabelled_note) + SherpaEngine::new(&cfg) } /// Diarize `samples` with `engine` (from [`speaker_engine`]) and attach -/// speakers to the transcribed `segments`. On failure, returns the note to -/// show with the transcript instead. +/// speakers to the transcribed `segments`. pub(crate) fn label_speakers( engine: &SherpaEngine, samples: &[f32], sample_rate: u32, segments: &[AsrSegment], num_speakers: Option, -) -> Result { - let spans = engine.diarize(samples, sample_rate, num_speakers).map_err(unlabelled_note)?; +) -> anyhow::Result { + let spans = engine.diarize(samples, sample_rate, num_speakers)?; Ok(merge::merge(segments, &spans)) } @@ -117,13 +143,12 @@ pub fn debug_asr_model_override() -> Option { pub(crate) fn resolve_models_dir( app: &AppHandle, asr_model: engine::AsrModel, - diarize: bool, ) -> Result { #[cfg(debug_assertions)] if let Some(raw) = debug_models_dir_override() { return Ok(raw); } - models::resolve_verified_models_dir(app, asr_model, diarize) + models::resolve_verified_models_dir(app, asr_model) } /// Transcribe an audio file (wav/mp3/m4a/mp4/flac/ogg…) into the project's JSON @@ -165,7 +190,7 @@ pub async fn transcribe( // 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.) - cfg.models_dir = resolve_models_dir(&resolve_app, cfg.asr_model, false)?; + cfg.models_dir = resolve_models_dir(&resolve_app, cfg.asr_model)?; // Timed from model load to the finished transcript: what the person // waits for, and what the Import estimate learns from. @@ -190,26 +215,11 @@ pub async fn transcribe( .map_err(|e| e.to_string())?; let segments = sherpa.transcribe(&samples, sample_rate, &progress).map_err(|e| e.to_string())?; - let mut result = NewTranscript { - transcript: merge::from_asr(&segments), - speakers_labelled: false, - note: None, - }; - if diarize { - progress(engine::Progress::new("diarizing", 0, 1, 0.95)); - let labelled = speaker_engine(&cfg).and_then(|eng| { - label_speakers(&eng, &samples, sample_rate, &segments, num_speakers) - }); - match labelled { - Ok(transcript) => { - result.transcript = transcript; - result.speakers_labelled = true; - } - Err(note) => result.note = Some(note), - } - } - progress(engine::Progress::new("done", 1, 1, 1.0)); - crate::vocab::apply(&run_app, &mut result.transcript); + let label = diarize.then_some(|| { + let eng = speaker_engine(&cfg)?; + label_speakers(&eng, &samples, sample_rate, &segments, num_speakers) + }); + let result = finish_transcript(&run_app, &segments, label, Vec::new()); crate::device::record_run( &run_app, crate::device::Run { diff --git a/app/src-tauri/src/models.rs b/app/src-tauri/src/models.rs index 9b544fa..60953f9 100644 --- a/app/src-tauri/src/models.rs +++ b/app/src-tauri/src/models.rs @@ -347,6 +347,11 @@ fn verified_packs( /// 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( packs_dir: &Path, cache_base: &Path, @@ -412,10 +417,11 @@ pub fn resolve_verified_models_dir_in( } /// 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, - diarize: bool, ) -> Result { let packs = packs_dir(app)?; let cache_base = app @@ -424,7 +430,7 @@ pub fn resolve_verified_models_dir( .map_err(|e| format!("cannot resolve app data dir: {e}"))?; let pubkey = PublicKey::SpkiPem(vendor_pubkey_pem()); let versions = engine_versions(); - resolve_verified_models_dir_in(&packs, &cache_base, &pubkey, &versions, asr_model, diarize) + resolve_verified_models_dir_in(&packs, &cache_base, &pubkey, &versions, asr_model, false) } /// Verified LLM-pack resolver. Enumerates `packs_dir`, VERIFIES every pack, and diff --git a/app/src-tauri/src/recorder.rs b/app/src-tauri/src/recorder.rs index 80a566f..01f5793 100644 --- a/app/src-tauri/src/recorder.rs +++ b/app/src-tauri/src/recorder.rs @@ -36,13 +36,13 @@ use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use engine::segment::PieceCutter; use engine::sherpa::{PIECE_S, PIECE_SEARCH_S}; use engine::{ - load_wav_16k_mono, merge, AsrSegment, EngineConfig, SherpaEngine, StreamResampler, VadProfile, + load_wav_16k_mono, AsrSegment, EngineConfig, SherpaEngine, StreamResampler, VadProfile, }; use serde::Serialize; use tauri::{AppHandle, Emitter, Manager}; use crate::commands::{ - label_speakers, resolve_models_dir, speaker_engine, unlabelled_note, NewTranscript, + finish_transcript, label_speakers, resolve_models_dir, speaker_engine, NewTranscript, }; use crate::system; @@ -1216,7 +1216,7 @@ pub async fn start_recording( } let mut cfg = EngineConfig::new(""); cfg.asr_model = crate::commands::parse_asr_model(model.as_deref()); - cfg.models_dir = resolve_models_dir(&app, cfg.asr_model, false)?; + cfg.models_dir = resolve_models_dir(&app, cfg.asr_model)?; let engine = SherpaEngine::new(&cfg).map_err(|e| e.to_string())?; let recognizer = engine.recognizer().map_err(|e| e.to_string())?; @@ -1377,24 +1377,9 @@ pub async fn stop_recording( done.unread_s.ceil() as u64 )); } - let mut result = NewTranscript { - transcript: merge::from_asr(&done.segments), - speakers_labelled: false, - note: None, - }; - if diarize.unwrap_or(false) { - let _ = app.emit("transcribe-progress", engine::Progress::new("diarizing", 0, 1, 0.95)); - match label_recording(&app, &done, num_speakers) { - Ok(transcript) => { - result.transcript = transcript; - result.speakers_labelled = true; - } - Err(note) => notes.push(note), - } - } - result.note = (!notes.is_empty()).then(|| notes.join(" ")); - crate::vocab::apply(&app, &mut result.transcript); - let _ = app.emit("transcribe-progress", engine::Progress::new("done", 1, 1, 1.0)); + let label = + diarize.unwrap_or(false).then_some(|| label_recording(&app, &done, num_speakers)); + let result = finish_transcript(&app, &done.segments, label, notes); // The notes file stays until the app has saved the transcript with // the notes (`forget_recording_notes`). Ok(result) @@ -1403,19 +1388,18 @@ pub async fn stop_recording( .map_err(|e| format!("recording task failed: {e}"))? } -/// Diarize the whole recording and attach speakers to the record's pieces. On -/// failure, returns the note to show with the transcript instead. +/// Diarize the whole recording and attach speakers to the record's pieces. fn label_recording( app: &AppHandle, done: &Finished, num_speakers: Option, -) -> Result { +) -> 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, false).map_err(unlabelled_note)?; + 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)?; - let (samples, sr) = load_wav_16k_mono(&done.path).map_err(unlabelled_note)?; + let (samples, sr) = load_wav_16k_mono(&done.path)?; label_speakers(&eng, &samples, sr, &done.segments, num_speakers) } diff --git a/app/src/App.tsx b/app/src/App.tsx index 00d47cb..88cd50a 100644 --- a/app/src/App.tsx +++ b/app/src/App.tsx @@ -3,7 +3,6 @@ import { invoke, convertFileSrc } from "@tauri-apps/api/core"; import { listen } from "@tauri-apps/api/event"; import { loadTranscript } from "@core/editor"; import type { EditorState } from "@core/editor"; -import type { Transcript } from "@core/types"; import { progressView } from "./progress"; import type { Progress, ProgressView } from "./progress"; import { @@ -438,18 +437,16 @@ export default function App() { // Open a just-created transcript in the editor and save it at once. async function openNewTranscript( - transcript: Transcript, + { transcript, speakersLabelled, note }: NewTranscript, path: string, - withSpeakers: boolean, newNotes = "", - note: string | null = null, fromRecording = false, ) { // Build the editor state once and reuse it for both the live history and // the saved copy, so the persisted session matches what is on screen. const editorState = loadTranscript(transcript); setHistory(initHistory(editorState)); - setDiarized(withSpeakers); + setDiarized(speakersLabelled); notesRef.current = newNotes; setNotes(newNotes); setReviewTab(newNotes ? "notes" : "transcript"); @@ -462,7 +459,7 @@ export default function App() { createdAt: new Date().toISOString(), audioPath: path, audioFilename: basename(path), - diarized: withSpeakers, + diarized: speakersLabelled, }; setCurrentSessionMeta(meta); setStatus("idle"); @@ -487,9 +484,7 @@ export default function App() { async function createTranscript() { if (!selectedPath || !asrModel) return; const path = selectedPath; - await transcribeAndOpen(path, (r) => - openNewTranscript(r.transcript, path, r.speakersLabelled, "", r.note), - ); + await transcribeAndOpen(path, (r) => openNewTranscript(r, path)); } // Transcribe a recording that has no transcript, with its notes, and open it. @@ -528,11 +523,9 @@ export default function App() { } const done = await transcribeAndOpen(path, (r) => openNewTranscript( - r.transcript, + { ...r, note: r.note ? `${RECOVERED_NOTE} ${r.note}` : RECOVERED_NOTE }, path, - r.speakersLabelled, notes, - r.note ? `${RECOVERED_NOTE} ${r.note}` : RECOVERED_NOTE, true, ), ); @@ -911,14 +904,7 @@ export default function App() { hintDismissed={recordHintDismissed} onDismissHint={() => setRecordHintDismissed(true)} onFinished={(r: FinishedRecording) => - void openNewTranscript( - r.transcript, - r.audioPath, - r.speakersLabelled, - r.notes, - r.note, - true, - ) + void openNewTranscript(r, r.audioPath, r.notes, true) } /> ) : view === "models" ? ( diff --git a/app/src/Record.tsx b/app/src/Record.tsx index 7b9e918..47925b5 100644 --- a/app/src/Record.tsx +++ b/app/src/Record.tsx @@ -46,12 +46,9 @@ export interface NewTranscript { } /** What a finished recording hands to the transcript view. */ -export interface FinishedRecording { - transcript: Transcript; +export interface FinishedRecording extends NewTranscript { audioPath: string; - speakersLabelled: boolean; notes: string; - note: string | null; } const SILENT_MESSAGE = @@ -247,13 +244,7 @@ export default function Record({ diarize: detectSpeakers, numSpeakers: requestedSpeakers(detectSpeakers, speakerCount), }); - const finished: FinishedRecording = { - transcript: stopped.transcript, - audioPath, - speakersLabelled: stopped.speakersLabelled, - notes: notesRef.current, - note: stopped.note, - }; + const finished: FinishedRecording = { ...stopped, audioPath, notes: notesRef.current }; reset(); onFinished(finished); } catch (e) {