Skip to main content

rightkit_transcript/
words.rs

1//! Word timing input: [`TimedWord`] in OUTPUT time, plus engine adapters.
2
3use crate::contract::Transcript;
4use serde::{Deserialize, Serialize};
5
6/// A mapped word may differ from its source duration by at most this much; a
7/// larger difference means a removed range cut through the word, so it is dropped.
8pub const MAP_DURATION_TOLERANCE_MS: u64 = 20;
9
10/// One spoken word (`end_ms` exclusive).
11#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
12pub struct TimedWord {
13    pub text: String,
14    pub start_ms: u64,
15    pub end_ms: u64,
16}
17
18impl TimedWord {
19    pub fn new(text: impl Into<String>, start_ms: u64, end_ms: u64) -> Self {
20        Self {
21            text: text.into(),
22            start_ms,
23            end_ms,
24        }
25    }
26}
27
28/// Engine adapter: `(text, start_seconds, end_seconds)` -> milliseconds.
29/// Negative or non-finite times are clamped to 0; rounding is to nearest ms.
30/// This is the shape of `rightkit_asr::TimedWord`/`TimedToken`.
31pub fn words_from_seconds<'a>(
32    items: impl IntoIterator<Item = (&'a str, f32, f32)>,
33) -> Vec<TimedWord> {
34    let ms = |s: f32| {
35        if s.is_finite() && s > 0.0 {
36            (s as f64 * 1000.0).round() as u64
37        } else {
38            0
39        }
40    };
41    items
42        .into_iter()
43        .map(|(t, s, e)| TimedWord::new(t, ms(s), ms(e)))
44        .collect()
45}
46
47/// Maps a source [`Transcript`] onto an output timeline (cut/edit).
48///
49/// `map` converts a source time (ms) to output time (ms), returning `None`
50/// when that instant lies in a removed range. A word is kept when its start
51/// and end both map and the mapped duration matches the source duration
52/// (within [`MAP_DURATION_TOLERANCE_MS`]); otherwise it falls in (or
53/// straddles) a removed range and is dropped.
54pub fn words_from_transcript<F>(transcript: &Transcript, map: F) -> Vec<TimedWord>
55where
56    F: Fn(u64) -> Option<u64>,
57{
58    let mut out = Vec::new();
59    for w in &transcript.words {
60        let text = w.text.trim();
61        if text.is_empty() || w.end_ms <= w.start_ms {
62            continue;
63        }
64        let Some(start) = map(w.start_ms) else {
65            continue;
66        };
67        let Some(end) = map(w.end_ms).or_else(|| map(w.end_ms - 1).map(|e| e + 1)) else {
68            continue;
69        };
70        if end <= start {
71            continue;
72        }
73        if (end - start).abs_diff(w.end_ms - w.start_ms) > MAP_DURATION_TOLERANCE_MS {
74            continue;
75        }
76        out.push(TimedWord::new(text, start, end));
77    }
78    out
79}