| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | use std::io::{BufRead, BufReader, Read}; |
| 10 | use std::path::{Path, PathBuf}; |
| 11 | use std::process::{Command, Stdio}; |
| 12 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 13 | |
| 14 | use crate::project::Lane; |
| 15 | use crate::{AudioSession, PlaybackSession, subtitle}; |
| 16 | |
| 17 | |
| 18 | pub const RATE: u32 = 16_000; |
| 19 | |
| 20 | pub const MODELS: &[&str] = &["tiny", "base", "small"]; |
| 21 | |
| 22 | pub const CAPTION_GAP_SECS: f64 = 0.7; |
| 23 | |
| 24 | |
| 25 | pub const FILLER_PROMPT: &str = "Um, uh, so, like, you know, I mean, er, hmm..."; |
| 26 | |
| 27 | pub const CAPTION_FILLERS: &[&str] = &["um", "uhm", "uh", "ah", "hum", "hmm", "er", "erm"]; |
| 28 | |
| 29 | |
| 30 | pub const CUE_MIN_SECS: f64 = 0.8; |
| 31 | |
| 32 | pub const CUE_LOW_P: f64 = 0.5; |
| 33 | |
| 34 | |
| 35 | const SIGN_OFFS: &[&str] = &["thank you", "thanks", "thanks for watching", "thank you for watching", "bye", "bye bye", "see you", "see you next time"]; |
| 36 | |
| 37 | |
| 38 | pub fn norm(w: &str) -> String { |
| 39 | w.trim_matches(|c: char| !c.is_alphanumeric()).to_lowercase() |
| 40 | } |
| 41 | |
| 42 | pub fn home() -> PathBuf { |
| 43 | std::env::var_os("HOME").map_or_else(std::env::temp_dir, PathBuf::from) |
| 44 | } |
| 45 | |
| 46 | |
| 47 | |
| 48 | pub 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 | |
| 65 | pub 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 | |
| 76 | pub 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 | |
| 82 | pub 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)] |
| 87 | pub struct RawWord { |
| 88 | pub w: String, |
| 89 | pub start: f64, |
| 90 | pub end: f64, |
| 91 | pub p: f64, |
| 92 | } |
| 93 | |
| 94 | #[derive(Clone, Debug)] |
| 95 | pub struct RawSeg { |
| 96 | pub start: f64, |
| 97 | pub end: f64, |
| 98 | pub text: String, |
| 99 | pub words: Vec<RawWord>, |
| 100 | |
| 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 | |
| 109 | pub 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 | |
| 129 | pub 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 | |
| 137 | pub 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 | |
| 157 | pub 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 | |
| 161 | pub 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 | |
| 191 | |
| 192 | pub 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 | |
| 201 | |
| 202 | |
| 203 | |
| 204 | |
| 205 | |
| 206 | |
| 207 | pub 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 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 319 | pub 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 | |
| 326 | |
| 327 | |
| 328 | |
| 329 | |
| 330 | pub 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 | |
| 338 | const LOOK_BACK: usize = 40; |
| 339 | |
| 340 | const SHORT: u64 = 10; |
| 341 | let n = words.len(); |
| 342 | |
| 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 | |
| 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 | |
| 374 | |
| 375 | pub 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 | |
| 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 | |
| 402 | pub fn closes_sentence(word: &str) -> bool { |
| 403 | word.trim_end_matches(['"', '\'', ')', ']', '”', '’']) |
| 404 | .ends_with(['.', '!', '?', '…']) |
| 405 | } |
| 406 | |
| 407 | |
| 408 | |
| 409 | pub 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 | |
| 422 | |
| 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 | |
| 430 | pub 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 | |
| 435 | |
| 436 | pub 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 | |
| 449 | pub fn stem(w: &str) -> String { |
| 450 | w.strip_suffix('s').filter(|s| s.len() > 2).unwrap_or(w).to_string() |
| 451 | } |
| 452 | |
| 453 | pub 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 | |
| 459 | |
| 460 | pub 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 | |
| 481 | |
| 482 | |
| 483 | pub 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 | |
| 502 | |
| 503 | |
| 504 | |
| 505 | pub 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 | |
| 519 | |
| 520 | |
| 521 | |
| 522 | #[derive(Debug, Default)] |
| 523 | pub struct Job { |
| 524 | |
| 525 | pub permille: std::sync::atomic::AtomicU32, |
| 526 | pub cancel: AtomicBool, |
| 527 | } |
| 528 | |
| 529 | impl Job { |
| 530 | |
| 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 | |
| 545 | pub const CANCELLED: &str = "cancelled"; |
| 546 | |
| 547 | |
| 548 | |
| 549 | |
| 550 | #[allow(clippy::too_many_arguments)] |
| 551 | pub 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 | |
| 612 | pub fn installed_models() -> Vec<&'static str> { |
| 613 | MODELS.iter().copied().filter(|m| check_model(m).is_ok()).collect() |
| 614 | } |
| 615 | |
| 616 | |
| 617 | pub fn models_dir() -> PathBuf { |
| 618 | home().join(".cache/edith/models") |
| 619 | } |
| 620 | |
| 621 | |
| 622 | const MODEL_FILES: [(&str, bool); 4] = [ |
| 623 | ("config.json", true), |
| 624 | ("model.safetensors", true), |
| 625 | ("tokenizer.json", true), |
| 626 | ("preprocessor_config.json", true), |
| 627 | ]; |
| 628 | const MODEL_OPTIONAL: &str = "generation_config.json"; |
| 629 | |
| 630 | |
| 631 | pub 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 | |
| 640 | |
| 641 | |
| 642 | |
| 643 | pub 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 | |
| 702 | pub 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 | |
| 711 | |
| 712 | |
| 713 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 714 | pub enum Hear { |
| 715 | |
| 716 | Mix, |
| 717 | |
| 718 | Lane(Lane), |
| 719 | } |
| 720 | |
| 721 | |
| 722 | #[derive(Clone, Debug, PartialEq)] |
| 723 | pub struct Spoken { |
| 724 | pub text: String, |
| 725 | pub start_f: u32, |
| 726 | pub end_f: u32, |
| 727 | |
| 728 | pub p: f64, |
| 729 | } |
| 730 | |
| 731 | |
| 732 | |
| 733 | fn 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 | |
| 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 | |
| 765 | fn 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 | |
| 772 | |
| 773 | |
| 774 | pub 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 | |
| 779 | |
| 780 | pub struct Heard { |
| 781 | samples: Vec<f32>, |
| 782 | fps: f64, |
| 783 | label: String, |
| 784 | } |
| 785 | |
| 786 | |
| 787 | pub 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 | |
| 800 | pub 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 | |
| 828 | struct TempFile(PathBuf); |
| 829 | |
| 830 | impl Drop for TempFile { |
| 831 | fn drop(&mut self) { |
| 832 | let _ = std::fs::remove_file(&self.0); |
| 833 | } |
| 834 | } |
| 835 | |
| 836 | |
| 837 | |
| 838 | |
| 839 | pub const CAPTION_MAX_CHARS: usize = 42; |
| 840 | pub const CAPTION_MAX_SECS: f64 = 6.0; |
| 841 | |
| 842 | |
| 843 | |
| 844 | |
| 845 | pub 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 | |
| 863 | |
| 864 | pub 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 | |
| 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 | |
| 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 | |
| 921 | |
| 922 | |
| 923 | #[derive(Clone, Debug, PartialEq)] |
| 924 | pub struct Filler { |
| 925 | pub text: String, |
| 926 | pub start_f: u32, |
| 927 | pub end_f: u32, |
| 928 | |
| 929 | pub cut: (u32, u32), |
| 930 | } |
| 931 | |
| 932 | |
| 933 | |
| 934 | pub 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 | |
| 950 | |
| 951 | pub 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 | |
| 957 | |
| 958 | |
| 959 | pub 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 | |
| 973 | let regions: Vec<(u32, u32)> = merged.iter().map(|&(a, b)| (a, b - a)).collect(); |
| 974 | s.cut_regions(®ions, lanes).map_err(|e| e.to_string())?; |
| 975 | Ok(regions) |
| 976 | } |
| 977 | |
| 978 | |
| 979 | |
| 980 | |
| 981 | pub 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 | |
| 991 | |
| 992 | |
| 993 | pub 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 | |
| 1003 | pub fn is_filler(text: &str) -> bool { |
| 1004 | CAPTION_FILLERS.contains(&norm(text).as_str()) |
| 1005 | } |
| 1006 | |
| 1007 | #[cfg(test)] |
| 1008 | mod 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 | } |