Repository navigation
Expand file tree
/
Copy pathtranscription.rs
More file actions
296 lines (264 loc) · 10 KB
/
Copy pathtranscription.rs
File metadata and controls
296 lines (264 loc) · 10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
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;
#[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 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(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).
#[cfg(target_os = "macos")]
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) => {
prepare_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) => {
prepare_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),
}
}
}
#[cfg(target_os = "macos")]
fn prepare_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.
#[cfg(target_os = "macos")]
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 tests {
use super::{Transcript, UNIFIED_ENGLISH_TRAILING_SILENCE_SAMPLES, prepare_gguf_samples};
use crate::transcription::models::TranscriptionModelId;
#[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);
}
#[test]
fn unified_english_gets_trailing_silence_for_final_token_context() {
let mut samples = vec![0.5; 32_000];
prepare_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];
prepare_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];
prepare_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));
}
}