feat(editor): manual framing override (auto / full frame / track subject)

The scene classifier only counts faces, so a screencast-style video with a
presenter in frame gets TRACK and the crop eats the slide (the SCREENCAST/
WIDE detectors sit behind the opt-in layouts=auto flag). The clip editor now
has a framing selector that pins every scene's layout: 'full' renders the
whole source frame (WIDE: no side-crop, blurred bands), 'track' forces the
subject-tracking crop, 'auto' returns to the classifier.

Plumbed as force_strategy through reframe_v2.render -> render_clip ->
perform_recut -> /api/clip/rerender (and the recut_clip MCP tool). A
non-auto choice always re-reframes from the retained source (409 without
it) and persists in the clip's recipe, so later plain trims inherit the
look instead of silently reverting; an explicit 'auto' resets it.

Verified live: framing=full on a TRACK-cropped clip re-rendered with the
full frame visible edge to edge (125s source path), and the editor reopens
with the persisted choice preselected.
This commit is contained in:
juancarlos.cavero 2026-08-19 01:06:48 +02:00
parent 4611ca119b
commit 9c220efddb
7 changed files with 173 additions and 17 deletions

31
app.py
View file

@ -2267,6 +2267,7 @@ async def get_clip_edl(job_id: str, clip_index: int, request: Request):
"clip_index": clip_index, "clip_index": clip_index,
"title": clip.get('video_title_for_youtube_short') or '', "title": clip.get('video_title_for_youtube_short') or '',
"segments": segments, "segments": segments,
"framing": (clip.get('recipe') or {}).get('framing') or 'auto',
"canonical_range": canonical_range, "canonical_range": canonical_range,
"duration": total, "duration": total,
"current_file": current_file, "current_file": current_file,
@ -2299,6 +2300,15 @@ class RerenderRequest(BaseModel):
segments: List[RerenderSegment] segments: List[RerenderSegment]
snap_to_words: bool = False snap_to_words: bool = False
reapply_captions: bool = True reapply_captions: bool = True
# None = inherit the recipe's framing (so plain trims keep the look);
# 'auto' resets to the classifier; 'full'/'track' force a layout.
framing: Optional[str] = None
# Manual framing -> reframe-engine strategy. 'full' shows the whole source
# frame (WIDE: no side-cropping, blurred filler bands); 'track' forces the
# subject-tracking crop. Anything non-auto needs the retained source video.
_FRAMING_STRATEGIES = {"auto": None, "full": "WIDE", "track": "TRACK"}
# One lock per job (same pattern as _restore_locks): rerenders on the same job # One lock per job (same pattern as _restore_locks): rerenders on the same job
@ -2356,6 +2366,12 @@ async def _rerender_locked(req: RerenderRequest, request: Request, job):
source_path = _locate_source(req.job_id) source_path = _locate_source(req.job_id)
source_duration = _source_duration_seconds(source_path) if source_path else None source_duration = _source_duration_seconds(source_path) if source_path else None
framing = req.framing or (clip.get('recipe') or {}).get('framing') or 'auto'
if framing not in _FRAMING_STRATEGIES:
raise HTTPException(status_code=400,
detail="framing must be one of: auto, full, track")
force_strategy = _FRAMING_STRATEGIES[framing]
try: try:
segments = recut.normalize_segments( segments = recut.normalize_segments(
[{"start": s.start, "end": s.end} for s in req.segments], [{"start": s.start, "end": s.end} for s in req.segments],
@ -2379,14 +2395,19 @@ async def _rerender_locked(req: RerenderRequest, request: Request, job):
except recut.RecutError as e: except recut.RecutError as e:
raise HTTPException(status_code=400, detail=str(e)) raise HTTPException(status_code=400, detail=str(e))
fast = (os.path.exists(canonical_path) # A framing override always re-reframes from the source: the canonical file
# has the old layout baked into its pixels.
fast = (force_strategy is None
and os.path.exists(canonical_path)
and recut.within_range(segments, canonical_range['start'], and recut.within_range(segments, canonical_range['start'],
canonical_range['end'])) canonical_range['end']))
if not fast and not source_path: if not fast and not source_path:
raise HTTPException( raise HTTPException(
status_code=409, status_code=409,
detail="The source video is no longer on the server, so segments " detail=("The source video is no longer on the server; changing the "
"must stay within the original clip range.") "framing needs it." if force_strategy is not None else
"The source video is no longer on the server, so segments "
"must stay within the original clip range."))
total = recut.total_duration(segments) total = recut.total_duration(segments)
rerender_minutes = (max(1, math.ceil(total / 60.0)) rerender_minutes = (max(1, math.ceil(total / 60.0))
@ -2410,6 +2431,7 @@ async def _rerender_locked(req: RerenderRequest, request: Request, job):
output_dir=output_dir, clean_name=clean_name, output_dir=output_dir, clean_name=clean_name,
reframe=True, output_format=data.get('output_format', 'auto'), reframe=True, output_format=data.get('output_format', 'auto'),
watermark=bool(job.get('watermark')), watermark=bool(job.get('watermark')),
force_strategy=force_strategy,
captions_transcript=v_transcript) captions_transcript=v_transcript)
try: try:
@ -2419,6 +2441,8 @@ async def _rerender_locked(req: RerenderRequest, request: Request, job):
new_video_url = f"/videos/{req.job_id}/{served_name}" new_video_url = f"/videos/{req.job_id}/{served_name}"
new_recipe = {"v": 1, "segments": segments, new_recipe = {"v": 1, "segments": segments,
"canonical_range": canonical_range} "canonical_range": canonical_range}
if framing != 'auto':
new_recipe["framing"] = framing
# Covering range, deliberately not segments[0]/segments[-1]: segments # Covering range, deliberately not segments[0]/segments[-1]: segments
# may legally be out of source order, and downstream consumers only # may legally be out of source order, and downstream consumers only
# need a sane positive window (the recipe is the real timeline). # need a sane positive window (the recipe is the real timeline).
@ -2442,6 +2466,7 @@ async def _rerender_locked(req: RerenderRequest, request: Request, job):
"success": True, "success": True,
"new_video_url": new_video_url, "new_video_url": new_video_url,
"recipe": new_recipe, "recipe": new_recipe,
"framing": framing,
"start": new_start, "start": new_start,
"end": new_end, "end": new_end,
"duration": total, "duration": total,

View file

@ -92,6 +92,9 @@ export default function ClipEditor({ jobId, clipIndex, clipTitle, onClose, onRer
const [snapToWords, setSnapToWords] = useState(true); const [snapToWords, setSnapToWords] = useState(true);
const [reapplyCaptions, setReapplyCaptions] = useState(true); const [reapplyCaptions, setReapplyCaptions] = useState(true);
// Framing override: 'auto' (classifier) | 'full' (whole frame) | 'track'.
const [framing, setFraming] = useState('auto');
const [renderedFraming, setRenderedFraming] = useState('auto');
// The recipe of the currently RENDERED preview (playhead maps onto it). // The recipe of the currently RENDERED preview (playhead maps onto it).
const [renderedSegments, setRenderedSegments] = useState(null); const [renderedSegments, setRenderedSegments] = useState(null);
const [previewUrl, setPreviewUrl] = useState(null); const [previewUrl, setPreviewUrl] = useState(null);
@ -120,6 +123,8 @@ export default function ClipEditor({ jobId, clipIndex, clipTitle, onClose, onRer
setEdl(data); setEdl(data);
dispatch({ type: 'init', segments: data.segments.map((s) => ({ ...s })) }); dispatch({ type: 'init', segments: data.segments.map((s) => ({ ...s })) });
setRenderedSegments(data.segments.map((s) => ({ ...s }))); setRenderedSegments(data.segments.map((s) => ({ ...s })));
setFraming(data.framing || 'auto');
setRenderedFraming(data.framing || 'auto');
setReapplyCaptions(true); setReapplyCaptions(true);
setPreviewUrl(getApiUrl(`/videos/${jobId}/${data.current_file}`)); setPreviewUrl(getApiUrl(`/videos/${jobId}/${data.current_file}`));
} catch (e) { } catch (e) {
@ -139,8 +144,9 @@ export default function ClipEditor({ jobId, clipIndex, clipTitle, onClose, onRer
const total = totalOf(segments); const total = totalOf(segments);
const dirty = useMemo(() => { const dirty = useMemo(() => {
if (!renderedSegments) return false; if (!renderedSegments) return false;
return JSON.stringify(segments) !== JSON.stringify(renderedSegments); return JSON.stringify(segments) !== JSON.stringify(renderedSegments)
}, [segments, renderedSegments]); || framing !== renderedFraming;
}, [segments, renderedSegments, framing, renderedFraming]);
// Trim bounds: with the source gone, cuts must stay inside the range the // Trim bounds: with the source gone, cuts must stay inside the range the
// canonical file was rendered from. // canonical file was rendered from.
@ -152,11 +158,13 @@ export default function ClipEditor({ jobId, clipIndex, clipTitle, onClose, onRer
(seg) => !sourceAvailable && (seg.start < canonical.start - 0.05 || seg.end > canonical.end + 0.05), (seg) => !sourceAvailable && (seg.start < canonical.start - 0.05 || seg.end > canonical.end + 0.05),
[sourceAvailable, canonical], [sourceAvailable, canonical],
); );
const needsSourcePath = segments.some((s) => s.start < canonical.start - 0.05 || s.end > canonical.end + 0.05); const needsSourcePath = framing !== 'auto'
|| segments.some((s) => s.start < canonical.start - 0.05 || s.end > canonical.end + 0.05);
const invalidSegments = segments.some(outOfRange); const invalidSegments = segments.some(outOfRange);
const overCaps = segments.length > limits.max_segments || total > limits.max_total_seconds; const overCaps = segments.length > limits.max_segments || total > limits.max_total_seconds;
const canRender = !rendering && segments.length > 0 && !invalidSegments && !overCaps const canRender = !rendering && segments.length > 0 && !invalidSegments && !overCaps
&& segments.every((s) => s.end - s.start >= minSeg); && segments.every((s) => s.end - s.start >= minSeg)
&& (framing === 'auto' || sourceAvailable);
// ---- helpers ------------------------------------------------------------ // ---- helpers ------------------------------------------------------------
const snapEdge = useCallback((t, kind) => { const snapEdge = useCallback((t, kind) => {
@ -367,6 +375,7 @@ export default function ClipEditor({ jobId, clipIndex, clipTitle, onClose, onRer
segments: segments.map((s) => ({ start: s.start, end: s.end })), segments: segments.map((s) => ({ start: s.start, end: s.end })),
snap_to_words: false, // boundaries are already word-snapped client-side snap_to_words: false, // boundaries are already word-snapped client-side
reapply_captions: reapplyCaptions, reapply_captions: reapplyCaptions,
framing,
}), }),
}); });
if (!res.ok) { if (!res.ok) {
@ -376,6 +385,8 @@ export default function ClipEditor({ jobId, clipIndex, clipTitle, onClose, onRer
} }
const data = await res.json(); const data = await res.json();
setRenderedSegments(data.recipe.segments.map((s) => ({ ...s }))); setRenderedSegments(data.recipe.segments.map((s) => ({ ...s })));
setRenderedFraming(data.framing || 'auto');
setFraming(data.framing || 'auto');
dispatch({ type: 'init', segments: data.recipe.segments.map((s) => ({ ...s })) }); dispatch({ type: 'init', segments: data.recipe.segments.map((s) => ({ ...s })) });
setPreviewUrl(`${getApiUrl(data.new_video_url)}?t=${Date.now()}`); setPreviewUrl(`${getApiUrl(data.new_video_url)}?t=${Date.now()}`);
onRerendered?.(clipIndex, data); onRerendered?.(clipIndex, data);
@ -550,6 +561,43 @@ export default function ClipEditor({ jobId, clipIndex, clipTitle, onClose, onRer
</button> </button>
</div> </div>
{/* framing override */}
<div>
<p className="eyebrow mb-2">Framing</p>
<div className="grid grid-cols-3 gap-1.5">
{[
{ value: 'auto', label: 'auto', hint: 'AI decides per scene' },
{ value: 'full', label: 'full frame', hint: 'whole shot, no side-crop' },
{ value: 'track', label: 'track subject', hint: 'crop follows the person' },
].map((f) => (
<button
key={f.value}
type="button"
title={f.hint}
disabled={f.value !== 'auto' && !sourceAvailable}
onClick={() => setFraming(f.value)}
className={`py-1.5 px-2 rounded-input border text-xs lowercase transition-colors
${framing === f.value
? 'border-[color:var(--color-accent)] text-ink'
: 'border-rule2 text-muted hover:border-[color:var(--color-accent)]'}
disabled:opacity-40 disabled:cursor-not-allowed`}
>
{f.label}
</button>
))}
</div>
{!sourceAvailable && (
<p className="text-[11px] text-muted mt-1.5 leading-relaxed">
framing changes need the source video, which is no longer on the server
</p>
)}
{framing !== renderedFraming && (
<p className="text-[11px] text-muted mt-1.5 leading-relaxed">
changing the framing re-runs the reframe engine (slower than a fast recut)
</p>
)}
</div>
{/* toggles */} {/* toggles */}
<div className="space-y-2.5"> <div className="space-y-2.5">
<label className="flex items-center justify-between cursor-pointer"> <label className="flex items-center justify-between cursor-pointer">

18
main.py
View file

@ -882,13 +882,17 @@ def auto_caption_clip(clip_path, transcript, clip_start, clip_end):
return None return None
def render_clip(input_video, final_output_video, output_format="auto"): def render_clip(input_video, final_output_video, output_format="auto",
force_strategy=None):
"""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.
``force_strategy`` (e.g. 'WIDE'/'TRACK') pins every scene's layout — the
clip editor's manual framing override."""
if output_format == "horizontal": if output_format == "horizontal":
return finalize_clip_passthrough(input_video, final_output_video) return finalize_clip_passthrough(input_video, final_output_video)
aspect = 1.0 if output_format == "square" else ASPECT_RATIO aspect = 1.0 if output_format == "square" else ASPECT_RATIO
return process_video_to_vertical(input_video, final_output_video, aspect_ratio=aspect) return process_video_to_vertical(input_video, final_output_video, aspect_ratio=aspect,
force_strategy=force_strategy)
# Watermark geometry, as fractions of the clip width/height. # Watermark geometry, as fractions of the clip width/height.
@ -956,11 +960,14 @@ def apply_watermark(video_path):
return False return False
def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPECT_RATIO): def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPECT_RATIO,
force_strategy=None):
""" """
Core logic to reframe a horizontal video to a target aspect ratio using Core logic to reframe a horizontal video to a target aspect ratio using
scene detection and Active Speaker Tracking (MediaPipe). scene detection and Active Speaker Tracking (MediaPipe).
aspect_ratio: width/height of the output (9/16 vertical, 1.0 square). aspect_ratio: width/height of the output (9/16 vertical, 1.0 square).
force_strategy pins every scene's layout (v2 engine only — the v1 loop
below has no layout concept beyond its own classifier).
""" """
script_start_time = time.time() script_start_time = time.time()
@ -970,7 +977,8 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE
try: try:
import reframe_v2 import reframe_v2
t0 = time.time() t0 = time.time()
result = reframe_v2.render(input_video, final_output_video, aspect_ratio) result = reframe_v2.render(input_video, final_output_video, aspect_ratio,
force_strategy=force_strategy)
print(f" ⏱️ Reframe v2 total: {time.time() - t0:.1f}s") print(f" ⏱️ Reframe v2 total: {time.time() - t0:.1f}s")
return result return result
except Exception as e: except Exception as e:

View file

@ -217,6 +217,14 @@ TOOLS = [
"type": "boolean", "type": "boolean",
"description": "Burn default captions back on after the recut (default true).", "description": "Burn default captions back on after the recut (default true).",
}, },
"framing": {
"type": "string", "enum": ["auto", "full", "track"],
"description": "Layout override: 'full' shows the whole source frame "
"(no side-cropping), 'track' forces the subject-tracking "
"crop, 'auto' resets to the AI classifier. Omit to keep "
"the clip's current framing. Non-auto values re-run the "
"reframe engine and need the retained source video.",
},
}, },
"required": ["job_id", "clip_index", "segments"], "required": ["job_id", "clip_index", "segments"],
}, },
@ -373,7 +381,7 @@ async def _tool_add_subtitles(client, args):
async def _tool_recut_clip(client, args): async def _tool_recut_clip(client, args):
body = {"job_id": args["job_id"], "clip_index": args["clip_index"], body = {"job_id": args["job_id"], "clip_index": args["clip_index"],
"segments": args["segments"]} "segments": args["segments"]}
for k in ("snap_to_words", "reapply_captions"): for k in ("snap_to_words", "reapply_captions", "framing"):
if args.get(k) is not None: if args.get(k) is not None:
body[k] = args[k] body[k] = args[k]
resp = await client.post("/api/clip/rerender", json=body) resp = await client.post("/api/clip/rerender", json=body)

View file

@ -260,7 +260,8 @@ def _run_ffmpeg(command):
def perform_recut(*, input_path, segments, output_dir, clean_name, def perform_recut(*, input_path, segments, output_dir, clean_name,
reframe=False, output_format="auto", watermark=False, reframe=False, output_format="auto", watermark=False,
captions_transcript=None, runner=None, renderer=None, captions_transcript=None, force_strategy=None,
runner=None, renderer=None,
watermarker=None, captioner=None): watermarker=None, captioner=None):
"""Render a recut clip. Returns (served_filename, clean_filename). """Render a recut clip. Returns (served_filename, clean_filename).
@ -292,7 +293,13 @@ def perform_recut(*, input_path, segments, output_dir, clean_name,
runner=runner) runner=runner)
if reframe: if reframe:
render = renderer or _main_attr("render_clip") if renderer is not None:
render = renderer # injected fakes keep the 3-arg contract
else:
main_render = _main_attr("render_clip")
def render(i, o, f):
return main_render(i, o, f, force_strategy=force_strategy)
if not render(work_path, out_path, output_format): if not render(work_path, out_path, output_format):
raise RuntimeError("reframe failed on the recut clip") raise RuntimeError("reframe failed on the recut clip")
else: else:

View file

@ -230,12 +230,18 @@ def _run(cmd):
stderr=subprocess.PIPE, timeout=1800) stderr=subprocess.PIPE, timeout=1800)
def render(input_video, final_output_video, aspect_ratio, content_ranges=None): def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
force_strategy=None):
"""Full v2 reframe of one clip. Raises on failure (caller falls back). """Full v2 reframe of one clip. Raises on failure (caller falls back).
``content_ranges`` comes from screencast_layout.detect_content_ranges() on ``content_ranges`` comes from screencast_layout.detect_content_ranges() on
the SOURCE video, already translated into this clip's timeline. None or [] the SOURCE video, already translated into this clip's timeline. None or []
means the layout never triggers, which is the default. means the layout never triggers, which is the default.
``force_strategy`` ('WIDE' / 'TRACK' / any layout the render loop knows)
applies that layout to EVERY scene, skipping the classifier and the layout
upgrades — it exists for the clip editor's manual framing override, where
the user's explicit choice is the whole point.
""" """
import main as m import main as m
content_ranges = content_ranges or [] content_ranges = content_ranges or []
@ -256,6 +262,11 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None):
scenes = [(FrameTimecode(0, fps), FrameTimecode(total, fps))] scenes = [(FrameTimecode(0, fps), FrameTimecode(total, fps))]
scene_boundaries = [(s.get_frames(), e.get_frames()) for s, e in scenes] scene_boundaries = [(s.get_frames(), e.get_frames()) for s, e in scenes]
if force_strategy:
strategies = [force_strategy] * len(scenes)
content_ranges = [] # no screencast/inset upgrades over an explicit choice
print(f" 🎯 Framing override: every scene -> {force_strategy}")
else:
strategies = m.analyze_scenes_strategy(input_video, scenes) strategies = m.analyze_scenes_strategy(input_video, scenes)
# SPLIT is an upgrade applied on top of the TRACK/GENERAL verdict, keyed by # SPLIT is an upgrade applied on top of the TRACK/GENERAL verdict, keyed by

View file

@ -160,6 +160,22 @@ class TestRerenderValidation:
assert resp.status_code == 409 assert resp.status_code == 409
assert fake_recut == [] assert fake_recut == []
def test_invalid_framing_400(self, job, fake_recut):
resp = _request("POST", "/api/clip/rerender", {
"job_id": JOB_ID, "clip_index": 0, "framing": "cinematic",
"segments": [{"start": 12, "end": 30}]})
assert resp.status_code == 400
assert fake_recut == []
def test_framing_without_source_409(self, job, fake_recut):
os.remove(job["dir"] / "src.mp4")
resp = _request("POST", "/api/clip/rerender", {
"job_id": JOB_ID, "clip_index": 0, "framing": "full",
"segments": [{"start": 12, "end": 30}]}) # in-range, but framing needs source
assert resp.status_code == 409
assert "framing" in resp.json()["detail"]
assert fake_recut == []
def test_snap_clamp_inverted_segment_400_not_500(self, job, fake_recut, def test_snap_clamp_inverted_segment_400_not_500(self, job, fake_recut,
monkeypatch): monkeypatch):
# No source + snap_to_words: a segment fully outside the canonical # No source + snap_to_words: a segment fully outside the canonical
@ -217,6 +233,39 @@ class TestRerenderPaths:
assert resp.status_code == 200 assert resp.status_code == 200
assert fake_recut[0]["captions_transcript"] is None assert fake_recut[0]["captions_transcript"] is None
def test_framing_full_forces_source_path_and_persists(self, job, fake_recut):
# In-range segments would take the fast path, but a framing override
# must re-reframe from the source with the forced layout.
resp = _request("POST", "/api/clip/rerender", {
"job_id": JOB_ID, "clip_index": 0, "framing": "full",
"segments": [{"start": 12, "end": 22}]})
assert resp.status_code == 200
data = resp.json()
assert data["render_path"] == "source"
assert data["framing"] == "full"
assert data["recipe"]["framing"] == "full"
call = fake_recut[0]
assert call["input_path"].endswith("src.mp4")
assert call["reframe"] is True
assert call["force_strategy"] == "WIDE"
# A follow-up trim WITHOUT a framing field inherits the recipe's
# framing (the look must not silently revert on a plain trim)...
resp2 = _request("POST", "/api/clip/rerender", {
"job_id": JOB_ID, "clip_index": 0,
"segments": [{"start": 13, "end": 21}]})
assert resp2.status_code == 200
assert resp2.json()["framing"] == "full"
assert fake_recut[1]["force_strategy"] == "WIDE"
# ...while an explicit 'auto' resets to the classifier and the fast path.
resp3 = _request("POST", "/api/clip/rerender", {
"job_id": JOB_ID, "clip_index": 0, "framing": "auto",
"segments": [{"start": 13, "end": 21}]})
assert resp3.status_code == 200
assert resp3.json()["render_path"] == "fast"
assert "framing" not in resp3.json()["recipe"]
class TestRerenderPersistence: class TestRerenderPersistence:
SEGMENTS = [{"start": 10, "end": 15}, {"start": 48, "end": 52}] SEGMENTS = [{"start": 10, "end": 15}, {"start": 48, "end": 52}]