fix(subtitle): keep WebVTT-only cue markup out of converted subtitles

Strip cue classes, <v>/<lang>/ruby and karaoke timestamps before conversion, decode entities for SRT/SSA/ASS, load pysubs2 as utf-8-sig, and route sdh_method: filter-subs through convert_before_strip instead of raising.
This commit is contained in:
imSp4rky
2026-08-24 15:55:06 -06:00
parent d4690e5c6b
commit 1f96a4bd78
5 changed files with 182 additions and 19 deletions
+24 -16
View File
@@ -288,6 +288,7 @@ class Subtitle(Track):
text = Subtitle.sanitize_webvtt_timestamps(text)
text = Subtitle.sanitize_webvtt_cue_identifiers(text)
text = Subtitle.merge_overlapping_webvtt_cues(text)
text = Subtitle.strip_webvtt_cue_classes(text)
preserve_formatting = config.subtitle.get("preserve_formatting", True)
@@ -315,6 +316,29 @@ class Subtitle(Track):
# Keep the sanitized version even if parsing failed
self.path.write_text(text, encoding="utf8")
@staticmethod
def strip_webvtt_cue_classes(text: str) -> str:
"""
Reduce a cue payload to the markup every target format shares: ``<i>``, ``<b>``
and ``<u>`` without their class list. It removes class spans (``<c.foo>``),
``<v>``, ``<lang>``, ``<ruby>``/``<rt>`` and karaoke timestamps
(``<00:00:01.000>``).
A class only selects a CSS ``::cue`` rule that no player receives, so it never
carries styling, but it does break rendering. FFmpeg's SubRip reader treats a tag
name as a tag only while it matches ``[0-9a-zA-Z_/]``. The dot fails that test, so
FFmpeg prints ``<i.loud>`` as cue text and then emits the closing italic-off with
nothing opened. FFmpeg's WebVTT reader matches ``i``/``b``/``u`` exactly and drops
the rest, so there a class silently loses the styling instead. The tags this
method removes outright are the ones both readers already discard, and that
libass would draw as text if a conversion carried them into ASS.
"""
text = re.sub(r"</?c(?:\.[^\s>]*)?(?:\s[^>]*)?>", "", text)
text = re.sub(r"(</?)([ibu])\.[^\s>]*", r"\1\2", text)
text = re.sub(r"</?(?:v|lang)(?:\.[^\s>]*)?(?:\s[^>]*)?>", "", text)
text = re.sub(r"</?(?:ruby|rt)>", "", text)
return re.sub(r"<\d{2,}:\d{2}(?::\d{2})?\.\d{3}>", "", text)
@staticmethod
def strip_webvtt_timestamp_map(text: str) -> str:
"""
@@ -1000,22 +1024,6 @@ class Subtitle(Track):
return
elif sdh_method == "subtitleedit" and binaries.SubtitleEdit:
pass # Continue to SubtitleEdit section below
elif sdh_method == "filter-subs":
sub = Subtitles(self.path)
try:
sub.filter(rm_fonts=True, rm_ast=True, rm_music=True, rm_effects=True, rm_names=True, rm_author=True)
except ValueError as e:
if "too many values to unpack" in str(e):
# Retry without name removal if the error is due to multiple colons in time references
# This can happen with lines like "at 10:00 and 2:00"
sub = Subtitles(self.path)
sub.filter(
rm_fonts=True, rm_ast=True, rm_music=True, rm_effects=True, rm_names=False, rm_author=True
)
else:
raise
sub.save()
return
elif sdh_method == "auto":
if self.codec == Subtitle.Codec.SubRip:
try:
+29 -1
View File
@@ -14,7 +14,9 @@ the codec enum, ``parse``, sanitizers and cue helpers (the collaborators backend
from __future__ import annotations
import html
import logging
import re
import subprocess
import time
from pathlib import Path
@@ -204,7 +206,7 @@ class Pysubs2Backend:
return 1 if source in (Codec.SubStationAlpha, Codec.SubStationAlphav4) else 2
def convert(self, source: Codec, src: Path, target: Codec, out: Path) -> None:
subs = pysubs2.load(str(src), encoding="utf-8")
subs = pysubs2.load(str(src), encoding="utf-8-sig")
subs.save(str(out), format_=PYSUBS2_FORMATS[target], encoding="utf-8")
@@ -289,6 +291,30 @@ def resolve_backends(source: Codec, target: Codec, *, pin: Optional[str] = None)
return sorted(available, key=lambda b: b.rank(source, target))
# Formats with no entity syntax of their own. WebVTT and TTML keep theirs escaped.
PLAIN_TEXT_TARGETS: frozenset[Codec] = frozenset({Codec.SubRip, Codec.SubStationAlpha, Codec.SubStationAlphav4})
def decode_entities(out: Path) -> None:
"""
Turn HTML entities into real characters in a format that has no entity syntax.
FFmpeg's SubRip reader (mpv, VLC, Plex, Jellyfin) and libass draw ``&amp;`` and the
other entities as literal text. Backends differ here: subby and SubtitleEdit
decode, pysubs2 does not.
"""
text = out.read_text(encoding="utf8")
if "&" not in text:
return
decoded = re.sub(
r"&(?:#\d{1,7}|#[xX][0-9a-fA-F]{1,6}|[A-Za-z][A-Za-z0-9]{1,31});",
lambda m: html.unescape(m.group(0)),
text,
)
if decoded != text:
out.write_text(decoded, encoding="utf8")
def finalize(sub: Subtitle, target: Codec, out: Path) -> Path:
"""Swap the track onto the converted file and fire the OnConverted callback."""
original = sub.path
@@ -338,6 +364,8 @@ def run_conversion(sub: Subtitle, target: Codec, *, pin: Optional[str] = None, f
last_exc = e
log.debug(f"Subtitle backend {backend.name} failed ({source.name}->{target.name}): {e}")
continue
if target in PLAIN_TEXT_TARGETS:
decode_entities(out)
return finalize(sub, target, out)
raise RuntimeError(f"All subtitle backends failed for {source.name}->{target.name}") from last_exc