forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

main.rs2308 lines, 92.9 KiBHistoryRawDownload
1//! edith-stt: offline Whisper speech-to-text on CPU (candle), JSON-lines output.
2//!
3//! usage: edith-stt --model base|small|tiny|<dir> [--device cpu|gpu] [--language en|auto] [--offset SECS] [--no-align] [--keep-all] <input.wav>
4//! edith-stt --has-gpu
5//!
6//! stdout: one JSON object per segment
7//! {"start":s,"end":s,"text":"...","words":[{"w":"Hello","start":s,"end":s,"p":prob}],"approx":false,
8//! "no_speech":p,"avg_logprob":lp}
9//! `approx` is true when the segment's words were spread proportionally (--no-align, or the
10//! cross-attention alignment failed for it); false when words come from DTW over cross-attention.
11//! `no_speech` is the window's `<|nocaptions|>` probability at the first decode step; `avg_logprob`
12//! is the mean token log-prob of the segment; `span_db` is the segment's level over the window's
13//! noise floor (null when unknown). Segments that look like hallucinated silence are
14//! dropped unless `--keep-all` is given (see `silence_reason`). With an English transcript the
15//! decoder never emits CJK, kana, Hangul, Cyrillic, Arabic or Indic tokens (see `Suppress`).
16//! stderr: progress lines `progress <0..1>` and diagnostics.
17
18mod whisper_model;
19#[cfg(feature = "vulkan")]
20mod gpu;
21#[cfg(not(feature = "vulkan"))]
22mod gpu {
23 use crate::Cli;
24 use anyhow::{bail, Result};
25
26 const NO_VULKAN: &str = "edith-stt was built without vulkan; rebuild with --features vulkan";
27
28 pub fn probe() -> Result<()> {
29 bail!(NO_VULKAN)
30 }
31
32 pub fn run(_: &Cli) -> Result<()> {
33 bail!(NO_VULKAN)
34 }
35}
36
37use anyhow::{anyhow, bail, Context, Result};
38use candle_core::{DType, Device, IndexOp, Tensor};
39use candle_nn::VarBuilder;
40use candle_transformers::models::whisper::{self as m, Config};
41use whisper_model::Whisper;
42use std::collections::HashMap;
43use std::fs::{self, File};
44use std::io::{BufReader, Write};
45use std::path::{Path, PathBuf};
46use std::time::Instant;
47
48const SR: usize = 16_000;
49/// 30 s window in samples (480000).
50const WINDOW: usize = m::N_SAMPLES;
51/// Samples per mel frame (10 ms).
52const FRAME: usize = m::HOP_LENGTH;
53/// Whisper timestamp token resolution.
54const SEC_PER_TS: f64 = 0.02;
55/// Temperature fallback schedule, as Whisper's reference: a window whose output is rejected is
56/// decoded again at the next temperature.
57const TEMPS: [f64; 6] = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0];
58/// A window whose text compresses above this ratio is a repetition: rejected.
59const MAX_COMPRESSION_RATIO: f64 = 2.4;
60/// A window whose mean token log-prob is below this is rejected.
61const MIN_AVG_LOGPROB: f64 = -1.0;
62const MAX_REPEAT: usize = 20;
63/// A text phrase (2 to `LOOP_MAX_PERIOD` tokens, timestamps skipped) repeated this many times in
64/// a row is a loop: the window ends after its first copy. Whisper loops on silence and fillers.
65const LOOP_REPEATS: usize = 4;
66const LOOP_MAX_PERIOD: usize = 24;
67/// Seek step after a looped window that has no timestamp before the loop. Short, so the speech
68/// that follows the loop is decoded next instead of being skipped with the whole window.
69const LOOP_STEP_S: f64 = 5.0;
70/// Longest `--prompt` kept, in tokens (Whisper's prompt budget).
71const MAX_PREV_TOKENS: usize = 223;
72/// Silence filter thresholds (see `silence_reason`).
73const NO_SPEECH_PROB: f64 = 0.6;
74const NO_SPEECH_LOGPROB: f64 = -1.0;
75const KNOWN_SIZES: &[&str] = &["tiny", "base", "small", "medium", "large-v2", "large-v3", "large-v3-turbo"];
76const REQUIRED: &[&str] = &[
77 "config.json",
78 "model.safetensors",
79 "tokenizer.json",
80 "preprocessor_config.json",
81];
82const OPTIONAL: &[&str] = &["generation_config.json"];
83
84fn main() {
85 if let Err(e) = run() {
86 eprintln!("edith-stt: error: {e:#}");
87 std::process::exit(1);
88 }
89}
90
91struct Cli {
92 model: String,
93 language: String,
94 offset: f64,
95 /// Word times from cross-attention DTW (default). `--no-align` gives proportional times.
96 align: bool,
97 /// `--keep-all`: emit every segment, including ones the silence filter would drop.
98 keep_all: bool,
99 /// `--prompt`: text Whisper sees before the audio, as OpenAI's `initial_prompt`. Names and
100 /// jargon spelled the way they should come out ("Edith, LUFS") steer the decoder.
101 prompt: Option<String>,
102 gpu: bool,
103 has_gpu: bool,
104 input: PathBuf,
105}
106
107fn usage() -> &'static str {
108 "usage: edith-stt --model base|small|tiny|<dir>|<file.bin> [--device cpu|gpu] [--language en|auto] [--offset SECS] [--no-align] [--keep-all] [--prompt TEXT] <input.wav>\n edith-stt --has-gpu"
109}
110
111fn parse_cli() -> Result<Cli> {
112 let mut model = "base".to_string();
113 let mut language = "en".to_string();
114 let mut offset = 0.0f64;
115 let mut align = true;
116 let mut keep_all = false;
117 let mut prompt: Option<String> = None;
118 let mut gpu = false;
119 let mut has_gpu = false;
120 let mut input: Option<PathBuf> = None;
121 let mut args = std::env::args().skip(1);
122 while let Some(a) = args.next() {
123 match a.as_str() {
124 "--model" => model = args.next().context("--model needs a value")?,
125 "--device" => {
126 gpu = match args.next().context("--device needs a value")?.as_str() {
127 "cpu" => false,
128 "gpu" => true,
129 other => bail!("--device must be cpu or gpu, got {other}"),
130 }
131 }
132 "--has-gpu" => has_gpu = true,
133 "--language" => language = args.next().context("--language needs a value")?,
134 "--offset" => {
135 offset = args
136 .next()
137 .context("--offset needs a value")?
138 .parse()
139 .context("--offset must be a number of seconds")?
140 }
141 "--no-align" => align = false,
142 "--keep-all" => keep_all = true,
143 "--prompt" => prompt = Some(args.next().context("--prompt needs a value")?),
144 "-h" | "--help" => {
145 println!("{}", usage());
146 std::process::exit(0);
147 }
148 s if s.starts_with("--") => bail!("unknown flag {s}\n{}", usage()),
149 s => {
150 if input.is_some() {
151 bail!("only one input file allowed\n{}", usage());
152 }
153 input = Some(PathBuf::from(s));
154 }
155 }
156 }
157 let input = match (has_gpu, input) {
158 (true, Some(_)) => bail!("--has-gpu takes no input file\n{}", usage()),
159 (true, None) => PathBuf::new(),
160 (false, input) => input.with_context(|| usage().to_string())?,
161 };
162 Ok(Cli { model, language, offset, align, keep_all, prompt, gpu, has_gpu, input })
163}
164
165fn run() -> Result<()> {
166 let cli = parse_cli()?;
167 if cli.has_gpu {
168 return gpu::probe();
169 }
170 if cli.gpu {
171 return gpu::run(&cli);
172 }
173 let dir = resolve_model(&cli.model)?;
174 let t_start = Instant::now();
175
176 let cfg: Config = serde_json::from_reader(BufReader::new(
177 File::open(dir.join("config.json")).context("open config.json")?,
178 ))?;
179 let pc: serde_json::Value = serde_json::from_reader(BufReader::new(
180 File::open(dir.join("preprocessor_config.json")).context("open preprocessor_config.json")?,
181 ))?;
182 let filters = load_mel_filters(&pc, cfg.num_mel_bins)?;
183
184 let dev = Device::Cpu;
185 // SAFETY: the safetensors file is read-only and we do not modify it while mapped.
186 let vb = unsafe {
187 VarBuilder::from_mmaped_safetensors(&[dir.join("model.safetensors")], DType::F32, &dev)?
188 };
189 let mut model = Whisper::load(&vb, cfg.clone())?;
190 let vocab = Vocab::load(&dir.join("tokenizer.json"))?;
191 let ids = Ids::new(&vocab)?;
192 let heads = alignment_heads(&dir, &cfg)?;
193 eprintln!("model loaded from {} in {:.2}s", dir.display(), t_start.elapsed().as_secs_f64());
194
195 let pcm = read_wav_16k_mono(&cli.input)?;
196 let audio_s = pcm.len() as f64 / SR as f64;
197 let total_frames = pcm.len().div_ceil(FRAME);
198
199 let mut lang: Option<u32> = if cli.language.eq_ignore_ascii_case("auto") {
200 None
201 } else {
202 Some(vocab.id(&format!("<|{}|>", cli.language.to_ascii_lowercase()))?)
203 };
204
205 let t_decode = Instant::now();
206 let mut rng = Rng(0x9E37_79B9_7F4A_7C15);
207 // Previous-text prompt: <|startofprev|> then the hint's tokens, the newest 223 at most
208 // (half of Whisper's 448-token context, less one, as in OpenAI's `initial_prompt`).
209 let mut prev: Vec<u32> = Vec::new();
210 if let Some(text) = cli.prompt.as_deref().map(str::trim).filter(|t| !t.is_empty()) {
211 let mut toks = vocab.encode(&format!(" {text}"));
212 if toks.len() > MAX_PREV_TOKENS {
213 toks.drain(..toks.len() - MAX_PREV_TOKENS);
214 }
215 if !toks.is_empty() {
216 prev.push(ids.startofprev);
217 prev.extend(toks);
218 }
219 eprintln!("prompt: {} token(s)", prev.len().saturating_sub(1));
220 }
221 let en_id = vocab.id("<|en|>").ok();
222 let mut sup: Option<Suppress> = None;
223 let mut seek = 0usize; // in mel frames (10 ms)
224 let mut n_segs = 0usize;
225 let mut align_s = 0f64;
226 let mut align_fail = 0usize;
227 // Absolute end of the last word emitted: the gap before the next segment starts there.
228 let mut prev_end_abs = 0f64;
229 while seek < total_frames {
230 let start_sample = seek * FRAME;
231 let end_sample = (start_sample + WINDOW).min(pcm.len());
232 let content_frames = (end_sample - start_sample).div_ceil(FRAME);
233 let content_s = content_frames as f64 * 0.01;
234 let seek_s = seek as f64 * 0.01;
235
236 let mut win = vec![0f32; WINDOW];
237 win[..end_sample - start_sample].copy_from_slice(&pcm[start_sample..end_sample]);
238 let mel = m::audio::pcm_to_mel(&cfg, &win, &filters);
239 let n_frames = mel.len() / cfg.num_mel_bins;
240 let mel_t = Tensor::from_vec(mel, (1, cfg.num_mel_bins, n_frames), &dev)?
241 .narrow(2, 0, WINDOW / FRAME)?;
242 let enc = model.encoder.forward(&mel_t, true)?;
243 // Levels and noise floor of the window's real audio, not its zero padding.
244 let lv = levels(&pcm[start_sample..end_sample]);
245 let speech = speech_frames(&lv);
246 let n_content = (end_sample - start_sample).div_ceil(ENC_HOP);
247
248 if lang.is_none() {
249 let (id, code) = detect_language(&mut model, &enc, &vocab, &ids, &dev)?;
250 eprintln!("detected language {code}");
251 lang = Some(id);
252 }
253 let mut prompt = prev.clone();
254 prompt.extend([ids.sot, lang.unwrap(), ids.transcribe]);
255
256 // English-only suppression follows the language in use: decided once, on the first window.
257 let english = lang == en_id;
258 let sup = sup.get_or_insert_with(|| Suppress::new(&vocab, english, ids.ts0));
259 let mut attempt = 0;
260 let (toks, no_speech, looped) = loop {
261 let temp = TEMPS[attempt];
262 let (toks, no_speech, looped) =
263 decode_window(&mut model, &enc, &prompt, temp, &ids, &cfg, sup, &mut rng, &dev)?;
264 let ids_only: Vec<u32> = toks.iter().map(|t| t.0).collect();
265 let text = vocab.decode(&ids_only);
266 let ratio = compression_ratio(&text)?;
267 let avg = avg_logprob(&toks);
268 attempt += 1;
269 let bad = window_rejected(ratio, avg, looped && !has_text(&toks, ids.ts0));
270 if !bad || attempt == TEMPS.len() {
271 break (toks, no_speech, looped);
272 }
273 eprintln!(
274 "window at {seek_s:.2}s: temp {temp} rejected (ratio {ratio:.2}, avg_logprob {avg:.2}, looped {looped}), retrying"
275 );
276 };
277
278 if std::env::var_os("EDITH_STT_DEBUG").is_some() {
279 let ids_dbg: Vec<u32> = toks.iter().map(|t| t.0).collect();
280 eprintln!("debug window {seek_s:.2}s: {} tokens: {:?}", toks.len(), &ids_dbg[..ids_dbg.len().min(60)]);
281 eprintln!("debug text: {:?}", vocab.decode(&ids_dbg));
282 }
283 // Split into segments and find where to seek next.
284 let ends_with_ts = toks.last().is_some_and(|t| t.0 >= ids.ts0);
285 let last_ts_time = toks
286 .iter()
287 .rev()
288 .find(|t| t.0 >= ids.ts0)
289 .map(|t| (t.0 - ids.ts0) as f64 * SEC_PER_TS);
290 let segs = split_segments(&toks, ids.ts0, content_s);
291
292 for seg in &segs {
293 // The model can place timestamps past the real audio in a short tail window.
294 if seg.start >= content_s || starts_past_end(seek_s + seg.start, audio_s) {
295 eprintln!("dropped segment at {:.2}s: starts at or past the audio end", seek_s + seg.start);
296 continue;
297 }
298 let abs_start = seek_s + seg.start + cli.offset;
299 let abs_end = (seek_s + seg.end.min(content_s) + cli.offset).max(abs_start);
300 let text_ids: Vec<u32> = seg.toks.iter().map(|t| t.0).collect();
301 let text = vocab.decode(&text_ids).trim().to_string();
302 if text.is_empty() {
303 continue;
304 }
305 let avg = avg_logprob(&seg.toks);
306 // Span level against the window's noise floor, from the window start.
307 let span = span_rel_db(&lv, seg.start, seg.end.min(content_s));
308 if let Some(reason) = silence_reason(no_speech, avg, span) {
309 if !cli.keep_all {
310 eprintln!(
311 "skipped segment {abs_start:.2}-{abs_end:.2}s ({reason}, no_speech {no_speech:.2}, avg_logprob {avg:.2}): {text:?}"
312 );
313 continue;
314 }
315 }
316 let aligned = if cli.align {
317 let t_al = Instant::now();
318 let crop = trim_crop_to_speech(
319 crop_frames(seg.start, seg.end.min(content_s), n_content, ALIGN_PAD_LEFT_S, ALIGN_PAD_RIGHT_S),
320 &speech,
321 );
322 let r = aligned_words(
323 &mut model,
324 &enc,
325 &prompt,
326 &seg.toks,
327 &vocab,
328 &ids,
329 &heads,
330 crop,
331 n_content,
332 seek_s + cli.offset,
333 &speech,
334 &dev,
335 );
336 align_s += t_al.elapsed().as_secs_f64();
337 match r {
338 Ok(w) => Some(w),
339 Err(e) => {
340 align_fail += 1;
341 eprintln!("word alignment failed at {abs_start:.2}s, using proportional times: {e:#}");
342 None
343 }
344 }
345 } else {
346 None
347 };
348 let (mut words, approx) = match aligned {
349 Some(w) => (w, false),
350 None => (word_times(&vocab, &seg.toks, abs_start, abs_end), true),
351 };
352 // Words that start at or past the audio end are cut, the rest of the segment stays;
353 // a word that runs past the end has its end clamped to it.
354 let n_words = words.len();
355 let cut = fit_words_to_audio(&mut words, cli.offset, audio_s);
356 if n_words > 0 && words.is_empty() {
357 eprintln!("dropped segment at {abs_start:.2}s: every word starts at or past the audio end: {text:?}");
358 continue;
359 }
360 let text = if cut > 0 {
361 eprintln!("cut {cut} word(s) at {abs_start:.2}s that start at or past the audio end");
362 words.iter().filter_map(|w| w["w"].as_str()).collect::<Vec<_>>().join(" ")
363 } else {
364 text
365 };
366 // A leading filler the window's decode dropped (Whisper drops a leading "Um" depending
367 // on the window it is given). When speech sounds for over ONSET_MIN_S before the first
368 // word, after the previous word, that gap is decoded again on its own and the filler
369 // words it holds go in front of the segment.
370 let win_abs = seek_s + cli.offset;
371 let (words, text) = match (cli.align, words.first().and_then(|w| w["start"].as_f64())) {
372 (true, Some(first)) => {
373 let first_rel = first - win_abs;
374 let from = ((prev_end_abs - win_abs).max(0.0) / ENC_SPF) as usize;
375 let word_frame = (first_rel.max(0.0) / ENC_SPF) as usize;
376 match leading_onset(&speech, from, word_frame) {
377 Some(onset) => {
378 let gap_lo = (onset as f64 * ENC_SPF - RECOVER_MARGIN_S).max(prev_end_abs - win_abs).max(0.0);
379 let gap_hi = first_rel + RECOVER_MARGIN_S;
380 match decode_gap_fillers(
381 &mut model,
382 &pcm,
383 start_sample,
384 (gap_lo, gap_hi),
385 &prompt,
386 &vocab,
387 &ids,
388 &cfg,
389 &filters,
390 &heads,
391 sup,
392 &mut rng,
393 win_abs,
394 &dev,
395 ) {
396 Ok(found) => {
397 let fillers = recovered_fillers(&found, prev_end_abs, first);
398 if fillers.is_empty() {
399 (words, text)
400 } else {
401 let lead: Vec<&str> = fillers.iter().filter_map(|w| w["w"].as_str()).collect();
402 eprintln!("recovered leading filler(s) {lead:?} at {first:.2}s");
403 let text = format!("{} {}", lead.join(" "), text);
404 let words = fillers.into_iter().chain(words).collect();
405 (words, text)
406 }
407 }
408 Err(e) => {
409 eprintln!("filler recovery failed at {first:.2}s: {e:#}");
410 (words, text)
411 }
412 }
413 }
414 None => (words, text),
415 }
416 }
417 _ => (words, text),
418 };
419 // Whisper's segment stamps can start before the speech or stop after it. Once the
420 // words are timed, the segment spans exactly its first word through its last.
421 let (abs_start, abs_end) = match (words.first(), words.last()) {
422 (Some(f), Some(l)) => (
423 f["start"].as_f64().unwrap_or(abs_start),
424 l["end"].as_f64().unwrap_or(abs_end),
425 ),
426 _ => (abs_start, abs_end),
427 };
428 if let Some(e) = words.last().and_then(|w| w["end"].as_f64()) {
429 prev_end_abs = e;
430 }
431 let line = serde_json::json!({
432 "start": r3(abs_start),
433 "end": r3(abs_end),
434 "text": text,
435 "words": words,
436 "approx": approx,
437 "no_speech": r3(no_speech),
438 "avg_logprob": r3(avg),
439 "span_db": span.map(r3),
440 });
441 println!("{line}");
442 n_segs += 1;
443 }
444 std::io::stdout().flush()?;
445
446 let advance = seek_advance_frames(ends_with_ts, last_ts_time, looped, content_frames);
447 seek += advance.max(1);
448 let p = (seek as f64 / total_frames as f64).min(1.0);
449 eprintln!("progress {p:.4}");
450 }
451
452 let elapsed = t_decode.elapsed().as_secs_f64();
453 eprintln!(
454 "done: {n_segs} segments, audio {audio_s:.2}s, decode {elapsed:.2}s, RTF {:.3}",
455 elapsed / audio_s.max(1e-9)
456 );
457 if cli.align {
458 eprintln!(
459 "alignment {align_s:.2}s ({:.1}% of decode), {align_fail} segment(s) fell back to proportional times",
460 100.0 * align_s / elapsed.max(1e-9)
461 );
462 }
463 Ok(())
464}
465
466fn r3(x: f64) -> f64 {
467 (x * 1000.0).round() / 1000.0
468}
469
470// ---------------------------------------------------------------- model files
471
472fn resolve_model(arg: &str) -> Result<PathBuf> {
473 let p = Path::new(arg);
474 if p.is_dir() {
475 return Ok(p.to_path_buf());
476 }
477 if !KNOWN_SIZES.contains(&arg) {
478 bail!("model '{arg}' is neither a directory nor one of {KNOWN_SIZES:?}");
479 }
480 let home = std::env::var("HOME").context("HOME not set")?;
481 let dir = PathBuf::from(home).join(".cache/edith/models").join(format!("whisper-{arg}"));
482 fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
483 let base = format!("https://huggingface.co/openai/whisper-{arg}/resolve/main");
484 for f in REQUIRED {
485 if !dir.join(f).exists() {
486 eprintln!("downloading {base}/{f}");
487 if let Err(e) = fetch(&format!("{base}/{f}"), &dir.join(f), false) {
488 bail!(
489 "{e:#}\n\nfetch the files manually:\n mkdir -p {d}\n{cmds}",
490 d = dir.display(),
491 cmds = REQUIRED
492 .iter()
493 .chain(OPTIONAL.iter())
494 .map(|f| format!(" curl -fL -o {d}/{f} {base}/{f}", d = dir.display()))
495 .collect::<Vec<_>>()
496 .join("\n")
497 );
498 }
499 }
500 }
501 for f in OPTIONAL {
502 if !dir.join(f).exists() {
503 let _ = fetch(&format!("{base}/{f}"), &dir.join(f), true);
504 }
505 }
506 Ok(dir)
507}
508
509/// Download to a .part file and rename on success. Returns Ok(false) for a missing optional file.
510fn fetch(url: &str, dest: &Path, optional: bool) -> Result<bool> {
511 let name = dest.file_name().context("bad dest")?.to_string_lossy().into_owned();
512 let tmp = dest.with_file_name(format!("{name}.part"));
513 match ureq::get(url).call() {
514 Ok(resp) => {
515 let mut reader = resp.into_reader();
516 let mut f = File::create(&tmp)?;
517 std::io::copy(&mut reader, &mut f).with_context(|| format!("write {}", tmp.display()))?;
518 f.flush()?;
519 drop(f);
520 fs::rename(&tmp, dest)?;
521 Ok(true)
522 }
523 Err(ureq::Error::Status(404, _)) if optional => Ok(false),
524 Err(e) => Err(anyhow!("GET {url}: {e}")),
525 }
526}
527
528fn load_mel_filters(pc: &serde_json::Value, n_mels: usize) -> Result<Vec<f32>> {
529 // HF stores mel_filters as [n_mels][n_freq] (201 = N_FFT/2+1); candle wants the same flat layout.
530 let rows = pc["mel_filters"].as_array().context("preprocessor_config has no mel_filters")?;
531 if rows.len() != n_mels {
532 bail!("mel_filters has {} rows, expected {n_mels}", rows.len());
533 }
534 let n_freq = m::N_FFT / 2 + 1;
535 let mut out = vec![0f32; n_mels * n_freq];
536 for (mi, row) in rows.iter().enumerate() {
537 let row = row.as_array().context("mel_filters row is not an array")?;
538 for (f, v) in row.iter().take(n_freq).enumerate() {
539 out[mi * n_freq + f] = v.as_f64().unwrap_or(0.0) as f32;
540 }
541 }
542 Ok(out)
543}
544
545// ---------------------------------------------------------------- audio input
546
547/// Reads WAV (int 8..32 or float 32, any channel count and rate) and returns 16 kHz mono f32.
548/// Channels are averaged; non-16 kHz input is resampled by linear interpolation.
549fn read_wav_16k_mono(path: &Path) -> Result<Vec<f32>> {
550 let mut r = hound::WavReader::open(path).with_context(|| format!("open {}", path.display()))?;
551 let spec = r.spec();
552 let ch = spec.channels.max(1) as usize;
553 let interleaved: Vec<f32> = match spec.sample_format {
554 hound::SampleFormat::Float => r.samples::<f32>().collect::<std::result::Result<_, _>>()?,
555 hound::SampleFormat::Int if spec.bits_per_sample <= 16 => {
556 let scale = 1.0 / 32768.0;
557 r.samples::<i16>()
558 .map(|s| s.map(|v| v as f32 * scale))
559 .collect::<std::result::Result<_, _>>()?
560 }
561 hound::SampleFormat::Int => {
562 let scale = 1.0 / (1i64 << (spec.bits_per_sample - 1)) as f32;
563 r.samples::<i32>()
564 .map(|s| s.map(|v| v as f32 * scale))
565 .collect::<std::result::Result<_, _>>()?
566 }
567 };
568 let mono: Vec<f32> = interleaved
569 .chunks(ch)
570 .map(|c| c.iter().sum::<f32>() / c.len() as f32)
571 .collect();
572 let src = spec.sample_rate as f64;
573 if spec.sample_rate as usize == SR {
574 return Ok(mono);
575 }
576 eprintln!("resampling {} Hz -> {SR} Hz (linear)", spec.sample_rate);
577 let out_len = (mono.len() as f64 * SR as f64 / src).round() as usize;
578 let mut out = Vec::with_capacity(out_len);
579 for i in 0..out_len {
580 let pos = i as f64 * src / SR as f64;
581 let idx = pos.floor() as usize;
582 let frac = (pos - idx as f64) as f32;
583 let a = mono.get(idx).copied().unwrap_or(0.0);
584 let b = mono.get(idx + 1).copied().unwrap_or(a);
585 out.push(a + (b - a) * frac);
586 }
587 Ok(out)
588}
589
590// ---------------------------------------------------------------- tokenizer
591
592/// Byte-level BPE vocabulary read straight from tokenizer.json (no `tokenizers` crate).
593struct Vocab {
594 ids: HashMap<String, u32>,
595 pieces: Vec<String>,
596 byte_of: HashMap<char, u8>,
597 /// Inverse of `byte_of`: the byte-level character for each byte value.
598 char_of: Vec<char>,
599 /// BPE merge ranks: (left, right) symbol pair -> rank, lower merges first.
600 merges: HashMap<(String, String), usize>,
601}
602
603impl Vocab {
604 fn load(path: &Path) -> Result<Self> {
605 let v: serde_json::Value = serde_json::from_reader(BufReader::new(
606 File::open(path).with_context(|| format!("open {}", path.display()))?,
607 ))?;
608 let mut ids = HashMap::new();
609 for (k, id) in v["model"]["vocab"].as_object().context("tokenizer.json: no model.vocab")? {
610 ids.insert(k.clone(), id.as_u64().context("bad vocab id")? as u32);
611 }
612 for t in v["added_tokens"].as_array().context("tokenizer.json: no added_tokens")? {
613 let content = t["content"].as_str().context("bad added token")?;
614 ids.insert(content.to_string(), t["id"].as_u64().context("bad added id")? as u32);
615 }
616 let n = ids.values().max().map_or(0, |m| *m as usize + 1);
617 let mut pieces = vec![String::new(); n];
618 for (k, &id) in &ids {
619 pieces[id as usize] = k.clone();
620 }
621 // GPT-2 bytes_to_unicode, inverted.
622 let mut bs: Vec<u32> = (33..=126).chain(161..=172).chain(174..=255).collect();
623 let mut cs = bs.clone();
624 let mut extra = 0u32;
625 for b in 0..256u32 {
626 if !bs.contains(&b) {
627 bs.push(b);
628 cs.push(256 + extra);
629 extra += 1;
630 }
631 }
632 let pairs: Vec<(char, u8)> =
633 cs.iter().zip(bs.iter()).map(|(c, b)| (char::from_u32(*c).unwrap(), *b as u8)).collect();
634 let byte_of: HashMap<char, u8> = pairs.iter().copied().collect();
635 let mut char_of = vec!['?'; 256];
636 for (c, b) in &pairs {
637 char_of[*b as usize] = *c;
638 }
639 let mut merges = HashMap::new();
640 for (rank, m) in v["model"]["merges"].as_array().context("tokenizer.json: no merges")?.iter().enumerate() {
641 let (a, b) = match m {
642 serde_json::Value::String(line) => {
643 let mut it = line.splitn(2, ' ');
644 (it.next().unwrap_or("").to_string(), it.next().unwrap_or("").to_string())
645 }
646 serde_json::Value::Array(pair) if pair.len() == 2 => {
647 (pair[0].as_str().unwrap_or("").to_string(), pair[1].as_str().unwrap_or("").to_string())
648 }
649 _ => bail!("tokenizer.json: bad merge entry"),
650 };
651 merges.entry((a, b)).or_insert(rank);
652 }
653 Ok(Vocab { ids, pieces, byte_of, char_of, merges })
654 }
655
656 fn id(&self, s: &str) -> Result<u32> {
657 self.ids.get(s).copied().with_context(|| format!("token {s} not in tokenizer"))
658 }
659
660 /// Byte-level BPE encoding of plain text (no special tokens). The pre-tokenizer keeps each
661 /// word with its leading space and splits runs of letters/digits from punctuation, which
662 /// is close enough to Whisper's GPT-2 regex for a decoding hint.
663 fn encode(&self, text: &str) -> Vec<u32> {
664 let mut chunks: Vec<String> = Vec::new();
665 let mut cur = String::new();
666 let mut cur_kind = 0u8; // 1 = alphanumeric run, 2 = punctuation run
667 for c in text.chars() {
668 if c.is_whitespace() {
669 if !cur.is_empty() {
670 chunks.push(std::mem::take(&mut cur));
671 }
672 cur_kind = 0;
673 cur.push(' ');
674 continue;
675 }
676 let kind = if c.is_alphanumeric() { 1 } else { 2 };
677 if kind != cur_kind && cur_kind != 0 {
678 chunks.push(std::mem::take(&mut cur));
679 }
680 cur.push(c);
681 cur_kind = kind;
682 }
683 if !cur.is_empty() {
684 chunks.push(cur);
685 }
686 let mut out = Vec::new();
687 for chunk in chunks {
688 let mut syms: Vec<String> = chunk.bytes().map(|b| self.char_of[b as usize].to_string()).collect();
689 loop {
690 let best = (0..syms.len().saturating_sub(1))
691 .filter_map(|i| {
692 self.merges.get(&(syms[i].clone(), syms[i + 1].clone())).map(|&r| (r, i))
693 })
694 .min();
695 let Some((_, i)) = best else { break };
696 let merged = format!("{}{}", syms[i], syms[i + 1]);
697 syms[i] = merged;
698 syms.remove(i + 1);
699 }
700 out.extend(syms.iter().filter_map(|t| self.ids.get(t).copied()));
701 }
702 out
703 }
704
705 fn piece_bytes(&self, id: u32) -> Vec<u8> {
706 match self.pieces.get(id as usize) {
707 Some(p) if !p.starts_with("<|") => {
708 p.chars().filter_map(|c| self.byte_of.get(&c).copied()).collect()
709 }
710 _ => Vec::new(),
711 }
712 }
713
714 /// Text of the given tokens, special/timestamp tokens skipped.
715 fn decode(&self, ids: &[u32]) -> String {
716 let bytes: Vec<u8> = ids.iter().flat_map(|&i| self.piece_bytes(i)).collect();
717 String::from_utf8_lossy(&bytes).into_owned()
718 }
719
720 /// (code, id) for every `<|xx|>` / `<|xxx|>` language token.
721 fn lang_tokens(&self) -> Vec<(String, u32)> {
722 let mut out: Vec<(String, u32)> = self
723 .ids
724 .iter()
725 .filter_map(|(k, &id)| {
726 let inner = k.strip_prefix("<|")?.strip_suffix("|>")?;
727 let ok = (2..=3).contains(&inner.len())
728 && inner.chars().all(|c| c.is_ascii_lowercase());
729 ok.then(|| (inner.to_string(), id))
730 })
731 .collect();
732 out.sort_by_key(|(_, id)| *id);
733 out
734 }
735}
736
737struct Ids {
738 /// `<|startofprev|>`, which opens the previous-text prompt.
739 startofprev: u32,
740 sot: u32,
741 eot: u32,
742 ts0: u32,
743 transcribe: u32,
744 nt: u32,
745 /// `<|nospeech|>` in some vocabularies, `<|nocaptions|>` in the multilingual ones.
746 no_speech: u32,
747}
748
749impl Ids {
750 fn new(v: &Vocab) -> Result<Self> {
751 let no_speech = v.id("<|nospeech|>").or_else(|_| v.id("<|nocaptions|>"))?;
752 Ok(Ids {
753 startofprev: v.id("<|startofprev|>")?,
754 sot: v.id("<|startoftranscript|>")?,
755 eot: v.id("<|endoftext|>")?,
756 ts0: v.id("<|0.00|>")?,
757 transcribe: v.id("<|transcribe|>")?,
758 nt: v.id("<|notimestamps|>")?,
759 no_speech,
760 })
761 }
762}
763
764/// Tokens the decoder may not emit. `any` is cleared at every step: for an English transcript,
765/// the tokens whose bytes start a CJK, kana, Hangul, Cyrillic, Arabic or Indic character (Whisper
766/// makes these up over quiet or musical audio). `first` is cleared at the first step only: the
767/// blank tokens, so a window never opens on a space (OpenAI's `suppress_blank`).
768struct Suppress {
769 any: Vec<u32>,
770 first: Vec<u32>,
771}
772
773impl Suppress {
774 fn new(v: &Vocab, english: bool, ts0: u32) -> Self {
775 let mut any = Vec::new();
776 let mut first = Vec::new();
777 for id in 0..ts0 {
778 let b = v.piece_bytes(id);
779 if b.is_empty() {
780 continue;
781 }
782 if english && foreign_script_bytes(&b) {
783 any.push(id);
784 }
785 if blank_bytes(&b) {
786 first.push(id);
787 }
788 }
789 Suppress { any, first }
790 }
791}
792
793/// True when a token's bytes start a character outside the Latin script that English uses:
794/// lead bytes of Cyrillic, Arabic, the Indic and Thai blocks (U+0400 to U+0FFF), CJK, kana,
795/// Hangul and Yi (U+3000 to U+ABFF). Punctuation (U+2000 to U+2BFF, lead byte 0xE2) and the
796/// Latin letters with accents (0xC3) are not foreign.
797fn foreign_script_bytes(b: &[u8]) -> bool {
798 b.iter().any(|&x| matches!(x, 0xD0..=0xD3 | 0xD8..=0xDB | 0xE0 | 0xE3..=0xED))
799}
800
801/// True for a token that is only ASCII whitespace (a bare space or newline).
802fn blank_bytes(b: &[u8]) -> bool {
803 !b.is_empty() && b.iter().all(u8::is_ascii_whitespace)
804}
805
806// ---------------------------------------------------------------- decoding
807
808struct Rng(u64);
809
810impl Rng {
811 fn next_f32(&mut self) -> f32 {
812 self.0 ^= self.0 << 13;
813 self.0 ^= self.0 >> 7;
814 self.0 ^= self.0 << 17;
815 (self.0 >> 40) as f32 / (1u64 << 24) as f32
816 }
817}
818
819fn detect_language(
820 model: &mut Whisper,
821 enc: &Tensor,
822 vocab: &Vocab,
823 ids: &Ids,
824 dev: &Device,
825) -> Result<(u32, String)> {
826 let t = Tensor::new(&[ids.sot][..], dev)?.unsqueeze(0)?;
827 let ys = model.decoder.forward(&t, enc, true)?;
828 let n = ys.dim(1)?;
829 let last = ys.narrow(1, n - 1, 1)?;
830 let l: Vec<f32> = model.decoder.final_linear(&last)?.flatten_all()?.to_vec1::<f32>()?;
831 let langs = vocab.lang_tokens();
832 let (code, id) = langs
833 .iter()
834 .max_by(|a, b| l[a.1 as usize].total_cmp(&l[b.1 as usize]))
835 .context("no language tokens in vocabulary")?;
836 Ok((*id, code.clone()))
837}
838
839/// Greedy (temp 0) or sampled decoding of one 30 s window with timestamp tokens enabled.
840/// Returns generated (token, logprob) pairs, excluding the prompt and the final EOT, and the
841/// window's no-speech probability: softmax over the full vocabulary at the start-of-transcript
842/// position of the first decode step, before any suppression (as OpenAI whisper computes it).
843/// What one decode window hands back: its tokens with their log-probs, the average
844/// log-prob, and whether it stopped on the end-of-text token.
845type DecodeWindow = (Vec<(u32, f32)>, f64, bool);
846
847#[allow(clippy::too_many_arguments)]
848fn decode_window(
849 model: &mut Whisper,
850 enc: &Tensor,
851 prompt: &[u32],
852 temp: f64,
853 ids: &Ids,
854 cfg: &Config,
855 sup: &Suppress,
856 rng: &mut Rng,
857 dev: &Device,
858) -> Result<DecodeWindow> {
859 const NEG: f32 = f32::NEG_INFINITY;
860 let ts0 = ids.ts0 as usize;
861 let eot = ids.eot as usize;
862 let mut seq: Vec<u32> = prompt.to_vec();
863 let mut out: Vec<(u32, f32)> = Vec::new();
864 let max_new = cfg.max_target_positions.saturating_sub(prompt.len() + 1);
865 let mut run = 0usize;
866 let mut no_speech = 0.0f64;
867 let mut looped = false;
868
869 for step in 0..max_new {
870 // The decoder keeps the keys and values of the tokens so far: after the prompt, a step
871 // feeds only the newest token.
872 let feed: &[u32] = if step == 0 { seq.as_slice() } else { &seq[seq.len() - 1..] };
873 let t = Tensor::new(feed, dev)?.unsqueeze(0)?;
874 let ys = model.decoder.forward(&t, enc, step == 0)?;
875 let n = ys.dim(1)?;
876 let last = ys.narrow(1, n - 1, 1)?;
877 let mut l: Vec<f32> = model.decoder.final_linear(&last)?.flatten_all()?.to_vec1::<f32>()?;
878 if step == 0 {
879 let sot_row = ys.narrow(1, 0, 1)?;
880 let raw: Vec<f32> = model.decoder.final_linear(&sot_row)?.flatten_all()?.to_vec1::<f32>()?;
881 no_speech = softmax_prob(&raw, ids.no_speech as usize);
882 }
883
884 for &s in cfg.suppress_tokens.iter().chain(&sup.any) {
885 if let Some(v) = l.get_mut(s as usize) {
886 *v = NEG;
887 }
888 }
889 if step == 0 {
890 l[eot] = NEG;
891 for &s in &sup.first {
892 l[s as usize] = NEG;
893 }
894 }
895 // No special/language/task tokens after the prompt, only text, EOT and timestamps.
896 for v in &mut l[(eot + 1)..ts0] {
897 *v = NEG;
898 }
899 // Timestamp grammar: pairs of timestamps must be followed by text; a lone
900 // timestamp must be followed by a timestamp or EOT.
901 let last_is_ts = out.last().is_some_and(|t| t.0 >= ids.ts0);
902 // Like Whisper: a lone leading timestamp counts as "penultimate was timestamp".
903 let pen_is_ts = out.len() < 2 || out[out.len() - 2].0 >= ids.ts0;
904 if last_is_ts {
905 if pen_is_ts {
906 for v in &mut l[ts0..] {
907 *v = NEG;
908 }
909 } else {
910 for v in &mut l[..eot] {
911 *v = NEG;
912 }
913 }
914 }
915 // Timestamps never go backwards.
916 if let Some(lt) = out.iter().rev().find(|t| t.0 >= ids.ts0).map(|t| t.0 as usize) {
917 for v in &mut l[ts0..lt] {
918 *v = NEG;
919 }
920 }
921 // First timestamp at most 1.0 s into the window.
922 if out.is_empty() {
923 let len = l.len();
924 for v in &mut l[(ts0 + 51).min(len)..] {
925 *v = NEG;
926 }
927 }
928
929 let mx = l.iter().copied().filter(|v| v.is_finite()).fold(NEG, f32::max);
930 let z: f32 = l.iter().filter(|v| v.is_finite()).map(|v| (v - mx).exp()).sum();
931 let lse = mx + z.ln();
932 let next: usize = if temp <= 0.0 {
933 l.iter()
934 .enumerate()
935 .filter(|(_, v)| v.is_finite())
936 .max_by(|a, b| a.1.total_cmp(b.1))
937 .map(|(i, _)| i)
938 .context("no finite logits")?
939 } else {
940 let probs: Vec<f32> = l.iter().map(|v| ((v - mx) / temp as f32).exp()).collect();
941 let total: f32 = probs.iter().sum();
942 let mut r = rng.next_f32() * total;
943 let mut pick = probs.len() - 1;
944 for (i, p) in probs.iter().enumerate() {
945 r -= p;
946 if r <= 0.0 {
947 pick = i;
948 break;
949 }
950 }
951 pick
952 };
953 if next == eot {
954 break;
955 }
956 let lp = l[next] - lse;
957 out.push((next as u32, lp));
958 seq.push(next as u32);
959
960 run = if out.len() >= 2 && out[out.len() - 2].0 == next as u32 { run + 1 } else { 1 };
961 if run >= MAX_REPEAT {
962 eprintln!("repetition guard: token {next} repeated {MAX_REPEAT}x, ending window");
963 break;
964 }
965 if let Some(p) = text_loop_period(&out, ids.ts0) {
966 eprintln!("repetition guard: a {p}-token phrase repeated {LOOP_REPEATS}x, ending window");
967 cut_loop(&mut out, ids.ts0, p);
968 looped = true;
969 break;
970 }
971 }
972 Ok((out, no_speech, looped))
973}
974
975/// True when the window's output must be decoded again at the next temperature: its text
976/// compresses too well (a repetition), its tokens are too unsure, or a loop cut left no text.
977fn window_rejected(ratio: f64, avg_logprob: f64, looped_without_text: bool) -> bool {
978 ratio > MAX_COMPRESSION_RATIO || avg_logprob < MIN_AVG_LOGPROB || looped_without_text
979}
980
981/// Whether any text token (not a timestamp) is in `toks`.
982fn has_text(toks: &[(u32, f32)], ts0: u32) -> bool {
983 toks.iter().any(|t| t.0 < ts0)
984}
985
986/// Frames to seek past a decoded window (10 ms frames). Standard long-form seek: jump to the last
987/// timestamp when the window ended on one, else consume the whole window. A looped window whose
988/// timestamps stop at the start (none after `0.00`) advances only `LOOP_STEP_S`, so the audio after
989/// the loop is decoded instead of skipped.
990fn seek_advance_frames(ends_with_ts: bool, last_ts_s: Option<f64>, looped: bool, content_frames: usize) -> usize {
991 let to_last_ts = match (ends_with_ts, last_ts_s) {
992 (true, Some(t)) if t > 0.0 => Some(((t * 100.0).round() as usize).min(content_frames)),
993 _ => None,
994 };
995 match (to_last_ts, looped) {
996 (Some(f), _) => f,
997 (None, true) => ((LOOP_STEP_S * 100.0).round() as usize).min(content_frames),
998 (None, false) => content_frames,
999 }
1000}
1001
1002/// The period of a phrase that the text tokens of `out` end with, repeated `LOOP_REPEATS` times
1003/// in a row (timestamps are skipped, so a loop whose copies get new times is still one).
1004fn text_loop_period(out: &[(u32, f32)], ts0: u32) -> Option<usize> {
1005 let text: Vec<u32> = out.iter().filter(|t| t.0 < ts0).map(|t| t.0).collect();
1006 for p in 2..=LOOP_MAX_PERIOD {
1007 let n = LOOP_REPEATS * p;
1008 if text.len() < n {
1009 break;
1010 }
1011 let tail = &text[text.len() - n..];
1012 if (1..LOOP_REPEATS).all(|r| tail[r * p..(r + 1) * p] == tail[..p]) {
1013 return Some(p);
1014 }
1015 }
1016 None
1017}
1018
1019/// Drops the repeats of a loop of period `p` from the end of `out` and ends the window on the last
1020/// timestamp at or before the loop, so the next window resumes there and the audio after the loop
1021/// is not skipped. The first copy is kept only when a timestamp follows it. With no timestamp
1022/// before the loop, the window's text is gone: the caller retries it, then steps forward briefly.
1023fn cut_loop(out: &mut Vec<(u32, f32)>, ts0: u32, p: usize) {
1024 let text_at: Vec<usize> = out.iter().enumerate().filter(|(_, t)| t.0 < ts0).map(|(i, _)| i).collect();
1025 let first_repeat = text_at[text_at.len() - (LOOP_REPEATS - 1) * p];
1026 out.truncate(first_repeat);
1027 if let Some(i) = out.iter().rposition(|t| t.0 >= ts0) {
1028 out.truncate(i + 1);
1029 }
1030}
1031
1032/// Probability of `idx` under a softmax over `logits`. Returns 0 for an out-of-range index.
1033fn softmax_prob(logits: &[f32], idx: usize) -> f64 {
1034 let Some(&target) = logits.get(idx) else { return 0.0 };
1035 let mx = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max) as f64;
1036 let z: f64 = logits.iter().map(|&v| (v as f64 - mx).exp()).sum();
1037 (target as f64 - mx).exp() / z
1038}
1039
1040fn compression_ratio(text: &str) -> Result<f64> {
1041 use flate2::{write::ZlibEncoder, Compression};
1042 if text.is_empty() {
1043 return Ok(0.0);
1044 }
1045 let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
1046 enc.write_all(text.as_bytes())?;
1047 let packed = enc.finish()?;
1048 Ok(text.len() as f64 / packed.len() as f64)
1049}
1050
1051fn avg_logprob(toks: &[(u32, f32)]) -> f64 {
1052 if toks.is_empty() {
1053 return 0.0;
1054 }
1055 toks.iter().map(|t| t.1 as f64).sum::<f64>() / toks.len() as f64
1056}
1057
1058struct Seg {
1059 /// Seconds from the window start.
1060 start: f64,
1061 end: f64,
1062 toks: Vec<(u32, f32)>,
1063}
1064
1065/// Splits a window's tokens into segments on timestamp tokens. A segment is the text
1066/// between two timestamps; text left after the last timestamp ends at `content_s`.
1067fn split_segments(toks: &[(u32, f32)], ts0: u32, content_s: f64) -> Vec<Seg> {
1068 let mut segs = Vec::new();
1069 let mut start: Option<f64> = None;
1070 let mut buf: Vec<(u32, f32)> = Vec::new();
1071 for &(id, lp) in toks {
1072 if id >= ts0 {
1073 let t = (id - ts0) as f64 * SEC_PER_TS;
1074 match start {
1075 None => {
1076 if !buf.is_empty() {
1077 segs.push(Seg { start: 0.0, end: t, toks: std::mem::take(&mut buf) });
1078 }
1079 start = Some(t);
1080 }
1081 Some(s) => {
1082 if !buf.is_empty() {
1083 segs.push(Seg { start: s, end: t, toks: std::mem::take(&mut buf) });
1084 }
1085 start = Some(t);
1086 }
1087 }
1088 } else {
1089 buf.push((id, lp));
1090 }
1091 }
1092 if !buf.is_empty() {
1093 let s = start.unwrap_or(0.0);
1094 segs.push(Seg { start: s, end: content_s.max(s), toks: buf });
1095 }
1096 segs
1097}
1098
1099/// Word timing approximation: the segment span divided across its words in proportion to
1100/// character count. Word probability is the geometric mean of its token probabilities.
1101fn word_times(vocab: &Vocab, toks: &[(u32, f32)], start: f64, end: f64) -> Vec<serde_json::Value> {
1102 // Group tokens into words: a token whose bytes start with a space opens a new word.
1103 let mut words: Vec<(Vec<u8>, Vec<f32>)> = Vec::new();
1104 for &(id, lp) in toks {
1105 let b = vocab.piece_bytes(id);
1106 if b.is_empty() {
1107 continue;
1108 }
1109 if b[0] == b' ' && words.last().is_some_and(|w| !w.0.is_empty()) {
1110 words.push((Vec::new(), Vec::new()));
1111 }
1112 if words.is_empty() {
1113 words.push((Vec::new(), Vec::new()));
1114 }
1115 let w = words.last_mut().unwrap();
1116 w.0.extend_from_slice(&b);
1117 w.1.push(lp);
1118 }
1119 let named: Vec<(String, f64)> = words
1120 .iter()
1121 .map(|(b, lps)| {
1122 let w = String::from_utf8_lossy(b).trim().to_string();
1123 let p = if lps.is_empty() {
1124 0.0
1125 } else {
1126 (lps.iter().map(|&x| x as f64).sum::<f64>() / lps.len() as f64).exp()
1127 };
1128 (w, p)
1129 })
1130 .filter(|(w, _)| !w.is_empty())
1131 .collect();
1132 let total_chars: usize = named.iter().map(|(w, _)| w.chars().count()).sum();
1133 let span = (end - start).max(0.0);
1134 let mut t = start;
1135 named
1136 .iter()
1137 .map(|(w, p)| {
1138 let chars = w.chars().count();
1139 let dur = if total_chars > 0 { span * chars as f64 / total_chars as f64 } else { 0.0 };
1140 let (ws, we) = (t, t + dur);
1141 t = we;
1142 serde_json::json!({"w": w, "start": r3(ws), "end": r3(we), "p": r3(*p)})
1143 })
1144 .collect()
1145}
1146
1147// ---------------------------------------------------------------- word alignment
1148
1149/// Audio (encoder) frame duration: 20 ms, twice the mel hop.
1150const ENC_SPF: f64 = 0.02;
1151/// Median filter width over audio frames (whisper's `medfilt_width`).
1152const MEDFILT: usize = 7;
1153
1154/// Heads whose cross-attention is used for alignment: `generation_config.json`'s
1155/// `alignment_heads`, or every head of the last half of the decoder layers when absent.
1156fn alignment_heads(dir: &Path, cfg: &Config) -> Result<Vec<(usize, usize)>> {
1157 let p = dir.join("generation_config.json");
1158 if p.exists() {
1159 let v: serde_json::Value = serde_json::from_reader(BufReader::new(File::open(&p)?))?;
1160 if let Some(arr) = v["alignment_heads"].as_array() {
1161 let mut out = Vec::with_capacity(arr.len());
1162 for h in arr {
1163 let l = h[0].as_u64().context("alignment_heads: bad layer")? as usize;
1164 let hd = h[1].as_u64().context("alignment_heads: bad head")? as usize;
1165 out.push((l, hd));
1166 }
1167 if !out.is_empty() {
1168 return Ok(out);
1169 }
1170 }
1171 }
1172 let first = cfg.decoder_layers / 2;
1173 Ok((first..cfg.decoder_layers)
1174 .flat_map(|l| (0..cfg.decoder_attention_heads).map(move |h| (l, h)))
1175 .collect())
1176}
1177
1178#[derive(Default)]
1179struct WordG {
1180 text: Vec<u8>,
1181 /// Indices into the segment's token list.
1182 toks: Vec<usize>,
1183 lps: Vec<f32>,
1184}
1185
1186fn is_punct_piece(s: &str) -> bool {
1187 let t = s.trim();
1188 let mut cs = t.chars();
1189 matches!((cs.next(), cs.next()), (Some(c), None) if c.is_ascii_punctuation())
1190}
1191
1192fn is_sentence_end(text: &[u8]) -> bool {
1193 let t = String::from_utf8_lossy(text);
1194 let t = t.trim();
1195 t.chars().count() == 1 && ".。!!??".contains(t)
1196}
1197
1198/// Whisper's `split_tokens_on_spaces` + `merge_punctuations`: a word opens at a token that
1199/// starts with a space or is a lone punctuation mark; prepend-punctuation joins the following
1200/// word and append-punctuation joins the previous one.
1201fn group_words(vocab: &Vocab, toks: &[(u32, f32)]) -> Vec<WordG> {
1202 const PREPEND: &str = "\"'“¿([{-";
1203 const APPEND: &str = "\"'.。,,!!??::”)]}、";
1204 let mut words: Vec<WordG> = Vec::new();
1205 for (i, &(id, lp)) in toks.iter().enumerate() {
1206 let b = vocab.piece_bytes(id);
1207 let opens = match b.first() {
1208 Some(&c) => c == b' ' || is_punct_piece(&String::from_utf8_lossy(&b)),
1209 None => false,
1210 };
1211 if words.is_empty() || opens {
1212 words.push(WordG::default());
1213 }
1214 let w = words.last_mut().unwrap();
1215 w.text.extend_from_slice(&b);
1216 w.toks.push(i);
1217 w.lps.push(lp);
1218 }
1219 let n = words.len();
1220 // Prepended punctuation: merge into the following word (walking backwards).
1221 if n >= 2 {
1222 let mut j = n - 1;
1223 for i in (0..n - 1).rev() {
1224 let prev = String::from_utf8_lossy(&words[i].text).into_owned();
1225 if prev.starts_with(' ') && !prev.trim().is_empty() && PREPEND.contains(prev.trim()) {
1226 let moved = std::mem::take(&mut words[i]);
1227 let f = &mut words[j];
1228 let mut t = moved.text;
1229 t.extend_from_slice(&f.text);
1230 f.text = t;
1231 let mut tk = moved.toks;
1232 tk.extend_from_slice(&f.toks);
1233 f.toks = tk;
1234 let mut lp = moved.lps;
1235 lp.extend_from_slice(&f.lps);
1236 f.lps = lp;
1237 } else {
1238 j = i;
1239 }
1240 }
1241 }
1242 // Appended punctuation: merge into the previous word (walking forwards).
1243 let mut i = 0usize;
1244 for j in 1..words.len() {
1245 let foll = String::from_utf8_lossy(&words[j].text).into_owned();
1246 let prev_ends_space = words[i].text.last() == Some(&b' ');
1247 if !words[j].text.is_empty() && !prev_ends_space && APPEND.contains(foll.as_str()) {
1248 let moved = std::mem::take(&mut words[j]);
1249 let p = &mut words[i];
1250 p.text.extend_from_slice(&moved.text);
1251 p.toks.extend_from_slice(&moved.toks);
1252 p.lps.extend_from_slice(&moved.lps);
1253 } else {
1254 i = j;
1255 }
1256 }
1257 words.retain(|w| !w.text.is_empty());
1258 words
1259}
1260
1261/// Whisper's `dtw` (cost matrix rows x cols, row-major). Returns the monotone path as
1262/// parallel (row, col) index lists from (0,0) to (rows-1, cols-1).
1263fn dtw_path(cost: &[f32], rows: usize, cols: usize) -> (Vec<usize>, Vec<usize>) {
1264 let w = cols + 1;
1265 let mut c = vec![f64::INFINITY; (rows + 1) * w];
1266 let mut tr = vec![0u8; (rows + 1) * w];
1267 c[0] = 0.0;
1268 for j in 1..=cols {
1269 for i in 1..=rows {
1270 let c0 = c[(i - 1) * w + j - 1];
1271 let c1 = c[(i - 1) * w + j];
1272 let c2 = c[i * w + j - 1];
1273 let (best, t) = if c0 < c1 && c0 < c2 {
1274 (c0, 0u8)
1275 } else if c1 < c0 && c1 < c2 {
1276 (c1, 1)
1277 } else {
1278 (c2, 2)
1279 };
1280 c[i * w + j] = cost[(i - 1) * cols + (j - 1)] as f64 + best;
1281 tr[i * w + j] = t;
1282 }
1283 }
1284 tr[..=cols].fill(2);
1285 for i in 0..=rows {
1286 tr[i * w] = 1;
1287 }
1288 let (mut i, mut j) = (rows, cols);
1289 let mut path = Vec::with_capacity(rows + cols);
1290 while i > 0 || j > 0 {
1291 path.push((i - 1, j - 1));
1292 match tr[i * w + j] {
1293 0 => {
1294 i -= 1;
1295 j -= 1;
1296 }
1297 1 => i -= 1,
1298 _ => j -= 1,
1299 }
1300 }
1301 path.reverse();
1302 path.into_iter().unzip()
1303}
1304
1305/// Median over a reflect-padded window (whisper's `median_filter`).
1306fn median_filter(x: &[f32], width: usize) -> Vec<f32> {
1307 let n = x.len();
1308 let pad = (width / 2) as isize;
1309 let refl = |i: isize| -> usize {
1310 if n == 1 {
1311 return 0;
1312 }
1313 let period = 2 * (n as isize - 1);
1314 let mut j = i.rem_euclid(period);
1315 if j >= n as isize {
1316 j = period - j;
1317 }
1318 j as usize
1319 };
1320 (0..n)
1321 .map(|i| {
1322 let mut win: Vec<f32> = (0..width)
1323 .map(|k| x[refl(i as isize + k as isize - pad)])
1324 .collect();
1325 win.sort_by(f32::total_cmp);
1326 win[width / 2]
1327 })
1328 .collect()
1329}
1330
1331fn median_f64(v: &mut [f64]) -> f64 {
1332 v.sort_by(f64::total_cmp);
1333 let n = v.len();
1334 if n % 2 == 1 {
1335 v[n / 2]
1336 } else {
1337 (v[n / 2 - 1] + v[n / 2]) / 2.0
1338 }
1339}
1340
1341/// Speech band edges in Hz: narration energy lives here, room tone and most beds sit below.
1342const BAND_LO_HZ: f64 = 300.0;
1343const BAND_HI_HZ: f64 = 3400.0;
1344/// A frame is speech when its band energy is this far above the rolling noise floor.
1345const SPEECH_MARGIN_DB: f64 = 10.0;
1346/// A segment span is silent when its band energy is less than this above the noise floor.
1347const SILENT_REL_DB: f64 = 6.0;
1348/// The noise floor is the mean of the quietest `FLOOR_SHARE` of the frames within
1349/// `FLOOR_HALF_FRAMES` either side of a frame (a 3 s rolling window).
1350const FLOOR_SHARE: f64 = 0.10;
1351const FLOOR_HALF_FRAMES: usize = 75;
1352/// Attention context added to a segment before and after it for DTW, in seconds. The left margin
1353/// is zero: the DTW start is pinned to the crop's first frame, and a margin there reaches into the
1354/// previous segment's words. The crop is then trimmed to the speech it holds.
1355const ALIGN_PAD_LEFT_S: f64 = 0.0;
1356const ALIGN_PAD_RIGHT_S: f64 = 0.5;
1357/// Samples per 20 ms audio frame.
1358const ENC_HOP: usize = 320;
1359/// Segments and words starting this close to the audio end, or later, are dropped.
1360const END_GUARD_S: f64 = 0.1;
1361
1362/// Second-order section (RBJ cookbook), direct form I.
1363#[derive(Clone, Copy)]
1364struct Biquad {
1365 b: [f64; 3],
1366 a: [f64; 2],
1367}
1368
1369impl Biquad {
1370 fn new(fc: f64, q: f64, high: bool) -> Self {
1371 let w = 2.0 * std::f64::consts::PI * fc / SR as f64;
1372 let (s, c) = (w.sin(), w.cos());
1373 let alpha = s / (2.0 * q);
1374 let a0 = 1.0 + alpha;
1375 let b = if high {
1376 [(1.0 + c) / 2.0, -(1.0 + c), (1.0 + c) / 2.0]
1377 } else {
1378 [(1.0 - c) / 2.0, 1.0 - c, (1.0 - c) / 2.0]
1379 };
1380 Biquad { b: [b[0] / a0, b[1] / a0, b[2] / a0], a: [-2.0 * c / a0, (1.0 - alpha) / a0] }
1381 }
1382
1383 fn apply(&self, x: &mut [f64]) {
1384 let (mut x1, mut x2, mut y1, mut y2) = (0.0, 0.0, 0.0, 0.0);
1385 for v in x.iter_mut() {
1386 let y = self.b[0] * *v + self.b[1] * x1 + self.b[2] * x2 - self.a[0] * y1 - self.a[1] * y2;
1387 x2 = x1;
1388 x1 = *v;
1389 y2 = y1;
1390 y1 = y;
1391 *v = y;
1392 }
1393 }
1394}
1395
1396/// The window's samples band-limited to the speech band: a 4th-order Butterworth band run
1397/// forward and then backward, so the band has no filter delay.
1398fn speech_band(pcm: &[f32]) -> Vec<f64> {
1399 const Q: [f64; 2] = [0.5412, 1.3066];
1400 let sections: Vec<Biquad> = Q
1401 .iter()
1402 .map(|&q| Biquad::new(BAND_LO_HZ, q, true))
1403 .chain(Q.iter().map(|&q| Biquad::new(BAND_HI_HZ, q, false)))
1404 .collect();
1405 let mut y: Vec<f64> = pcm.iter().map(|&v| v as f64).collect();
1406 for _ in 0..2 {
1407 for bq in &sections {
1408 bq.apply(&mut y);
1409 }
1410 y.reverse();
1411 }
1412 y
1413}
1414
1415/// Band-limited level of each 20 ms frame of a window, and its rolling noise floor. Both in dB.
1416struct Levels {
1417 db: Vec<f64>,
1418 floor: Vec<f64>,
1419}
1420
1421fn levels(pcm: &[f32]) -> Levels {
1422 let y = speech_band(pcm);
1423 let db: Vec<f64> = y.chunks(ENC_HOP).map(power_db).collect();
1424 let floor = (0..db.len())
1425 .map(|j| {
1426 let a = j.saturating_sub(FLOOR_HALF_FRAMES);
1427 let b = (j + FLOOR_HALF_FRAMES + 1).min(db.len());
1428 quiet_floor_db(&db[a..b])
1429 })
1430 .collect();
1431 Levels { db, floor }
1432}
1433
1434/// Mean power of a block of samples in dB (full scale = 1.0).
1435fn power_db(c: &[f64]) -> f64 {
1436 let ms = c.iter().map(|x| x * x).sum::<f64>() / c.len().max(1) as f64;
1437 10.0 * (ms + 1e-12).log10()
1438}
1439
1440/// Noise floor of a stretch of frame levels: the mean of its quietest `FLOOR_SHARE`, in dB.
1441fn quiet_floor_db(levels_db: &[f64]) -> f64 {
1442 if levels_db.is_empty() {
1443 return -120.0;
1444 }
1445 let mut s = levels_db.to_vec();
1446 s.sort_by(f64::total_cmp);
1447 let k = ((s.len() as f64 * FLOOR_SHARE).ceil() as usize).clamp(1, s.len());
1448 s[..k].iter().sum::<f64>() / k as f64
1449}
1450
1451/// One flag per 20 ms frame of a window: true when the frame is speech-band louder than the
1452/// rolling noise floor by `SPEECH_MARGIN_DB`. A bed that is quiet in the speech band never counts.
1453fn speech_frames(lv: &Levels) -> Vec<bool> {
1454 lv.db.iter().zip(&lv.floor).map(|(d, f)| d - f > SPEECH_MARGIN_DB).collect()
1455}
1456
1457/// Level of a span in dB above the noise floor (mean power over the span against the mean floor
1458/// over the same frames), or None when the span holds no frames. Span times are window-relative.
1459fn span_rel_db(lv: &Levels, start_s: f64, end_s: f64) -> Option<f64> {
1460 let a = ((start_s.max(0.0) / ENC_SPF).floor() as usize).min(lv.db.len());
1461 let b = ((end_s.max(0.0) / ENC_SPF).ceil() as usize).min(lv.db.len());
1462 if b <= a {
1463 return None;
1464 }
1465 let n = (b - a) as f64;
1466 let mean_power = lv.db[a..b].iter().map(|d| 10f64.powf(d / 10.0)).sum::<f64>() / n;
1467 let floor = lv.floor[a..b].iter().sum::<f64>() / n;
1468 Some(10.0 * mean_power.max(1e-30).log10() - floor)
1469}
1470
1471/// Segment-level hallucination gate, after OpenAI whisper's no-speech rule plus an energy gate.
1472/// Returns the reason to drop the segment, or None to keep it.
1473/// - `no_speech > 0.6` and `avg_logprob < -1.0`: the model says silence and is not confident.
1474/// - the segment's span is not `SILENT_REL_DB` above the noise floor: nothing audible to transcribe.
1475fn silence_reason(no_speech: f64, avg_logprob: f64, span_rel: Option<f64>) -> Option<&'static str> {
1476 if no_speech > NO_SPEECH_PROB && avg_logprob < NO_SPEECH_LOGPROB {
1477 return Some("no_speech");
1478 }
1479 if span_rel.is_some_and(|d| d < SILENT_REL_DB) {
1480 return Some("silent_span");
1481 }
1482 None
1483}
1484
1485/// True when a time (seconds in the audio file, no CLI offset) is at or past the audio end.
1486fn starts_past_end(t: f64, audio_s: f64) -> bool {
1487 t >= audio_s - END_GUARD_S
1488}
1489
1490/// Cuts the words of a segment that start at or past the audio end (`starts_past_end`), keeping
1491/// the rest, and clamps the ends of the kept words to the audio end. `offset` is the CLI offset
1492/// the word times carry. Returns how many words were cut.
1493fn fit_words_to_audio(words: &mut Vec<serde_json::Value>, offset: f64, audio_s: f64) -> usize {
1494 let before = words.len();
1495 words.retain(|w| w["start"].as_f64().is_none_or(|s| !starts_past_end(s - offset, audio_s)));
1496 let audio_end_abs = audio_s + offset;
1497 for w in words.iter_mut() {
1498 if w["end"].as_f64().is_some_and(|e| e > audio_end_abs) {
1499 w["end"] = serde_json::json!(r3(audio_end_abs));
1500 }
1501 }
1502 before - words.len()
1503}
1504
1505/// The 20 ms frames `[f0, f1)` of a window that a segment's DTW may use: the segment's span plus
1506/// `left_s` before and `right_s` after, clamped to the `n` frames of real audio. Always at least one frame.
1507fn crop_frames(start_s: f64, end_s: f64, n: usize, left_s: f64, right_s: f64) -> (usize, usize) {
1508 let n = n.max(1);
1509 let f0 = ((((start_s - left_s).max(0.0)) / ENC_SPF).floor() as usize).min(n - 1);
1510 let f1 = (((end_s + right_s) / ENC_SPF).ceil() as usize).clamp(f0 + 1, n);
1511 (f0, f1)
1512}
1513
1514/// Trims a crop to the first and last speech frame inside it, so DTW is pinned to speech rather
1515/// than to the silence the crop margin adds. A crop with no speech is returned unchanged.
1516fn trim_crop_to_speech(crop: (usize, usize), speech: &[bool]) -> (usize, usize) {
1517 let (f0, f1) = crop;
1518 let inside: Vec<usize> = (f0..f1.min(speech.len())).filter(|&j| speech[j]).collect();
1519 match (inside.first(), inside.last()) {
1520 (Some(&a), Some(&b)) => (a, b + 1),
1521 _ => crop,
1522 }
1523}
1524
1525/// DTW pins the first token row to the crop's first frame, and a row whose attention sits at that
1526/// frame can tie with its neighbour, which makes a word of zero length. Each run of tied starts
1527/// is spread evenly between its left anchor (the start before it, or the pinned first start) and
1528/// the next start (or `end_s` for a run at the end). The first entry of a run at index 0 is kept.
1529fn spread_tied_starts(starts: &mut [f64], end_s: f64) {
1530 let n = starts.len();
1531 let mut i = 0;
1532 while i < n {
1533 let mut j = i;
1534 while j + 1 < n && starts[j + 1] <= starts[i] + 1e-9 {
1535 j += 1;
1536 }
1537 if j > i {
1538 let m = j - i + 1;
1539 let v = starts[i];
1540 if i == 0 {
1541 let right = if j + 1 < n { starts[j + 1] } else { end_s.max(v) };
1542 for (k, s) in starts[1..=j].iter_mut().enumerate() {
1543 *s = v + (right - v) * (k + 1) as f64 / m as f64;
1544 }
1545 } else {
1546 let left = starts[i - 1];
1547 let right = if j + 1 < n { starts[j + 1] } else { end_s.max(v) };
1548 for (k, s) in starts[i..=j].iter_mut().enumerate() {
1549 *s = left + (right - left) * (k + 1) as f64 / (m + 1) as f64;
1550 }
1551 }
1552 }
1553 i = j + 1;
1554 }
1555}
1556
1557/// Z-scores each column of `m` over its rows, as OpenAI whisper does over the token axis.
1558fn zscore_columns(m: &mut [Vec<f32>]) {
1559 let rows = m.len();
1560 if rows == 0 {
1561 return;
1562 }
1563 for f in 0..m[0].len() {
1564 let mean = m.iter().map(|r| r[f] as f64).sum::<f64>() / rows as f64;
1565 let var = m.iter().map(|r| (r[f] as f64 - mean).powi(2)).sum::<f64>() / rows as f64;
1566 let sd = var.sqrt().max(1e-12);
1567 for r in m.iter_mut() {
1568 r[f] = ((r[f] as f64 - mean) / sd) as f32;
1569 }
1570 }
1571}
1572
1573/// Word timestamps for one segment, following OpenAI whisper's `find_alignment` and
1574/// `add_word_timestamps`. One teacher-forced decoder pass over
1575/// [prompt, <|notimestamps|>, text, <|endoftext|>] gives the cross-attention of the alignment
1576/// heads. DTW runs over the crop `crop = [f0, f1)` of the window (the segment plus a margin),
1577/// not the whole window: the path is pinned to the crop's first and last frame, so a DTW over
1578/// the whole window stretches a later segment's words across the audio before it and they
1579/// collapse. `n_content` is the number of 20 ms frames of real audio in the window, `base` the
1580/// absolute time of the window start (with the CLI offset). Returned times are absolute.
1581#[allow(clippy::too_many_arguments)]
1582fn aligned_words(
1583 model: &mut Whisper,
1584 enc: &Tensor,
1585 prompt: &[u32],
1586 toks: &[(u32, f32)],
1587 vocab: &Vocab,
1588 ids: &Ids,
1589 heads: &[(usize, usize)],
1590 crop: (usize, usize),
1591 n_content: usize,
1592 base: f64,
1593 speech: &[bool],
1594 dev: &Device,
1595) -> Result<Vec<serde_json::Value>> {
1596 let n = toks.len();
1597 let (f0, f1) = crop;
1598 if n == 0 || heads.is_empty() || f0 >= f1 || f1 > n_content {
1599 bail!("nothing to align");
1600 }
1601 let width = f1 - f0;
1602 let mut seq: Vec<u32> = prompt.to_vec();
1603 seq.push(ids.nt);
1604 seq.extend(toks.iter().map(|t| t.0));
1605 seq.push(ids.eot);
1606 let (p, l) = (prompt.len(), seq.len());
1607 let t = Tensor::new(seq.as_slice(), dev)?.unsqueeze(0)?;
1608 let (_, caps) = model.decoder.forward_with_cross_attn(&t, enc, true)?;
1609
1610 // Rows [p, l-1): the <|notimestamps|> row, then one per text token. Row j is the start of
1611 // token j and row n the end of the segment. Each head's weights are softmaxed over the
1612 // window's real frames, cropped to [f0, f1), z-scored over the rows and median-filtered over
1613 // time; the heads are then averaged.
1614 let rows = l - 1 - p;
1615 let mut acc = vec![0f32; rows * width];
1616 for &(layer, head) in heads {
1617 let c = caps.get(layer).context("alignment head: layer out of range")?;
1618 let (_, nh, _, nf) = c.dims4()?;
1619 if head >= nh || n_content > nf {
1620 bail!("alignment head ({layer},{head}) out of range");
1621 }
1622 let full: Vec<Vec<f32>> = c.i((0, head, p..l - 1, ..n_content))?.to_vec2::<f32>()?;
1623 let mut m: Vec<Vec<f32>> = full
1624 .iter()
1625 .map(|row| {
1626 let s = row.iter().sum::<f32>().max(1e-12);
1627 row[f0..f1].iter().map(|v| v / s).collect()
1628 })
1629 .collect();
1630 zscore_columns(&mut m);
1631 for (r, row) in m.iter().enumerate() {
1632 let med = median_filter(row, MEDFILT);
1633 for f in 0..width {
1634 acc[r * width + f] += med[f] / heads.len() as f32;
1635 }
1636 }
1637 }
1638
1639 let cost: Vec<f32> = acc.iter().map(|v| -v).collect();
1640 let (ti, tj) = dtw_path(&cost, rows, width);
1641 let mut first: Vec<Option<usize>> = vec![None; rows];
1642 for (&r, &f) in ti.iter().zip(tj.iter()) {
1643 if first[r].is_none() {
1644 first[r] = Some(f);
1645 }
1646 }
1647 // Seconds from the window start: crop column j is window frame f0 + j.
1648 let mut starts: Vec<f64> = first
1649 .iter()
1650 .map(|f| f.map(|f| (f0 + f) as f64 * ENC_SPF))
1651 .collect::<Option<Vec<f64>>>()
1652 .context("DTW path skipped a token")?;
1653 spread_tied_starts(&mut starts, f1 as f64 * ENC_SPF);
1654
1655 let words = group_words(vocab, toks);
1656 let k = words.len();
1657 if k == 0 {
1658 bail!("no words in segment");
1659 }
1660 let mut ws: Vec<f64> = words.iter().map(|w| starts[w.toks[0]]).collect();
1661 let mut we: Vec<f64> = (0..k)
1662 .map(|i| if i + 1 < k { starts[words[i + 1].toks[0]] } else { starts[n] })
1663 .collect();
1664
1665 // Whisper's long-word heuristic: cap at 2x the median word duration (median capped at 0.7 s).
1666 let mut durs: Vec<f64> = (0..k).map(|i| we[i] - ws[i]).filter(|d| *d > 0.0).collect();
1667 if !durs.is_empty() {
1668 let max_d = median_f64(&mut durs).min(0.7) * 2.0;
1669 for i in 1..k {
1670 if we[i] - ws[i] > max_d {
1671 if is_sentence_end(&words[i].text) {
1672 we[i] = ws[i] + max_d;
1673 } else if is_sentence_end(&words[i - 1].text) {
1674 ws[i] = we[i] - max_d;
1675 }
1676 }
1677 }
1678 // The DTW path is pinned to the crop's first and last frame, so edge words absorb
1679 // silence: cap them too.
1680 if we[0] - ws[0] > max_d {
1681 ws[0] = we[0] - max_d;
1682 }
1683 if we[k - 1] - ws[k - 1] > max_d {
1684 we[k - 1] = ws[k - 1] + max_d;
1685 }
1686 }
1687
1688 // Words stay inside the crop, which lies inside the audio.
1689 let lo = base + f0 as f64 * ENC_SPF;
1690 let hi = base + f1 as f64 * ENC_SPF;
1691 let mut s: Vec<f64> = ws.iter().map(|&x| (base + x).clamp(lo, hi)).collect();
1692 let mut e: Vec<f64> = we.iter().map(|&x| (base + x).clamp(lo, hi)).collect();
1693 // Snap edges onto speech frames. DTW spreads a word over the silence before it, so a start
1694 // moves to the first speech frame inside the word's span and an end to the end of the last
1695 // speech frame inside it.
1696 let frame_of = |t: f64| ((t - base) / ENC_SPF).round().max(0.0) as usize;
1697 let audible = |j: usize| speech.get(j).copied().unwrap_or(false);
1698 for i in 0..k {
1699 let (fs, fe) = (frame_of(s[i]), frame_of(e[i]));
1700 if let Some(j) = (fs..=fe).find(|&j| audible(j)) {
1701 if j > fs {
1702 s[i] = (base + j as f64 * ENC_SPF).min(e[i]);
1703 }
1704 }
1705 let fs = frame_of(s[i]);
1706 if let Some(j) = (fs..=fe).rev().find(|&j| audible(j)) {
1707 if j + 1 < fe {
1708 e[i] = (base + (j + 1) as f64 * ENC_SPF).max(s[i]);
1709 }
1710 }
1711 }
1712 if repair_spans(&mut s, &mut e, lo, hi) {
1713 bail!("degenerate word spans: DTW collapsed words onto one another");
1714 }
1715
1716 let out: Vec<serde_json::Value> = words
1717 .iter()
1718 .enumerate()
1719 .filter_map(|(i, w)| {
1720 let text = String::from_utf8_lossy(&w.text).trim().to_string();
1721 if text.is_empty() {
1722 return None;
1723 }
1724 let p = (w.lps.iter().map(|&x| x as f64).sum::<f64>() / w.lps.len() as f64).exp();
1725 Some(serde_json::json!({"w": text, "start": r3(s[i]), "end": r3(e[i]), "p": r3(p)}))
1726 })
1727 .collect();
1728 if out.is_empty() {
1729 bail!("alignment produced no words");
1730 }
1731 Ok(out)
1732}
1733
1734/// Shortest word the output may carry: two encoder frames (40 ms).
1735const MIN_WORD_S: f64 = 2.0 * ENC_SPF;
1736
1737/// Makes word spans monotone, non-overlapping and at least `MIN_WORD_S` long, inside
1738/// `[lo, hi]` where the audio allows. Returns true when the alignment is degenerate, i.e. a
1739/// word had collapsed to a point or overlapped its neighbour by more than a frame, or the words
1740/// could not be fitted into the segment. The spans are still repaired in that case, but the
1741/// caller should not trust them.
1742fn repair_spans(s: &mut [f64], e: &mut [f64], lo: f64, hi: f64) -> bool {
1743 let n = s.len();
1744 let mut degenerate = false;
1745 let mut prev_end = lo;
1746 for i in 0..n {
1747 if e[i] - s[i] < 1e-3 {
1748 degenerate = true;
1749 }
1750 if s[i] < prev_end - ENC_SPF {
1751 degenerate = true;
1752 }
1753 s[i] = s[i].max(prev_end);
1754 e[i] = e[i].max(s[i] + MIN_WORD_S);
1755 prev_end = e[i];
1756 }
1757 if n > 0 && e[n - 1] > hi {
1758 // The words ran past the segment: pull them back from the end, keeping the minimum.
1759 let mut limit = hi;
1760 for i in (0..n).rev() {
1761 e[i] = e[i].min(limit);
1762 s[i] = s[i].min(e[i] - MIN_WORD_S);
1763 limit = s[i];
1764 }
1765 if s[0] < lo - ENC_SPF {
1766 degenerate = true;
1767 }
1768 }
1769 degenerate
1770}
1771
1772/// Speech that must come before a segment's first word, after the previous word, for the gap to
1773/// be re-decoded for a leading filler. Shorter gaps are breaths and onsets, not a filler.
1774const ONSET_MIN_S: f64 = 0.25;
1775/// Audio kept on each side of a re-decoded gap, in seconds: the margin Whisper needs to hear the
1776/// gap's edges as edges.
1777const RECOVER_MARGIN_S: f64 = 0.3;
1778/// Words a leading gap may carry and still be a filler: the spellings Whisper gives those sounds.
1779const FILLER_WORDS: &[&str] = &["um", "uh", "er", "ah", "hmm", "hm", "mm", "uhm", "umm", "uhh", "erm"];
1780
1781/// The first speech frame in `[from, word)` (frames of 20 ms, window-relative) when the speech
1782/// before the word, from that frame on, runs longer than `ONSET_MIN_S`. None when the gap before
1783/// the word holds no speech that long: the word is the first thing said since `from`.
1784fn leading_onset(speech: &[bool], from: usize, word: usize) -> Option<usize> {
1785 let end = word.min(speech.len());
1786 let first = (from..end).find(|&j| speech[j])?;
1787 ((end - first) as f64 * ENC_SPF > ONSET_MIN_S).then_some(first)
1788}
1789
1790/// True when a word is a filler sound, ignoring case and punctuation ("Um," is "um").
1791fn is_filler_word(w: &str) -> bool {
1792 let norm: String = w.chars().filter(|c| c.is_alphanumeric()).collect::<String>().to_ascii_lowercase();
1793 FILLER_WORDS.contains(&norm.as_str())
1794}
1795
1796/// The filler words a re-decoded gap found that belong in front of a segment: fillers that start
1797/// at or after `min_s` (the previous word's end, so nothing is taken twice) and clearly before the
1798/// segment's first word `first_s`. A filler at the word's own start is the same sound, not a
1799/// second one, and is left to the segment.
1800fn recovered_fillers(words: &[serde_json::Value], min_s: f64, first_s: f64) -> Vec<serde_json::Value> {
1801 words
1802 .iter()
1803 .filter(|w| {
1804 let (Some(s), Some(t)) = (w["start"].as_f64(), w["w"].as_str()) else { return false };
1805 is_filler_word(t) && s >= min_s && s < first_s - 0.05
1806 })
1807 .cloned()
1808 .collect()
1809}
1810
1811/// Re-decodes the gap `[gap_s.0, gap_s.1]` (window-relative seconds, margins included) on its own
1812/// and returns the filler words it holds, timed with DTW. `base` is the absolute time of the
1813/// window start (with the CLI offset). The gap is decoded with the same `prompt` as the window,
1814/// so the filler hint is in force, but only the filler words are kept.
1815#[allow(clippy::too_many_arguments)]
1816fn decode_gap_fillers(
1817 model: &mut Whisper,
1818 pcm: &[f32],
1819 win_start_sample: usize,
1820 gap_s: (f64, f64),
1821 prompt: &[u32],
1822 vocab: &Vocab,
1823 ids: &Ids,
1824 cfg: &Config,
1825 filters: &[f32],
1826 heads: &[(usize, usize)],
1827 sup: &Suppress,
1828 rng: &mut Rng,
1829 base: f64,
1830 dev: &Device,
1831) -> Result<Vec<serde_json::Value>> {
1832 let a = win_start_sample + (gap_s.0 * SR as f64) as usize;
1833 let b = (win_start_sample + (gap_s.1 * SR as f64) as usize).min(pcm.len());
1834 if b <= a + SR / 10 {
1835 return Ok(Vec::new());
1836 }
1837 let stretch = &pcm[a..b];
1838 let mut win = vec![0f32; WINDOW];
1839 win[..stretch.len()].copy_from_slice(stretch);
1840 let mel = m::audio::pcm_to_mel(cfg, &win, filters);
1841 let n_frames = mel.len() / cfg.num_mel_bins;
1842 let mel_t = Tensor::from_vec(mel, (1, cfg.num_mel_bins, n_frames), dev)?.narrow(2, 0, WINDOW / FRAME)?;
1843 let enc = model.encoder.forward(&mel_t, true)?;
1844 let n_content = stretch.len().div_ceil(ENC_HOP);
1845 let speech = speech_frames(&levels(stretch));
1846 let crop = trim_crop_to_speech((0, n_content), &speech);
1847 let base = base + (a - win_start_sample) as f64 / SR as f64;
1848
1849 let (toks, _, _) = decode_window(model, &enc, prompt, 0.0, ids, cfg, sup, rng, dev)?;
1850 let content_s = stretch.len() as f64 / SR as f64;
1851 let mut out = Vec::new();
1852 for seg in split_segments(&toks, ids.ts0, content_s) {
1853 // A gap that holds no alignable words, or no DTW path, has no fillers to keep.
1854 if let Ok(words) = aligned_words(model, &enc, prompt, &seg.toks, vocab, ids, heads, crop, n_content, base, &speech, dev) {
1855 out.extend(words.into_iter().filter(|w| w["w"].as_str().is_some_and(is_filler_word)));
1856 }
1857 }
1858 Ok(out)
1859}
1860
1861// ---------------------------------------------------------------- tests
1862
1863#[cfg(test)]
1864mod tests {
1865 use super::*;
1866
1867 #[test]
1868 fn segments_split_on_timestamp_pairs() {
1869 let ts0 = 1000;
1870 // ts 0.00, text(10,11), ts 1.00, ts 1.00, text(12), ts 2.00
1871 let toks = vec![(ts0, 0.0), (10, -0.1), (11, -0.1), (ts0 + 50, 0.0), (ts0 + 50, 0.0), (12, -0.2), (ts0 + 100, 0.0)];
1872 let segs = split_segments(&toks, ts0, 30.0);
1873 assert_eq!(segs.len(), 2);
1874 assert!((segs[0].start - 0.0).abs() < 1e-9 && (segs[0].end - 1.0).abs() < 1e-9);
1875 assert!((segs[1].start - 1.0).abs() < 1e-9 && (segs[1].end - 2.0).abs() < 1e-9);
1876 }
1877
1878 #[test]
1879 fn leftover_text_ends_at_content() {
1880 let ts0 = 1000;
1881 let toks = vec![(ts0, 0.0), (10, -0.1), (11, -0.1)];
1882 let segs = split_segments(&toks, ts0, 12.5);
1883 assert_eq!(segs.len(), 1);
1884 assert!((segs[0].end - 12.5).abs() < 1e-9);
1885 }
1886
1887 #[test]
1888 fn repaired_spans_are_monotone_and_never_zero_length() {
1889 // The shape the DTW produced on the dog3 narration: "You" collapsed onto the segment
1890 // start, "describe" overlapping it.
1891 let mut s = vec![5.24, 5.24, 5.62];
1892 let mut e = vec![5.24, 5.62, 6.0];
1893 assert!(repair_spans(&mut s, &mut e, 5.24, 6.0), "a collapsed word is degenerate");
1894 for i in 0..3 {
1895 assert!(e[i] - s[i] >= MIN_WORD_S - 1e-9, "word {i}: {} to {}", s[i], e[i]);
1896 if i > 0 {
1897 assert!(s[i] >= e[i - 1] - 1e-9, "word {i} overlaps the one before");
1898 }
1899 }
1900 }
1901
1902 #[test]
1903 fn clean_spans_are_not_degenerate_and_stay_put() {
1904 let mut s = vec![0.0, 0.14, 0.2];
1905 let mut e = vec![0.14, 0.2, 0.6];
1906 assert!(!repair_spans(&mut s, &mut e, 0.0, 0.6));
1907 assert_eq!(s, vec![0.0, 0.14, 0.2]);
1908 assert_eq!(e, vec![0.14, 0.2, 0.6]);
1909 }
1910
1911 #[test]
1912 fn words_that_overrun_the_segment_are_pulled_back_or_flagged() {
1913 let mut s = vec![0.0, 0.5, 0.9];
1914 let mut e = vec![0.5, 0.9, 1.4];
1915 // Fits: the last word is pulled back to the segment end.
1916 assert!(!repair_spans(&mut s, &mut e, 0.0, 1.2));
1917 assert!(e[2] <= 1.2 + 1e-9 && e[2] > s[2]);
1918 // Cannot fit three words of minimum length into 0.05 s.
1919 let mut s = vec![0.0, 0.01, 0.02];
1920 let mut e = vec![0.01, 0.02, 0.03];
1921 assert!(repair_spans(&mut s, &mut e, 0.0, 0.05));
1922 for i in 0..3 {
1923 assert!(e[i] > s[i]);
1924 }
1925 }
1926
1927 #[test]
1928 fn prompt_encodes_to_tokens_that_decode_back() {
1929 // Needs the base model on disk; the vocabulary is the only input.
1930 let home = std::env::var("HOME").unwrap_or_default();
1931 let path = Path::new(&home).join(".cache/edith/models/whisper-base/tokenizer.json");
1932 let Ok(vocab) = Vocab::load(&path) else { return };
1933 for text in [" Edith, LUFS", " Edith turns a folder of raw footage."] {
1934 let toks = vocab.encode(text);
1935 assert!(!toks.is_empty());
1936 assert_eq!(vocab.decode(&toks), text);
1937 }
1938 // Merges are applied: a common word is one token, not one per byte.
1939 assert_eq!(vocab.encode(" turns").len(), 1);
1940 }
1941
1942 #[test]
1943 fn dtw_follows_the_cheap_diagonal() {
1944 // 3 rows x 5 frames; cells (0,0) (1,2) (2,4) are cheap, so the path must cross them.
1945 let (rows, cols) = (3, 5);
1946 let mut cost = vec![1.0f32; rows * cols];
1947 cost[0] = -1.0;
1948 cost[cols + 2] = -1.0;
1949 cost[2 * cols + 4] = -1.0;
1950 let (ti, tj) = dtw_path(&cost, rows, cols);
1951 assert_eq!((ti[0], tj[0]), (0, 0));
1952 assert_eq!((*ti.last().unwrap(), *tj.last().unwrap()), (2, 4));
1953 let path: Vec<(usize, usize)> = ti.iter().copied().zip(tj.iter().copied()).collect();
1954 for cell in [(0, 0), (1, 2), (2, 4)] {
1955 assert!(path.contains(&cell), "path misses {cell:?}: {path:?}");
1956 }
1957 }
1958
1959 #[test]
1960 fn median_filter_reflects_edges() {
1961 let x = [1.0f32, 1.0, 9.0, 1.0, 1.0];
1962 assert_eq!(median_filter(&x, 3), vec![1.0, 1.0, 1.0, 1.0, 1.0]);
1963 assert_eq!(median_filter(&[5.0], 7), vec![5.0]);
1964 }
1965
1966 #[test]
1967 fn silence_filter_needs_both_no_speech_signals() {
1968 // Hallucination: model says no speech and is unsure of its own text.
1969 assert_eq!(silence_reason(0.9, -1.5, None), Some("no_speech"));
1970 // Confident text is kept even when no_speech is high.
1971 assert_eq!(silence_reason(0.9, -0.2, None), None);
1972 // Unsure text is kept when the model does not think it is silence, if the span is audible.
1973 assert_eq!(silence_reason(0.1, -1.5, Some(-30.0)), Some("silent_span"));
1974 assert_eq!(silence_reason(0.1, -1.5, Some(20.0)), None);
1975 // Thresholds are strict: exactly 0.6 and exactly -1.0 are kept.
1976 assert_eq!(silence_reason(0.6, -1.5, None), None);
1977 assert_eq!(silence_reason(0.9, -1.0, None), None);
1978 }
1979
1980 #[test]
1981 fn silence_filter_drops_spans_at_the_noise_floor_regardless_of_text() {
1982 assert_eq!(silence_reason(0.0, -0.1, Some(1.0)), Some("silent_span"));
1983 assert_eq!(silence_reason(0.0, -0.1, Some(SILENT_REL_DB - 0.1)), Some("silent_span"));
1984 assert_eq!(silence_reason(0.0, -0.1, Some(SILENT_REL_DB)), None);
1985 // No frames in the span: no energy evidence either way.
1986 assert_eq!(silence_reason(0.0, -0.1, None), None);
1987 }
1988
1989 #[test]
1990 fn span_level_is_relative_to_the_noise_floor() {
1991 // 2 s of a 220 Hz bed at -20 dBFS, then 2 s of 1 kHz speech at -10 dBFS: the speech band
1992 // drops the bed, so the speech span sits far above the floor and the bed span does not.
1993 let sr = SR as f32;
1994 let bed: Vec<f32> = (0..2 * SR).map(|i| 0.1 * (2.0 * std::f32::consts::PI * 220.0 * i as f32 / sr).sin()).collect();
1995 let speech: Vec<f32> = (0..2 * SR).map(|i| 0.316 * (2.0 * std::f32::consts::PI * 1000.0 * i as f32 / sr).sin()).collect();
1996 let pcm: Vec<f32> = bed.iter().chain(speech.iter()).copied().collect();
1997 let lv = levels(&pcm);
1998 let speech_rel = span_rel_db(&lv, 2.5, 3.5).unwrap();
1999 let bed_rel = span_rel_db(&lv, 0.5, 1.5).unwrap();
2000 assert!(speech_rel > 20.0, "speech span {speech_rel:.1} dB above floor");
2001 assert!(bed_rel.abs() < SILENT_REL_DB, "bed span {bed_rel:.1} dB above floor");
2002 assert_eq!(span_rel_db(&lv, 0.5, 0.5), None);
2003 }
2004
2005 #[test]
2006 fn speech_band_drops_the_bed_and_keeps_speech() {
2007 let sr = SR as f32;
2008 let bed: Vec<f32> = (0..SR).map(|i| 0.1 * (2.0 * std::f32::consts::PI * 220.0 * i as f32 / sr).sin()).collect();
2009 let voice: Vec<f32> = (0..SR).map(|i| 0.1 * (2.0 * std::f32::consts::PI * 1000.0 * i as f32 / sr).sin()).collect();
2010 let rms = |v: &[f64]| (v[SR / 4..3 * SR / 4].iter().map(|x| x * x).sum::<f64>() / (SR / 2) as f64).sqrt();
2011 let bed_out = rms(&speech_band(&bed));
2012 let voice_out = rms(&speech_band(&voice));
2013 assert!(bed_out < 0.1 * 0.1, "220 Hz bed leaks through: {bed_out}");
2014 assert!(voice_out > 0.9 * 0.1 / 2f64.sqrt(), "1 kHz speech attenuated: {voice_out}");
2015 }
2016
2017 #[test]
2018 fn speech_frames_flag_only_frames_above_the_floor() {
2019 // 1 s of bed (220 Hz), 1 s of speech-band tone, 1 s of bed again.
2020 let sr = SR as f32;
2021 let mut pcm = Vec::new();
2022 for i in 0..3 * SR {
2023 let f = if (SR..2 * SR).contains(&i) { 1000.0 } else { 220.0 };
2024 let a = if f > 500.0 { 0.2 } else { 0.1 };
2025 pcm.push(a * (2.0 * std::f32::consts::PI * f * i as f32 / sr).sin());
2026 }
2027 let flags = speech_frames(&levels(&pcm));
2028 let frame = |t: f64| (t / ENC_SPF) as usize;
2029 assert!(!flags[frame(0.3)] && !flags[frame(2.7)], "bed frames flagged");
2030 assert!(flags[frame(1.2)] && flags[frame(1.8)], "speech frames missed");
2031 }
2032
2033 #[test]
2034 fn quiet_floor_is_the_mean_of_the_quietest_tenth() {
2035 let v: Vec<f64> = (1..=20).map(|x| x as f64).collect();
2036 assert_eq!(quiet_floor_db(&v), 1.5); // quietest 2 of 20: 1 and 2
2037 assert_eq!(quiet_floor_db(&[7.0]), 7.0);
2038 }
2039
2040 #[test]
2041 fn crop_covers_the_segment_plus_margin_and_is_clamped() {
2042 // 5 s segment inside 20 s of audio, 0.5 s margin: 6 s of 20 ms frames.
2043 assert_eq!(crop_frames(5.0, 10.0, 1000, 0.5, 0.5), (225, 525));
2044 // Margins past the audio edges are clamped to it.
2045 assert_eq!(crop_frames(0.2, 1.0, 1000, 0.5, 0.5), (0, 75));
2046 assert_eq!(crop_frames(14.9, 15.0, 760, 0.5, 0.5), (720, 760));
2047 // Never empty, even for a zero-length span.
2048 let (f0, f1) = crop_frames(3.0, 3.0, 100, 0.0, 0.0);
2049 assert!(f1 > f0 && f1 <= 100);
2050 }
2051
2052 #[test]
2053 fn tied_starts_are_spread_between_their_neighbours() {
2054 // Tokens 0 and 1 both pinned at 14.16 s, the next token at 14.44 s, the end at 15.0 s.
2055 let mut s = vec![14.16, 14.16, 14.44, 14.74];
2056 spread_tied_starts(&mut s, 15.0);
2057 assert_eq!(s[0], 14.16);
2058 assert!((s[1] - 14.30).abs() < 1e-9, "{}", s[1]);
2059 assert_eq!(s[2], 14.44);
2060 // A tie in the middle is spread from the start before it.
2061 let mut m = vec![1.0, 2.0, 2.0, 2.0, 5.0];
2062 spread_tied_starts(&mut m, 6.0);
2063 assert!((m[2] - 3.0).abs() < 1e-9 && (m[3] - 4.0).abs() < 1e-9, "{m:?}");
2064 // Strictly increasing starts are left alone.
2065 let mut t = vec![0.0, 0.5, 1.0];
2066 spread_tied_starts(&mut t, 2.0);
2067 assert_eq!(t, vec![0.0, 0.5, 1.0]);
2068 }
2069
2070 #[test]
2071 fn crop_trims_to_the_speech_it_contains() {
2072 let mut speech = vec![false; 100];
2073 speech[40..60].fill(true);
2074 assert_eq!(trim_crop_to_speech((30, 80), &speech), (40, 60));
2075 // Crops with no speech keep their span.
2076 assert_eq!(trim_crop_to_speech((0, 30), &speech), (0, 30));
2077 // A single speech frame gives a one-frame crop.
2078 let mut one = vec![false; 10];
2079 one[4] = true;
2080 assert_eq!(trim_crop_to_speech((2, 8), &one), (4, 5));
2081 }
2082
2083 #[test]
2084 fn segments_starting_at_the_audio_end_are_dropped() {
2085 // 15.28 s of audio: a start at 15.26 s is the spurious tail segment.
2086 assert!(starts_past_end(15.26, 15.28));
2087 assert!(starts_past_end(15.18, 15.28));
2088 assert!(!starts_past_end(15.0, 15.28));
2089 assert!(!starts_past_end(0.0, 15.28));
2090 }
2091
2092 #[test]
2093 fn words_past_the_audio_end_are_cut_and_the_rest_of_the_segment_stays() {
2094 let word = |w: &str, s: f64, e: f64| serde_json::json!({"w": w, "start": s, "end": e, "p": 0.9});
2095 // 2.0 s of audio, offset 0: "Edith makes editing fast." ends before it, "We can." starts after it.
2096 let mut words = vec![
2097 word("Edith", 0.04, 0.4),
2098 word("makes", 0.4, 0.6),
2099 word("editing", 0.6, 1.08),
2100 word("fast.", 1.08, 1.92),
2101 word("We", 1.95, 2.2),
2102 word("can.", 2.2, 2.4),
2103 ];
2104 assert_eq!(fit_words_to_audio(&mut words, 0.0, 2.0), 2);
2105 let kept: Vec<&str> = words.iter().filter_map(|w| w["w"].as_str()).collect();
2106 assert_eq!(kept, ["Edith", "makes", "editing", "fast."]);
2107 assert_eq!(words[3]["end"].as_f64(), Some(1.92));
2108
2109 // A word starting inside the audio but running past its end keeps its start and gets its end clamped.
2110 let mut words = vec![word("cut", 1.5, 2.3)];
2111 assert_eq!(fit_words_to_audio(&mut words, 0.0, 2.0), 0);
2112 assert_eq!(words[0]["start"].as_f64(), Some(1.5));
2113 assert_eq!(words[0]["end"].as_f64(), Some(2.0));
2114
2115 // Offset: word times are absolute, so the cut is judged on audio-local times.
2116 let mut words = vec![word("a", 10.5, 10.9), word("b", 11.95, 12.2)];
2117 assert_eq!(fit_words_to_audio(&mut words, 10.0, 2.0), 1);
2118 assert_eq!(words.len(), 1);
2119 assert_eq!(words[0]["end"].as_f64(), Some(10.9));
2120
2121 // Every word past the end: nothing is kept.
2122 let mut words = vec![word("x", 2.0, 2.3)];
2123 assert_eq!(fit_words_to_audio(&mut words, 0.0, 2.0), 1);
2124 assert!(words.is_empty());
2125 }
2126
2127 #[test]
2128 fn zscore_normalises_each_frame_over_the_token_rows() {
2129 let mut m = vec![vec![1.0f32, 5.0], vec![3.0, 5.0], vec![5.0, 5.0]];
2130 zscore_columns(&mut m);
2131 // Column 0: mean 3, population sd sqrt(8/3). Column 1 is constant: all zeros.
2132 let sd = (8.0f64 / 3.0).sqrt();
2133 assert!((m[0][0] as f64 + 2.0 / sd).abs() < 1e-4);
2134 assert!((m[2][0] as f64 - 2.0 / sd).abs() < 1e-4);
2135 assert!(m.iter().all(|r| r[1].abs() < 1e-6));
2136 }
2137
2138 #[test]
2139 fn softmax_prob_is_a_probability() {
2140 let logits = [0.0f32, 1.0, 2.0];
2141 let total: f64 = (0..3).map(|i| softmax_prob(&logits, i)).sum();
2142 assert!((total - 1.0).abs() < 1e-9);
2143 assert!(softmax_prob(&logits, 2) > softmax_prob(&logits, 0));
2144 assert_eq!(softmax_prob(&logits, 9), 0.0);
2145 }
2146
2147 #[test]
2148 fn english_suppression_catches_foreign_scripts_not_punctuation() {
2149 // "锈" (U+9508) and "拜" (U+62DC) start with 0xE9 and 0xE6; Cyrillic "д" is D0 B4.
2150 assert!(foreign_script_bytes("锈".as_bytes()));
2151 assert!(foreign_script_bytes("拜".as_bytes()));
2152 assert!(foreign_script_bytes("д".as_bytes()));
2153 assert!(foreign_script_bytes("、".as_bytes())); // U+3001, ideographic comma
2154 assert!(foreign_script_bytes("ひ".as_bytes()));
2155 assert!(foreign_script_bytes("한".as_bytes()));
2156 // Plain English, accented Latin and general punctuation are kept.
2157 for ok in ["the", " harbour", "café", "naïve", "\u{2018}quoted\u{2019}", "a\u{2014}b", "…", "$5"] {
2158 assert!(!foreign_script_bytes(ok.as_bytes()), "{ok:?} must not be suppressed");
2159 }
2160 }
2161
2162 #[test]
2163 fn blank_tokens_are_whitespace_only() {
2164 assert!(blank_bytes(b" "));
2165 assert!(blank_bytes(b"\n"));
2166 assert!(!blank_bytes(b""));
2167 assert!(!blank_bytes(b" The"));
2168 }
2169
2170 #[test]
2171 fn resample_keeps_length_ratio() {
2172 let mono = vec![0.0f32; 22050];
2173 let src = 22050.0f64;
2174 let out_len = (mono.len() as f64 * SR as f64 / src).round() as usize;
2175 assert_eq!(out_len, 16000);
2176 }
2177
2178 #[test]
2179 fn loops_are_found_on_text_tokens_and_cut_to_one_copy() {
2180 let ts0 = 1000u32;
2181 // Text 1, then the phrase "7 8" said four times, each copy after its own timestamp.
2182 let mut out: Vec<(u32, f32)> = vec![(ts0 + 5, 0.0), (1, 0.0), (ts0 + 10, 0.0)];
2183 for copy in 0..4u32 {
2184 out.push((7, 0.0));
2185 out.push((8, 0.0));
2186 out.push((ts0 + 14 + copy * 4, 0.0));
2187 }
2188 let p = text_loop_period(&out, ts0).expect("a loop");
2189 assert_eq!(p, 2);
2190 cut_loop(&mut out, ts0, p);
2191 // The first copy stays, and the window ends on the timestamp before the repeats.
2192 let kept: Vec<u32> = out.iter().map(|t| t.0).collect();
2193 assert_eq!(kept, vec![ts0 + 5, 1, ts0 + 10, 7, 8, ts0 + 14]);
2194 }
2195
2196 #[test]
2197 fn loop_right_after_the_first_timestamp_leaves_no_text() {
2198 // The window-0 case: `<|0.00|>`, then the phrase said four times with no timestamp
2199 // between the copies. The cut keeps only the timestamp, so the window has no text.
2200 let ts0 = 1000u32;
2201 let mut out: Vec<(u32, f32)> = vec![(ts0, 0.0)];
2202 for _ in 0..4u32 {
2203 out.push((7, 0.0));
2204 out.push((8, 0.0));
2205 }
2206 let p = text_loop_period(&out, ts0).expect("a loop");
2207 cut_loop(&mut out, ts0, p);
2208 assert!(!has_text(&out, ts0));
2209 assert!(window_rejected(0.3, -0.2, true), "an empty loop cut must be retried");
2210 }
2211
2212 #[test]
2213 fn window_rejection_follows_whisper_thresholds() {
2214 assert!(!window_rejected(1.5, -0.4, false));
2215 assert!(window_rejected(2.5, -0.4, false), "repetitive text");
2216 assert!(window_rejected(1.5, -1.2, false), "unsure tokens");
2217 assert!(window_rejected(1.5, -0.4, true), "loop without text");
2218 }
2219
2220 #[test]
2221 fn temperature_schedule_is_whisper_fallback() {
2222 assert_eq!(TEMPS.first(), Some(&0.0));
2223 assert_eq!(TEMPS.last(), Some(&1.0));
2224 assert!(TEMPS.windows(2).all(|w| (w[1] - w[0] - 0.2).abs() < 1e-9));
2225 }
2226
2227 #[test]
2228 fn seek_goes_to_the_last_timestamp_when_the_window_ends_on_one() {
2229 // Ends on a timestamp at 5.0 s: seek there (500 frames), whether or not it looped.
2230 assert_eq!(seek_advance_frames(true, Some(5.0), false, 3000), 500);
2231 assert_eq!(seek_advance_frames(true, Some(5.0), true, 3000), 500);
2232 // Ends on text: the whole window is consumed.
2233 assert_eq!(seek_advance_frames(false, Some(5.0), false, 3000), 3000);
2234 }
2235
2236 #[test]
2237 fn looped_window_without_a_timestamp_steps_briefly_not_thirty_seconds() {
2238 // Window 0 looped right after `<|0.00|>`: the cut leaves only that timestamp (t = 0).
2239 assert_eq!(seek_advance_frames(true, Some(0.0), true, 3000), 500);
2240 // Nothing left at all after the cut.
2241 assert_eq!(seek_advance_frames(false, None, true, 3000), 500);
2242 // Near the end of the audio the step is clamped to what is left.
2243 assert_eq!(seek_advance_frames(false, None, true, 200), 200);
2244 // A loop after a timestamp at 12 s seeks to it.
2245 assert_eq!(seek_advance_frames(true, Some(12.0), true, 3000), 1200);
2246 }
2247
2248 #[test]
2249 fn ordinary_speech_is_not_a_loop() {
2250 let ts0 = 1000u32;
2251 let out: Vec<(u32, f32)> = [1u32, 2, 3, 4, 5, 6, 7, 8, 9, 10].iter().map(|&t| (t, 0.0)).collect();
2252 assert_eq!(text_loop_period(&out, ts0), None);
2253 let twice: Vec<(u32, f32)> = [1u32, 2, 1, 2, 3, 4].iter().map(|&t| (t, 0.0)).collect();
2254 assert_eq!(text_loop_period(&twice, ts0), None);
2255 }
2256
2257 /// Speech flags with `[a, b)` (frames) set.
2258 fn speech_at(n: usize, a: usize, b: usize) -> Vec<bool> {
2259 (0..n).map(|j| (a..b).contains(&j)).collect()
2260 }
2261
2262 #[test]
2263 fn onset_needs_more_than_a_quarter_second_of_speech_before_the_word() {
2264 // 1 s of speech (50 frames) from frame 10, the word at frame 60: an onset at 10.
2265 let s = speech_at(100, 10, 60);
2266 assert_eq!(leading_onset(&s, 0, 60), Some(10));
2267 // 0.2 s (10 frames) is a breath, not a filler: no onset.
2268 let short = speech_at(100, 50, 60);
2269 assert_eq!(leading_onset(&short, 0, 60), None);
2270 // 0.24 s (12 frames) is still short of the 0.25 s that must come before the word.
2271 let just_short = speech_at(100, 48, 60);
2272 assert_eq!(leading_onset(&just_short, 0, 60), None);
2273 }
2274
2275 #[test]
2276 fn onset_search_starts_after_the_previous_word() {
2277 // Speech in [0, 30) is the previous word's; the gap [30, 60) is silent: no onset.
2278 let s = speech_at(100, 0, 30);
2279 assert_eq!(leading_onset(&s, 30, 60), None);
2280 // With speech after the previous word's end the onset is found from `from`.
2281 let s = speech_at(100, 0, 60);
2282 assert_eq!(leading_onset(&s, 30, 60), Some(30));
2283 }
2284
2285 #[test]
2286 fn filler_words_match_regardless_of_case_and_punctuation() {
2287 assert!(is_filler_word("Um,"));
2288 assert!(is_filler_word("uh"));
2289 assert!(is_filler_word("Hmm..."));
2290 assert!(is_filler_word("Uhm,"));
2291 assert!(!is_filler_word("yes,"));
2292 assert!(!is_filler_word("like"), "like is a real word too often to recover");
2293 }
2294
2295 #[test]
2296 fn recovered_fillers_stop_at_the_previous_word_and_the_segment_word() {
2297 let w = |t: &str, s: f64| serde_json::json!({"w": t, "start": s, "end": s + 0.3});
2298 let found = vec![
2299 w("Um,", 0.98), // in the gap: kept
2300 w("Yes,", 2.6), // not a filler: dropped
2301 w("uh", 0.1), // before the previous word's end: already taken
2302 w("Hmm", 2.02), // at the segment's first word (2.0): the same sound, dropped
2303 ];
2304 let got = recovered_fillers(&found, 0.5, 2.0);
2305 assert_eq!(got.len(), 1);
2306 assert_eq!(got[0]["w"], "Um,");
2307 }
2308}