forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBb02f499Tahinli1 month ago1000 commits

speech.rs1040 lines, 43.2 KiBHistoryRawDownload
1//! Speech for the editor: what is said on the timeline (edith-stt, Whisper), captions cut from
2//! it, and the fillers ("um", "uh") found in it.
3//!
4//! The pieces here are shared by the MCP server's `transcript`, `find_words` and
5//! `auto_captions` and by the GUI's Captions and Fillers cards: locating the `edith-stt` binary
6//! and its models, running it over a WAV, reading its JSON lines, and cutting timed words into
7//! caption cues.
8
9use std::io::{BufRead, BufReader, Read};
10use std::path::{Path, PathBuf};
11use std::process::{Command, Stdio};
12use std::sync::atomic::{AtomicBool, Ordering};
13
14use crate::project::Lane;
15use crate::{AudioSession, PlaybackSession, subtitle};
16
17/// The sample rate edith-stt is fed.
18pub const RATE: u32 = 16_000;
19/// The Whisper model sizes edith-stt knows.
20pub const MODELS: &[&str] = &["tiny", "base", "small"];
21/// Silence longer than this (seconds) between two words ends a caption cue.
22pub const CAPTION_GAP_SECS: f64 = 0.7;
23/// Whisper drops disfluencies unless its prompt shows them: this prompt, put before the
24/// user's `hint`, makes it keep "um", "uh" and friends.
25pub const FILLER_PROMPT: &str = "Um, uh, so, like, you know, I mean, er, hmm...";
26/// Disfluencies that captions leave out. "like" and "you know" are real words too often to strip.
27pub const CAPTION_FILLERS: &[&str] = &["um", "uhm", "uh", "ah", "hum", "hmm", "er", "erm"];
28/// A caption cue shorter than this (seconds), or of one word, is folded into a neighbour when the
29/// merged text still fits, and otherwise held on screen this long (or up to the next cue).
30pub const CUE_MIN_SECS: f64 = 0.8;
31/// A trailing caption cue whose mean word probability is below this is dropped.
32pub const CUE_LOW_P: f64 = 0.5;
33/// Whisper's stock sign-offs, which it makes up over silence. A trailing one that
34/// follows another sign-off is dropped.
35const SIGN_OFFS: &[&str] = &["thank you", "thanks", "thanks for watching", "thank you for watching", "bye", "bye bye", "see you", "see you next time"];
36
37/// The word as compared: edge punctuation off, lower case.
38pub fn norm(w: &str) -> String {
39 w.trim_matches(|c: char| !c.is_alphanumeric()).to_lowercase()
40}
41
42pub fn home() -> PathBuf {
43 std::env::var_os("HOME").map_or_else(std::env::temp_dir, PathBuf::from)
44}
45
46/// The edith-stt binary: `EDITH_STT_BIN`, else the first
47/// `tools/edith-stt/target/release/edith-stt` above the running executable.
48pub fn stt_bin() -> Result<PathBuf, String> {
49 const NOT_BUILT: &str = "edith-stt is not built. Run `cd tools/edith-stt && cargo build --release` in the edith repo, or set EDITH_STT_BIN to the binary";
50 if let Some(p) = std::env::var_os("EDITH_STT_BIN") {
51 let p = PathBuf::from(p);
52 return if p.is_file() { Ok(p) } else { Err(format!("EDITH_STT_BIN is set to {}, which is not a file. {NOT_BUILT}", p.display())) };
53 }
54 if let Ok(exe) = std::env::current_exe() {
55 for dir in exe.ancestors() {
56 let c = dir.join("tools/edith-stt/target/release/edith-stt");
57 if c.is_file() {
58 return Ok(c);
59 }
60 }
61 }
62 Err(NOT_BUILT.into())
63}
64
65pub fn check_model(model: &str) -> Result<(), String> {
66 if !MODELS.contains(&model) {
67 return Err(format!("model `{model}` is not one of {}", MODELS.join(", ")));
68 }
69 let dir = home().join(".cache/edith/models").join(format!("whisper-{model}"));
70 if !dir.is_dir() {
71 return Err(format!("the {model} model is not installed at {}; edith-stt downloads it only when asked to", dir.display()));
72 }
73 Ok(())
74}
75
76pub fn check_lang(lang: &str) -> Result<(), String> {
77 let ok = lang == "auto" || ((2..=3).contains(&lang.len()) && lang.chars().all(|c| c.is_ascii_lowercase()));
78 if ok { Ok(()) } else { Err(format!("language `{lang}` must be auto or a language code such as en")) }
79}
80
81/// The model when none is named: the first installed of base, small, tiny.
82pub fn pick_model(installed: impl Fn(&str) -> bool) -> Option<&'static str> {
83 ["base", "small", "tiny"].into_iter().find(|m| installed(m))
84}
85
86#[derive(Clone, Debug)]
87pub struct RawWord {
88 pub w: String,
89 pub start: f64,
90 pub end: f64,
91 pub p: f64,
92}
93
94#[derive(Clone, Debug)]
95pub struct RawSeg {
96 pub start: f64,
97 pub end: f64,
98 pub text: String,
99 pub words: Vec<RawWord>,
100 /// edith-stt's `approx`; a line without it counts as approximate.
101 pub approx: bool,
102 pub no_speech: Option<f64>,
103 pub avg_logprob: Option<f64>,
104 pub span_db: Option<f64>,
105}
106
107
108/// Linear resampling, the way edith-stt resamples its own input.
109pub fn resample_linear(input: &[f32], src: f64, dst: f64) -> Vec<f32> {
110 if input.is_empty() || src <= 0.0 || dst <= 0.0 {
111 return Vec::new();
112 }
113 if (src - dst).abs() < 0.5 {
114 return input.to_vec();
115 }
116 let n = (input.len() as f64 * dst / src).round() as usize;
117 (0..n)
118 .map(|i| {
119 let pos = i as f64 * src / dst;
120 let idx = pos.floor() as usize;
121 let frac = (pos - idx as f64) as f32;
122 let a = input.get(idx).copied().unwrap_or(0.0);
123 let b = input.get(idx + 1).copied().unwrap_or(a);
124 a + (b - a) * frac
125 })
126 .collect()
127}
128
129pub fn i16_bytes(samples: &[f32]) -> Vec<u8> {
130 samples
131 .iter()
132 .flat_map(|s| ((s.clamp(-1.0, 1.0) * 32767.0).round() as i16).to_le_bytes())
133 .collect()
134}
135
136/// A 16-bit mono PCM WAV at [`RATE`].
137pub fn wav_bytes(samples: &[f32]) -> Vec<u8> {
138 let data = i16_bytes(samples);
139 let len = data.len() as u32;
140 let mut b = Vec::with_capacity(44 + data.len());
141 b.extend_from_slice(b"RIFF");
142 b.extend_from_slice(&(36 + len).to_le_bytes());
143 b.extend_from_slice(b"WAVEfmt ");
144 b.extend_from_slice(&16u32.to_le_bytes());
145 b.extend_from_slice(&1u16.to_le_bytes());
146 b.extend_from_slice(&1u16.to_le_bytes());
147 b.extend_from_slice(&RATE.to_le_bytes());
148 b.extend_from_slice(&(RATE * 2).to_le_bytes());
149 b.extend_from_slice(&2u16.to_le_bytes());
150 b.extend_from_slice(&16u16.to_le_bytes());
151 b.extend_from_slice(b"data");
152 b.extend_from_slice(&len.to_le_bytes());
153 b.extend_from_slice(&data);
154 b
155}
156
157pub fn num(v: &serde_json::Value, k: &str) -> Result<f64, String> {
158 v.get(k).and_then(serde_json::Value::as_f64).ok_or_else(|| format!("edith-stt line has no `{k}` number"))
159}
160
161pub fn parse_raw(raw: &str) -> Result<Vec<RawSeg>, String> {
162 let mut out = Vec::new();
163 for line in raw.lines().filter(|l| !l.trim().is_empty()) {
164 let v: serde_json::Value = serde_json::from_str(line).map_err(|e| format!("edith-stt printed a line that is not JSON: {e}"))?;
165 let mut words = Vec::new();
166 if let Some(arr) = v.get("words").and_then(serde_json::Value::as_array) {
167 for w in arr {
168 words.push(RawWord {
169 w: w.get("w").and_then(serde_json::Value::as_str).unwrap_or("").trim().to_string(),
170 start: num(w, "start")?,
171 end: num(w, "end")?,
172 p: w.get("p").and_then(serde_json::Value::as_f64).unwrap_or(0.0),
173 });
174 }
175 }
176 out.push(RawSeg {
177 start: num(&v, "start")?,
178 end: num(&v, "end")?,
179 text: v.get("text").and_then(serde_json::Value::as_str).unwrap_or("").trim().to_string(),
180 words,
181 approx: v.get("approx").and_then(serde_json::Value::as_bool).unwrap_or(true),
182 no_speech: v.get("no_speech").and_then(serde_json::Value::as_f64),
183 avg_logprob: v.get("avg_logprob").and_then(serde_json::Value::as_f64),
184 span_db: v.get("span_db").and_then(serde_json::Value::as_f64),
185 });
186 }
187 Ok(out)
188}
189
190/// One caption cue while it is cleaned up: its words with their probabilities, and the speaker
191/// (an index into a mix's speaker lanes; 0 for one lane) whose words they are.
192pub struct Cap {
193 pub start_us: i64,
194 pub end_us: i64,
195 pub words: Vec<(String, f64)>,
196 pub text: String,
197 pub owner: u32,
198}
199
200/// Caption cues for timed words (start us, end us, text, probability), each word's speaker in
201/// `owners` (parallel to `words`). The words are partitioned into cues by [`partition`], which keeps
202/// every cue at [`CUE_MIN_SECS`] where the limits allow it; then a trailing cue that is a
203/// hallucination is dropped, cues shorter than the minimum fold into the nearer neighbour of the
204/// same speaker, and no cue runs into the next (the earlier one is clipped). A cue never spans two
205/// speakers. Returns the cues, for each dropped cue what it said and why, and the cues still under
206/// the minimum because the limits leave no split that holds them.
207pub fn caption_cues(
208 words: &[(i64, i64, String, f64)],
209 owners: &[u32],
210 max_chars: usize,
211 max_secs: f64,
212 gap_secs: f64,
213) -> (Vec<subtitle::Cue>, Vec<String>, Vec<String>) {
214 let mut skipped: Vec<String> = Vec::new();
215 let mut order: Vec<usize> = (0..words.len()).filter(|&i| !words[i].2.trim().is_empty()).collect();
216 order.sort_by_key(|&i| words[i].0);
217 let sorted: Vec<&(i64, i64, String, f64)> = order.iter().map(|&i| &words[i]).collect();
218 let own: Vec<u32> = order.iter().map(|&i| owners.get(i).copied().unwrap_or(0)).collect();
219 let min_us = (CUE_MIN_SECS * 1e6) as i64;
220 // Each run of one speaker is partitioned on its own, so no cue spans two speakers.
221 let mut groups: Vec<Vec<usize>> = Vec::new();
222 let mut r0 = 0;
223 for r1 in 1..=sorted.len() {
224 if r1 == sorted.len() || own[r1] != own[r0] {
225 for g in partition(&sorted[r0..r1], max_chars, max_secs, gap_secs, min_us) {
226 groups.push(g.into_iter().map(|i| i + r0).collect());
227 }
228 r0 = r1;
229 }
230 }
231 let mut caps: Vec<Cap> = groups
232 .iter()
233 .filter(|g| !g.is_empty())
234 .map(|g| {
235 let ws: Vec<(String, f64)> = g.iter().map(|&i| (sorted[i].2.trim().to_string(), sorted[i].3)).collect();
236 let start_us = sorted[g[0]].0;
237 let end_us = sorted[g[g.len() - 1]].1.max(start_us);
238 Cap { start_us, end_us, text: caption_text(&ws, max_chars), words: ws, owner: own[g[0]] }
239 })
240 .collect();
241 if caps.len() > 1 {
242 let last = caps.len() - 1;
243 if let Some(why) = hallucination(&caps[last], &caps[last - 1]) {
244 let c = caps.pop().expect("a last cue");
245 skipped.push(format!(
246 "\"{}\" ({:.3}s–{:.3}s): {why}",
247 c.text.replace('\n', " / "),
248 c.start_us as f64 / 1e6,
249 c.end_us as f64 / 1e6
250 ));
251 }
252 }
253 let mut i = 0;
254 while caps.len() > 1 && i < caps.len() {
255 if !is_short_cue(&caps[i], min_us) {
256 i += 1;
257 continue;
258 }
259 let before = (i > 0).then(|| caps[i].start_us - caps[i - 1].end_us);
260 let after = (i + 1 < caps.len()).then(|| caps[i + 1].start_us - caps[i].end_us);
261 let prev_nearer = match (before, after) {
262 (Some(b), Some(a)) => b <= a,
263 (Some(_), None) => true,
264 _ => false,
265 };
266 let can_prev = i > 0 && fits_merged(&caps[i - 1], &caps[i], max_chars, max_secs);
267 let can_next = i + 1 < caps.len() && fits_merged(&caps[i], &caps[i + 1], max_chars, max_secs);
268 let into_prev = can_prev && (prev_nearer || !can_next);
269 if into_prev || can_next {
270 let cur = caps.remove(i);
271 // Removing `i` leaves the next cue at `i`, so the loop goes on from there either way.
272 if into_prev {
273 let p = &mut caps[i - 1];
274 p.end_us = p.end_us.max(cur.end_us);
275 p.words.extend(cur.words);
276 p.text = caption_text(&p.words, max_chars);
277 } else {
278 let n = &mut caps[i];
279 n.start_us = n.start_us.min(cur.start_us);
280 let mut ws = cur.words;
281 ws.append(&mut n.words);
282 n.words = ws;
283 n.text = caption_text(&n.words, max_chars);
284 }
285 } else {
286 // Nothing it can join: it stays up to min_us, or until the next cue starts.
287 let next_start = caps.get(i + 1).map_or(i64::MAX, |c| c.start_us);
288 let c = &mut caps[i];
289 c.end_us = c.end_us.max((c.start_us + min_us).min(next_start));
290 i += 1;
291 }
292 }
293 for i in 0..caps.len().saturating_sub(1) {
294 let next = caps[i + 1].start_us;
295 let c = &mut caps[i];
296 c.end_us = c.end_us.min(next).max(c.start_us);
297 }
298 // The cues still under the minimum after every move: the limits left no split that holds them.
299 let mut short: Vec<String> = Vec::new();
300 if caps.len() > 1 {
301 for c in caps.iter().filter(|c| c.end_us - c.start_us < min_us) {
302 short.push(format!(
303 "\"{}\" ({:.3}s–{:.3}s, {:.2} s)",
304 c.text.replace('\n', " / "),
305 c.start_us as f64 / 1e6,
306 c.end_us as f64 / 1e6,
307 (c.end_us - c.start_us) as f64 / 1e6
308 ));
309 }
310 }
311 let cues = caps
312 .into_iter()
313 .map(|c| subtitle::Cue { start_us: c.start_us, end_us: c.end_us, text: c.text, image: None, words: Vec::new(), karaoke: Vec::new() })
314 .collect();
315 (cues, skipped, short)
316}
317
318/// How many times the speaker changes as the words are read in time order.
319pub fn speaker_changes(words: &[(i64, i64, String, f64)], owners: &[u32]) -> usize {
320 let mut order: Vec<usize> = (0..words.len()).collect();
321 order.sort_by_key(|&i| words[i].0);
322 order.windows(2).filter(|p| owners.get(p[0]) != owners.get(p[1])).count()
323}
324
325/// The cues for sorted words: contiguous runs, each one a cue the cut would make (see
326/// [`cue_valid`]), chosen to leave the fewest cues under `min_us` and then the fewest cues. A
327/// cue under the minimum costs as much as ten cues that are not, so words move to a neighbour
328/// whenever that holds the minimum, and a short cue is kept only when no run of words around it
329/// can hold it. Each cue is the indices of its words, in order.
330pub fn partition(
331 words: &[&(i64, i64, String, f64)],
332 max_chars: usize,
333 max_secs: f64,
334 gap_secs: f64,
335 min_us: i64,
336) -> Vec<Vec<usize>> {
337 /// The longest cue tried: a cue this long is past any caption a screen takes.
338 const LOOK_BACK: usize = 40;
339 /// The cost of a cue under the minimum, against 1 for every cue.
340 const SHORT: u64 = 10;
341 let n = words.len();
342 // Best (cost, start of its last cue) for the first `j` words.
343 let mut best: Vec<(u64, usize)> = vec![(u64::MAX, 0); n + 1];
344 best[0] = (0, 0);
345 for j in 1..=n {
346 for i in (j.saturating_sub(LOOK_BACK)..j).rev() {
347 // A run that is not a cue stays not one as it grows, so the search stops there.
348 if i + 1 < j && !cue_valid(&words[i..j], max_chars, max_secs, gap_secs) {
349 break;
350 }
351 if best[i].0 == u64::MAX {
352 continue;
353 }
354 let dur = words[j - 1].1 - words[i].0;
355 let cost = 1 + if dur < min_us { SHORT * 10 } else { 0 };
356 let total = best[i].0 + cost;
357 if total < best[j].0 {
358 best[j] = (total, i);
359 }
360 }
361 }
362 let mut groups: Vec<Vec<usize>> = Vec::new();
363 let mut j = n;
364 while j > 0 {
365 let i = best[j].1;
366 groups.push((i..j).collect());
367 j = i;
368 }
369 groups.reverse();
370 groups
371}
372
373/// Whether a run of words is a cue the cut would make: no pause over `gap_secs` inside it, no
374/// sentence ending before its last word, under `max_secs`, and two lines of `max_chars`.
375pub fn cue_valid(ws: &[&(i64, i64, String, f64)], max_chars: usize, max_secs: f64, gap_secs: f64) -> bool {
376 if ws.len() <= 1 {
377 return true;
378 }
379 let gap_us = (gap_secs * 1e6) as i64;
380 let max_us = (max_secs * 1e6) as i64;
381 if ws.windows(2).any(|p| p[1].0 - p[0].1 > gap_us) {
382 return false;
383 }
384 if ws[..ws.len() - 1].iter().any(|w| closes_sentence(&w.2)) {
385 return false;
386 }
387 if ws[ws.len() - 1].1 - ws[0].0 > max_us {
388 return false;
389 }
390 // Two lines of at most max_chars each, split anywhere between two words.
391 let lens: Vec<usize> = ws.iter().map(|w| w.2.trim().chars().count()).collect();
392 let total: usize = lens.iter().sum::<usize>() + lens.len() - 1;
393 let mut head = 0usize;
394 (1..ws.len()).any(|k| {
395 head += lens[k - 1] + usize::from(k > 1);
396 let tail = total - head - 1;
397 head <= max_chars && tail <= max_chars
398 })
399}
400
401/// Whether a word closes a sentence, looking past closing quotes and brackets (as the cut does).
402pub fn closes_sentence(word: &str) -> bool {
403 word.trim_end_matches(['"', '\'', ')', ']', '”', '’'])
404 .ends_with(['.', '!', '?', '…'])
405}
406
407/// Why a trailing cue is a hallucination, or `None`: low confidence, made of words the cue
408/// before already said, or a sign-off after a sign-off.
409pub fn hallucination(cap: &Cap, prev: &Cap) -> Option<&'static str> {
410 if cap.words.is_empty() {
411 return None;
412 }
413 let mean = cap.words.iter().map(|w| w.1).sum::<f64>() / cap.words.len() as f64;
414 if mean < CUE_LOW_P {
415 return Some("low confidence, the model was unsure of these words");
416 }
417 let key = |ws: &[(String, f64)]| -> Vec<String> {
418 ws.iter().map(|w| stem(&norm(&w.0))).filter(|w| !w.is_empty()).collect()
419 };
420 let (mine, theirs) = (key(&cap.words), key(&prev.words));
421 // The same words in the same order, one after another: a common word scattered through the
422 // cue before (the "the" or "us" of a different line) is not a repeat.
423 if !mine.is_empty() && theirs.windows(mine.len()).any(|w| w == mine.as_slice()) {
424 return Some("repeats the words of the cue before");
425 }
426 (sign_off(cap) && sign_off(prev)).then_some("a second sign-off after one")
427}
428
429/// A cue that is too short to read: under the minimum on screen, or one word.
430pub fn is_short_cue(c: &Cap, min_us: i64) -> bool {
431 c.end_us - c.start_us < min_us || c.words.len() == 1
432}
433
434/// Whether two neighbouring cues can be one: the merged text lays out in two lines of at most
435/// `max_chars` each, and the merged cue is no longer than `max_secs`.
436pub fn fits_merged(a: &Cap, b: &Cap, max_chars: usize, max_secs: f64) -> bool {
437 if a.owner != b.owner {
438 return false;
439 }
440 let span = (a.end_us.max(b.end_us) - a.start_us.min(b.start_us)) as f64 / 1e6;
441 if span > max_secs {
442 return false;
443 }
444 let words: Vec<(String, f64)> = a.words.iter().chain(b.words.iter()).cloned().collect();
445 caption_text(&words, max_chars).lines().all(|l| l.chars().count() <= max_chars)
446}
447
448/// Plural `s` dropped, so "thanks" and "thank" count as one word for repeats.
449pub fn stem(w: &str) -> String {
450 w.strip_suffix('s').filter(|s| s.len() > 2).unwrap_or(w).to_string()
451}
452
453pub fn sign_off(cap: &Cap) -> bool {
454 let text = cap.words.iter().map(|w| norm(&w.0)).filter(|w| !w.is_empty()).collect::<Vec<_>>().join(" ");
455 SIGN_OFFS.contains(&text.as_str())
456}
457
458/// The text of a cue over at most two lines, split where the longer line is shortest
459/// (as the engine lays out a cue).
460pub fn caption_text(words: &[(String, f64)], max_chars: usize) -> String {
461 let ws: Vec<&str> = words.iter().map(|w| w.0.as_str()).collect();
462 let len = |s: &[&str]| s.iter().map(|w| w.chars().count()).sum::<usize>() + s.len().saturating_sub(1);
463 let total = len(&ws);
464 if total <= max_chars || ws.len() < 2 {
465 return ws.join(" ");
466 }
467 let middle = total as i64 / 2;
468 let mut best: Option<(usize, (usize, i64))> = None;
469 for k in 1..ws.len() {
470 let (a, b) = (len(&ws[..k]), len(&ws[k..]));
471 let score = (a.max(b), (a as i64 - middle).abs());
472 if best.is_none_or(|(_, s)| score < s) {
473 best = Some((k, score));
474 }
475 }
476 let k = best.map_or(1, |(k, _)| k);
477 format!("{}\n{}", ws[..k].join(" "), ws[k..].join(" "))
478}
479
480/// Gives each cue the transcript's word times: every word belongs to the cue that starts last at
481/// or before it. A cue whose words do not read back as its text (the cut and merge steps can
482/// differ from the raw word list) keeps none and is drawn with evenly spread ones.
483pub fn attach_word_times(cues: &mut [subtitle::Cue], words: &[(i64, i64, String, f64)]) {
484 let mut sorted: Vec<&(i64, i64, String, f64)> = words.iter().filter(|w| !w.2.trim().is_empty()).collect();
485 sorted.sort_by_key(|w| w.0);
486 let mut by_cue: Vec<Vec<(i64, i64, String)>> = vec![Vec::new(); cues.len()];
487 for w in sorted {
488 if let Some(i) = cues.iter().rposition(|c| c.start_us <= w.0) {
489 let end = w.1.clamp(w.0, cues[i].end_us.max(w.0));
490 by_cue[i].push((w.0, end, w.2.trim().to_string()));
491 }
492 }
493 for (c, ws) in cues.iter_mut().zip(by_cue) {
494 c.words = ws;
495 if c.real_words().is_none() {
496 c.words.clear();
497 }
498 }
499}
500
501/// Capitalises the first letter of each cue that begins a sentence: the first cue, a cue that starts
502/// where a transcript segment's first kept word does (`segment_starts`, in microseconds), and a cue
503/// after one that ends in . ! or ?. A dropped filler leaves the word after it heading its cue in
504/// lower case, so "Um, hello there." would read "hello there." without this.
505pub fn capitalise_sentence_starts(cues: &mut [subtitle::Cue], segment_starts: &[i64]) {
506 let mut begins = true;
507 for c in cues.iter_mut() {
508 if (begins || segment_starts.contains(&c.start_us))
509 && let Some(first) = c.text.chars().next().filter(|f| f.is_lowercase())
510 {
511 let upper: String = first.to_uppercase().collect();
512 c.text.replace_range(..first.len_utf8(), &upper);
513 }
514 begins = c.text.trim_end().ends_with(['.', '!', '?']);
515 }
516}
517
518// ---- running edith-stt ------------------------------------------------------
519
520/// A running speech job's shared state: how far it is, and whether anyone still wants it.
521/// The GUI reads `fraction` for its progress line and sets `cancel` for its Cancel button.
522#[derive(Debug, Default)]
523pub struct Job {
524 /// Progress in thousandths (0..=1000).
525 pub permille: std::sync::atomic::AtomicU32,
526 pub cancel: AtomicBool,
527}
528
529impl Job {
530 /// Progress as a fraction, 0..=1.
531 pub fn fraction(&self) -> f32 {
532 self.permille.load(Ordering::Relaxed) as f32 / 1000.0
533 }
534
535 fn set(&self, f: f64) {
536 self.permille.store((f.clamp(0.0, 1.0) * 1000.0) as u32, Ordering::Relaxed);
537 }
538
539 pub fn cancelled(&self) -> bool {
540 self.cancel.load(Ordering::Relaxed)
541 }
542}
543
544/// The error a cancelled job returns.
545pub const CANCELLED: &str = "cancelled";
546
547/// Runs edith-stt on one WAV and returns its stdout (one JSON line per segment). Its progress
548/// lines feed `job`; setting `job.cancel` kills it. The last few other stderr lines are kept
549/// for the error if the binary fails.
550#[allow(clippy::too_many_arguments)]
551pub fn run_stt(bin: &Path, wav: &Path, model: &str, lang: &str, hint: &str, offset: f64, label: &str, job: &Job) -> Result<String, String> {
552 let hint_args: Vec<&str> = if hint.is_empty() { Vec::new() } else { vec!["--prompt", hint] };
553 let mut child = Command::new(bin)
554 .args(["--model", model, "--language", lang, "--offset"])
555 .arg(format!("{offset:.3}"))
556 .args(&hint_args)
557 .arg(wav)
558 .stdout(Stdio::piped())
559 .stderr(Stdio::piped())
560 .spawn()
561 .map_err(|e| format!("starting {}: {e}", bin.display()))?;
562 let stderr = child.stderr.take().ok_or("edith-stt: no stderr pipe")?;
563 let mut stdout = child.stdout.take().ok_or("edith-stt: no stdout pipe")?;
564 let progress = std::sync::Arc::new(Job::default());
565 let seen = std::sync::Arc::clone(&progress);
566 let err_reader = std::thread::spawn(move || {
567 let mut tail: Vec<String> = Vec::new();
568 for line in BufReader::new(stderr).lines().map_while(Result::ok) {
569 if let Some(p) = line.strip_prefix("progress ").and_then(|v| v.trim().parse::<f64>().ok()) {
570 seen.set(p);
571 } else if !line.trim().is_empty() {
572 tail.push(line);
573 if tail.len() > 6 {
574 tail.remove(0);
575 }
576 }
577 }
578 tail
579 });
580 let out_reader = std::thread::spawn(move || {
581 let mut out = String::new();
582 stdout.read_to_string(&mut out).map(|_| out)
583 });
584 let status = loop {
585 job.set(f64::from(progress.fraction()));
586 if job.cancelled() {
587 let _ = child.kill();
588 let _ = child.wait();
589 let _ = err_reader.join();
590 let _ = out_reader.join();
591 return Err(CANCELLED.into());
592 }
593 match child.try_wait() {
594 Ok(Some(st)) => break st,
595 Ok(None) => std::thread::sleep(std::time::Duration::from_millis(40)),
596 Err(e) => return Err(format!("waiting for edith-stt: {e}")),
597 }
598 };
599 let tail = err_reader.join().unwrap_or_default();
600 let out = out_reader
601 .join()
602 .map_err(|_| "reading edith-stt output: the reader panicked".to_string())?
603 .map_err(|e| format!("reading edith-stt output: {e}"))?;
604 if !status.success() {
605 return Err(format!("edith-stt failed on {label}: {}", tail.join(" | ")));
606 }
607 job.set(1.0);
608 Ok(out)
609}
610
611/// The models installed, smallest first.
612pub fn installed_models() -> Vec<&'static str> {
613 MODELS.iter().copied().filter(|m| check_model(m).is_ok()).collect()
614}
615
616/// Where the speech models live: one folder per model, `whisper-<name>`, here.
617pub fn models_dir() -> PathBuf {
618 home().join(".cache/edith/models")
619}
620
621/// The files a model folder holds, and whether each is needed (the last is a nicety).
622const MODEL_FILES: [(&str, bool); 4] = [
623 ("config.json", true),
624 ("model.safetensors", true),
625 ("tokenizer.json", true),
626 ("preprocessor_config.json", true),
627];
628const MODEL_OPTIONAL: &str = "generation_config.json";
629
630/// About how many bytes a model's files add up to, for a progress bar before the sizes are known.
631pub fn model_bytes(model: &str) -> u64 {
632 match model {
633 "tiny" => 152_000_000,
634 "small" => 970_000_000,
635 _ => 293_000_000,
636 }
637}
638
639/// Downloads the `model` (one of [`MODELS`]) into [`models_dir`] with `curl`, from the same place
640/// `edith-stt` fetches it (huggingface.co/openai/whisper-<model>). The folder appears only when
641/// every file is in, so a half-finished download is never taken for an installed model; the files
642/// already fetched are kept for the next try. `job` carries the progress and the cancel.
643pub fn download_model(model: &str, job: &Job) -> Result<(), String> {
644 if !MODELS.contains(&model) {
645 return Err(format!("model `{model}` is not one of {}", MODELS.join(", ")));
646 }
647 let root = models_dir();
648 let part = root.join(format!("whisper-{model}.part"));
649 let done = root.join(format!("whisper-{model}"));
650 std::fs::create_dir_all(&part).map_err(|e| format!("cannot create {}: {e}", part.display()))?;
651 let base = format!("https://huggingface.co/openai/whisper-{model}/resolve/main");
652 let total = model_bytes(model) as f64;
653 let have = |dir: &Path| -> u64 {
654 std::fs::read_dir(dir)
655 .map(|d| d.flatten().filter_map(|e| e.metadata().ok()).map(|m| m.len()).sum())
656 .unwrap_or(0)
657 };
658 let files = MODEL_FILES.iter().map(|&(f, need)| (f, need)).chain([(MODEL_OPTIONAL, false)]);
659 for (file, needed) in files {
660 let target = part.join(file);
661 if target.exists() {
662 continue;
663 }
664 let tmp = part.join(format!("{file}.tmp"));
665 let mut child = Command::new("curl")
666 .args(["-fsSL", "--retry", "2", "--connect-timeout", "20", "-o"])
667 .arg(&tmp)
668 .arg(format!("{base}/{file}"))
669 .stdin(Stdio::null())
670 .stdout(Stdio::null())
671 .stderr(Stdio::null())
672 .spawn()
673 .map_err(|e| format!("cannot run curl ({e}): install curl, or copy the model into {}", done.display()))?;
674 let status = loop {
675 if job.cancelled() {
676 let _ = child.kill();
677 let _ = child.wait();
678 let _ = std::fs::remove_file(&tmp);
679 return Err(CANCELLED.into());
680 }
681 if let Some(status) = child.try_wait().map_err(|e| e.to_string())? {
682 break status;
683 }
684 job.set((have(&part) as f64 / total).min(0.99));
685 std::thread::sleep(std::time::Duration::from_millis(150));
686 };
687 if status.success() {
688 std::fs::rename(&tmp, &target).map_err(|e| format!("cannot save {file}: {e}"))?;
689 } else {
690 let _ = std::fs::remove_file(&tmp);
691 if needed {
692 return Err(format!("could not download {file}: check the internet connection and try again"));
693 }
694 }
695 }
696 std::fs::rename(&part, &done).map_err(|e| format!("cannot finish the download: {e}"))?;
697 job.set(1.0);
698 Ok(())
699}
700
701/// Whether speech can run at all here: the edith-stt binary is built and a model is installed.
702pub fn available() -> Result<(), String> {
703 stt_bin()?;
704 if installed_models().is_empty() {
705 return Err("The speech model is not installed yet.".into());
706 }
707 Ok(())
708}
709
710// ---- hearing the timeline ---------------------------------------------------
711
712/// What to listen to.
713#[derive(Clone, Copy, Debug, PartialEq, Eq)]
714pub enum Hear {
715 /// Every unmuted lane, as an export writes it.
716 Mix,
717 /// One audio lane alone, as the engine plays it (lane gain and ducks not applied).
718 Lane(Lane),
719}
720
721/// One word on the timeline.
722#[derive(Clone, Debug, PartialEq)]
723pub struct Spoken {
724 pub text: String,
725 pub start_f: u32,
726 pub end_f: u32,
727 /// The model's probability for the word.
728 pub p: f64,
729}
730
731/// The audio of `hear` as mono 16 kHz samples of timeline time (a gap is silence), or `None`
732/// when there is no sound at all.
733fn timeline_16k(s: &PlaybackSession, hear: Hear) -> Result<Option<Vec<f32>>, String> {
734 let fps = s.meta().frame_rate;
735 let (rate, ch, chunks): (f64, usize, Box<dyn Iterator<Item = Vec<f32>>>) = match hear {
736 Hear::Lane(lane) => {
737 let Some((meta, rx)) = crate::normalize::open_lane(s, lane, 0, fps)? else {
738 return Ok(None);
739 };
740 (f64::from(meta.sample_rate), usize::from(meta.channels).max(1), Box::new(rx.into_iter().map(|c| c.samples)))
741 }
742 Hear::Mix => {
743 let wav = crate::normalize::render_mix(s)?;
744 let sources = [(wav.0.clone(), 0usize)];
745 let Some((meta, rx)) = AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)])
746 .map_err(|e| format!("reading the mix: {e}"))?
747 else {
748 return Ok(None);
749 };
750 // Drained before the temp file goes: the reader holds it open.
751 let all: Vec<Vec<f32>> = rx.into_iter().map(|c| c.samples).collect();
752 (f64::from(meta.sample_rate), usize::from(meta.channels).max(1), Box::new(all.into_iter()))
753 }
754 };
755 let mut mono = Vec::new();
756 for samples in chunks {
757 for frame in samples.chunks(ch) {
758 mono.push(frame.iter().sum::<f32>() / frame.len() as f32);
759 }
760 }
761 Ok(Some(resample_linear(&mono, rate, f64::from(RATE))))
762}
763
764/// A known silence hallucination: Whisper's stock sign-off over audio the model doubts is speech.
765fn silence_hallucination(text: &str, no_speech: Option<f64>, avg_logprob: Option<f64>) -> bool {
766 const STOCK: &[&str] = &["thank you", "thank you for watching", "thanks for watching", "you"];
767 let t = text.split_whitespace().map(norm).filter(|w| !w.is_empty()).collect::<Vec<_>>().join(" ");
768 STOCK.contains(&t.as_str()) && (no_speech.is_some_and(|p| p >= 0.5) || avg_logprob.is_some_and(|lp| lp < -1.0))
769}
770
771/// What is said in `hear`, word by word, in timeline frames. `fillers` asks Whisper to keep its
772/// disfluencies ([`FILLER_PROMPT`]); without it the model tends to drop them. The model runs on
773/// a worker thread of the caller's choosing: this blocks until it is done or `job` is cancelled.
774pub fn transcribe(s: &PlaybackSession, hear: Hear, model: &str, lang: &str, fillers: bool, job: &Job) -> Result<Vec<Spoken>, String> {
775 listen(prepare(s, hear)?, model, lang, fillers, job)
776}
777
778/// The sound of `hear` as the speech model takes it, read off the session. Split from
779/// [`listen`] so a window can read the sound where the session is and run the model on a thread.
780pub struct Heard {
781 samples: Vec<f32>,
782 fps: f64,
783 label: String,
784}
785
786/// Reads what [`transcribe`] listens to: the timeline's sound at 16 kHz mono.
787pub fn prepare(s: &PlaybackSession, hear: Hear) -> Result<Heard, String> {
788 let samples = timeline_16k(s, hear)?.ok_or("there is no sound to listen to")?;
789 if samples.iter().all(|x| x.abs() < 1e-4) {
790 return Err("the sound is silent: there is nothing to transcribe".into());
791 }
792 let label = match hear {
793 Hear::Mix => "the mix".to_string(),
794 Hear::Lane(l) => l.label(),
795 };
796 Ok(Heard { samples, fps: s.meta().frame_rate, label })
797}
798
799/// Runs the speech model over what [`prepare`] read. Needs no session, so it can run anywhere.
800pub fn listen(heard: Heard, model: &str, lang: &str, fillers: bool, job: &Job) -> Result<Vec<Spoken>, String> {
801 let bin = stt_bin()?;
802 check_model(model)?;
803 check_lang(lang)?;
804 let fps = heard.fps;
805 if job.cancelled() {
806 return Err(CANCELLED.into());
807 }
808 let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos());
809 let wav = std::env::temp_dir().join(format!("edith-speech-{}-{nanos}.wav", std::process::id()));
810 std::fs::write(&wav, wav_bytes(&heard.samples)).map_err(|e| format!("writing {}: {e}", wav.display()))?;
811 let guard = TempFile(wav.clone());
812 let hint = if fillers { FILLER_PROMPT } else { "" };
813 let raw = run_stt(&bin, &wav, model, lang, hint, 0.0, &heard.label, job);
814 drop(guard);
815 let mut words = Vec::new();
816 for seg in parse_raw(&raw?)? {
817 if seg.text.is_empty() || silence_hallucination(&seg.text, seg.no_speech, seg.avg_logprob) {
818 continue;
819 }
820 for w in seg.words.iter().filter(|w| !w.w.is_empty()) {
821 let start_f = (w.start * fps).round().max(0.0) as u32;
822 words.push(Spoken { text: w.w.clone(), start_f, end_f: ((w.end * fps).round() as u32).max(start_f), p: w.p });
823 }
824 }
825 Ok(words)
826}
827
828struct TempFile(PathBuf);
829
830impl Drop for TempFile {
831 fn drop(&mut self) {
832 let _ = std::fs::remove_file(&self.0);
833 }
834}
835
836// ---- captions ---------------------------------------------------------------
837
838/// The characters per line and seconds per cue captions default to.
839pub const CAPTION_MAX_CHARS: usize = 42;
840pub const CAPTION_MAX_SECS: f64 = 6.0;
841
842/// Caption cues for `words`: disfluencies left out, cut at pauses and at the length limits, a
843/// trailing hallucination dropped, short cues folded, sentence starts capitalised, and each cue
844/// given its words' real times.
845pub fn captions(words: &[Spoken], fps: f64) -> Vec<subtitle::Cue> {
846 let us = |f: u32| (f64::from(f) / fps * 1e6).round() as i64;
847 let timed: Vec<(i64, i64, String, f64)> = words
848 .iter()
849 .filter(|w| !CAPTION_FILLERS.contains(&norm(&w.text).as_str()))
850 .map(|w| (us(w.start_f), us(w.end_f), w.text.clone(), w.p))
851 .collect();
852 if timed.is_empty() {
853 return Vec::new();
854 }
855 let owners = vec![0; timed.len()];
856 let (mut cues, _, _) = caption_cues(&timed, &owners, CAPTION_MAX_CHARS, CAPTION_MAX_SECS, CAPTION_GAP_SECS);
857 capitalise_sentence_starts(&mut cues, &[]);
858 attach_word_times(&mut cues, &timed);
859 cues
860}
861
862/// Puts `cues` on caption lane `lane` as a new subtitle track, written to `srt` first (the track
863/// is a file, as every subtitle track is). One undo step. Returns the track's index.
864pub fn place_captions(s: &mut PlaybackSession, cues: &[subtitle::Cue], lane: Lane, srt: &Path) -> Result<usize, String> {
865 use crate::project::{LaneKind, SubClip};
866 if lane.kind != LaneKind::Subtitle {
867 return Err(format!("{} is not a caption lane; captions go on S1..", lane.label()));
868 }
869 if s.lane_locked(lane) {
870 return Err(format!("lane {} is locked: unlock it first", lane.label()));
871 }
872 let end_us = cues.iter().map(|c| c.end_us).max().unwrap_or(0);
873 if cues.is_empty() || end_us <= 0 {
874 return Err("there are no cues to place".into());
875 }
876 if let Some(dir) = srt.parent() {
877 let _ = std::fs::create_dir_all(dir);
878 }
879 subtitle::save_cues(srt, cues).map_err(|e| format!("writing {}: {e}", srt.display()))?;
880 let fps = s.meta().frame_rate;
881 let pushed = s.history_pushes();
882 s.begin_batch();
883 let placed = (|| -> Result<usize, String> {
884 let added = s.import_subtitles(srt).map_err(|e| format!("importing {}: {e}", srt.display()))?;
885 if added == 0 {
886 return Err(format!("importing {} added no subtitle track", srt.display()));
887 }
888 let want = std::fs::canonicalize(srt).unwrap_or_else(|_| srt.to_path_buf());
889 let track = s
890 .subtitles()
891 .iter()
892 .rposition(|t| std::fs::canonicalize(&t.path).unwrap_or_else(|_| t.path.clone()) == want)
893 .ok_or_else(|| format!("{} was imported but no track for it was found", srt.display()))?;
894 // The transcript's word times ride along: the SRT cannot hold them.
895 s.attach_cue_words(track, cues);
896 let mut guard = 0;
897 while !s.subtitle_lanes().contains(&lane) {
898 guard += 1;
899 if guard > lane.ord + 1 {
900 return Err(format!("{} could not be made", lane.label()));
901 }
902 s.add_lane(LaneKind::Subtitle);
903 }
904 s.place_sub(lane, 0, SubClip::whole_track(track, end_us, fps)).map_err(|e| e.to_string())?;
905 Ok(track)
906 })();
907 s.end_batch();
908 if placed.is_err() && s.history_pushes() > pushed {
909 // A failed attempt leaves nothing behind: take back what it pushed.
910 for _ in pushed..s.history_pushes() {
911 if !s.undo() {
912 break;
913 }
914 }
915 s.clear_redo();
916 }
917 placed
918}
919
920// ---- fillers ----------------------------------------------------------------
921
922/// One filler word found in speech: "um", "uh" and the like.
923#[derive(Clone, Debug, PartialEq)]
924pub struct Filler {
925 pub text: String,
926 pub start_f: u32,
927 pub end_f: u32,
928 /// The span a cut takes: the word padded a little each side, never into its neighbours.
929 pub cut: (u32, u32),
930}
931
932/// The filler words among `words`, in order. A cut span pads the word by `pad` frames each side
933/// but stops at the neighbouring words, and at the timeline `end`.
934pub fn find_fillers(words: &[Spoken], pad: u32, end: u32) -> Vec<Filler> {
935 let mut out = Vec::new();
936 for (i, w) in words.iter().enumerate() {
937 if !CAPTION_FILLERS.contains(&norm(&w.text).as_str()) {
938 continue;
939 }
940 let prev_end = if i == 0 { 0 } else { words[i - 1].end_f };
941 let next_start = words.get(i + 1).map_or(u32::MAX, |n| n.start_f);
942 let a = w.start_f.saturating_sub(pad).max(prev_end.min(w.start_f));
943 let b = w.end_f.saturating_add(pad).min(next_start.max(w.end_f)).min(end.max(w.end_f));
944 out.push(Filler { text: w.text.trim_matches(|c: char| !c.is_alphanumeric()).to_string(), start_f: w.start_f, end_f: w.end_f, cut: (a, b) });
945 }
946 out
947}
948
949/// Cuts the spans of `fillers` out of `lanes`, closing each hole, as one undo step. Returns the
950/// regions cut, `(start, length)` in frames, for [`remap_words`].
951pub fn cut_fillers(s: &mut PlaybackSession, fillers: &[Filler], lanes: &[Lane]) -> Result<Vec<(u32, u32)>, String> {
952 let spans: Vec<(u32, u32)> = fillers.iter().map(|f| f.cut).collect();
953 cut_spans(s, &spans, lanes)
954}
955
956/// Cuts `spans` (`(start, end)` frames, any order, overlaps merged) out of `lanes` and closes
957/// each hole, as one undo step: the one door filler cuts and transcript word cuts share. Returns
958/// the regions cut as `(start, length)`.
959pub fn cut_spans(s: &mut PlaybackSession, spans: &[(u32, u32)], lanes: &[Lane]) -> Result<Vec<(u32, u32)>, String> {
960 let mut spans: Vec<(u32, u32)> = spans.iter().copied().filter(|(a, b)| b > a).collect();
961 spans.sort_unstable();
962 let mut merged: Vec<(u32, u32)> = Vec::new();
963 for (a, b) in spans {
964 match merged.last_mut() {
965 Some(last) if a <= last.1 => last.1 = last.1.max(b),
966 _ => merged.push((a, b)),
967 }
968 }
969 if merged.is_empty() {
970 return Err("there is nothing to cut".into());
971 }
972 // cut_regions takes (start, length).
973 let regions: Vec<(u32, u32)> = merged.iter().map(|&(a, b)| (a, b - a)).collect();
974 s.cut_regions(&regions, lanes).map_err(|e| e.to_string())?;
975 Ok(regions)
976}
977
978/// The span a cut of words `first..=last` takes: from the first word's start to the last word's
979/// end, padded by `pad` frames each side but stopped at the neighbouring words and at the
980/// timeline `end`, so no other speech goes with it.
981pub fn word_span(words: &[Spoken], first: usize, last: usize, pad: u32, end: u32) -> Option<(u32, u32)> {
982 let (a, b) = (words.get(first)?, words.get(last)?);
983 let prev_end = if first == 0 { 0 } else { words[first - 1].end_f };
984 let next_start = words.get(last + 1).map_or(u32::MAX, |n| n.start_f);
985 let from = a.start_f.saturating_sub(pad).max(prev_end.min(a.start_f));
986 let to = b.end_f.saturating_add(pad).min(next_start.max(b.end_f)).min(end.max(b.end_f));
987 Some((from, to))
988}
989
990/// `words` as they stand after `regions` (`(start, length)`, sorted, as [`cut_spans`] returns
991/// them) were cut and closed: a word the cut covers is gone, the rest move up by the time cut
992/// before them.
993pub fn remap_words(words: &[Spoken], regions: &[(u32, u32)]) -> Vec<Spoken> {
994 let moved = |f: u32| -> u32 { f - regions.iter().map(|&(a, len)| f.saturating_sub(a).min(len)).sum::<u32>() };
995 words
996 .iter()
997 .filter(|w| !regions.iter().any(|&(a, len)| w.start_f >= a && w.end_f <= a + len && (w.end_f > w.start_f || w.start_f > a)))
998 .map(|w| Spoken { text: w.text.clone(), start_f: moved(w.start_f), end_f: moved(w.end_f), p: w.p })
999 .collect()
1000}
1001
1002/// Whether `text` is a disfluency ("um", "uh"...): what a transcript view dims.
1003pub fn is_filler(text: &str) -> bool {
1004 CAPTION_FILLERS.contains(&norm(text).as_str())
1005}
1006
1007#[cfg(test)]
1008mod transcript_cut_tests {
1009 use super::*;
1010
1011 fn w(t: &str, a: u32, b: u32) -> Spoken {
1012 Spoken { text: t.into(), start_f: a, end_f: b, p: 0.9 }
1013 }
1014
1015 #[test]
1016 fn a_word_span_pads_but_stops_at_neighbours() {
1017 let ws = [w("so", 10, 20), w("um", 22, 30), w("yes", 31, 40)];
1018 assert_eq!(word_span(&ws, 1, 1, 3, 100), Some((20, 31)));
1019 assert_eq!(word_span(&ws, 0, 1, 3, 100), Some((7, 31)));
1020 assert_eq!(word_span(&ws, 2, 2, 5, 42), Some((30, 42)));
1021 assert_eq!(word_span(&ws, 3, 3, 3, 100), None);
1022 }
1023
1024 #[test]
1025 fn remapping_drops_cut_words_and_closes_the_hole() {
1026 let ws = [w("a", 0, 10), w("b", 12, 20), w("c", 22, 30), w("d", 32, 40)];
1027 let out = remap_words(&ws, &[(11, 10)]);
1028 assert_eq!(out.iter().map(|x| x.text.as_str()).collect::<Vec<_>>(), ["a", "c", "d"]);
1029 assert_eq!((out[1].start_f, out[1].end_f), (12, 20));
1030 assert_eq!((out[2].start_f, out[2].end_f), (22, 30));
1031 let two = remap_words(&ws, &[(11, 10), (31, 9)]);
1032 assert_eq!(two.iter().map(|x| x.text.as_str()).collect::<Vec<_>>(), ["a", "c"]);
1033 assert_eq!(two[1].start_f, 12);
1034 }
1035
1036 #[test]
1037 fn fillers_are_told_by_spelling() {
1038 assert!(is_filler("Um,") && is_filler("uh") && !is_filler("umbrella"));
1039 }
1040}