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    /// From engine seconds. Negative or non-finite times clamp to 0; rounding
28    /// is to the nearest millisecond (the same rule as [`words_from_seconds`]).
29    pub fn from_seconds(text: impl Into<String>, start_s: f32, end_s: f32) -> Self {
30        Self::new(text, seconds_to_ms(start_s), seconds_to_ms(end_s))
31    }
32
33    /// Start in seconds.
34    pub fn start_secs(&self) -> f64 {
35        self.start_ms as f64 / 1000.0
36    }
37
38    /// End in seconds.
39    pub fn end_secs(&self) -> f64 {
40        self.end_ms as f64 / 1000.0
41    }
42}
43
44impl<T: Into<String>> From<(T, u64, u64)> for TimedWord {
45    /// `(text, start_ms, end_ms)`.
46    fn from((text, start_ms, end_ms): (T, u64, u64)) -> Self {
47        Self::new(text, start_ms, end_ms)
48    }
49}
50
51fn seconds_to_ms(s: f32) -> u64 {
52    if s.is_finite() && s > 0.0 {
53        (s as f64 * 1000.0).round() as u64
54    } else {
55        0
56    }
57}
58
59/// Engine adapter: `(text, start_seconds, end_seconds)` -> milliseconds.
60/// Negative or non-finite times are clamped to 0; rounding is to nearest ms.
61/// This is the shape of `rightkit_asr::TimedWord`/`TimedToken`.
62pub fn words_from_seconds<'a>(
63    items: impl IntoIterator<Item = (&'a str, f32, f32)>,
64) -> Vec<TimedWord> {
65    items
66        .into_iter()
67        .map(|(t, s, e)| TimedWord::from_seconds(t, s, e))
68        .collect()
69}
70
71/// Maps a source [`Transcript`] onto an output timeline (cut/edit).
72///
73/// `map` converts a source time (ms) to output time (ms), returning `None`
74/// when that instant lies in a removed range. A word is kept when its start
75/// and end both map and the mapped duration matches the source duration
76/// (within [`MAP_DURATION_TOLERANCE_MS`]); otherwise it falls in (or
77/// straddles) a removed range and is dropped.
78pub fn words_from_transcript<F>(transcript: &Transcript, map: F) -> Vec<TimedWord>
79where
80    F: Fn(u64) -> Option<u64>,
81{
82    let mut out = Vec::new();
83    for w in &transcript.words {
84        let text = w.text.trim();
85        if text.is_empty() || w.end_ms <= w.start_ms {
86            continue;
87        }
88        let Some(start) = map(w.start_ms) else {
89            continue;
90        };
91        let Some(end) = map(w.end_ms).or_else(|| map(w.end_ms - 1).map(|e| e + 1)) else {
92            continue;
93        };
94        if end <= start {
95            continue;
96        }
97        if (end - start).abs_diff(w.end_ms - w.start_ms) > MAP_DURATION_TOLERANCE_MS {
98            continue;
99        }
100        out.push(TimedWord::new(text, start, end));
101    }
102    out
103}