From 0d9e04f333a75bc8eb81ef08ddad7236e06d332f Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Wed, 19 Aug 2026 12:09:02 +0200 Subject: [PATCH] fix(reframe): harden PR #70's manual reframing after review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Meter the re-render: /api/clip/reframe now reserves/commits/releases minutes exactly like a source-path /rerender — it is the same GPU work, and it was free and uncapped. - Re-apply captions by default (reapply_captions param to opt out): every default clip ships with burned captions, and the reframe silently returned caption-less files. - Read metadata.json INSIDE the per-job lock (same _reframe_locked shape as /rerender): the read-outside/write-inside window let a concurrent rerender's recipe get clobbered by a stale write. - Interplay with whole-clip framing: recipe.framing keeps forcing its layout on the scenes the user did not hand-position (apply_crop_overrides runs after force_strategy, so per-scene wins where named), and the recipe is preserved through the reframe instead of being rebuilt bare. - /rerender clears stale crop_overrides: scene indices only mean anything against the cut they were made for, and the trim render does not apply them — leaving them made /scenes reopen showing overrides that would land on the wrong shots. - /scenes: entitlement-gated (it cuts, scene-detects and encodes on every open), serialized per job (stable output names tore under concurrent opens), 400 on horizontal jobs, real aspect for square jobs, temp_ prefix on preview/thumbnails (kept out of the self-host S3 backup), faststart + timeout on the preview encode. - Tests for all of it plus the apply_crop_overrides math the PR described but did not include (12 new, suite at 502). --- app.py | 197 ++++++++++++++++++++--------- tests/test_reframe_endpoint.py | 225 +++++++++++++++++++++++++++++++++ 2 files changed, 359 insertions(+), 63 deletions(-) create mode 100644 tests/test_reframe_endpoint.py diff --git a/app.py b/app.py index 476d492..46c844b 100644 --- a/app.py +++ b/app.py @@ -2327,6 +2327,10 @@ _FRAMING_STRATEGIES = {"auto": None, "full": "WIDE", "track": "TRACK"} # share metadata.json and the canonical files, so they must not interleave. _rerender_locks: Dict[str, asyncio.Lock] = {} +# Scene-listing builds write stable preview/thumbnail names per job; serialize +# them so overlapping editor opens don't tear each other's files. +_scenes_locks: Dict[str, asyncio.Lock] = {} + @app.post("/api/clip/rerender") async def rerender_clip(req: RerenderRequest, request: Request): @@ -2463,6 +2467,12 @@ async def _rerender_locked(req: RerenderRequest, request: Request, job): updates = {'video_url': new_video_url, 'start': new_start, 'end': new_end, 'recipe': new_recipe} + # 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 + # wrong shots (re-frame after trimming to re-apply by hand). + if clip.get('crop_overrides'): + updates['crop_overrides'] = None clip.update(updates) data['shorts'] = clips with open(json_files[0], 'w') as f: @@ -2513,6 +2523,7 @@ class ReframeRequest(BaseModel): # regions. Fractions travel instead of pixels so the editor never needs to # know the source dimensions. crop_overrides: Dict[str, Any] + reapply_captions: bool = True def _clip_scene_workfile(source_path, segments, output_dir, token): @@ -2535,6 +2546,9 @@ async def get_clip_scenes(job_id: str, clip_index: int, request: Request): is to show what the automatic crop threw away, which the 9:16 file no longer contains. """ + # Entitlement too, not just ownership: listing scenes cuts the clip from + # source, runs scene detection and encodes a preview — real compute. + await require_managed_entitlement(request) await _ensure_job_files(job_id, request) if job_id not in jobs: raise HTTPException(status_code=404, detail="Job not found") @@ -2552,6 +2566,11 @@ async def get_clip_scenes(job_id: str, clip_index: int, request: Request): if clip_index < 0 or clip_index >= len(clips): raise HTTPException(status_code=404, detail="Clip not found") + if data.get('output_format') == 'horizontal': + raise HTTPException( + status_code=400, + detail="Horizontal clips keep the full frame; there is no crop to reframe.") + clip = clips[clip_index] segments, _canonical_range = _clip_recipe_parts(clip) # What was applied last time. Without this the editor reopens blank, and @@ -2571,9 +2590,11 @@ async def get_clip_scenes(job_id: str, clip_index: int, request: Request): # Stable for the files the browser fetches (no accumulation), unique # for the temp cut (no collision between overlapping requests). + # temp_ prefix keeps these editor-only artifacts out of the self-host + # S3 backup (it skips temp_*); stable names still avoid accumulation. token = str(clip_index) work_token = f"{clip_index}_{uuid.uuid4().hex[:8]}" - preview_name = f"preview_{clip_index}.mp4" + preview_name = f"temp_preview_{clip_index}.mp4" preview_path = os.path.join(output_dir, preview_name) work_path = _clip_scene_workfile(source_path, segments, output_dir, work_token) try: @@ -2593,7 +2614,7 @@ async def get_clip_scenes(job_id: str, clip_index: int, request: Request): mid = (start_f + end_f) // 2 cap.set(cv2.CAP_PROP_POS_FRAMES, mid) ok, frame = cap.read() - thumb_name = f"scene_{token}_{idx:03d}.jpg" + thumb_name = f"temp_scene_{token}_{idx:03d}.jpg" suggested = 0.5 suggested_y = 0.5 if ok: @@ -2638,23 +2659,32 @@ async def get_clip_scenes(job_id: str, clip_index: int, request: Request): ["ffmpeg", "-y", "-loglevel", "error", "-i", work_path, "-vf", "scale=640:-2", "-c:v", "libx264", "-preset", "veryfast", "-crf", "30", "-c:a", "aac", "-b:a", "96k", - preview_path], check=True) + # faststart: the editor's