From d9b15b43285c75c52e108df1b3213d9fa490c6de Mon Sep 17 00:00:00 2001 From: victorcavero14 Date: Wed, 5 Aug 2026 11:03:15 +0200 Subject: [PATCH 1/7] =?UTF-8?q?feat(editor):=20per-clip=20EDL=20backend=20?= =?UTF-8?q?=E2=80=94=20recut=20engine,=20/edl=20+=20/rerender=20endpoints,?= =?UTF-8?q?=20MCP=20tool?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every clip now exposes its recipe (which source segments it was cut from) via GET /api/clip/{job}/{i}/edl, and POST /api/clip/rerender re-renders it from an edited segment list: fast path recuts from the already-reframed canonical file, source path re-reframes from the retained source (--keep-original now passed for URL jobs). Captions/subtitles/transcript remap piecewise through recut.virtual_transcript for multi-segment clips. Co-Authored-By: Claude Fable 5 --- app.py | 359 ++++++++++++++++++++++++++++++-- main.py | 6 + mcp_server.py | 55 +++++ recut.py | 292 ++++++++++++++++++++++++++ tests/test_recut.py | 277 ++++++++++++++++++++++++ tests/test_rerender_endpoint.py | 258 +++++++++++++++++++++++ 6 files changed, 1228 insertions(+), 19 deletions(-) create mode 100644 recut.py create mode 100644 tests/test_recut.py create mode 100644 tests/test_rerender_endpoint.py diff --git a/app.py b/app.py index f98b6e2..fae8134 100644 --- a/app.py +++ b/app.py @@ -23,6 +23,7 @@ from fastapi.responses import HTMLResponse, FileResponse, JSONResponse 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 load_dotenv() @@ -371,15 +372,20 @@ 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 ``_clip_.mp4`` and any - post-processing (auto-captions, and /api/subtitle re-styles) as - ``subtitled__.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. + post-processing (auto-captions, /api/subtitle re-styles, and clip-editor + recuts) as ``subtitled__.mp4`` / ``recut__.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 (or their recut) on a redeploy. """ clean = f"{base_name}_clip_{index + 1}.mp4" try: - derived = glob.glob(os.path.join(output_dir, f"subtitled_*_{clean}")) + # subtitled_*_{clean} also matches subtitled__recut__{clean}, + # i.e. a captioned recut; the bare recut_ pattern covers recuts that + # shipped uncaptioned. + derived = (glob.glob(os.path.join(output_dir, f"subtitled_*_{clean}")) + + glob.glob(os.path.join(output_dir, f"recut_*_{clean}"))) except Exception: derived = [] if not derived: @@ -425,6 +431,15 @@ def _reapply_captions(job_id, clip_index, video_path): return None clip = clips[clip_index] import main as _main + # A recut clip is a concatenation of source segments, so the flat + # start..end window is wrong for it — caption against the clip-relative + # remapped transcript instead (same trick /api/subtitle uses). + recipe_segments = (clip.get('recipe') or {}).get('segments') + if recipe_segments: + v_transcript = recut.virtual_transcript(transcript, recipe_segments) + return _main.auto_caption_clip( + video_path, v_transcript, 0.0, + recut.total_duration(recipe_segments)) return _main.auto_caption_clip(video_path, transcript, clip['start'], clip['end']) except Exception as e: @@ -1546,7 +1561,10 @@ async def process_endpoint( input_path = None if url: - cmd.extend(["-u", url]) + # Keep the downloaded source inside the job dir: the clip editor's + # re-render path cuts new segments from it, and it ages out with the + # rest of the job (retention window + OUTPUT_MAX_GB cap) either way. + cmd.extend(["-u", url, "--keep-original"]) else: # Save uploaded file with size limit check. # basename() strips any path components from the client-supplied @@ -1638,21 +1656,46 @@ async def get_status(job_id: str, request: Request): } +def _locate_source(job_id: str): + """Find a job's source video on disk, or None. + + Upload jobs keep it in uploads/{job_id}_*; URL jobs keep the download in + the job dir (--keep-original) under the name recorded as ``source_video`` + in metadata.json. Either way it ages out with the normal retention caps. + """ + matches = [ + f for f in glob.glob(os.path.join(UPLOAD_DIR, f"{glob.escape(job_id)}_*")) + if not os.path.basename(f).startswith("thumb_") + ] + if matches: + return matches[0] + try: + meta_files = glob.glob(os.path.join(OUTPUT_DIR, job_id, "*_metadata.json")) + if meta_files: + with open(meta_files[0], 'r') as f: + name = json.load(f).get('source_video') + if name: + candidate = os.path.join(OUTPUT_DIR, job_id, os.path.basename(name)) + if os.path.exists(candidate): + return candidate + except Exception: + pass + return None + + @app.get("/api/source/{job_id}") async def get_source_video(job_id: str): - """Stream a job's original source video for the live-analysis preview. + """Stream a job's original source video for the live-analysis preview and + the clip editor's source monitor. Uploaded sources are blob URLs in the browser and don't survive a reload, so the recovered session points the preview here instead. Unauthenticated like the /videos mount — the UUID job_id is the capability. """ - matches = [ - f for f in glob.glob(os.path.join(UPLOAD_DIR, f"{job_id}_*")) - if not os.path.basename(f).startswith("thumb_") - ] - if not matches: + source_path = _locate_source(job_id) + if not source_path: raise HTTPException(status_code=404, detail="Source not found") - return FileResponse(matches[0], media_type="video/mp4") + return FileResponse(source_path, media_type="video/mp4") @app.get("/api/jobs/{job_id}/download-all") @@ -2073,8 +2116,16 @@ async def get_clip_transcript(job_id: str, clip_index: int, request: Request): raise HTTPException(status_code=404, detail="Clip not found") clip_data = clips[clip_index] - clip_start = clip_data.get('start', 0) - clip_end = clip_data.get('end', 0) + + # Recut clips are concatenations of source segments; remap the transcript + # onto the clip timeline so every consumer keeps its flat start..end logic. + recipe_segments = (clip_data.get('recipe') or {}).get('segments') + if recipe_segments: + transcript = recut.virtual_transcript(transcript, recipe_segments) + clip_start, clip_end = 0.0, recut.total_duration(recipe_segments) + else: + clip_start = clip_data.get('start', 0) + clip_end = clip_data.get('end', 0) # Extract words within clip range and convert to CaptionWord format captions = [] @@ -2096,6 +2147,264 @@ async def get_clip_transcript(job_id: str, clip_index: int, request: Request): } +# --- Clip editor: EDL + re-render --- + +# How much transcript to send around the clip's segments — enough for the +# editor's word-level trimming without shipping a whole podcast's words. +EDL_WORD_CONTEXT_SECONDS = 45.0 + + +def _source_duration_seconds(path): + """Probe a video's duration; None when it can't be read.""" + try: + import cv2 + cap = cv2.VideoCapture(path) + fps = cap.get(cv2.CAP_PROP_FPS) + frames = cap.get(cv2.CAP_PROP_FRAME_COUNT) + cap.release() + # OpenCV reports -1/-1 for files it can't read — a naive truthiness + # check would turn that into a phantom 1.0s duration. + if fps > 0 and frames > 0: + return round(frames / fps, 3) + except Exception: + pass + return None + + +def _clip_recipe_parts(clip): + """(segments, canonical_range) for a clip — synthesized from the flat + start/end for clips that were never recut.""" + recipe = clip.get('recipe') or {} + fallback = {"start": float(clip.get('start', 0) or 0), + "end": float(clip.get('end', 0) or 0)} + segments = recipe.get('segments') or [dict(fallback)] + canonical_range = recipe.get('canonical_range') or dict(fallback) + return segments, canonical_range + + +@app.get("/api/clip/{job_id}/{clip_index}/edl") +async def get_clip_edl(job_id: str, clip_index: int, request: Request): + """The clip's editable recipe: which source segments it was cut from, the + word timeline around them, and whether the source is still available for + cuts outside the original range.""" + await _ensure_job_files(job_id, request) + if job_id not in jobs: + raise HTTPException(status_code=404, detail="Job not found") + job = jobs[job_id] + await _assert_job_owner(request, job) + + output_dir = os.path.join(OUTPUT_DIR, 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 clip_index < 0 or clip_index >= len(clips): + raise HTTPException(status_code=404, detail="Clip not found") + clip = clips[clip_index] + + segments, canonical_range = _clip_recipe_parts(clip) + transcript = data.get('transcript') or {} + words = recut.transcript_words(transcript) + + source_path = _locate_source(job_id) + source_duration = _source_duration_seconds(source_path) if source_path else None + duration_estimated = source_duration is None + if duration_estimated: + # Best remaining scale for the source track: the last spoken word or + # the furthest point any recipe touches. + candidates = [canonical_range['end']] + [s['end'] for s in segments] + if words: + candidates.append(words[-1]['e']) + source_duration = round(max(candidates), 3) + + lo = min(s['start'] for s in segments) - EDL_WORD_CONTEXT_SECONDS + hi = max(s['end'] for s in segments) + EDL_WORD_CONTEXT_SECONDS + words_out = [ + {"w": w["w"], "s": round(w["s"], 3), "e": round(w["e"], 3)} + for w in words if w["e"] >= lo and w["s"] <= hi + ] + + current_file = (clip.get('video_url') or '').split('/')[-1] + if not current_file: + base_name = os.path.basename(json_files[0]).replace('_metadata.json', '') + current_file = _canonical_clip_file(output_dir, base_name, clip_index) + + total = recut.total_duration(segments) + return { + "job_id": job_id, + "clip_index": clip_index, + "title": clip.get('video_title_for_youtube_short') or '', + "segments": segments, + "canonical_range": canonical_range, + "duration": total, + "current_file": current_file, + "has_captions": bool(re.match(r'^subtitled_\d+_', current_file)), + "words": words_out, + "source": { + "available": bool(source_path), + "url": f"/api/source/{job_id}" if source_path else None, + "duration": source_duration, + "duration_estimated": duration_estimated, + }, + "limits": { + "max_segments": recut.MAX_SEGMENTS, + "min_segment_seconds": recut.MIN_SEGMENT_SECONDS, + "max_total_seconds": recut.MAX_TOTAL_SECONDS, + }, + "rerender_minutes": (max(1, math.ceil(total / 60.0)) + if BILLING_ENABLED else 0), + } + + +class RerenderSegment(BaseModel): + start: float + end: float + + +class RerenderRequest(BaseModel): + job_id: str + clip_index: int + segments: List[RerenderSegment] + snap_to_words: bool = False + reapply_captions: bool = True + + +@app.post("/api/clip/rerender") +async def rerender_clip(req: RerenderRequest, request: Request): + """Re-render a clip from an edited EDL (the clip editor's save button). + + Two paths, chosen automatically: + - FAST: every segment stays inside the range the canonical clip was cut + from → recut straight from the already-reframed canonical file. No ML, + no source needed. + - SOURCE: a segment reaches outside → recut from the retained source and + re-reframe with the same engine the pipeline used. 409 when the source + already aged out. + """ + await require_managed_entitlement(request) + await _ensure_job_files(req.job_id, request) + if req.job_id not in jobs: + raise HTTPException(status_code=404, detail="Job not found") + job = jobs[req.job_id] + 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] + transcript = data.get('transcript') or {} + + base_name = os.path.basename(json_files[0]).replace('_metadata.json', '') + clean_name = f"{base_name}_clip_{req.clip_index + 1}.mp4" + canonical_path = os.path.join(output_dir, clean_name) + + _, canonical_range = _clip_recipe_parts(clip) + source_path = _locate_source(req.job_id) + source_duration = _source_duration_seconds(source_path) if source_path else None + + try: + segments = recut.normalize_segments( + [{"start": s.start, "end": s.end} for s in req.segments], + source_duration) + if req.snap_to_words: + snap_bound = source_duration or max(s['end'] for s in segments) + segments = recut.snap_segments(segments, transcript, snap_bound) + if not source_path: + # Snapping trails into silence and may nudge a boundary past + # the canonical range; without a source the fast path is the + # only path, so clamp back instead of failing with a 409. + segments = [ + {"start": round(max(s['start'], canonical_range['start']), 3), + "end": round(min(s['end'], canonical_range['end']), 3)} + for s in segments] + except recut.RecutError as e: + raise HTTPException(status_code=400, detail=str(e)) + + fast = (os.path.exists(canonical_path) + and recut.within_range(segments, canonical_range['start'], + canonical_range['end'])) + if not fast and not source_path: + raise HTTPException( + status_code=409, + detail="The source video is no longer on the server, so segments " + "must stay within the original clip range.") + + 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, "rerender") + + v_transcript = (recut.virtual_transcript(transcript, segments) + if req.reapply_captions else None) + + def run_recut(): + if fast: + return recut.perform_recut( + input_path=canonical_path, + segments=recut.rebase_segments( + segments, canonical_range['start'], canonical_range['end']), + output_dir=output_dir, clean_name=clean_name, + reframe=False, captions_transcript=v_transcript) + return recut.perform_recut( + input_path=source_path, segments=segments, + output_dir=output_dir, clean_name=clean_name, + reframe=True, output_format=data.get('output_format', 'auto'), + watermark=bool(job.get('watermark')), + captions_transcript=v_transcript) + + try: + loop = asyncio.get_event_loop() + served_name, _clean_recut_name = await loop.run_in_executor(None, run_recut) + + new_video_url = f"/videos/{req.job_id}/{served_name}" + new_recipe = {"v": 1, "segments": segments, + "canonical_range": canonical_range} + # Covering range, deliberately not segments[0]/segments[-1]: segments + # may legally be out of source order, and downstream consumers only + # need a sane positive window (the recipe is the real timeline). + new_start = min(s['start'] for s in segments) + new_end = max(s['end'] for s in segments) + + updates = {'video_url': new_video_url, 'start': new_start, + 'end': new_end, 'recipe': new_recipe} + clip.update(updates) + data['shorts'] = clips + with open(json_files[0], 'w') as f: + json.dump(data, f, indent=2) + mem_clips = (job.get('result') or {}).get('clips') or [] + if req.clip_index < len(mem_clips): + mem_clips[req.clip_index].update(updates) + + _archive_clip_edit_bg(req.job_id, req.clip_index, served_name) + if reservation_id: + await _metering.commit_reservation(reservation_id) + return { + "success": True, + "new_video_url": new_video_url, + "recipe": new_recipe, + "start": new_start, + "end": new_end, + "duration": total, + "render_path": "fast" if fast else "source", + } + except Exception as e: + if reservation_id: + await _metering.release_reservation(reservation_id) + print(f"❌ Rerender Error: {e}") + raise HTTPException(status_code=500, detail=str(e)) + + # --- Remotion Render Proxy --- RENDER_SERVICE_URL = os.getenv("RENDER_SERVICE_URL", "http://renderer:3100") @@ -2284,7 +2593,19 @@ async def add_subtitles(req: SubtitleRequest, request: Request): raise HTTPException(status_code=404, detail="Clip not found") clip_data = clips[req.clip_index] - + + # Recut clips concatenate several source segments, so their caption window + # is not the flat start..end range — restyle against the clip-relative + # remapped transcript instead. + recipe_segments = (clip_data.get('recipe') or {}).get('segments') + if recipe_segments: + sub_transcript = recut.virtual_transcript(transcript, recipe_segments) + sub_start, sub_end = 0.0, recut.total_duration(recipe_segments) + else: + sub_transcript = transcript + sub_start = clip_data.get('start', 0) + sub_end = clip_data.get('end', 0) + # Video Path if req.input_filename: # Use chained file @@ -2356,9 +2677,9 @@ async def add_subtitles(req: SubtitleRequest, request: Request): loop = asyncio.get_event_loop() success = await loop.run_in_executor(None, run_transcribe_srt) elif is_karaoke: - success = generate_ass(transcript, clip_data['start'], clip_data['end'], srt_path, **karaoke_opts) + success = generate_ass(sub_transcript, sub_start, sub_end, srt_path, **karaoke_opts) else: - success = generate_srt(transcript, clip_data['start'], clip_data['end'], srt_path) + success = generate_srt(sub_transcript, sub_start, sub_end, srt_path) if not success: raise HTTPException(status_code=400, detail="No words found for this clip range.") diff --git a/main.py b/main.py index 947ee60..bc44114 100644 --- a/main.py +++ b/main.py @@ -1505,6 +1505,12 @@ if __name__ == '__main__': # Save metadata. Silent videos have no transcript → no subtitles, # which is correct (there's no speech to caption). clips_data['transcript'] = transcript or {"language": "none", "segments": []} + # The clip editor's re-render path needs to find the source video + # again and reproduce the render settings, so record both. The + # basename is enough — the file sits in the job dir (URL jobs with + # --keep-original) or in uploads/ (upload jobs). + clips_data['source_video'] = os.path.basename(input_video) + clips_data['output_format'] = output_format metadata_file = os.path.join(output_dir, f"{video_title}_metadata.json") with open(metadata_file, 'w') as f: json.dump(clips_data, f, indent=2) diff --git a/mcp_server.py b/mcp_server.py index 2b7b136..2caab75 100644 --- a/mcp_server.py +++ b/mcp_server.py @@ -156,6 +156,48 @@ TOOLS = [ "required": ["job_id", "clip_index"], }, }, + { + "name": "recut_clip", + "title": "Re-cut a clip from an edited segment list", + "description": ( + "Re-render one clip from a new list of source-video segments (the " + "same engine behind the dashboard's clip editor). Times are seconds " + "in the ORIGINAL source video; segments are concatenated in the " + "given order, so you can trim, extend, drop a dead moment in the " + "middle, or reorder. Segments inside the clip's original range " + "re-render in seconds; going outside needs the retained source " + "video and re-runs the reframe engine." + ), + "inputSchema": { + "type": "object", + "properties": { + "job_id": {"type": "string"}, + "clip_index": {"type": "integer", "description": "0-based index from list_clips."}, + "segments": { + "type": "array", + "items": { + "type": "object", + "properties": { + "start": {"type": "number", "description": "Seconds in the source video."}, + "end": {"type": "number", "description": "Seconds in the source video."}, + }, + "required": ["start", "end"], + }, + "minItems": 1, + "description": "Ordered source segments the new clip is made of.", + }, + "snap_to_words": { + "type": "boolean", + "description": "Snap each boundary onto transcript word boundaries (recommended).", + }, + "reapply_captions": { + "type": "boolean", + "description": "Burn default captions back on after the recut (default true).", + }, + }, + "required": ["job_id", "clip_index", "segments"], + }, + }, { "name": "publish_clip", "title": "Publish a clip to social platforms", @@ -302,6 +344,18 @@ async def _tool_add_subtitles(client, args): return resp.json(), False +async def _tool_recut_clip(client, args): + body = {"job_id": args["job_id"], "clip_index": args["clip_index"], + "segments": args["segments"]} + for k in ("snap_to_words", "reapply_captions"): + if args.get(k) is not None: + body[k] = args[k] + resp = await client.post("/api/clip/rerender", json=body) + if resp.status_code >= 400: + return _api_error(resp), True + return resp.json(), False + + async def _tool_publish_clip(client, args): body = {"job_id": args["job_id"], "clip_index": args["clip_index"], "platforms": args["platforms"]} @@ -320,6 +374,7 @@ _TOOL_IMPLS = { "list_clips": _tool_list_clips, "get_quota": _tool_get_quota, "add_subtitles": _tool_add_subtitles, + "recut_clip": _tool_recut_clip, "publish_clip": _tool_publish_clip, } diff --git a/recut.py b/recut.py new file mode 100644 index 0000000..e10dbe4 --- /dev/null +++ b/recut.py @@ -0,0 +1,292 @@ +""" +Recut engine for the clip editor: a per-clip EDL (list of source segments) is +turned into a rendered clip. + +The pure helpers here are standard-library only (plus ffmpeg_utils, which is +also light) so the module imports in the thin CI environment; everything heavy +(reframing, watermark, auto-captions live in main.py) is imported lazily and +only on the paths that need it. + +Two render paths: + +- FAST: every segment falls inside the range the canonical clip was originally + cut from, so the recut can be cut straight out of the already-reframed + canonical file. No ML, no source video needed, seconds instead of minutes. +- SOURCE: at least one segment reaches outside that range (or there is no + canonical file), so the recut is cut from the source video and re-reframed + with the same engine the pipeline used. +""" + +import json +import os +import shutil +import subprocess +import time + +from ffmpeg_utils import QUALITY_FAST, audio_encode_args, video_encode_args + +# EDL limits. Deliberately generous — the editor is for humans fixing cuts, +# not for stitching feature films. +MAX_SEGMENTS = 12 +MIN_SEGMENT_SECONDS = 0.5 +MAX_TOTAL_SECONDS = 180.0 + +# Segments may start/end a hair outside the canonical range through float +# round-tripping; treat them as inside. +RANGE_TOLERANCE = 0.05 + + +class RecutError(ValueError): + """Invalid EDL — safe to surface verbatim as a 400 detail.""" + + +def normalize_segments(segments, source_duration=None): + """Validate and clamp an EDL. Returns [{'start': float, 'end': float}, ...]. + + Order is preserved — the segment order IS the clip order, and reusing a + source range twice is legal (an echo/replay is a real editing move). + """ + if not isinstance(segments, (list, tuple)) or not segments: + raise RecutError("segments must be a non-empty list") + if len(segments) > MAX_SEGMENTS: + raise RecutError(f"too many segments (max {MAX_SEGMENTS})") + + normalized = [] + for i, seg in enumerate(segments): + try: + start = float(seg["start"]) + end = float(seg["end"]) + except (KeyError, TypeError, ValueError): + raise RecutError(f"segment {i + 1}: start/end must be numbers") + if start != start or end != end: # NaN guard + raise RecutError(f"segment {i + 1}: start/end must be numbers") + start = max(0.0, start) + if source_duration is not None: + end = min(float(source_duration), end) + start = min(start, float(source_duration)) + if end - start < MIN_SEGMENT_SECONDS: + raise RecutError( + f"segment {i + 1} is shorter than {MIN_SEGMENT_SECONDS}s") + normalized.append({"start": round(start, 3), "end": round(end, 3)}) + + if total_duration(normalized) > MAX_TOTAL_SECONDS: + raise RecutError(f"clip would exceed {MAX_TOTAL_SECONDS:.0f}s") + return normalized + + +def total_duration(segments): + return round(sum(s["end"] - s["start"] for s in segments), 3) + + +def within_range(segments, range_start, range_end, tolerance=RANGE_TOLERANCE): + """True when every segment fits inside [range_start, range_end].""" + return all( + s["start"] >= float(range_start) - tolerance + and s["end"] <= float(range_end) + tolerance + for s in segments + ) + + +def rebase_segments(segments, range_start, range_end=None): + """Map source-absolute segments onto a file cut at ``range_start``. + + Used by the fast path: the canonical clip's t=0 is the source's + ``range_start``. Clamps to the file bounds so tolerance-admitted segments + never produce negative seek times. + """ + rebased = [] + for seg in segments: + start = max(0.0, seg["start"] - float(range_start)) + end = seg["end"] - float(range_start) + if range_end is not None: + end = min(end, float(range_end) - float(range_start)) + rebased.append({"start": round(start, 3), "end": round(end, 3)}) + return rebased + + +def snap_segments(segments, transcript, source_duration): + """Snap each segment's bounds onto word boundaries (ground truth beats + millisecond arithmetic — same rationale as the pipeline's snapping).""" + from clip_selection import snap_clip_to_words + + words = transcript_words(transcript) + if not words: + return segments + snapped = [] + for seg in segments: + start, end = snap_clip_to_words( + seg["start"], seg["end"], words, source_duration, + min_duration=MIN_SEGMENT_SECONDS, max_duration=MAX_TOTAL_SECONDS) + snapped.append({"start": start, "end": end}) + return snapped + + +def transcript_words(transcript): + """Flatten a Whisper transcript to [{'w','s','e'}, ...] sorted by start.""" + words = [] + for segment in (transcript or {}).get("segments", []): + for w in segment.get("words", []) or []: + try: + words.append({ + "w": str(w.get("word", "")).strip(), + "s": float(w["start"]), + "e": float(w["end"]), + }) + except (KeyError, TypeError, ValueError): + continue + words.sort(key=lambda w: w["s"]) + return words + + +def virtual_transcript(transcript, segments): + """Remap a source-absolute transcript onto the concatenated clip timeline. + + Each EDL segment becomes one synthetic transcript segment whose words are + shifted so t=0 is the start of the recut clip. This is what lets + auto-captions and subtitle restyles work on multi-segment clips: they keep + slicing "words between clip_start and clip_end" exactly as before, against + this transcript with clip_start=0. + """ + out_segments = [] + offset = 0.0 + for seg in segments: + seg_start, seg_end = float(seg["start"]), float(seg["end"]) + seg_duration = seg_end - seg_start + words = [] + for w in transcript_words(transcript): + if w["e"] <= seg_start or w["s"] >= seg_end: + continue + words.append({ + "word": w["w"], + "start": round(max(0.0, w["s"] - seg_start) + offset, 3), + "end": round(min(seg_duration, w["e"] - seg_start) + offset, 3), + }) + out_segments.append({ + "start": round(offset, 3), + "end": round(offset + seg_duration, 3), + "text": " ".join(w["word"] for w in words), + "words": words, + }) + offset += seg_duration + return { + "language": (transcript or {}).get("language", "en"), + "segments": out_segments, + } + + +def cut_commands(input_path, segments, part_paths): + """ffmpeg argv for each segment cut. Re-encodes for frame-accurate cuts + with uniform parameters so the parts concat cleanly.""" + commands = [] + for seg, part in zip(segments, part_paths): + commands.append([ + "ffmpeg", "-y", + "-ss", str(seg["start"]), + "-to", str(seg["end"]), + "-i", input_path, + *video_encode_args(QUALITY_FAST), + *audio_encode_args(), + part, + ]) + return commands + + +def concat_command(list_path, out_path): + """Concat demuxer over identically-encoded parts — stream copy, no + generation loss on the join.""" + return [ + "ffmpeg", "-y", "-f", "concat", "-safe", "0", + "-i", list_path, "-c", "copy", out_path, + ] + + +def run_cut_concat(input_path, segments, out_path, workdir, runner=None): + """Cut every segment from ``input_path`` and join them into ``out_path``.""" + run = runner or _run_ffmpeg + if len(segments) == 1: + run(cut_commands(input_path, segments, [out_path])[0]) + return out_path + + part_paths = [ + os.path.join(workdir, f"recut_part_{i}.mp4") + for i in range(len(segments)) + ] + list_path = os.path.join(workdir, "recut_concat.txt") + try: + for command in cut_commands(input_path, segments, part_paths): + run(command) + with open(list_path, "w") as f: + for part in part_paths: + f.write(f"file '{part}'\n") + run(concat_command(list_path, out_path)) + finally: + for path in part_paths + [list_path]: + if os.path.exists(path): + os.remove(path) + return out_path + + +def _run_ffmpeg(command): + result = subprocess.run( + command, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + if result.returncode != 0: + tail = (result.stderr or b"").decode("utf-8", "replace")[-400:] + raise RuntimeError(f"ffmpeg failed ({command[1:6]}...): {tail}") + + +def perform_recut(*, input_path, segments, output_dir, clean_name, + reframe=False, output_format="auto", watermark=False, + captions_transcript=None, runner=None, renderer=None, + watermarker=None, captioner=None): + """Render a recut clip. Returns (served_filename, clean_filename). + + - ``input_path``/``segments``: the file to cut from and the times ON THAT + FILE (the caller rebases for the fast path). + - ``reframe``: run the reframe engine on the joined cut (source path only — + the canonical file is already framed). + - ``watermark``: re-apply the free-plan watermark (source path only — the + canonical file already carries it). + - ``captions_transcript``: a clip-relative transcript (see + ``virtual_transcript``); when given and non-empty, captions are burned + LAST onto a ``subtitled__`` derivative, preserving the invariant + that the clean file stays clean for later re-styling. + + The renderer/watermarker/captioner hooks default to main.py's + implementations, imported lazily so this module stays importable without + the ML stack; tests inject fakes. + """ + out_name = f"recut_{int(time.time())}_{clean_name}" + out_path = os.path.join(output_dir, out_name) + work_name = f"temp_{out_name}" + work_path = os.path.join(output_dir, work_name) + + try: + run_cut_concat(input_path, segments, work_path, output_dir, + runner=runner) + + if reframe: + render = renderer or _main_attr("render_clip") + if not render(work_path, out_path, output_format): + raise RuntimeError("reframe failed on the recut clip") + else: + shutil.move(work_path, out_path) + + if watermark: + (watermarker or _main_attr("apply_watermark"))(out_path) + + served_name = out_name + if captions_transcript and captions_transcript.get("segments"): + caption = captioner or _main_attr("auto_caption_clip") + captioned = caption(out_path, captions_transcript, + 0.0, total_duration(segments)) + if captioned: + served_name = os.path.basename(captioned) + return served_name, out_name + finally: + if os.path.exists(work_path): + os.remove(work_path) + + +def _main_attr(name): + import main # heavy — resolved only when a real render/caption runs + return getattr(main, name) diff --git a/tests/test_recut.py b/tests/test_recut.py new file mode 100644 index 0000000..1a557ba --- /dev/null +++ b/tests/test_recut.py @@ -0,0 +1,277 @@ +"""Unit tests for recut.py — the clip editor's EDL engine. + +Pure logic only: validation, range math, the piecewise transcript remap that +keeps captions correct on multi-segment clips, and the ffmpeg command shapes. +The heavy render paths are exercised through injected fakes, never real ffmpeg. +""" + +import os + +import pytest + +import recut + + +def _seg(start, end): + return {"start": start, "end": end} + + +TRANSCRIPT = { + "language": "en", + "segments": [ + { + "start": 0.0, "end": 60.0, "text": "hello world again", + "words": [ + {"word": "hello", "start": 12.0, "end": 12.5}, + {"word": "world", "start": 20.0, "end": 20.4}, + {"word": "again", "start": 50.0, "end": 50.5}, + ], + }, + ], +} + + +class TestNormalizeSegments: + def test_valid_segments_pass_through_in_order(self): + segs = recut.normalize_segments([_seg(50, 60), _seg(10, 20)]) + # Order is the CLIP order — reordering source material is legal. + assert segs == [_seg(50.0, 60.0), _seg(10.0, 20.0)] + + def test_clamps_to_source_duration(self): + segs = recut.normalize_segments([_seg(-5, 20), _seg(90, 500)], + source_duration=100) + assert segs == [_seg(0.0, 20.0), _seg(90.0, 100.0)] + + def test_rejects_empty_and_non_list(self): + for bad in ([], None, "nope", {}): + with pytest.raises(recut.RecutError): + recut.normalize_segments(bad) + + def test_rejects_bad_numbers(self): + for bad in ([{"start": "x", "end": 5}], [{"end": 5}], + [{"start": float("nan"), "end": 5}]): + with pytest.raises(recut.RecutError): + recut.normalize_segments(bad) + + def test_rejects_too_short_segment(self): + with pytest.raises(recut.RecutError): + recut.normalize_segments([_seg(10, 10.2)]) + # A clamp can also make it too short — that must fail, not slip by. + with pytest.raises(recut.RecutError): + recut.normalize_segments([_seg(99.9, 150)], source_duration=100) + + def test_rejects_too_many_segments(self): + segs = [_seg(i * 10, i * 10 + 5) for i in range(recut.MAX_SEGMENTS + 1)] + with pytest.raises(recut.RecutError): + recut.normalize_segments(segs) + + def test_rejects_total_over_cap(self): + with pytest.raises(recut.RecutError): + recut.normalize_segments([_seg(0, recut.MAX_TOTAL_SECONDS + 10)]) + + +class TestRangeMath: + def test_total_duration(self): + assert recut.total_duration([_seg(10, 20), _seg(30, 35)]) == 15.0 + + def test_within_range(self): + assert recut.within_range([_seg(10, 20)], 10, 40) + assert not recut.within_range([_seg(5, 20)], 10, 40) + assert not recut.within_range([_seg(10, 41)], 10, 40) + + def test_within_range_tolerates_float_noise(self): + assert recut.within_range([_seg(9.98, 40.02)], 10, 40) + + def test_rebase_segments_clamps_to_file_bounds(self): + rebased = recut.rebase_segments([_seg(9.98, 40.02)], 10, 40) + assert rebased == [_seg(0.0, 30.0)] + + def test_rebase_segments_shifts_by_range_start(self): + rebased = recut.rebase_segments([_seg(15, 25), _seg(30, 35)], 10) + assert rebased == [_seg(5.0, 15.0), _seg(20.0, 25.0)] + + +class TestTranscriptWords: + def test_flattens_and_sorts(self): + transcript = { + "segments": [ + {"words": [{"word": "b", "start": 5.0, "end": 5.5}]}, + {"words": [{"word": "a", "start": 1.0, "end": 1.5}]}, + ], + } + words = recut.transcript_words(transcript) + assert [w["w"] for w in words] == ["a", "b"] + + def test_survives_missing_and_broken_words(self): + transcript = { + "segments": [ + {"words": None}, + {}, + {"words": [{"word": "ok", "start": "1", "end": 2}, + {"word": "bad", "start": None, "end": 2}]}, + ], + } + words = recut.transcript_words(transcript) + assert [w["w"] for w in words] == ["ok"] + + def test_empty_transcript(self): + assert recut.transcript_words(None) == [] + assert recut.transcript_words({}) == [] + + +class TestVirtualTranscript: + def test_two_segments_remap_onto_clip_timeline(self): + v = recut.virtual_transcript(TRANSCRIPT, [_seg(10, 15), _seg(48, 52)]) + assert v["language"] == "en" + assert len(v["segments"]) == 2 + # "hello" (12.0-12.5 in source) → 2.0-2.5 on the clip. + first = v["segments"][0] + assert first["words"] == [{"word": "hello", "start": 2.0, "end": 2.5}] + assert (first["start"], first["end"]) == (0.0, 5.0) + # "again" (50.0-50.5) → second segment starts at offset 5.0 → 7.0-7.5. + second = v["segments"][1] + assert second["words"] == [{"word": "again", "start": 7.0, "end": 7.5}] + assert (second["start"], second["end"]) == (5.0, 9.0) + + def test_partial_overlap_is_clamped_to_the_segment(self): + # Word 12.0-12.5, segment 12.3-20 → starts at 0, ends at 0.2. + v = recut.virtual_transcript(TRANSCRIPT, [_seg(12.3, 20)]) + word = v["segments"][0]["words"][0] + assert word["word"] == "hello" + assert word["start"] == 0.0 + assert word["end"] == 0.2 + + def test_words_outside_every_segment_are_dropped(self): + v = recut.virtual_transcript(TRANSCRIPT, [_seg(30, 40)]) + assert v["segments"][0]["words"] == [] + assert v["segments"][0]["text"] == "" + + +class TestSnapSegments: + def test_snaps_onto_word_boundaries(self): + # 11.8 is near "hello"'s start (12.0); 20.6 near "world"'s end (20.4). + snapped = recut.snap_segments([_seg(11.8, 20.6)], TRANSCRIPT, 60.0) + start, end = snapped[0]["start"], snapped[0]["end"] + assert 11.5 <= start <= 12.0 + assert 20.4 <= end <= 20.9 + + def test_no_words_returns_input(self): + segs = [_seg(1, 5)] + assert recut.snap_segments(segs, {"segments": []}, 60.0) is segs + + +class TestFfmpegCommands: + @pytest.fixture(autouse=True) + def _stable_encode_args(self, monkeypatch): + monkeypatch.setattr(recut, "video_encode_args", lambda tier: ["-c:v", "test"]) + monkeypatch.setattr(recut, "audio_encode_args", lambda: ["-c:a", "test"]) + + def test_cut_commands_shape(self): + commands = recut.cut_commands("in.mp4", [_seg(10, 20), _seg(30, 35)], + ["p0.mp4", "p1.mp4"]) + assert commands[0] == ["ffmpeg", "-y", "-ss", "10", "-to", "20", + "-i", "in.mp4", "-c:v", "test", "-c:a", "test", + "p0.mp4"] + assert commands[1][3] == "30" and commands[1][-1] == "p1.mp4" + + def test_concat_command_stream_copies(self): + cmd = recut.concat_command("list.txt", "out.mp4") + assert "-c" in cmd and cmd[cmd.index("-c") + 1] == "copy" + + def test_single_segment_cuts_straight_to_output(self, tmp_path): + ran = [] + recut.run_cut_concat("in.mp4", [_seg(10, 20)], + str(tmp_path / "out.mp4"), str(tmp_path), + runner=ran.append) + assert len(ran) == 1 + assert ran[0][-1] == str(tmp_path / "out.mp4") + + def test_multi_segment_concats_and_cleans_parts(self, tmp_path): + ran = [] + + def fake_run(cmd): + ran.append(cmd) + with open(cmd[-1], "wb") as f: + f.write(b"x") + + out = str(tmp_path / "out.mp4") + recut.run_cut_concat("in.mp4", [_seg(10, 20), _seg(30, 35)], out, + str(tmp_path), runner=fake_run) + # Two cuts + one concat, and no part/list files left behind. + assert len(ran) == 3 + assert ran[2][:4] == ["ffmpeg", "-y", "-f", "concat"] + assert os.listdir(tmp_path) == ["out.mp4"] + + +class TestPerformRecut: + @pytest.fixture(autouse=True) + def _stable_encode_args(self, monkeypatch): + monkeypatch.setattr(recut, "video_encode_args", lambda tier: []) + monkeypatch.setattr(recut, "audio_encode_args", lambda: []) + + @staticmethod + def _touching_runner(cmd): + with open(cmd[-1], "wb") as f: + f.write(b"x") + + def test_fast_path_no_reframe_no_captions(self, tmp_path): + served, clean = recut.perform_recut( + input_path="clip.mp4", segments=[_seg(0, 10)], + output_dir=str(tmp_path), clean_name="t_clip_1.mp4", + runner=self._touching_runner) + assert served == clean + assert served.startswith("recut_") and served.endswith("_t_clip_1.mp4") + assert os.path.exists(tmp_path / served) + # The temp work file is gone. + assert all(not f.startswith("temp_") for f in os.listdir(tmp_path)) + + def test_captions_burn_last_and_win_the_served_name(self, tmp_path): + captioned = [] + + def fake_captioner(path, transcript, start, end): + captioned.append((os.path.basename(path), start, end)) + out = os.path.join(os.path.dirname(path), + f"subtitled_1_{os.path.basename(path)}") + with open(out, "wb") as f: + f.write(b"x") + return out + + v_transcript = {"segments": [{"words": [{"word": "a", "start": 0, "end": 1}]}]} + served, clean = recut.perform_recut( + input_path="clip.mp4", segments=[_seg(0, 10)], + output_dir=str(tmp_path), clean_name="t_clip_1.mp4", + captions_transcript=v_transcript, + runner=self._touching_runner, captioner=fake_captioner) + assert served == f"subtitled_1_{clean}" + # Captioned over the CLEAN recut, with the clip-relative window. + assert captioned == [(clean, 0.0, 10.0)] + # Both files remain: clean for re-styling, captioned for serving. + assert os.path.exists(tmp_path / clean) + assert os.path.exists(tmp_path / served) + + def test_source_path_reframes_and_watermarks(self, tmp_path): + events = [] + + def fake_renderer(work, out, output_format): + events.append(("reframe", output_format)) + with open(out, "wb") as f: + f.write(b"x") + return True + + served, clean = recut.perform_recut( + input_path="source.mp4", segments=[_seg(5, 15)], + output_dir=str(tmp_path), clean_name="t_clip_1.mp4", + reframe=True, output_format="vertical", watermark=True, + runner=self._touching_runner, renderer=fake_renderer, + watermarker=lambda path: events.append(("watermark",))) + assert events == [("reframe", "vertical"), ("watermark",)] + assert served == clean + + def test_renderer_failure_raises_and_cleans_up(self, tmp_path): + with pytest.raises(RuntimeError): + recut.perform_recut( + input_path="source.mp4", segments=[_seg(5, 15)], + output_dir=str(tmp_path), clean_name="t_clip_1.mp4", + reframe=True, runner=self._touching_runner, + renderer=lambda *a: False) + assert all(not f.startswith("temp_") for f in os.listdir(tmp_path)) diff --git a/tests/test_rerender_endpoint.py b/tests/test_rerender_endpoint.py new file mode 100644 index 0000000..517c6de --- /dev/null +++ b/tests/test_rerender_endpoint.py @@ -0,0 +1,258 @@ +"""HTTP tests for the clip editor's backend: GET .../edl and POST /api/clip/rerender. + +Same conventions as test_mcp_endpoint.py: a real ASGI round-trip against the +imported app (BILLING_ENABLED=0 via conftest, so the self-host branch runs and +no cloud auth or database is involved), with the actual render work stubbed at +the recut.perform_recut seam — these tests own the ENDPOINT contract: request +validation, fast/source path choice, 409 on a gone source, and the persistence +of the recipe into metadata.json and the in-memory job. +""" + +import asyncio +import json +import os + +import httpx +import pytest + +app_module = pytest.importorskip("app") +import recut # noqa: E402 + +JOB_ID = "recut-endpoint-test-job" + +TRANSCRIPT = { + "language": "en", + "segments": [ + { + "start": 0.0, "end": 60.0, "text": "hello world again", + "words": [ + {"word": "hello", "start": 12.0, "end": 12.5}, + {"word": "world", "start": 20.0, "end": 20.4}, + {"word": "again", "start": 50.0, "end": 50.5}, + ], + }, + ], +} + + +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): + """A completed job on disk + in memory: canonical clip, metadata with + transcript, and a retained source video in the job dir (URL-job style).""" + 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): + """Stub the render seam; records kwargs and materializes the output file.""" + 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 TestGetEdl: + def test_synthesizes_recipe_for_pristine_clip(self, job): + resp = _request("GET", f"/api/clip/{JOB_ID}/0/edl") + assert resp.status_code == 200 + data = resp.json() + assert data["segments"] == [{"start": 10.0, "end": 40.0}] + assert data["canonical_range"] == {"start": 10.0, "end": 40.0} + assert data["duration"] == 30.0 + assert data["current_file"] == "mytitle_clip_1.mp4" + assert data["has_captions"] is False + assert data["source"]["available"] is True + assert data["source"]["url"] == f"/api/source/{JOB_ID}" + # All three transcript words sit within the ±context window. + assert [w["w"] for w in data["words"]] == ["hello", "world", "again"] + assert data["limits"]["max_segments"] == recut.MAX_SEGMENTS + # Self-host meters nothing. + assert data["rerender_minutes"] == 0 + + def test_reports_missing_source(self, job): + os.remove(job["dir"] / "src.mp4") + data = _request("GET", f"/api/clip/{JOB_ID}/0/edl").json() + assert data["source"]["available"] is False + assert data["source"]["url"] is None + assert data["source"]["duration_estimated"] is True + + def test_404s(self, job): + assert _request("GET", "/api/clip/nope/0/edl").status_code == 404 + assert _request("GET", f"/api/clip/{JOB_ID}/7/edl").status_code == 404 + + +class TestRerenderValidation: + def test_unknown_job_404(self, job, fake_recut): + resp = _request("POST", "/api/clip/rerender", { + "job_id": "nope", "clip_index": 0, + "segments": [{"start": 10, "end": 20}]}) + assert resp.status_code == 404 + + def test_clip_index_out_of_range_404(self, job, fake_recut): + resp = _request("POST", "/api/clip/rerender", { + "job_id": JOB_ID, "clip_index": 5, + "segments": [{"start": 10, "end": 20}]}) + assert resp.status_code == 404 + + def test_invalid_segments_400(self, job, fake_recut): + for segments in ([], [{"start": 15, "end": 15.1}]): + resp = _request("POST", "/api/clip/rerender", { + "job_id": JOB_ID, "clip_index": 0, "segments": segments}) + assert resp.status_code == 400, segments + assert fake_recut == [] + + def test_gone_source_with_outside_segment_409(self, job, fake_recut): + os.remove(job["dir"] / "src.mp4") + resp = _request("POST", "/api/clip/rerender", { + "job_id": JOB_ID, "clip_index": 0, + "segments": [{"start": 45, "end": 55}]}) + assert resp.status_code == 409 + assert fake_recut == [] + + +class TestRerenderPaths: + def test_fast_path_cuts_from_canonical_clip(self, job, fake_recut): + resp = _request("POST", "/api/clip/rerender", { + "job_id": JOB_ID, "clip_index": 0, + "segments": [{"start": 12, "end": 22}, {"start": 30, "end": 35}]}) + assert resp.status_code == 200 + data = resp.json() + assert data["render_path"] == "fast" + assert data["new_video_url"] == f"/videos/{JOB_ID}/recut_1_mytitle_clip_1.mp4" + assert data["duration"] == 15.0 + + call = fake_recut[0] + assert call["input_path"].endswith("mytitle_clip_1.mp4") + assert call["reframe"] is False + # Segments arrive rebased onto the canonical file (t=0 is source 10s). + assert call["segments"] == [{"start": 2.0, "end": 12.0}, + {"start": 20.0, "end": 25.0}] + # Captions re-applied by default, against the clip-relative transcript. + assert call["captions_transcript"]["segments"][0]["words"] + + def test_source_path_reframes_from_retained_source(self, job, fake_recut): + resp = _request("POST", "/api/clip/rerender", { + "job_id": JOB_ID, "clip_index": 0, + "segments": [{"start": 45, "end": 55}]}) + assert resp.status_code == 200 + assert resp.json()["render_path"] == "source" + call = fake_recut[0] + assert call["input_path"].endswith("src.mp4") + assert call["reframe"] is True + assert call["output_format"] == "auto" + assert call["watermark"] is False + # Source-absolute times, not rebased. + assert call["segments"] == [{"start": 45.0, "end": 55.0}] + + def test_reapply_captions_false_skips_the_transcript(self, job, fake_recut): + resp = _request("POST", "/api/clip/rerender", { + "job_id": JOB_ID, "clip_index": 0, "reapply_captions": False, + "segments": [{"start": 12, "end": 22}]}) + assert resp.status_code == 200 + assert fake_recut[0]["captions_transcript"] is None + + +class TestRerenderPersistence: + SEGMENTS = [{"start": 10, "end": 15}, {"start": 48, "end": 52}] + + def _rerender(self): + resp = _request("POST", "/api/clip/rerender", { + "job_id": JOB_ID, "clip_index": 0, "segments": self.SEGMENTS}) + assert resp.status_code == 200 + return resp.json() + + def test_recipe_lands_in_metadata_and_memory(self, job, fake_recut): + data = self._rerender() + expected_segments = [{"start": 10.0, "end": 15.0}, + {"start": 48.0, "end": 52.0}] + assert data["recipe"]["segments"] == expected_segments + assert data["recipe"]["canonical_range"] == {"start": 10.0, "end": 40.0} + # Covering range, so downstream start/end stay a sane positive window. + assert (data["start"], data["end"]) == (10.0, 52.0) + + meta = json.loads(job["meta_path"].read_text()) + stored = meta["shorts"][0] + assert stored["recipe"]["segments"] == expected_segments + assert stored["video_url"] == data["new_video_url"] + mem = app_module.jobs[JOB_ID]["result"]["clips"][0] + assert mem["recipe"]["segments"] == expected_segments + assert mem["video_url"] == data["new_video_url"] + + def test_edl_reflects_the_recut(self, job, fake_recut): + self._rerender() + data = _request("GET", f"/api/clip/{JOB_ID}/0/edl").json() + assert data["segments"] == [{"start": 10.0, "end": 15.0}, + {"start": 48.0, "end": 52.0}] + # The canonical range survives, so the fast path stays available. + assert data["canonical_range"] == {"start": 10.0, "end": 40.0} + + def test_transcript_endpoint_remaps_piecewise(self, job, fake_recut): + self._rerender() + data = _request("GET", f"/api/clip/{JOB_ID}/0/transcript").json() + assert data["durationSec"] == 9.0 + by_text = {c["text"]: c for c in data["captions"]} + # "hello" (12.0s in source) → 2.0s into the clip. + assert by_text["hello"]["startMs"] == 2000 + # "again" (50.0s) sits in the second segment → 5.0 + 2.0 = 7.0s. + assert by_text["again"]["startMs"] == 7000 + # "world" (20.0s) was cut out. + assert "world" not in by_text + + +class TestMcpTool: + def test_recut_clip_is_registered(self): + import mcp_server + names = [t["name"] for t in mcp_server.TOOLS] + assert "recut_clip" in names + assert "recut_clip" in mcp_server._TOOL_IMPLS From b884131639904e577813d270c0ab45a0fe4ee6b6 Mon Sep 17 00:00:00 2001 From: victorcavero14 Date: Wed, 5 Aug 2026 12:03:15 +0200 Subject: [PATCH 2/7] =?UTF-8?q?feat(editor):=20clip=20editor=20frontend=20?= =?UTF-8?q?=E2=80=94=20ClipEditor=20overlay=20wired=20into=20results?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - ClipEditor.jsx: per-clip edit overlay driving the /edl + /rerender backend - App.jsx: editingClip state, handleClipRerendered syncs results, reopened project state and per-clip edit state after a recut (burned layers reset) - ResultCard.jsx: "edit clip" entry button (Scissors), layout tweak - recut.py: write absolute paths in the concat list — the demuxer resolves relative entries against the list file's dir, not the process cwd Co-Authored-By: Claude Fable 5 --- dashboard/src/App.jsx | 44 +- dashboard/src/components/ClipEditor.jsx | 753 ++++++++++++++++++++++++ dashboard/src/components/ResultCard.jsx | 16 +- recut.py | 4 +- 4 files changed, 812 insertions(+), 5 deletions(-) create mode 100644 dashboard/src/components/ClipEditor.jsx diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index 33ffdd7..d0e82bd 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -9,6 +9,7 @@ import ThumbnailStudio from './components/ThumbnailStudio'; import SaaShortsTab from './components/SaaShortsTab'; import UGCGallery from './components/UGCGallery'; import ScheduleWeekModal from './components/ScheduleWeekModal'; +import ClipEditor from './components/ClipEditor'; import UsageMeter from './components/UsageMeter'; import TopUpModal from './components/TopUpModal'; import StarBanner from './components/StarBanner'; @@ -228,6 +229,8 @@ function App() { const [sessionRecovered, setSessionRecovered] = useState(false); const [showScheduleWeek, setShowScheduleWeek] = useState(false); + // Clip editor overlay: index of the clip being edited, or null. + const [editingClip, setEditingClip] = useState(null); // Silent-success "saved" states for the settings key inputs (design.md: no alert popups) const [elevenLabsSaved, setElevenLabsSaved] = useState(false); @@ -280,6 +283,35 @@ function App() { s.timer = setTimeout(flushClipState, 2000); }; + // A recut replaced the clip's server file with a fresh render (burned layers + // reset), so update the results, the reopened-project state and the synced + // per-clip edit state, and let the ResultCard remount from the new file. + const handleClipRerendered = (index, data) => { + const newFile = (data.new_video_url || '').split('/').pop(); + setResults((prev) => { + if (!prev?.clips?.[index]) return prev; + const clips = prev.clips.slice(); + clips[index] = { + ...clips[index], + video_url: data.new_video_url, + start: data.start, + end: data.end, + recipe: data.recipe, + }; + return { ...prev, clips }; + }); + setProjectState((prev) => { + if (!prev?.clips) return prev; + return { + ...prev, + clips: prev.clips.map((c) => (c.index === index + ? { ...c, server_file: newFile, active_layers: null } + : c)), + }; + }); + handleClipStateChange(index, { activeLayers: null, serverVideoFile: newFile }); + }; + // Reopen an archived project from the History tab: the backend re-downloads // its files from R2 into the server's working dir and returns the full state. const restoreProject = async (projectJobId) => { @@ -1402,10 +1434,11 @@ function App() {
{results.clips.map((clip, i) => ( setEditingClip(index)} initialState={projectState?.clips?.find((c) => c.index === i) || null} onStateChange={handleClipStateChange} durableUrl={durableClips[i]} @@ -1576,6 +1609,15 @@ function App() { )} + {editingClip !== null && results?.clips?.[editingClip] && ( + setEditingClip(null)} + onRerendered={handleClipRerendered} + /> + )} {showLogin && setShowLogin(false)} />} {showPlanChoice && setShowPlanChoice(false)} />} {showTopUp && ( diff --git a/dashboard/src/components/ClipEditor.jsx b/dashboard/src/components/ClipEditor.jsx new file mode 100644 index 0000000..1fa057b --- /dev/null +++ b/dashboard/src/components/ClipEditor.jsx @@ -0,0 +1,753 @@ +import React, { useState, useEffect, useReducer, useRef, useCallback, useMemo } from 'react'; +import { + X, Loader2, Plus, Trash2, ChevronUp, ChevronDown, Scissors, + AlertCircle, Undo2, Redo2, Film, +} from 'lucide-react'; +import { getApiUrl } from '../config'; +import { apiFetch, apiJson, QuotaError } from '../lib/api'; + +// Full-screen clip editor: shows WHICH source segments a clip was cut from, +// lets the user trim/extend/split/reorder them (word-snapped), and re-renders +// through POST /api/clip/rerender. The recipe (EDL) comes from GET .../edl. + +const MIN_SEGMENT_SECONDS = 0.5; +const SNAP_WINDOW_SECONDS = 0.35; +const WORD_CONTEXT_SECONDS = 15; + +const SEGMENT_COLORS = [ + 'oklch(76% .17 50)', // brass + 'oklch(70% .12 200)', + 'oklch(72% .13 140)', + 'oklch(70% .14 300)', + 'oklch(74% .13 90)', + 'oklch(68% .13 250)', +]; + +function fmt(t) { + if (!Number.isFinite(t)) return '–:––'; + const m = Math.floor(t / 60); + const s = t - m * 60; + return `${m}:${s.toFixed(1).padStart(4, '0')}`; +} + +function totalOf(segments) { + return segments.reduce((acc, s) => acc + (s.end - s.start), 0); +} + +function editorReducer(state, action) { + switch (action.type) { + case 'init': + return { segments: action.segments, selected: 0, past: [], future: [], pendingBase: null }; + case 'select': + return { ...state, selected: action.index }; + // Live drag feedback: replaces segments without touching history; the + // pre-drag snapshot is kept so the whole drag undoes as ONE step. + case 'preview': + return { ...state, segments: action.segments, pendingBase: state.pendingBase || state.segments }; + case 'commit': { + const base = state.pendingBase || state.segments; + return { + ...state, + segments: action.segments, + selected: Math.min(action.select ?? state.selected, action.segments.length - 1), + past: [...state.past, base], + future: [], + pendingBase: null, + }; + } + case 'undo': { + if (!state.past.length) return state; + const prev = state.past[state.past.length - 1]; + return { + ...state, + segments: prev, + selected: Math.min(state.selected, prev.length - 1), + past: state.past.slice(0, -1), + future: [state.segments, ...state.future], + pendingBase: null, + }; + } + case 'redo': { + if (!state.future.length) return state; + const next = state.future[0]; + return { + ...state, + segments: next, + selected: Math.min(state.selected, next.length - 1), + past: [...state.past, state.segments], + future: state.future.slice(1), + pendingBase: null, + }; + } + default: + return state; + } +} + +export default function ClipEditor({ jobId, clipIndex, clipTitle, onClose, onRerendered }) { + const [edl, setEdl] = useState(null); + const [loadError, setLoadError] = useState(null); + const [state, dispatch] = useReducer(editorReducer, { segments: [], selected: 0, past: [], future: [], pendingBase: null }); + const { segments, selected } = state; + + const [snapToWords, setSnapToWords] = useState(true); + const [reapplyCaptions, setReapplyCaptions] = useState(true); + // The recipe of the currently RENDERED preview (playhead maps onto it). + const [renderedSegments, setRenderedSegments] = useState(null); + const [previewUrl, setPreviewUrl] = useState(null); + const [rendering, setRendering] = useState(false); + const [renderSeconds, setRenderSeconds] = useState(0); + const [renderError, setRenderError] = useState(null); + const [confirmClose, setConfirmClose] = useState(false); + const [selectedWord, setSelectedWord] = useState(null); + const [playhead, setPlayhead] = useState(0); + const [showSource, setShowSource] = useState(false); + + const videoRef = useRef(null); + const sourceRef = useRef(null); + const clipTrackRef = useRef(null); + const sourceTrackRef = useRef(null); + const dragRef = useRef(null); + const [ghost, setGhost] = useState(null); // in-progress new segment on the source track + + // ---- load the EDL ------------------------------------------------------- + useEffect(() => { + let cancelled = false; + (async () => { + try { + const data = await apiJson(`/api/clip/${jobId}/${clipIndex}/edl`); + if (cancelled) return; + setEdl(data); + dispatch({ type: 'init', segments: data.segments.map((s) => ({ ...s })) }); + setRenderedSegments(data.segments.map((s) => ({ ...s }))); + setReapplyCaptions(true); + setPreviewUrl(getApiUrl(`/videos/${jobId}/${data.current_file}`)); + } catch (e) { + if (!cancelled) setLoadError(e.detail || e.message || 'could not load the clip recipe'); + } + })(); + return () => { cancelled = true; }; + }, [jobId, clipIndex]); + + const words = useMemo(() => (edl?.words || []), [edl]); + const sourceAvailable = !!edl?.source?.available; + const sourceDuration = edl?.source?.duration || 0; + const canonical = edl?.canonical_range || { start: 0, end: 0 }; + const limits = edl?.limits || { max_segments: 12, min_segment_seconds: MIN_SEGMENT_SECONDS, max_total_seconds: 180 }; + const minSeg = limits.min_segment_seconds || MIN_SEGMENT_SECONDS; + + const total = totalOf(segments); + const dirty = useMemo(() => { + if (!renderedSegments) return false; + return JSON.stringify(segments) !== JSON.stringify(renderedSegments); + }, [segments, renderedSegments]); + + // Trim bounds: with the source gone, cuts must stay inside the range the + // canonical file was rendered from. + const bounds = sourceAvailable + ? { lo: 0, hi: sourceDuration || Infinity } + : { lo: canonical.start, hi: canonical.end }; + + const outOfRange = useCallback( + (seg) => !sourceAvailable && (seg.start < canonical.start - 0.05 || seg.end > canonical.end + 0.05), + [sourceAvailable, canonical], + ); + const needsSourcePath = segments.some((s) => s.start < canonical.start - 0.05 || s.end > canonical.end + 0.05); + const invalidSegments = segments.some(outOfRange); + const overCaps = segments.length > limits.max_segments || total > limits.max_total_seconds; + const canRender = !rendering && segments.length > 0 && !invalidSegments && !overCaps + && segments.every((s) => s.end - s.start >= minSeg); + + // ---- helpers ------------------------------------------------------------ + const snapEdge = useCallback((t, kind) => { + if (!snapToWords || !words.length) return t; + let best = null; + for (const w of words) { + const c = kind === 'start' ? w.s : w.e; + if (Math.abs(c - t) <= SNAP_WINDOW_SECONDS && (best === null || Math.abs(c - t) < Math.abs(best - t))) best = c; + } + return best ?? t; + }, [snapToWords, words]); + + const clampSeg = useCallback((seg) => ({ + start: Math.max(bounds.lo, Math.min(seg.start, seg.end - minSeg)), + end: Math.min(bounds.hi, Math.max(seg.end, seg.start + minSeg)), + }), [bounds.lo, bounds.hi, minSeg]); + + const setSegment = (index, next, { snap = true } = {}) => { + const updated = segments.map((s, i) => { + if (i !== index) return s; + const seg = { ...s, ...next }; + if (snap) { + if (next.start !== undefined) seg.start = snapEdge(seg.start, 'start'); + if (next.end !== undefined) seg.end = snapEdge(seg.end, 'end'); + } + return clampSeg(seg); + }); + dispatch({ type: 'commit', segments: updated, select: index }); + }; + + const addSegment = () => { + if (segments.length >= limits.max_segments) return; + const last = segments[segments.length - 1]; + let start = last ? last.end : bounds.lo; + let end = start + 10; + if (end > bounds.hi) { end = bounds.hi; start = Math.max(bounds.lo, end - 10); } + if (end - start < minSeg) return; + dispatch({ type: 'commit', segments: [...segments, { start: Math.round(start * 1000) / 1000, end: Math.round(end * 1000) / 1000 }], select: segments.length }); + }; + + const deleteSegment = (index) => { + if (segments.length <= 1) return; + dispatch({ type: 'commit', segments: segments.filter((_, i) => i !== index), select: Math.max(0, index - 1) }); + }; + + const moveSegment = (index, dir) => { + const j = index + dir; + if (j < 0 || j >= segments.length) return; + const next = segments.slice(); + [next[index], next[j]] = [next[j], next[index]]; + dispatch({ type: 'commit', segments: next, select: j }); + }; + + const splitSegment = (index) => { + if (segments.length >= limits.max_segments) return; + const seg = segments[index]; + if (seg.end - seg.start < minSeg * 2) return; + let at = seg.start + (seg.end - seg.start) / 2; + // Prefer the playhead when it currently maps inside this segment. + if (!dirty && renderedSegments) { + let offset = 0; + for (let i = 0; i < renderedSegments.length; i += 1) { + const r = renderedSegments[i]; + const len = r.end - r.start; + if (i === index && playhead > offset + minSeg && playhead < offset + len - minSeg) { + at = r.start + (playhead - offset); + } + offset += len; + } + } + at = snapEdge(at, 'end'); + if (at - seg.start < minSeg || seg.end - at < minSeg) at = seg.start + (seg.end - seg.start) / 2; + const next = segments.flatMap((s, i) => (i === index + ? [{ start: s.start, end: Math.round(at * 1000) / 1000 }, { start: Math.round(at * 1000) / 1000, end: s.end }] + : [s])); + dispatch({ type: 'commit', segments: next, select: index }); + }; + + // ---- drag: trim handles on the clip track ------------------------------- + const onDragMove = useCallback((e) => { + const d = dragRef.current; + if (!d) return; + const dt = (e.clientX - d.startX) / d.pxPerSec; + const seg = { ...d.base[d.idx] }; + if (d.edge === 'start') seg.start = Math.max(d.lo, Math.min(seg.start + dt, seg.end - d.minSeg)); + else seg.end = Math.min(d.hi, Math.max(seg.end + dt, seg.start + d.minSeg)); + const next = d.base.map((s, i) => (i === d.idx ? seg : s)); + d.last = { seg, next }; + dispatch({ type: 'preview', segments: next }); + }, []); + + const onDragUp = useCallback(() => { + const d = dragRef.current; + dragRef.current = null; + window.removeEventListener('pointermove', onDragMove); + window.removeEventListener('pointerup', onDragUp); + if (!d || !d.last) return; + const { seg, next } = d.last; + const snapped = { ...seg }; + if (d.edge === 'start') snapped.start = Math.max(d.lo, Math.min(d.snap(seg.start, 'start'), seg.end - d.minSeg)); + else snapped.end = Math.min(d.hi, Math.max(d.snap(seg.end, 'end'), seg.start + d.minSeg)); + dispatch({ type: 'commit', segments: next.map((s, i) => (i === d.idx ? snapped : s)), select: d.idx }); + }, [onDragMove]); + + const startTrimDrag = (e, idx, edge, trackEl, secondsOnTrack) => { + e.preventDefault(); + e.stopPropagation(); + const rect = trackEl?.getBoundingClientRect(); + if (!rect || !secondsOnTrack) return; + dragRef.current = { + idx, edge, startX: e.clientX, pxPerSec: rect.width / secondsOnTrack, + base: segments.map((s) => ({ ...s })), last: null, + lo: bounds.lo, hi: bounds.hi, minSeg, snap: snapEdge, + }; + dispatch({ type: 'select', index: idx }); + window.addEventListener('pointermove', onDragMove); + window.addEventListener('pointerup', onDragUp); + }; + + // ---- drag: paint a NEW segment on the source track ---------------------- + const onGhostMove = useCallback((e) => { + const d = dragRef.current; + if (!d || d.kind !== 'ghost') return; + const t = Math.max(0, Math.min(d.duration, d.t0 + (e.clientX - d.startX) / d.pxPerSec)); + d.range = { start: Math.min(d.t0, t), end: Math.max(d.t0, t) }; + setGhost({ ...d.range }); + }, []); + + const onGhostUp = useCallback(() => { + const d = dragRef.current; + dragRef.current = null; + window.removeEventListener('pointermove', onGhostMove); + window.removeEventListener('pointerup', onGhostUp); + setGhost(null); + if (!d || !d.range) return; + const seg = { + start: Math.round(d.snap(d.range.start, 'start') * 1000) / 1000, + end: Math.round(d.snap(d.range.end, 'end') * 1000) / 1000, + }; + if (seg.end - seg.start < d.minSeg || d.count >= d.maxSegments) return; + d.commit(seg); + }, [onGhostMove]); + + const startGhostDrag = (e) => { + if (!sourceAvailable || !sourceDuration || segments.length >= limits.max_segments) return; + const rect = sourceTrackRef.current?.getBoundingClientRect(); + if (!rect) return; + const t0 = ((e.clientX - rect.left) / rect.width) * sourceDuration; + dragRef.current = { + kind: 'ghost', startX: e.clientX, pxPerSec: rect.width / sourceDuration, + t0, duration: sourceDuration, range: null, snap: snapEdge, minSeg, + count: segments.length, maxSegments: limits.max_segments, + commit: (seg) => dispatch({ type: 'commit', segments: [...segments, seg], select: segments.length }), + }; + window.addEventListener('pointermove', onGhostMove); + window.addEventListener('pointerup', onGhostUp); + }; + + // ---- keyboard ----------------------------------------------------------- + useEffect(() => { + const onKey = (e) => { + const tag = (e.target?.tagName || '').toLowerCase(); + const typing = tag === 'input' || tag === 'textarea' || tag === 'select'; + if (e.key === 'Escape') { + e.preventDefault(); + if (dirty) setConfirmClose(true); else onClose(); + return; + } + if (typing) return; + if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'z') { + e.preventDefault(); + dispatch({ type: e.shiftKey ? 'redo' : 'undo' }); + } else if (e.key === ' ') { + e.preventDefault(); + const v = videoRef.current; + if (v) { if (v.paused) v.play().catch(() => {}); else v.pause(); } + } else if (e.key === 'Backspace' || e.key === 'Delete') { + e.preventDefault(); + deleteSegment(selected); + } else if (e.key.toLowerCase() === 's') { + e.preventDefault(); + splitSegment(selected); + } + }; + window.addEventListener('keydown', onKey); + return () => window.removeEventListener('keydown', onKey); + }); + + // ---- re-render ---------------------------------------------------------- + useEffect(() => { + if (!rendering) return undefined; + setRenderSeconds(0); + const t = setInterval(() => setRenderSeconds((s) => s + 1), 1000); + return () => clearInterval(t); + }, [rendering]); + + const doRender = async () => { + if (!canRender) return; + setRendering(true); + setRenderError(null); + try { + const res = await apiFetch('/api/clip/rerender', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + job_id: jobId, + clip_index: clipIndex, + segments: segments.map((s) => ({ start: s.start, end: s.end })), + snap_to_words: false, // boundaries are already word-snapped client-side + reapply_captions: reapplyCaptions, + }), + }); + if (!res.ok) { + let detail = `re-render failed (HTTP ${res.status})`; + try { detail = (await res.json()).detail || detail; } catch { /* keep fallback */ } + throw new Error(detail); + } + const data = await res.json(); + setRenderedSegments(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()}`); + onRerendered?.(clipIndex, data); + } catch (e) { + if (e instanceof QuotaError) { + setRenderError(`not enough minutes left (needs ${e.minutesRequired ?? '?'}, ${e.minutesRemaining ?? 0} remaining)`); + } else { + setRenderError(e.message || 're-render failed'); + } + } finally { + setRendering(false); + } + }; + + // ---- transcript panel data --------------------------------------------- + const selectedSeg = segments[selected] || null; + const panelWords = useMemo(() => { + if (!selectedSeg) return []; + const lo = selectedSeg.start - WORD_CONTEXT_SECONDS; + const hi = selectedSeg.end + WORD_CONTEXT_SECONDS; + return words.filter((w) => w.e >= lo && w.s <= hi); + }, [words, selectedSeg]); + + // ---- render ------------------------------------------------------------- + if (loadError) { + return ( +
+
e.stopPropagation()}> +

EDITOR · CLIP {clipIndex + 1}

+
{loadError}
+ +
+
+ ); + } + + if (!edl) { + return ( +
+
+ loading clip recipe… +
+
+ ); + } + + const clipTrackSeconds = Math.max(total, 0.001); + let runningOffset = 0; + const blocks = segments.map((s, i) => { + const left = (runningOffset / clipTrackSeconds) * 100; + const width = ((s.end - s.start) / clipTrackSeconds) * 100; + runningOffset += s.end - s.start; + return { seg: s, i, left, width }; + }); + const renderedTotal = renderedSegments ? totalOf(renderedSegments) : 0; + + return ( +
+ {/* header */} +
+
+

EDITOR · CLIP {clipIndex + 1}

+

edit clip

+ {clipTitle &&

{clipTitle}

} +
+
+
+

DURATION · {fmt(total)}

+

+ {needsSourcePath ? 'PATH · FULL RE-FRAME' : 'PATH · FAST RECUT'} + {edl.rerender_minutes > 0 && ` · ≈${Math.max(1, Math.ceil(total / 60))} MIN`} +

+
+ {confirmClose ? ( +
+ discard changes? + + +
+ ) : ( + + )} +
+
+ + {/* main */} +
+ {/* preview */} +
+
+
+
+ + {/* rail */} +
+
+ {/* segments */} +
+
+

Segments · {segments.length}/{limits.max_segments}

+
+ + +
+
+
+ {segments.map((seg, i) => ( +
dispatch({ type: 'select', index: i })} + className={`rounded-input border p-2.5 cursor-pointer transition-colors ${i === selected ? 'border-[color:var(--color-accent)] bg-paper3' : 'border-rule hover:bg-paper3'} ${outOfRange(seg) ? 'border-[color:var(--color-danger)]' : ''}`} + > +
+ + #{i + 1} + e.stopPropagation()} + onChange={(e) => setSegment(i, { start: parseFloat(e.target.value) || 0 }, { snap: false })} + className="input-field w-20 py-1 px-1.5 text-xs text-center" + aria-label={`segment ${i + 1} start`} + /> + → + e.stopPropagation()} + onChange={(e) => setSegment(i, { end: parseFloat(e.target.value) || 0 }, { snap: false })} + className="input-field w-20 py-1 px-1.5 text-xs text-center" + aria-label={`segment ${i + 1} end`} + /> + {fmt(seg.end - seg.start)} +
+
+ + + + +
+ {outOfRange(seg) && ( +

outside the original range — the source video is gone

+ )} +
+ ))} +
+ +
+ + {/* toggles */} +
+ + +
+ + {/* source monitor */} + {sourceAvailable && ( +
+ + {showSource && ( +
+
+ )} +
+ )} + + {/* transcript */} +
+

Transcript · segment #{selected + 1}

+ {panelWords.length === 0 ? ( +

no words near this segment

+ ) : ( +
+ {panelWords.map((w, i) => { + const inside = selectedSeg && w.e > selectedSeg.start && w.s < selectedSeg.end; + const isSel = selectedWord && selectedWord.s === w.s && selectedWord.e === w.e; + return ( + + ); + })} +
+ )} + {selectedWord && selectedSeg && ( +
+ “{selectedWord.w}” · {fmt(selectedWord.s)} + + +
+ )} +
+
+ + {/* footer actions */} +
+ {renderError && ( +
+ {renderError} +
+ )} + {overCaps && ( +

+ {total > limits.max_total_seconds ? `clip is over ${Math.round(limits.max_total_seconds)}s` : `more than ${limits.max_segments} segments`} +

+ )} +
+ + +
+
+
+
+ + {/* timeline */} +
+ {/* clip track */} +
+
+

CLIP · {fmt(total)}

+

SPACE PLAY · S SPLIT · ⌫ DELETE · ⌘Z UNDO

+
+
+ {blocks.map(({ seg, i, left, width }) => ( +
dispatch({ type: 'select', index: i })} + className={`absolute top-1 bottom-1 rounded-[6px] border ${i === selected ? 'border-[color:var(--color-accent)]' : 'border-transparent'} ${outOfRange(seg) ? 'border-[color:var(--color-danger)]' : ''}`} + style={{ left: `${left}%`, width: `${width}%`, background: `color-mix(in oklab, ${SEGMENT_COLORS[i % SEGMENT_COLORS.length]} 28%, transparent)` }} + > + + #{i + 1} · {fmt(seg.end - seg.start)} + + {/* trim handles */} +
startTrimDrag(e, i, 'start', clipTrackRef.current, clipTrackSeconds)} + className="absolute left-0 top-0 bottom-0 w-2 cursor-ew-resize rounded-l-[6px]" + style={{ background: SEGMENT_COLORS[i % SEGMENT_COLORS.length] }} + /> +
startTrimDrag(e, i, 'end', clipTrackRef.current, clipTrackSeconds)} + className="absolute right-0 top-0 bottom-0 w-2 cursor-ew-resize rounded-r-[6px]" + style={{ background: SEGMENT_COLORS[i % SEGMENT_COLORS.length] }} + /> +
+ ))} + {/* playhead over the last rendered recipe */} + {!dirty && renderedTotal > 0 && playhead <= renderedTotal && ( +
+ )} +
+
+ + {/* source track */} +
+
+

+ SOURCE · {fmt(sourceDuration)}{edl.source.duration_estimated ? ' (EST.)' : ''} + {!sourceAvailable && ' · EXPIRED — TRIMS LIMITED TO THE ORIGINAL RANGE'} +

+ {sourceAvailable && segments.length < limits.max_segments && ( +

DRAG ON EMPTY SPACE TO ADD A SEGMENT

+ )} +
+
+ {/* canonical range marker */} + {sourceDuration > 0 && ( +
+ )} + {sourceDuration > 0 && segments.map((seg, i) => ( +
{ e.stopPropagation(); dispatch({ type: 'select', index: i }); }} + className={`absolute top-1 bottom-1 rounded-[4px] cursor-pointer ${i === selected ? 'ring-1 ring-[color:var(--color-accent)]' : ''}`} + style={{ + left: `${(seg.start / sourceDuration) * 100}%`, + width: `${Math.max(((seg.end - seg.start) / sourceDuration) * 100, 0.4)}%`, + background: SEGMENT_COLORS[i % SEGMENT_COLORS.length], + }} + title={`#${i + 1} · ${fmt(seg.start)} → ${fmt(seg.end)}`} + /> + ))} + {ghost && sourceDuration > 0 && ( +
+ )} +
+
+ 0:00 + {fmt(sourceDuration / 2)} + {fmt(sourceDuration)} +
+
+
+
+ ); +} diff --git a/dashboard/src/components/ResultCard.jsx b/dashboard/src/components/ResultCard.jsx index 4551c53..0f55816 100644 --- a/dashboard/src/components/ResultCard.jsx +++ b/dashboard/src/components/ResultCard.jsx @@ -1,5 +1,5 @@ import React, { useState, useEffect } from 'react'; -import { Download, Share2, Instagram, Youtube, Video, AlertCircle, Loader2, Copy, Check, Wand2, Type, Calendar, Languages, FileText, Link2 } from 'lucide-react'; +import { Download, Share2, Instagram, Youtube, Video, AlertCircle, Loader2, Copy, Check, Wand2, Type, Calendar, Languages, FileText, Link2, Scissors } from 'lucide-react'; import { getApiUrl } from '../config'; import { apiFetch } from '../lib/api'; import SubtitleModal from './SubtitleModal'; @@ -25,7 +25,7 @@ function formatDuration(clip) { return `${String(Math.floor(secs / 60)).padStart(2, '0')}:${String(secs % 60).padStart(2, '0')}`; } -export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostKey, uploadUserId, geminiApiKey, elevenLabsKey, isManaged, onPlay, onPause, onBulkSubtitle, clipCount = 1, bulkProgress, initialState = null, onStateChange, connectedPlatforms = null, onConnectSocials }) { +export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostKey, uploadUserId, geminiApiKey, elevenLabsKey, isManaged, onPlay, onPause, onBulkSubtitle, clipCount = 1, bulkProgress, initialState = null, onStateChange, connectedPlatforms = null, onConnectSocials, onEditClip = null }) { const [showModal, setShowModal] = useState(false); const [showDescModal, setShowDescModal] = useState(false); const [showSubtitleModal, setShowSubtitleModal] = useState(false); @@ -709,6 +709,16 @@ export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostK {/* Actions Footer */}
+ {onEditClip && ( + + )} + diff --git a/recut.py b/recut.py index e10dbe4..8c7d7c3 100644 --- a/recut.py +++ b/recut.py @@ -217,7 +217,9 @@ def run_cut_concat(input_path, segments, out_path, workdir, runner=None): run(command) with open(list_path, "w") as f: for part in part_paths: - f.write(f"file '{part}'\n") + # Absolute paths: the concat demuxer resolves relative entries + # against the LIST FILE's directory, not the process cwd. + f.write(f"file '{os.path.abspath(part)}'\n") run(concat_command(list_path, out_path)) finally: for path in part_paths + [list_path]: From 18654eabf6132c88b4a3ee8d905fdfe50a67c6aa Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Tue, 18 Aug 2026 15:26:44 +0200 Subject: [PATCH 3/7] fix(editor): harden the recut engine - Add METADATA_SCRUB + '-movflags +faststart' to the cut and concat commands: a fast-path recut IS the delivered file, and without a fronted moov atom the browser preview hangs (same invariant as every other final-artifact producer in the repo). - Unique per-invocation temp names (uuid token) for part/list files and a uuid suffix on the output name: two concurrent recuts in one job dir no longer overwrite or delete each other's intermediates, and same-second saves of one clip no longer collide on the output filename. - 1800s timeout on ffmpeg runs (matching apply_watermark) so a hung render can't pin an executor thread and its quota reservation until restart. --- recut.py | 39 ++++++++++++++++++++++++++++++++------- tests/test_recut.py | 13 +++++++++++++ 2 files changed, 45 insertions(+), 7 deletions(-) diff --git a/recut.py b/recut.py index 8c7d7c3..5b7d730 100644 --- a/recut.py +++ b/recut.py @@ -22,8 +22,10 @@ import os import shutil import subprocess import time +import uuid -from ffmpeg_utils import QUALITY_FAST, audio_encode_args, video_encode_args +from ffmpeg_utils import (METADATA_SCRUB, QUALITY_FAST, audio_encode_args, + video_encode_args) # EDL limits. Deliberately generous — the editor is for humans fixing cuts, # not for stitching feature films. @@ -186,6 +188,12 @@ def cut_commands(input_path, segments, part_paths): "-i", input_path, *video_encode_args(QUALITY_FAST), *audio_encode_args(), + # Every final-artifact producer in the repo scrubs source metadata + # and fronts the moov atom (a fast-path recut IS the delivered + # file, and without +faststart the browser preview hangs). Also on + # intermediate parts: harmless, and it keeps the source's handler + # metadata from ever entering the chain. + *METADATA_SCRUB, "-movflags", "+faststart", part, ]) return commands @@ -196,7 +204,8 @@ def concat_command(list_path, out_path): generation loss on the join.""" return [ "ffmpeg", "-y", "-f", "concat", "-safe", "0", - "-i", list_path, "-c", "copy", out_path, + "-i", list_path, "-c", "copy", + *METADATA_SCRUB, "-movflags", "+faststart", out_path, ] @@ -207,11 +216,14 @@ def run_cut_concat(input_path, segments, out_path, workdir, runner=None): run(cut_commands(input_path, segments, [out_path])[0]) return out_path + # Unique per invocation: two concurrent recuts in the same job dir must + # not overwrite each other's parts (or delete them via the finally below). + token = uuid.uuid4().hex[:8] part_paths = [ - os.path.join(workdir, f"recut_part_{i}.mp4") + os.path.join(workdir, f"temp_recut_part_{token}_{i}.mp4") for i in range(len(segments)) ] - list_path = os.path.join(workdir, "recut_concat.txt") + list_path = os.path.join(workdir, f"temp_recut_concat_{token}.txt") try: for command in cut_commands(input_path, segments, part_paths): run(command) @@ -228,9 +240,19 @@ def run_cut_concat(input_path, segments, out_path, workdir, runner=None): return out_path +# Same ceiling as apply_watermark's: a hung ffmpeg must not pin the executor +# thread (and the caller's quota reservation) until a server restart. +FFMPEG_TIMEOUT_SECONDS = 1800 + + def _run_ffmpeg(command): - result = subprocess.run( - command, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + try: + result = subprocess.run( + command, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, + timeout=FFMPEG_TIMEOUT_SECONDS) + except subprocess.TimeoutExpired: + raise RuntimeError( + f"ffmpeg timed out after {FFMPEG_TIMEOUT_SECONDS}s ({command[1:6]}...)") if result.returncode != 0: tail = (result.stderr or b"").decode("utf-8", "replace")[-400:] raise RuntimeError(f"ffmpeg failed ({command[1:6]}...): {tail}") @@ -257,7 +279,10 @@ def perform_recut(*, input_path, segments, output_dir, clean_name, implementations, imported lazily so this module stays importable without the ML stack; tests inject fakes. """ - out_name = f"recut_{int(time.time())}_{clean_name}" + # The uuid token keeps two same-second saves of one clip from writing (and + # then serving) the same filename; the timestamp keeps "newest derived + # file" resolution working in _canonical_clip_file. + out_name = f"recut_{int(time.time())}_{uuid.uuid4().hex[:6]}_{clean_name}" out_path = os.path.join(output_dir, out_name) work_name = f"temp_{out_name}" work_path = os.path.join(output_dir, work_name) diff --git a/tests/test_recut.py b/tests/test_recut.py index 1a557ba..e19f6a6 100644 --- a/tests/test_recut.py +++ b/tests/test_recut.py @@ -171,6 +171,8 @@ class TestFfmpegCommands: ["p0.mp4", "p1.mp4"]) assert commands[0] == ["ffmpeg", "-y", "-ss", "10", "-to", "20", "-i", "in.mp4", "-c:v", "test", "-c:a", "test", + *recut.METADATA_SCRUB, + "-movflags", "+faststart", "p0.mp4"] assert commands[1][3] == "30" and commands[1][-1] == "p1.mp4" @@ -178,6 +180,17 @@ class TestFfmpegCommands: cmd = recut.concat_command("list.txt", "out.mp4") assert "-c" in cmd and cmd[cmd.index("-c") + 1] == "copy" + def test_final_outputs_carry_faststart_and_scrub(self): + # The delivered-artifact invariants: the moov atom must be fronted + # (browser preview hangs otherwise) and source metadata scrubbed — + # on the concat join AND on the single-segment direct cut, since both + # can be the file the fast path serves. + concat = recut.concat_command("list.txt", "out.mp4") + single = recut.cut_commands("in.mp4", [_seg(10, 20)], ["out.mp4"])[0] + for cmd in (concat, single): + assert "+faststart" in cmd + assert "-map_metadata" in cmd + def test_single_segment_cuts_straight_to_output(self, tmp_path): ran = [] recut.run_cut_concat("in.mp4", [_seg(10, 20)], From e381d21b54310527535e11ef4443fef46089dce0 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Tue, 18 Aug 2026 15:26:45 +0200 Subject: [PATCH 4/7] fix(editor): serialize rerenders per job and re-validate after snapping - Per-job asyncio lock around /api/clip/rerender (same pattern as _restore_locks): concurrent saves raced on the metadata.json read-modify-write, with the last writer silently reverting the other clip's recipe and video_url. - Re-run normalize_segments after snap_to_words + clamp: a segment fully outside the canonical range used to clamp to an inverted (end < start) window that passed within_range and died in ffmpeg as a 500; it is now a clean 400. --- app.py | 20 ++++++++++++++++++++ tests/test_rerender_endpoint.py | 15 +++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/app.py b/app.py index fae8134..8607f13 100644 --- a/app.py +++ b/app.py @@ -2272,6 +2272,11 @@ class RerenderRequest(BaseModel): reapply_captions: bool = True +# One lock per job (same pattern as _restore_locks): rerenders on the same job +# share metadata.json and the canonical files, so they must not interleave. +_rerender_locks: Dict[str, asyncio.Lock] = {} + + @app.post("/api/clip/rerender") async def rerender_clip(req: RerenderRequest, request: Request): """Re-render a clip from an edited EDL (the clip editor's save button). @@ -2291,6 +2296,16 @@ async def rerender_clip(req: RerenderRequest, request: Request): job = jobs[req.job_id] await _assert_job_owner(request, job) + # Serialize rerenders per job: concurrent saves (easy for an MCP agent to + # produce) would otherwise race on the shared metadata.json + # read-modify-write below, with the last writer silently reverting the + # other clip's recipe/video_url. + lock = _rerender_locks.setdefault(req.job_id, asyncio.Lock()) + async with lock: + return await _rerender_locked(req, request, job) + + +async def _rerender_locked(req: RerenderRequest, request: 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: @@ -2327,6 +2342,11 @@ async def rerender_clip(req: RerenderRequest, request: Request): {"start": round(max(s['start'], canonical_range['start']), 3), "end": round(min(s['end'], canonical_range['end']), 3)} for s in segments] + # Re-validate after snapping/clamping: a segment fully outside the + # canonical range clamps to an inverted (end < start) window, and + # snapping can stretch the total past the cap. Without this it + # reaches ffmpeg and dies as a 500 instead of a clean 400. + segments = recut.normalize_segments(segments, source_duration) except recut.RecutError as e: raise HTTPException(status_code=400, detail=str(e)) diff --git a/tests/test_rerender_endpoint.py b/tests/test_rerender_endpoint.py index 517c6de..1445e07 100644 --- a/tests/test_rerender_endpoint.py +++ b/tests/test_rerender_endpoint.py @@ -160,6 +160,21 @@ class TestRerenderValidation: assert resp.status_code == 409 assert fake_recut == [] + def test_snap_clamp_inverted_segment_400_not_500(self, job, fake_recut, + monkeypatch): + # No source + snap_to_words: a segment fully outside the canonical + # range clamps to an inverted (end < start) window. That must be + # rejected as a 400 by the post-snap re-validation, never reach + # ffmpeg as `-ss 150 -to 30` and surface as a 500. + os.remove(job["dir"] / "src.mp4") + monkeypatch.setattr(recut, "snap_segments", + lambda segments, transcript, bound: segments) + resp = _request("POST", "/api/clip/rerender", { + "job_id": JOB_ID, "clip_index": 0, "snap_to_words": True, + "segments": [{"start": 200, "end": 210}]}) + assert resp.status_code == 400 + assert fake_recut == [] + class TestRerenderPaths: def test_fast_path_cuts_from_canonical_clip(self, job, fake_recut): From a0e25828fd4048ee401781c8480cdf0c0f1eb26d Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Tue, 18 Aug 2026 15:26:45 +0200 Subject: [PATCH 5/7] fix(cloud): archive clean canonical clips so restored projects stay editable The clip editor's fast path (and /api/subtitle re-styles) cut from the clean canonical file, but archive_job only uploaded the served derivative, so every project restored from R2 after a redeploy 409'd on rerender even for in-range segments. Archive the clean canonical alongside the served file; restore already downloads everything under the job prefix. The free-retention purge now deletes the whole job prefix so these extra keys (and previously leaked derivatives) can't become orphans. --- cloud/videos.py | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/cloud/videos.py b/cloud/videos.py index 0e27775..9ad3f0b 100644 --- a/cloud/videos.py +++ b/cloud/videos.py @@ -37,6 +37,8 @@ async def archive_job(user_id, job_id, clips, output_dir): except Exception as e: print(f"⚠️ R2 upload failed for {key}: {e}") + base_name = (os.path.basename(meta_files[0]).replace("_metadata.json", "") + if meta_files else None) uploaded = [] # (clip_index, filename, key, title, size_bytes) for i, clip in enumerate(clips): video_url = clip.get("video_url") or "" @@ -54,6 +56,22 @@ async def archive_job(user_id, job_id, clips, output_dir): continue uploaded.append((i, filename, key, _clip_title(clip), os.path.getsize(local_path))) + # Also archive the clean canonical when the served file is a derived + # one (captioned/recut): it is the editable master — the clip editor's + # fast path and /api/subtitle re-styles cut from it, so a project + # restored after a redeploy is only editable if it comes back too. + # Restore downloads every key under the job prefix, so no change is + # needed on that side; the free-retention purge deletes by prefix. + if base_name: + clean = f"{base_name}_clip_{i + 1}.mp4" + clean_path = os.path.join(output_dir, clean) + if clean != filename and os.path.exists(clean_path): + clean_key = storage.job_key(user_id, job_id, clean) + try: + await asyncio.to_thread(storage.upload_file, clean_path, clean_key) + except Exception as e: + print(f"⚠️ R2 upload failed for {clean_key}: {e}") + if not uploaded: return async with database.session() as s: @@ -317,8 +335,17 @@ async def purge_free_expired(): for v in items["videos"]: await asyncio.to_thread(storage.delete_key, v.r2_key) for p in items["projects"]: - if p.metadata_r2_key: - await asyncio.to_thread(storage.delete_key, p.metadata_r2_key) + # Delete everything under the job prefix, not just the metadata + # key: the archive also stores clean canonical clips (which have + # no DB row of their own) and superseded derivatives would + # otherwise leak as orphans. + try: + prefix = storage.job_key(user_id, p.job_id, "") + for key in await asyncio.to_thread(storage.list_keys, prefix): + await asyncio.to_thread(storage.delete_key, key) + except Exception: + if p.metadata_r2_key: + await asyncio.to_thread(storage.delete_key, p.metadata_r2_key) async with database.session() as s: async with s.begin(): if items["videos"]: From d1bf36c6665b2fac3b42ddc066a0cf4cc3a65e7e Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Tue, 18 Aug 2026 15:26:45 +0200 Subject: [PATCH 6/7] fix(dashboard): recut duration display and stale durable URL - A recut clip's start/end are the covering source range, so end - start showed a 20s two-segment clip as minutes long; duration now sums the recipe segments when present. - Drop the clip's durable R2 URL after a rerender: archive_clip_edit deletes the superseded object, so the stale URL would 404 as the playback fallback. --- dashboard/src/App.jsx | 8 ++++++++ dashboard/src/components/ResultCard.jsx | 17 +++++++++++++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index d0e82bd..aa9e4ef 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -309,6 +309,14 @@ function App() { : c)), }; }); + // The old durable R2 object is deleted when the recut is archived, so the + // stale URL would 404 as a fallback; drop it until the next refresh. + setDurableClips((prev) => { + if (!(index in prev)) return prev; + const next = { ...prev }; + delete next[index]; + return next; + }); handleClipStateChange(index, { activeLayers: null, serverVideoFile: newFile }); }; diff --git a/dashboard/src/components/ResultCard.jsx b/dashboard/src/components/ResultCard.jsx index 0f55816..c25bf00 100644 --- a/dashboard/src/components/ResultCard.jsx +++ b/dashboard/src/components/ResultCard.jsx @@ -19,8 +19,18 @@ const PLATFORM_OPTIONS = [ { value: 'youtube', label: 'youtube', icon: }, ]; +function clipDurationSeconds(clip) { + // A recut clip's start/end are the covering source range (segments may be + // non-contiguous or reordered); its real duration is the segment sum. + const segments = clip.recipe?.segments; + if (segments?.length) { + return segments.reduce((acc, s) => acc + (s.end - s.start), 0); + } + return clip.end && clip.start ? clip.end - clip.start : NaN; +} + function formatDuration(clip) { - const secs = clip.end && clip.start ? Math.floor(clip.end - clip.start) : NaN; + const secs = Math.floor(clipDurationSeconds(clip)); if (!Number.isFinite(secs) || secs < 0) return null; return `${String(Math.floor(secs / 60)).padStart(2, '0')}:${String(secs % 60).padStart(2, '0')}`; } @@ -126,7 +136,10 @@ export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostK const [showTranslateModal, setShowTranslateModal] = useState(false); const [editError, setEditError] = useState(null); - const [clipDuration, setClipDuration] = useState(clip.end && clip.start ? clip.end - clip.start : 30); + const [clipDuration, setClipDuration] = useState(() => { + const secs = clipDurationSeconds(clip); + return Number.isFinite(secs) ? secs : 30; + }); // Accumulate Remotion layers across operations. A reopened project restores // the layers persisted in its project state, so the next edit composes over From b81125c572338f3faf9c738200c12023c5740b75 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Tue, 18 Aug 2026 19:21:42 +0200 Subject: [PATCH 7/7] feat(generate): manual clip count and duration controls (discussion #65) /api/process (and the process_video MCP tool) now accept optional target_clips (1-15) and clip_min_seconds / clip_max_seconds (5-180), surfaced in the dashboard as a collapsed 'advanced options' section. Blank means the AI decides, keeping the default request byte-identical. Plumbed through the same env overrides the A/B harness already reads: CLIP_TARGET_MIN/MAX (existing) and a new clip_duration_bounds() in clip_selection.py backing CLIP_MIN_SECONDS/MAX_SECONDS. The detail and visual prompts take the band as template placeholders instead of the hardcoded 15-60, and word-snapping enforces the same bounds. All three knobs are honest targets, not guarantees: the model still returns fewer clips when the material doesn't hold them, and the UI copy says so. Verified live: target_clips=2 + band 8-15s on the demo video returned exactly 2 clips of 13.3s and 13.7s (the uncontrolled run gave one 41.7s clip); out-of-range values 400 with a named reason. --- app.py | 43 ++++++++++++- clip_selection.py | 24 ++++++++ dashboard/src/App.jsx | 12 ++++ dashboard/src/components/MediaInput.jsx | 70 ++++++++++++++++++++- gemini_worker.py | 12 ++-- main.py | 22 ++++++- mcp_server.py | 17 ++++++ tests/test_clip_selection.py | 3 +- tests/test_generation_controls.py | 81 +++++++++++++++++++++++++ 9 files changed, 271 insertions(+), 13 deletions(-) create mode 100644 tests/test_generation_controls.py diff --git a/app.py b/app.py index 8607f13..b03f05e 100644 --- a/app.py +++ b/app.py @@ -1461,7 +1461,10 @@ async def process_endpoint( layouts: Optional[str] = Form(None), force_low_quality: Optional[str] = Form(None), webhook_url: Optional[str] = Form(None), - webhook_secret: Optional[str] = Form(None) + webhook_secret: Optional[str] = Form(None), + target_clips: Optional[str] = Form(None), + clip_min_seconds: Optional[str] = Form(None), + clip_max_seconds: Optional[str] = Form(None) ): api_key = await resolve_gemini(request) if not api_key: @@ -1481,6 +1484,9 @@ async def process_endpoint( layouts = body.get("layouts") webhook_url = body.get("webhook_url") webhook_secret = body.get("webhook_secret") + target_clips = body.get("target_clips") + clip_min_seconds = body.get("clip_min_seconds") + clip_max_seconds = body.get("clip_max_seconds") # Normalize output format (auto = keep pipeline default). if output_format not in ("vertical", "horizontal", "square"): @@ -1559,6 +1565,41 @@ async def process_endpoint( if chosen: print(f"[layouts] job={job_id} enabled={sorted(chosen)}") + # Manual generation controls (discussion #65): optional clip-count target + # and duration band, forwarded to the selection prompts via the same env + # overrides the A/B harness already reads (clip_selection.py). All three + # are honest TARGETS, not guarantees — the model may return fewer clips + # when the material doesn't hold them. Bad values 400 instead of silently + # producing something the user didn't ask for. + def _gen_control(raw, name, lo, hi, integer=False): + if raw in (None, ""): + return None + try: + val = float(raw) + except (TypeError, ValueError): + raise HTTPException(status_code=400, detail=f"{name} must be a number") + if integer and val != int(val): + raise HTTPException(status_code=400, detail=f"{name} must be an integer") + if not (lo <= val <= hi): + raise HTTPException(status_code=400, + detail=f"{name} must be between {lo:g} and {hi:g}") + return int(val) if integer else val + + n_clips = _gen_control(target_clips, "target_clips", 1, 15, integer=True) + min_secs = _gen_control(clip_min_seconds, "clip_min_seconds", 5, 175) + max_secs = _gen_control(clip_max_seconds, "clip_max_seconds", 10, 180) + if min_secs is not None and max_secs is not None and max_secs < min_secs + 5: + raise HTTPException(status_code=400, + detail="clip_max_seconds must be at least 5s above clip_min_seconds") + if n_clips is not None: + env["CLIP_TARGET_MIN"] = env["CLIP_TARGET_MAX"] = str(n_clips) + if min_secs is not None: + env["CLIP_MIN_SECONDS"] = str(min_secs) + if max_secs is not None: + env["CLIP_MAX_SECONDS"] = str(max_secs) + if n_clips is not None or min_secs is not None or max_secs is not None: + print(f"[gen-controls] job={job_id} clips={n_clips} band={min_secs}-{max_secs}") + input_path = None if url: # Keep the downloaded source inside the job dir: the clip editor's diff --git a/clip_selection.py b/clip_selection.py index 03b8c87..b0c4650 100644 --- a/clip_selection.py +++ b/clip_selection.py @@ -67,6 +67,30 @@ def clip_count_targets(n_windows): return low, max(low, high) +def clip_duration_bounds(): + """The clip length band (seconds) the selection prompts and word-snapping + enforce. ``CLIP_MIN_SECONDS`` / ``CLIP_MAX_SECONDS`` override the classic + 15-60 — set per job by /api/process when the user asks for a specific + length, or by hand for A/B runs. Values are clamped to platform-sane + limits and re-ordered so bad input degrades instead of breaking the job. + """ + import os + + def _read(name, default): + try: + return float(os.environ.get(name, "")) + except ValueError: + return default + + lo = _read("CLIP_MIN_SECONDS", 15.0) + hi = _read("CLIP_MAX_SECONDS", 60.0) + lo = min(max(lo, 5.0), 175.0) + hi = min(max(hi, 10.0), 180.0) + if hi < lo + 5.0: # keep a real band: degenerate ranges starve the model + hi = min(180.0, lo + 5.0) + return round(lo, 3), round(hi, 3) + + def compact_words(words, precision=2): """Round word timestamps for prompts — full float precision wastes tokens.""" return [ diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index aa9e4ef..76ef611 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -647,6 +647,14 @@ function App() { // that apiFetch attaches automatically. const headers = apiKey ? { 'X-Gemini-Key': apiKey } : {}; + // Advanced generation controls: only sent when the user set them, so the + // default request stays byte-identical to the pre-feature one. + const advanced = { + target_clips: data.targetClips || null, + clip_min_seconds: data.clipMinSeconds || null, + clip_max_seconds: data.clipMaxSeconds || null, + }; + if (data.type === 'url') { headers['Content-Type'] = 'application/json'; body = JSON.stringify({ @@ -654,12 +662,16 @@ function App() { acknowledged: !!data.acknowledged, output_format: data.outputFormat || 'auto', force_low_quality: forceLowQuality, + ...Object.fromEntries(Object.entries(advanced).filter(([, v]) => v != null)), }); } else { const formData = new FormData(); formData.append('file', data.payload); formData.append('acknowledged', data.acknowledged ? 'true' : 'false'); formData.append('output_format', data.outputFormat || 'auto'); + for (const [k, v] of Object.entries(advanced)) { + if (v != null) formData.append(k, v); + } body = formData; } diff --git a/dashboard/src/components/MediaInput.jsx b/dashboard/src/components/MediaInput.jsx index 41f71fe..743c4fa 100644 --- a/dashboard/src/components/MediaInput.jsx +++ b/dashboard/src/components/MediaInput.jsx @@ -1,5 +1,5 @@ import React, { useState, useEffect, useRef } from 'react'; -import { Link2, Upload, FileVideo, X, Info, Loader2 } from 'lucide-react'; +import { Link2, Upload, FileVideo, X, Info, Loader2, ChevronDown } from 'lucide-react'; import { getApiUrl } from '../config'; const SUPPORTED_PLATFORMS = [ @@ -16,6 +16,12 @@ export default function MediaInput({ onProcess, isProcessing }) { const [acknowledged, setAcknowledged] = useState(false); const [outputFormat, setOutputFormat] = useState('vertical'); // vertical | horizontal | square const [showInfo, setShowInfo] = useState(false); + // Advanced generation controls — empty string means "let the AI decide", + // which keeps the default pipeline behavior untouched. + const [showAdvanced, setShowAdvanced] = useState(false); + const [targetClips, setTargetClips] = useState(''); + const [clipMinSeconds, setClipMinSeconds] = useState(''); + const [clipMaxSeconds, setClipMaxSeconds] = useState(''); const infoRef = useRef(null); // Close the compatibility popover on any outside click. @@ -58,10 +64,15 @@ export default function MediaInput({ onProcess, isProcessing }) { const handleSubmit = (e) => { e.preventDefault(); if (!acknowledged) return; + const advanced = { + targetClips: targetClips || null, + clipMinSeconds: clipMinSeconds || null, + clipMaxSeconds: clipMaxSeconds || null, + }; if (mode === 'url' && url) { - onProcess({ type: 'url', payload: url, acknowledged: true, outputFormat }); + onProcess({ type: 'url', payload: url, acknowledged: true, outputFormat, ...advanced }); } else if (mode === 'file' && file) { - onProcess({ type: 'file', payload: file, acknowledged: true, outputFormat }); + onProcess({ type: 'file', payload: file, acknowledged: true, outputFormat, ...advanced }); } }; @@ -210,6 +221,59 @@ export default function MediaInput({ onProcess, isProcessing }) {
+ {/* Advanced generation controls — collapsed by default; blank = AI decides */} +
+ + {showAdvanced && ( +
+
+

clips to aim for

+ setTargetClips(e.target.value)} + placeholder="auto" + className="input-field" + /> +
+
+

min length (s)

+ setClipMinSeconds(e.target.value)} + placeholder="15" + className="input-field" + /> +
+
+

max length (s)

+ setClipMaxSeconds(e.target.value)} + placeholder="60" + className="input-field" + /> +
+

+ Targets, not guarantees: the AI returns fewer clips when the + material doesn't hold them. Leave blank to let it decide. +

+
+ )} +
+