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