268 lines · 9.5 KB · RustRaw
//! Timed words → meeting lines and subtitle cues, written by the same rules//! as dictation ([`super::format`]): one casing, one spoken punctuation, one//! spacing for the phone, the Mac (meeting transcripts) and the Worker//! (film subtitles).use serde::{Deserialize, Serialize};use super::format::{self, Context, Options, Rules};/// One word as an engine timed it.#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]pub struct TimedWord { pub w: String, pub start_ms: u64, pub end_ms: u64, #[serde(default, skip_serializing_if = "Option::is_none")] pub speaker: Option<String>,}/// The most words a spoken mark is said in, in any language's file.const MOST_SPOKEN_WORDS: usize = 3;/// A written token: a word with the marks glued to it, and its time.#[derive(Debug, Clone, PartialEq)]struct Token { text: String, space_before: bool, start_ms: u64, end_ms: u64, speaker: Option<String>,}fn tokens(words: &[TimedWord], rules: &Rules, upper_case: bool) -> Vec<Token> { let mut out: Vec<Token> = Vec::new(); let mut written = String::new(); let mut context = Context::START; let options = Options { upper_case, command: false }; let mut i = 0; while i < words.len() { // A spoken mark said in several words ("full stop", "new paragraph") // is one token over their time. let mut n = 1; for take in (2..=MOST_SPOKEN_WORDS).rev() { if i + take <= words.len() { let said: Vec<&str> = words[i..i + take].iter().map(|w| w.w.as_str()).collect(); let piece = format::format(&said.join(" "), rules, context, options); if !piece.is_empty() && !piece.chars().any(char::is_alphanumeric) && words[i..i + take].iter().all(|w| w.speaker == words[i].speaker) { n = take; break; } } } let word = TimedWord { w: words[i..i + n].iter().map(|w| w.w.as_str()).collect::<Vec<_>>().join(" "), start_ms: words[i].start_ms, end_ms: words[i + n - 1].end_ms, speaker: words[i].speaker.clone(), }; i += n; let word = &word; let piece = format::format(&word.w, rules, context, options); if piece.is_empty() { continue; } written.push_str(&piece); context = rules.context_after(&written); let has_word = piece.chars().any(char::is_alphanumeric); match out.last_mut() { Some(last) if !has_word && last.speaker == word.speaker => { last.text.push_str(piece.trim_start_matches(' ')); last.end_ms = last.end_ms.max(word.end_ms); } _ => out.push(Token { space_before: piece.starts_with(' '), text: piece.trim_start_matches(' ').to_string(), start_ms: word.start_ms, end_ms: word.end_ms, speaker: word.speaker.clone(), }), } } out}/// One line of a transcript: a speaker's sentence.#[derive(Debug, Clone, PartialEq, Serialize)]pub struct Line { pub speaker: Option<String>, pub start_ms: u64, pub end_ms: u64, pub text: String,}/// A silence this long ends a line even mid-sentence.pub const LINE_GAP_MS: u64 = 2000;/// A meeting's lines: a new line at every change of speaker, every/// sentence's end, and every silence of [`LINE_GAP_MS`].pub fn lines(words: &[TimedWord], rules: &Rules, upper_case: bool) -> Vec<Line> { let mut out: Vec<Line> = Vec::new(); let mut open = false; for token in tokens(words, rules, upper_case) { let joins = open && out.last().is_some_and(|line| line.speaker == token.speaker && token.start_ms.saturating_sub(line.end_ms) < LINE_GAP_MS); if joins { let line = out.last_mut().unwrap(); if token.space_before { line.text.push(' '); } line.text.push_str(&token.text); line.end_ms = token.end_ms; } else { out.push(Line { speaker: token.speaker.clone(), start_ms: token.start_ms, end_ms: token.end_ms, text: format::capitalise(&token.text) }); } open = !rules.text_ends_sentence(&token.text) && !token.text.ends_with('\n'); } for line in &mut out { line.text = line.text.trim().to_string(); } out}/// How cues are cut.#[derive(Debug, Clone, Copy, PartialEq, Deserialize)]#[serde(default)]pub struct CueRules { /// Columns per line: a full-width character (Japanese) takes two. pub max_columns: usize, pub max_lines: usize, pub max_ms: u64, pub min_ms: u64, pub gap_ms: u64,}impl Default for CueRules { fn default() -> Self { CueRules { max_columns: 42, max_lines: 2, max_ms: 7000, min_ms: 833, gap_ms: 1500 } }}#[derive(Debug, Clone, PartialEq, Serialize)]pub struct Cue { pub start_ms: u64, pub end_ms: u64, pub lines: Vec<String>,}/// The columns `text` takes on screen.pub fn columns(text: &str) -> usize { text.chars().map(|c| if format::unspaced(c) { 2 } else { 1 }).sum()}fn joined(tokens: &[Token]) -> String { let mut text = String::new(); for (i, token) in tokens.iter().enumerate() { if i > 0 && token.space_before { text.push(' '); } text.push_str(&token.text); } text}/// Subtitle cues: at most `max_lines` lines of `max_columns`, at most/// `max_ms` on screen, a new cue after a silence of `gap_ms` and, where the/// cue is already half full, after a sentence ends. Lines are balanced and/// broken after punctuation where they can be.pub fn cues(words: &[TimedWord], rules: &Rules, upper_case: bool, cut: CueRules) -> Vec<Cue> { let capacity = cut.max_columns * cut.max_lines; let mut out = Vec::new(); let mut current: Vec<Token> = Vec::new(); let flush = |current: &mut Vec<Token>, out: &mut Vec<Cue>| { if current.is_empty() { return; } let start_ms = current[0].start_ms; let end_ms = current.last().unwrap().end_ms.max(start_ms + cut.min_ms); out.push(Cue { start_ms, end_ms, lines: break_lines(current, cut) }); current.clear(); }; for token in tokens(words, rules, upper_case) { for token in split_long(token, cut.max_columns) { if let Some(last) = current.last() { let mut trial = current.clone(); trial.push(token.clone()); let too_long = columns(&joined(&trial)) > capacity; let too_slow = token.end_ms.saturating_sub(current[0].start_ms) > cut.max_ms; let silence = token.start_ms.saturating_sub(last.end_ms) > cut.gap_ms; let sentence = rules.text_ends_sentence(&last.text) && columns(&joined(¤t)) * 2 >= cut.max_columns; if too_long || too_slow || silence || sentence || last.speaker != token.speaker { flush(&mut current, &mut out); } } current.push(token); } } flush(&mut current, &mut out); // A cue's minimum time never runs over the next cue. for i in 1..out.len() { let next = out[i].start_ms; if out[i - 1].end_ms > next { out[i - 1].end_ms = next.max(out[i - 1].start_ms); } } out}/// A token wider than a line (a long unspaced run) cut into line-wide parts.fn split_long(token: Token, max_columns: usize) -> Vec<Token> { if columns(&token.text) <= max_columns { return vec![token]; } let mut parts = Vec::new(); let mut part = String::new(); for c in token.text.chars() { if columns(&part) + columns(&c.to_string()) > max_columns { parts.push(std::mem::take(&mut part)); } part.push(c); } parts.push(part); let total = token.end_ms.saturating_sub(token.start_ms); let count = parts.len() as u64; parts .into_iter() .enumerate() .map(|(i, text)| Token { space_before: i == 0 && token.space_before, start_ms: token.start_ms + total * i as u64 / count, end_ms: token.start_ms + total * (i as u64 + 1) / count, speaker: token.speaker.clone(), text, }) .collect()}/// The cue's tokens in at most `max_lines` lines, the longest line as short/// as it can be, a break after punctuation preferred.fn break_lines(tokens: &[Token], cut: CueRules) -> Vec<String> { let whole = joined(tokens); if columns(&whole) <= cut.max_columns || cut.max_lines < 2 || tokens.len() < 2 { return vec![whole]; } let mut best: Option<(usize, usize)> = None; let mut best_score = usize::MAX; for split in 1..tokens.len() { let (top, bottom) = (joined(&tokens[..split]), joined(&tokens[split..])); let (a, b) = (columns(&top), columns(&bottom)); if a > cut.max_columns || b > cut.max_columns { continue; } let punctuated = top.ends_with([',', '.', '?', '!', ';', ':', '、', '。', '।']); // A break after punctuation is worth a third of a line of balance. let score = (a.max(b) * 4 + a.abs_diff(b)).saturating_sub(if punctuated { cut.max_columns * 4 / 3 } else { 0 }); if score < best_score { best_score = score; best = Some((split, 0)); } } match best { Some((split, _)) => vec![joined(&tokens[..split]), joined(&tokens[split..])], None => vec![whole], }}#[cfg(test)]#[path = "cues_tests.rs"]mod tests;