Files
unshackle/unshackle/core/tracks/subtitle_convert.py
T

496 lines
19 KiB
Python

"""
Subtitle conversion backend registry.
Routing is data-driven: each backend declares which (source -> target) codec pairs it can
read/write, whether it is available in the current environment, and a preference rank.
``resolve_backends`` filters the registry to the available backends that can convert the
requested pair and orders them by rank. ``run_conversion`` tries each in turn (a real
fallback chain) until one succeeds.
The public entry point stays ``Subtitle.convert`` / ``Subtitle.strip_hearing_impaired`` in
subtitle.py. This module only holds the selection + conversion logic so subtitle.py keeps
the codec enum, ``parse``, sanitizers and cue helpers (the collaborators backends reuse).
"""
from __future__ import annotations
import html
import logging
import math
import re
from collections.abc import Mapping
from itertools import pairwise
from pathlib import Path
from typing import Any, Protocol
import pycaption
import pysubs2
from subby import CommonIssuesFixer, SAMIConverter, WebVTTConverter, WVTTConverter
from unshackle.core import binaries
from unshackle.core.tracks.subtitle import Subtitle
from unshackle.core.utils.subprocess import run_tool
log = logging.getLogger("subtitle")
Codec = Subtitle.Codec
# SubtitleEdit (and the cross-platform seconv port) /convert format names.
# Shared by SubtitleEditBackend, strip_hearing_impaired and reverse_rtl so the map lives once.
SUBTITLE_EDIT_FORMATS: dict[Codec, str] = {
Codec.SubRip: "subrip",
Codec.SubStationAlpha: "substationalpha",
Codec.SubStationAlphav4: "advancedsubstationalpha",
Codec.TimedTextMarkupLang: "timedtext1.0",
Codec.WebVTT: "webvtt",
Codec.SAMI: "sami",
Codec.MicroDVD: "microdvd",
}
# pycaption can only WRITE these three formats.
PYCAPTION_WRITERS = {
Codec.SubRip: pycaption.SRTWriter,
Codec.TimedTextMarkupLang: pycaption.DFXPWriter,
Codec.WebVTT: pycaption.WebVTTWriter,
}
PYSUBS2_FORMATS: dict[Codec, str] = {
Codec.SubRip: "srt",
Codec.SubStationAlpha: "ssa",
Codec.SubStationAlphav4: "ass",
Codec.WebVTT: "vtt",
Codec.TimedTextMarkupLang: "ttml",
Codec.SAMI: "sami",
Codec.MicroDVD: "microdvd",
Codec.MPL2: "mpl2",
Codec.TMP: "tmp",
}
def is_seconv(binary: object) -> bool:
"""True for the SubtitleEdit 5+ CLI (seconv). 4.x binaries need legacy /convert syntax."""
name = str(binary).replace("\\", "/").rsplit("/", 1)[-1]
return name.lower().rsplit(".", 1)[0] == "seconv"
def subtitleedit_args(
binary: object,
src: Path,
fmt: str,
*,
output_folder: Path | None = None,
convert_colors: bool = False,
remove_hi: bool = False,
reverse_rtl: bool = False,
) -> list[str]:
"""
Assemble a SubtitleEdit batch-convert command in 5.x (seconv ``--flags``) or 4.x
(``/convert /flags``) syntax, per ``is_seconv``.
Both name the output ``<input-stem>.<format-ext>``. ``output_folder`` steers placement
(a bare ``--output-filename`` resolves against the cwd, not the input dir). Overwrite is
always set so re-runs and in-place transforms (SDH/RTL) do not fail on an existing file.
"""
if not is_seconv(binary):
args = [str(binary), "/convert", str(src), fmt, "/encoding:utf8", "/overwrite"]
if output_folder is not None:
args.append(f"/outputfolder:{output_folder}")
if convert_colors:
args.append("/ConvertColorsToDialog")
if remove_hi:
args.append("/RemoveTextForHI")
if reverse_rtl:
args.append("/ReverseRtlStartEnd")
return args
args = [str(binary), str(src), fmt, "--encoding:utf-8", "--overwrite"]
if output_folder is not None:
args.append(f"--output-folder:{output_folder}")
if convert_colors:
args.append("--convert-colors-to-dialog")
if remove_hi:
args.append("--remove-text-for-hi")
if reverse_rtl:
args.append("--reverse-rtl-start-end")
return args
SUBSTATION: frozenset[Codec] = frozenset({Codec.SubStationAlpha, Codec.SubStationAlphav4})
# Styled SubStation formats flattened to SRT lose positioning/colours/italics.
# Never performed automatically, only when the user explicitly forces a target format.
LOSSY_DOWNCONVERTS: frozenset[tuple[Codec, Codec]] = frozenset(
{
(Codec.SubStationAlpha, Codec.SubRip),
(Codec.SubStationAlphav4, Codec.SubRip),
}
)
class SubtitleBackend(Protocol):
name: str
def is_available(self) -> bool: ...
def can_convert(self, source: Codec, target: Codec) -> bool: ...
def rank(self, source: Codec, target: Codec) -> int: ...
def convert(self, source: Codec, src: Path, target: Codec, out: Path) -> None:
"""Convert ``src`` (a ``source`` file) to ``target``, writing to ``out``. Raise on failure."""
...
class SubtitleEditBackend:
"""SubtitleEdit / seconv CLI. Highest fidelity (keeps positioning + italics) when present."""
name = "subtitleedit"
reads = frozenset(SUBTITLE_EDIT_FORMATS)
writes = frozenset(SUBTITLE_EDIT_FORMATS)
def is_available(self) -> bool:
return bool(binaries.SubtitleEdit)
def can_convert(self, source: Codec, target: Codec) -> bool:
# Segmented box formats cannot be read by SubtitleEdit.
if source in (Codec.fTTML, Codec.fVTT):
return False
return source in self.reads and target in self.writes
def rank(self, source: Codec, target: Codec) -> int:
if source in SUBSTATION and target in (Codec.TimedTextMarkupLang, Codec.WebVTT):
return 3
return 0
def convert(self, source: Codec, src: Path, target: Codec, out: Path) -> None:
args = subtitleedit_args(
binaries.SubtitleEdit,
src,
SUBTITLE_EDIT_FORMATS[target],
output_folder=out.parent,
convert_colors=(target == Codec.SubRip),
)
run_tool("SubtitleEdit", args, "SubtitleEdit convert", source=str(source), target=str(target))
# SE5 names the output <input-stem>.<format-ext>, which may differ from our target
# suffix (e.g. timedtext1.0 -> .ttml). Normalise it onto `out`.
if not out.exists():
produced = next((p for p in out.parent.glob(f"{src.stem}.*") if p not in (src, out)), None)
if produced is None:
raise FileNotFoundError(f"SubtitleEdit produced no output for {src.name} -> {target.name}")
produced.replace(out)
class Pysubs2Backend:
"""pysubs2: pure Python, broad format support, best fidelity for SSA/ASS (native style model)."""
name = "pysubs2"
formats = frozenset(PYSUBS2_FORMATS)
def is_available(self) -> bool:
return True
def can_convert(self, source: Codec, target: Codec) -> bool:
return source in self.formats and target in self.formats
def rank(self, source: Codec, target: Codec) -> int:
# Preferred reader for styled SubStation sources; solid general fallback otherwise.
return 1 if source in SUBSTATION else 2
def convert(self, source: Codec, src: Path, target: Codec, out: Path) -> None:
subs = pysubs2.load(str(src), encoding="utf-8-sig")
subs.save(str(out), format_=PYSUBS2_FORMATS[target], encoding="utf-8")
class SubbyBackend:
"""subby: purpose-built for streaming subs. WebVTT/fVTT/SAMI -> SRT + CommonIssuesFixer cleanup."""
name = "subby"
reads = frozenset({Codec.WebVTT, Codec.fVTT, Codec.SAMI})
# Native SRT output; non-SRT targets re-encoded from the SRT intermediate via pycaption.
writes = frozenset({Codec.SubRip, Codec.TimedTextMarkupLang, Codec.WebVTT})
converters = {
Codec.WebVTT: WebVTTConverter,
Codec.fVTT: WVTTConverter,
Codec.SAMI: SAMIConverter,
}
def is_available(self) -> bool:
return True
def can_convert(self, source: Codec, target: Codec) -> bool:
return source in self.reads and target in self.writes
def rank(self, source: Codec, target: Codec) -> int:
# Great for *->SRT (adds cleanup); the SRT intermediate is lossy for other targets.
return 1 if target == Codec.SubRip else 5
def convert(self, source: Codec, src: Path, target: Codec, out: Path) -> None:
srt_subtitles = self.converters[source]().from_file(src)
fixed_srt, _ = CommonIssuesFixer().from_srt(srt_subtitles)
if target == Codec.SubRip:
fixed_srt.save(out, encoding="utf8")
return
temp_srt = src.with_suffix(".temp.srt")
fixed_srt.save(temp_srt, encoding="utf8")
try:
caption_set = Subtitle.parse(temp_srt.read_bytes(), Codec.SubRip)
Subtitle.merge_same_cues(caption_set)
out.write_text(PYCAPTION_WRITERS[target]().write(caption_set), encoding="utf8")
finally:
temp_srt.unlink(missing_ok=True)
class PycaptionBackend:
"""pycaption: last resort. Flattens positioning/italics (devine #39), so ranked last."""
name = "pycaption"
reads = frozenset(
{Codec.SubRip, Codec.TimedTextMarkupLang, Codec.WebVTT, Codec.SAMI, Codec.SCC, Codec.fTTML, Codec.fVTT}
)
writes = frozenset(PYCAPTION_WRITERS)
def is_available(self) -> bool:
return True
def can_convert(self, source: Codec, target: Codec) -> bool:
return source in self.reads and target in self.writes
def rank(self, source: Codec, target: Codec) -> int:
return 9
def convert(self, source: Codec, src: Path, target: Codec, out: Path) -> None:
caption_set = Subtitle.parse(src.read_bytes(), source)
Subtitle.merge_same_cues(caption_set)
if target == Codec.WebVTT:
Subtitle.filter_unwanted_cues(caption_set)
out.write_text(PYCAPTION_WRITERS[target]().write(caption_set), encoding="utf8")
REGISTRY: list[SubtitleBackend] = [
SubtitleEditBackend(),
SubbyBackend(),
Pysubs2Backend(),
PycaptionBackend(),
]
def resolve_backends(source: Codec, target: Codec, *, pin: str | None = None) -> list[SubtitleBackend]:
"""Available backends that can convert source->target, ordered by rank. A pinned backend goes first."""
available = [b for b in REGISTRY if b.is_available() and b.can_convert(source, target)]
if pin:
pinned = [b for b in available if b.name == pin]
rest = sorted((b for b in available if b.name != pin), key=lambda b: b.rank(source, target))
return pinned + rest
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")
ASS_CANVAS_HEIGHT = 1080
ASS_STYLE_DEFAULTS: dict[str, Any] = {
"fontsize": 72,
"bold": True,
"outline": 3.6,
"shadow": 1.5,
"backcolor": "&HA0000000",
"marginl": 100,
"marginr": 100,
"marginv": 60,
}
NON_NEGATIVE_STYLE_FIELDS = frozenset({"fontsize", "outline", "shadow", "scalex", "scaley"})
def ass_color(text: str) -> pysubs2.Color:
"""Read an ``&HAABBGGRR`` colour, the form an ASS style line uses."""
value = int(text.strip().upper().removeprefix("&H").rstrip("&"), 16)
if not 0 <= value <= 0xFFFFFFFF:
raise ValueError(f"{text!r} is not an &HAABBGGRR colour")
return pysubs2.Color(value & 0xFF, value >> 8 & 0xFF, value >> 16 & 0xFF, value >> 24 & 0xFF)
def style_field_value(name: str, current: Any, value: Any) -> Any:
"""``value`` as the type of the style field that holds ``current``; ValueError or TypeError when it does not fit."""
if isinstance(current, pysubs2.Color):
if not isinstance(value, str):
raise ValueError
return ass_color(value)
if isinstance(current, bool) != isinstance(value, bool):
raise ValueError
if isinstance(current, bool):
return value
if isinstance(current, str):
if not isinstance(value, str) or not value.strip() or "," in value or not value.isprintable():
raise ValueError
return value
number = float(value)
if not math.isfinite(number) or (name in NON_NEGATIVE_STYLE_FIELDS and number < 0):
raise ValueError
if isinstance(current, float):
return number
if not number.is_integer():
raise ValueError
return type(current)(int(number))
def build_ass_style(fields: Mapping[str, Any]) -> pysubs2.SSAStyle:
"""Build the style for converted subtitles from style fields over ``ASS_STYLE_DEFAULTS``.
A field is a pysubs2 name (``primarycolor``) or an ASS one (``PrimaryColour``). Sizes and margins are for a
1080-line canvas. A value that does not fit its field raises ValueError.
"""
style = pysubs2.SSAStyle()
for name, value in {**ASS_STYLE_DEFAULTS, **fields}.items():
field = str(name).lower().replace("colour", "color")
if field not in vars(style):
raise ValueError(f"ass_style has no field {name!r}")
try:
setattr(style, field, style_field_value(field, getattr(style, field), value))
except (ValueError, TypeError):
raise ValueError(f"ass_style {name}: {value!r} is not valid") from None
return style
def style_substation(path: Path, style: pysubs2.SSAStyle, video_size: tuple[int, int] | None) -> None:
"""Give every style of a converted SSA/ASS file the look of ``style``.
A file with no PlayResY gets a 1080-line canvas in the shape of the video. A file with one keeps it, so positions
a converter wrote stay put, and the style scales to it. Each style keeps its own alignment and italic flag.
"""
try:
subs = pysubs2.load(str(path), encoding="utf-8-sig")
except (pysubs2.exceptions.Pysubs2Error, UnicodeDecodeError, ValueError) as e:
log.warning(f"Cannot style {path.name}: {e}")
return
try:
height = float(subs.info["PlayResY"])
except (KeyError, ValueError):
height = 0.0
if height <= 0:
width, video_height = video_size or (16, 9)
height = ASS_CANVAS_HEIGHT
subs.info["PlayResX"] = str(round(height * width / video_height))
subs.info["PlayResY"] = str(ASS_CANVAS_HEIGHT)
if video_size:
subs.info["LayoutResX"], subs.info["LayoutResY"] = str(width), str(video_height)
subs.info["ScaledBorderAndShadow"] = "yes"
scale = height / ASS_CANVAS_HEIGHT
scaled = style.copy()
for name in ("fontsize", "outline", "shadow", "spacing"):
setattr(scaled, name, getattr(style, name) * scale)
for name in ("marginl", "marginr", "marginv"):
setattr(scaled, name, round(getattr(style, name) * scale))
styles = {}
for name, old in subs.styles.items():
styles[name] = scaled.copy()
styles[name].alignment, styles[name].italic = old.alignment, old.italic
styles["Default"] = scaled
subs.styles = styles
subs.save(str(path), format_=subs.format, encoding="utf-8")
def finalize(sub: Subtitle, target: Codec, out: Path) -> Path:
"""Swap the track onto the converted file and fire the OnConverted callback."""
original = sub.path
if original and original.exists() and original != out:
original.unlink()
sub.path = out
sub.codec = target
if callable(sub.OnConverted):
sub.OnConverted(target)
return out
def time_sorted_copy(src: Path) -> Path | None:
"""
Copy an SSA/ASS file with its events in start-time order, or return None when it is already in order.
Layered sign events are often out of time order, and SubtitleEdit and the pysubs2 SRT writer keep file order.
The source stays as it is, because ASS draws the events of one layer in file order.
"""
try:
subs = pysubs2.load(str(src), encoding="utf-8-sig")
except (pysubs2.exceptions.Pysubs2Error, UnicodeDecodeError, ValueError) as e:
log.debug(f"Cannot read {src.name} to sort it by start time, converting it unsorted: {e}")
return None
if all(a.start <= b.start for a, b in pairwise(subs.events)):
return None
subs.sort()
copy = src.with_name(f"{src.stem}.sorted{src.suffix}")
subs.save(str(copy), format_=subs.format, encoding="utf-8")
return copy
def run_conversion(sub: Subtitle, target: Codec, *, pin: str | None = None, forced: bool = False) -> Path:
"""
Convert ``sub`` to ``target`` using the best available backend, falling back through the
capability chain on failure.
``forced`` is True only for explicit user requests (``--sub-format``). unshackle skips
lossy downconverts (styled SubStation -> SRT) unless ``forced`` is True.
"""
if sub.path is None or not sub.path.exists():
raise ValueError("You must download the subtitle track first.")
if sub.codec is None:
raise ValueError("Subtitle has no codec to convert from.")
source, src = sub.codec, sub.path
if source == target:
return src
if (source, target) in LOSSY_DOWNCONVERTS and not forced:
log.info(
f"Keeping {source.name} subtitle as-is "
f"(skipping lossy auto-conversion to {target.name}; pass --sub-format to force)"
)
return src
chain = resolve_backends(source, target, pin=pin)
if not chain:
raise NotImplementedError(f"Cannot convert {source.name} to {target.name}.")
out = src.with_suffix(f".{target.value.lower()}")
sorted_src = time_sorted_copy(src) if source in SUBSTATION and target not in SUBSTATION else None
last_exc: Exception | None = None
try:
for backend in chain:
try:
backend.convert(source, sorted_src or src, target, out)
except Exception as e:
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)
if sub.ass_style and target in SUBSTATION and source not in SUBSTATION:
style_substation(out, sub.ass_style, sub.ass_video_size)
return finalize(sub, target, out)
finally:
if sorted_src:
sorted_src.unlink(missing_ok=True)
raise RuntimeError(f"All subtitle backends failed for {source.name}->{target.name}: {last_exc}") from last_exc