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 3d8e253..62ed713 100644 --- a/app/src-tauri/src/commands.rs +++ b/app/src-tauri/src/commands.rs @@ -1,11 +1,91 @@ //! 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."; + +/// 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`. +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. 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) +} + +/// Diarize `samples` with `engine` (from [`speaker_engine`]) and attach +/// speakers to the transcribed `segments`. +pub(crate) fn label_speakers( + engine: &SherpaEngine, + samples: &[f32], + sample_rate: u32, + segments: &[AsrSegment], + num_speakers: Option, +) -> anyhow::Result { + let spans = engine.diarize(samples, sample_rate, num_speakers)?; + 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 { @@ -63,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 @@ -79,7 +158,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 +172,25 @@ 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 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)?; // Timed from model load to the finished transcript: what the person // waits for, and what the Import estimate learns from. @@ -130,18 +213,22 @@ 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 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 { 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/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 928e7a7..01f5793 100644 --- a/app/src-tauri/src/recorder.rs +++ b/app/src-tauri/src/recorder.rs @@ -36,12 +36,14 @@ 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, AsrSegment, EngineConfig, SherpaEngine, StreamResampler, VadProfile, }; use serde::Serialize; use tauri::{AppHandle, Emitter, Manager}; +use crate::commands::{ + finish_transcript, label_speakers, resolve_models_dir, speaker_engine, NewTranscript, +}; use crate::system; const SAMPLE_RATE: u32 = 16_000; @@ -1214,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 = crate::commands::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())?; @@ -1357,16 +1359,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 +1367,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,26 +1377,9 @@ pub async fn stop_recording( done.unread_s.ceil() as u64 )); } - let mut result = StoppedRecording { - 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) { - 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})" - )), - } - } - 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) @@ -1414,18 +1389,18 @@ pub async fn stop_recording( } /// Diarize the whole recording and attach speakers to the record's pieces. -fn label_speakers( +fn label_recording( app: &AppHandle, done: &Finished, num_speakers: Option, -) -> Result { +) -> anyhow::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).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)?; + label_speakers(&eng, &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..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 { @@ -24,7 +23,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"; @@ -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,10 +484,7 @@ 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, path)); } // Transcribe a recording that has no transcript, with its notes, and open it. @@ -527,9 +521,13 @@ 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, note: r.note ? `${RECOVERED_NOTE} ${r.note}` : RECOVERED_NOTE }, + path, + notes, + true, + ), ); if (done) setInterrupted((list) => list.filter((r) => r.audioPath !== path)); } finally { @@ -561,7 +559,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 +576,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 +584,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)}`); @@ -906,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 a6db05c..47925b5 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). */ @@ -46,12 +46,9 @@ interface Stopped { } /** 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 = @@ -243,17 +240,11 @@ 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), }); - 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) {