Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions app/src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down
115 changes: 101 additions & 14 deletions app/src-tauri/src/commands.rs
Original file line number Diff line number Diff line change
@@ -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<String>,
}

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<impl FnOnce() -> anyhow::Result<engine::Transcript>>,
mut notes: Vec<String>,
) -> 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::<engine::EngineError>() {
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<SherpaEngine> {
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<u32>,
) -> anyhow::Result<engine::Transcript> {
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 {
Expand Down Expand Up @@ -63,13 +143,12 @@ pub fn debug_asr_model_override() -> Option<String> {
pub(crate) fn resolve_models_dir(
app: &AppHandle,
asr_model: engine::AsrModel,
diarize: bool,
) -> Result<std::path::PathBuf, String> {
#[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
Expand All @@ -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.
Expand All @@ -92,22 +172,25 @@ pub async fn transcribe(
num_speakers: Option<u32>,
diarize: Option<bool>,
model: Option<String>,
) -> Result<engine::Transcript, String> {
) -> Result<NewTranscript, String> {
// `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.
Expand All @@ -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}"))?
Expand Down
10 changes: 8 additions & 2 deletions app/src-tauri/src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<PathBuf, String> {
let packs = packs_dir(app)?;
let cache_base = app
Expand All @@ -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
Expand Down
59 changes: 17 additions & 42 deletions app/src-tauri/src/recorder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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())?;

Expand Down Expand Up @@ -1357,16 +1359,6 @@ fn finish(app: &AppHandle, discarding: bool) -> Result<Finished, String> {
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<String>,
}

/// 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.
Expand All @@ -1375,7 +1367,7 @@ pub async fn stop_recording(
app: AppHandle,
diarize: Option<bool>,
num_speakers: Option<u32>,
) -> Result<StoppedRecording, String> {
) -> Result<NewTranscript, String> {
tauri::async_runtime::spawn_blocking(move || {
let done = finish(&app, false)?;
let mut notes = Vec::new();
Expand All @@ -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)
Expand All @@ -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<u32>,
) -> Result<engine::Transcript, String> {
) -> anyhow::Result<engine::Transcript> {
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
Expand Down
Loading
Loading