use crate::contract::Transcript;
use serde::{Deserialize, Serialize};
pub const MAP_DURATION_TOLERANCE_MS: u64 = 20;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TimedWord {
pub text: String,
pub start_ms: u64,
pub end_ms: u64,
}
impl TimedWord {
pub fn new(text: impl Into<String>, start_ms: u64, end_ms: u64) -> Self {
Self {
text: text.into(),
start_ms,
end_ms,
}
}
pub fn from_seconds(text: impl Into<String>, start_s: f32, end_s: f32) -> Self {
Self::new(text, seconds_to_ms(start_s), seconds_to_ms(end_s))
}
pub fn start_secs(&self) -> f64 {
self.start_ms as f64 / 1000.0
}
pub fn end_secs(&self) -> f64 {
self.end_ms as f64 / 1000.0
}
}
impl<T: Into<String>> From<(T, u64, u64)> for TimedWord {
fn from((text, start_ms, end_ms): (T, u64, u64)) -> Self {
Self::new(text, start_ms, end_ms)
}
}
fn seconds_to_ms(s: f32) -> u64 {
if s.is_finite() && s > 0.0 {
(s as f64 * 1000.0).round() as u64
} else {
0
}
}
pub fn words_from_seconds<'a>(
items: impl IntoIterator<Item = (&'a str, f32, f32)>,
) -> Vec<TimedWord> {
items
.into_iter()
.map(|(t, s, e)| TimedWord::from_seconds(t, s, e))
.collect()
}
pub fn words_from_transcript<F>(transcript: &Transcript, map: F) -> Vec<TimedWord>
where
F: Fn(u64) -> Option<u64>,
{
let mut out = Vec::new();
for w in &transcript.words {
let text = w.text.trim();
if text.is_empty() || w.end_ms <= w.start_ms {
continue;
}
let Some(start) = map(w.start_ms) else {
continue;
};
let Some(end) = map(w.end_ms).or_else(|| map(w.end_ms - 1).map(|e| e + 1)) else {
continue;
};
if end <= start {
continue;
}
if (end - start).abs_diff(w.end_ms - w.start_ms) > MAP_DURATION_TOLERANCE_MS {
continue;
}
out.push(TimedWord::new(text, start, end));
}
out
}