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}
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 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 pub fn start_secs(&self) -> f64 {
35 self.start_ms as f64 / 1000.0
36 }
37
38 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 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
59pub 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
71pub 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}