Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions docling_core/types/doc/webvtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -595,14 +595,20 @@ def _close_top_span() -> None:
closed = tag_stack.pop()
stack[-1].append(WebVTTCueComponentWithTerminator(component=cls._create_span(closed, children)))

def _add_text(text: str) -> None:
# A line break right after an end tag belongs to the span that just closed.
components = stack[-1]
if text.startswith("\n") and components and components[-1].terminator is None:
components[-1].terminator = WebVTTLineTerminator.LF
components.extend(cls._create_text_components(text))

pos = 0
matches = list(cls._pattern_tag.finditer(cue_text))
i = 0
while i < len(matches):
match = matches[i]
if match.start() > pos:
text = cue_text[pos : match.start()]
stack[-1].extend(cls._create_text_components(text))
_add_text(cue_text[pos : match.start()])
gps = {k: (v if v else None) for k, v in match.groupdict().items()}

# Following WebVTT 1, 6.4, <rt> only applies directly inside <ruby>; otherwise its
Expand All @@ -625,8 +631,7 @@ def _close_top_span() -> None:
i += 1

if pos < len(cue_text):
text = cue_text[pos:]
stack[-1].extend(cls._create_text_components(text))
_add_text(cue_text[pos:])

# Close any remaining unclosed spans at the end of the cue.
while tag_stack:
Expand Down
22 changes: 22 additions & 0 deletions tests/test_webvtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -654,3 +654,25 @@ def test_webvtt_file_cues_out_of_start_time_order() -> None:
# A model built directly still requires the cues to be in order.
with pytest.raises(ValidationError):
WebVTTFile(cue_blocks=[vtt[3], vtt[0]])


@pytest.mark.parametrize(
"cue_text",
[
"<i>Previously on the show</i>\nwe met the team.",
"<v Ann>Hello there</v>\n<v Bob>Hi Ann</v>",
"Text <b>bold</b>\n<i>italic</i> text",
"<ruby>a<rt>b</rt></ruby>\nc",
],
)
def test_webvtt_parse_line_break_after_end_tag(cue_text: str) -> None:
"""A line that ends with an end tag keeps its line terminator."""
timings = "00:01.000 --> 00:02.000\n"
block = WebVTTCueBlock.parse(timings + cue_text)
assert str(block) == timings + cue_text + "\n"


def test_webvtt_parse_line_break_after_stray_end_tag() -> None:
"""A stray end tag is ignored, and the line break after it is kept."""
block = WebVTTCueBlock.parse("00:01.000 --> 00:02.000\na</i>\nb")
assert str(block) == "00:01.000 --> 00:02.000\na\nb\n"
Loading