feat(clips): ship every clip captioned by default

Captions are what make a short readable with the sound off, and 91% of
delivered clips had none (35 subtitle jobs against 380 process jobs in the
25-jul-2026 prod audit) because they were opt-in behind a modal. Now every clip
comes out captioned and the modal becomes a re-style, not a discovery.

The look was picked by rendering four candidates on a real clip and comparing
them: white Anton uppercase, yellow active word, heavy black outline, gentle
pop. Yellow because it is the one colour that almost never occurs in footage,
so the active word reads instantly on any background. The base text stays fully
opaque — dimming it, which several caption tools do, tested worse over bright
scenes. Captured in AUTO_CAPTION_STYLE so there is one place to change it.

Two fixes fell out of rendering it for real:
- Captions sat at MarginV=25 (8.7% of frame height), underneath TikTok's and
  Reels' own bottom chrome. Raised to a documented SAFE_MARGIN_V of ~15%, now
  a parameter rather than a hardcoded literal.
- The pop effect scaled the active word 75->112, wide enough that any frame
  caught mid-animation read as a sizing bug. Softened to 90->108.

Wiring follows the convention already used by /api/subtitle: the captioned file
is written as subtitled_<ts>_<clip>.mp4 next to the untouched original, so
re-styling from the modal replaces the captions instead of burning a second
layer over them (its existing walk-back resolves this unchanged). The places
that rebuild the canonical clip name from disk — restore after a restart, the
project reopen, the download bundle — now resolve through _canonical_clip_file
so a redeploy cannot silently serve the uncaptioned version. R2 uploads follow
video_url, so the durable library gets the captioned clip too.

Captions are applied after the watermark, never before, and any failure is
swallowed: a caption problem must not cost the user a clip they already paid
for. Silent videos have no transcript and are skipped. AUTO_CAPTIONS=0 is the
rollback lever.

Verified end to end in the container: burn produces the derived file, the app
resolves to it, the modal walks back to the clean original, silent input ships
uncaptioned, the kill switch works, and the newest styling wins.
This commit is contained in:
juancarlos.cavero 2026-07-25 17:42:08 +02:00
parent a793e02ddf
commit a2237d07d3
4 changed files with 176 additions and 9 deletions

34
app.py
View file

@ -357,6 +357,27 @@ def _relocate_root_job_artifacts(job_id: str, job_output_dir: str) -> bool:
except Exception: except Exception:
return False return False
def _canonical_clip_file(output_dir, base_name, index):
"""The file to serve for clip ``index``, preferring a derived version.
The pipeline writes the clean reframe as ``<base>_clip_<n>.mp4`` and any
post-processing (auto-captions, and /api/subtitle re-styles) as
``subtitled_<ts>_<clean>.mp4``, keeping the original for re-styling. Every
place that rebuilds the canonical name from disk — restore after a restart,
the R2 upload, the download bundle — must therefore resolve to the newest
derived file, or clips silently lose their captions on a redeploy.
"""
clean = f"{base_name}_clip_{index + 1}.mp4"
try:
derived = glob.glob(os.path.join(output_dir, f"subtitled_*_{clean}"))
except Exception:
derived = []
if not derived:
return clean
# Highest timestamp wins — that's the most recent styling.
return os.path.basename(max(derived, key=os.path.getmtime))
def _recover_jobs_from_disk(): def _recover_jobs_from_disk():
"""Rebuild completed jobs from OUTPUT_DIR after a restart (issue #46 / #18). """Rebuild completed jobs from OUTPUT_DIR after a restart (issue #46 / #18).
@ -384,7 +405,9 @@ def _recover_jobs_from_disk():
clips = data.get('shorts', []) clips = data.get('shorts', [])
for i, clip in enumerate(clips): for i, clip in enumerate(clips):
if not clip.get('video_url'): if not clip.get('video_url'):
clip['video_url'] = f"/videos/{job_id}/{base_name}_clip_{i+1}.mp4" clip['video_url'] = (
f"/videos/{job_id}/"
f"{_canonical_clip_file(job_path, base_name, i)}")
owner = None owner = None
owner_path = os.path.join(job_path, ".owner") owner_path = os.path.join(job_path, ".owner")
if os.path.exists(owner_path): if os.path.exists(owner_path):
@ -1104,7 +1127,7 @@ async def run_job(job_id, job_data):
cost_analysis = data.get('cost_analysis') cost_analysis = data.get('cost_analysis')
for i, clip in enumerate(clips): for i, clip in enumerate(clips):
clip_filename = f"{base_name}_clip_{i+1}.mp4" clip_filename = _canonical_clip_file(output_dir, base_name, i)
clip['video_url'] = f"/videos/{job_id}/{clip_filename}" clip['video_url'] = f"/videos/{job_id}/{clip_filename}"
jobs[job_id]['result'] = {'clips': clips, 'cost_analysis': cost_analysis} jobs[job_id]['result'] = {'clips': clips, 'cost_analysis': cost_analysis}
@ -1358,7 +1381,8 @@ async def download_all_clips(job_id: str, request: Request):
if i < len(mem_clips): if i < len(mem_clips):
url = (mem_clips[i] or {}).get('video_url') url = (mem_clips[i] or {}).get('video_url')
url = url or clip.get('video_url') url = url or clip.get('video_url')
filename = os.path.basename(url.split('/')[-1]) if url else f"{base_name}_clip_{i+1}.mp4" filename = (os.path.basename(url.split('/')[-1]) if url
else _canonical_clip_file(output_dir, base_name, i))
path = os.path.join(output_dir, filename) path = os.path.join(output_dir, filename)
if filename and os.path.exists(path): if filename and os.path.exists(path):
files.append((i, path)) files.append((i, path))
@ -1472,7 +1496,9 @@ async def restore_project(job_id: str, request: Request):
clips = data.get('shorts', []) clips = data.get('shorts', [])
for i, clip in enumerate(clips): for i, clip in enumerate(clips):
if not clip.get('video_url'): if not clip.get('video_url'):
clip['video_url'] = f"/videos/{job_id}/{base_name}_clip_{i+1}.mp4" clip['video_url'] = (
f"/videos/{job_id}/"
f"{_canonical_clip_file(job_dir, base_name, i)}")
jobs[job_id] = { jobs[job_id] = {
'status': 'completed', 'status': 'completed',
'logs': ["♻️ Project restored from your library."], 'logs': ["♻️ Project restored from your library."],

56
main.py
View file

@ -713,6 +713,59 @@ def finalize_clip_passthrough(input_video, final_output_video):
return True return True
def auto_caption_clip(clip_path, transcript, clip_start, clip_end):
"""Burn the default caption style onto a finished clip.
Captions are mandatory for short-form to land, but they were opt-in behind a
modal and only 9% of delivered clips ever got them (prod audit, 25-jul-2026).
So every clip now ships captioned by default.
The captioned file is written ALONGSIDE the clip as
``subtitled_<ts>_<clip>.mp4`` — the same convention /api/subtitle uses — so
the untouched original stays on disk and re-styling from the modal replaces
the captions instead of burning a second layer over them.
Returns the captioned path, or None when captions were skipped (silent
video, no words in range, AUTO_CAPTIONS=0, or any failure — a caption
problem must never cost the user the clip they already paid for).
"""
if os.environ.get("AUTO_CAPTIONS", "1").strip() == "0":
return None
if not transcript or not transcript.get('segments'):
return None # silent video: nothing to caption
try:
import subtitles as _subs
style = _subs.AUTO_CAPTION_STYLE
output_dir = os.path.dirname(clip_path)
stem = os.path.basename(clip_path)
generation_id = int(time.time())
ass_path = os.path.join(output_dir, f"autosubs_{generation_id}_{stem}.ass")
out_path = os.path.join(output_dir, f"subtitled_{generation_id}_{stem}")
if not _subs.generate_ass(
transcript, clip_start, clip_end, ass_path,
max_chars=style["max_chars"], max_duration=style["max_duration"],
alignment=style["alignment"], fontsize=style["font_size"],
font_name=style["font_name"], font_color=style["font_color"],
border_color=style["border_color"], border_width=style["border_width"],
highlight_color=style["highlight_color"], effect=style["effect"],
base_opacity=style["base_opacity"], uppercase=style["uppercase"]):
print(" ℹ️ No words in range — clip ships without captions.")
return None
_subs.burn_subtitles(
clip_path, ass_path, out_path,
alignment=style["alignment"], fontsize=style["font_size"],
font_name=style["font_name"], font_color=style["font_color"],
border_color=style["border_color"], border_width=style["border_width"])
print(f" 💬 Captions burned: {os.path.basename(out_path)}")
return out_path
except Exception as e:
print(f" ⚠️ Auto-captions failed ({type(e).__name__}: {e}) — "
f"delivering the clip without them.")
return None
def render_clip(input_video, final_output_video, output_format="auto"): def render_clip(input_video, final_output_video, output_format="auto"):
"""Route a cut clip through the right renderer for the chosen output format. """Route a cut clip through the right renderer for the chosen output format.
vertical/auto -> 9:16 reframe, square -> 1:1 reframe, horizontal -> keep.""" vertical/auto -> 9:16 reframe, square -> 1:1 reframe, horizontal -> keep."""
@ -1356,6 +1409,9 @@ if __name__ == '__main__':
if success and os.environ.get("WATERMARK") == "1": if success and os.environ.get("WATERMARK") == "1":
apply_watermark(clip_final_path) apply_watermark(clip_final_path)
if success: if success:
# Captions last, so they sit on top of the watermark and
# the canonical file stays clean for re-styling.
auto_caption_clip(clip_final_path, transcript, start, end)
print(f" ✅ Clip {i+1} ready: {clip_final_path}") print(f" ✅ Clip {i+1} ready: {clip_final_path}")
return success return success
finally: finally:

View file

@ -204,6 +204,38 @@ def generate_srt(transcript, clip_start, clip_end, output_path, max_chars=20, ma
return True return True
# Vertical margin for burned captions, in PlayResY=288 units (so ~15% of the
# frame height). The old hardcoded 25 (8.7%) put captions underneath TikTok's
# and Reels' own bottom UI — the caption/username block and the music ticker —
# where they were partly covered on the platform even though the exported file
# looked fine.
SAFE_MARGIN_V = 43
# The caption look applied automatically to every generated clip. Chosen by
# rendering four candidates on a real clip and comparing them (25-jul-2026):
# white Anton uppercase with a yellow active word, heavy black outline, gentle
# pop. Yellow because it is the one colour that almost never occurs in footage,
# so the active word reads instantly on any background; the base text stays
# fully opaque (dimming it tested worse over bright scenes). This is a starting
# point, not a cage — the subtitle modal still overrides every field.
AUTO_CAPTION_STYLE = {
"style": "karaoke",
"alignment": "bottom",
"font_name": "Anton",
"font_size": 44,
"font_color": "#FFFFFF",
"highlight_color": "#FFE500",
"border_color": "#000000",
"border_width": 4,
"effect": "pop",
"base_opacity": 1.0,
"uppercase": True,
"max_chars": 16,
"max_duration": 1.4,
}
def _ass_time(seconds): def _ass_time(seconds):
"""Format seconds as ASS timestamp H:MM:SS.cc (centiseconds).""" """Format seconds as ASS timestamp H:MM:SS.cc (centiseconds)."""
seconds = max(0, seconds) seconds = max(0, seconds)
@ -256,7 +288,8 @@ def generate_ass(transcript, clip_start, clip_end, output_path,
fontsize=16, font_name="Verdana", font_color="#FFFFFF", fontsize=16, font_name="Verdana", font_color="#FFFFFF",
border_color="#000000", border_width=2, border_color="#000000", border_width=2,
highlight_color="#FFD700", bg_color="#000000", bg_opacity=0.0, highlight_color="#FFD700", bg_color="#000000", bg_opacity=0.0,
effect="none", base_opacity=1.0, uppercase=False): effect="none", base_opacity=1.0, uppercase=False,
margin_v=SAFE_MARGIN_V):
""" """
Generates a karaoke-style ASS file: each block is shown like the SRT path, Generates a karaoke-style ASS file: each block is shown like the SRT path,
but the currently spoken word is rendered in highlight_color (modern but the currently spoken word is rendered in highlight_color (modern
@ -311,8 +344,10 @@ def generate_ass(transcript, clip_start, clip_end, output_path,
active_prefix = (f"{{\\c&HFFFFFF&\\3c{highlight_inline}" active_prefix = (f"{{\\c&HFFFFFF&\\3c{highlight_inline}"
f"\\bord{box_bord}\\blur0}}") f"\\bord{box_bord}\\blur0}}")
elif effect == "pop": elif effect == "pop":
# Gentle pop. The old 75->112 range started the word so small that any
# frame caught mid-animation read as a sizing bug rather than a beat.
active_prefix = (f"{{\\c{highlight_inline}" active_prefix = (f"{{\\c{highlight_inline}"
f"\\fscx75\\fscy75\\t(0,120,\\fscx112\\fscy112)}}") f"\\fscx90\\fscy90\\t(0,110,\\fscx108\\fscy108)}}")
else: else:
active_prefix = f"{{\\c{highlight_inline}}}" active_prefix = f"{{\\c{highlight_inline}}}"
@ -330,7 +365,7 @@ def generate_ass(transcript, clip_start, clip_end, output_path,
"Alignment, MarginL, MarginR, MarginV, Encoding\n" "Alignment, MarginL, MarginR, MarginV, Encoding\n"
f"Style: Default,{safe_font},{final_fontsize},{primary_colour},{primary_colour}," f"Style: Default,{safe_font},{final_fontsize},{primary_colour},{primary_colour},"
f"{outline_colour},{back_colour},1,0,0,0,100,100,0,0,{border_style}," f"{outline_colour},{back_colour},1,0,0,0,100,100,0,0,{border_style},"
f"{outline_width},0,{ass_alignment},10,10,25,1\n" f"{outline_width},0,{ass_alignment},10,10,{int(_clamp_number(margin_v, 0, 200, SAFE_MARGIN_V))},1\n"
"\n" "\n"
"[Events]\n" "[Events]\n"
"Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n" "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n"
@ -474,7 +509,7 @@ def burn_subtitles(video_path, srt_path, output_path, alignment=2, fontsize=16,
f"BorderStyle={border_style}," f"BorderStyle={border_style},"
f"Outline={outline_width}," f"Outline={outline_width},"
f"Shadow=0," f"Shadow=0,"
f"MarginV=25," f"MarginV={SAFE_MARGIN_V},"
f"Bold=1" f"Bold=1"
) )

View file

@ -173,7 +173,10 @@ class TestGenerateAss:
words = [_w(" pop", 0.0, 0.5)] words = [_w(" pop", 0.0, 0.5)]
assert generate_ass(self._transcript(words), 0, 10, str(out), effect="pop") is True assert generate_ass(self._transcript(words), 0, 10, str(out), effect="pop") is True
content = out.read_text(encoding="utf-8-sig") content = out.read_text(encoding="utf-8-sig")
assert "\\t(0,120,\\fscx112\\fscy112)" in content # Gentle range: the old 75->112 pop was so wide that a frame caught
# mid-animation read as a sizing bug rather than a beat.
assert "\\fscx90\\fscy90" in content
assert "\\t(0,110,\\fscx108\\fscy108)" in content
def test_uppercase_transform(self, tmp_path): def test_uppercase_transform(self, tmp_path):
from subtitles import generate_ass from subtitles import generate_ass
@ -239,3 +242,50 @@ class TestBurnFilterFonts:
assert "fontsdir=" in cmd assert "fontsdir=" in cmd
# ASS carries its own styles; force_style must NOT override them # ASS carries its own styles; force_style must NOT override them
assert "force_style" not in cmd assert "force_style" not in cmd
class TestAutoCaptionDefaults:
"""The caption look every clip now ships with (chosen 25-jul-2026)."""
def test_style_is_complete(self):
from subtitles import AUTO_CAPTION_STYLE, generate_ass
required = {"alignment", "font_name", "font_size", "font_color",
"highlight_color", "border_color", "border_width",
"effect", "base_opacity", "uppercase",
"max_chars", "max_duration"}
assert required <= set(AUTO_CAPTION_STYLE)
def test_font_is_one_the_image_actually_ships(self):
# libass falls back to DejaVu SILENTLY when the font is missing (#57),
# so the default must be a family baked into the image.
from subtitles import AUTO_CAPTION_STYLE
assert AUTO_CAPTION_STYLE["font_name"] in {
"Anton", "Liberation Sans", "Liberation Serif", "DejaVu Sans"}
def test_highlight_differs_from_body_text(self):
# The whole point of the karaoke look: the active word must stand out.
from subtitles import AUTO_CAPTION_STYLE as s
assert s["highlight_color"].lower() != s["font_color"].lower()
def test_captions_clear_the_platform_ui(self, tmp_path):
from subtitles import SAFE_MARGIN_V, generate_ass
# PlayResY is 288, so the margin must be a meaningful share of it —
# the old hardcoded 25 (8.7%) sat under TikTok's own bottom chrome.
assert SAFE_MARGIN_V / 288 >= 0.12
out = tmp_path / "subs.ass"
words = [_w(" hola", 0.0, 0.5)]
assert generate_ass(self._t(words), 0, 10, str(out)) is True
style_line = [l for l in out.read_text(encoding="utf-8-sig").splitlines()
if l.startswith("Style: Default")][0]
assert f",10,10,{SAFE_MARGIN_V},1" in style_line
def test_margin_is_overridable(self, tmp_path):
from subtitles import generate_ass
out = tmp_path / "subs.ass"
assert generate_ass(self._t([_w(" hola", 0.0, 0.5)]), 0, 10, str(out),
margin_v=90) is True
assert ",10,10,90,1" in out.read_text(encoding="utf-8-sig")
@staticmethod
def _t(words):
return {"segments": [{"words": words}]}