use std::collections::BTreeSet; use std::sync::Arc; use std::sync::Mutex; use std::sync::Once; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::mpsc::{self, Receiver, SyncSender, TrySendError}; use std::thread; use std::time::Instant; use color_eyre::eyre::{Result, WrapErr, eyre}; use transcribe_cpp::{Backend, Model, ModelOptions, RunOptions, TimestampKind, Transcript}; use crate::continuation::InputActivity; use crate::dictation::context::ContextSnapshot; use crate::dictation::paste_last::LastDictation; use crate::dictation::processor::ProcessingObservation; use crate::dictation::{DictationClip, correction_watch, pad_for_parakeet}; use crate::history::History; #[cfg(test)] use crate::history::HistoryKind; use crate::paste::{PasteMode, Paster}; use crate::transcription::WarmTranscriber; use crate::transcription::engine::{PendingTranscript, TranscriptionEngine}; use crate::transcription::gguf_session::{OfflineGgufSession, output_truncated}; use crate::transcription::models::{ TranscriptionModelId, TranscriptionSelection, model_path, validate, }; pub struct Parakeet { session: OfflineGgufSession, options: RunOptions, name: String, selection: Option, max_audio_samples: Option, _weights: procwatch::Lease, } /// Loaded model weights, estimated from the model file size (they live in Metal buffers). static MODEL_WEIGHTS: procwatch::Gauge = procwatch::Gauge::new("speech.model_weights"); static TRANSCRIBE_LOGGING: Once = Once::new(); const MAX_PENDING_OUTPUTS: usize = 16; pub enum WorkerEvent { ModelFailed(String), Completed { job_id: DictationJobId, target: TranscriptionTarget, result: Result, processing: Option, }, Stage { job_id: DictationJobId, stage: DictationJobStage, }, Pasted { kind: PasteKind, result: Result, }, } #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] pub struct DictationJobId(u64); impl DictationJobId { pub const fn value(self) -> u64 { self.0 } #[cfg(test)] pub(crate) const fn for_test(value: u64) -> Self { Self(value) } } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum DictationJobStage { Transcribing, Processing, } #[derive(Clone, Copy, Debug)] pub enum PasteKind { LastTranscript, } pub use crate::dictation::modes::output::OutputTarget as TranscriptionTarget; struct InferenceJob { ticket: OutputTicket, job_id: DictationJobId, control: Arc, submitted_at: Instant, transcript: PendingTranscript, audio_ms: u64, prepare_ms: u128, target: TranscriptionTarget, context: ContextSnapshot, /// Labs › Return to app: the app the capture started in, which the /// paste returns to (macOS). return_to: Option, /// The language the model was asked for at submission. language: String, /// The clip, kept for History while Labs › Keep recordings is on. recording: Option, /// See [`JobTimings::send_gate`]. send_gate: Option, /// Labs › Stop phrase: the words its capture ended with, read when the /// phrase was heard, removed from the transcript before processing. stop_phrase: Option, } struct ProcessorJob { ticket: OutputTicket, job_id: DictationJobId, control: Arc, target: TranscriptionTarget, text: String, context: ContextSnapshot, return_to: Option, language: String, timings: JobTimings, recording: Option, } /// Pipeline timings carried from inference through output for the final log. #[derive(Clone, Copy)] struct JobTimings { total_started: Instant, queue_ms: u128, audio_ms: u64, prepare_ms: u128, inference_ms: u128, /// Only a shortcut's processed paste can send. An Escape after /// submission lets the text paste but skips Return. send_gate: Option, } struct CompletedTranscript { text: String, /// Labs › Rewrite by voice asked for nothing: finish without output even if /// some later stage left text behind. nothing: bool, /// Corrected local transcript before mode processing. raw: String, application: Option, /// [`crate::dictation::context::ContextSnapshot::bundle_name`]. bundle_name: Option, /// Labs › Return to app: the app the capture started in, which the /// paste returns to (macOS). return_to: Option, timings: JobTimings, processing: Option, recording: Option, } enum OutputJob { PreparePaste, Skipped { sequence: u64, }, #[cfg(hex_capture)] Recent { ticket: OutputTicket, request: crate::paste::recent::Request, }, Completed { ticket: OutputTicket, job_id: DictationJobId, control: Arc, target: TranscriptionTarget, result: Box>, }, Paste { ticket: OutputTicket, kind: PasteKind, }, } impl OutputJob { fn sequence(&self) -> u64 { match self { Self::PreparePaste => u64::MAX, Self::Skipped { sequence } => *sequence, #[cfg(hex_capture)] Self::Recent { ticket, .. } => ticket.sequence(), Self::Completed { ticket, .. } => ticket.sequence(), Self::Paste { ticket, .. } => ticket.sequence(), } } fn disarm_ticket(self) { match self { Self::PreparePaste | Self::Skipped { .. } => {} #[cfg(hex_capture)] Self::Recent { ticket, .. } => ticket.disarm(), Self::Completed { ticket, .. } => ticket.disarm(), Self::Paste { ticket, .. } => ticket.disarm(), } } } #[derive(Default)] struct JobControl { /// A printing stop's reply; dropping the job unanswered tells it the /// dictation was cancelled or failed. print: Mutex>, } impl JobControl { fn answer_print(&self, transcript: crate::control::PrintedTranscript) { if let Some(reply) = self .print .lock() .unwrap_or_else(|error| error.into_inner()) .take() { reply.send(transcript); } } } mod ordered; use ordered::{OrderedOutputs, OutputTicket, TicketKind}; pub struct DictationWorker { engine: Option>, inference_jobs: Option>, output_jobs: Option>, events: Receiver, event_sender: mpsc::Sender, state: Arc>, inference_worker: Option>, processor_workers: Vec>, output_worker: Option>, } #[derive(Default)] struct WorkerState { next_sequence: u64, jobs: BTreeSet, pending_pastes: usize, /// Sequences whose [`OutputTicket`] dropped unsettled; drained by the /// output worker so [`OrderedOutputs`] never wedges even if the output /// channel was full when the drop occurred. skipped: BTreeSet, /// Labs › Return to app: the app in front when the capture started, /// which its output returns to (macOS). return_to: Option, /// Whether the dictation shortcut, rather than `hex dictation`, started /// the capture now recording (Labs › YOLO mode). started_by_shortcut: bool, } impl WorkerState { fn next_output_sequence(&self) -> Result { // Count accepted work even after it leaves a channel for ordered buffering. if self.jobs.len() + self.pending_pastes >= MAX_PENDING_OUTPUTS { return Err("dictation queue is full"); } Ok(self.next_sequence) } } impl DictationWorker { pub fn start( activity: InputActivity, transformations: Arc, history: Option, ) -> Self { const PROCESSOR_WORKERS: usize = 2; // Admission caps accepted jobs, so a submitted job always has a slot. let (inference_jobs, inference_receiver) = mpsc::sync_channel::(MAX_PENDING_OUTPUTS); let (processor_jobs, processor_receiver) = mpsc::sync_channel::(4); let (output_jobs, output_receiver) = mpsc::sync_channel::(8); let (event_sender, events) = mpsc::channel(); let state = Arc::new(Mutex::new(WorkerState::default())); let (_, selection) = crate::app_settings::transcription_selection(); // Labs › Free memory when idle parks a GGUF model at launch too: // the first dictation reloads it, so memory stays free until then. // Apple Speech holds no model of Hex's and stays loaded. let parked = crate::labs::unload_idle().is_some() && validate(&selection).is_ok_and(|definition| definition.runtime.is_gguf()); let engine = if parked { TranscriptionEngine::start_parked(selection) } else { TranscriptionEngine::start(WarmTranscriber::default()) }; let engine = match engine { Ok(engine) => { if !parked { let events = event_sender.clone(); let _ = engine.run(move |model| { prioritize_inference_thread(); match WarmTranscriber::load() { Ok(loaded) => { tracing::info!("transcription model loaded"); *model = loaded; } Err(error) => { let _ = events.send(WorkerEvent::ModelFailed(error.to_string())); } } }); } let engine = Arc::new(engine); engine.share(); Some(engine) } Err(error) => { let _ = event_sender.send(WorkerEvent::ModelFailed(error.to_string())); None } }; let output_worker = thread::spawn({ let state = state.clone(); let events = event_sender.clone(); move || run_output_worker(output_receiver, activity, history, &state, &events) }); let processor_receiver = Arc::new(Mutex::new(processor_receiver)); let processor_workers = (0..PROCESSOR_WORKERS) .map(|_| { let jobs = processor_receiver.clone(); let output = output_jobs.clone(); let events = event_sender.clone(); let transformations = transformations.clone(); thread::spawn(move || { run_processor_worker(&jobs, &output, &events, &transformations) }) }) .collect(); let inference_worker = thread::spawn({ let output = output_jobs.clone(); let events = event_sender.clone(); move || run_inference_worker(inference_receiver, &processor_jobs, &output, &events) }); Self { engine, inference_jobs: Some(inference_jobs), output_jobs: Some(output_jobs), events, event_sender, state, inference_worker: Some(inference_worker), processor_workers, output_worker: Some(output_worker), } } /// Labs › Return to app (macOS): remembers the app in front as this /// capture starts, so its paste can bring it back. Read only while the /// lab is on, and never Hex itself. pub fn remember_return_to_app(&self) { let return_to = crate::paste::return_to_app::capture_start(); let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner()); state.return_to = return_to; } /// Records who started the capture now recording: a dictation shortcut, /// or a `hex dictation` command. Only a shortcut's paste may send /// (Labs › YOLO mode). pub fn set_started_by_shortcut(&self, by_shortcut: bool) { let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner()); state.started_by_shortcut = by_shortcut; } #[cfg(hex_capture)] pub(crate) fn started_by_shortcut(&self) -> bool { self.state .lock() .unwrap_or_else(|e| e.into_inner()) .started_by_shortcut } /// Hands the clip to the engine at once, so its live stream finishes /// before any later capture begins one; the job then waits in order. pub fn transcribe( &self, clip: DictationClip, target: TranscriptionTarget, context: ContextSnapshot, stop_phrase: Option, ) -> Result { self.submit(clip, target, context, None, stop_phrase) } /// Like a paste, but the transcript (processed unless `raw`) goes to /// `print`. pub fn transcribe_printed( &self, clip: DictationClip, print: crate::control::PrintReply, raw: bool, context: ContextSnapshot, stop_phrase: Option, ) -> Result { let target = if raw { TranscriptionTarget::RawPrint } else { TranscriptionTarget::Print }; self.submit(clip, target, context, Some(print), stop_phrase) } fn submit( &self, mut clip: DictationClip, target: TranscriptionTarget, context: ContextSnapshot, print: Option, stop_phrase: Option, ) -> Result { let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner()); let job_id = DictationJobId(state.next_output_sequence()?); // Labs › Return to app: only a paste returns to an app; a printing // stop and the service never paste. let return_to = matches!( target, TranscriptionTarget::Paste | TranscriptionTarget::RawPaste ) .then(|| state.return_to.take()) .flatten(); let (Some(engine), Some(jobs), Some(output)) = (&self.engine, &self.inference_jobs, &self.output_jobs) else { return Err("dictation worker is unavailable"); }; let control = Arc::new(JobControl { print: Mutex::new(print), }); let (_, selection) = crate::app_settings::transcription_selection(); let language = selection.language.clone(); let submitted_at = Instant::now(); let audio_ms = clip.duration_ms(); let send_gate = (matches!(target, TranscriptionTarget::Paste) && state.started_by_shortcut) .then(crate::dictation::yolo_mode::SendGate::open); // Labs › Words on screen: this capture's terms belong to its // whole-clip run and no other job. Only a model that reads the terms // gives up its live stream, whose vocabulary is fixed when it starts // (before the window was read); a model that ignores them keeps it. let screen_terms = context.screen_terms.clone(); let keeps_stream = screen_terms.is_empty() || !crate::dictation::vocabulary::uses_terms(); let stream = clip.take_stream().filter(|_| keeps_stream); let _capture = clip.take_capture_marker(); let samples = clip.into_transcription_samples(); crate::dictation::diagnostics::persist(&samples); let recording = match target { TranscriptionTarget::Service => None, _ => crate::history::Recording::keep(&samples), }; let prepare_ms = submitted_at.elapsed().as_millis(); let offline = Box::new(move |model: &mut WarmTranscriber, samples: Vec| { let _busy = DictationInference::begin(); let transcriber = model .activate(&selection) .map_err(|error| error.to_string())?; crate::dictation::vocabulary::for_capture(&screen_terms, || { transcriber.transcribe(samples) }) .map_err(|error| error.to_string()) }); let transcript = engine .finish_with(stream, samples, offline) .map_err(|_| "dictation worker is unavailable")?; let ticket = OutputTicket::new( job_id.0, TicketKind::Dictation { job_id, target }, self.state.clone(), output.clone(), self.event_sender.clone(), ); match jobs.try_send(InferenceJob { ticket, job_id, control, submitted_at, transcript, audio_ms, prepare_ms, target, context, return_to, language, recording, send_gate, stop_phrase, }) { Ok(()) => { state.next_sequence += 1; state.jobs.insert(job_id); Ok(job_id) } Err(error) => { let message = match error { TrySendError::Full(job) => { job.ticket.disarm(); "dictation queue is full" } TrySendError::Disconnected(job) => { job.ticket.disarm(); "dictation worker is unavailable" } }; Err(message) } } } /// The engine that streams hotkey captures while they are recorded. pub fn engine(&self) -> Option> { self.engine.clone() } pub fn prepare_paste(&self) { let state = self.state.lock().unwrap_or_else(|error| error.into_inner()); if !state.jobs.is_empty() || state.pending_pastes > 0 { return; } drop(state); let Some(output_jobs) = &self.output_jobs else { return; }; let _ = output_jobs.try_send(OutputJob::PreparePaste); } /// Switches the warm model after the work already handed to the engine. pub fn reload(&self, selection: TranscriptionSelection) -> Result<(), &'static str> { let events = self.event_sender.clone(); self.engine .as_ref() .ok_or("dictation worker is unavailable")? .run(move |model| { let _busy = DictationInference::begin(); if let Err(error) = model.activate(&selection) { let _ = events.send(WorkerEvent::ModelFailed(error.to_string())); } }) .map_err(|_| "dictation worker is unavailable") } pub fn paste_last(&self) -> Result<(), &'static str> { #[cfg(hex_capture)] if crate::paste::recent::enabled() { return self.paste_recent(crate::paste::recent::Request { id: None, target: crate::paste::recent::Target::capture() .ok_or("could not confirm the paste target")?, }); } self.submit_paste(PasteKind::LastTranscript) } fn submit_paste(&self, kind: PasteKind) -> Result<(), &'static str> { self.enqueue_paste(kind, |ticket| OutputJob::Paste { ticket, kind }) } #[cfg(hex_capture)] pub(crate) fn paste_recent( &self, request: crate::paste::recent::Request, ) -> Result<(), &'static str> { self.enqueue_paste(PasteKind::LastTranscript, |ticket| OutputJob::Recent { ticket, request, }) } fn enqueue_paste( &self, kind: PasteKind, job: impl FnOnce(OutputTicket) -> OutputJob, ) -> Result<(), &'static str> { let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner()); let sequence = state.next_output_sequence()?; let output = self .output_jobs .as_ref() .ok_or("dictation worker is unavailable")?; let ticket = OutputTicket::new( sequence, TicketKind::Paste(kind), self.state.clone(), output.clone(), self.event_sender.clone(), ); match output.try_send(job(ticket)) { Ok(()) => { state.next_sequence += 1; state.pending_pastes += 1; Ok(()) } Err(error) => { let message = match error { TrySendError::Full(job) => { job.disarm_ticket(); "dictation queue is full" } TrySendError::Disconnected(job) => { job.disarm_ticket(); "dictation worker is unavailable" } }; Err(message) } } } pub fn try_recv(&self) -> Option { self.events.try_recv().ok() } pub fn is_busy(&self) -> bool { let state = self.state.lock().unwrap_or_else(|error| error.into_inner()); !state.jobs.is_empty() || state.pending_pastes > 0 } pub fn pending_count(&self) -> usize { self.state .lock() .unwrap_or_else(|error| error.into_inner()) .jobs .len() } fn shutdown(&mut self) { // Accepted jobs still finish: the inference worker drains its queue. self.inference_jobs.take(); join_worker(self.inference_worker.take(), "dictation inference"); for worker in self.processor_workers.drain(..) { join_worker(Some(worker), "dictation processing"); } self.output_jobs.take(); join_worker(self.output_worker.take(), "dictation output"); } } impl Drop for DictationWorker { fn drop(&mut self) { self.shutdown(); } } fn run_output_worker( jobs: Receiver, activity: InputActivity, history: Option, state: &Mutex, events: &mpsc::Sender, ) { let mut paster = Paster::new(activity); let mut last_transcript = None; let mut ordered = OrderedOutputs::default(); while let Ok(job) = jobs.recv() { if matches!(job, OutputJob::PreparePaste) { paster.prepare(); continue; } let skipped = { let mut state = state.lock().unwrap_or_else(|error| error.into_inner()); std::mem::take(&mut state.skipped) }; let mut ready = Vec::new(); for sequence in skipped { ready.extend(ordered.skip(sequence)); } ready.extend(ordered.push(job)); for job in ready { let event = match job { OutputJob::PreparePaste | OutputJob::Skipped { .. } => continue, #[cfg(hex_capture)] OutputJob::Recent { ticket, request } => { let result = request .insert(&mut paster, history.as_ref()) .map_err(|e| e.to_string()); ticket.settle(); WorkerEvent::Pasted { kind: PasteKind::LastTranscript, result, } } job => finish_output( job, &mut |text, mode| paster.paste(text, mode), &mut last_transcript, history.as_ref(), ), }; if events.send(event).is_err() { return; } } } } fn run_processor_worker( jobs: &Mutex>, output: &SyncSender, events: &mpsc::Sender, transformations: &crate::personal_commands::TransformationClient, ) { loop { let job = jobs .lock() .unwrap_or_else(|error| error.into_inner()) .recv(); let Ok(job) = job else { break }; let mut processed = process_job_text(&job, crate::dictation::config::dictation_profiles, || { let _ = events.send(WorkerEvent::Stage { job_id: job.job_id, stage: DictationJobStage::Processing, }); }); processed.apply_transformations( transformations, &job.context, &AtomicBool::new(false), crate::dictation::processor::Source::Dictation, ); if let Some(observation) = &processed.observation && let Some(error) = &observation.fallback { tracing::warn!( profile = observation.profile, %error, "dictation processing fell back to the previous pipeline output" ); } if output .send(OutputJob::Completed { ticket: job.ticket, job_id: job.job_id, control: job.control, target: job.target, result: Box::new(Ok(CompletedTranscript { text: processed.text, nothing: processed.nothing, raw: job.text, application: job.context.application, bundle_name: job.context.bundle_name, return_to: job.return_to, timings: job.timings, processing: processed.observation, recording: job.recording, })), }) .is_err() { break; } } } /// Select processing when the worker reaches the job; the stage precedes processing. fn process_job_text( job: &ProcessorJob, profiles: impl FnOnce() -> crate::dictation::processor::Profiles, processing: impl FnOnce(), ) -> crate::dictation::processor::Processed { let profiles = profiles(); // A voice prompt can run a request even when the mode's own rewrite and // transformations are off, so the HUD shows its stage too. if profiles.processes(&job.context) || profiles.voice_prompts( &job.text, &job.language, &job.context, crate::dictation::processor::Source::Dictation, ) { processing(); } profiles.process_cancellable( &job.text, &job.language, &job.context, &AtomicBool::new(false), crate::dictation::processor::Source::Dictation, ) } #[cfg(hex_capture)] mod words; #[cfg(hex_capture)] pub use words::transcribe_with_words; #[cfg(all(test, hex_capture))] use words::{WORD_CHUNK_SAMPLES, transcribe_in_chunks}; /// Waits for each accepted job's transcript in submission order, then hands /// it to processing. The engine thread runs the inference itself. fn run_inference_worker( jobs: Receiver, processor_jobs: &SyncSender, output: &SyncSender, events: &mpsc::Sender, ) { while let Ok(job) = jobs.recv() { let _busy = DictationInference::begin(); let _ = events.send(WorkerEvent::Stage { job_id: job.job_id, stage: DictationJobStage::Transcribing, }); let total_started = job.submitted_at; let queue_ms = total_started.elapsed().as_millis(); let inference_started = Instant::now(); let audio_ms = job.audio_ms; let result = job.transcript.wait().map(|transcribed| { tracing::info!( source = transcribed.source.label(), finish_ms = transcribed.finish_ms, audio_ms, "transcribed dictation" ); let raw = transcribed.text; // Labs › Stop phrase: the words that finished this capture never // reach the text, and a capture that was only the phrase reads as // empty. let corrected = match crate::dictation::modes::output::prepare_transcript( raw.clone(), job.stop_phrase.as_deref(), job.target, ) { crate::dictation::modes::output::PreparedTranscript::Ready(text) => text, crate::dictation::modes::output::PreparedTranscript::StopPhraseOnly | crate::dictation::modes::output::PreparedTranscript::Empty => String::new(), }; tracing::debug!( raw_transcript = raw, corrected_transcript = corrected, "prepared local transcript" ); corrected }); let timings = JobTimings { total_started, queue_ms, audio_ms, prepare_ms: job.prepare_ms, inference_ms: inference_started.elapsed().as_millis(), send_gate: job.send_gate, }; let target = job.target; match result { Ok(text) if target.processes() && !text.trim().is_empty() => { if processor_jobs .send(ProcessorJob { ticket: job.ticket, job_id: job.job_id, control: job.control, target, text, context: job.context, return_to: job.return_to, language: job.language, timings, recording: job.recording, }) .is_err() { break; } } result => { let application = job.context.application; let bundle_name = job.context.bundle_name; let recording = job.recording; let result = result.map(|text| CompletedTranscript { raw: text.clone(), text, nothing: false, application, bundle_name, return_to: job.return_to, timings, processing: None, recording, }); if output .send(OutputJob::Completed { ticket: job.ticket, job_id: job.job_id, control: job.control, target, result: Box::new(result), }) .is_err() { break; } } } } } fn join_worker(worker: Option>, name: &str) { if let Some(worker) = worker && worker.join().is_err() { tracing::error!(worker = name, "worker panicked during shutdown"); } } #[cfg(target_os = "macos")] pub(crate) fn prioritize_inference_thread() { // ggml worker pthreads start at default QoS instead of inheriting this // class; GGUF sessions use one decoder thread so decoding stays here. const QOS_CLASS_USER_INTERACTIVE: u32 = 0x21; unsafe extern "C" { fn pthread_set_qos_class_self_np(qos_class: u32, relative_priority: i32) -> i32; } // SAFETY: This configures only the calling worker thread using the public // macOS pthread QoS API. Relative priority zero is valid for this class. let status = unsafe { pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0) }; if status == 0 { tracing::info!("dictation inference worker uses user-interactive QoS"); } else { tracing::warn!(status, "could not raise dictation inference worker QoS"); } } #[cfg(not(target_os = "macos"))] pub(crate) fn prioritize_inference_thread() {} static DICTATION_INFERENCE: AtomicUsize = AtomicUsize::new(0); struct DictationInference; impl DictationInference { fn begin() -> Self { DICTATION_INFERENCE.fetch_add(1, Ordering::AcqRel); Self } } impl Drop for DictationInference { fn drop(&mut self) { DICTATION_INFERENCE.fetch_sub(1, Ordering::AcqRel); } } /// Whether dictation is capturing or running inference. Meeting /// transcription starts no chunk while this holds. A capture counts from its /// press: a chunk already running then finishes during the hold threshold /// and release tail, before the clip needs the model. pub(crate) fn dictation_busy() -> bool { DICTATION_INFERENCE.load(Ordering::Acquire) > 0 || crate::audio::recording_environment::capture_active() || crate::audio::recording_environment::intentional_recording_active() } /// Runs `work` at utility QoS on the dictation inference thread, then /// restores its user-interactive class. pub(crate) fn at_background_priority(work: impl FnOnce() -> R) -> R { const QOS_CLASS_USER_INTERACTIVE: u32 = 0x21; const QOS_CLASS_UTILITY: u32 = 0x11; unsafe extern "C" { fn pthread_set_qos_class_self_np(qos_class: u32, relative_priority: i32) -> i32; } // SAFETY: These configure only the calling thread using the public macOS // pthread QoS API. Relative priority zero is valid for both classes. unsafe { pthread_set_qos_class_self_np(QOS_CLASS_UTILITY, 0) }; let result = work(); unsafe { pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0) }; result } /// Runs the calling thread at utility QoS for background transcription. pub(crate) fn deprioritize_background_thread() { const QOS_CLASS_UTILITY: u32 = 0x11; unsafe extern "C" { fn pthread_set_qos_class_self_np(qos_class: u32, relative_priority: i32) -> i32; } // SAFETY: This configures only the calling thread using the public macOS // pthread QoS API. Relative priority zero is valid for this class. let status = unsafe { pthread_set_qos_class_self_np(QOS_CLASS_UTILITY, 0) }; if status != 0 { tracing::warn!(status, "could not lower background transcription QoS"); } } fn finish_output( job: OutputJob, paste: &mut impl FnMut(&str, PasteMode) -> Result, last_transcript: &mut Option, history: Option<&History>, ) -> WorkerEvent { match job { OutputJob::PreparePaste => unreachable!("paste preparation bypasses ordered output"), OutputJob::Skipped { .. } => unreachable!("skipped sequences never reach finish_output"), #[cfg(hex_capture)] OutputJob::Recent { .. } => unreachable!("a recent paste uses its own insertion adapter"), OutputJob::Completed { ticket, job_id, control, target, result, } => { let result = *result; let processing = result .as_ref() .ok() .and_then(|result| result.processing.clone()); let result = result.and_then(|completed| { output_history::deliver_completed( target, completed, paste, last_transcript, history, ) }); if target.is_print() { control.answer_print(match &result { Ok(text) if text.trim().is_empty() => { crate::control::PrintedTranscript::NoSpeech } Ok(text) => crate::control::PrintedTranscript::Text(text.clone()), Err(error) => crate::control::PrintedTranscript::Failed(error.clone()), }); } ticket.settle(); WorkerEvent::Completed { job_id, target, result, processing, } } OutputJob::Paste { ticket, kind } => { let result = match kind { PasteKind::LastTranscript => output_history::paste_last( last_transcript.as_ref(), history.and_then(History::recovered_output), paste, ), }; ticket.settle(); WorkerEvent::Pasted { kind, result } } } } mod output_history; #[cfg(test)] use output_history::{record_history, send_unless_escaped}; pub(crate) fn default_model_path() -> Result { model_path(&crate::transcription::models::definition( crate::transcription::models::TranscriptionModelId::default(), )) } impl Parakeet { #[cfg(test)] pub fn load() -> Result { let (_, selection) = crate::app_settings::transcription_selection(); Self::load_selection(&selection) } pub fn load_selection(selection: &TranscriptionSelection) -> Result { let definition = validate(selection)?; if !crate::transcription::models::is_installed(&definition, &selection.language) { return Err(eyre!("{} is not installed", definition.name)); } let path = model_path(&definition)?; let mut parakeet = Self::load_from(&path, true, Some(selection))?; parakeet.prewarm()?; let stream_run = parakeet.stream_run_options(); parakeet.session.probe_stream(&stream_run, &path); Ok(parakeet) } /// Streams decode like offline runs, at segment timestamps: only the text /// of a stream is used. fn stream_run_options(&self) -> RunOptions { RunOptions { timestamps: match self.options.timestamps { TimestampKind::Word | TimestampKind::Token => TimestampKind::Segment, timestamps => timestamps, }, ..self.options.clone() } } pub(crate) fn stream_options(&self) -> Option<&transcribe_cpp::StreamOptions> { self.session.stream_options() } /// Whether this model streams with Parakeet's buffered chunk menus, whose /// first-word timestamp lags its audio. pub(crate) fn streams_buffered_parakeet(&mut self) -> bool { self.session.streams_buffered_parakeet() } /// Re-probes the live stream when Labs › Faster live text or an env /// override changed, so a later capture streams with it. Streams decode /// with [`Self::stream_run_options`], as the load-time probe does. pub(crate) fn refresh_stream(&mut self) { let options = self.stream_run_options(); self.session.refresh_stream(&options); } 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(crate) fn load_for_benchmark(model_path: &std::path::Path) -> Result { Self::load_from(model_path, false, None) } fn load_from( model_path: &std::path::Path, diagnostics: bool, selection: Option<&TranscriptionSelection>, ) -> Result { if diagnostics { TRANSCRIBE_LOGGING.call_once(transcribe_cpp::init_logging); } else { transcribe_cpp::disable_logging(); } let model = Model::load_with( model_path, &ModelOptions { backend: Backend::Metal, ..Default::default() }, ) .wrap_err_with(|| { format!( "could not load transcription model from {}", model_path.display() ) })?; let device = model.device()?; if device.kind != "metal" { return Err(eyre!( "transcription model selected {} ({}) instead of Metal", device.kind, device.name )); } let variant = model.variant(); let architecture = model.arch(); let name = format!("transcribe-cpp-{}-{variant}", device.kind); let definition = selection.map(validate).transpose()?; tracing::info!( backend = device.kind, device = device.description, variant, "loaded transcription model" ); let capabilities = model.capabilities()?; let mut options = RunOptions { timestamps: match capabilities.max_timestamp_kind { TimestampKind::Word | TimestampKind::Token => TimestampKind::Word, TimestampKind::Auto | TimestampKind::Segment => TimestampKind::Segment, TimestampKind::None => TimestampKind::None, }, ..Default::default() }; if let (Some(selection), Some(definition)) = (selection, definition) { let runtime_language = crate::transcription::gguf_session::validate_gguf_artifact( model_path, &definition, &architecture, &variant, selection, capabilities.supports_language_detect, )?; if let Some(runtime_language) = &runtime_language && !capabilities.languages.is_empty() && !capabilities .languages .iter() .any(|language| language == runtime_language) { return Err(eyre!( "{} does not advertise support for {}", definition.name, crate::transcription::models::language_name(&selection.language) )); } options.language = runtime_language; } let session = OfflineGgufSession::new(model)?; let weights_bytes = std::fs::metadata(model_path).map_or(0, |meta| meta.len() as usize); Ok(Self { session, options, name, selection: selection.cloned(), max_audio_samples: crate::transcription::models::max_audio_chunk_samples( &architecture, capabilities.max_audio_ms, ), _weights: MODEL_WEIGHTS.track(weights_bytes), }) } /// Runs a short silent inference. ggml keeps the Metal weights resident /// for only three minutes after a run; then macOS may compress or swap /// them out, and the next run pays to bring them back. A prewarm pays that /// before the audio arrives, and is skipped right after another run. pub(crate) fn prewarm(&mut self) -> Result<()> { if self.session.ran_recently() { return Ok(()); } let started = Instant::now(); let mut silence = Vec::new(); pad_for_parakeet(&mut silence); // No vocabulary: with it, a decoder such as Qwen3-ASR 1.7B reads a // long term list back to its output cap on every warm-up (#1568). let result = self .session .warm(&silence, &self.options) .map(drop) .wrap_err("could not prewarm transcription model"); match result { // Backstop: a decode that still runs to its generation cap on // silence (Qwen3-ASR 1.7B, #968) ran the whole graph on the // device, so that is a warm model, not a failed selection; Linux // and Windows accept it the same way. Err(error) if output_truncated(&error) => { tracing::info!( error = format!("{error:#}"), "the warm-up run on silence hit the output limit; the model is warm" ); } result => result?, } tracing::info!( prewarm_ms = started.elapsed().as_millis(), "prewarmed transcription model" ); Ok(()) } pub(crate) fn name(&self) -> &str { &self.name } pub(crate) fn matches_selection(&self, selection: &TranscriptionSelection) -> bool { self.selection.as_ref() == Some(selection) } pub(crate) fn selection(&self) -> Option<&TranscriptionSelection> { self.selection.as_ref() } pub(crate) fn model_id(&self) -> Option { self.selection.as_ref().map(|selection| selection.model) } /// Low-level GGUF entry point over prepared audio. `Transcriber` owns the /// whole-clip padding; chunks only apply the minimum duration, never /// another model-specific trailing context. pub fn transcribe(&mut self, samples: &[f32]) -> Result { self.session .transcribe_chunked(samples, &self.options, self.max_audio_samples) } /// [`Self::transcribe`] with the model's own segment and word times, /// chunked and offset exactly as the untimed run chunks it. pub(crate) fn transcribe_timed( &mut self, samples: &[f32], ) -> Result { self.session .transcribe_chunked_timed(samples, &self.options, self.max_audio_samples) } /// The finest native timings this model gives, as a timed request needs /// them. Never the level a caller asked for. pub(crate) fn timestamps(&self) -> crate::transcription::transcript::TimestampLevel { crate::transcription::gguf_session::timestamp_level(self.options.timestamps) } pub fn transcribe_segments(&mut self, samples: &[f32]) -> Result { self.session .run(samples, &self.options) .wrap_err("transcription failed") } } #[cfg(test)] mod tests { use std::path::PathBuf; use hound::WavReader; use super::*; use crate::dictation::resample_for_parakeet; fn processing_job(target: TranscriptionTarget) -> ProcessorJob { ProcessorJob { ticket: OutputTicket::for_test(0), job_id: DictationJobId(0), control: Arc::new(JobControl::default()), target, text: "raw instruction".into(), context: ContextSnapshot::default(), return_to: None, language: "en".into(), timings: JobTimings { total_started: Instant::now(), queue_ms: 0, audio_ms: 1000, prepare_ms: 0, inference_ms: 0, send_gate: None, }, recording: None, } } #[test] fn ordinary_processing_snapshots_modes_before_stage_and_keeps_transformations() { use crate::dictation::processor::{Profile, Profiles}; use std::cell::Cell; for transformations in [vec![], vec!["fixture-transform".to_string()]] { let loaded = Cell::new(false); let stage_sent = Cell::new(false); let processed = process_job_text( &processing_job(TranscriptionTarget::Paste), || { assert!(!stage_sent.get()); loaded.set(true); Profiles::new( Profile::new("Global", "").transformations(transformations.clone()), ) }, || { assert!(loaded.get()); stage_sent.set(true); }, ); assert!(loaded.get()); assert_eq!(stage_sent.get(), !transformations.is_empty()); assert_eq!(processed.text, "raw instruction"); assert_eq!(processed.transformations, transformations); } } #[test] #[ignore = "requires HEX_COHERE_MODEL and HEX_COHERE_FIXTURES synthetic audio"] fn cohere_long_form_keeps_all_sections_with_and_without_pauses() { let model_path = PathBuf::from(std::env::var_os("HEX_COHERE_MODEL").expect("model path")); let fixtures = PathBuf::from(std::env::var_os("HEX_COHERE_FIXTURES").expect("fixture path")); let selection = TranscriptionSelection { model: TranscriptionModelId::CohereTranscribe, language: "en".into(), }; let mut model = Parakeet::load_from(&model_path, false, Some(&selection)).unwrap(); eprintln!( "Cohere maximum chunk: {:?} samples", model.max_audio_samples ); for (name, repeats) in [ ("long-continuous", 1), ("long-pauses", 1), ("long-repeated", 3), ] { let mut reader = WavReader::open(fixtures.join(format!("{name}.wav"))).unwrap(); assert_eq!(reader.spec().sample_rate, 16_000); assert_eq!(reader.spec().channels, 1); let samples = reader .samples::() .map(|sample| f32::from(sample.unwrap()) / 32768.0) .collect::>(); assert!(samples.len() > 35 * 16_000); let text = model.transcribe(&samples).unwrap().to_lowercase(); for phrase in [ "small community garden", "bright green door", "purple submarine", ] { assert_eq!( text.matches(phrase).count(), repeats, "{name} lost {phrase:?}: {text}" ); } assert!( text.split_whitespace().count() >= 160 * repeats, "{name}: {text}" ); } } #[test] fn yolo_sends_yep_only_after_a_successful_paste() { use crate::app_settings::LabsSettings; use crate::dictation::yolo_mode::{ESCAPE_WINDOW, SendGate}; use std::sync::atomic::AtomicU64; static ESCAPES: AtomicU64 = AtomicU64::new(0); let mut labs = LabsSettings { yolo_mode: true, yolo_mode_apps: vec!["Messages".into()], ..Default::default() }; crate::labs::apply(&labs); let deliver = |text: Result<&str, &str>, app: &str, paste_succeeds: bool| { let mut calls = Vec::new(); let result = text .map(|text| CompletedTranscript { raw: "yep".into(), text: text.into(), nothing: false, application: Some(app.into()), bundle_name: None, return_to: None, timings: JobTimings { audio_ms: 1_000, send_gate: Some(SendGate::on(&ESCAPES, Instant::now() - ESCAPE_WINDOW)), ..processing_job(TranscriptionTarget::Paste).timings }, processing: None, recording: None, }) .map_err(str::to_owned); finish_output( OutputJob::Completed { ticket: OutputTicket::for_test(1), job_id: DictationJobId(1), control: Arc::new(JobControl::default()), target: TranscriptionTarget::Paste, result: Box::new(result), }, &mut |text, mode| { calls.push(match mode { PasteMode::Return => "Return".into(), PasteMode::CopyOnly => format!("copy {text}"), _ => format!("paste {text}"), }); if !paste_succeeds { return Err(eyre!("failed insertion")); } Ok(text.to_owned()) }, &mut Some(LastDictation::new("older dictation".to_owned(), false)), None, ); calls }; assert_eq!( deliver(Ok("yep"), "Messages", true), ["paste yep", "Return"] ); assert_eq!(deliver(Ok("yep"), "Messages", false), ["paste yep"]); assert_eq!(deliver(Ok("yep"), "Notes", true), ["paste yep"]); for no_text in [Ok(""), Ok(" \t\n"), Err("failed transcription")] { assert!(deliver(no_text, "Messages", true).is_empty()); } labs.copy_only = true; crate::labs::apply(&labs); assert_eq!( deliver(Ok("yep"), "Messages", true), ["paste yep", "Return"], "YOLO mode's apps paste and send through Copy dictation only" ); assert_eq!(deliver(Ok("yep"), "Notes", true), ["copy yep"]); crate::labs::apply(&LabsSettings::default()); assert_eq!(deliver(Ok("yep"), "Messages", true), ["paste yep"]); } #[test] fn a_failed_paste_keeps_the_dictation_for_paste_last() { let text = "the dictation whose paste failed"; let mut last_transcript = Some(LastDictation::new("an older dictation".to_string(), false)); let event = finish_output( OutputJob::Completed { ticket: OutputTicket::for_test(1), job_id: DictationJobId(1), control: Arc::new(JobControl::default()), target: TranscriptionTarget::Paste, result: Box::new(Ok(CompletedTranscript { text: text.into(), nothing: false, raw: text.into(), application: None, bundle_name: None, return_to: None, timings: JobTimings { total_started: Instant::now(), queue_ms: 0, audio_ms: 2_000, prepare_ms: 0, inference_ms: 0, send_gate: None, }, processing: None, recording: None, })), }, &mut |_, _| Err(eyre!("clipboard changed while Hex was preserving it")), &mut last_transcript, None, ); assert!(matches!( event, WorkerEvent::Completed { result: Err(_), .. } )); assert_eq!( last_transcript.as_ref().map(LastDictation::text), Some(text) ); } #[test] fn paste_last_reinserts_a_signed_dictation_standalone() { for (signed, expected) in [(true, "standalone"), (false, "continue")] { let mut last_transcript = Some(LastDictation::new( "we ship friday\nSent from Hex".to_string(), signed, )); let mut mode = None; let event = finish_output( OutputJob::Paste { ticket: OutputTicket::for_test(1), kind: PasteKind::LastTranscript, }, &mut |text, paste_mode| { assert_eq!(text, "we ship friday\nSent from Hex"); mode = Some(match paste_mode { PasteMode::Standalone => "standalone", PasteMode::Continue => "continue", PasteMode::CopyOnly | PasteMode::Send | PasteMode::Return => "other", }); Ok(text.to_owned()) }, &mut last_transcript, None, ); assert!(matches!(event, WorkerEvent::Pasted { result: Ok(_), .. })); assert_eq!(mode, Some(expected)); } } #[test] fn a_salvaged_dictation_is_copied_and_kept_for_paste_last_and_history() { // A normal salvage is processed before it is copied; a raw one is // copied as heard and recorded as raw history. Neither is pasted. for (target, kind) in [ (TranscriptionTarget::CopyOnlyPaste, HistoryKind::Dictation), (TranscriptionTarget::RawCopyOnlyPaste, HistoryKind::Raw), ] { let directory = std::env::temp_dir().join(format!( "hex-parakeet-salvage-{}-{target:?}", std::process::id() )); let _ = std::fs::remove_dir_all(&directory); std::fs::create_dir_all(&directory).unwrap(); let history = History::new(crate::history::HistoryStore::open( directory.join("history.json"), crate::history::HistoryRetention::Week, crate::history::now_ms(), )); let text = "the part of the dictation the microphone heard"; let mut pasted = None; let mut last_transcript = None; let event = finish_output( OutputJob::Completed { ticket: OutputTicket::for_test(1), job_id: DictationJobId(1), control: Arc::new(JobControl::default()), target, result: Box::new(Ok(CompletedTranscript { text: text.into(), nothing: false, raw: text.into(), application: Some("Call".into()), bundle_name: None, return_to: None, timings: JobTimings { total_started: Instant::now(), queue_ms: 0, audio_ms: 4_000, prepare_ms: 0, inference_ms: 0, send_gate: None, }, processing: None, recording: None, })), }, &mut |pasted_text, mode| { pasted = Some((pasted_text.to_string(), mode)); Ok(pasted_text.to_owned()) }, &mut last_transcript, Some(&history), ); assert!(matches!( event, WorkerEvent::Completed { result: Ok(ref completed), .. } if completed.as_str() == text )); let (pasted_text, mode) = pasted.expect("the transcript reaches the clipboard"); assert_eq!(pasted_text, text); assert!( matches!(mode, PasteMode::CopyOnly), "{target:?}: an interrupted dictation is copied, never pasted" ); assert_eq!( last_transcript.as_ref().map(LastDictation::text), Some(text) ); let entries = history.recent(1); assert_eq!(entries.len(), 1); assert_eq!(entries[0].kind, kind, "{target:?}"); assert_eq!(entries[0].final_text, text); assert_eq!(entries[0].application.as_deref(), Some("Call")); let _ = std::fs::remove_dir_all(&directory); } } /// Labs › YOLO mode: Escape after the release keeps the paste and skips /// the Return, so History records a dictation rather than a send. #[test] fn escape_after_release_pastes_a_yolo_dictation_without_return() { use crate::dictation::yolo_mode::{ESCAPE_WINDOW, SendGate}; use std::sync::atomic::{AtomicU64, Ordering}; static ESCAPES: AtomicU64 = AtomicU64::new(0); let submitted = Instant::now() - ESCAPE_WINDOW; let presses = std::cell::RefCell::new(Vec::new()); let mut paste = |text: &str, mode| { presses .borrow_mut() .push((text.to_owned(), matches!(mode, PasteMode::Return))); Ok(text.to_owned()) }; let gate = SendGate::on(&ESCAPES, submitted); ESCAPES.fetch_add(1, Ordering::AcqRel); assert!(!send_unless_escaped(gate, submitted, &mut paste)); assert!(presses.borrow().is_empty(), "no Return after an Escape"); let gate = SendGate::on(&ESCAPES, submitted); assert!(send_unless_escaped(gate, submitted, &mut paste)); assert_eq!(*presses.borrow(), [(String::new(), true)]); let failing = SendGate::on(&ESCAPES, submitted); assert!(!send_unless_escaped(failing, submitted, &mut |_, _| Err( eyre!("Return failed") ))); let directory = std::env::temp_dir().join(format!("hex-parakeet-yolo-{}", std::process::id())); let _ = std::fs::remove_dir_all(&directory); std::fs::create_dir_all(&directory).unwrap(); let history = History::new(crate::history::HistoryStore::open( directory.join("history.json"), crate::history::HistoryRetention::Week, crate::history::now_ms(), )); for sent in [false, true] { let mut completed = CompletedTranscript { text: "a long message".into(), nothing: false, raw: "a long message".into(), application: None, bundle_name: None, return_to: None, timings: JobTimings { total_started: Instant::now(), queue_ms: 0, audio_ms: 3_000, prepare_ms: 0, inference_ms: 0, send_gate: Some(SendGate::open()), }, processing: None, recording: None, }; record_history(&history, TranscriptionTarget::Paste, sent, &mut completed); } let kinds: Vec<_> = history .recent(2) .into_iter() .map(|entry| entry.kind) .collect(); assert!(kinds.contains(&HistoryKind::Dictation) && kinds.contains(&HistoryKind::Send)); let _ = std::fs::remove_dir_all(&directory); } #[test] fn parallel_processing_results_are_released_in_submission_order() { let mut outputs = OrderedOutputs::default(); let job = |sequence| OutputJob::Paste { ticket: OutputTicket::for_test(sequence), kind: PasteKind::LastTranscript, }; assert!(outputs.push(job(1)).is_empty()); assert_eq!( outputs .push(job(0)) .into_iter() .map(|job| job.sequence()) .collect::>(), [0, 1] ); assert_eq!( outputs .push(job(2)) .into_iter() .map(|job| job.sequence()) .collect::>(), [2] ); } #[test] fn ordered_waiting_outputs_remain_bounded_after_channel_drain() { let (output_sender, output_receiver) = mpsc::sync_channel(1); let (event_sender, events) = mpsc::channel(); let worker = DictationWorker { engine: None, inference_jobs: None, output_jobs: Some(output_sender), events, event_sender, state: Arc::new(Mutex::new(WorkerState { next_sequence: 1, jobs: BTreeSet::from([DictationJobId(0)]), pending_pastes: 0, skipped: BTreeSet::new(), return_to: None, started_by_shortcut: false, })), inference_worker: None, processor_workers: Vec::new(), output_worker: None, }; let mut ordered = OrderedOutputs::default(); for _ in 1..MAX_PENDING_OUTPUTS { worker.paste_last().unwrap(); assert!(ordered.push(output_receiver.try_recv().unwrap()).is_empty()); } assert_eq!(worker.paste_last(), Err("dictation queue is full")); assert_eq!(ordered.waiting.len(), MAX_PENDING_OUTPUTS - 1); assert_eq!( worker.state.lock().unwrap().next_sequence, MAX_PENDING_OUTPUTS as u64 ); worker.state.lock().unwrap().jobs.remove(&DictationJobId(0)); worker.paste_last().unwrap(); assert_eq!( output_receiver.try_recv().unwrap().sequence(), MAX_PENDING_OUTPUTS as u64 ); } /// Replays recordings into the production engine as capture would (160 ms /// blocks, the last 200 ms held back as the release tail) and compares /// the stream's release latency and text with whole-clip transcription. #[test] #[ignore = "requires HEX_STREAM_MODEL (Unified English GGUF) and HEX_STREAM_WAVS (comma-separated)"] fn metal_stream_tracks_offline_transcription() { use crate::transcription::engine::{Offline, Source, TranscriptionEngine}; use crate::transcription::{Transcriber, WarmTranscriber}; let selection = TranscriptionSelection::default(); let path = PathBuf::from(std::env::var("HEX_STREAM_MODEL").unwrap()); let mut model = Parakeet::load_from(&path, false, Some(&selection)).unwrap(); model .session .probe_stream(&model.stream_run_options(), &path); assert!(model.stream_options().is_some(), "Metal must stream"); let engine = TranscriptionEngine::start(WarmTranscriber::serving(Transcriber::Gguf( Box::new(model), ))) .unwrap(); // `HEX_STREAM_LIVE_TEXT=0` replays without reading live text. let engine = if std::env::var("HEX_STREAM_LIVE_TEXT").is_ok_and(|value| value == "0") { engine } else { engine.with_live_text() }; let speed = std::env::var("HEX_STREAM_SPEED") .ok() .and_then(|speed| speed.parse::().ok()) .unwrap_or(4.0); let offline = || -> Offline { let selection = selection.clone(); Box::new(move |model, samples| { model .activate(&selection) .and_then(|model| model.transcribe(samples)) .map_err(|error| error.to_string()) }) }; let words = |text: &str| { text.split_whitespace() .map(|word| { word.chars() .filter(|c| c.is_alphanumeric()) .flat_map(char::to_lowercase) .collect::() }) .filter(|word| !word.is_empty()) .collect::>() }; for path in std::env::var("HEX_STREAM_WAVS").unwrap().split(',') { let mut reader = WavReader::open(path).unwrap(); let rate = reader.spec().sample_rate; let channels = usize::from(reader.spec().channels); let raw = match reader.spec().sample_format { hound::SampleFormat::Float => reader .samples::() .map(Result::unwrap) .collect::>(), hound::SampleFormat::Int => reader .samples::() .map(|sample| f32::from(sample.unwrap()) / 32_768.0) .collect(), }; let mono = raw .chunks(channels) .map(|frame| frame.iter().sum::() / channels as f32) .collect::>(); let samples = resample_for_parakeet(&mono, rate); // A warm app has already run inputs of this size. let run = |samples: Vec| { engine .finish_with(None, samples, offline()) .unwrap() .wait() .unwrap() }; run(samples.clone()); let whole = run(samples.clone()); let mut stream = engine.begin().expect("the model streams"); let held = samples.len().saturating_sub(3_200); let feeding = Instant::now(); // Live text as a HUD would read it: (audio fed in ms, stable // words, tentative words), and how often the stable text was // rewritten instead of extended. let mut timeline = Vec::new(); let mut stable = String::new(); let mut rewrites = 0; for (index, block) in samples[..held].chunks(2_560).enumerate() { let due = std::time::Duration::from_secs_f64(index as f64 * 0.16 / speed); thread::sleep(due.saturating_sub(feeding.elapsed())); stream.feed(block); if let Some(partial) = stream.take_partial() { if !partial.stable.starts_with(stable.as_str()) { rewrites += 1; } stable = partial.stable.clone(); timeline.push(( stream.fed() / 16, words(&partial.stable).len(), words(&partial.tentative).len(), )); } } thread::sleep(std::time::Duration::from_secs_f64(0.2 / speed)); let streamed = engine .finish_with(Some(stream), samples.clone(), offline()) .unwrap() .wait() .unwrap(); let (reference, hypothesis) = (words(&whole.text), words(&streamed.text)); let mut previous = (0..=hypothesis.len()).collect::>(); for (row, expected) in reference.iter().enumerate() { let mut current = vec![row + 1; hypothesis.len() + 1]; for (column, actual) in hypothesis.iter().enumerate() { current[column + 1] = (previous[column + 1] + 1) .min(current[column] + 1) .min(previous[column] + usize::from(expected != actual)); } previous = current; } let differences = previous[hypothesis.len()]; println!( "{path}: audio_ms={} offline_ms={} release_ms={} ({}) word_differences={differences}/{}", samples.len() / 16, whole.finish_ms, streamed.finish_ms, streamed.source.label(), reference.len() ); println!(" offline {}", whole.text); println!(" stream {}", streamed.text); let first_text_ms = timeline .iter() .find(|(_, stable, tentative)| stable + tentative > 0) .map(|(fed_ms, ..)| *fed_ms); println!( " live text: updates={} first_text_at_audio_ms={first_text_ms:?} stable_rewrites={rewrites} last_stable_words={}/{}", timeline.len(), timeline.last().map_or(0, |(_, stable, _)| *stable), reference.len() ); for (fed_ms, stable, tentative) in &timeline { println!(" audio_ms={fed_ms} stable_words={stable} tentative_words={tentative}"); } let closing_mark = |text: &str| { const CLOSERS: [char; 8] = ['"', '\'', '”', '’', ')', ']', '}', '»']; text.trim_end() .trim_end_matches(CLOSERS) .chars() .last() .is_some_and(|last| matches!(last, '.' | '?' | '!' | '…')) }; // A stream that dropped its closing mark takes the whole-clip // fallback for that reason only (#1933). assert!( streamed.source == Source::Stream || matches!( &streamed.source, Source::Fallback(reason) if reason.as_str() == "the stream ended without closing sentence punctuation" ), "unexpected source {}", streamed.source.label() ); if closing_mark(&whole.text) { assert!( closing_mark(&streamed.text), "the stream dropped the offline text's closing mark: {}", streamed.text ); } assert!(differences * 20 <= reference.len().max(20)); } } #[cfg(hex_capture)] #[test] fn chunked_word_transcription_keeps_word_times_across_chunks() { use crate::transcription::{Transcript, TranscriptSegment}; let span = |start_ms, end_ms, text: &str| TranscriptSegment { start_ms, end_ms, text: text.into(), }; // Loud audio with explicit 200 ms silent pauses centered at 8 s and 16 s // so quiet-span cuts land on those pauses instead of arbitrary sample edges. let mut samples = vec![0.4; 16_000 * 22]; samples[16_000 * 8 - 1_600..16_000 * 8 + 1_600].fill(0.0); samples[16_000 * 16 - 1_600..16_000 * 16 + 1_600].fill(0.0); let mut calls = Vec::new(); let merged = transcribe_in_chunks(samples, 16_000 * 10, |chunk| { calls.push(chunk.len()); let chunk_index = calls.len(); Ok(Transcript { text: format!(" part {chunk_index} "), segments: vec![span(0, 900, " part ")], words: vec![ span(-5, 400, " part"), span(450, 300, "two"), span(500, 600, " "), ], }) }) .unwrap(); assert_eq!(calls.len(), 3); assert!(calls.iter().all(|&len| len <= 16_000 * 10)); let second_ms = (calls[0] / 16) as i64; let third_ms = ((calls[0] + calls[1]) / 16) as i64; // Cuts landed inside the silent pauses around 8 s and 16 s. assert!( (7_900..=8_100).contains(&second_ms), "cut 1 at {second_ms} ms" ); assert!( (15_900..=16_100).contains(&third_ms), "cut 2 at {third_ms} ms" ); assert_eq!(merged.text, "part 1 part 2 part 3"); let words = merged .words .iter() .map(|word| (word.start_ms, word.end_ms, word.text.as_str())) .collect::>(); assert_eq!( words, [ (0, 400, "part"), (450, 450, "two"), (second_ms, second_ms + 400, "part"), (second_ms + 450, second_ms + 450, "two"), (third_ms, third_ms + 400, "part"), (third_ms + 450, third_ms + 450, "two"), ] ); assert_eq!(merged.segments[2].start_ms, third_ms); } #[cfg(hex_capture)] #[test] fn word_chunk_cap_never_exceeds_whisper_max_audio_chunk_samples() { let whisper_cap = crate::transcription::models::max_audio_chunk_samples("whisper", 0).unwrap(); assert!( WORD_CHUNK_SAMPLES <= whisper_cap, "capture foreground chunks must never exceed Whisper's 30 s single-window cap" ); // Even a 30.04 s clip fed into `transcribe_in_chunks` is split so no // chunk exceeds Whisper's 30 s limit. let mut sizes = Vec::new(); transcribe_in_chunks(vec![0.1; whisper_cap + 640], WORD_CHUNK_SAMPLES, |chunk| { sizes.push(chunk.len()); Ok(crate::transcription::Transcript::default()) }) .unwrap(); assert_eq!(sizes.len(), 2); assert!(sizes.iter().all(|&len| len > 0 && len <= whisper_cap)); } #[cfg(hex_capture)] #[test] fn word_transcription_is_a_foreground_request_on_the_shared_engine() { use crate::transcription::engine::Command as EngineCommand; let (engine, commands) = TranscriptionEngine::for_test(); let engine = Arc::new(engine); let weak = Arc::downgrade(&engine); assert!( transcribe_with_words(&weak, &Default::default(), Vec::new()) .unwrap() .words .is_empty() ); assert!( commands.try_recv().is_err(), "silence never reaches the model" ); // A busy dictation holds the chunk back until it is idle. let busy = DictationInference::begin(); let request = { let weak = weak.clone(); thread::spawn(move || { transcribe_with_words( &weak, &Default::default(), vec![0.1; WORD_CHUNK_SAMPLES + 1_600], ) }) }; assert!( commands .recv_timeout(std::time::Duration::from_millis(200)) .is_err() ); drop(busy); let command = commands .recv_timeout(std::time::Duration::from_secs(5)) .unwrap(); // A foreground request: after dictation already sent, counted as a // request so meeting chunks yield to it, and never inside a stream. assert!(matches!( command, EngineCommand::Foreground { ref clip, .. } if !clip.is_empty() && clip.len() <= WORD_CHUNK_SAMPLES )); // The next chunk waits for this one, so a dictation sent meanwhile // runs first. assert!( commands .recv_timeout(std::time::Duration::from_millis(100)) .is_err() ); drop(command); assert!(request.join().unwrap().is_err()); // Only a weak reference is held: once the engine is gone, a capture // fails instead of keeping it alive. drop(engine); assert!(transcribe_with_words(&weak, &Default::default(), vec![0.1; 16]).is_err()); } #[test] #[ignore = "requires HEX_STUTTER_FIXTURE and the installed Parakeet model"] fn tdt_decoder_does_not_repeat_single_letter_tokens() { let path = PathBuf::from(std::env::var("HEX_STUTTER_FIXTURE").unwrap()); let mut reader = WavReader::open(path).unwrap(); let sample_rate = reader.spec().sample_rate; let samples = reader .samples::() .skip(sample_rate as usize * 20) .take(sample_rate as usize * 25) .collect::, _>>() .unwrap(); let samples = resample_for_parakeet(&samples, sample_rate); let text = Parakeet::load().unwrap().transcribe(&samples).unwrap(); assert!(text.contains("sweatshirt"), "unexpected transcript: {text}"); assert!( !text.contains("p p p p") && !text.contains("p-p-p-p"), "pathological token repetition: {text}" ); } } #[cfg(test)] #[path = "dictation/tail_tests.rs"] mod dictation_tail_tests; #[cfg(test)] #[path = "dictation/corpus_tests.rs"] mod dictation_corpus_tests; /// Loads a GGUF model file directly, for opt-in harnesses that replay /// recordings without the installed model catalog. #[cfg(test)] pub(crate) fn load_test_model(path: &std::path::Path) -> Result { Parakeet::load_from(path, false, Some(&TranscriptionSelection::default())) }