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
21pub 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
34fn 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
44pub 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('&', "&")
71 .replace('<', "<")
72 .replace('>', ">")
73}
74
75pub 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
98pub fn to_plain_text(cues: &[Cue]) -> String {
100 cues.iter()
101 .map(|c| c.lines.join(" "))
102 .collect::<Vec<_>>()
103 .join("\n")
104}
105
106pub 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}