1use serde_json::Value;
27
28use crate::DoclingDocument;
29
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32pub struct VttExportOptions {
33 pub omit_hours_if_zero: bool,
35 pub omit_voice_end: bool,
38}
39
40impl Default for VttExportOptions {
41 fn default() -> Self {
44 Self {
45 omit_hours_if_zero: false,
46 omit_voice_end: true,
47 }
48 }
49}
50
51pub(crate) fn to_vtt(doc: &DoclingDocument, options: &VttExportOptions) -> String {
52 let (json, _tables) = crate::json::to_json_typed_tables(doc, false);
54 let mut parts = Vec::new();
55 let mut inline_done = std::collections::HashSet::new();
56 walk(&json, &json["body"], &mut parts, &mut inline_done);
57 serialize_doc(&parts, options)
58}
59
60struct Part<'a> {
62 text: String,
63 title: bool,
64 track: Option<&'a Value>,
65}
66
67fn resolve<'a>(json: &'a Value, r: &str) -> Option<&'a Value> {
68 let path = r.strip_prefix("#/")?;
69 if path == "body" {
70 return Some(&json["body"]);
71 }
72 let (bucket, idx) = path.split_once('/')?;
73 json.get(bucket)?.get(idx.parse::<usize>().ok()?)
74}
75
76fn children<'a>(json: &'a Value, item: &'a Value) -> Vec<&'a Value> {
77 item["children"]
78 .as_array()
79 .into_iter()
80 .flatten()
81 .filter_map(|c| c["$ref"].as_str().and_then(|r| resolve(json, r)))
82 .collect()
83}
84
85fn is_text(item: &Value) -> bool {
86 item["self_ref"]
87 .as_str()
88 .is_some_and(|r| r.starts_with("#/texts/"))
89}
90
91fn walk<'a>(
96 json: &'a Value,
97 item: &'a Value,
98 parts: &mut Vec<Part<'a>>,
99 done: &mut std::collections::HashSet<&'a str>,
100) {
101 let self_ref = item["self_ref"].as_str().unwrap_or("");
102 let body_layer = item["content_layer"].as_str().is_none_or(|l| l == "body");
103 if body_layer && !done.contains(self_ref) {
104 if is_text(item) {
105 if let Some(part) = text_part(item, false) {
106 parts.push(part);
107 }
108 } else if item["label"] == "inline" && self_ref.starts_with("#/groups/") {
109 let kids = children(json, item);
110 let mut text = String::new();
111 for kid in &kids {
112 if let Some(r) = kid["self_ref"].as_str() {
113 done.insert(r);
114 }
115 if is_text(kid) && kid["content_layer"].as_str().is_none_or(|l| l == "body") {
116 if let Some(part) = text_part(kid, true) {
117 text.push_str(&part.text);
118 }
119 }
120 }
121 let text = remove_pairs_until_stable(text);
122 if !text.is_empty() {
123 let first = kids.first().copied();
125 parts.push(Part {
126 text,
127 title: false,
128 track: first.and_then(track_of),
129 });
130 }
131 }
132 }
133 let picture = self_ref.starts_with("#/pictures/");
134 let captions: Vec<&str> = item["captions"]
135 .as_array()
136 .into_iter()
137 .flatten()
138 .filter_map(|c| c["$ref"].as_str())
139 .collect();
140 for (child_ref, child) in item["children"]
141 .as_array()
142 .into_iter()
143 .flatten()
144 .filter_map(|c| c["$ref"].as_str())
145 .filter_map(|r| Some((r, resolve(json, r)?)))
146 {
147 if picture && !captions.contains(&child_ref) {
148 continue;
149 }
150 walk(json, child, parts, done);
151 }
152}
153
154fn track_of(item: &Value) -> Option<&Value> {
155 let source = item["source"].as_array()?.first()?;
156 (source["kind"] == "track").then_some(source)
157}
158
159fn text_part(item: &Value, inline: bool) -> Option<Part<'_>> {
162 let text = item["text"].as_str().unwrap_or("");
163 if item["label"] == "title" {
164 return Some(Part {
165 text: text.to_string(),
166 title: true,
167 track: None,
168 });
169 }
170 let track = track_of(item)?;
171 if text.is_empty() {
172 return None;
173 }
174 let mut out = escape(text);
175 let f = &item["formatting"];
176 for (flag, tag) in [("bold", "b"), ("italic", "i"), ("underline", "u")] {
177 if f[flag].as_bool() == Some(true) {
178 out = format!("<{tag}>{out}</{tag}>");
179 }
180 }
181 if let Some(voice) = track["voice"].as_str().filter(|v| !v.is_empty()) {
182 out = format!(
183 "<v {}>{out}</v>",
184 voice.replace('&', "&").replace('>', ">")
185 );
186 }
187 if inline {
188 out = remove_pairs_until_stable(out);
189 }
190 Some(Part {
191 text: out,
192 title: false,
193 track: Some(track),
194 })
195}
196
197fn escape(text: &str) -> String {
199 text.replace('&', "&").replace('<', "<")
200}
201
202fn millis(seconds: f64) -> u64 {
205 (seconds * 1000.0).round_ties_even().max(0.0) as u64
206}
207
208fn timestamp_seconds(ms: u64) -> f64 {
211 let (h, rest) = (ms / 3_600_000, ms % 3_600_000);
212 let (m, rest) = (rest / 60_000, rest % 60_000);
213 let (s, milli) = (rest / 1000, rest % 1000);
214 (h * 3600 + m * 60 + s) as f64 + milli as f64 / 1000.0
215}
216
217fn format_timestamp(ms: u64, omit_hours_if_zero: bool) -> String {
218 let (h, rest) = (ms / 3_600_000, ms % 3_600_000);
219 let (m, rest) = (rest / 60_000, rest % 60_000);
220 let (s, milli) = (rest / 1000, rest % 1000);
221 if omit_hours_if_zero && h == 0 {
222 format!("{m:02}:{s:02}.{milli:03}")
223 } else {
224 format!("{h:02}:{m:02}:{s:02}.{milli:03}")
225 }
226}
227
228struct Cue {
229 identifier: Option<String>,
230 start: u64,
231 end: u64,
232 text: String,
233}
234
235fn cue_timings(start_s: f64, end_s: f64) -> (u64, u64) {
242 let (start, end) = (millis(start_s), millis(end_s));
243 if end > start {
244 return (start, end);
245 }
246 crate::debug_log!(
247 "vtt: track segment {start_s}..{end_s} collapses onto {} at WebVTT millisecond \
248 precision, extending the cue end to {}",
249 format_timestamp(start, false),
250 format_timestamp(start + 1, false)
251 );
252 (start, start + 1)
253}
254
255fn serialize_doc(parts: &[Part], options: &VttExportOptions) -> String {
257 let mut title: Option<&str> = None;
258 let mut cues: Vec<Cue> = Vec::new();
259 for part in parts {
260 if part.text.is_empty() {
261 continue;
262 }
263 if part.title {
264 title = Some(&part.text);
265 continue;
266 }
267 let Some(track) = part.track else {
268 continue;
269 };
270 let start_s = track["start_time"].as_f64().unwrap_or(0.0);
271 let end_s = track["end_time"].as_f64().unwrap_or(0.0);
272 let identifier = track["identifier"].as_str().map(str::to_string);
273 if let Some(cue) = cues.last_mut().filter(|c| {
274 c.identifier == identifier
275 && timestamp_seconds(c.start) == start_s
276 && timestamp_seconds(c.end) == end_s
277 }) {
278 let joined = format!("{}\n{}", cue.text.trim_end(), part.text);
279 cue.text = remove_pairs_until_stable(joined);
280 } else {
281 let (start, end) = cue_timings(start_s, end_s);
282 cues.push(Cue {
283 identifier,
284 start,
285 end,
286 text: part.text.clone(),
287 });
288 }
289 }
290 let mut out = match title {
291 Some(t) => format!("WEBVTT {t}\n"),
292 None => "WEBVTT\n".to_string(),
293 };
294 for cue in &cues {
295 out.push('\n');
296 if let Some(id) = &cue.identifier {
297 out.push_str(id);
298 out.push('\n');
299 }
300 out.push_str(&format_timestamp(cue.start, options.omit_hours_if_zero));
301 out.push_str(" --> ");
302 out.push_str(&format_timestamp(cue.end, options.omit_hours_if_zero));
303 out.push('\n');
304 let payload = cue.text.trim_end_matches('\n');
305 if options.omit_voice_end && is_single_voice_span(payload) {
306 out.push_str(payload.strip_suffix("</v>").unwrap_or(payload));
307 } else {
308 out.push_str(payload);
309 }
310 out.push('\n');
311 }
312 out.trim_end_matches('\n').to_string()
313}
314
315fn is_single_voice_span(payload: &str) -> bool {
318 if !payload.starts_with("<v") || !payload.ends_with("</v>") {
319 return false;
320 }
321 let mut depth = 0i32;
324 let mut i = 0;
325 let b = payload.as_bytes();
326 while i < b.len() {
327 if b[i] == b'<' {
328 let close = payload[i..].find('>').map(|j| i + j);
329 let Some(end) = close else { return false };
330 let tag = &payload[i + 1..end];
331 if tag.starts_with('/') {
332 depth -= 1;
333 if depth == 0 && end + 1 != b.len() {
334 return false;
335 }
336 } else if !tag.chars().next().is_some_and(|c| c.is_ascii_digit()) {
337 depth += 1;
339 }
340 i = end + 1;
341 } else {
342 if depth == 0 {
343 return false;
344 }
345 i += 1;
346 }
347 }
348 depth == 0
349}
350
351fn span_name(s: &str) -> Option<&str> {
353 if s.starts_with("lang") {
354 Some("lang")
355 } else {
356 s.chars()
357 .next()
358 .filter(|c| "bciuv".contains(*c))
359 .map(|_| &s[..1])
360 }
361}
362
363fn start_tag<'a>(s: &'a str, want: Option<&str>) -> Option<(&'a str, &'a str, &'a str, usize)> {
366 let rest = s.strip_prefix('<')?;
367 let name = match want {
368 Some(w) => rest.starts_with(w).then_some(&rest[..w.len()])?,
369 None => span_name(rest)?,
370 };
371 let mut pos = 1 + name.len();
372 let classes_start = pos;
374 loop {
375 let tail = &s[pos..];
376 let Some(after_dot) = tail.strip_prefix('.') else {
377 break;
378 };
379 let word = after_dot
380 .char_indices()
381 .find(|(_, c)| !(c.is_alphanumeric() || *c == '_'))
382 .map_or(after_dot.len(), |(i, _)| i);
383 if word == 0 {
384 break;
385 }
386 pos += 1 + word;
387 }
388 let classes = &s[classes_start..pos];
389 let tail = &s[pos..];
391 if let Some(stripped) = tail.strip_prefix('>') {
392 let _ = stripped;
393 return Some((name, classes, "", pos + 1));
394 }
395 let ws = tail
396 .char_indices()
397 .find(|(_, c)| !c.is_whitespace())
398 .map_or(tail.len(), |(i, _)| i);
399 if ws == 0 {
400 return None;
401 }
402 let anno_start = pos + ws;
403 let close = s[anno_start..].find('>')?;
404 if close == 0 {
405 return None;
406 }
407 Some((
408 name,
409 classes,
410 &s[anno_start..anno_start + close],
411 anno_start + close + 1,
412 ))
413}
414
415fn merge_adjacent(text: &str) -> String {
421 let mut out = String::with_capacity(text.len());
422 let mut i = 0;
423 while i < text.len() {
424 if let Some(m) = match_adjacent(&text[i..]) {
425 out.push_str(&m.0);
426 i += m.1;
427 } else {
428 let c = text[i..].chars().next().expect("in bounds");
429 out.push(c);
430 i += c.len_utf8();
431 }
432 }
433 out
434}
435
436fn match_adjacent(s: &str) -> Option<(String, usize)> {
437 let (name, classes1, anno1, open_len) = start_tag(s, None)?;
438 let end_tag = format!("</{name}>");
439 let close = s[open_len..].find(&end_tag)?;
440 let content = &s[open_len..open_len + close];
441 if content.contains('\n') {
442 return None;
443 }
444 let after_close = open_len + close + end_tag.len();
445 let tail = &s[after_close..];
446 let ws_len = tail
447 .char_indices()
448 .find(|(_, c)| !c.is_whitespace())
449 .map_or(tail.len(), |(i, _)| i);
450 let ws = &tail[..ws_len];
451 let (_, classes2, anno2, open2_len) = start_tag(&tail[ws_len..], Some(name))?;
452 let total = after_close + ws_len + open2_len;
453 if classes1 == classes2 && anno1 == anno2 {
454 let anno = if anno1.is_empty() {
455 String::new()
456 } else {
457 format!(" {anno1}")
458 };
459 Some((format!("<{name}{classes1}{anno}>{content}{ws}"), total))
460 } else {
461 Some((s[..total].to_string(), total))
462 }
463}
464
465fn merge_around(text: &str) -> String {
467 let mut out = String::with_capacity(text.len());
468 let mut i = 0;
469 while i < text.len() {
470 if let Some((keep, len)) = match_around(&text[i..]) {
471 out.push_str(keep);
472 i += len;
473 } else {
474 let c = text[i..].chars().next().expect("in bounds");
475 out.push(c);
476 i += c.len_utf8();
477 }
478 }
479 out
480}
481
482fn match_around(s: &str) -> Option<(&str, usize)> {
483 let rest = s.strip_prefix("</")?;
484 let name = span_name(rest)?;
485 let after_name = 2 + name.len();
486 if !s[after_name..].starts_with('>') {
487 return None;
488 }
489 let mid_start = after_name + 1;
490 let tail = &s[mid_start..];
491 if !tail.starts_with('<') {
492 return None;
493 }
494 let mid_close = tail[1..].find('>')? + 1;
495 if mid_close < 2 {
496 return None;
497 }
498 let mid = &tail[..mid_close + 1];
499 let (_, _, _, open_len) = start_tag(&tail[mid.len()..], Some(name))?;
500 Some((mid, mid_start + mid.len() + open_len))
501}
502
503fn remove_pairs_until_stable(mut text: String) -> String {
505 loop {
506 let next = merge_around(&merge_adjacent(&text));
507 if next == text {
508 return text;
509 }
510 text = next;
511 }
512}
513
514#[cfg(test)]
515mod tests {
516 use super::*;
517
518 #[test]
519 fn merges_like_upstreams_patterns() {
520 let cases = [
523 ("<i>a</i> <i>b</i>", "<i>a b</i>"),
524 (
525 "<v Speaker A>OK,</v>\n<v Speaker A>I think</v>",
526 "<v Speaker A>OK,\nI think</v>",
527 ),
528 ("<v A>x</v> <v B>y</v>", "<v A>x</v> <v B>y</v>"),
529 (
530 "<i><b>unexpected</b></i><i> </i><u><i>arcobaleno</i></u><i> of flavors</i>",
531 "<i><b>unexpected</b> <u>arcobaleno</u> of flavors</i>",
532 ),
533 ("<b.loud>a</b><b.loud>b</b>", "<b.loud>ab</b>"),
534 ("<b.loud>a</b><b>b</b>", "<b.loud>a</b><b>b</b>"),
535 ("<i>a\nb</i><i>c</i>", "<i>a\nb</i><i>c</i>"),
537 ("<lang en>x</lang><lang en>y</lang>", "<lang en>xy</lang>"),
538 ("<u>a</u><i></i><u>b</u>", "<u>a</u><i></i><u>b</u>"),
540 ("<b>a</b> \n <b>c</b>", "<b>a \n c</b>"),
541 ];
542 for (input, want) in cases {
543 assert_eq!(
544 remove_pairs_until_stable(input.to_string()),
545 want,
546 "{input}"
547 );
548 }
549 }
550
551 fn segment(start: f64, end: f64, words: &str) -> crate::Node {
554 crate::Node::Track {
555 track: crate::tree::TreeTrack {
556 start_time: start,
557 end_time: end,
558 identifier: None,
559 voice: None,
560 },
561 cue: words.into(),
562 inner: Box::new(crate::Node::Paragraph {
563 text: format!("[time: {start}-{end}] {words}"),
564 }),
565 }
566 }
567
568 #[test]
572 fn sub_millisecond_cue_stays_serializable() {
573 let mut doc = DoclingDocument::new("sub-millisecond-cue");
574 doc.push(segment(11.00001, 11.00002, "short cue"));
575 doc.push(segment(12.0, 13.5, "normal cue"));
576 assert_eq!(
577 doc.export_to_vtt(),
578 "WEBVTT\n\n00:00:11.000 --> 00:00:11.001\nshort cue\n\n\
579 00:00:12.000 --> 00:00:13.500\nnormal cue"
580 );
581 }
582
583 #[test]
588 fn asr_segments_become_cues_like_upstream() {
589 let mut doc = DoclingDocument::new("talk");
590 for (s, e, t) in [
591 (0.0, 2.345678, "And so my fellow Americans"),
592 (2.5, 2.501, "ask not"),
593 (3.0, 4.25, "what your country"),
594 (3.0, 4.25, "can do for you"),
595 (3661.2, 3662.0, "late remark"),
596 ] {
597 doc.push(segment(s, e, t));
598 }
599 assert_eq!(
600 doc.export_to_vtt(),
601 "WEBVTT\n\n00:00:00.000 --> 00:00:02.346\nAnd so my fellow Americans\n\n\
602 00:00:02.500 --> 00:00:02.501\nask not\n\n00:00:03.000 --> 00:00:04.250\n\
603 what your country\ncan do for you\n\n01:01:01.200 --> 01:01:02.000\nlate remark"
604 );
605 let json = doc.export_to_json_value();
608 assert_eq!(json["texts"][0]["text"], "And so my fellow Americans");
609 assert_eq!(json["texts"][0]["orig"], "And so my fellow Americans");
610 assert_eq!(
611 json["texts"][0]["source"],
612 serde_json::json!([{"kind": "track", "start_time": 0.0, "end_time": 2.345678}])
613 );
614 assert!(doc
616 .export_to_markdown()
617 .starts_with("[time: 0-2.345678] And so"));
618 }
619
620 #[test]
623 fn untimed_documents_are_the_bare_header() {
624 let mut doc = DoclingDocument::new("x");
625 doc.push(crate::Node::Heading {
626 level: 1,
627 text: "My Title".into(),
628 });
629 doc.push(crate::Node::Paragraph {
630 text: "no timing".into(),
631 });
632 assert_eq!(doc.export_to_vtt(), "WEBVTT My Title");
633 let mut doc = DoclingDocument::new("y");
634 doc.push(crate::Node::Paragraph {
635 text: "no timing".into(),
636 });
637 assert_eq!(doc.export_to_vtt(), "WEBVTT");
638 }
639
640 #[test]
643 fn cue_text_is_escaped() {
644 let mut doc = DoclingDocument::new("e");
645 doc.push(segment(1.0, 2.0, "Q&A: a < b > c"));
646 assert_eq!(
647 doc.export_to_vtt(),
648 "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nQ&A: a < b > c"
649 );
650 }
651
652 #[test]
653 fn timestamps_round_half_even_and_format() {
654 assert_eq!(format_timestamp(millis(4.963), false), "00:00:04.963");
655 assert_eq!(format_timestamp(millis(14_586.5), false), "04:03:06.500");
656 assert_eq!(format_timestamp(millis(62.0), true), "01:02.000");
657 assert_eq!(millis(0.0005), 0); assert_eq!(millis(0.0015), 2);
659 assert_eq!(timestamp_seconds(millis(4.963)), 4.963);
660 }
661
662 #[test]
663 fn voice_end_is_omitted_only_for_a_lone_voice_span() {
664 assert!(is_single_voice_span("<v A>OK,\nI think</v>"));
665 assert!(is_single_voice_span("<v A><i>x</i> y</v>"));
666 assert!(!is_single_voice_span("<v Esme>Hee!</v> <i>laughter</i>"));
667 assert!(!is_single_voice_span("<v A>x</v><v B>y</v>"));
668 assert!(!is_single_voice_span("plain"));
669 }
670}