mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-28 13:02:21 +01:00
* stream: a faster live-text geometry from the model's own menus Live text trails speech by a whole chunk plus right context: 2.08 s on Parakeet Unified English, whose default tuple is 70/13/13 frames. The only knob was HEX_STREAM_CHUNK_MS, which forced right == chunk and silently disabled streaming when the model's menu rejected the value. Labs › Faster live text (labs.faster_live_text, off by default) asks for a shorter tuple chosen from the model's own GGUF chunk menus: the largest chunk frame count from 2 to 7 and the largest right up to 7, which is 560/560 ms on Unified English (70/7/7, 1.12 s of lookahead) at about 1.6 times the encoder work. A file whose header Hex cannot read still asks for 560/560 in shipped 80 ms frames and trusts the native probe. HEX_STREAM_RIGHT_MS joins HEX_STREAM_CHUNK_MS; a chunk alone still sets the right context, and the env wins over the lab. A geometry the model's menu rejects now warns and falls back to the default tuple instead of turning streaming off. The geometry is cached on the session with the tuning it was probed for, and the engine compares that tuning as each live stream opens, so a toggle change applies to the next capture without a restart (and every other capture pays one comparison). Measured by aymuos15: with 13-frame chunks, live text arrives about 2.08 s behind speech, and right context is what delays it. closes #2102 * audio: the press-across-reopen helper is Linux and Windows only #2098 added a re-export of interruption::capture_idle for the two listeners that read it, but gated it on test too, so a macOS build carries an import nothing there uses. Check macOS (clippy -D warnings) fails on dev with unused import: interruption::capture_idle; PRs only compile on macOS, so it landed unseen. * stream: gate the re-probe, adopt it while idle, keep a failed geometry Review fixes for #2107: - refresh_stream only runs after the gated probe passed (HEX_STREAMING, capability, GPU), so a parked engine on a CPU never starts a stream, and a non-Parakeet model is never re-probed. - a changed tuning is the only thing that re-probes: a failure keeps the working geometry and is not retried, and toggling back is a no-op. - the header is read only when the lab's tuple needs its menus, lazily at load or on the first re-probe; a header that reads fine without chunk menus (a cache-aware model) takes no buffered extension at all. - the engine re-probes after each command and on its idle tick instead of at capture start, and yielding streams check cancellation first. - macOS re-probes with stream_run_options, as its load probe and streams do. - gguf_header keeps only the Parakeet stream keys, and the frame size uses checked_mul. - the card and docs say the pasted text comes from the same shorter lookahead. * stream: drop the unused architecture from the macOS probe call probe_stream no longer takes an architecture (the session reads the file's own), so load_selection's match became an unused variable in a macOS-only module. Linux clippy cannot see it; Check macOS can. * stream: re-probe only when the engine is quiet Review follow-ups for #2107: - the after-command re-probe waits for `next.is_empty() && !recording()`, so a queued Begin, deferred meeting chunk, or active recording never waits behind the probe. - both idle-tick re-probes check `!recording()` too, and the unload tick keeps its park behind the same guard. - docs/features/labs.md's Faster live text row indents its continuation lines at the table's column like every other row.
375 lines
13 KiB
Rust
375 lines
13 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 file_transcript;
|
||
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 stream_tuning;
|
||
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
|
||
}
|
||
}
|
||
|
||
/// Whether a live stream of `model` must end its text with closing sentence
|
||
/// punctuation before it is trusted: Unified English's chunked decode drops
|
||
/// the mark its whole-clip run keeps (issue 1933).
|
||
pub(crate) fn requires_closing_mark(model: Option<TranscriptionModelId>) -> bool {
|
||
model == Some(TranscriptionModelId::ParakeetUnifiedEnglish)
|
||
}
|
||
|
||
#[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,
|
||
}
|
||
}
|
||
|
||
/// Whether a live stream of the warm model must end its text with closing
|
||
/// sentence punctuation before it is trusted, as Unified English's does
|
||
/// (issue 1933).
|
||
pub(crate) fn stream_requires_closing_mark(&self) -> bool {
|
||
match &self.active {
|
||
Some(Transcriber::Gguf(model)) => requires_closing_mark(model.model_id()),
|
||
_ => false,
|
||
}
|
||
}
|
||
|
||
/// 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,
|
||
}
|
||
}
|
||
|
||
/// Re-probes the live stream when Labs › Faster live text or an env
|
||
/// override changed, so the next capture streams with it.
|
||
pub(crate) fn refresh_stream(&mut self) {
|
||
if let Some(Transcriber::Gguf(model)) = &mut self.active {
|
||
model.refresh_stream();
|
||
}
|
||
}
|
||
|
||
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));
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod closing_mark_tests {
|
||
use super::requires_closing_mark;
|
||
use crate::transcription::models::{CustomModelId, TranscriptionModelId};
|
||
|
||
#[test]
|
||
fn only_unified_english_streams_require_a_closing_mark() {
|
||
assert!(requires_closing_mark(Some(
|
||
TranscriptionModelId::ParakeetUnifiedEnglish
|
||
)));
|
||
assert!(!requires_closing_mark(None));
|
||
assert!(!requires_closing_mark(Some(
|
||
TranscriptionModelId::ParakeetV2
|
||
)));
|
||
assert!(!requires_closing_mark(Some(TranscriptionModelId::Custom(
|
||
CustomModelId::parse("custom-0123456789abcdef").expect("16 hex digits")
|
||
))));
|
||
}
|
||
}
|