rightkit_transcript/
words.rs1use crate::contract::Transcript;
4use serde::{Deserialize, Serialize};
5
6pub const MAP_DURATION_TOLERANCE_MS: u64 = 20;
9
10#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
20 pub source_ms: Option<(u64, u64)>,
21}
22
23impl TimedWord {
24 pub fn new(text: impl Into<String>, start_ms: u64, end_ms: u64) -> Self {
25 Self {
26 text: text.into(),
27 start_ms,
28 end_ms,
29 source_ms: None,
30 }
31 }
32
33 pub fn from_seconds(text: impl Into<String>, start_s: f32, end_s: f32) -> Self {
36 Self::new(text, seconds_to_ms(start_s), seconds_to_ms(end_s))
37 }
38
39 pub fn start_secs(&self) -> f64 {
41 self.start_ms as f64 / 1000.0
42 }
43
44 pub fn end_secs(&self) -> f64 {
46 self.end_ms as f64 / 1000.0
47 }
48}
49
50impl<T: Into<String>> From<(T, u64, u64)> for TimedWord {
51 fn from((text, start_ms, end_ms): (T, u64, u64)) -> Self {
53 Self::new(text, start_ms, end_ms)
54 }
55}
56
57fn seconds_to_ms(s: f32) -> u64 {
58 if s.is_finite() && s > 0.0 {
59 (s as f64 * 1000.0).round() as u64
60 } else {
61 0
62 }
63}
64
65pub fn words_from_seconds<'a>(
69 items: impl IntoIterator<Item = (&'a str, f32, f32)>,
70) -> Vec<TimedWord> {
71 items
72 .into_iter()
73 .map(|(t, s, e)| TimedWord::from_seconds(t, s, e))
74 .collect()
75}
76
77pub fn words_from_transcript<F>(transcript: &Transcript, map: F) -> Vec<TimedWord>
87where
88 F: Fn(u64) -> Option<u64>,
89{
90 let mut out = Vec::new();
91 for w in &transcript.words {
92 let text = w.text.trim();
93 if text.is_empty() || w.end_ms <= w.start_ms {
94 continue;
95 }
96 let Some(start) = map(w.start_ms) else {
97 continue;
98 };
99 let Some(end) = map(w.end_ms).or_else(|| map(w.end_ms - 1).map(|e| e + 1)) else {
100 continue;
101 };
102 if end <= start {
103 continue;
104 }
105 if (end - start).abs_diff(w.end_ms - w.start_ms) > MAP_DURATION_TOLERANCE_MS {
106 continue;
107 }
108 let mut word = TimedWord::new(text, start, end);
109 word.source_ms = Some((w.start_ms, w.end_ms));
110 out.push(word);
111 }
112 out
113}