| 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::OnceLock; |
| 13 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 14 | |
| 15 | use crate::project::Lane; |
| 16 | use crate::{AudioSession, PlaybackSession, subtitle}; |
| 17 | |
| 18 | |
| 19 | pub const RATE: u32 = 16_000; |
| 20 | |
| 21 | pub const MODELS: &[&str] = &["tiny", "base", "small", "medium", "large-v3", "large-v3-turbo"]; |
| 22 | |
| 23 | pub const CAPTION_GAP_SECS: f64 = 0.7; |
| 24 | |
| 25 | |
| 26 | pub const FILLER_PROMPT: &str = "Um, uh, so, like, you know, I mean, er, hmm..."; |
| 27 | |
| 28 | pub const CAPTION_FILLERS: &[&str] = &["um", "uhm", "uh", "ah", "hum", "hmm", "er", "erm"]; |
| 29 | |
| 30 | |
| 31 | pub const CUE_MIN_SECS: f64 = 0.8; |
| 32 | |
| 33 | pub const CUE_LOW_P: f64 = 0.5; |
| 34 | |
| 35 | |
| 36 | const SIGN_OFFS: &[&str] = &["thank you", "thanks", "thanks for watching", "thank you for watching", "bye", "bye bye", "see you", "see you next time"]; |
| 37 | |
| 38 | |
| 39 | pub fn norm(w: &str) -> String { |
| 40 | w.trim_matches(|c: char| !c.is_alphanumeric()).to_lowercase() |
| 41 | } |
| 42 | |
| 43 | pub fn home() -> PathBuf { |
| 44 | std::env::var_os("HOME").map_or_else(std::env::temp_dir, PathBuf::from) |
| 45 | } |
| 46 | |
| 47 | |
| 48 | |
| 49 | pub fn stt_bin() -> Result<PathBuf, String> { |
| 50 | const NOT_BUILT: &str = "edith-stt is not built. Run `cd tools/edith-stt && cargo build --release` (`--features vulkan` for the GPU) in the edith repo, or set EDITH_STT_BIN to the binary"; |
| 51 | if let Some(p) = std::env::var_os("EDITH_STT_BIN") { |
| 52 | let p = PathBuf::from(p); |
| 53 | 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())) }; |
| 54 | } |
| 55 | if let Ok(exe) = std::env::current_exe() { |
| 56 | for dir in exe.ancestors() { |
| 57 | let c = dir.join("tools/edith-stt/target/release/edith-stt"); |
| 58 | if c.is_file() { |
| 59 | return Ok(c); |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 | Err(NOT_BUILT.into()) |
| 64 | } |
| 65 | |
| 66 | |
| 67 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 68 | pub enum Device { |
| 69 | Cpu, |
| 70 | Gpu, |
| 71 | } |
| 72 | |
| 73 | impl Device { |
| 74 | |
| 75 | pub fn flag(self) -> &'static str { |
| 76 | match self { |
| 77 | Self::Cpu => "cpu", |
| 78 | Self::Gpu => "gpu", |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | |
| 84 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 85 | pub enum DeviceChoice { |
| 86 | #[default] |
| 87 | Auto, |
| 88 | Cpu, |
| 89 | Gpu, |
| 90 | } |
| 91 | |
| 92 | impl DeviceChoice { |
| 93 | pub fn parse(s: &str) -> Option<Self> { |
| 94 | match s { |
| 95 | "auto" => Some(Self::Auto), |
| 96 | "cpu" => Some(Self::Cpu), |
| 97 | "gpu" => Some(Self::Gpu), |
| 98 | _ => None, |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | pub fn as_str(self) -> &'static str { |
| 103 | match self { |
| 104 | Self::Auto => "auto", |
| 105 | Self::Cpu => "cpu", |
| 106 | Self::Gpu => "gpu", |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | |
| 111 | |
| 112 | pub fn resolve(self, model: &str) -> Device { |
| 113 | match self { |
| 114 | Self::Cpu => Device::Cpu, |
| 115 | Self::Gpu => Device::Gpu, |
| 116 | Self::Auto if gpu_available() && check_model(model, Device::Gpu).is_ok() => Device::Gpu, |
| 117 | Self::Auto => Device::Cpu, |
| 118 | } |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | |
| 123 | |
| 124 | pub fn gpu_available() -> bool { |
| 125 | static GPU: OnceLock<bool> = OnceLock::new(); |
| 126 | *GPU.get_or_init(|| { |
| 127 | stt_bin().is_ok_and(|bin| { |
| 128 | Command::new(bin) |
| 129 | .arg("--has-gpu") |
| 130 | .stdin(Stdio::null()) |
| 131 | .stdout(Stdio::null()) |
| 132 | .stderr(Stdio::null()) |
| 133 | .status() |
| 134 | .is_ok_and(|st| st.success()) |
| 135 | }) |
| 136 | }) |
| 137 | } |
| 138 | |
| 139 | |
| 140 | |
| 141 | pub fn model_path(model: &str, device: Device) -> PathBuf { |
| 142 | match device { |
| 143 | Device::Cpu => models_dir().join(format!("whisper-{model}")), |
| 144 | Device::Gpu => models_dir().join(format!("ggml-{model}.bin")), |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | pub fn check_model(model: &str, device: Device) -> Result<(), String> { |
| 149 | if !MODELS.contains(&model) { |
| 150 | return Err(format!("model `{model}` is not one of {}", MODELS.join(", "))); |
| 151 | } |
| 152 | let at = model_path(model, device); |
| 153 | let there = match device { |
| 154 | Device::Cpu => at.is_dir(), |
| 155 | Device::Gpu => at.is_file(), |
| 156 | }; |
| 157 | if !there { |
| 158 | return Err(format!("the {model} model ({}) is not installed at {}; edith-stt downloads it only when asked to", device.flag(), at.display())); |
| 159 | } |
| 160 | Ok(()) |
| 161 | } |
| 162 | |
| 163 | pub fn check_lang(lang: &str) -> Result<(), String> { |
| 164 | let ok = lang == "auto" || ((2..=3).contains(&lang.len()) && lang.chars().all(|c| c.is_ascii_lowercase())); |
| 165 | if ok { Ok(()) } else { Err(format!("language `{lang}` must be auto or a language code such as en")) } |
| 166 | } |
| 167 | |
| 168 | |
| 169 | pub fn pick_model(installed: impl Fn(&str) -> bool, device: Device) -> Option<&'static str> { |
| 170 | let order: [&'static str; 6] = match device { |
| 171 | Device::Gpu => ["large-v3-turbo", "large-v3", "medium", "small", "base", "tiny"], |
| 172 | Device::Cpu => ["base", "small", "tiny", "medium", "large-v3-turbo", "large-v3"], |
| 173 | }; |
| 174 | order.into_iter().find(|m| installed(m)) |
| 175 | } |
| 176 | |
| 177 | |
| 178 | |
| 179 | pub fn plan(choice: DeviceChoice, model: Option<&str>) -> Option<(String, Device)> { |
| 180 | if let Some(m) = model { |
| 181 | return Some((m.to_string(), choice.resolve(m))); |
| 182 | } |
| 183 | let on = |d: Device| move |m: &str| check_model(m, d).is_ok(); |
| 184 | let gpu = || pick_model(on(Device::Gpu), Device::Gpu).map(|m| (m.to_string(), Device::Gpu)); |
| 185 | let cpu = || pick_model(on(Device::Cpu), Device::Cpu).map(|m| (m.to_string(), Device::Cpu)); |
| 186 | match choice { |
| 187 | DeviceChoice::Cpu => cpu(), |
| 188 | DeviceChoice::Gpu => gpu(), |
| 189 | DeviceChoice::Auto if gpu_available() => gpu().or_else(cpu), |
| 190 | DeviceChoice::Auto => cpu(), |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | #[derive(Clone, Debug)] |
| 195 | pub struct RawWord { |
| 196 | pub w: String, |
| 197 | pub start: f64, |
| 198 | pub end: f64, |
| 199 | pub p: f64, |
| 200 | } |
| 201 | |
| 202 | #[derive(Clone, Debug)] |
| 203 | pub struct RawSeg { |
| 204 | pub start: f64, |
| 205 | pub end: f64, |
| 206 | pub text: String, |
| 207 | pub words: Vec<RawWord>, |
| 208 | |
| 209 | pub approx: bool, |
| 210 | pub no_speech: Option<f64>, |
| 211 | pub avg_logprob: Option<f64>, |
| 212 | pub span_db: Option<f64>, |
| 213 | } |
| 214 | |
| 215 | |
| 216 | |
| 217 | pub fn resample_linear(input: &[f32], src: f64, dst: f64) -> Vec<f32> { |
| 218 | if input.is_empty() || src <= 0.0 || dst <= 0.0 { |
| 219 | return Vec::new(); |
| 220 | } |
| 221 | if (src - dst).abs() < 0.5 { |
| 222 | return input.to_vec(); |
| 223 | } |
| 224 | let n = (input.len() as f64 * dst / src).round() as usize; |
| 225 | (0..n) |
| 226 | .map(|i| { |
| 227 | let pos = i as f64 * src / dst; |
| 228 | let idx = pos.floor() as usize; |
| 229 | let frac = (pos - idx as f64) as f32; |
| 230 | let a = input.get(idx).copied().unwrap_or(0.0); |
| 231 | let b = input.get(idx + 1).copied().unwrap_or(a); |
| 232 | a + (b - a) * frac |
| 233 | }) |
| 234 | .collect() |
| 235 | } |
| 236 | |
| 237 | pub fn i16_bytes(samples: &[f32]) -> Vec<u8> { |
| 238 | samples |
| 239 | .iter() |
| 240 | .flat_map(|s| ((s.clamp(-1.0, 1.0) * 32767.0).round() as i16).to_le_bytes()) |
| 241 | .collect() |
| 242 | } |
| 243 | |
| 244 | |
| 245 | pub fn wav_bytes(samples: &[f32]) -> Vec<u8> { |
| 246 | let data = i16_bytes(samples); |
| 247 | let len = data.len() as u32; |
| 248 | let mut b = Vec::with_capacity(44 + data.len()); |
| 249 | b.extend_from_slice(b"RIFF"); |
| 250 | b.extend_from_slice(&(36 + len).to_le_bytes()); |
| 251 | b.extend_from_slice(b"WAVEfmt "); |
| 252 | b.extend_from_slice(&16u32.to_le_bytes()); |
| 253 | b.extend_from_slice(&1u16.to_le_bytes()); |
| 254 | b.extend_from_slice(&1u16.to_le_bytes()); |
| 255 | b.extend_from_slice(&RATE.to_le_bytes()); |
| 256 | b.extend_from_slice(&(RATE * 2).to_le_bytes()); |
| 257 | b.extend_from_slice(&2u16.to_le_bytes()); |
| 258 | b.extend_from_slice(&16u16.to_le_bytes()); |
| 259 | b.extend_from_slice(b"data"); |
| 260 | b.extend_from_slice(&len.to_le_bytes()); |
| 261 | b.extend_from_slice(&data); |
| 262 | b |
| 263 | } |
| 264 | |
| 265 | pub fn num(v: &serde_json::Value, k: &str) -> Result<f64, String> { |
| 266 | v.get(k).and_then(serde_json::Value::as_f64).ok_or_else(|| format!("edith-stt line has no `{k}` number")) |
| 267 | } |
| 268 | |
| 269 | pub fn parse_raw(raw: &str) -> Result<Vec<RawSeg>, String> { |
| 270 | let mut out = Vec::new(); |
| 271 | for line in raw.lines().filter(|l| !l.trim().is_empty()) { |
| 272 | let v: serde_json::Value = serde_json::from_str(line).map_err(|e| format!("edith-stt printed a line that is not JSON: {e}"))?; |
| 273 | let mut words = Vec::new(); |
| 274 | if let Some(arr) = v.get("words").and_then(serde_json::Value::as_array) { |
| 275 | for w in arr { |
| 276 | words.push(RawWord { |
| 277 | w: w.get("w").and_then(serde_json::Value::as_str).unwrap_or("").trim().to_string(), |
| 278 | start: num(w, "start")?, |
| 279 | end: num(w, "end")?, |
| 280 | p: w.get("p").and_then(serde_json::Value::as_f64).unwrap_or(0.0), |
| 281 | }); |
| 282 | } |
| 283 | } |
| 284 | out.push(RawSeg { |
| 285 | start: num(&v, "start")?, |
| 286 | end: num(&v, "end")?, |
| 287 | text: v.get("text").and_then(serde_json::Value::as_str).unwrap_or("").trim().to_string(), |
| 288 | words, |
| 289 | approx: v.get("approx").and_then(serde_json::Value::as_bool).unwrap_or(true), |
| 290 | no_speech: v.get("no_speech").and_then(serde_json::Value::as_f64), |
| 291 | avg_logprob: v.get("avg_logprob").and_then(serde_json::Value::as_f64), |
| 292 | span_db: v.get("span_db").and_then(serde_json::Value::as_f64), |
| 293 | }); |
| 294 | } |
| 295 | Ok(out) |
| 296 | } |
| 297 | |
| 298 | |
| 299 | |
| 300 | pub struct Cap { |
| 301 | pub start_us: i64, |
| 302 | pub end_us: i64, |
| 303 | pub words: Vec<(String, f64)>, |
| 304 | pub text: String, |
| 305 | pub owner: u32, |
| 306 | } |
| 307 | |
| 308 | |
| 309 | |
| 310 | |
| 311 | |
| 312 | |
| 313 | |
| 314 | |
| 315 | pub fn caption_cues( |
| 316 | words: &[(i64, i64, String, f64)], |
| 317 | owners: &[u32], |
| 318 | max_chars: usize, |
| 319 | max_secs: f64, |
| 320 | gap_secs: f64, |
| 321 | ) -> (Vec<subtitle::Cue>, Vec<String>, Vec<String>) { |
| 322 | let mut skipped: Vec<String> = Vec::new(); |
| 323 | let mut order: Vec<usize> = (0..words.len()).filter(|&i| !words[i].2.trim().is_empty()).collect(); |
| 324 | order.sort_by_key(|&i| words[i].0); |
| 325 | let sorted: Vec<&(i64, i64, String, f64)> = order.iter().map(|&i| &words[i]).collect(); |
| 326 | let own: Vec<u32> = order.iter().map(|&i| owners.get(i).copied().unwrap_or(0)).collect(); |
| 327 | let min_us = (CUE_MIN_SECS * 1e6) as i64; |
| 328 | |
| 329 | let mut groups: Vec<Vec<usize>> = Vec::new(); |
| 330 | let mut r0 = 0; |
| 331 | for r1 in 1..=sorted.len() { |
| 332 | if r1 == sorted.len() || own[r1] != own[r0] { |
| 333 | for g in partition(&sorted[r0..r1], max_chars, max_secs, gap_secs, min_us) { |
| 334 | groups.push(g.into_iter().map(|i| i + r0).collect()); |
| 335 | } |
| 336 | r0 = r1; |
| 337 | } |
| 338 | } |
| 339 | let mut caps: Vec<Cap> = groups |
| 340 | .iter() |
| 341 | .filter(|g| !g.is_empty()) |
| 342 | .map(|g| { |
| 343 | let ws: Vec<(String, f64)> = g.iter().map(|&i| (sorted[i].2.trim().to_string(), sorted[i].3)).collect(); |
| 344 | let start_us = sorted[g[0]].0; |
| 345 | let end_us = sorted[g[g.len() - 1]].1.max(start_us); |
| 346 | Cap { start_us, end_us, text: caption_text(&ws, max_chars), words: ws, owner: own[g[0]] } |
| 347 | }) |
| 348 | .collect(); |
| 349 | if caps.len() > 1 { |
| 350 | let last = caps.len() - 1; |
| 351 | if let Some(why) = hallucination(&caps[last], &caps[last - 1]) { |
| 352 | let c = caps.pop().expect("a last cue"); |
| 353 | skipped.push(format!( |
| 354 | "\"{}\" ({:.3}s–{:.3}s): {why}", |
| 355 | c.text.replace('\n', " / "), |
| 356 | c.start_us as f64 / 1e6, |
| 357 | c.end_us as f64 / 1e6 |
| 358 | )); |
| 359 | } |
| 360 | } |
| 361 | let mut i = 0; |
| 362 | while caps.len() > 1 && i < caps.len() { |
| 363 | if !is_short_cue(&caps[i], min_us) { |
| 364 | i += 1; |
| 365 | continue; |
| 366 | } |
| 367 | let before = (i > 0).then(|| caps[i].start_us - caps[i - 1].end_us); |
| 368 | let after = (i + 1 < caps.len()).then(|| caps[i + 1].start_us - caps[i].end_us); |
| 369 | let prev_nearer = match (before, after) { |
| 370 | (Some(b), Some(a)) => b <= a, |
| 371 | (Some(_), None) => true, |
| 372 | _ => false, |
| 373 | }; |
| 374 | let can_prev = i > 0 && fits_merged(&caps[i - 1], &caps[i], max_chars, max_secs); |
| 375 | let can_next = i + 1 < caps.len() && fits_merged(&caps[i], &caps[i + 1], max_chars, max_secs); |
| 376 | let into_prev = can_prev && (prev_nearer || !can_next); |
| 377 | if into_prev || can_next { |
| 378 | let cur = caps.remove(i); |
| 379 | |
| 380 | if into_prev { |
| 381 | let p = &mut caps[i - 1]; |
| 382 | p.end_us = p.end_us.max(cur.end_us); |
| 383 | p.words.extend(cur.words); |
| 384 | p.text = caption_text(&p.words, max_chars); |
| 385 | } else { |
| 386 | let n = &mut caps[i]; |
| 387 | n.start_us = n.start_us.min(cur.start_us); |
| 388 | let mut ws = cur.words; |
| 389 | ws.append(&mut n.words); |
| 390 | n.words = ws; |
| 391 | n.text = caption_text(&n.words, max_chars); |
| 392 | } |
| 393 | } else { |
| 394 | |
| 395 | let next_start = caps.get(i + 1).map_or(i64::MAX, |c| c.start_us); |
| 396 | let c = &mut caps[i]; |
| 397 | c.end_us = c.end_us.max((c.start_us + min_us).min(next_start)); |
| 398 | i += 1; |
| 399 | } |
| 400 | } |
| 401 | for i in 0..caps.len().saturating_sub(1) { |
| 402 | let next = caps[i + 1].start_us; |
| 403 | let c = &mut caps[i]; |
| 404 | c.end_us = c.end_us.min(next).max(c.start_us); |
| 405 | } |
| 406 | |
| 407 | let mut short: Vec<String> = Vec::new(); |
| 408 | if caps.len() > 1 { |
| 409 | for c in caps.iter().filter(|c| c.end_us - c.start_us < min_us) { |
| 410 | short.push(format!( |
| 411 | "\"{}\" ({:.3}s–{:.3}s, {:.2} s)", |
| 412 | c.text.replace('\n', " / "), |
| 413 | c.start_us as f64 / 1e6, |
| 414 | c.end_us as f64 / 1e6, |
| 415 | (c.end_us - c.start_us) as f64 / 1e6 |
| 416 | )); |
| 417 | } |
| 418 | } |
| 419 | let cues = caps |
| 420 | .into_iter() |
| 421 | .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() }) |
| 422 | .collect(); |
| 423 | (cues, skipped, short) |
| 424 | } |
| 425 | |
| 426 | |
| 427 | pub fn speaker_changes(words: &[(i64, i64, String, f64)], owners: &[u32]) -> usize { |
| 428 | let mut order: Vec<usize> = (0..words.len()).collect(); |
| 429 | order.sort_by_key(|&i| words[i].0); |
| 430 | order.windows(2).filter(|p| owners.get(p[0]) != owners.get(p[1])).count() |
| 431 | } |
| 432 | |
| 433 | |
| 434 | |
| 435 | |
| 436 | |
| 437 | |
| 438 | pub fn partition( |
| 439 | words: &[&(i64, i64, String, f64)], |
| 440 | max_chars: usize, |
| 441 | max_secs: f64, |
| 442 | gap_secs: f64, |
| 443 | min_us: i64, |
| 444 | ) -> Vec<Vec<usize>> { |
| 445 | |
| 446 | const LOOK_BACK: usize = 40; |
| 447 | |
| 448 | const SHORT: u64 = 10; |
| 449 | let n = words.len(); |
| 450 | |
| 451 | let mut best: Vec<(u64, usize)> = vec![(u64::MAX, 0); n + 1]; |
| 452 | best[0] = (0, 0); |
| 453 | for j in 1..=n { |
| 454 | for i in (j.saturating_sub(LOOK_BACK)..j).rev() { |
| 455 | |
| 456 | if i + 1 < j && !cue_valid(&words[i..j], max_chars, max_secs, gap_secs) { |
| 457 | break; |
| 458 | } |
| 459 | if best[i].0 == u64::MAX { |
| 460 | continue; |
| 461 | } |
| 462 | let dur = words[j - 1].1 - words[i].0; |
| 463 | let cost = 1 + if dur < min_us { SHORT * 10 } else { 0 }; |
| 464 | let total = best[i].0 + cost; |
| 465 | if total < best[j].0 { |
| 466 | best[j] = (total, i); |
| 467 | } |
| 468 | } |
| 469 | } |
| 470 | let mut groups: Vec<Vec<usize>> = Vec::new(); |
| 471 | let mut j = n; |
| 472 | while j > 0 { |
| 473 | let i = best[j].1; |
| 474 | groups.push((i..j).collect()); |
| 475 | j = i; |
| 476 | } |
| 477 | groups.reverse(); |
| 478 | groups |
| 479 | } |
| 480 | |
| 481 | |
| 482 | |
| 483 | pub fn cue_valid(ws: &[&(i64, i64, String, f64)], max_chars: usize, max_secs: f64, gap_secs: f64) -> bool { |
| 484 | if ws.len() <= 1 { |
| 485 | return true; |
| 486 | } |
| 487 | let gap_us = (gap_secs * 1e6) as i64; |
| 488 | let max_us = (max_secs * 1e6) as i64; |
| 489 | if ws.windows(2).any(|p| p[1].0 - p[0].1 > gap_us) { |
| 490 | return false; |
| 491 | } |
| 492 | if ws[..ws.len() - 1].iter().any(|w| closes_sentence(&w.2)) { |
| 493 | return false; |
| 494 | } |
| 495 | if ws[ws.len() - 1].1 - ws[0].0 > max_us { |
| 496 | return false; |
| 497 | } |
| 498 | |
| 499 | let lens: Vec<usize> = ws.iter().map(|w| w.2.trim().chars().count()).collect(); |
| 500 | let total: usize = lens.iter().sum::<usize>() + lens.len() - 1; |
| 501 | let mut head = 0usize; |
| 502 | (1..ws.len()).any(|k| { |
| 503 | head += lens[k - 1] + usize::from(k > 1); |
| 504 | let tail = total - head - 1; |
| 505 | head <= max_chars && tail <= max_chars |
| 506 | }) |
| 507 | } |
| 508 | |
| 509 | |
| 510 | pub fn closes_sentence(word: &str) -> bool { |
| 511 | word.trim_end_matches(['"', '\'', ')', ']', '”', '’']) |
| 512 | .ends_with(['.', '!', '?', '…']) |
| 513 | } |
| 514 | |
| 515 | |
| 516 | |
| 517 | pub fn hallucination(cap: &Cap, prev: &Cap) -> Option<&'static str> { |
| 518 | if cap.words.is_empty() { |
| 519 | return None; |
| 520 | } |
| 521 | let mean = cap.words.iter().map(|w| w.1).sum::<f64>() / cap.words.len() as f64; |
| 522 | if mean < CUE_LOW_P { |
| 523 | return Some("low confidence, the model was unsure of these words"); |
| 524 | } |
| 525 | let key = |ws: &[(String, f64)]| -> Vec<String> { |
| 526 | ws.iter().map(|w| stem(&norm(&w.0))).filter(|w| !w.is_empty()).collect() |
| 527 | }; |
| 528 | let (mine, theirs) = (key(&cap.words), key(&prev.words)); |
| 529 | |
| 530 | |
| 531 | if !mine.is_empty() && theirs.windows(mine.len()).any(|w| w == mine.as_slice()) { |
| 532 | return Some("repeats the words of the cue before"); |
| 533 | } |
| 534 | (sign_off(cap) && sign_off(prev)).then_some("a second sign-off after one") |
| 535 | } |
| 536 | |
| 537 | |
| 538 | pub fn is_short_cue(c: &Cap, min_us: i64) -> bool { |
| 539 | c.end_us - c.start_us < min_us || c.words.len() == 1 |
| 540 | } |
| 541 | |
| 542 | |
| 543 | |
| 544 | pub fn fits_merged(a: &Cap, b: &Cap, max_chars: usize, max_secs: f64) -> bool { |
| 545 | if a.owner != b.owner { |
| 546 | return false; |
| 547 | } |
| 548 | let span = (a.end_us.max(b.end_us) - a.start_us.min(b.start_us)) as f64 / 1e6; |
| 549 | if span > max_secs { |
| 550 | return false; |
| 551 | } |
| 552 | let words: Vec<(String, f64)> = a.words.iter().chain(b.words.iter()).cloned().collect(); |
| 553 | caption_text(&words, max_chars).lines().all(|l| l.chars().count() <= max_chars) |
| 554 | } |
| 555 | |
| 556 | |
| 557 | pub fn stem(w: &str) -> String { |
| 558 | w.strip_suffix('s').filter(|s| s.len() > 2).unwrap_or(w).to_string() |
| 559 | } |
| 560 | |
| 561 | pub fn sign_off(cap: &Cap) -> bool { |
| 562 | let text = cap.words.iter().map(|w| norm(&w.0)).filter(|w| !w.is_empty()).collect::<Vec<_>>().join(" "); |
| 563 | SIGN_OFFS.contains(&text.as_str()) |
| 564 | } |
| 565 | |
| 566 | |
| 567 | |
| 568 | pub fn caption_text(words: &[(String, f64)], max_chars: usize) -> String { |
| 569 | let ws: Vec<&str> = words.iter().map(|w| w.0.as_str()).collect(); |
| 570 | let len = |s: &[&str]| s.iter().map(|w| w.chars().count()).sum::<usize>() + s.len().saturating_sub(1); |
| 571 | let total = len(&ws); |
| 572 | if total <= max_chars || ws.len() < 2 { |
| 573 | return ws.join(" "); |
| 574 | } |
| 575 | let middle = total as i64 / 2; |
| 576 | let mut best: Option<(usize, (usize, i64))> = None; |
| 577 | for k in 1..ws.len() { |
| 578 | let (a, b) = (len(&ws[..k]), len(&ws[k..])); |
| 579 | let score = (a.max(b), (a as i64 - middle).abs()); |
| 580 | if best.is_none_or(|(_, s)| score < s) { |
| 581 | best = Some((k, score)); |
| 582 | } |
| 583 | } |
| 584 | let k = best.map_or(1, |(k, _)| k); |
| 585 | format!("{}\n{}", ws[..k].join(" "), ws[k..].join(" ")) |
| 586 | } |
| 587 | |
| 588 | |
| 589 | |
| 590 | |
| 591 | pub fn attach_word_times(cues: &mut [subtitle::Cue], words: &[(i64, i64, String, f64)]) { |
| 592 | let mut sorted: Vec<&(i64, i64, String, f64)> = words.iter().filter(|w| !w.2.trim().is_empty()).collect(); |
| 593 | sorted.sort_by_key(|w| w.0); |
| 594 | let mut by_cue: Vec<Vec<(i64, i64, String)>> = vec![Vec::new(); cues.len()]; |
| 595 | for w in sorted { |
| 596 | if let Some(i) = cues.iter().rposition(|c| c.start_us <= w.0) { |
| 597 | let end = w.1.clamp(w.0, cues[i].end_us.max(w.0)); |
| 598 | by_cue[i].push((w.0, end, w.2.trim().to_string())); |
| 599 | } |
| 600 | } |
| 601 | for (c, ws) in cues.iter_mut().zip(by_cue) { |
| 602 | c.words = ws; |
| 603 | if c.real_words().is_none() { |
| 604 | c.words.clear(); |
| 605 | } |
| 606 | } |
| 607 | } |
| 608 | |
| 609 | |
| 610 | |
| 611 | |
| 612 | |
| 613 | pub fn capitalise_sentence_starts(cues: &mut [subtitle::Cue], segment_starts: &[i64]) { |
| 614 | let mut begins = true; |
| 615 | for c in cues.iter_mut() { |
| 616 | if (begins || segment_starts.contains(&c.start_us)) |
| 617 | && let Some(first) = c.text.chars().next().filter(|f| f.is_lowercase()) |
| 618 | { |
| 619 | let upper: String = first.to_uppercase().collect(); |
| 620 | c.text.replace_range(..first.len_utf8(), &upper); |
| 621 | } |
| 622 | begins = c.text.trim_end().ends_with(['.', '!', '?']); |
| 623 | } |
| 624 | } |
| 625 | |
| 626 | |
| 627 | |
| 628 | |
| 629 | |
| 630 | #[derive(Debug, Default)] |
| 631 | pub struct Job { |
| 632 | |
| 633 | pub permille: std::sync::atomic::AtomicU32, |
| 634 | pub cancel: AtomicBool, |
| 635 | } |
| 636 | |
| 637 | impl Job { |
| 638 | |
| 639 | pub fn fraction(&self) -> f32 { |
| 640 | self.permille.load(Ordering::Relaxed) as f32 / 1000.0 |
| 641 | } |
| 642 | |
| 643 | fn set(&self, f: f64) { |
| 644 | self.permille.store((f.clamp(0.0, 1.0) * 1000.0) as u32, Ordering::Relaxed); |
| 645 | } |
| 646 | |
| 647 | pub fn cancelled(&self) -> bool { |
| 648 | self.cancel.load(Ordering::Relaxed) |
| 649 | } |
| 650 | } |
| 651 | |
| 652 | |
| 653 | pub const CANCELLED: &str = "cancelled"; |
| 654 | |
| 655 | |
| 656 | |
| 657 | |
| 658 | #[allow(clippy::too_many_arguments)] |
| 659 | pub fn run_stt(bin: &Path, wav: &Path, model: &str, device: Device, lang: &str, hint: &str, offset: f64, label: &str, job: &Job) -> Result<String, String> { |
| 660 | let hint_args: Vec<&str> = if hint.is_empty() { Vec::new() } else { vec!["--prompt", hint] }; |
| 661 | let mut child = Command::new(bin) |
| 662 | .args(["--model", model, "--device", device.flag(), "--language", lang, "--offset"]) |
| 663 | .arg(format!("{offset:.3}")) |
| 664 | .args(&hint_args) |
| 665 | .arg(wav) |
| 666 | .stdout(Stdio::piped()) |
| 667 | .stderr(Stdio::piped()) |
| 668 | .spawn() |
| 669 | .map_err(|e| format!("starting {}: {e}", bin.display()))?; |
| 670 | let stderr = child.stderr.take().ok_or("edith-stt: no stderr pipe")?; |
| 671 | let mut stdout = child.stdout.take().ok_or("edith-stt: no stdout pipe")?; |
| 672 | let progress = std::sync::Arc::new(Job::default()); |
| 673 | let seen = std::sync::Arc::clone(&progress); |
| 674 | let err_reader = std::thread::spawn(move || { |
| 675 | let mut tail: Vec<String> = Vec::new(); |
| 676 | for line in BufReader::new(stderr).lines().map_while(Result::ok) { |
| 677 | if let Some(p) = line.strip_prefix("progress ").and_then(|v| v.trim().parse::<f64>().ok()) { |
| 678 | seen.set(p); |
| 679 | } else if !line.trim().is_empty() { |
| 680 | tail.push(line); |
| 681 | if tail.len() > 6 { |
| 682 | tail.remove(0); |
| 683 | } |
| 684 | } |
| 685 | } |
| 686 | tail |
| 687 | }); |
| 688 | let out_reader = std::thread::spawn(move || { |
| 689 | let mut out = String::new(); |
| 690 | stdout.read_to_string(&mut out).map(|_| out) |
| 691 | }); |
| 692 | let status = loop { |
| 693 | job.set(f64::from(progress.fraction())); |
| 694 | if job.cancelled() { |
| 695 | let _ = child.kill(); |
| 696 | let _ = child.wait(); |
| 697 | let _ = err_reader.join(); |
| 698 | let _ = out_reader.join(); |
| 699 | return Err(CANCELLED.into()); |
| 700 | } |
| 701 | match child.try_wait() { |
| 702 | Ok(Some(st)) => break st, |
| 703 | Ok(None) => std::thread::sleep(std::time::Duration::from_millis(40)), |
| 704 | Err(e) => return Err(format!("waiting for edith-stt: {e}")), |
| 705 | } |
| 706 | }; |
| 707 | let tail = err_reader.join().unwrap_or_default(); |
| 708 | let out = out_reader |
| 709 | .join() |
| 710 | .map_err(|_| "reading edith-stt output: the reader panicked".to_string())? |
| 711 | .map_err(|e| format!("reading edith-stt output: {e}"))?; |
| 712 | if !status.success() { |
| 713 | return Err(format!("edith-stt failed on {label}: {}", tail.join(" | "))); |
| 714 | } |
| 715 | job.set(1.0); |
| 716 | Ok(out) |
| 717 | } |
| 718 | |
| 719 | |
| 720 | pub fn installed_models(device: Device) -> Vec<&'static str> { |
| 721 | MODELS.iter().copied().filter(|m| check_model(m, device).is_ok()).collect() |
| 722 | } |
| 723 | |
| 724 | |
| 725 | pub fn models_dir() -> PathBuf { |
| 726 | home().join(".cache/edith/models") |
| 727 | } |
| 728 | |
| 729 | |
| 730 | const MODEL_FILES: [(&str, bool); 4] = [ |
| 731 | ("config.json", true), |
| 732 | ("model.safetensors", true), |
| 733 | ("tokenizer.json", true), |
| 734 | ("preprocessor_config.json", true), |
| 735 | ]; |
| 736 | const MODEL_OPTIONAL: &str = "generation_config.json"; |
| 737 | |
| 738 | |
| 739 | pub fn model_bytes(model: &str, device: Device) -> u64 { |
| 740 | match (device, model) { |
| 741 | (Device::Gpu, "tiny") => 78_000_000, |
| 742 | (Device::Gpu, "base") => 148_000_000, |
| 743 | (Device::Gpu, "small") => 488_000_000, |
| 744 | (Device::Gpu, "medium") => 1_530_000_000, |
| 745 | (Device::Gpu, "large-v3") => 3_100_000_000, |
| 746 | (Device::Gpu, "large-v3-turbo") => 1_620_000_000, |
| 747 | (Device::Cpu, "tiny") => 152_000_000, |
| 748 | (Device::Cpu, "small") => 970_000_000, |
| 749 | (Device::Cpu, "medium") => 3_060_000_000, |
| 750 | (Device::Cpu, "large-v3") => 3_090_000_000, |
| 751 | (Device::Cpu, "large-v3-turbo") => 1_620_000_000, |
| 752 | _ => 293_000_000, |
| 753 | } |
| 754 | } |
| 755 | |
| 756 | |
| 757 | |
| 758 | fn fetch(url: &str, tmp: &Path, job: &Job, total: f64, have: &dyn Fn() -> u64) -> Result<bool, String> { |
| 759 | let mut child = Command::new("curl") |
| 760 | .args(["-fsSL", "--retry", "2", "--connect-timeout", "20", "-o"]) |
| 761 | .arg(tmp) |
| 762 | .arg(url) |
| 763 | .stdin(Stdio::null()) |
| 764 | .stdout(Stdio::null()) |
| 765 | .stderr(Stdio::null()) |
| 766 | .spawn() |
| 767 | .map_err(|e| format!("cannot run curl ({e}): install curl, or copy the model into {}", models_dir().display()))?; |
| 768 | let status = loop { |
| 769 | if job.cancelled() { |
| 770 | let _ = child.kill(); |
| 771 | let _ = child.wait(); |
| 772 | let _ = std::fs::remove_file(tmp); |
| 773 | return Err(CANCELLED.into()); |
| 774 | } |
| 775 | if let Some(status) = child.try_wait().map_err(|e| e.to_string())? { |
| 776 | break status; |
| 777 | } |
| 778 | job.set((have() as f64 / total).min(0.99)); |
| 779 | std::thread::sleep(std::time::Duration::from_millis(150)); |
| 780 | }; |
| 781 | if !status.success() { |
| 782 | let _ = std::fs::remove_file(tmp); |
| 783 | } |
| 784 | Ok(status.success()) |
| 785 | } |
| 786 | |
| 787 | |
| 788 | |
| 789 | |
| 790 | |
| 791 | |
| 792 | pub fn download_model(model: &str, device: Device, job: &Job) -> Result<(), String> { |
| 793 | if !MODELS.contains(&model) { |
| 794 | return Err(format!("model `{model}` is not one of {}", MODELS.join(", "))); |
| 795 | } |
| 796 | let root = models_dir(); |
| 797 | std::fs::create_dir_all(&root).map_err(|e| format!("cannot create {}: {e}", root.display()))?; |
| 798 | let total = model_bytes(model, device) as f64; |
| 799 | match device { |
| 800 | Device::Gpu => { |
| 801 | let file = format!("ggml-{model}.bin"); |
| 802 | let target = root.join(&file); |
| 803 | let tmp = root.join(format!("{file}.part")); |
| 804 | let url = format!("https://huggingface.co/ggerganov/whisper.cpp/resolve/main/{file}"); |
| 805 | let len = || std::fs::metadata(&tmp).map(|m| m.len()).unwrap_or(0); |
| 806 | if !fetch(&url, &tmp, job, total, &len)? { |
| 807 | return Err(format!("could not download {file}: check the internet connection and try again")); |
| 808 | } |
| 809 | std::fs::rename(&tmp, &target).map_err(|e| format!("cannot save {file}: {e}"))?; |
| 810 | } |
| 811 | Device::Cpu => { |
| 812 | let part = root.join(format!("whisper-{model}.part")); |
| 813 | let done = model_path(model, device); |
| 814 | std::fs::create_dir_all(&part).map_err(|e| format!("cannot create {}: {e}", part.display()))?; |
| 815 | let base = format!("https://huggingface.co/openai/whisper-{model}/resolve/main"); |
| 816 | let have = || -> u64 { |
| 817 | std::fs::read_dir(&part) |
| 818 | .map(|d| d.flatten().filter_map(|e| e.metadata().ok()).map(|m| m.len()).sum()) |
| 819 | .unwrap_or(0) |
| 820 | }; |
| 821 | let files = MODEL_FILES.iter().copied().chain([(MODEL_OPTIONAL, false)]); |
| 822 | for (file, needed) in files { |
| 823 | let target = part.join(file); |
| 824 | if target.exists() { |
| 825 | continue; |
| 826 | } |
| 827 | let tmp = part.join(format!("{file}.tmp")); |
| 828 | if fetch(&format!("{base}/{file}"), &tmp, job, total, &have)? { |
| 829 | std::fs::rename(&tmp, &target).map_err(|e| format!("cannot save {file}: {e}"))?; |
| 830 | } else if needed { |
| 831 | return Err(format!("could not download {file}: check the internet connection and try again")); |
| 832 | } |
| 833 | } |
| 834 | std::fs::rename(&part, &done).map_err(|e| format!("cannot finish the download: {e}"))?; |
| 835 | } |
| 836 | } |
| 837 | job.set(1.0); |
| 838 | Ok(()) |
| 839 | } |
| 840 | |
| 841 | |
| 842 | |
| 843 | pub fn available(device: Device) -> Result<(), String> { |
| 844 | stt_bin()?; |
| 845 | if device == Device::Gpu && !gpu_available() { |
| 846 | return Err("edith-stt finds no usable GPU".into()); |
| 847 | } |
| 848 | if installed_models(device).is_empty() { |
| 849 | return Err("The speech model is not installed yet.".into()); |
| 850 | } |
| 851 | Ok(()) |
| 852 | } |
| 853 | |
| 854 | |
| 855 | |
| 856 | |
| 857 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 858 | pub enum Hear { |
| 859 | |
| 860 | Mix, |
| 861 | |
| 862 | Lane(Lane), |
| 863 | } |
| 864 | |
| 865 | |
| 866 | #[derive(Clone, Debug, PartialEq)] |
| 867 | pub struct Spoken { |
| 868 | pub text: String, |
| 869 | pub start_f: u32, |
| 870 | pub end_f: u32, |
| 871 | |
| 872 | pub p: f64, |
| 873 | } |
| 874 | |
| 875 | |
| 876 | |
| 877 | fn timeline_16k(s: &PlaybackSession, hear: Hear) -> Result<Option<Vec<f32>>, String> { |
| 878 | let fps = s.meta().frame_rate; |
| 879 | let (rate, ch, chunks): (f64, usize, Box<dyn Iterator<Item = Vec<f32>>>) = match hear { |
| 880 | Hear::Lane(lane) => { |
| 881 | let Some((meta, rx)) = crate::normalize::open_lane(s, lane, 0, fps)? else { |
| 882 | return Ok(None); |
| 883 | }; |
| 884 | (f64::from(meta.sample_rate), usize::from(meta.channels).max(1), Box::new(rx.into_iter().map(|c| c.samples))) |
| 885 | } |
| 886 | Hear::Mix => { |
| 887 | let wav = crate::normalize::render_mix(s)?; |
| 888 | let sources = [(wav.0.clone(), 0usize)]; |
| 889 | let Some((meta, rx)) = AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)]) |
| 890 | .map_err(|e| format!("reading the mix: {e}"))? |
| 891 | else { |
| 892 | return Ok(None); |
| 893 | }; |
| 894 | |
| 895 | let all: Vec<Vec<f32>> = rx.into_iter().map(|c| c.samples).collect(); |
| 896 | (f64::from(meta.sample_rate), usize::from(meta.channels).max(1), Box::new(all.into_iter())) |
| 897 | } |
| 898 | }; |
| 899 | let mut mono = Vec::new(); |
| 900 | for samples in chunks { |
| 901 | for frame in samples.chunks(ch) { |
| 902 | mono.push(frame.iter().sum::<f32>() / frame.len() as f32); |
| 903 | } |
| 904 | } |
| 905 | Ok(Some(resample_linear(&mono, rate, f64::from(RATE)))) |
| 906 | } |
| 907 | |
| 908 | |
| 909 | fn silence_hallucination(text: &str, no_speech: Option<f64>, avg_logprob: Option<f64>) -> bool { |
| 910 | const STOCK: &[&str] = &["thank you", "thank you for watching", "thanks for watching", "you"]; |
| 911 | let t = text.split_whitespace().map(norm).filter(|w| !w.is_empty()).collect::<Vec<_>>().join(" "); |
| 912 | STOCK.contains(&t.as_str()) && (no_speech.is_some_and(|p| p >= 0.5) || avg_logprob.is_some_and(|lp| lp < -1.0)) |
| 913 | } |
| 914 | |
| 915 | |
| 916 | |
| 917 | |
| 918 | pub fn transcribe(s: &PlaybackSession, hear: Hear, model: &str, device: Device, lang: &str, fillers: bool, job: &Job) -> Result<Vec<Spoken>, String> { |
| 919 | listen(prepare(s, hear)?, model, device, lang, fillers, job) |
| 920 | } |
| 921 | |
| 922 | |
| 923 | |
| 924 | pub struct Heard { |
| 925 | samples: Vec<f32>, |
| 926 | fps: f64, |
| 927 | label: String, |
| 928 | } |
| 929 | |
| 930 | |
| 931 | pub fn prepare(s: &PlaybackSession, hear: Hear) -> Result<Heard, String> { |
| 932 | let samples = timeline_16k(s, hear)?.ok_or("there is no sound to listen to")?; |
| 933 | if samples.iter().all(|x| x.abs() < 1e-4) { |
| 934 | return Err("the sound is silent: there is nothing to transcribe".into()); |
| 935 | } |
| 936 | let label = match hear { |
| 937 | Hear::Mix => "the mix".to_string(), |
| 938 | Hear::Lane(l) => l.label(), |
| 939 | }; |
| 940 | Ok(Heard { samples, fps: s.meta().frame_rate, label }) |
| 941 | } |
| 942 | |
| 943 | |
| 944 | pub fn listen(heard: Heard, model: &str, device: Device, lang: &str, fillers: bool, job: &Job) -> Result<Vec<Spoken>, String> { |
| 945 | let bin = stt_bin()?; |
| 946 | check_model(model, device)?; |
| 947 | check_lang(lang)?; |
| 948 | let fps = heard.fps; |
| 949 | if job.cancelled() { |
| 950 | return Err(CANCELLED.into()); |
| 951 | } |
| 952 | let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()); |
| 953 | let wav = std::env::temp_dir().join(format!("edith-speech-{}-{nanos}.wav", std::process::id())); |
| 954 | std::fs::write(&wav, wav_bytes(&heard.samples)).map_err(|e| format!("writing {}: {e}", wav.display()))?; |
| 955 | let guard = TempFile(wav.clone()); |
| 956 | let hint = if fillers { FILLER_PROMPT } else { "" }; |
| 957 | let raw = run_stt(&bin, &wav, model, device, lang, hint, 0.0, &heard.label, job); |
| 958 | drop(guard); |
| 959 | let mut words = Vec::new(); |
| 960 | for seg in parse_raw(&raw?)? { |
| 961 | if seg.text.is_empty() || silence_hallucination(&seg.text, seg.no_speech, seg.avg_logprob) { |
| 962 | continue; |
| 963 | } |
| 964 | for w in seg.words.iter().filter(|w| !w.w.is_empty()) { |
| 965 | let start_f = (w.start * fps).round().max(0.0) as u32; |
| 966 | words.push(Spoken { text: w.w.clone(), start_f, end_f: ((w.end * fps).round() as u32).max(start_f), p: w.p }); |
| 967 | } |
| 968 | } |
| 969 | Ok(words) |
| 970 | } |
| 971 | |
| 972 | struct TempFile(PathBuf); |
| 973 | |
| 974 | impl Drop for TempFile { |
| 975 | fn drop(&mut self) { |
| 976 | let _ = std::fs::remove_file(&self.0); |
| 977 | } |
| 978 | } |
| 979 | |
| 980 | |
| 981 | |
| 982 | |
| 983 | pub const CAPTION_MAX_CHARS: usize = 42; |
| 984 | pub const CAPTION_MAX_SECS: f64 = 6.0; |
| 985 | |
| 986 | |
| 987 | |
| 988 | |
| 989 | pub fn captions(words: &[Spoken], fps: f64) -> Vec<subtitle::Cue> { |
| 990 | let us = |f: u32| (f64::from(f) / fps * 1e6).round() as i64; |
| 991 | let timed: Vec<(i64, i64, String, f64)> = words |
| 992 | .iter() |
| 993 | .filter(|w| !CAPTION_FILLERS.contains(&norm(&w.text).as_str())) |
| 994 | .map(|w| (us(w.start_f), us(w.end_f), w.text.clone(), w.p)) |
| 995 | .collect(); |
| 996 | if timed.is_empty() { |
| 997 | return Vec::new(); |
| 998 | } |
| 999 | let owners = vec![0; timed.len()]; |
| 1000 | let (mut cues, _, _) = caption_cues(&timed, &owners, CAPTION_MAX_CHARS, CAPTION_MAX_SECS, CAPTION_GAP_SECS); |
| 1001 | capitalise_sentence_starts(&mut cues, &[]); |
| 1002 | attach_word_times(&mut cues, &timed); |
| 1003 | cues |
| 1004 | } |
| 1005 | |
| 1006 | |
| 1007 | |
| 1008 | pub fn place_captions(s: &mut PlaybackSession, cues: &[subtitle::Cue], lane: Lane, srt: &Path) -> Result<usize, String> { |
| 1009 | use crate::project::{LaneKind, SubClip}; |
| 1010 | if lane.kind != LaneKind::Subtitle { |
| 1011 | return Err(format!("{} is not a caption lane; captions go on S1..", lane.label())); |
| 1012 | } |
| 1013 | if s.lane_locked(lane) { |
| 1014 | return Err(format!("lane {} is locked: unlock it first", lane.label())); |
| 1015 | } |
| 1016 | let end_us = cues.iter().map(|c| c.end_us).max().unwrap_or(0); |
| 1017 | if cues.is_empty() || end_us <= 0 { |
| 1018 | return Err("there are no cues to place".into()); |
| 1019 | } |
| 1020 | if let Some(dir) = srt.parent() { |
| 1021 | let _ = std::fs::create_dir_all(dir); |
| 1022 | } |
| 1023 | subtitle::save_cues(srt, cues).map_err(|e| format!("writing {}: {e}", srt.display()))?; |
| 1024 | let fps = s.meta().frame_rate; |
| 1025 | let pushed = s.history_pushes(); |
| 1026 | s.begin_batch(); |
| 1027 | let placed = (|| -> Result<usize, String> { |
| 1028 | let added = s.import_subtitles(srt).map_err(|e| format!("importing {}: {e}", srt.display()))?; |
| 1029 | if added == 0 { |
| 1030 | return Err(format!("importing {} added no subtitle track", srt.display())); |
| 1031 | } |
| 1032 | let want = std::fs::canonicalize(srt).unwrap_or_else(|_| srt.to_path_buf()); |
| 1033 | let track = s |
| 1034 | .subtitles() |
| 1035 | .iter() |
| 1036 | .rposition(|t| std::fs::canonicalize(&t.path).unwrap_or_else(|_| t.path.clone()) == want) |
| 1037 | .ok_or_else(|| format!("{} was imported but no track for it was found", srt.display()))?; |
| 1038 | |
| 1039 | s.attach_cue_words(track, cues); |
| 1040 | let mut guard = 0; |
| 1041 | while !s.subtitle_lanes().contains(&lane) { |
| 1042 | guard += 1; |
| 1043 | if guard > lane.ord + 1 { |
| 1044 | return Err(format!("{} could not be made", lane.label())); |
| 1045 | } |
| 1046 | s.add_lane(LaneKind::Subtitle); |
| 1047 | } |
| 1048 | s.place_sub(lane, 0, SubClip::whole_track(track, end_us, fps)).map_err(|e| e.to_string())?; |
| 1049 | Ok(track) |
| 1050 | })(); |
| 1051 | s.end_batch(); |
| 1052 | if placed.is_err() && s.history_pushes() > pushed { |
| 1053 | |
| 1054 | for _ in pushed..s.history_pushes() { |
| 1055 | if !s.undo() { |
| 1056 | break; |
| 1057 | } |
| 1058 | } |
| 1059 | s.clear_redo(); |
| 1060 | } |
| 1061 | placed |
| 1062 | } |
| 1063 | |
| 1064 | |
| 1065 | |
| 1066 | |
| 1067 | #[derive(Clone, Debug, PartialEq)] |
| 1068 | pub struct Filler { |
| 1069 | pub text: String, |
| 1070 | pub start_f: u32, |
| 1071 | pub end_f: u32, |
| 1072 | |
| 1073 | pub cut: (u32, u32), |
| 1074 | } |
| 1075 | |
| 1076 | |
| 1077 | |
| 1078 | pub fn find_fillers(words: &[Spoken], pad: u32, end: u32) -> Vec<Filler> { |
| 1079 | let mut out = Vec::new(); |
| 1080 | for (i, w) in words.iter().enumerate() { |
| 1081 | if !CAPTION_FILLERS.contains(&norm(&w.text).as_str()) { |
| 1082 | continue; |
| 1083 | } |
| 1084 | let prev_end = if i == 0 { 0 } else { words[i - 1].end_f }; |
| 1085 | let next_start = words.get(i + 1).map_or(u32::MAX, |n| n.start_f); |
| 1086 | let a = w.start_f.saturating_sub(pad).max(prev_end.min(w.start_f)); |
| 1087 | let b = w.end_f.saturating_add(pad).min(next_start.max(w.end_f)).min(end.max(w.end_f)); |
| 1088 | 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) }); |
| 1089 | } |
| 1090 | out |
| 1091 | } |
| 1092 | |
| 1093 | |
| 1094 | |
| 1095 | pub fn cut_fillers(s: &mut PlaybackSession, fillers: &[Filler], lanes: &[Lane]) -> Result<Vec<(u32, u32)>, String> { |
| 1096 | let spans: Vec<(u32, u32)> = fillers.iter().map(|f| f.cut).collect(); |
| 1097 | cut_spans(s, &spans, lanes) |
| 1098 | } |
| 1099 | |
| 1100 | |
| 1101 | |
| 1102 | |
| 1103 | pub fn cut_spans(s: &mut PlaybackSession, spans: &[(u32, u32)], lanes: &[Lane]) -> Result<Vec<(u32, u32)>, String> { |
| 1104 | let mut spans: Vec<(u32, u32)> = spans.iter().copied().filter(|(a, b)| b > a).collect(); |
| 1105 | spans.sort_unstable(); |
| 1106 | let mut merged: Vec<(u32, u32)> = Vec::new(); |
| 1107 | for (a, b) in spans { |
| 1108 | match merged.last_mut() { |
| 1109 | Some(last) if a <= last.1 => last.1 = last.1.max(b), |
| 1110 | _ => merged.push((a, b)), |
| 1111 | } |
| 1112 | } |
| 1113 | if merged.is_empty() { |
| 1114 | return Err("there is nothing to cut".into()); |
| 1115 | } |
| 1116 | |
| 1117 | let regions: Vec<(u32, u32)> = merged.iter().map(|&(a, b)| (a, b - a)).collect(); |
| 1118 | s.cut_regions(®ions, lanes).map_err(|e| e.to_string())?; |
| 1119 | Ok(regions) |
| 1120 | } |
| 1121 | |
| 1122 | |
| 1123 | |
| 1124 | |
| 1125 | pub fn word_span(words: &[Spoken], first: usize, last: usize, pad: u32, end: u32) -> Option<(u32, u32)> { |
| 1126 | let (a, b) = (words.get(first)?, words.get(last)?); |
| 1127 | let prev_end = if first == 0 { 0 } else { words[first - 1].end_f }; |
| 1128 | let next_start = words.get(last + 1).map_or(u32::MAX, |n| n.start_f); |
| 1129 | let from = a.start_f.saturating_sub(pad).max(prev_end.min(a.start_f)); |
| 1130 | let to = b.end_f.saturating_add(pad).min(next_start.max(b.end_f)).min(end.max(b.end_f)); |
| 1131 | Some((from, to)) |
| 1132 | } |
| 1133 | |
| 1134 | |
| 1135 | |
| 1136 | |
| 1137 | pub fn remap_words(words: &[Spoken], regions: &[(u32, u32)]) -> Vec<Spoken> { |
| 1138 | let moved = |f: u32| -> u32 { f - regions.iter().map(|&(a, len)| f.saturating_sub(a).min(len)).sum::<u32>() }; |
| 1139 | words |
| 1140 | .iter() |
| 1141 | .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))) |
| 1142 | .map(|w| Spoken { text: w.text.clone(), start_f: moved(w.start_f), end_f: moved(w.end_f), p: w.p }) |
| 1143 | .collect() |
| 1144 | } |
| 1145 | |
| 1146 | |
| 1147 | pub fn is_filler(text: &str) -> bool { |
| 1148 | CAPTION_FILLERS.contains(&norm(text).as_str()) |
| 1149 | } |
| 1150 | |
| 1151 | #[cfg(test)] |
| 1152 | mod transcript_cut_tests { |
| 1153 | use super::*; |
| 1154 | |
| 1155 | fn w(t: &str, a: u32, b: u32) -> Spoken { |
| 1156 | Spoken { text: t.into(), start_f: a, end_f: b, p: 0.9 } |
| 1157 | } |
| 1158 | |
| 1159 | #[test] |
| 1160 | fn a_word_span_pads_but_stops_at_neighbours() { |
| 1161 | let ws = [w("so", 10, 20), w("um", 22, 30), w("yes", 31, 40)]; |
| 1162 | assert_eq!(word_span(&ws, 1, 1, 3, 100), Some((20, 31))); |
| 1163 | assert_eq!(word_span(&ws, 0, 1, 3, 100), Some((7, 31))); |
| 1164 | assert_eq!(word_span(&ws, 2, 2, 5, 42), Some((30, 42))); |
| 1165 | assert_eq!(word_span(&ws, 3, 3, 3, 100), None); |
| 1166 | } |
| 1167 | |
| 1168 | #[test] |
| 1169 | fn remapping_drops_cut_words_and_closes_the_hole() { |
| 1170 | let ws = [w("a", 0, 10), w("b", 12, 20), w("c", 22, 30), w("d", 32, 40)]; |
| 1171 | let out = remap_words(&ws, &[(11, 10)]); |
| 1172 | assert_eq!(out.iter().map(|x| x.text.as_str()).collect::<Vec<_>>(), ["a", "c", "d"]); |
| 1173 | assert_eq!((out[1].start_f, out[1].end_f), (12, 20)); |
| 1174 | assert_eq!((out[2].start_f, out[2].end_f), (22, 30)); |
| 1175 | let two = remap_words(&ws, &[(11, 10), (31, 9)]); |
| 1176 | assert_eq!(two.iter().map(|x| x.text.as_str()).collect::<Vec<_>>(), ["a", "c"]); |
| 1177 | assert_eq!(two[1].start_f, 12); |
| 1178 | } |
| 1179 | |
| 1180 | #[test] |
| 1181 | fn fillers_are_told_by_spelling() { |
| 1182 | assert!(is_filler("Um,") && is_filler("uh") && !is_filler("umbrella")); |
| 1183 | } |
| 1184 | } |