use docling_core::tree::{Formatting, ItemTree, TreeKind, TreeTrack};
use docling_core::{DoclingDocument, Node};
use crate::backend::markdown::escape_text;
use crate::backend::DeclarativeBackend;
use crate::error::ConversionError;
use crate::source::SourceDocument;
pub struct WebVttBackend;
#[derive(Default, Clone)]
struct Meta {
voice: Option<String>,
formatting: Option<Formatting>,
}
struct Run {
text: String,
meta: Meta,
}
enum Comp {
Text {
text: String,
terminator: bool,
},
Span {
tag: Tag,
annotation: Option<String>,
children: Vec<Comp>,
},
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Tag {
Bold,
Italic,
Underline,
Voice,
Transparent,
Ruby,
RubyText,
}
const MAX_SPAN_DEPTH: usize = 100;
struct Cue {
start: f64,
end: f64,
identifier: Option<String>,
payload: Vec<Comp>,
}
impl DeclarativeBackend for WebVttBackend {
fn convert(&self, source: &SourceDocument) -> Result<DoclingDocument, ConversionError> {
let content = source.text()?.replace("\r\n", "\n").replace('\r', "\n");
let mut doc = DoclingDocument::new(&source.name);
let mut tree = ItemTree::default();
let (header, body) = content.split_once('\n').unwrap_or((&content, ""));
if let Some(rest) = header.strip_prefix("WEBVTT") {
let title = rest.trim();
if !title.is_empty() {
doc.push(Node::Heading {
level: 1,
text: escape_text(title),
});
tree.add(None, None, text_kind("title", title, None));
}
}
append_cues(&mut doc, &mut tree, body);
tree.inline_whitespace = true;
doc.tree = Some(tree);
Ok(doc)
}
}
pub(crate) fn append_cues(doc: &mut DoclingDocument, tree: &mut ItemTree, body: &str) {
for block in blank_line_blocks(body) {
if block.starts_with("NOTE") || block.starts_with("STYLE") || block.starts_with("REGION") {
continue;
}
let Some(cue) = parse_cue_block(&block) else {
continue;
};
let mut paras: Vec<Vec<Run>> = vec![Vec::new()];
extract_components(&cue.payload, &mut Vec::new(), &mut paras);
for para in ¶s {
if para.is_empty() {
continue;
}
let text = para.iter().map(serialize_run).collect::<String>();
let text = text.trim().to_string();
if !text.is_empty() {
doc.push(Node::Paragraph { text });
}
let track = |run: &Run| TreeTrack {
start_time: cue.start,
end_time: cue.end,
identifier: cue.identifier.clone(),
voice: run.meta.voice.clone().filter(|v| !v.is_empty()),
};
if let [run] = para.as_slice() {
let id = tree.add(
None,
None,
text_kind("text", &run.text, run.meta.formatting),
);
tree.items[id].source = Some(track(run));
} else {
let group = tree.add(
None,
None,
TreeKind::Group {
label: "inline".into(),
name: "WebVTT cue span".into(),
},
);
for run in para {
let id = tree.add(
Some(group),
None,
text_kind("text", &run.text, run.meta.formatting),
);
tree.items[id].source = Some(track(run));
}
}
}
}
}
fn text_kind(label: &str, text: &str, formatting: Option<Formatting>) -> TreeKind {
TreeKind::Text {
label: label.into(),
text: text.into(),
orig: None,
formatting,
hyperlink: None,
level: None,
list: None,
}
}
fn blank_line_blocks(body: &str) -> Vec<String> {
let lines: Vec<&str> = body.trim().split('\n').collect();
let mut blocks: Vec<Vec<&str>> = vec![Vec::new()];
for (index, line) in lines.iter().enumerate() {
let separates = line.is_empty()
|| (line.trim().is_empty()
&& lines[index + 1..]
.iter()
.take(2)
.any(|following| following.contains("-->")));
if separates {
blocks.push(Vec::new());
} else {
blocks.last_mut().expect("a block").push(line);
}
}
blocks
.into_iter()
.filter(|b| !b.is_empty())
.map(|b| b.join("\n"))
.collect()
}
fn parse_cue_block(block: &str) -> Option<Cue> {
let lines: Vec<&str> = block.lines().collect();
let first = *lines.first()?;
let (identifier, timing_line, cue_lines) = if !first.contains("-->") && lines.len() > 1 {
(Some(first.to_string()), lines[1], &lines[2..])
} else {
(None, first, &lines[1..])
};
let mut parts = timing_line.split("-->");
let start = parts.next()?.trim();
let end = parts.next()?.trim();
if parts.next().is_some() {
return None;
}
let end = end.split([' ', '\t']).next().unwrap_or("");
let (start, end) = (parse_timestamp(start)?, parse_timestamp(end)?);
if end <= start {
return None;
}
let cue_text = cue_lines.join("\n").trim().to_string();
Some(Cue {
start,
end,
identifier,
payload: parse_components(&cue_text),
})
}
fn parse_timestamp(raw: &str) -> Option<f64> {
let (rest, millis) = raw.split_once('.')?;
if millis.len() != 3 || !millis.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
let fields: Vec<&str> = rest.split(':').collect();
let (hours, minutes, seconds) = match fields.as_slice() {
[m, s] => ("", *m, *s),
[h, m, s] if h.len() >= 2 => (*h, *m, *s),
_ => return None,
};
let two_digits = |f: &str| {
(f.len() == 2 && f.bytes().all(|b| b.is_ascii_digit()) && f.as_bytes()[0] <= b'5')
.then(|| f.parse::<u64>().ok())
.flatten()
};
let hours = if hours.is_empty() {
0
} else if hours.bytes().all(|b| b.is_ascii_digit()) {
hours.parse::<u64>().ok()?
} else {
return None;
};
let (minutes, seconds) = (two_digits(minutes)?, two_digits(seconds)?);
let millis: u64 = millis.parse().ok()?;
Some((hours * 3600 + minutes * 60 + seconds) as f64 + millis as f64 / 1000.0)
}
fn is_timestamp_tag(tag: &str) -> bool {
parse_timestamp(tag).is_some()
}
fn parse_components(cue_text: &str) -> Vec<Comp> {
let mut stack: Vec<(Option<Tag>, Option<String>, Vec<Comp>)> = Vec::new();
let mut root: Vec<Comp> = Vec::new();
let mut buf = String::new();
let mut rest = cue_text;
let flush = |buf: &mut String, target: &mut Vec<Comp>| -> bool {
if buf.is_empty() {
return true;
}
let text = std::mem::take(buf);
let pieces: Vec<&str> = text.split('\n').collect();
let n = pieces.len();
for (i, line) in pieces.iter().enumerate() {
if !line.is_empty() {
let Some(text) = html_unescape(line) else {
return false;
};
target.push(Comp::Text {
text,
terminator: i + 1 < n,
});
}
}
true
};
while let Some(lt) = rest.find('<') {
let Some(gt_rel) = rest[lt..].find('>') else {
break;
};
let tag = &rest[lt + 1..lt + gt_rel];
let after = &rest[lt + gt_rel + 1..];
if is_timestamp_tag(tag) {
buf.push_str(&rest[..lt]);
rest = after;
continue;
}
let Some((closing, kind, annotation)) = parse_tag(tag) else {
buf.push_str(&rest[..lt]);
rest = after;
continue;
};
buf.push_str(&rest[..lt]);
if !flush(&mut buf, stack.last_mut().map_or(&mut root, |s| &mut s.2)) {
return Vec::new();
}
rest = after;
let top = stack.last().and_then(|s| s.0);
if closing {
if stack.is_empty() || (kind == Tag::RubyText && top != Some(Tag::RubyText)) {
continue;
}
if kind == Tag::Ruby && top == Some(Tag::RubyText) {
let open = stack.pop().expect("an open rt");
close_span(open, stack.last_mut().map_or(&mut root, |s| &mut s.2));
}
let open = stack.pop().expect("an open span");
if open.0.is_some_and(|t| t != kind) {
return Vec::new();
}
close_span(open, stack.last_mut().map_or(&mut root, |s| &mut s.2));
} else {
if kind == Tag::RubyText && top != Some(Tag::Ruby) {
continue;
}
let annotation = match annotation.map(|a| html_unescape(&a)) {
Some(Some(a)) => Some(a),
Some(None) => return Vec::new(),
None => None,
};
let tag = (stack.len() < MAX_SPAN_DEPTH).then_some(kind);
stack.push((tag, annotation, Vec::new()));
}
}
buf.push_str(rest);
if !flush(&mut buf, stack.last_mut().map_or(&mut root, |s| &mut s.2)) {
return Vec::new();
}
while let Some(open) = stack.pop() {
close_span(open, stack.last_mut().map_or(&mut root, |s| &mut s.2));
}
root
}
fn html_unescape(text: &str) -> Option<String> {
if !text.contains('&') {
return Some(text.to_string());
}
let mut out = String::with_capacity(text.len());
let mut rest = text;
while let Some(amp) = rest.find('&') {
out.push_str(&rest[..amp]);
let tail = &rest[amp + 1..];
let (decoded, used) = char_reference(tail);
if decoded.contains(['\n', '\r']) {
return None;
}
out.push_str(&decoded);
rest = &tail[used..];
}
out.push_str(rest);
Some(out)
}
fn char_reference(tail: &str) -> (String, usize) {
if let Some(num) = tail.strip_prefix('#') {
let (hex, digits) = match num.strip_prefix(['x', 'X']) {
Some(h) => (true, h),
None => (false, num),
};
let len = digits
.bytes()
.take_while(|b| {
if hex {
b.is_ascii_hexdigit()
} else {
b.is_ascii_digit()
}
})
.count();
if len == 0 {
return ("&".into(), 0);
}
let consumed = 1 + usize::from(hex) + len + usize::from(digits[len..].starts_with(';'));
let n = u32::from_str_radix(&digits[..len], if hex { 16 } else { 10 }).unwrap_or(u32::MAX);
return (numeric_reference(n), consumed);
}
let len = tail
.char_indices()
.take_while(|(i, c)| {
*i < 128 && !matches!(c, '\t' | '\n' | '\x0c' | ' ' | '<' | '&' | '#' | ';')
})
.take(32)
.map(|(i, c)| i + c.len_utf8())
.last()
.unwrap_or(0);
if len == 0 {
return ("&".into(), 0);
}
let with_semi = len + usize::from(tail[len..].starts_with(';'));
let entity = |name: &str| {
web_atoms::NAMED_ENTITIES
.get(name)
.filter(|&&(a, _)| a != 0)
.map(|&(a, b)| {
[a, b]
.into_iter()
.filter(|&c| c != 0)
.filter_map(char::from_u32)
.collect::<String>()
})
};
if let Some(v) = entity(&tail[..with_semi]) {
return (v, with_semi);
}
let ends: Vec<usize> = tail[..with_semi]
.char_indices()
.map(|(i, _)| i)
.skip(2)
.collect();
for &end in ends.iter().rev() {
if let Some(v) = entity(&tail[..end]) {
return (v, end);
}
}
("&".into(), 0)
}
fn numeric_reference(n: u32) -> String {
match n {
0 => "\u{fffd}".into(),
0x0d => "\r".into(),
0x80..=0x9f => web_atoms::C1_REPLACEMENTS[(n - 0x80) as usize]
.unwrap_or_else(|| char::from_u32(n).expect("a C1 control"))
.to_string(),
0xd800..=0xdfff | 0x110000.. => "\u{fffd}".into(),
0x1..=0x8 | 0xb | 0xe..=0x1f | 0x7f | 0xfdd0..=0xfdef => String::new(),
n if n & 0xfffe == 0xfffe => String::new(),
n => char::from_u32(n).map(String::from).unwrap_or_default(),
}
}
fn close_span(open: (Option<Tag>, Option<String>, Vec<Comp>), target: &mut Vec<Comp>) {
match open {
(Some(tag), annotation, children) => target.push(Comp::Span {
tag,
annotation,
children,
}),
(None, _, children) => target.extend(children),
}
}
fn parse_tag(tag: &str) -> Option<(bool, Tag, Option<String>)> {
let (closing, body) = match tag.strip_prefix('/') {
Some(b) => (true, b),
None => (false, tag),
};
let name_len = body
.find(|c: char| !c.is_ascii_alphabetic())
.unwrap_or(body.len());
let (name, mut after) = body.split_at(name_len);
let kind = match name {
"i" => Tag::Italic,
"b" => Tag::Bold,
"u" => Tag::Underline,
"v" => Tag::Voice,
"c" | "lang" => Tag::Transparent,
"ruby" => Tag::Ruby,
"rt" => Tag::RubyText,
_ => return None,
};
while let Some(cls) = after.strip_prefix('.') {
let len = cls
.find(['\t', '\n', '\r', ' ', '&', '<', '>', '.'])
.unwrap_or(cls.len());
if len == 0 {
return None;
}
after = &cls[len..];
}
let annotation = match after.chars().next() {
None => None,
Some(' ' | '\t') => {
let a = &after[1..];
if a.contains(['\n', '\r']) {
return None;
}
let a = a.trim();
(!a.is_empty()).then(|| a.to_string())
}
Some(_) => return None,
};
Some((closing, kind, annotation))
}
fn extract_components(comps: &[Comp], parents: &mut Vec<Meta>, paras: &mut Vec<Vec<Run>>) {
for comp in comps {
let mut meta = parents.last().cloned().unwrap_or_default();
match comp {
Comp::Text { text, terminator } => {
paras.last_mut().expect("paragraph").push(Run {
text: text.clone(),
meta,
});
if *terminator {
paras.push(Vec::new());
}
}
Comp::Span {
tag,
annotation,
children,
} => {
match tag {
Tag::Bold => {
meta.formatting.get_or_insert_with(Formatting::default).bold = true
}
Tag::Italic => {
meta.formatting
.get_or_insert_with(Formatting::default)
.italic = true
}
Tag::Underline => {
meta.formatting
.get_or_insert_with(Formatting::default)
.underline = true
}
Tag::Voice => meta.voice = annotation.clone(),
Tag::Transparent | Tag::Ruby | Tag::RubyText => {}
}
parents.push(meta);
extract_components(children, parents, paras);
parents.pop();
}
}
}
}
fn serialize_run(run: &Run) -> String {
docling_core::inline::hoist(&run.text, |core| serialize_core(run, core))
}
fn serialize_core(run: &Run, text: &str) -> String {
let mut s = escape_text(text);
let fmt = run.meta.formatting.unwrap_or_default();
if fmt.bold {
s = format!("**{s}**");
}
if fmt.italic {
s = format!("*{s}*");
}
docling_core::fallback::underline(s, fmt.underline)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::format::InputFormat;
fn convert(vtt: &str) -> DoclingDocument {
let src = SourceDocument::from_bytes("t", InputFormat::Vtt, vtt.as_bytes().to_vec());
WebVttBackend.convert(&src).unwrap()
}
fn md(vtt: &str) -> String {
convert(vtt).export_to_markdown()
}
fn texts(vtt: &str) -> Vec<String> {
let v = convert(vtt).export_to_json_value();
v["texts"]
.as_array()
.unwrap()
.iter()
.map(|t| t["text"].as_str().unwrap().to_string())
.collect()
}
#[test]
fn character_references_resolve() {
let vtt = "WEBVTT\n\n00:01.000 --> 00:03.000\nIt's raining.\n\n\
00:03.000 --> 00:05.000\nCafé or café?\n\n\
00:05.000 --> 00:07.000\n<v René>Tom & Jerry</v>\n\n\
00:07.000 --> 00:09.000\nR&foo;d &\n\n\
00:09.000 --> 00:10.000\nbroken a b\n";
assert_eq!(
texts(vtt),
["It's raining.", "Café or café?", "Tom & Jerry", "R&foo;d &"]
);
let v = convert(vtt).export_to_json_value();
assert_eq!(v["texts"][2]["source"][0]["voice"], "René");
assert_eq!(
html_unescape("Ask © and & me ¬it; 😀 € �").as_deref(),
Some("Ask © and & me ¬it; 😀 € \u{fffd}")
);
assert_eq!(html_unescape("a b"), None);
let out = convert(vtt).export_to_vtt();
assert!(out.contains("\nIt's raining.\n"), "{out}");
assert!(out.ends_with("\nR&foo;d &"), "{out}");
assert!(out.contains("<v René>Tom & Jerry"), "{out}");
}
#[test]
fn whitespace_only_line_is_cue_text() {
let youtube = "WEBVTT\n\n00:00:00.160 --> 00:00:02.869 align:start position:0%\n \n\
hello<00:00:00.640><c> everyone</c>\n\n\
00:00:02.879 --> 00:00:05.110 align:start position:0%\nhello everyone\nwelcome back\n";
assert_eq!(
texts(youtube),
["hello", " everyone", "hello everyone", "welcome back"]
);
let separated =
"WEBVTT\n\n1\n00:01.000 --> 00:02.000\none\n \n2\n00:02.000 --> 00:03.000\n\
two\n \n00:03.000 --> 00:04.000\nthree\n";
assert_eq!(texts(separated), ["one", "two", "three"]);
let v = convert(separated).export_to_json_value();
assert_eq!(v["texts"][0]["source"][0]["identifier"], "1");
assert!(v["texts"][2]["source"][0]
.get("identifier")
.is_none_or(|i| i.is_null()));
}
#[test]
fn ruby_spans_keep_their_runs() {
let runs = |cue: &str| texts(&format!("WEBVTT\n\n00:01.000 --> 00:02.000\n{cue}\n"));
assert_eq!(
runs("<ruby>漢字<rt>かんじ</rt></ruby> is kanji"),
["漢字", "かんじ", " is kanji"]
);
assert_eq!(
runs("<ruby>漢字<rt>かんじ</ruby> is kanji"),
["漢字", "かんじ", " is kanji"]
);
assert_eq!(
runs("<ruby>日<rt>に</rt>本<rt>ほん</ruby>"),
["日", "に", "本", "ほん"]
);
assert_eq!(
runs("<ruby>日<rt>に<rt>ほん</rt></ruby>"),
["日", "に", "ほん"]
);
assert_eq!(
runs("<rt>x</rt> and <i><rt>y</rt></i>"),
["x", " and ", "y"]
);
assert!(runs("<ruby>a<rt>b<i>c</ruby>").is_empty());
}
#[test]
fn strips_voice_and_skips_notes() {
let out = md("WEBVTT\n\nNOTE hi\n\n00:01.000 --> 00:02.000\n<v Roger>Hello world\n");
assert_eq!(out.trim(), "Hello world");
}
#[test]
fn text_after_multiline_span_stays_in_reading_order() {
let out =
md("WEBVTT\n\n00:00:01.000 --> 00:00:05.000\n<v Bob>Hello\nthere</v> and afterwards\n");
assert_eq!(out.trim(), "Hello\n\nthere and afterwards");
}
#[test]
fn cue_timestamp_tags_are_stripped_from_the_run() {
let out = md("WEBVTT\n\n00:00:00.030 --> 00:00:02.669\nthe<00:00:00.389> quick<00:00:00.750> brown\n");
assert_eq!(out.trim(), "the quick brown");
}
#[test]
fn cr_and_crlf_terminators_parse() {
assert_eq!(
md("WEBVTT\r\r00:00:00.000 --> 00:00:01.000\rHello world\r").trim(),
"Hello world"
);
assert_eq!(
md("WEBVTT\r\n\r\n00:00:00.000 --> 00:00:01.000\r\nHello\r\nworld\r\n").trim(),
"Hello\n\nworld"
);
}
#[test]
fn nested_spans_serialize_with_the_faithful_join() {
let out = md("WEBVTT\n\n00:01.000 --> 00:02.000\n\
a <i>b <lang es>c</lang></i> d\n");
assert_eq!(out.trim(), "a *b* *c* d");
}
#[test]
fn tree_carries_track_source_and_formatting() {
let doc = convert(
"WEBVTT Kitchen talk\n\nid-1\n01:02:03.500 --> 01:02:04.750 line:0\n\
<v Chef>Hello <b>there</b></v>\nBye\n",
);
let json = doc.export_to_json();
let v: serde_json::Value = serde_json::from_str(&json).unwrap();
let texts = v["texts"].as_array().unwrap();
assert_eq!(texts[0]["label"], "title");
assert_eq!(texts[0]["text"], "Kitchen talk");
assert!(texts[0].get("source").is_none());
assert_eq!(v["groups"][0]["name"], "WebVTT cue span");
assert_eq!(v["groups"][0]["label"], "inline");
assert_eq!(texts[1]["parent"]["$ref"], "#/groups/0");
assert_eq!(texts[1]["text"], "Hello ");
assert_eq!(
texts[1]["source"],
serde_json::json!([{
"kind": "track",
"start_time": 3723.5,
"end_time": 3724.75,
"identifier": "id-1",
"voice": "Chef",
}])
);
assert!(texts[1].get("formatting").is_none());
assert_eq!(texts[2]["text"], "there");
assert_eq!(texts[2]["formatting"]["bold"], true);
assert_eq!(texts[2]["source"][0]["voice"], "Chef");
assert_eq!(texts[3]["text"], "Bye");
assert_eq!(texts[3]["parent"]["$ref"], "#/groups/0");
assert!(texts[3]["source"][0].get("voice").is_none());
assert_eq!(v["body"]["children"].as_array().unwrap().len(), 2);
}
#[test]
fn unclosed_spans_close_at_the_end_of_the_cue() {
let cue = |text: &str| md(&format!("WEBVTT\n\n00:01.000 --> 00:02.000\n{text}\n"));
assert_eq!(cue("<i>I'm thinking about").trim(), "*I'm thinking about*");
assert_eq!(cue("what she said</i>").trim(), "what she said");
assert_eq!(cue("He said <i>stop").trim(), "He said *stop*");
assert_eq!(cue("<v Bob>Hi <b>there").trim(), "Hi **there**");
assert_eq!(cue("<i>a <b>b</i></b>").trim(), "");
let v: serde_json::Value = serde_json::from_str(
&convert("WEBVTT\n\n00:01.000 --> 00:02.000\n<v Bob>Hi <b>there\n").export_to_json(),
)
.unwrap();
let texts = v["texts"].as_array().unwrap();
assert_eq!(texts[1]["text"], "there");
assert_eq!(texts[1]["formatting"]["bold"], true);
assert_eq!(texts[1]["source"][0]["voice"], "Bob");
}
#[test]
fn malformed_timings_drop_the_block() {
assert_eq!(md("WEBVTT\n\n00:01.000 -> 00:02.000\nlost\n").trim(), "");
assert_eq!(md("WEBVTT\n\n00:02.000 --> 00:01.000\nlost\n").trim(), "");
assert_eq!(
md("WEBVTT\n\n00:01.000 --> 00:02.000 align:start\n<v Ann>kept\n").trim(),
"kept"
);
}
}