hex/src/transcription.rs
Dax cdb96f585e
capture: keep all audio in long captures (#1795) (#1894)
* capture: stream audio to disk so long captures keep all of it

A capture's timeline now writes 16 kHz mono PCM16 to its bundle's
audio.wav as it records, with the leading offset and gaps as silence, so
memory stays flat and the 20-minute drop is gone. An 8-hour guard bounds
disk use only; past it the rest is one recorded gap.

A finished capture is transcribed from the WAV in 30 s pieces, the
reader hex transcribe already used (lifted to transcription/pieces.rs),
and each piece's words move onto the capture clock. The Parakeet, Apple
(path-based), and GGUF paths keep every word without holding the
session. The pipeline never rewrites a streamed audio.wav from empty
samples, an iPhone narration is read back where it must be re-based,
and a cancelled capture closes and removes its file.

* capture: say where a capture's audio stopped

A streamed capture keeps all of its audio, but the 8-hour disk guard (or
a failed audio write) still stops it early, and only the process log
said so. The timeline now carries the stop point onto RecordedAudio,
the bundle stores it as audioStoppedAtMs (serde default, so old bundles
load unchanged), and three places say it plainly: summary.md, `hex
capture show`, and `hex capture status`.

The guard records its point at a 1 s test limit, and the summary line is
tested at 12:34 and 8:00:00 so both clock shapes are covered.

* capture: fill the replay's stop point from its bundle

The 15 s replay builds Written too, on macOS only, so the new field
broke the macOS clippy job while Linux never compiled that function.

* capture: keep a recording out of recovery until it stops

Review fixes for the streamed timeline.

A capture now streams to `audio.wav.partial` and renames it to `audio.wav`
in `Timeline::finish`, so a bundle with a movie and an in-progress audio
file is never mistaken for a capture whose build never ran (recover's
orphan rule, Scrawl.app's `scrawl recover`) and retention cleans a crashed
one like any other bundle. Cancel and discard remove the partial; a failed
publish reads it back into memory rather than pointing at a missing file.

Also: a write failure's stop point is the last sample that reached the
file, not the end of the failed chunk; a trim failure counts every written
sample; the capture's words keep one running frame total instead of
adding truncated per-piece millis; an iPhone narration's `since` drains the
decoded samples instead of copying them and treats a missing file as no
audio; the phone and replay paths carry the audio stop point into their
bundles; and empty audio answers `source: "none"`, as `transcribe_with`
does.

Tests: a movie plus partial audio is never owed, retention trashes a
crashed bundle's media, a write failure records its stop point, a missing
streamed file shifts to no samples, and the replay shift moves the stop
point with the clock.

* capture: publish audio.wav only once its build journals the capture

Follow-ups from review.

A capture now streams to audio.wav.partial and keeps that name after it
stops: the partial is renamed to audio.wav right after the build writes
unfinished.json, so audio.wav never exists without a journal, and a
stopped capture waiting in the finish queue no longer looks like an
orphan to Scrawl.app's recover. A partial that cannot take the name is
read back and written by the build, and its partial name removed; the
replay removes the unshifted partial once the narration is read for
shifting.

Also: a periodic header flush error is now a write failure (the rest of
the capture is a gap) rather than a log line; the midpoint of a failed
write records where the file stopped; and the words test cuts pieces at
odd sample counts and computes offsets from the running frame total, so
per-piece millisecond drift would fail it.

Tests: a streamed audio takes its final name only when the build settles
it (and falls back when it cannot), a capture that has not been
journaled is never owed a rebuild, a mid-capture write failure stops
where the file stopped, and the word offsets are exact at odd piece
lengths.

* capture: consume a streamed recording's partial when it is read

Follow-ups from review.

`RecordedAudio::since` and `into_memory` now remove the partial once its
samples are read: an iPhone narration (capture.rs's `host_narration`
path) used to leave the whole streamed file in the finished bundle. The
replay relies on the same path instead of removing it by hand, and the
light zip leaves `audio.wav.partial` out defensively. A read that fails
is an error to `into_memory` (so a build keeps the only copy) while
`since` still treats a missing file as no audio for an iPhone.

A failed publish now reads the audio back only when it produced the
samples the recording had; a failed read keeps the partial and removes
any half-copied `audio.wav`. `publish_audio` takes `&mut self` and points
the recording at the published file.

A journaled bundle whose `audio.wav` is missing adopts `audio.wav.partial`
before rebuilding. Docs say the guarantee is a streamed capture's, and
that a crash while recording or queued is retention's job, not
recovery's.

Tests: reading a streamed recording consumes the partial; a finished
iPhone bundle keeps none; a streamed audio is published only when its
build settles it, including the read-back and unreadable-partial cases; a
journaled capture adopts its partial.

* capture: keep a failed audio publish recoverable

Follow-ups from review.

The publish fallback read the partial with `into_memory`, which deletes
it, and then ignored whether its own write landed: a failed write left
the audio nowhere. It now reads through `read_streamed` (no deletion),
writes `audio.wav` and checks the result, and removes the partial only
once that write succeeded. A failed read or write removes any half
`audio.wav` and fails the build, which is the pipeline's existing failed
path: `recover::finished` runs only for an `Ok` build, so `unfinished.json`
stays and the next launch's recovery adopts the partial instead of the
capture quietly finishing without its audio.

`publish_audio` also treats a landed copy as success even when deleting
the partial fails, logging it rather than reporting failure and letting
the fallback overwrite a good `audio.wav`.

Tests: a blocked target keeps the partial and fails the build; a
fallback write that lands consumes the partial and writes `audio.wav`;
an unreadable partial is kept.
2026-11-16 10:28:54 -05:00

328 lines
11 KiB
Rust

pub(crate) mod app_model_switching;
pub(crate) mod artifacts;
pub(crate) mod background_priority;
#[cfg(target_os = "macos")]
pub(crate) mod benchmark;
#[cfg(all(
target_arch = "x86_64",
any(target_os = "linux", target_os = "windows")
))]
pub(crate) mod cpu_floor;
pub(crate) mod custom_models;
pub(crate) mod engine;
pub(crate) mod found_models;
pub(crate) mod gguf_header;
#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]
pub(crate) mod gguf_session;
#[cfg(any(target_os = "linux", target_os = "windows"))]
pub(crate) mod gpu_health;
pub(crate) mod keyboard_model_switching;
pub(crate) mod languages;
#[cfg(any(target_os = "linux", target_os = "windows"))]
pub(crate) mod local_transcriber;
pub(crate) mod model_benchmarks;
pub(crate) mod model_details;
pub(crate) mod models;
pub(crate) mod pause_segmenter;
pub(crate) mod pieces;
#[cfg(any(target_os = "macos", target_os = "windows", test))]
pub(crate) mod preparation;
pub(crate) mod service;
pub(crate) mod speech_detector;
pub(crate) mod stream;
pub(crate) mod subtitle_credits;
pub(crate) mod transcript;
#[cfg(target_os = "macos")]
use color_eyre::eyre::Result;
#[cfg(target_os = "macos")]
use crate::apple_speech::AppleSpeech;
#[cfg(target_os = "macos")]
use crate::parakeet::Parakeet;
#[cfg(not(target_os = "macos"))]
use crate::transcription::models::TranscriptionModelId;
#[cfg(target_os = "macos")]
use crate::transcription::models::{
ModelRuntime, TranscriptionModelId, TranscriptionSelection, validate,
};
#[cfg(target_os = "macos")]
pub use crate::transcription::transcript::{Transcript, TranscriptSegment};
/// Silence after a Unified English clip (400 ms at 16 kHz), so the model
/// has the context to emit the final word and its closing punctuation
/// (issue 657: sentences lost their full stop or question mark).
pub(crate) const UNIFIED_ENGLISH_TRAILING_SILENCE_SAMPLES: usize = 6_400;
#[cfg(target_os = "macos")]
pub enum Transcriber {
Gguf(Box<Parakeet>),
AppleSpeech(AppleSpeech),
}
#[cfg(target_os = "macos")]
#[derive(Default)]
pub struct WarmTranscriber {
active: Option<Transcriber>,
}
#[cfg(target_os = "macos")]
impl Transcriber {
pub fn load() -> Result<Self> {
let (_, selection) = crate::app_settings::transcription_selection();
Self::load_selection(&selection)
}
pub fn load_selection(selection: &TranscriptionSelection) -> Result<Self> {
match validate(selection)?.runtime {
ModelRuntime::Gguf(_) => Parakeet::load_selection(selection)
.map(Box::new)
.map(Self::Gguf),
ModelRuntime::AppleSpeech => AppleSpeech::load(selection).map(Self::AppleSpeech),
}
}
pub fn matches_selection(&self, selection: &TranscriptionSelection) -> bool {
match self {
Self::Gguf(model) => model.matches_selection(selection),
Self::AppleSpeech(model) => model.matches_selection(selection),
}
}
/// Brings an idle GGUF model's weights back before audio arrives (see
/// [`Parakeet::prewarm`]). Apple Speech has no weights of Hex's to warm.
pub fn prewarm(&mut self) -> Result<()> {
match self {
Self::Gguf(model) => model.prewarm(),
Self::AppleSpeech(_) => Ok(()),
}
}
/// Transcribe normalized 16 kHz audio. Backend padding is applied once here,
/// before GGUF chunking or any hex retranscription.
pub fn transcribe(&mut self, mut samples: Vec<f32>) -> Result<String> {
match self {
Self::Gguf(model) => {
pad_gguf_samples(&mut samples, model.model_id());
model.transcribe(&samples)
}
Self::AppleSpeech(model) => model.transcribe(&samples).map(|result| result.text),
}
}
/// Transcribe one normalized segment with the same input preparation as
/// plain dictation. The caller retains ownership of segment offsets.
pub fn transcribe_segments(&mut self, mut samples: Vec<f32>) -> Result<Transcript> {
match self {
Self::Gguf(model) => {
pad_gguf_samples(&mut samples, model.model_id());
model
.transcribe_segments(&samples)
.map(|result| Transcript {
text: result.text,
segments: result
.segments
.into_iter()
.map(|segment| TranscriptSegment {
start_ms: segment.t0_ms,
end_ms: segment.t1_ms,
text: segment.text,
})
.collect(),
words: result
.words
.into_iter()
.map(|word| TranscriptSegment {
start_ms: word.t0_ms,
end_ms: word.t1_ms,
text: word.text,
})
.collect(),
})
}
Self::AppleSpeech(model) => model.transcribe(&samples),
}
}
/// A complete clip with its native timings, padded exactly as
/// [`Self::transcribe`] pads it so the text matches an untimed request.
pub fn transcribe_timed(&mut self, mut samples: Vec<f32>) -> Result<Transcript> {
match self {
Self::Gguf(model) => {
pad_gguf_samples(&mut samples, model.model_id());
model.transcribe_timed(&samples)
}
// Apple Speech segments the whole clip itself.
Self::AppleSpeech(model) => model.transcribe(&samples),
}
}
/// The finest native timings this backend gives: Apple Speech segments,
/// and a GGUF model what its metadata advertises.
pub fn timestamps(&self) -> crate::transcription::transcript::TimestampLevel {
match self {
Self::Gguf(model) => model.timestamps(),
Self::AppleSpeech(_) => crate::transcription::transcript::TimestampLevel::Segment,
}
}
}
/// Pads a GGUF clip as dictation prepares it on every OS: the backend's
/// minimum duration, then the model's trailing silence. Applied after any
/// pause cut, so a trailing pause cannot trim that silence.
pub(crate) fn pad_gguf_samples(samples: &mut Vec<f32>, model: Option<TranscriptionModelId>) {
crate::dictation::pad_for_parakeet(samples);
samples.resize(samples.len() + trailing_silence_samples(model), 0.0);
}
/// Silence a clip of `model` gets after its audio, whole clip or stream.
pub(crate) fn trailing_silence_samples(model: Option<TranscriptionModelId>) -> usize {
if model == Some(TranscriptionModelId::ParakeetUnifiedEnglish) {
UNIFIED_ENGLISH_TRAILING_SILENCE_SAMPLES
} else {
0
}
}
#[cfg(target_os = "macos")]
impl WarmTranscriber {
/// A warm transcriber already serving `model`, for opt-in harnesses.
#[cfg(test)]
pub(crate) fn serving(model: Transcriber) -> Self {
Self {
active: Some(model),
}
}
pub fn load() -> Result<Self> {
Ok(Self {
active: Some(Transcriber::load()?),
})
}
/// The selection of the warm model when it is a GGUF model.
pub(crate) fn gguf_selection(&self) -> Option<&TranscriptionSelection> {
match &self.active {
Some(Transcriber::Gguf(model)) => model.selection(),
_ => None,
}
}
/// Silence a live stream of the warm model hears before it finalizes,
/// the same trailing silence its whole-clip runs get.
pub(crate) fn stream_trailing_silence(&self) -> usize {
match &self.active {
Some(Transcriber::Gguf(model)) => trailing_silence_samples(model.model_id()),
_ => 0,
}
}
/// Stream options of the warm model, when it can stream on its device.
pub(crate) fn stream_options(&self) -> Option<&transcribe_cpp::StreamOptions> {
match &self.active {
Some(Transcriber::Gguf(model)) => model.stream_options(),
_ => None,
}
}
pub(crate) fn with_stream<R>(
&mut self,
stream_options: &transcribe_cpp::StreamOptions,
cancel: &transcribe_cpp::CancelToken,
drive: impl FnOnce(&mut transcribe_cpp::Stream<'_>) -> R,
) -> transcribe_cpp::Result<R> {
match &mut self.active {
Some(Transcriber::Gguf(model)) => model.with_stream(stream_options, cancel, drive),
_ => Err(transcribe_cpp::Error::NotImplemented(
"the active transcriber cannot stream".into(),
)),
}
}
/// The loaded model, without switching or loading one.
pub(crate) fn active(&mut self) -> Option<&mut Transcriber> {
self.active.as_mut()
}
pub fn activate(&mut self, selection: &TranscriptionSelection) -> Result<&mut Transcriber> {
if !self
.active
.as_ref()
.is_some_and(|model| model.matches_selection(selection))
{
let candidate = Transcriber::load_selection(selection)?;
self.active = Some(candidate);
}
Ok(self
.active
.as_mut()
.expect("activated transcriber must be available"))
}
}
#[cfg(all(test, target_os = "macos"))]
mod apple_speech_tests {
use super::Transcript;
#[test]
fn apple_bridge_transcript_uses_the_canonical_wire_shape() {
let transcript: Transcript = serde_json::from_str(
r#"{"text":"hello","segments":[{"startMs":10,"endMs":40,"text":"hello"}]}"#,
)
.unwrap();
assert_eq!(transcript.text, "hello");
assert_eq!(transcript.segments.len(), 1);
assert_eq!(transcript.segments[0].start_ms, 10);
assert_eq!(transcript.segments[0].end_ms, 40);
}
}
#[cfg(test)]
mod padding_tests {
use super::{UNIFIED_ENGLISH_TRAILING_SILENCE_SAMPLES, pad_gguf_samples};
use crate::transcription::models::TranscriptionModelId;
#[test]
fn unified_english_gets_trailing_silence_for_final_token_context() {
let mut samples = vec![0.5; 32_000];
pad_gguf_samples(
&mut samples,
Some(TranscriptionModelId::ParakeetUnifiedEnglish),
);
assert_eq!(
samples.len(),
32_000 + UNIFIED_ENGLISH_TRAILING_SILENCE_SAMPLES
);
assert!(samples[..32_000].iter().all(|sample| *sample == 0.5));
assert!(samples[32_000..].iter().all(|sample| *sample == 0.0));
}
#[test]
fn other_gguf_models_do_not_get_trailing_silence() {
let mut samples = vec![0.5; 32_000];
pad_gguf_samples(&mut samples, Some(TranscriptionModelId::ParakeetV2));
assert_eq!(samples.len(), 32_000);
}
#[test]
fn short_unified_input_is_minimum_padded_before_trailing_context() {
let mut samples = vec![0.5; 1_600];
pad_gguf_samples(
&mut samples,
Some(TranscriptionModelId::ParakeetUnifiedEnglish),
);
// The 400 ms context is additional to the 1.5 s minimum, not part of it.
assert_eq!(
samples.len(),
24_000 + UNIFIED_ENGLISH_TRAILING_SILENCE_SAMPLES
);
assert!(samples[..1_600].iter().all(|sample| *sample == 0.5));
assert!(samples[1_600..].iter().all(|sample| *sample == 0.0));
}
}