Skip to main content

rightkit_transcript/
export.rs

1//! SRT, WebVTT, plain-text and timing-JSON export. UTF-8, exact millisecond timestamps.
2
3use crate::segment::Cue;
4
5/// Line terminator for exported files.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum Newline {
8    Lf,
9    Crlf,
10}
11
12impl Newline {
13    fn as_str(self) -> &'static str {
14        match self {
15            Newline::Lf => "\n",
16            Newline::Crlf => "\r\n",
17        }
18    }
19}
20
21/// `HH:MM:SS<sep>mmm` for a millisecond offset: `,` gives the SubRip and whisper.cpp
22/// `timestamps` form (`01:02:03,004`), `.` gives the WebVTT form (`01:02:03.004`).
23/// Shared by [`to_srt`], [`to_vtt`] and any whisper-compatible JSON writer (#1095).
24pub fn subtitle_timestamp(ms: u64, sep: char) -> String {
25    format!(
26        "{:02}:{:02}:{:02}{sep}{:03}",
27        ms / 3_600_000,
28        ms / 60_000 % 60,
29        ms / 1000 % 60,
30        ms % 1000
31    )
32}
33
34/// Cue text lines made safe for either format: no CR, no blank line (which
35/// would end the cue) and no `-->` (which would read as a timing line).
36fn safe_lines(cue: &Cue) -> Vec<String> {
37    cue.lines
38        .iter()
39        .map(|l| l.replace('\r', "").replace("-->", "->"))
40        .filter(|l| !l.trim().is_empty())
41        .collect()
42}
43
44/// SubRip: numbered cues, `HH:MM:SS,mmm --> HH:MM:SS,mmm`, blank line after each.
45pub fn to_srt(cues: &[Cue], nl: Newline) -> String {
46    let nl = nl.as_str();
47    let mut out = String::new();
48    let mut n = 0;
49    for c in cues {
50        let lines = safe_lines(c);
51        if lines.is_empty() {
52            continue;
53        }
54        n += 1;
55        out.push_str(&format!(
56            "{n}{nl}{} --> {}{nl}",
57            subtitle_timestamp(c.start_ms, ','),
58            subtitle_timestamp(c.end_ms, ',')
59        ));
60        for l in lines {
61            out.push_str(&l);
62            out.push_str(nl);
63        }
64        out.push_str(nl);
65    }
66    out
67}
68
69fn vtt_escape(s: &str) -> String {
70    s.replace('&', "&amp;")
71        .replace('<', "&lt;")
72        .replace('>', "&gt;")
73}
74
75/// WebVTT: `WEBVTT` header, `HH:MM:SS.mmm` timestamps, `&`/`<`/`>` escaped.
76pub fn to_vtt(cues: &[Cue], nl: Newline) -> String {
77    let nl = nl.as_str();
78    let mut out = format!("WEBVTT{nl}{nl}");
79    for c in cues {
80        let lines = safe_lines(c);
81        if lines.is_empty() {
82            continue;
83        }
84        out.push_str(&format!(
85            "{} --> {}{nl}",
86            subtitle_timestamp(c.start_ms, '.'),
87            subtitle_timestamp(c.end_ms, '.')
88        ));
89        for l in lines {
90            out.push_str(&vtt_escape(&l));
91            out.push_str(nl);
92        }
93        out.push_str(nl);
94    }
95    out
96}
97
98/// Plain text: one line per cue.
99pub fn to_plain_text(cues: &[Cue]) -> String {
100    cues.iter()
101        .map(|c| c.lines.join(" "))
102        .collect::<Vec<_>>()
103        .join("\n")
104}
105
106/// Timing JSON shared by every consumer (same shape `rightkit-asr` emits):
107/// `segments` are the cues, `words` the word timings, times in seconds.
108pub fn to_timing_json(cues: &[Cue], words: &[crate::words::TimedWord]) -> String {
109    let secs = |ms: u64| ms as f64 / 1000.0;
110    let seg: Vec<serde_json::Value> = cues
111        .iter()
112        .map(|c| serde_json::json!({ "text": c.lines.join(" "), "start": secs(c.start_ms), "end": secs(c.end_ms) }))
113        .collect();
114    let w: Vec<serde_json::Value> = words
115        .iter()
116        .map(|w| serde_json::json!({ "text": w.text, "start": secs(w.start_ms), "end": secs(w.end_ms) }))
117        .collect();
118    serde_json::to_string(&serde_json::json!({ "segments": seg, "words": w }))
119        .expect("json serialises")
120}