From e2df4c1f0c9627724dccf70100b9ee5a4072ab71 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Tue, 25 Aug 2026 14:35:46 +0200 Subject: [PATCH] feat(captions): put subtitles on the seam of SPLIT scenes On a stacked two-shot the seam between the halves is the one place the text covers nobody (OpusClip does the same), so every word event inside a SPLIT stretch is anchored mid-frame with an inline \an5; other layouts keep the style's alignment, and the text moves with the cut. The render records which stretches use which layout in a .layout.json sidecar (layout_ranges.py). The job pipeline, rerender and manual reframe copy it into the clip's metadata as layout_ranges, so /api/subtitle finds it on a restyle too. auto_caption_clip reads the sidecar when not told, which is how recut hands it over. Only the ASS path can do this; SRT burns keep one alignment per file. Checked on the 45-clip corpus with SPLIT on: 45/45 render, 0 caption errors, 42 with no split at all, and the 3 that split are real two-shots. --- CLAUDE.md | 8 +++- app.py | 14 +++++- layout_ranges.py | 75 ++++++++++++++++++++++++++++++ main.py | 19 +++++++- reframe_v2.py | 4 ++ subtitles.py | 18 +++++++- tests/test_layout_ranges.py | 92 +++++++++++++++++++++++++++++++++++++ 7 files changed, 224 insertions(+), 6 deletions(-) create mode 100644 layout_ranges.py create mode 100644 tests/test_layout_ranges.py diff --git a/CLAUDE.md b/CLAUDE.md index 02dca2e..aecb2c2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -126,7 +126,13 @@ se desactiva porque el modelo diga `none`. visible **in the same frame** for at least half the sampled frames — that is what separates a real two-shot from a plano/contraplano, where stacking would show the same person twice. `SPLIT_TIGHTNESS` (default 0.8) trades a little - upscale for keeping the other speaker out of each half. + upscale for keeping the other speaker out of each half. Captions on a SPLIT + stretch sit on the seam between the halves (`{\an5}` per word event in + `subtitles.generate_ass`), the one place they cover nobody; the render + records which stretches are stacked in a `.layout.json` sidecar + (`layout_ranges.py`) and every metadata writer copies it into the clip's + `layout_ranges`, so `/api/subtitle` finds it after a restyle too. Only the + ASS path can do this; SRT burns keep one alignment for the whole file. - **SCREENCAST / WIDE Modes** (`screencast_layout.py`, `SCREENCAST_LAYOUT=1`): for scenes whose meaning lives outside the centre. Gemini reports each range's **width_fraction**, and that is the gate — coverage was tried before and did diff --git a/app.py b/app.py index 7b3297a..78b2c65 100644 --- a/app.py +++ b/app.py @@ -26,6 +26,7 @@ from starlette.background import BackgroundTask from pydantic import BaseModel from s3_uploader import upload_job_artifacts, list_all_clips, upload_actor_to_s3, list_actor_gallery, upload_video_to_gallery, list_video_gallery import recut +import layout_ranges load_dotenv() @@ -3021,7 +3022,11 @@ async def _rerender_locked(req: RerenderRequest, request: Request, job): new_end = max(s['end'] for s in segments) updates = {'video_url': new_video_url, 'start': new_start, - 'end': new_end, 'recipe': new_recipe} + 'end': new_end, 'recipe': new_recipe, + # The stacked stretches of THIS render (empty on the fast + # path, which never reframes): captions follow them. + 'layout_ranges': layout_ranges.read( + os.path.join(output_dir, _clean_recut_name))} # Per-scene manual framing is keyed by scene indices of a specific cut; # this render neither applied it nor can it survive a changed cut, so # clear it rather than let /scenes serve stale overrides against the @@ -3375,6 +3380,7 @@ async def _reframe_locked(req: ReframeRequest, request: Request, job, overrides) 'video_url': new_video_url, 'recipe': new_recipe, 'crop_overrides': {str(k): v for k, v in overrides.items()}, + 'layout_ranges': layout_ranges.read(os.path.join(output_dir, _clean)), } clip.update(updates) data['shorts'] = clips @@ -3659,7 +3665,13 @@ async def add_subtitles(req: SubtitleRequest, request: Request): srt_path = os.path.join(output_dir, srt_filename) # Style options shared by the karaoke ASS generator paths. + # Stacked (SPLIT) stretches put their captions on the seam. The metadata + # copy is authoritative; the sidecar covers clips rendered before it was + # recorded there. + seam_ranges = layout_ranges.split_ranges( + clip_data.get('layout_ranges') or layout_ranges.read(input_path)) karaoke_opts = dict( + split_ranges=seam_ranges, alignment=req.position, fontsize=req.font_size, font_name=req.font_name, font_color=req.font_color, border_color=req.border_color, border_width=req.border_width, highlight_color=req.highlight_color, diff --git a/layout_ranges.py b/layout_ranges.py new file mode 100644 index 0000000..bf79956 --- /dev/null +++ b/layout_ranges.py @@ -0,0 +1,75 @@ +"""Which stretches of a rendered clip use which layout, kept next to the clip. + +reframe_v2 decides a layout per scene (TRACK, GENERAL, SPLIT, ...) and renders +it, and nothing downstream used to know. Captions need to: on a SPLIT scene +the two speakers sit one above the other and the seam between the halves is +the emptiest place in the frame, so that is where the captions go (OpusClip +does the same). On every other layout they stay at the bottom. + +The ranges travel as a sidecar ``.layout.json`` written by the render, +because the render happens in four different places (the job pipeline, the +recut/rerender, the manual reframe and the v1 fallback, which writes none) +and a return value would have to be threaded through all of them. Times are +in the CLIP's own timeline, which is also the timeline captions are laid on. +Whoever updates a clip's metadata copies them into ``layout_ranges`` so +/api/subtitle can find them after the sidecar is gone. +""" +import json +import os + +SIDECAR_SUFFIX = ".layout.json" + + +def sidecar_path(video_path): + return video_path + SIDECAR_SUFFIX + + +def write(video_path, ranges): + """``ranges``: iterable of (start_s, end_s, strategy). Best effort: a + failure here must never fail a render that already succeeded.""" + payload = [{"start": round(float(s), 3), "end": round(float(e), 3), + "layout": str(layout).lower()} for s, e, layout in ranges] + try: + with open(sidecar_path(video_path), "w") as f: + json.dump({"ranges": payload}, f) + except OSError: + pass + return payload + + +def read(video_path): + """The ranges recorded for this file, or [] (no sidecar, v1 render, or + a file that was never reframed).""" + try: + with open(sidecar_path(video_path)) as f: + data = json.load(f) + except (OSError, ValueError): + return [] + return normalise(data.get("ranges")) + + +def normalise(ranges): + """Accept the sidecar/metadata shape or bare tuples; drop anything odd + (an old metadata file, a hand-edited value) instead of raising.""" + out = [] + for r in ranges or []: + try: + if isinstance(r, dict): + s, e, layout = r["start"], r["end"], r.get("layout", "") + else: + s, e, layout = r + s, e = float(s), float(e) + except (KeyError, TypeError, ValueError): + continue + if e > s: + out.append({"start": s, "end": e, "layout": str(layout).lower()}) + return out + + +def split_ranges(ranges): + """(start, end) pairs of the stretches where captions belong on the seam.""" + return [(r["start"], r["end"]) for r in normalise(ranges) if r["layout"] == "split"] + + +def in_split(t, splits): + return any(s <= t < e for s, e in splits or []) diff --git a/main.py b/main.py index 760a84a..229afad 100644 --- a/main.py +++ b/main.py @@ -908,9 +908,14 @@ def finalize_clip_passthrough(input_video, final_output_video): return True -def auto_caption_clip(clip_path, transcript, clip_start, clip_end): +def auto_caption_clip(clip_path, transcript, clip_start, clip_end, split_ranges=None): """Burn the default caption style onto a finished clip. + ``split_ranges``: (start, end) stretches, in clip seconds, rendered with + the SPLIT layout; captions there sit on the seam between the two speakers + instead of the bottom. None reads the render's own sidecar next to + ``clip_path`` (layout_ranges), which is where recut hands it over. + 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. @@ -960,8 +965,12 @@ def auto_caption_clip(clip_path, transcript, clip_start, clip_end): output_dir, f"autosubs_{generation_id}_{uuid.uuid4().hex[:8]}.ass") out_path = os.path.join(output_dir, f"subtitled_{generation_id}_{stem}") + if split_ranges is None: + import layout_ranges as _layouts + split_ranges = _layouts.split_ranges(_layouts.read(clip_path)) if not _subs.generate_ass( transcript, clip_start, clip_end, ass_path, + split_ranges=split_ranges, 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"], @@ -1847,12 +1856,18 @@ if __name__ == '__main__': if success and os.environ.get("WATERMARK") == "1": apply_watermark(clip_final_path) deliver_path = clip_final_path + # Which stretches were stacked (SPLIT): captions go on the + # seam there, and /api/subtitle needs it again later. + import layout_ranges as _layouts + clip['layout_ranges'] = _layouts.read(clip_final_path) if success and os.environ.get("AUTO_HOOK") == "1": hooked = auto_hook_clip(clip_final_path, clip) if hooked: deliver_path, clip['auto_hook'] = hooked if success: - captioned = auto_caption_clip(deliver_path, transcript, start, end) + captioned = auto_caption_clip( + deliver_path, transcript, start, end, + split_ranges=_layouts.split_ranges(clip['layout_ranges'])) print(f" ✅ Clip {i+1} ready: {clip_final_path}") # Hand the API the file to actually serve for this clip. # Without it the status poller guesses the clean reframe diff --git a/reframe_v2.py b/reframe_v2.py index f417161..0970005 100644 --- a/reframe_v2.py +++ b/reframe_v2.py @@ -25,6 +25,7 @@ import active_speaker import camera_inset import punch_in import screencast_layout +import layout_ranges import split_layout from ffmpeg_utils import (video_encode_args, escape_filter_value, QUALITY_FAST, METADATA_SCRUB) @@ -565,5 +566,8 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None, import shutil shutil.rmtree(workdir, ignore_errors=True) + # Tell the caption pass which stretches are stacked (see layout_ranges). + layout_ranges.write(final_output_video, + [(s / fps, e / fps, strategy) for s, e, strategy in ranges]) print(f" ✅ Clip saved to {final_output_video}") return True diff --git a/subtitles.py b/subtitles.py index 4e8c0e0..efaf431 100644 --- a/subtitles.py +++ b/subtitles.py @@ -306,7 +306,7 @@ def generate_ass(transcript, clip_start, clip_end, output_path, border_color="#000000", border_width=2, highlight_color="#FFD700", bg_color="#000000", bg_opacity=0.0, effect="none", base_opacity=1.0, uppercase=False, - margin_v=SAFE_MARGIN_V): + margin_v=SAFE_MARGIN_V, split_ranges=None): """ 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 @@ -330,6 +330,19 @@ def generate_ass(transcript, clip_start, clip_end, output_path, align_map = {'top': 8, 'middle': 5, 'bottom': 2} ass_alignment = align_map.get(str(alignment).lower(), 2) + # On a SPLIT scene the two speakers are stacked and the seam between the + # halves (exactly mid-frame) is the one place the text covers nobody, so + # every word event inside such a stretch is anchored there with an inline + # \an5, per event rather than per style: a clip mixes stacked and single + # shots, and the text moves with the cut. ``split_ranges`` is a list of + # (start, end) in clip seconds (layout_ranges.split_ranges); the style's + # own alignment still rules everywhere else. Only the ASS path can do + # this: SRT burns carry one alignment for the whole file. + seam_ranges = [(float(a), float(b)) for a, b in (split_ranges or [])] + + def seam_prefix(t): + return "{\\an5}" if any(a <= t < b for a, b in seam_ranges) else "" + safe_font = _sanitize_font_name(font_name) base_opacity = _clamp_number(base_opacity, 0.05, 1.0, 1.0) # Dim inactive words via a fully-opaque scaled color (NOT alpha — see @@ -409,7 +422,8 @@ def generate_ass(transcript, clip_start, clip_end, output_path, parts.append(text) events.append( - f"Dialogue: 0,{_ass_time(ev_start)},{_ass_time(ev_end)},Default,,0,0,0,,{' '.join(parts)}" + f"Dialogue: 0,{_ass_time(ev_start)},{_ass_time(ev_end)},Default,,0,0,0,," + f"{seam_prefix(ev_start)}{' '.join(parts)}" ) if not events: diff --git a/tests/test_layout_ranges.py b/tests/test_layout_ranges.py new file mode 100644 index 0000000..e092748 --- /dev/null +++ b/tests/test_layout_ranges.py @@ -0,0 +1,92 @@ +"""Captions on the seam of SPLIT scenes: the render records which stretches +are stacked (layout_ranges sidecar), and generate_ass anchors the word events +inside them mid-frame (\\an5) while everything else keeps the style's own +alignment. A clip mixes both, so the placement is per event, not per style.""" +import json +import os + +import pytest + +import layout_ranges +import subtitles + + +def _transcript(words): + return {"language": "en", "segments": [{ + "start": words[0][1], "end": words[-1][2], + "words": [{"word": w, "start": s, "end": e} for w, s, e in words]}]} + + +class TestSidecar: + def test_write_then_read_roundtrip(self, tmp_path): + clip = str(tmp_path / "clip_1.mp4") + layout_ranges.write(clip, [(0, 4.5, "TRACK"), (4.5, 10, "SPLIT")]) + assert os.path.exists(clip + ".layout.json") + got = layout_ranges.read(clip) + assert got == [{"start": 0.0, "end": 4.5, "layout": "track"}, + {"start": 4.5, "end": 10.0, "layout": "split"}] + assert layout_ranges.split_ranges(got) == [(4.5, 10.0)] + + def test_missing_sidecar_is_empty(self, tmp_path): + assert layout_ranges.read(str(tmp_path / "nope.mp4")) == [] + + def test_garbage_is_ignored_not_raised(self, tmp_path): + clip = str(tmp_path / "c.mp4") + with open(clip + ".layout.json", "w") as f: + f.write("{not json") + assert layout_ranges.read(clip) == [] + assert layout_ranges.normalise([{"start": "x"}, (3, 1, "split"), (1, 2, "SPLIT"), 7]) == [ + {"start": 1.0, "end": 2.0, "layout": "split"}] + + def test_write_failure_does_not_raise(self, tmp_path): + layout_ranges.write(str(tmp_path / "missing_dir" / "c.mp4"), [(0, 1, "split")]) + + +class TestSeamCaptions: + def _events(self, tmp_path, split_ranges, **kw): + out = tmp_path / "subs.ass" + # Leading spaces as Whisper emits them: without them the merge step + # glues the words into one token and one block. + words = [(" one", 10.0, 10.4), (" two", 10.5, 10.9), # single shot + (" three", 13.0, 13.4), (" four", 13.5, 13.9)] # stacked + ok = subtitles.generate_ass(_transcript(words), 10.0, 14.0, str(out), + max_chars=8, split_ranges=split_ranges, **kw) + assert ok + return [l for l in out.read_text(encoding="utf-8-sig").splitlines() + if l.startswith("Dialogue:")] + + def test_only_split_stretches_move_to_the_seam(self, tmp_path): + # Ranges are in CLIP seconds, like the events themselves. + ev = self._events(tmp_path, [(2.5, 4.0)]) + first_block = [e for e in ev if "one" in e] + second_block = [e for e in ev if "three" in e] + assert first_block and second_block + assert all("{\\an5}" not in e for e in first_block) + assert all(e.split(",,")[-1].startswith("{\\an5}") for e in second_block) + + def test_no_ranges_changes_nothing(self, tmp_path): + assert all("\\an5" not in e for e in self._events(tmp_path, None)) + assert all("\\an5" not in e for e in self._events(tmp_path, [])) + + def test_style_alignment_still_rules_elsewhere(self, tmp_path): + out = tmp_path / "s.ass" + subtitles.generate_ass(_transcript([(" hi", 0.0, 0.5)]), 0.0, 1.0, str(out), + alignment="top", split_ranges=[(5, 6)]) + header = out.read_text(encoding="utf-8-sig") + assert ",8,10,10," in header # Alignment 8 = top in the Style line + + +class TestCaptionerReadsSidecar: + def test_auto_caption_uses_sidecar_when_not_told(self, tmp_path, monkeypatch): + main = pytest.importorskip("main") + clip = str(tmp_path / "x.mp4") + open(clip, "wb").close() + layout_ranges.write(clip, [(0, 3, "SPLIT")]) + seen = {} + + def fake_generate_ass(*a, **kw): + seen["split_ranges"] = kw.get("split_ranges") + return False # stop before ffmpeg + monkeypatch.setattr(subtitles, "generate_ass", fake_generate_ass) + main.auto_caption_clip(clip, _transcript([(" a", 0.0, 0.5)]), 0.0, 3.0) + assert seen["split_ranges"] == [(0.0, 3.0)]