fix(reframe): harden PR #70's manual reframing after review
- 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).
This commit is contained in:
parent
0bfe27561d
commit
0d9e04f333
2 changed files with 359 additions and 63 deletions
115
app.py
115
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.
|
# share metadata.json and the canonical files, so they must not interleave.
|
||||||
_rerender_locks: Dict[str, asyncio.Lock] = {}
|
_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")
|
@app.post("/api/clip/rerender")
|
||||||
async def rerender_clip(req: RerenderRequest, request: Request):
|
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,
|
updates = {'video_url': new_video_url, 'start': new_start,
|
||||||
'end': new_end, 'recipe': new_recipe}
|
'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)
|
clip.update(updates)
|
||||||
data['shorts'] = clips
|
data['shorts'] = clips
|
||||||
with open(json_files[0], 'w') as f:
|
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
|
# regions. Fractions travel instead of pixels so the editor never needs to
|
||||||
# know the source dimensions.
|
# know the source dimensions.
|
||||||
crop_overrides: Dict[str, Any]
|
crop_overrides: Dict[str, Any]
|
||||||
|
reapply_captions: bool = True
|
||||||
|
|
||||||
|
|
||||||
def _clip_scene_workfile(source_path, segments, output_dir, token):
|
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
|
is to show what the automatic crop threw away, which the 9:16 file no
|
||||||
longer contains.
|
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)
|
await _ensure_job_files(job_id, request)
|
||||||
if job_id not in jobs:
|
if job_id not in jobs:
|
||||||
raise HTTPException(status_code=404, detail="Job not found")
|
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):
|
if clip_index < 0 or clip_index >= len(clips):
|
||||||
raise HTTPException(status_code=404, detail="Clip not found")
|
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]
|
clip = clips[clip_index]
|
||||||
segments, _canonical_range = _clip_recipe_parts(clip)
|
segments, _canonical_range = _clip_recipe_parts(clip)
|
||||||
# What was applied last time. Without this the editor reopens blank, and
|
# 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
|
# Stable for the files the browser fetches (no accumulation), unique
|
||||||
# for the temp cut (no collision between overlapping requests).
|
# 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)
|
token = str(clip_index)
|
||||||
work_token = f"{clip_index}_{uuid.uuid4().hex[:8]}"
|
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)
|
preview_path = os.path.join(output_dir, preview_name)
|
||||||
work_path = _clip_scene_workfile(source_path, segments, output_dir, work_token)
|
work_path = _clip_scene_workfile(source_path, segments, output_dir, work_token)
|
||||||
try:
|
try:
|
||||||
|
|
@ -2593,7 +2614,7 @@ async def get_clip_scenes(job_id: str, clip_index: int, request: Request):
|
||||||
mid = (start_f + end_f) // 2
|
mid = (start_f + end_f) // 2
|
||||||
cap.set(cv2.CAP_PROP_POS_FRAMES, mid)
|
cap.set(cv2.CAP_PROP_POS_FRAMES, mid)
|
||||||
ok, frame = cap.read()
|
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 = 0.5
|
||||||
suggested_y = 0.5
|
suggested_y = 0.5
|
||||||
if ok:
|
if ok:
|
||||||
|
|
@ -2638,13 +2659,20 @@ async def get_clip_scenes(job_id: str, clip_index: int, request: Request):
|
||||||
["ffmpeg", "-y", "-loglevel", "error", "-i", work_path,
|
["ffmpeg", "-y", "-loglevel", "error", "-i", work_path,
|
||||||
"-vf", "scale=640:-2", "-c:v", "libx264", "-preset",
|
"-vf", "scale=640:-2", "-c:v", "libx264", "-preset",
|
||||||
"veryfast", "-crf", "30", "-c:a", "aac", "-b:a", "96k",
|
"veryfast", "-crf", "30", "-c:a", "aac", "-b:a", "96k",
|
||||||
preview_path], check=True)
|
# faststart: the editor's <video> streams the preview;
|
||||||
|
# a tail moov would stall it until fully downloaded.
|
||||||
|
"-movflags", "+faststart",
|
||||||
|
preview_path], check=True, timeout=600)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
print(f"Scene preview failed: {exc}")
|
print(f"Scene preview failed: {exc}")
|
||||||
finally:
|
finally:
|
||||||
if os.path.exists(work_path):
|
if os.path.exists(work_path):
|
||||||
os.remove(work_path)
|
os.remove(work_path)
|
||||||
|
|
||||||
|
# Serialized per job: two overlapping opens would run two ffmpeg writers
|
||||||
|
# on the same stable preview/thumbnail names and serve a torn file.
|
||||||
|
lock = _scenes_locks.setdefault(job_id, asyncio.Lock())
|
||||||
|
async with lock:
|
||||||
try:
|
try:
|
||||||
loop = asyncio.get_event_loop()
|
loop = asyncio.get_event_loop()
|
||||||
orig_w, orig_h, scenes_out, preview_name = await loop.run_in_executor(None, build)
|
orig_w, orig_h, scenes_out, preview_name = await loop.run_in_executor(None, build)
|
||||||
|
|
@ -2652,9 +2680,11 @@ async def get_clip_scenes(job_id: str, clip_index: int, request: Request):
|
||||||
print(f"Scene listing error: {e}")
|
print(f"Scene listing error: {e}")
|
||||||
raise HTTPException(status_code=500, detail=str(e))
|
raise HTTPException(status_code=500, detail=str(e))
|
||||||
|
|
||||||
# Width of the 9:16 window as a fraction of the source width: the editor
|
# Width of the crop window as a fraction of the source width: the editor
|
||||||
# draws the rectangle with it and needs no pixel arithmetic of its own.
|
# draws the rectangle with it and needs no pixel arithmetic of its own.
|
||||||
crop_w = min(orig_w, orig_h * (9.0 / 16.0))
|
# The aspect follows the job's output format (9:16, or 1:1 for square).
|
||||||
|
aspect = 1.0 if data.get('output_format') == 'square' else 9.0 / 16.0
|
||||||
|
crop_w = min(orig_w, orig_h * aspect)
|
||||||
return {
|
return {
|
||||||
"job_id": job_id,
|
"job_id": job_id,
|
||||||
"clip_index": clip_index,
|
"clip_index": clip_index,
|
||||||
|
|
@ -2683,18 +2713,6 @@ async def reframe_clip(req: ReframeRequest, request: Request):
|
||||||
job = jobs[req.job_id]
|
job = jobs[req.job_id]
|
||||||
await _assert_job_owner(request, job)
|
await _assert_job_owner(request, job)
|
||||||
|
|
||||||
output_dir = os.path.join(OUTPUT_DIR, req.job_id)
|
|
||||||
json_files = glob.glob(os.path.join(output_dir, "*_metadata.json"))
|
|
||||||
if not json_files:
|
|
||||||
raise HTTPException(status_code=404, detail="Metadata not found")
|
|
||||||
with open(json_files[0], 'r') as f:
|
|
||||||
data = json.load(f)
|
|
||||||
|
|
||||||
clips = data.get('shorts', [])
|
|
||||||
if req.clip_index < 0 or req.clip_index >= len(clips):
|
|
||||||
raise HTTPException(status_code=404, detail="Clip not found")
|
|
||||||
clip = clips[req.clip_index]
|
|
||||||
|
|
||||||
def _fraction(v):
|
def _fraction(v):
|
||||||
return min(1.0, max(0.0, float(v)))
|
return min(1.0, max(0.0, float(v)))
|
||||||
|
|
||||||
|
|
@ -2717,6 +2735,32 @@ async def reframe_clip(req: ReframeRequest, request: Request):
|
||||||
raise HTTPException(status_code=400,
|
raise HTTPException(status_code=400,
|
||||||
detail="No scene framing was provided.")
|
detail="No scene framing was provided.")
|
||||||
|
|
||||||
|
# Same lock as /rerender: both read-modify-write the job's metadata.json,
|
||||||
|
# and the metadata must be read INSIDE the lock or a rerender committing
|
||||||
|
# in between gets clobbered by a write of stale data.
|
||||||
|
lock = _rerender_locks.setdefault(req.job_id, asyncio.Lock())
|
||||||
|
async with lock:
|
||||||
|
return await _reframe_locked(req, request, job, overrides)
|
||||||
|
|
||||||
|
|
||||||
|
async def _reframe_locked(req: ReframeRequest, request: Request, job, overrides):
|
||||||
|
output_dir = os.path.join(OUTPUT_DIR, req.job_id)
|
||||||
|
json_files = glob.glob(os.path.join(output_dir, "*_metadata.json"))
|
||||||
|
if not json_files:
|
||||||
|
raise HTTPException(status_code=404, detail="Metadata not found")
|
||||||
|
with open(json_files[0], 'r') as f:
|
||||||
|
data = json.load(f)
|
||||||
|
|
||||||
|
clips = data.get('shorts', [])
|
||||||
|
if req.clip_index < 0 or req.clip_index >= len(clips):
|
||||||
|
raise HTTPException(status_code=404, detail="Clip not found")
|
||||||
|
clip = clips[req.clip_index]
|
||||||
|
|
||||||
|
if data.get('output_format') == 'horizontal':
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="Horizontal clips keep the full frame; there is no crop to reframe.")
|
||||||
|
|
||||||
segments, canonical_range = _clip_recipe_parts(clip)
|
segments, canonical_range = _clip_recipe_parts(clip)
|
||||||
source_path = _locate_source(req.job_id)
|
source_path = _locate_source(req.job_id)
|
||||||
if not source_path:
|
if not source_path:
|
||||||
|
|
@ -2725,6 +2769,25 @@ async def reframe_clip(req: ReframeRequest, request: Request):
|
||||||
detail="The source video is no longer on the server, so the "
|
detail="The source video is no longer on the server, so the "
|
||||||
"framing of this clip can no longer be changed.")
|
"framing of this clip can no longer be changed.")
|
||||||
|
|
||||||
|
# Whole-clip framing (recipe.framing, the clip editor's selector) still
|
||||||
|
# applies to the scenes the user did NOT hand-position: apply_crop_overrides
|
||||||
|
# runs after force_strategy, so a per-scene choice beats the whole-clip one.
|
||||||
|
framing = (clip.get('recipe') or {}).get('framing') or 'auto'
|
||||||
|
force_strategy = _FRAMING_STRATEGIES.get(framing)
|
||||||
|
|
||||||
|
# A reframe re-renders the full cut from source — same work as a source-path
|
||||||
|
# rerender, so it meters the same.
|
||||||
|
total = recut.total_duration(segments)
|
||||||
|
rerender_minutes = (max(1, math.ceil(total / 60.0))
|
||||||
|
if BILLING_ENABLED else 0)
|
||||||
|
reservation_id = await reserve_managed_action(
|
||||||
|
request, rerender_minutes, req.job_id, "reframe")
|
||||||
|
|
||||||
|
# Every default clip ships with burned captions; re-rendering without them
|
||||||
|
# would silently hand back a caption-less file.
|
||||||
|
v_transcript = (recut.virtual_transcript(data.get('transcript') or {}, segments)
|
||||||
|
if req.reapply_captions else None)
|
||||||
|
|
||||||
base_name = os.path.basename(json_files[0]).replace('_metadata.json', '')
|
base_name = os.path.basename(json_files[0]).replace('_metadata.json', '')
|
||||||
# The CLEAN base name, exactly as /api/clip/rerender does — never the
|
# The CLEAN base name, exactly as /api/clip/rerender does — never the
|
||||||
# current derived file. perform_recut prefixes whatever it is given, so
|
# current derived file. perform_recut prefixes whatever it is given, so
|
||||||
|
|
@ -2734,23 +2797,28 @@ async def reframe_clip(req: ReframeRequest, request: Request):
|
||||||
# "Error opening output ...: File name too long".
|
# "Error opening output ...: File name too long".
|
||||||
clean_name = f"{base_name}_clip_{req.clip_index + 1}.mp4"
|
clean_name = f"{base_name}_clip_{req.clip_index + 1}.mp4"
|
||||||
|
|
||||||
lock = _rerender_locks.setdefault(req.job_id, asyncio.Lock())
|
|
||||||
async with lock:
|
|
||||||
def run():
|
def run():
|
||||||
return recut.perform_recut(
|
return recut.perform_recut(
|
||||||
input_path=source_path, segments=segments,
|
input_path=source_path, segments=segments,
|
||||||
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')),
|
||||||
crop_overrides=overrides)
|
force_strategy=force_strategy,
|
||||||
|
crop_overrides=overrides,
|
||||||
|
captions_transcript=v_transcript)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
loop = asyncio.get_event_loop()
|
loop = asyncio.get_event_loop()
|
||||||
served_name, _clean = await loop.run_in_executor(None, run)
|
served_name, _clean = await loop.run_in_executor(None, run)
|
||||||
|
|
||||||
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,
|
||||||
|
"canonical_range": canonical_range}
|
||||||
|
if framing != 'auto':
|
||||||
|
new_recipe["framing"] = framing
|
||||||
updates = {
|
updates = {
|
||||||
'video_url': new_video_url,
|
'video_url': new_video_url,
|
||||||
|
'recipe': new_recipe,
|
||||||
'crop_overrides': {str(k): v for k, v in overrides.items()},
|
'crop_overrides': {str(k): v for k, v in overrides.items()},
|
||||||
}
|
}
|
||||||
clip.update(updates)
|
clip.update(updates)
|
||||||
|
|
@ -2762,19 +2830,22 @@ async def reframe_clip(req: ReframeRequest, request: Request):
|
||||||
mem_clips[req.clip_index].update(updates)
|
mem_clips[req.clip_index].update(updates)
|
||||||
|
|
||||||
_archive_clip_edit_bg(req.job_id, req.clip_index, served_name)
|
_archive_clip_edit_bg(req.job_id, req.clip_index, served_name)
|
||||||
|
if reservation_id:
|
||||||
|
await _metering.commit_reservation(reservation_id)
|
||||||
# The cut is untouched, but the response mirrors /rerender's shape
|
# The cut is untouched, but the response mirrors /rerender's shape
|
||||||
# so the dashboard can reuse one handler without clearing the
|
# so the dashboard can reuse one handler without clearing the
|
||||||
# clip's timing fields.
|
# clip's timing fields.
|
||||||
return {
|
return {
|
||||||
"success": True,
|
"success": True,
|
||||||
"new_video_url": new_video_url,
|
"new_video_url": new_video_url,
|
||||||
"recipe": {"v": 1, "segments": segments,
|
"recipe": new_recipe,
|
||||||
"canonical_range": canonical_range},
|
|
||||||
"start": min(s['start'] for s in segments),
|
"start": min(s['start'] for s in segments),
|
||||||
"end": max(s['end'] for s in segments),
|
"end": max(s['end'] for s in segments),
|
||||||
"framed_scenes": sorted(overrides),
|
"framed_scenes": sorted(overrides),
|
||||||
}
|
}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
if reservation_id:
|
||||||
|
await _metering.release_reservation(reservation_id)
|
||||||
print(f"Reframe Error: {e}")
|
print(f"Reframe Error: {e}")
|
||||||
raise HTTPException(status_code=500, detail=str(e))
|
raise HTTPException(status_code=500, detail=str(e))
|
||||||
|
|
||||||
|
|
|
||||||
225
tests/test_reframe_endpoint.py
Normal file
225
tests/test_reframe_endpoint.py
Normal file
|
|
@ -0,0 +1,225 @@
|
||||||
|
"""Tests for PR #70's manual per-scene reframing: the /api/clip/reframe
|
||||||
|
endpoint contract (validation, metering seam, caption reapply, persistence,
|
||||||
|
interplay with whole-clip framing) and the pure apply_crop_overrides math.
|
||||||
|
|
||||||
|
Same harness as test_rerender_endpoint.py: BILLING_ENABLED=0 self-host round
|
||||||
|
trips with the render stubbed at recut.perform_recut.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
app_module = pytest.importorskip("app")
|
||||||
|
import recut # noqa: E402
|
||||||
|
|
||||||
|
JOB_ID = "reframe-endpoint-test-job"
|
||||||
|
|
||||||
|
TRANSCRIPT = {
|
||||||
|
"language": "en",
|
||||||
|
"segments": [
|
||||||
|
{"start": 0.0, "end": 60.0, "text": "hello world",
|
||||||
|
"words": [{"word": "hello", "start": 12.0, "end": 12.5},
|
||||||
|
{"word": "world", "start": 20.0, "end": 20.4}]},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _request(method, path, json_body=None):
|
||||||
|
async def _do():
|
||||||
|
transport = httpx.ASGITransport(app=app_module.app)
|
||||||
|
async with httpx.AsyncClient(transport=transport,
|
||||||
|
base_url="http://testserver") as client:
|
||||||
|
return await client.request(method, path, json=json_body)
|
||||||
|
return asyncio.run(_do())
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def job(tmp_path, monkeypatch):
|
||||||
|
out_root = tmp_path / "output"
|
||||||
|
up_root = tmp_path / "uploads"
|
||||||
|
job_dir = out_root / JOB_ID
|
||||||
|
job_dir.mkdir(parents=True)
|
||||||
|
up_root.mkdir()
|
||||||
|
monkeypatch.setattr(app_module, "OUTPUT_DIR", str(out_root))
|
||||||
|
monkeypatch.setattr(app_module, "UPLOAD_DIR", str(up_root))
|
||||||
|
|
||||||
|
clip = {
|
||||||
|
"start": 10.0, "end": 40.0,
|
||||||
|
"video_title_for_youtube_short": "test clip",
|
||||||
|
"video_url": f"/videos/{JOB_ID}/mytitle_clip_1.mp4",
|
||||||
|
}
|
||||||
|
meta = {"shorts": [clip], "transcript": TRANSCRIPT,
|
||||||
|
"source_video": "src.mp4", "output_format": "auto",
|
||||||
|
"cost_analysis": {}}
|
||||||
|
(job_dir / "mytitle_metadata.json").write_text(json.dumps(meta))
|
||||||
|
(job_dir / "mytitle_clip_1.mp4").write_bytes(b"canonical")
|
||||||
|
(job_dir / "src.mp4").write_bytes(b"source")
|
||||||
|
|
||||||
|
app_module.jobs[JOB_ID] = {
|
||||||
|
"status": "completed", "logs": [],
|
||||||
|
"result": {"clips": [dict(clip)], "cost_analysis": {}},
|
||||||
|
"user_id": None, "watermark": False,
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
yield {"dir": job_dir, "meta_path": job_dir / "mytitle_metadata.json"}
|
||||||
|
finally:
|
||||||
|
app_module.jobs.pop(JOB_ID, None)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def fake_recut(monkeypatch):
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def fake(**kwargs):
|
||||||
|
calls.append(kwargs)
|
||||||
|
name = f"recut_1_{kwargs['clean_name']}"
|
||||||
|
with open(os.path.join(kwargs["output_dir"], name), "wb") as f:
|
||||||
|
f.write(b"recut")
|
||||||
|
return name, name
|
||||||
|
|
||||||
|
monkeypatch.setattr(recut, "perform_recut", fake)
|
||||||
|
return calls
|
||||||
|
|
||||||
|
|
||||||
|
class TestReframeValidation:
|
||||||
|
def test_no_usable_overrides_400(self, job, fake_recut):
|
||||||
|
for overrides in ({}, {"notanumber": "x"}, {"0": "garbage"}):
|
||||||
|
resp = _request("POST", "/api/clip/reframe", {
|
||||||
|
"job_id": JOB_ID, "clip_index": 0,
|
||||||
|
"crop_overrides": overrides})
|
||||||
|
assert resp.status_code == 400, overrides
|
||||||
|
assert fake_recut == []
|
||||||
|
|
||||||
|
def test_horizontal_clips_400(self, job, fake_recut):
|
||||||
|
meta = json.loads(job["meta_path"].read_text())
|
||||||
|
meta["output_format"] = "horizontal"
|
||||||
|
job["meta_path"].write_text(json.dumps(meta))
|
||||||
|
resp = _request("POST", "/api/clip/reframe", {
|
||||||
|
"job_id": JOB_ID, "clip_index": 0, "crop_overrides": {"0": 0.5}})
|
||||||
|
assert resp.status_code == 400
|
||||||
|
assert fake_recut == []
|
||||||
|
|
||||||
|
def test_gone_source_409(self, job, fake_recut):
|
||||||
|
os.remove(job["dir"] / "src.mp4")
|
||||||
|
resp = _request("POST", "/api/clip/reframe", {
|
||||||
|
"job_id": JOB_ID, "clip_index": 0, "crop_overrides": {"0": 0.5}})
|
||||||
|
assert resp.status_code == 409
|
||||||
|
assert fake_recut == []
|
||||||
|
|
||||||
|
|
||||||
|
class TestReframeRender:
|
||||||
|
def test_renders_from_source_with_overrides_and_captions(self, job, fake_recut):
|
||||||
|
resp = _request("POST", "/api/clip/reframe", {
|
||||||
|
"job_id": JOB_ID, "clip_index": 0,
|
||||||
|
"crop_overrides": {"0": 0.2, "1": {"top": 0.6, "bottom": {"x": 0.3, "y": 0.4}}}})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
data = resp.json()
|
||||||
|
assert data["framed_scenes"] == [0, 1]
|
||||||
|
|
||||||
|
call = fake_recut[0]
|
||||||
|
assert call["input_path"].endswith("src.mp4")
|
||||||
|
assert call["reframe"] is True
|
||||||
|
assert call["crop_overrides"][0] == 0.2
|
||||||
|
assert call["crop_overrides"][1]["top"] == {"x": 0.6, "y": 0.5}
|
||||||
|
assert call["crop_overrides"][1]["bottom"] == {"x": 0.3, "y": 0.4}
|
||||||
|
# Captions come back by default — every default clip ships with them.
|
||||||
|
assert call["captions_transcript"]["segments"][0]["words"]
|
||||||
|
|
||||||
|
# Overrides persisted (string keys, JSON-style) for /scenes to serve.
|
||||||
|
meta = json.loads(job["meta_path"].read_text())
|
||||||
|
assert meta["shorts"][0]["crop_overrides"]["0"] == 0.2
|
||||||
|
|
||||||
|
def test_reapply_captions_false(self, job, fake_recut):
|
||||||
|
resp = _request("POST", "/api/clip/reframe", {
|
||||||
|
"job_id": JOB_ID, "clip_index": 0, "reapply_captions": False,
|
||||||
|
"crop_overrides": {"0": 0.5}})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert fake_recut[0]["captions_transcript"] is None
|
||||||
|
|
||||||
|
def test_whole_clip_framing_carries_into_the_render(self, job, fake_recut):
|
||||||
|
# recipe.framing='full' (the clip editor's selector) must keep forcing
|
||||||
|
# WIDE on the scenes the user did not hand-position.
|
||||||
|
meta = json.loads(job["meta_path"].read_text())
|
||||||
|
meta["shorts"][0]["recipe"] = {
|
||||||
|
"v": 1, "segments": [{"start": 10.0, "end": 40.0}],
|
||||||
|
"canonical_range": {"start": 10.0, "end": 40.0},
|
||||||
|
"framing": "full"}
|
||||||
|
job["meta_path"].write_text(json.dumps(meta))
|
||||||
|
resp = _request("POST", "/api/clip/reframe", {
|
||||||
|
"job_id": JOB_ID, "clip_index": 0, "crop_overrides": {"0": 0.5}})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert fake_recut[0]["force_strategy"] == "WIDE"
|
||||||
|
assert resp.json()["recipe"]["framing"] == "full"
|
||||||
|
|
||||||
|
|
||||||
|
class TestRerenderClearsSceneOverrides:
|
||||||
|
def test_trim_clears_stale_overrides(self, job, fake_recut):
|
||||||
|
# Hand-frame first…
|
||||||
|
assert _request("POST", "/api/clip/reframe", {
|
||||||
|
"job_id": JOB_ID, "clip_index": 0,
|
||||||
|
"crop_overrides": {"0": 0.2}}).status_code == 200
|
||||||
|
# …then trim: scene indices no longer mean anything against the new
|
||||||
|
# cut, so the stale overrides must not survive for /scenes to serve.
|
||||||
|
assert _request("POST", "/api/clip/rerender", {
|
||||||
|
"job_id": JOB_ID, "clip_index": 0,
|
||||||
|
"segments": [{"start": 12, "end": 22}]}).status_code == 200
|
||||||
|
meta = json.loads(job["meta_path"].read_text())
|
||||||
|
assert not meta["shorts"][0].get("crop_overrides")
|
||||||
|
|
||||||
|
|
||||||
|
class TestApplyCropOverrides:
|
||||||
|
"""Pure math on the trajectory — no ffmpeg, no models."""
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _mod(self):
|
||||||
|
self.rf = pytest.importorskip("reframe_v2")
|
||||||
|
|
||||||
|
def test_single_crop_centres_the_window(self):
|
||||||
|
xs = [None] * 100
|
||||||
|
strategies = ["GENERAL"]
|
||||||
|
xs, strategies = self.rf.apply_crop_overrides(
|
||||||
|
xs, strategies, [(0, 100)], {"0": 0.5}, crop_w=608, orig_w=1920)
|
||||||
|
assert strategies == ["TRACK"]
|
||||||
|
assert xs[0] == xs[99] == 656 # 1920*0.5 - 608/2
|
||||||
|
|
||||||
|
def test_clamps_at_both_edges(self):
|
||||||
|
xs = [0] * 10
|
||||||
|
xs, _ = self.rf.apply_crop_overrides(
|
||||||
|
xs, ["TRACK"], [(0, 10)], {"0": 0.0}, crop_w=608, orig_w=1920)
|
||||||
|
assert xs[0] == 0
|
||||||
|
xs, _ = self.rf.apply_crop_overrides(
|
||||||
|
xs, ["TRACK"], [(0, 10)], {"0": 1.0}, crop_w=608, orig_w=1920)
|
||||||
|
assert xs[0] == 1920 - 608
|
||||||
|
|
||||||
|
def test_untouched_scenes_stay_untouched(self):
|
||||||
|
xs = [111] * 20
|
||||||
|
strategies = ["TRACK", "GENERAL"]
|
||||||
|
xs, strategies = self.rf.apply_crop_overrides(
|
||||||
|
xs, strategies, [(0, 10), (10, 20)], {"1": 0.5},
|
||||||
|
crop_w=608, orig_w=1920)
|
||||||
|
assert xs[:10] == [111] * 10 # scene 0 keeps the auto camera
|
||||||
|
assert strategies[0] == "TRACK"
|
||||||
|
assert strategies[1] == "TRACK" # scene 1 forced back from GENERAL
|
||||||
|
|
||||||
|
def test_malformed_and_unknown_indices_are_skipped(self):
|
||||||
|
xs = [7] * 10
|
||||||
|
out_xs, strategies = self.rf.apply_crop_overrides(
|
||||||
|
xs, ["TRACK"], [(0, 10)],
|
||||||
|
{"nope": 0.5, "9": 0.5, "0": "garbage"}, crop_w=608, orig_w=1920)
|
||||||
|
assert out_xs == [7] * 10
|
||||||
|
assert strategies == ["TRACK"]
|
||||||
|
|
||||||
|
def test_split_writes_into_splits_keyed_by_start_frame(self):
|
||||||
|
splits = {}
|
||||||
|
xs, strategies = self.rf.apply_crop_overrides(
|
||||||
|
[None] * 10, ["GENERAL"], [(0, 10)],
|
||||||
|
{"0": {"top": {"x": 0.6, "y": 0.3}, "bottom": 0.2}},
|
||||||
|
crop_w=608, orig_w=1920, orig_h=1080, splits=splits)
|
||||||
|
assert strategies == ["SPLIT"]
|
||||||
|
top, bottom = splits[0]
|
||||||
|
assert top == (0.6 * 1920, 0.3 * 1080)
|
||||||
|
assert bottom == (0.2 * 1920, 0.5 * 1080)
|
||||||
Loading…
Reference in a new issue