use std::path::Path; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::time::Instant; use color_eyre::eyre::{Result, WrapErr, eyre}; use transcribe_cpp::{Backend, Model, ModelOptions, RunOptions, TimestampKind}; use crate::gguf_session::OfflineGgufSession; use crate::transcription_models::{ ModelDefinition, TranscriptionModelId, TranscriptionSelection, definition, download_with_progress, model_path, validate, }; pub struct LocalTranscriber { session: OfflineGgufSession, options: RunOptions, device_label: String, max_audio_samples: Option, stream: Option, } pub fn default_model() -> &'static ModelDefinition { definition(TranscriptionModelId::default()) } pub fn install_default(canceled: &AtomicBool) -> Result<()> { install(&TranscriptionSelection::default(), canceled) } pub fn install(selection: &TranscriptionSelection, canceled: &AtomicBool) -> Result<()> { let model = validate(selection)?; let downloaded = AtomicU64::new(0); println!("Installing {} ({})...", model.name, model.size_label()); let path = download_with_progress(model, canceled, &downloaded)?; println!( "Installed {} bytes at {}", downloaded.load(Ordering::Relaxed), path.display() ); Ok(()) } pub fn devices() -> Result> { transcribe_cpp::init_logging(); transcribe_cpp::init_backends_default() .wrap_err("could not initialize transcription backends")?; Ok(transcribe_cpp::devices() .into_iter() .map(|device| { format!( "{}\t{}\t{} MB\t{}", device .index .map_or_else(|| "-".into(), |index| index.to_string()), device.kind, device.memory_total / (1024 * 1024), if device.description.is_empty() { device.name } else { device.description } ) }) .collect()) } pub fn transcribe_wav(path: &Path) -> Result { transcribe_wav_with_selection(path, &TranscriptionSelection::default()) } pub fn transcribe_wav_with_selection( path: &Path, selection: &TranscriptionSelection, ) -> Result { let samples = read_wav_for_parakeet(path)?; LocalTranscriber::load(selection)?.transcribe(&samples) } pub fn read_wav_for_parakeet(path: &Path) -> Result> { let mut reader = hound::WavReader::open(path) .wrap_err_with(|| format!("could not open {}", path.display()))?; let spec = reader.spec(); let samples = match spec.sample_format { hound::SampleFormat::Float => reader .samples::() .collect::, _>>()?, hound::SampleFormat::Int if spec.bits_per_sample <= 16 => reader .samples::() .map(|sample| sample.map(|sample| sample as f32 / i16::MAX as f32)) .collect::, _>>()?, hound::SampleFormat::Int => reader .samples::() .map(|sample| sample.map(|sample| sample as f32 / i32::MAX as f32)) .collect::, _>>()?, }; let channels = usize::from(spec.channels); let mono = samples .chunks(channels) .map(|frame| frame.iter().sum::() / channels as f32) .collect::>(); let mut samples = crate::dictation::resample_for_parakeet(&mono, spec.sample_rate); crate::dictation::pad_for_parakeet(&mut samples); Ok(samples) } impl LocalTranscriber { pub fn load_default() -> Result { Self::load(&TranscriptionSelection::default()) } pub fn load(selection: &TranscriptionSelection) -> Result { transcribe_cpp::init_logging(); transcribe_cpp::init_backends_default() .wrap_err("could not initialize transcription backends")?; let definition = validate(selection)?; if !crate::transcription_models::is_installed(definition, &selection.language) { return Err(eyre!( "{} is not installed; run `cargo run -- model install`", definition.name )); } let path = model_path(definition)?; let model = Model::load_with( &path, &ModelOptions { backend: Backend::Auto, device: None, }, ) .wrap_err_with(|| format!("could not load transcription model from {}", path.display()))?; let device = model.device()?; let variant = model.variant(); let architecture = model.arch(); let capabilities = model.capabilities(); let language = crate::gguf_session::validate_gguf_artifact( &path, definition, &architecture, &variant, selection, capabilities.supports_language_detect, )?; // Recognition hints softly prime Whisper's decoder as its initial // prompt; validate() already rejects hints on unsupported models. let recognition_hints = selection.recognition_hints.trim(); let family = (definition.supports_recognition_hints && !recognition_hints.is_empty()).then(|| { transcribe_cpp::RunExtension::Whisper(transcribe_cpp::WhisperRunOptions { initial_prompt: Some(recognition_hints.to_string()), ..Default::default() }) }); let device_label = format!("{} ({})", device.description, device.kind); tracing::info!( backend = device.kind, device = device.description, variant, "loaded local transcription model" ); let session = OfflineGgufSession::new(model)?; let mut transcriber = Self { session, options: RunOptions { timestamps: if capabilities.max_timestamp_kind == TimestampKind::None { TimestampKind::None } else { TimestampKind::Segment }, language, family, ..Default::default() }, device_label, max_audio_samples: crate::transcription_models::max_audio_chunk_samples( &architecture, capabilities.max_audio_ms, ), stream: None, }; let started = Instant::now(); transcriber.transcribe(&vec![0.0; 24_000])?; tracing::info!( prewarm_ms = started.elapsed().as_millis(), "prewarmed local transcription model" ); let stream_run = transcriber.stream_run_options(); transcriber.stream = transcriber.session.probe_stream(&stream_run, &architecture); Ok(transcriber) } /// Streams decode exactly as offline; a run-slot family extension /// (Whisper's prompt) does not apply to a stream. fn stream_run_options(&self) -> RunOptions { RunOptions { family: None, ..self.options.clone() } } pub(crate) fn stream_options(&self) -> Option<&transcribe_cpp::StreamOptions> { self.stream.as_ref() } pub(crate) fn with_stream( &mut self, stream_options: &transcribe_cpp::StreamOptions, cancel: &transcribe_cpp::CancelToken, drive: impl FnOnce(&mut transcribe_cpp::Stream<'_>) -> R, ) -> transcribe_cpp::Result { let options = self.stream_run_options(); self.session .with_stream(&options, stream_options, cancel, drive) } pub fn device_label(&self) -> &str { &self.device_label } pub fn transcribe(&mut self, samples: &[f32]) -> Result { let Some(max_samples) = self .max_audio_samples .filter(|&max_samples| samples.len() > max_samples) else { return self.run(samples); }; let mut output = Vec::new(); for samples in samples.chunks(max_samples) { let mut chunk = samples.to_vec(); crate::dictation::pad_for_parakeet(&mut chunk); let text = self.run(&chunk)?; let text = text.trim(); if !text.is_empty() { output.push(text.to_string()); } } Ok(output.join(" ")) } fn run(&mut self, samples: &[f32]) -> Result { self.session .run(samples, &self.options) .map(|transcript| transcript.text) .wrap_err("transcription failed") } }