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
28pub 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
47pub 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}