fix(captions): keep apostrophes out of the burned subtitle path

Auto-captions have been silently failing in prod on any video whose title
contains an apostrophe — constant in English ("Earth's", "Don't"). The clip
that surfaced it: "Inside Earth's Most Mysterious Temple". Four failures in a
two-hour window, each swallowed by the guard that ships the clip uncaptioned,
so nothing alerted.

The .ass path is interpolated INTO a filter string (-vf ass='...'), where a
literal apostrophe closes the quote and truncates the filter. /api/subtitle has
always been safe because it names its file subs_<i>_<ts>.ass; shipping captions
by default introduced a name built from the clip stem, which carries the title.

So the .ass name drops the stem. It also gains a uuid: clips render in parallel
under CLIP_WORKERS, and a bare timestamp would let two clips in the same second
write the same file and burn each other's captions. The OUTPUT name keeps the
stem, and must — the modal's walk-back and _canonical_clip_file reconstruct the
clean original from it — but that one is only ever an argv element, never
inside a filter.

Smarter escaping was tried first and is worse, so the reasoning is recorded in
_escape_ffmpeg_filter_value rather than left for someone to rediscover: the
shell idiom "'\''" is not understood by ffmpeg's filtergraph parser, which
dropped the apostrophe AND swallowed the following option, resolving
ass='…Earth'\''s.ass':fontsdir='…' to a filename of "…Earths.ass:fontsdir=…".
An apostrophe in a filter path cannot be escaped; it has to be absent.

Verified in the prod image against the failing filename: the burn now produces
a 540x960 clip where it previously errored.
This commit is contained in:
juancarlos.cavero 2026-07-29 15:04:50 +02:00
parent 4c04b37e4f
commit be4dd06189
3 changed files with 72 additions and 2 deletions

19
main.py
View file

@ -6,6 +6,7 @@ import argparse
import re import re
import sys import sys
import threading import threading
import uuid
from concurrent.futures import ThreadPoolExecutor, as_completed from concurrent.futures import ThreadPoolExecutor, as_completed
from scenedetect import open_video, SceneManager from scenedetect import open_video, SceneManager
from scenedetect.detectors import ContentDetector from scenedetect.detectors import ContentDetector
@ -836,7 +837,23 @@ def auto_caption_clip(clip_path, transcript, clip_start, clip_end):
# download time. A legacy clip whose name predates that budget can still # download time. A legacy clip whose name predates that budget can still
# overflow — that raises OSError 36, which the except below turns into # overflow — that raises OSError 36, which the except below turns into
# "ship the clip uncaptioned" rather than a broken filename. # "ship the clip uncaptioned" rather than a broken filename.
ass_path = os.path.join(output_dir, f"autosubs_{generation_id}_{stem}.ass") # The .ass path is interpolated INTO an ffmpeg filter string
# (-vf ass='...'), where a literal apostrophe closes the quote and
# breaks the filter. Titles carry apostrophes constantly in English
# ("Earth's", "Don't"), so this name must stay free of the clip stem —
# which is exactly why /api/subtitle has always used a neutral
# "subs_<i>_<ts>.ass". Deriving it from the stem silently cost captions
# on every apostrophe title until 29-jul-2026.
#
# The OUTPUT name still carries the stem, and must: the modal's
# walk-back and _canonical_clip_file reconstruct the clean original
# from it. That one is only ever passed as an argv element, never
# inside a filter string, so quoting never applies to it.
# Unique per clip, not just per second: clips render in parallel
# (CLIP_WORKERS), so a bare timestamp would collide and let one clip
# burn another's captions.
ass_path = os.path.join(
output_dir, f"autosubs_{generation_id}_{uuid.uuid4().hex[:8]}.ass")
out_path = os.path.join(output_dir, f"subtitled_{generation_id}_{stem}") out_path = os.path.join(output_dir, f"subtitled_{generation_id}_{stem}")
if not _subs.generate_ass( if not _subs.generate_ass(

View file

@ -88,7 +88,19 @@ def _log(message):
def _escape_ffmpeg_filter_value(value): def _escape_ffmpeg_filter_value(value):
"""Escape a path/value for use inside a quoted FFmpeg filter argument.""" """Escape a path/value for use inside a quoted FFmpeg filter argument.
NOTE: an apostrophe in the path cannot be made safe here. ffmpeg's
filtergraph parser is not a shell — the shell idiom ``'\\''`` was tried on
29-jul-2026 and is worse than doing nothing: it drops the apostrophe AND
swallows the following option, so ``ass='…Earth'\\''s.ass':fontsdir='…'``
resolved to a filename of "…Earths.ass:fontsdir=…" and failed to open.
The only reliable answer is to keep apostrophes OUT of any path that is
interpolated into a filter. Callers generate their own subtitle filenames,
so they control this: use a neutral name (``subs_<i>_<ts>.ass``), never one
derived from a video title.
"""
return value.replace('\\', '/').replace(':', '\\:').replace("'", "\\'") return value.replace('\\', '/').replace(':', '\\:').replace("'", "\\'")

View file

@ -289,3 +289,44 @@ class TestAutoCaptionDefaults:
@staticmethod @staticmethod
def _t(words): def _t(words):
return {"segments": [{"words": words}]} return {"segments": [{"words": words}]}
class TestFilterQuoting:
"""Paths are interpolated INTO a single-quoted ffmpeg filter argument.
Regression cover for captions silently failing in prod on 29-jul-2026: a
clip named "Inside Earth's Most Mysterious Temple" produced an .ass path
carrying that apostrophe, which ends the quoted argument early and kills
the burn. Apostrophes are constant in English titles.
The fix is NOT smarter escaping. The shell idiom "'\\''" was tried and is
worse — ffmpeg's filtergraph parser is not a shell, so it dropped the
apostrophe and swallowed the following ":fontsdir=" option into the
filename. The fix is to keep apostrophes out of filter paths entirely.
"""
def test_generated_subtitle_paths_carry_no_apostrophe(self):
# Both generators must name their own file, never derive it from a
# video title. This is the property that actually prevents the bug.
import re
src = open("main.py").read()
m = re.search(r'ass_path = os\.path\.join\(\s*output_dir,\s*f"([^"]+)"', src)
assert m, "auto-caption .ass path not found"
assert "{stem}" not in m.group(1), (
f"auto-caption .ass name derives from the clip stem: {m.group(1)}")
def test_auto_caption_ass_name_is_unique_per_clip(self):
# Clips render in parallel; a bare timestamp collides and lets one clip
# burn another's captions.
import re
src = open("main.py").read()
m = re.search(r'ass_path = os\.path\.join\(\s*output_dir,\s*f"([^"]+)"', src)
assert "uuid" in m.group(1), f"not unique per clip: {m.group(1)}"
def test_colon_is_escaped(self):
from subtitles import _escape_ffmpeg_filter_value
assert "\\:" in _escape_ffmpeg_filter_value("C:/out/subs.ass")
def test_plain_path_untouched(self):
from subtitles import _escape_ffmpeg_filter_value
assert _escape_ffmpeg_filter_value("/out/subs_0_123.ass") == "/out/subs_0_123.ass"