fix(subtitle): drop the XML declaration of TTML before pycaption reads it

This commit is contained in:
imSp4rky
2026-11-30 10:17:42 -07:00
parent ac7d10abb6
commit ea073209da
3 changed files with 44 additions and 1 deletions
-1
View File
@@ -117,7 +117,6 @@ filterwarnings = [
"ignore::aiohttp.web_exceptions.NotAppKeyWarning", "ignore::aiohttp.web_exceptions.NotAppKeyWarning",
"ignore::DeprecationWarning:pycaption.*", "ignore::DeprecationWarning:pycaption.*",
"ignore::DeprecationWarning:pytest_asyncio.*", "ignore::DeprecationWarning:pytest_asyncio.*",
"ignore::bs4.XMLParsedAsHTMLWarning",
] ]
addopts = "-ra --strict-markers" addopts = "-ra --strict-markers"
# dumps every thread's stack for a test that hangs; the CI job timeout alone leaves no trace # dumps every thread's stack for a test that hangs; the CI job timeout alone leaves no trace
+42
View File
@@ -15,9 +15,11 @@ from __future__ import annotations
import pathlib import pathlib
import re import re
import struct import struct
import warnings
import pycaption import pycaption
import pytest import pytest
from bs4 import XMLParsedAsHTMLWarning
from unshackle.core import binaries from unshackle.core import binaries
from unshackle.core.tracks import subtitle_convert as sc from unshackle.core.tracks import subtitle_convert as sc
@@ -655,3 +657,43 @@ def test_fttml_with_viewport_units_converts(tmp_path, monkeypatch):
out = sub.convert(Codec.SubRip, forced=True) out = sub.convert(Codec.SubRip, forced=True)
assert cue_count(out) == 3 assert cue_count(out) == 3
assert "Speed 10vw" in out.read_text("utf8") assert "Speed 10vw" in out.read_text("utf8")
TTML_DECLARATION = '<?xml version="1.0" encoding="UTF-8"?>'
TTML_CUE = ttml_fragment(("00:00:01.000", "00:00:02.000"))
@pytest.mark.parametrize(
("data", "codec", "cues"),
[
pytest.param((TTML_DECLARATION + TTML_CUE).encode(), Codec.TimedTextMarkupLang, 1, id="plain"),
pytest.param((TTML_DECLARATION + TTML_CUE).encode("utf-8-sig"), Codec.TimedTextMarkupLang, 1, id="bom"),
pytest.param(
(TTML_DECLARATION + TTML_CUE).encode("utf-8-sig") + b"\xff", Codec.TimedTextMarkupLang, 1, id="bom-bad-byte"
),
pytest.param((TTML_DECLARATION.upper() + TTML_CUE).encode(), Codec.TimedTextMarkupLang, 1, id="uppercase"),
pytest.param(f"\r\n {TTML_DECLARATION}{TTML_CUE}".encode(), Codec.TimedTextMarkupLang, 1, id="whitespace"),
pytest.param(
f'{TTML_DECLARATION}<tt xmlns="http://www.w3.org/ns/ttml"/>'.encode(),
Codec.TimedTextMarkupLang,
0,
id="self-closing-root",
),
pytest.param(
build_stpp_mp4(TTML_DECLARATION + TTML_CUE, f"{TTML_DECLARATION}<tt/>"), Codec.fTTML, 1, id="fttml"
),
],
)
def test_ttml_parse_raises_no_bs4_warning(data, codec, cues):
with warnings.catch_warnings():
warnings.simplefilter("error", XMLParsedAsHTMLWarning)
assert caption_total(Subtitle.parse(data, codec)) == cues
def test_ttml_parse_keeps_a_declaration_inside_the_cue_text():
cue = ttml_fragment(("00:00:01.000", "00:00:02.000", "<![CDATA[Hi <?xml a?> there]]>"))
expected = pycaption.DFXPReader().read(cue)
caption_set = Subtitle.parse((TTML_DECLARATION + cue).encode(), Codec.TimedTextMarkupLang)
assert pycaption.DFXPWriter().write(caption_set) == pycaption.DFXPWriter().write(expected)
+2
View File
@@ -824,6 +824,7 @@ class Subtitle(Track):
@staticmethod @staticmethod
def parse(data: bytes, codec: Subtitle.Codec) -> pycaption.CaptionSet: def parse(data: bytes, codec: Subtitle.Codec) -> pycaption.CaptionSet:
"""Parse a subtitle, without the XML declaration of a TTML file, which makes bs4 warn when pycaption reads it."""
if not isinstance(data, bytes): if not isinstance(data, bytes):
raise ValueError(f"Subtitle data must be parsed as bytes data, not {type(data).__name__}") raise ValueError(f"Subtitle data must be parsed as bytes data, not {type(data).__name__}")
@@ -843,6 +844,7 @@ class Subtitle(Track):
caption_set = pycaption.CaptionSet(caption_lists) caption_set = pycaption.CaptionSet(caption_lists)
elif codec == Subtitle.Codec.TimedTextMarkupLang: elif codec == Subtitle.Codec.TimedTextMarkupLang:
text = try_ensure_utf8(data).decode("utf8") text = try_ensure_utf8(data).decode("utf8")
text = re.sub(r"(?i)^[^<]*<\?xml\s[^>]*>", "", text)
text = text.replace("tt:", "") text = text.replace("tt:", "")
text = re.sub( text = re.sub(
r"tts:(?:extent|origin|padding)=(\"[^\"]*\"|'[^']*')", r"tts:(?:extent|origin|padding)=(\"[^\"]*\"|'[^']*')",