rightkit_transcript/
export.rs1use crate::segment::Cue;
4
5#[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
21fn stamp(ms: u64, sep: char) -> String {
22 format!(
23 "{:02}:{:02}:{:02}{sep}{:03}",
24 ms / 3_600_000,
25 ms / 60_000 % 60,
26 ms / 1000 % 60,
27 ms % 1000
28 )
29}
30
31fn safe_lines(cue: &Cue) -> Vec<String> {
34 cue.lines
35 .iter()
36 .map(|l| l.replace('\r', "").replace("-->", "->"))
37 .filter(|l| !l.trim().is_empty())
38 .collect()
39}
40
41pub fn to_srt(cues: &[Cue], nl: Newline) -> String {
43 let nl = nl.as_str();
44 let mut out = String::new();
45 let mut n = 0;
46 for c in cues {
47 let lines = safe_lines(c);
48 if lines.is_empty() {
49 continue;
50 }
51 n += 1;
52 out.push_str(&format!(
53 "{n}{nl}{} --> {}{nl}",
54 stamp(c.start_ms, ','),
55 stamp(c.end_ms, ',')
56 ));
57 for l in lines {
58 out.push_str(&l);
59 out.push_str(nl);
60 }
61 out.push_str(nl);
62 }
63 out
64}
65
66fn vtt_escape(s: &str) -> String {
67 s.replace('&', "&")
68 .replace('<', "<")
69 .replace('>', ">")
70}
71
72pub fn to_vtt(cues: &[Cue], nl: Newline) -> String {
74 let nl = nl.as_str();
75 let mut out = format!("WEBVTT{nl}{nl}");
76 for c in cues {
77 let lines = safe_lines(c);
78 if lines.is_empty() {
79 continue;
80 }
81 out.push_str(&format!(
82 "{} --> {}{nl}",
83 stamp(c.start_ms, '.'),
84 stamp(c.end_ms, '.')
85 ));
86 for l in lines {
87 out.push_str(&vtt_escape(&l));
88 out.push_str(nl);
89 }
90 out.push_str(nl);
91 }
92 out
93}
94
95pub fn to_plain_text(cues: &[Cue]) -> String {
97 cues.iter()
98 .map(|c| c.lines.join(" "))
99 .collect::<Vec<_>>()
100 .join("\n")
101}
102
103pub fn to_timing_json(cues: &[Cue], words: &[crate::words::TimedWord]) -> String {
106 let secs = |ms: u64| ms as f64 / 1000.0;
107 let seg: Vec<serde_json::Value> = cues
108 .iter()
109 .map(|c| serde_json::json!({ "text": c.lines.join(" "), "start": secs(c.start_ms), "end": secs(c.end_ms) }))
110 .collect();
111 let w: Vec<serde_json::Value> = words
112 .iter()
113 .map(|w| serde_json::json!({ "text": w.text, "start": secs(w.start_ms), "end": secs(w.end_ms) }))
114 .collect();
115 serde_json::to_string(&serde_json::json!({ "segments": seg, "words": w }))
116 .expect("json serialises")
117}