Merge feat/clip-editor: per-clip EDL editor + manual generation controls (PR #62, discussion #65)

This commit is contained in:
juancarlos.cavero 2026-08-18 19:27:49 +02:00
commit 100fa583a1
15 changed files with 2435 additions and 40 deletions

416
app.py
View file

@ -23,6 +23,7 @@ from fastapi.responses import HTMLResponse, FileResponse, JSONResponse
from starlette.background import BackgroundTask from starlette.background import BackgroundTask
from pydantic import BaseModel 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 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() 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 file to serve for clip ``index``, preferring a derived version.
The pipeline writes the clean reframe as ``<base>_clip_<n>.mp4`` and any The pipeline writes the clean reframe as ``<base>_clip_<n>.mp4`` and any
post-processing (auto-captions, and /api/subtitle re-styles) as post-processing (auto-captions, /api/subtitle re-styles, and clip-editor
``subtitled_<ts>_<clean>.mp4``, keeping the original for re-styling. Every recuts) as ``subtitled_<ts>_<clean>.mp4`` / ``recut_<ts>_<clean>.mp4``,
place that rebuilds the canonical name from disk — restore after a restart, keeping the original for re-styling. Every place that rebuilds the
the R2 upload, the download bundle — must therefore resolve to the newest canonical name from disk — restore after a restart, the R2 upload, the
derived file, or clips silently lose their captions on a redeploy. 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" clean = f"{base_name}_clip_{index + 1}.mp4"
try: try:
derived = glob.glob(os.path.join(output_dir, f"subtitled_*_{clean}")) # subtitled_*_{clean} also matches subtitled_<ts>_recut_<ts>_{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: except Exception:
derived = [] derived = []
if not derived: if not derived:
@ -425,6 +431,15 @@ def _reapply_captions(job_id, clip_index, video_path):
return None return None
clip = clips[clip_index] clip = clips[clip_index]
import main as _main 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, return _main.auto_caption_clip(video_path, transcript,
clip['start'], clip['end']) clip['start'], clip['end'])
except Exception as e: except Exception as e:
@ -1434,7 +1449,10 @@ async def process_endpoint(
layouts: Optional[str] = Form(None), layouts: Optional[str] = Form(None),
force_low_quality: Optional[str] = Form(None), force_low_quality: Optional[str] = Form(None),
webhook_url: 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) api_key = await resolve_gemini(request)
if not api_key: if not api_key:
@ -1454,6 +1472,9 @@ async def process_endpoint(
layouts = body.get("layouts") layouts = body.get("layouts")
webhook_url = body.get("webhook_url") webhook_url = body.get("webhook_url")
webhook_secret = body.get("webhook_secret") 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). # Normalize output format (auto = keep pipeline default).
if output_format not in ("vertical", "horizontal", "square"): if output_format not in ("vertical", "horizontal", "square"):
@ -1532,9 +1553,47 @@ async def process_endpoint(
if chosen: if chosen:
print(f"[layouts] job={job_id} enabled={sorted(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 input_path = None
if url: 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: else:
# Save uploaded file with size limit check. # Save uploaded file with size limit check.
# basename() strips any path components from the client-supplied # basename() strips any path components from the client-supplied
@ -1626,21 +1685,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}") @app.get("/api/source/{job_id}")
async def get_source_video(job_id: str): 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, Uploaded sources are blob URLs in the browser and don't survive a reload,
so the recovered session points the preview here instead. Unauthenticated so the recovered session points the preview here instead. Unauthenticated
like the /videos mount — the UUID job_id is the capability. like the /videos mount — the UUID job_id is the capability.
""" """
matches = [ source_path = _locate_source(job_id)
f for f in glob.glob(os.path.join(UPLOAD_DIR, f"{job_id}_*")) if not source_path:
if not os.path.basename(f).startswith("thumb_")
]
if not matches:
raise HTTPException(status_code=404, detail="Source not found") 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") @app.get("/api/jobs/{job_id}/download-all")
@ -2061,6 +2145,14 @@ async def get_clip_transcript(job_id: str, clip_index: int, request: Request):
raise HTTPException(status_code=404, detail="Clip not found") raise HTTPException(status_code=404, detail="Clip not found")
clip_data = clips[clip_index] clip_data = clips[clip_index]
# 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_start = clip_data.get('start', 0)
clip_end = clip_data.get('end', 0) clip_end = clip_data.get('end', 0)
@ -2084,6 +2176,284 @@ 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
# 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).
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)
# 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:
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]
# 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))
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 --- # --- Remotion Render Proxy ---
RENDER_SERVICE_URL = os.getenv("RENDER_SERVICE_URL", "http://renderer:3100") RENDER_SERVICE_URL = os.getenv("RENDER_SERVICE_URL", "http://renderer:3100")
@ -2273,6 +2643,18 @@ async def add_subtitles(req: SubtitleRequest, request: Request):
clip_data = clips[req.clip_index] 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 # Video Path
if req.input_filename: if req.input_filename:
# Use chained file # Use chained file
@ -2344,9 +2726,9 @@ async def add_subtitles(req: SubtitleRequest, request: Request):
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
success = await loop.run_in_executor(None, run_transcribe_srt) success = await loop.run_in_executor(None, run_transcribe_srt)
elif is_karaoke: 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: 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: if not success:
raise HTTPException(status_code=400, detail="No words found for this clip range.") raise HTTPException(status_code=400, detail="No words found for this clip range.")

View file

@ -67,6 +67,30 @@ def clip_count_targets(n_windows):
return low, max(low, high) 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): def compact_words(words, precision=2):
"""Round word timestamps for prompts — full float precision wastes tokens.""" """Round word timestamps for prompts — full float precision wastes tokens."""
return [ return [

View file

@ -37,6 +37,8 @@ async def archive_job(user_id, job_id, clips, output_dir):
except Exception as e: except Exception as e:
print(f"⚠️ R2 upload failed for {key}: {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) uploaded = [] # (clip_index, filename, key, title, size_bytes)
for i, clip in enumerate(clips): for i, clip in enumerate(clips):
video_url = clip.get("video_url") or "" video_url = clip.get("video_url") or ""
@ -54,6 +56,22 @@ async def archive_job(user_id, job_id, clips, output_dir):
continue continue
uploaded.append((i, filename, key, _clip_title(clip), os.path.getsize(local_path))) 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: if not uploaded:
return return
async with database.session() as s: async with database.session() as s:
@ -317,6 +335,15 @@ async def purge_free_expired():
for v in items["videos"]: for v in items["videos"]:
await asyncio.to_thread(storage.delete_key, v.r2_key) await asyncio.to_thread(storage.delete_key, v.r2_key)
for p in items["projects"]: for p in items["projects"]:
# 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: if p.metadata_r2_key:
await asyncio.to_thread(storage.delete_key, p.metadata_r2_key) await asyncio.to_thread(storage.delete_key, p.metadata_r2_key)
async with database.session() as s: async with database.session() as s:

View file

@ -9,6 +9,7 @@ import ThumbnailStudio from './components/ThumbnailStudio';
import SaaShortsTab from './components/SaaShortsTab'; import SaaShortsTab from './components/SaaShortsTab';
import UGCGallery from './components/UGCGallery'; import UGCGallery from './components/UGCGallery';
import ScheduleWeekModal from './components/ScheduleWeekModal'; import ScheduleWeekModal from './components/ScheduleWeekModal';
import ClipEditor from './components/ClipEditor';
import UsageMeter from './components/UsageMeter'; import UsageMeter from './components/UsageMeter';
import TopUpModal from './components/TopUpModal'; import TopUpModal from './components/TopUpModal';
import StarBanner from './components/StarBanner'; import StarBanner from './components/StarBanner';
@ -228,6 +229,8 @@ function App() {
const [sessionRecovered, setSessionRecovered] = useState(false); const [sessionRecovered, setSessionRecovered] = useState(false);
const [showScheduleWeek, setShowScheduleWeek] = 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) // Silent-success "saved" states for the settings key inputs (design.md: no alert popups)
const [elevenLabsSaved, setElevenLabsSaved] = useState(false); const [elevenLabsSaved, setElevenLabsSaved] = useState(false);
@ -280,6 +283,43 @@ function App() {
s.timer = setTimeout(flushClipState, 2000); 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)),
};
});
// 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 });
};
// Reopen an archived project from the History tab: the backend re-downloads // 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. // its files from R2 into the server's working dir and returns the full state.
const restoreProject = async (projectJobId) => { const restoreProject = async (projectJobId) => {
@ -607,6 +647,14 @@ function App() {
// that apiFetch attaches automatically. // that apiFetch attaches automatically.
const headers = apiKey ? { 'X-Gemini-Key': apiKey } : {}; 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') { if (data.type === 'url') {
headers['Content-Type'] = 'application/json'; headers['Content-Type'] = 'application/json';
body = JSON.stringify({ body = JSON.stringify({
@ -614,12 +662,16 @@ function App() {
acknowledged: !!data.acknowledged, acknowledged: !!data.acknowledged,
output_format: data.outputFormat || 'auto', output_format: data.outputFormat || 'auto',
force_low_quality: forceLowQuality, force_low_quality: forceLowQuality,
...Object.fromEntries(Object.entries(advanced).filter(([, v]) => v != null)),
}); });
} else { } else {
const formData = new FormData(); const formData = new FormData();
formData.append('file', data.payload); formData.append('file', data.payload);
formData.append('acknowledged', data.acknowledged ? 'true' : 'false'); formData.append('acknowledged', data.acknowledged ? 'true' : 'false');
formData.append('output_format', data.outputFormat || 'auto'); formData.append('output_format', data.outputFormat || 'auto');
for (const [k, v] of Object.entries(advanced)) {
if (v != null) formData.append(k, v);
}
body = formData; body = formData;
} }
@ -1402,10 +1454,11 @@ function App() {
<div className={`grid gap-4 pb-10 ${status === 'complete' ? 'grid-cols-1 xl:grid-cols-2' : 'grid-cols-1'}`}> <div className={`grid gap-4 pb-10 ${status === 'complete' ? 'grid-cols-1 xl:grid-cols-2' : 'grid-cols-1'}`}>
{results.clips.map((clip, i) => ( {results.clips.map((clip, i) => (
<ResultCard <ResultCard
key={`${jobId}-${i}`} key={`${jobId}-${i}-${clip.video_url || ''}`}
clip={clip} clip={clip}
index={i} index={i}
jobId={jobId} jobId={jobId}
onEditClip={(index) => setEditingClip(index)}
initialState={projectState?.clips?.find((c) => c.index === i) || null} initialState={projectState?.clips?.find((c) => c.index === i) || null}
onStateChange={handleClipStateChange} onStateChange={handleClipStateChange}
durableUrl={durableClips[i]} durableUrl={durableClips[i]}
@ -1576,6 +1629,15 @@ function App() {
)} )}
{editingClip !== null && results?.clips?.[editingClip] && (
<ClipEditor
jobId={jobId}
clipIndex={editingClip}
clipTitle={results.clips[editingClip].video_title_for_youtube_short || ''}
onClose={() => setEditingClip(null)}
onRerendered={handleClipRerendered}
/>
)}
{showLogin && <LoginModal onClose={() => setShowLogin(false)} />} {showLogin && <LoginModal onClose={() => setShowLogin(false)} />}
{showPlanChoice && <PlanChoiceModal onClose={() => setShowPlanChoice(false)} />} {showPlanChoice && <PlanChoiceModal onClose={() => setShowPlanChoice(false)} />}
{showTopUp && ( {showTopUp && (

View file

@ -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 (
<div className="fixed inset-0 z-[110] bg-black/70 flex items-center justify-center p-4 animate-fade" onMouseDown={onClose}>
<div className="card p-6 max-w-md" onMouseDown={(e) => e.stopPropagation()}>
<p className="eyebrow mb-2">EDITOR · CLIP {clipIndex + 1}</p>
<div className="flex items-center gap-2 text-danger text-sm"><AlertCircle size={16} /> {loadError}</div>
<button className="btn-ghost mt-5" onClick={onClose}>close</button>
</div>
</div>
);
}
if (!edl) {
return (
<div className="fixed inset-0 z-[110] bg-paper/90 flex items-center justify-center animate-fade">
<div className="flex items-center gap-3 text-muted text-sm lowercase">
<Loader2 size={18} className="animate-spin text-brass" /> loading clip recipe…
</div>
</div>
);
}
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 (
<div className="fixed inset-0 z-[110] bg-paper flex flex-col animate-fade">
{/* header */}
<div className="px-4 sm:px-6 pt-5 pb-4 border-b border-rule flex items-start justify-between gap-4 shrink-0">
<div className="min-w-0">
<p className="eyebrow mb-1">EDITOR · CLIP {clipIndex + 1}</p>
<h2 className="font-display lowercase text-2xl text-ink truncate">edit clip</h2>
{clipTitle && <p className="text-xs text-muted truncate mt-0.5">{clipTitle}</p>}
</div>
<div className="flex items-center gap-4 shrink-0">
<div className="text-right">
<p className="readout">DURATION · {fmt(total)}</p>
<p className="readout mt-1">
{needsSourcePath ? 'PATH · FULL RE-FRAME' : 'PATH · FAST RECUT'}
{edl.rerender_minutes > 0 && ` · ≈${Math.max(1, Math.ceil(total / 60))} MIN`}
</p>
</div>
{confirmClose ? (
<div className="flex items-center gap-2">
<span className="text-xs text-warn lowercase">discard changes?</span>
<button className="btn-danger text-xs py-1.5 px-3" onClick={onClose}>discard</button>
<button className="btn-ghost text-xs py-1.5 px-3" onClick={() => setConfirmClose(false)}>keep editing</button>
</div>
) : (
<button
onClick={() => (dirty ? setConfirmClose(true) : onClose())}
className="p-2 rounded-input text-muted hover:text-ink hover:bg-paper3 transition-colors"
aria-label="close editor"
>
<X size={18} />
</button>
)}
</div>
</div>
{/* main */}
<div className="flex-1 min-h-0 flex flex-col md:flex-row gap-6 px-4 sm:px-6 py-5 overflow-hidden">
{/* preview */}
<div className="flex-1 min-w-0 flex items-center justify-center">
<div className="h-full max-h-full aspect-[9/16] bg-black rounded-card border border-rule overflow-hidden relative">
<video
ref={videoRef}
src={previewUrl}
controls
playsInline
className="w-full h-full object-contain"
onTimeUpdate={(e) => setPlayhead(e.target.currentTime)}
/>
{dirty && (
<div className="absolute top-2 left-2 badge-warn">preview shows the last render</div>
)}
</div>
</div>
{/* rail */}
<div className="w-full md:w-[24rem] shrink-0 flex flex-col min-h-0">
<div className="flex-1 overflow-y-auto custom-scrollbar pr-1 space-y-5">
{/* segments */}
<div>
<div className="flex items-center justify-between mb-2">
<p className="eyebrow">Segments · {segments.length}/{limits.max_segments}</p>
<div className="flex items-center gap-1">
<button className="p-1.5 rounded-input text-muted hover:text-ink hover:bg-paper3 disabled:opacity-45" disabled={!state.past.length} onClick={() => dispatch({ type: 'undo' })} aria-label="undo"><Undo2 size={14} /></button>
<button className="p-1.5 rounded-input text-muted hover:text-ink hover:bg-paper3 disabled:opacity-45" disabled={!state.future.length} onClick={() => dispatch({ type: 'redo' })} aria-label="redo"><Redo2 size={14} /></button>
</div>
</div>
<div className="space-y-2">
{segments.map((seg, i) => (
<div
key={i}
onClick={() => 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)]' : ''}`}
>
<div className="flex items-center gap-2">
<span className="w-4 h-4 rounded-full shrink-0" style={{ background: SEGMENT_COLORS[i % SEGMENT_COLORS.length] }} />
<span className="readout">#{i + 1}</span>
<input
type="number"
step="0.1"
value={seg.start}
onClick={(e) => 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`}
/>
<span className="text-muted text-xs">→</span>
<input
type="number"
step="0.1"
value={seg.end}
onClick={(e) => 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`}
/>
<span className="readout ml-auto">{fmt(seg.end - seg.start)}</span>
</div>
<div className="flex items-center gap-1 mt-2">
<button className="p-1 rounded-input text-muted hover:text-ink hover:bg-paper disabled:opacity-45" disabled={i === 0} onClick={(e) => { e.stopPropagation(); moveSegment(i, -1); }} aria-label="move up"><ChevronUp size={13} /></button>
<button className="p-1 rounded-input text-muted hover:text-ink hover:bg-paper disabled:opacity-45" disabled={i === segments.length - 1} onClick={(e) => { e.stopPropagation(); moveSegment(i, 1); }} aria-label="move down"><ChevronDown size={13} /></button>
<button className="p-1 rounded-input text-muted hover:text-ink hover:bg-paper disabled:opacity-45" disabled={seg.end - seg.start < minSeg * 2 || segments.length >= limits.max_segments} onClick={(e) => { e.stopPropagation(); splitSegment(i); }} aria-label="split segment"><Scissors size={13} /></button>
<button className="p-1 rounded-input text-muted hover:text-danger hover:bg-paper disabled:opacity-45 ml-auto" disabled={segments.length <= 1} onClick={(e) => { e.stopPropagation(); deleteSegment(i); }} aria-label="delete segment"><Trash2 size={13} /></button>
</div>
{outOfRange(seg) && (
<p className="text-[11px] text-danger mt-1.5 lowercase">outside the original range — the source video is gone</p>
)}
</div>
))}
</div>
<button
onClick={addSegment}
disabled={segments.length >= limits.max_segments}
className="mt-2 w-full flex items-center justify-center gap-1.5 py-2 rounded-input border border-dashed border-rule2 text-xs lowercase text-ink2 hover:bg-paper3 transition-colors disabled:opacity-45"
>
<Plus size={14} /> add segment
</button>
</div>
{/* toggles */}
<div className="space-y-2.5">
<label className="flex items-center justify-between cursor-pointer">
<span className="text-xs lowercase text-ink2">snap cuts to words</span>
<span className="relative inline-flex items-center">
<input type="checkbox" checked={snapToWords} onChange={(e) => setSnapToWords(e.target.checked)} className="sr-only peer" />
<span className="w-8 h-4 rounded-full bg-paper3 peer-checked:bg-brass transition-colors after:content-[''] after:absolute after:left-0.5 after:top-0.5 after:w-3 after:h-3 after:rounded-full after:bg-ink after:transition-transform peer-checked:after:translate-x-4" />
</span>
</label>
<label className="flex items-center justify-between cursor-pointer">
<span className="text-xs lowercase text-ink2">re-apply captions after recut</span>
<span className="relative inline-flex items-center">
<input type="checkbox" checked={reapplyCaptions} onChange={(e) => setReapplyCaptions(e.target.checked)} className="sr-only peer" />
<span className="w-8 h-4 rounded-full bg-paper3 peer-checked:bg-brass transition-colors after:content-[''] after:absolute after:left-0.5 after:top-0.5 after:w-3 after:h-3 after:rounded-full after:bg-ink after:transition-transform peer-checked:after:translate-x-4" />
</span>
</label>
</div>
{/* source monitor */}
{sourceAvailable && (
<div>
<button onClick={() => setShowSource((v) => !v)} className="w-full flex items-center justify-between mb-2">
<p className="eyebrow">Source monitor</p>
<Film size={13} className={showSource ? 'text-brass' : 'text-muted'} />
</button>
{showSource && (
<div className="bg-black rounded-card border border-rule overflow-hidden">
<video ref={sourceRef} src={getApiUrl(edl.source.url)} controls playsInline className="w-full max-h-48 object-contain" />
<div className="flex flex-wrap gap-1 p-2 bg-paper2">
{segments.map((seg, i) => (
<button
key={i}
onClick={() => { if (sourceRef.current) { sourceRef.current.currentTime = seg.start; sourceRef.current.play().catch(() => {}); } }}
className="px-2 py-1 rounded-input border border-rule text-[11px] text-ink2 hover:bg-paper3 lowercase"
>
#{i + 1} · {fmt(seg.start)}
</button>
))}
</div>
</div>
)}
</div>
)}
{/* transcript */}
<div>
<p className="eyebrow mb-2">Transcript · segment #{selected + 1}</p>
{panelWords.length === 0 ? (
<p className="text-xs text-muted lowercase">no words near this segment</p>
) : (
<div className="flex flex-wrap gap-x-1 gap-y-1.5 max-h-40 overflow-y-auto custom-scrollbar pr-1">
{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 (
<button
key={`${w.s}-${i}`}
onClick={() => setSelectedWord(isSel ? null : w)}
title={`${fmt(w.s)} – ${fmt(w.e)}`}
className={`px-1 py-0.5 rounded text-xs transition-colors ${isSel ? 'bg-brass text-brassink' : inside ? 'text-ink hover:bg-paper3' : 'text-muted hover:bg-paper3'}`}
>
{w.w}
</button>
);
})}
</div>
)}
{selectedWord && selectedSeg && (
<div className="flex items-center gap-2 mt-2">
<span className="readout">“{selectedWord.w}” · {fmt(selectedWord.s)}</span>
<button className="btn-quiet text-[11px] py-1 px-2" onClick={() => { setSegment(selected, { start: selectedWord.s }, { snap: false }); setSelectedWord(null); }}>start here</button>
<button className="btn-quiet text-[11px] py-1 px-2" onClick={() => { setSegment(selected, { end: selectedWord.e }, { snap: false }); setSelectedWord(null); }}>end here</button>
</div>
)}
</div>
</div>
{/* footer actions */}
<div className="shrink-0 pt-4 mt-4 border-t border-rule">
{renderError && (
<div className="mb-3 px-3 py-2 rounded-input text-xs text-danger bg-[color-mix(in_oklab,var(--color-danger)_10%,transparent)] flex items-center gap-2">
<AlertCircle size={14} className="shrink-0" /> {renderError}
</div>
)}
{overCaps && (
<p className="mb-3 text-[11px] text-warn lowercase">
{total > limits.max_total_seconds ? `clip is over ${Math.round(limits.max_total_seconds)}s` : `more than ${limits.max_segments} segments`}
</p>
)}
<div className="flex gap-2">
<button className="btn-ghost" onClick={() => (dirty ? setConfirmClose(true) : onClose())}>
{dirty ? 'cancel' : 'close'}
</button>
<button className="btn-primary flex-1 flex items-center justify-center gap-2" disabled={!canRender || !dirty} onClick={doRender}>
{rendering
? (<><Loader2 size={16} className="animate-spin text-brassink" /> re-rendering… {renderSeconds}s</>)
: (needsSourcePath ? 're-render from source' : 're-render clip')}
</button>
</div>
</div>
</div>
</div>
{/* timeline */}
<div className="shrink-0 border-t border-rule px-4 sm:px-6 py-4 space-y-3 bg-paper2">
{/* clip track */}
<div>
<div className="flex items-center justify-between mb-1.5">
<p className="readout">CLIP · {fmt(total)}</p>
<p className="readout hidden sm:block">SPACE PLAY · S SPLIT · ⌫ DELETE · ⌘Z UNDO</p>
</div>
<div ref={clipTrackRef} className="relative h-12 rounded-input bg-paper border border-rule overflow-hidden">
{blocks.map(({ seg, i, left, width }) => (
<div
key={i}
onPointerDown={() => 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)` }}
>
<span className="absolute inset-0 flex items-center justify-center readout pointer-events-none select-none">
#{i + 1} · {fmt(seg.end - seg.start)}
</span>
{/* trim handles */}
<div
onPointerDown={(e) => 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] }}
/>
<div
onPointerDown={(e) => 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] }}
/>
</div>
))}
{/* playhead over the last rendered recipe */}
{!dirty && renderedTotal > 0 && playhead <= renderedTotal && (
<div className="absolute top-0 bottom-0 w-px bg-ink pointer-events-none" style={{ left: `${(playhead / renderedTotal) * 100}%` }} />
)}
</div>
</div>
{/* source track */}
<div>
<div className="flex items-center justify-between mb-1.5">
<p className="readout">
SOURCE · {fmt(sourceDuration)}{edl.source.duration_estimated ? ' (EST.)' : ''}
{!sourceAvailable && ' · EXPIRED — TRIMS LIMITED TO THE ORIGINAL RANGE'}
</p>
{sourceAvailable && segments.length < limits.max_segments && (
<p className="readout hidden sm:block">DRAG ON EMPTY SPACE TO ADD A SEGMENT</p>
)}
</div>
<div
ref={sourceTrackRef}
onPointerDown={startGhostDrag}
className={`relative h-8 rounded-input border overflow-hidden ${sourceAvailable ? 'bg-paper border-rule cursor-crosshair' : 'bg-paper border-rule opacity-60'}`}
>
{/* canonical range marker */}
{sourceDuration > 0 && (
<div
className="absolute top-0 bottom-0 border-x border-rule2 bg-paper3/60 pointer-events-none"
style={{
left: `${(canonical.start / sourceDuration) * 100}%`,
width: `${((canonical.end - canonical.start) / sourceDuration) * 100}%`,
}}
/>
)}
{sourceDuration > 0 && segments.map((seg, i) => (
<div
key={i}
onPointerDown={(e) => { 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 && (
<div
className="absolute top-1 bottom-1 rounded-[4px] bg-ink/40 border border-dashed border-ink pointer-events-none"
style={{
left: `${(ghost.start / sourceDuration) * 100}%`,
width: `${((ghost.end - ghost.start) / sourceDuration) * 100}%`,
}}
/>
)}
</div>
<div className="flex justify-between mt-1">
<span className="readout">0:00</span>
<span className="readout">{fmt(sourceDuration / 2)}</span>
<span className="readout">{fmt(sourceDuration)}</span>
</div>
</div>
</div>
</div>
);
}

View file

@ -1,5 +1,5 @@
import React, { useState, useEffect, useRef } from 'react'; 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'; import { getApiUrl } from '../config';
const SUPPORTED_PLATFORMS = [ const SUPPORTED_PLATFORMS = [
@ -16,6 +16,12 @@ export default function MediaInput({ onProcess, isProcessing }) {
const [acknowledged, setAcknowledged] = useState(false); const [acknowledged, setAcknowledged] = useState(false);
const [outputFormat, setOutputFormat] = useState('vertical'); // vertical | horizontal | square const [outputFormat, setOutputFormat] = useState('vertical'); // vertical | horizontal | square
const [showInfo, setShowInfo] = useState(false); 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); const infoRef = useRef(null);
// Close the compatibility popover on any outside click. // Close the compatibility popover on any outside click.
@ -58,10 +64,15 @@ export default function MediaInput({ onProcess, isProcessing }) {
const handleSubmit = (e) => { const handleSubmit = (e) => {
e.preventDefault(); e.preventDefault();
if (!acknowledged) return; if (!acknowledged) return;
const advanced = {
targetClips: targetClips || null,
clipMinSeconds: clipMinSeconds || null,
clipMaxSeconds: clipMaxSeconds || null,
};
if (mode === 'url' && url) { 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) { } 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 }) {
</div> </div>
</div> </div>
{/* Advanced generation controls — collapsed by default; blank = AI decides */}
<div className="mt-4">
<button
type="button"
onClick={() => setShowAdvanced((v) => !v)}
className="flex items-center gap-1.5 text-xs text-muted hover:text-ink2 lowercase transition-colors"
>
<ChevronDown size={14} className={`transition-transform ${showAdvanced ? 'rotate-180' : ''}`} />
advanced options
{(targetClips || clipMinSeconds || clipMaxSeconds) && (
<span className="text-brass">·</span>
)}
</button>
{showAdvanced && (
<div className="mt-3 grid grid-cols-3 gap-2 animate-fade">
<div>
<p className="eyebrow mb-1.5">clips to aim for</p>
<input
type="number" min="1" max="15" step="1"
value={targetClips}
onChange={(e) => setTargetClips(e.target.value)}
placeholder="auto"
className="input-field"
/>
</div>
<div>
<p className="eyebrow mb-1.5">min length (s)</p>
<input
type="number" min="5" max="175" step="1"
value={clipMinSeconds}
onChange={(e) => setClipMinSeconds(e.target.value)}
placeholder="15"
className="input-field"
/>
</div>
<div>
<p className="eyebrow mb-1.5">max length (s)</p>
<input
type="number" min="10" max="180" step="1"
value={clipMaxSeconds}
onChange={(e) => setClipMaxSeconds(e.target.value)}
placeholder="60"
className="input-field"
/>
</div>
<p className="col-span-3 text-[11px] leading-relaxed text-muted">
Targets, not guarantees: the AI returns fewer clips when the
material doesn't hold them. Leave blank to let it decide.
</p>
</div>
)}
</div>
<label className="flex items-start gap-2 mt-5 text-xs text-muted cursor-pointer select-none"> <label className="flex items-start gap-2 mt-5 text-xs text-muted cursor-pointer select-none">
<input <input
type="checkbox" type="checkbox"

View file

@ -1,5 +1,5 @@
import React, { useState, useEffect } from 'react'; 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 { getApiUrl } from '../config';
import { apiFetch } from '../lib/api'; import { apiFetch } from '../lib/api';
import SubtitleModal from './SubtitleModal'; import SubtitleModal from './SubtitleModal';
@ -19,13 +19,23 @@ const PLATFORM_OPTIONS = [
{ value: 'youtube', label: 'youtube', icon: <Youtube size={16} /> }, { value: 'youtube', label: 'youtube', icon: <Youtube size={16} /> },
]; ];
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) { 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; if (!Number.isFinite(secs) || secs < 0) return null;
return `${String(Math.floor(secs / 60)).padStart(2, '0')}:${String(secs % 60).padStart(2, '0')}`; 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 [showModal, setShowModal] = useState(false);
const [showDescModal, setShowDescModal] = useState(false); const [showDescModal, setShowDescModal] = useState(false);
const [showSubtitleModal, setShowSubtitleModal] = useState(false); const [showSubtitleModal, setShowSubtitleModal] = useState(false);
@ -126,7 +136,10 @@ export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostK
const [showTranslateModal, setShowTranslateModal] = useState(false); const [showTranslateModal, setShowTranslateModal] = useState(false);
const [editError, setEditError] = useState(null); 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 // Accumulate Remotion layers across operations. A reopened project restores
// the layers persisted in its project state, so the next edit composes over // the layers persisted in its project state, so the next edit composes over
@ -709,6 +722,16 @@ export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostK
{/* Actions Footer */} {/* Actions Footer */}
<div className="grid grid-cols-2 gap-2 mt-auto pt-4 border-t border-rule"> <div className="grid grid-cols-2 gap-2 mt-auto pt-4 border-t border-rule">
{onEditClip && (
<button
onClick={() => onEditClip(index)}
className={QUIET_BTN}
>
<Scissors size={16} className="text-muted group-hover:text-brass transition-colors shrink-0" />
edit clip
</button>
)}
<button <button
onClick={handleAutoEdit} onClick={handleAutoEdit}
disabled={isEditing} disabled={isEditing}
@ -762,7 +785,7 @@ export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostK
} }
downloadClip(); downloadClip();
}} }}
className={QUIET_BTN} className={`${QUIET_BTN}${onEditClip ? ' col-span-2' : ''}`}
> >
<Download size={16} className="text-muted group-hover:text-brass transition-colors shrink-0" /> download <Download size={16} className="text-muted group-hover:text-brass transition-colors shrink-0" /> download
</button> </button>

View file

@ -9,7 +9,8 @@ from google import genai
from google.genai import types as genai_types from google.genai import types as genai_types
from pydantic import BaseModel from pydantic import BaseModel
from clip_selection import clip_count_targets, lookup_model_prices from clip_selection import (clip_count_targets, clip_duration_bounds,
lookup_model_prices)
load_dotenv() load_dotenv()
@ -63,7 +64,7 @@ class VisualResponse(BaseModel):
VISUAL_PROMPT_TEMPLATE = """ VISUAL_PROMPT_TEMPLATE = """
You are a senior short-form video editor. This video has NO speech/audio — judge You are a senior short-form video editor. This video has NO speech/audio — judge
it purely by what you SEE. Watch the whole thing and pick the 3–15 MOST engaging it purely by what you SEE. Watch the whole thing and pick the {min_clips}–{max_clips} MOST engaging
visual moments for TikTok / Reels / Shorts (action, reveals, transformations, visual moments for TikTok / Reels / Shorts (action, reveals, transformations,
striking or funny shots, satisfying payoffs, dramatic movement). striking or funny shots, satisfying payoffs, dramatic movement).
@ -71,8 +72,8 @@ TIME CONTRACT — STRICT:
- Timestamps in ABSOLUTE SECONDS from the start (usable with ffmpeg -ss/-to). - Timestamps in ABSOLUTE SECONDS from the start (usable with ffmpeg -ss/-to).
- Only numbers with up to 3 decimals (e.g. 0, 12.5, 47.250). - Only numbers with up to 3 decimals (e.g. 0, 12.5, 47.250).
- 0 <= start < end <= {video_duration}. - 0 <= start < end <= {video_duration}.
- Each clip 15 to 60 seconds long. If the whole video is shorter than 15s, - Each clip {min_secs:g} to {max_secs:g} seconds long. If the whole video is
return one clip spanning the full video. shorter than {min_secs:g}s, return one clip spanning the full video.
- Cut on visual scene changes, never mid-motion. - Cut on visual scene changes, never mid-motion.
For each clip write catchy copy in {language} (a scroll-stopping hook, a TikTok For each clip write catchy copy in {language} (a scroll-stopping hook, a TikTok
@ -241,7 +242,7 @@ Choose the BEST short clips from these shortlisted candidate windows.
CLIP RULES: CLIP RULES:
- Return only valid JSON. - Return only valid JSON.
- Each clip must be 15 to 60 seconds long, in absolute seconds from the start of the source video. - Each clip must be {min_secs:g} to {max_secs:g} seconds long, in absolute seconds from the start of the source video.
- Stay within the candidate window boundaries. - Stay within the candidate window boundaries.
- THE 2-SECOND RULE: the clip MUST open on its strongest moment. If the first - THE 2-SECOND RULE: the clip MUST open on its strongest moment. If the first
2 seconds would not stop a cold viewer from scrolling, move the start or skip the clip. 2 seconds would not stop a cold viewer from scrolling, move the start or skip the clip.
@ -515,6 +516,7 @@ def main() -> int:
# derived from it would be meaningless — and the score template has no # derived from it would be meaningless — and the score template has no
# placeholder for one anyway. # placeholder for one anyway.
fmt["min_clips"], fmt["max_clips"] = clip_count_targets(len(payload.get("windows") or [])) fmt["min_clips"], fmt["max_clips"] = clip_count_targets(len(payload.get("windows") or []))
fmt["min_secs"], fmt["max_secs"] = clip_duration_bounds()
prompt = template.format(**fmt) prompt = template.format(**fmt)
_log(f"🤖 Gemini worker request: mode={args.mode} strategy={args.strategy} model={model_name} items={len(payload.get('windows', []))}") _log(f"🤖 Gemini worker request: mode={args.mode} strategy={args.strategy} model={model_name} items={len(payload.get('windows', []))}")

28
main.py
View file

@ -23,7 +23,8 @@ from google.genai import types as genai_types
import gemini_worker import gemini_worker
import layout_picker import layout_picker
from clip_selection import build_transcript_windows, clip_count_targets, snap_clip_to_words from clip_selection import (build_transcript_windows, clip_count_targets,
clip_duration_bounds, snap_clip_to_words)
from ffmpeg_utils import (video_encode_args, audio_encode_args, QUALITY, from ffmpeg_utils import (video_encode_args, audio_encode_args, QUALITY,
QUALITY_FAST, METADATA_SCRUB) QUALITY_FAST, METADATA_SCRUB)
from dotenv import load_dotenv from dotenv import load_dotenv
@ -1275,9 +1276,11 @@ def get_viral_clips(transcript_result, video_duration):
# --- Pass 2: detailed clip extraction on the shortlist --- # --- Pass 2: detailed clip extraction on the shortlist ---
payload = [{"id": w["id"], "start": w["start"], "end": w["end"], "text": w["text"]} for w in shortlist] payload = [{"id": w["id"], "start": w["start"], "end": w["end"], "text": w["text"]} for w in shortlist]
min_clips, max_clips = clip_count_targets(len(shortlist)) min_clips, max_clips = clip_count_targets(len(shortlist))
min_secs, max_secs = clip_duration_bounds()
prompt = gemini_worker.DETAIL_PROMPT_TEMPLATE.format( prompt = gemini_worker.DETAIL_PROMPT_TEMPLATE.format(
video_duration=video_duration, language=language, video_duration=video_duration, language=language,
min_clips=min_clips, max_clips=max_clips, min_clips=min_clips, max_clips=max_clips,
min_secs=min_secs, max_secs=max_secs,
windows_json=json.dumps(payload, ensure_ascii=False)) windows_json=json.dumps(payload, ensure_ascii=False))
detail, cost = _run_gemini_stage(client, model_name, prompt, gemini_worker.DetailResponse) detail, cost = _run_gemini_stage(client, model_name, prompt, gemini_worker.DetailResponse)
if cost: if cost:
@ -1286,7 +1289,8 @@ def get_viral_clips(transcript_result, video_duration):
shorts = detail.get("shorts") or [] shorts = detail.get("shorts") or []
# Snap each proposed clip onto real word boundaries (+ a bit of silence). # Snap each proposed clip onto real word boundaries (+ a bit of silence).
for s in shorts: for s in shorts:
ns, ne = snap_clip_to_words(s.get("start", 0), s.get("end", 0), words, video_duration) ns, ne = snap_clip_to_words(s.get("start", 0), s.get("end", 0), words, video_duration,
min_duration=min_secs, max_duration=max_secs)
s["start"], s["end"] = ns, ne s["start"], s["end"] = ns, ne
# Aggregate cost across both passes. # Aggregate cost across both passes.
@ -1348,8 +1352,20 @@ def get_visual_clips(video_path, video_duration, language="en"):
return None return None
time.sleep(2) time.sleep(2)
# The vision path has no scoring windows to derive a count from, so the
# env targets (user request) apply directly over the classic 3-15.
def _env_int(name, default):
try:
return max(1, int(os.environ.get(name, "")))
except ValueError:
return default
v_min_clips = _env_int("CLIP_TARGET_MIN", 3)
v_max_clips = max(v_min_clips, _env_int("CLIP_TARGET_MAX", 15))
v_min_secs, v_max_secs = clip_duration_bounds()
prompt = gemini_worker.VISUAL_PROMPT_TEMPLATE.format( prompt = gemini_worker.VISUAL_PROMPT_TEMPLATE.format(
video_duration=video_duration, language=language) video_duration=video_duration, language=language,
min_clips=v_min_clips, max_clips=v_max_clips,
min_secs=v_min_secs, max_secs=v_max_secs)
config = genai_types.GenerateContentConfig( config = genai_types.GenerateContentConfig(
response_mime_type="application/json", response_mime_type="application/json",
response_schema=gemini_worker.VisualResponse, response_schema=gemini_worker.VisualResponse,
@ -1505,6 +1521,12 @@ if __name__ == '__main__':
# Save metadata. Silent videos have no transcript → no subtitles, # Save metadata. Silent videos have no transcript → no subtitles,
# which is correct (there's no speech to caption). # which is correct (there's no speech to caption).
clips_data['transcript'] = transcript or {"language": "none", "segments": []} 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") metadata_file = os.path.join(output_dir, f"{video_title}_metadata.json")
with open(metadata_file, 'w') as f: with open(metadata_file, 'w') as f:
json.dump(clips_data, f, indent=2) json.dump(clips_data, f, indent=2)

View file

@ -95,6 +95,20 @@ TOOLS = [
"type": "boolean", "type": "boolean",
"description": "Set true to proceed after a needs_confirmation low-resolution warning.", "description": "Set true to proceed after a needs_confirmation low-resolution warning.",
}, },
"target_clips": {
"type": "integer", "minimum": 1, "maximum": 15,
"description": "How many clips to aim for. A target, not a guarantee: "
"fewer come back when the material doesn't hold them. "
"Default: the AI decides (usually 2-6).",
},
"clip_min_seconds": {
"type": "number", "minimum": 5, "maximum": 175,
"description": "Minimum clip length in seconds (default 15).",
},
"clip_max_seconds": {
"type": "number", "minimum": 10, "maximum": 180,
"description": "Maximum clip length in seconds (default 60). Must be ≥ 5s above the minimum.",
},
}, },
"required": ["source_url", "confirm_rights"], "required": ["source_url", "confirm_rights"],
}, },
@ -165,6 +179,48 @@ TOOLS = [
"required": ["job_id", "clip_index"], "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", "name": "publish_clip",
"title": "Publish a clip to social platforms", "title": "Publish a clip to social platforms",
@ -228,6 +284,9 @@ async def _tool_process_video(client, args):
"webhook_url": args.get("webhook_url"), "webhook_url": args.get("webhook_url"),
"webhook_secret": args.get("webhook_secret"), "webhook_secret": args.get("webhook_secret"),
} }
for k in ("target_clips", "clip_min_seconds", "clip_max_seconds"):
if args.get(k) is not None:
body[k] = args[k]
resp = await client.post("/api/process", json=body) resp = await client.post("/api/process", json=body)
if resp.status_code >= 400: if resp.status_code >= 400:
return _api_error(resp), True return _api_error(resp), True
@ -311,6 +370,18 @@ async def _tool_add_subtitles(client, args):
return resp.json(), False 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): async def _tool_publish_clip(client, args):
body = {"job_id": args["job_id"], "clip_index": args["clip_index"], body = {"job_id": args["job_id"], "clip_index": args["clip_index"],
"platforms": args["platforms"]} "platforms": args["platforms"]}
@ -329,6 +400,7 @@ _TOOL_IMPLS = {
"list_clips": _tool_list_clips, "list_clips": _tool_list_clips,
"get_quota": _tool_get_quota, "get_quota": _tool_get_quota,
"add_subtitles": _tool_add_subtitles, "add_subtitles": _tool_add_subtitles,
"recut_clip": _tool_recut_clip,
"publish_clip": _tool_publish_clip, "publish_clip": _tool_publish_clip,
} }

319
recut.py Normal file
View file

@ -0,0 +1,319 @@
"""
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
import uuid
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.
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(),
# 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
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",
*METADATA_SCRUB, "-movflags", "+faststart", 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
# 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"temp_recut_part_{token}_{i}.mp4")
for i in range(len(segments))
]
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)
with open(list_path, "w") as f:
for part in part_paths:
# 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]:
if os.path.exists(path):
os.remove(path)
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):
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}")
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_<ts>_`` 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.
"""
# 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)
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)

View file

@ -157,8 +157,9 @@ class TestDetailPromptCarriesTheCount:
low, high = clip_count_targets(5) low, high = clip_count_targets(5)
prompt = gw.DETAIL_PROMPT_TEMPLATE.format( prompt = gw.DETAIL_PROMPT_TEMPLATE.format(
video_duration=300, language="es", min_clips=low, max_clips=high, video_duration=300, language="es", min_clips=low, max_clips=high,
windows_json="[]") min_secs=15.0, max_secs=60.0, windows_json="[]")
assert f"return {low} to {high} clips" in prompt assert f"return {low} to {high} clips" in prompt
assert "15 to 60 seconds" in prompt
# The JSON schema example legitimately keeps braces (they are {{ }} in # The JSON schema example legitimately keeps braces (they are {{ }} in
# the template), so assert on unsubstituted placeholders specifically. # the template), so assert on unsubstituted placeholders specifically.
assert re.findall(r"\{[a-z_]+\}", prompt) == [] assert re.findall(r"\{[a-z_]+\}", prompt) == []

View file

@ -0,0 +1,81 @@
"""Unit tests for the manual generation controls (discussion #65): the
clip-duration band helper and the prompt templates it feeds.
Pure logic only — no API calls, no heavy imports (gemini_worker's templates are
read via ast so the ML stack never loads in CI).
"""
import ast
import os
import pytest
import clip_selection
@pytest.fixture(autouse=True)
def _clean_env(monkeypatch):
monkeypatch.delenv("CLIP_MIN_SECONDS", raising=False)
monkeypatch.delenv("CLIP_MAX_SECONDS", raising=False)
class TestClipDurationBounds:
def test_defaults_are_the_classic_band(self):
assert clip_selection.clip_duration_bounds() == (15.0, 60.0)
def test_env_overrides_apply(self, monkeypatch):
monkeypatch.setenv("CLIP_MIN_SECONDS", "20")
monkeypatch.setenv("CLIP_MAX_SECONDS", "30")
assert clip_selection.clip_duration_bounds() == (20.0, 30.0)
def test_clamped_to_platform_limits(self, monkeypatch):
monkeypatch.setenv("CLIP_MIN_SECONDS", "1")
monkeypatch.setenv("CLIP_MAX_SECONDS", "9999")
assert clip_selection.clip_duration_bounds() == (5.0, 180.0)
def test_degenerate_band_keeps_a_real_range(self, monkeypatch):
# max below min must widen, not invert or collapse.
monkeypatch.setenv("CLIP_MIN_SECONDS", "60")
monkeypatch.setenv("CLIP_MAX_SECONDS", "20")
lo, hi = clip_selection.clip_duration_bounds()
assert lo == 60.0 and hi >= lo + 5.0
def test_garbage_falls_back_to_defaults(self, monkeypatch):
monkeypatch.setenv("CLIP_MIN_SECONDS", "garbage")
monkeypatch.setenv("CLIP_MAX_SECONDS", "")
assert clip_selection.clip_duration_bounds() == (15.0, 60.0)
def _templates():
"""The prompt template constants, read without importing gemini_worker
(which pulls google-genai — absent in the thin CI env)."""
mod = ast.parse(open(os.path.join(os.path.dirname(__file__), "..",
"gemini_worker.py")).read())
return {
node.targets[0].id: node.value.value
for node in mod.body
if isinstance(node, ast.Assign) and isinstance(node.value, ast.Constant)
and isinstance(node.targets[0], ast.Name)
and node.targets[0].id.endswith("_PROMPT_TEMPLATE")
}
class TestPromptTemplates:
def test_detail_template_carries_the_band(self):
text = _templates()["DETAIL_PROMPT_TEMPLATE"].format(
video_duration=100, language="es", min_clips=2, max_clips=4,
min_secs=10.0, max_secs=20.0, windows_json="[]")
assert "10 to 20 seconds" in text
assert "return 2 to 4 clips" in text
def test_visual_template_carries_band_and_count(self):
text = _templates()["VISUAL_PROMPT_TEMPLATE"].format(
video_duration=100, language="es", min_clips=2, max_clips=4,
min_secs=10.0, max_secs=20.0)
assert "2–4 MOST engaging" in text
assert "10 to 20 seconds" in text
def test_score_template_needs_no_new_keys(self):
# The scoring pass has no count/duration placeholders; formatting with
# only its classic keys must keep working.
_templates()["SCORE_PROMPT_TEMPLATE"].format(
video_duration=100, language="es", windows_json="[]")

290
tests/test_recut.py Normal file
View file

@ -0,0 +1,290 @@
"""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",
*recut.METADATA_SCRUB,
"-movflags", "+faststart",
"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_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)],
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))

View file

@ -0,0 +1,273 @@
"""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 == []
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):
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