diff --git a/app.py b/app.py index 911b772..a0f84e5 100644 --- a/app.py +++ b/app.py @@ -23,6 +23,7 @@ from fastapi.responses import HTMLResponse, FileResponse, JSONResponse from starlette.background import BackgroundTask from pydantic import BaseModel from s3_uploader import upload_job_artifacts, list_all_clips, upload_actor_to_s3, list_actor_gallery, upload_video_to_gallery, list_video_gallery +import recut load_dotenv() @@ -371,15 +372,20 @@ def _canonical_clip_file(output_dir, base_name, index): """The file to serve for clip ``index``, preferring a derived version. The pipeline writes the clean reframe as ``_clip_.mp4`` and any - post-processing (auto-captions, and /api/subtitle re-styles) as - ``subtitled__.mp4``, keeping the original for re-styling. Every - place that rebuilds the canonical name from disk — restore after a restart, - the R2 upload, the download bundle — must therefore resolve to the newest - derived file, or clips silently lose their captions on a redeploy. + post-processing (auto-captions, /api/subtitle re-styles, and clip-editor + recuts) as ``subtitled__.mp4`` / ``recut__.mp4``, + keeping the original for re-styling. Every place that rebuilds the + canonical name from disk — restore after a restart, the R2 upload, the + download bundle — must therefore resolve to the newest derived file, or + clips silently lose their captions (or their recut) on a redeploy. """ clean = f"{base_name}_clip_{index + 1}.mp4" try: - derived = glob.glob(os.path.join(output_dir, f"subtitled_*_{clean}")) + # subtitled_*_{clean} also matches subtitled__recut__{clean}, + # i.e. a captioned recut; the bare recut_ pattern covers recuts that + # shipped uncaptioned. + derived = (glob.glob(os.path.join(output_dir, f"subtitled_*_{clean}")) + + glob.glob(os.path.join(output_dir, f"recut_*_{clean}"))) except Exception: derived = [] if not derived: @@ -425,6 +431,15 @@ def _reapply_captions(job_id, clip_index, video_path): return None clip = clips[clip_index] import main as _main + # A recut clip is a concatenation of source segments, so the flat + # start..end window is wrong for it — caption against the clip-relative + # remapped transcript instead (same trick /api/subtitle uses). + recipe_segments = (clip.get('recipe') or {}).get('segments') + if recipe_segments: + v_transcript = recut.virtual_transcript(transcript, recipe_segments) + return _main.auto_caption_clip( + video_path, v_transcript, 0.0, + recut.total_duration(recipe_segments)) return _main.auto_caption_clip(video_path, transcript, clip['start'], clip['end']) except Exception as e: @@ -1434,7 +1449,10 @@ async def process_endpoint( layouts: Optional[str] = Form(None), force_low_quality: Optional[str] = Form(None), webhook_url: Optional[str] = Form(None), - webhook_secret: Optional[str] = Form(None) + webhook_secret: Optional[str] = Form(None), + target_clips: Optional[str] = Form(None), + clip_min_seconds: Optional[str] = Form(None), + clip_max_seconds: Optional[str] = Form(None) ): api_key = await resolve_gemini(request) if not api_key: @@ -1454,6 +1472,9 @@ async def process_endpoint( layouts = body.get("layouts") webhook_url = body.get("webhook_url") webhook_secret = body.get("webhook_secret") + target_clips = body.get("target_clips") + clip_min_seconds = body.get("clip_min_seconds") + clip_max_seconds = body.get("clip_max_seconds") # Normalize output format (auto = keep pipeline default). if output_format not in ("vertical", "horizontal", "square"): @@ -1532,9 +1553,47 @@ async def process_endpoint( if chosen: print(f"[layouts] job={job_id} enabled={sorted(chosen)}") + # Manual generation controls (discussion #65): optional clip-count target + # and duration band, forwarded to the selection prompts via the same env + # overrides the A/B harness already reads (clip_selection.py). All three + # are honest TARGETS, not guarantees — the model may return fewer clips + # when the material doesn't hold them. Bad values 400 instead of silently + # producing something the user didn't ask for. + def _gen_control(raw, name, lo, hi, integer=False): + if raw in (None, ""): + return None + try: + val = float(raw) + except (TypeError, ValueError): + raise HTTPException(status_code=400, detail=f"{name} must be a number") + if integer and val != int(val): + raise HTTPException(status_code=400, detail=f"{name} must be an integer") + if not (lo <= val <= hi): + raise HTTPException(status_code=400, + detail=f"{name} must be between {lo:g} and {hi:g}") + return int(val) if integer else val + + n_clips = _gen_control(target_clips, "target_clips", 1, 15, integer=True) + min_secs = _gen_control(clip_min_seconds, "clip_min_seconds", 5, 175) + max_secs = _gen_control(clip_max_seconds, "clip_max_seconds", 10, 180) + if min_secs is not None and max_secs is not None and max_secs < min_secs + 5: + raise HTTPException(status_code=400, + detail="clip_max_seconds must be at least 5s above clip_min_seconds") + if n_clips is not None: + env["CLIP_TARGET_MIN"] = env["CLIP_TARGET_MAX"] = str(n_clips) + if min_secs is not None: + env["CLIP_MIN_SECONDS"] = str(min_secs) + if max_secs is not None: + env["CLIP_MAX_SECONDS"] = str(max_secs) + if n_clips is not None or min_secs is not None or max_secs is not None: + print(f"[gen-controls] job={job_id} clips={n_clips} band={min_secs}-{max_secs}") + input_path = None if url: - cmd.extend(["-u", url]) + # Keep the downloaded source inside the job dir: the clip editor's + # re-render path cuts new segments from it, and it ages out with the + # rest of the job (retention window + OUTPUT_MAX_GB cap) either way. + cmd.extend(["-u", url, "--keep-original"]) else: # Save uploaded file with size limit check. # basename() strips any path components from the client-supplied @@ -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}") async def get_source_video(job_id: str): - """Stream a job's original source video for the live-analysis preview. + """Stream a job's original source video for the live-analysis preview and + the clip editor's source monitor. Uploaded sources are blob URLs in the browser and don't survive a reload, so the recovered session points the preview here instead. Unauthenticated like the /videos mount — the UUID job_id is the capability. """ - matches = [ - f for f in glob.glob(os.path.join(UPLOAD_DIR, f"{job_id}_*")) - if not os.path.basename(f).startswith("thumb_") - ] - if not matches: + source_path = _locate_source(job_id) + if not source_path: raise HTTPException(status_code=404, detail="Source not found") - return FileResponse(matches[0], media_type="video/mp4") + return FileResponse(source_path, media_type="video/mp4") @app.get("/api/jobs/{job_id}/download-all") @@ -2061,8 +2145,16 @@ async def get_clip_transcript(job_id: str, clip_index: int, request: Request): raise HTTPException(status_code=404, detail="Clip not found") clip_data = clips[clip_index] - clip_start = clip_data.get('start', 0) - clip_end = clip_data.get('end', 0) + + # Recut clips are concatenations of source segments; remap the transcript + # onto the clip timeline so every consumer keeps its flat start..end logic. + recipe_segments = (clip_data.get('recipe') or {}).get('segments') + if recipe_segments: + transcript = recut.virtual_transcript(transcript, recipe_segments) + clip_start, clip_end = 0.0, recut.total_duration(recipe_segments) + else: + clip_start = clip_data.get('start', 0) + clip_end = clip_data.get('end', 0) # Extract words within clip range and convert to CaptionWord format captions = [] @@ -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 --- RENDER_SERVICE_URL = os.getenv("RENDER_SERVICE_URL", "http://renderer:3100") @@ -2272,7 +2642,19 @@ async def add_subtitles(req: SubtitleRequest, request: Request): raise HTTPException(status_code=404, detail="Clip not found") clip_data = clips[req.clip_index] - + + # Recut clips concatenate several source segments, so their caption window + # is not the flat start..end range — restyle against the clip-relative + # remapped transcript instead. + recipe_segments = (clip_data.get('recipe') or {}).get('segments') + if recipe_segments: + sub_transcript = recut.virtual_transcript(transcript, recipe_segments) + sub_start, sub_end = 0.0, recut.total_duration(recipe_segments) + else: + sub_transcript = transcript + sub_start = clip_data.get('start', 0) + sub_end = clip_data.get('end', 0) + # Video Path if req.input_filename: # Use chained file @@ -2344,9 +2726,9 @@ async def add_subtitles(req: SubtitleRequest, request: Request): loop = asyncio.get_event_loop() success = await loop.run_in_executor(None, run_transcribe_srt) elif is_karaoke: - success = generate_ass(transcript, clip_data['start'], clip_data['end'], srt_path, **karaoke_opts) + success = generate_ass(sub_transcript, sub_start, sub_end, srt_path, **karaoke_opts) else: - success = generate_srt(transcript, clip_data['start'], clip_data['end'], srt_path) + success = generate_srt(sub_transcript, sub_start, sub_end, srt_path) if not success: raise HTTPException(status_code=400, detail="No words found for this clip range.") diff --git a/clip_selection.py b/clip_selection.py index 03b8c87..b0c4650 100644 --- a/clip_selection.py +++ b/clip_selection.py @@ -67,6 +67,30 @@ def clip_count_targets(n_windows): return low, max(low, high) +def clip_duration_bounds(): + """The clip length band (seconds) the selection prompts and word-snapping + enforce. ``CLIP_MIN_SECONDS`` / ``CLIP_MAX_SECONDS`` override the classic + 15-60 — set per job by /api/process when the user asks for a specific + length, or by hand for A/B runs. Values are clamped to platform-sane + limits and re-ordered so bad input degrades instead of breaking the job. + """ + import os + + def _read(name, default): + try: + return float(os.environ.get(name, "")) + except ValueError: + return default + + lo = _read("CLIP_MIN_SECONDS", 15.0) + hi = _read("CLIP_MAX_SECONDS", 60.0) + lo = min(max(lo, 5.0), 175.0) + hi = min(max(hi, 10.0), 180.0) + if hi < lo + 5.0: # keep a real band: degenerate ranges starve the model + hi = min(180.0, lo + 5.0) + return round(lo, 3), round(hi, 3) + + def compact_words(words, precision=2): """Round word timestamps for prompts — full float precision wastes tokens.""" return [ diff --git a/cloud/videos.py b/cloud/videos.py index 4bac00f..f2d7a87 100644 --- a/cloud/videos.py +++ b/cloud/videos.py @@ -37,6 +37,8 @@ async def archive_job(user_id, job_id, clips, output_dir): except Exception as e: print(f"⚠️ R2 upload failed for {key}: {e}") + base_name = (os.path.basename(meta_files[0]).replace("_metadata.json", "") + if meta_files else None) uploaded = [] # (clip_index, filename, key, title, size_bytes) for i, clip in enumerate(clips): video_url = clip.get("video_url") or "" @@ -54,6 +56,22 @@ async def archive_job(user_id, job_id, clips, output_dir): continue uploaded.append((i, filename, key, _clip_title(clip), os.path.getsize(local_path))) + # Also archive the clean canonical when the served file is a derived + # one (captioned/recut): it is the editable master — the clip editor's + # fast path and /api/subtitle re-styles cut from it, so a project + # restored after a redeploy is only editable if it comes back too. + # Restore downloads every key under the job prefix, so no change is + # needed on that side; the free-retention purge deletes by prefix. + if base_name: + clean = f"{base_name}_clip_{i + 1}.mp4" + clean_path = os.path.join(output_dir, clean) + if clean != filename and os.path.exists(clean_path): + clean_key = storage.job_key(user_id, job_id, clean) + try: + await asyncio.to_thread(storage.upload_file, clean_path, clean_key) + except Exception as e: + print(f"⚠️ R2 upload failed for {clean_key}: {e}") + if not uploaded: return async with database.session() as s: @@ -317,8 +335,17 @@ async def purge_free_expired(): for v in items["videos"]: await asyncio.to_thread(storage.delete_key, v.r2_key) for p in items["projects"]: - if p.metadata_r2_key: - await asyncio.to_thread(storage.delete_key, p.metadata_r2_key) + # Delete everything under the job prefix, not just the metadata + # key: the archive also stores clean canonical clips (which have + # no DB row of their own) and superseded derivatives would + # otherwise leak as orphans. + try: + prefix = storage.job_key(user_id, p.job_id, "") + for key in await asyncio.to_thread(storage.list_keys, prefix): + await asyncio.to_thread(storage.delete_key, key) + except Exception: + if p.metadata_r2_key: + await asyncio.to_thread(storage.delete_key, p.metadata_r2_key) async with database.session() as s: async with s.begin(): if items["videos"]: diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index 33ffdd7..76ef611 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -9,6 +9,7 @@ import ThumbnailStudio from './components/ThumbnailStudio'; import SaaShortsTab from './components/SaaShortsTab'; import UGCGallery from './components/UGCGallery'; import ScheduleWeekModal from './components/ScheduleWeekModal'; +import ClipEditor from './components/ClipEditor'; import UsageMeter from './components/UsageMeter'; import TopUpModal from './components/TopUpModal'; import StarBanner from './components/StarBanner'; @@ -228,6 +229,8 @@ function App() { const [sessionRecovered, setSessionRecovered] = useState(false); const [showScheduleWeek, setShowScheduleWeek] = useState(false); + // Clip editor overlay: index of the clip being edited, or null. + const [editingClip, setEditingClip] = useState(null); // Silent-success "saved" states for the settings key inputs (design.md: no alert popups) const [elevenLabsSaved, setElevenLabsSaved] = useState(false); @@ -280,6 +283,43 @@ function App() { s.timer = setTimeout(flushClipState, 2000); }; + // A recut replaced the clip's server file with a fresh render (burned layers + // reset), so update the results, the reopened-project state and the synced + // per-clip edit state, and let the ResultCard remount from the new file. + const handleClipRerendered = (index, data) => { + const newFile = (data.new_video_url || '').split('/').pop(); + setResults((prev) => { + if (!prev?.clips?.[index]) return prev; + const clips = prev.clips.slice(); + clips[index] = { + ...clips[index], + video_url: data.new_video_url, + start: data.start, + end: data.end, + recipe: data.recipe, + }; + return { ...prev, clips }; + }); + setProjectState((prev) => { + if (!prev?.clips) return prev; + return { + ...prev, + clips: prev.clips.map((c) => (c.index === index + ? { ...c, server_file: newFile, active_layers: null } + : c)), + }; + }); + // 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 // its files from R2 into the server's working dir and returns the full state. const restoreProject = async (projectJobId) => { @@ -607,6 +647,14 @@ function App() { // that apiFetch attaches automatically. const headers = apiKey ? { 'X-Gemini-Key': apiKey } : {}; + // Advanced generation controls: only sent when the user set them, so the + // default request stays byte-identical to the pre-feature one. + const advanced = { + target_clips: data.targetClips || null, + clip_min_seconds: data.clipMinSeconds || null, + clip_max_seconds: data.clipMaxSeconds || null, + }; + if (data.type === 'url') { headers['Content-Type'] = 'application/json'; body = JSON.stringify({ @@ -614,12 +662,16 @@ function App() { acknowledged: !!data.acknowledged, output_format: data.outputFormat || 'auto', force_low_quality: forceLowQuality, + ...Object.fromEntries(Object.entries(advanced).filter(([, v]) => v != null)), }); } else { const formData = new FormData(); formData.append('file', data.payload); formData.append('acknowledged', data.acknowledged ? 'true' : 'false'); formData.append('output_format', data.outputFormat || 'auto'); + for (const [k, v] of Object.entries(advanced)) { + if (v != null) formData.append(k, v); + } body = formData; } @@ -1402,10 +1454,11 @@ function App() {
{results.clips.map((clip, i) => ( setEditingClip(index)} initialState={projectState?.clips?.find((c) => c.index === i) || null} onStateChange={handleClipStateChange} durableUrl={durableClips[i]} @@ -1576,6 +1629,15 @@ function App() { )} + {editingClip !== null && results?.clips?.[editingClip] && ( + setEditingClip(null)} + onRerendered={handleClipRerendered} + /> + )} {showLogin && setShowLogin(false)} />} {showPlanChoice && setShowPlanChoice(false)} />} {showTopUp && ( diff --git a/dashboard/src/components/ClipEditor.jsx b/dashboard/src/components/ClipEditor.jsx new file mode 100644 index 0000000..1fa057b --- /dev/null +++ b/dashboard/src/components/ClipEditor.jsx @@ -0,0 +1,753 @@ +import React, { useState, useEffect, useReducer, useRef, useCallback, useMemo } from 'react'; +import { + X, Loader2, Plus, Trash2, ChevronUp, ChevronDown, Scissors, + AlertCircle, Undo2, Redo2, Film, +} from 'lucide-react'; +import { getApiUrl } from '../config'; +import { apiFetch, apiJson, QuotaError } from '../lib/api'; + +// Full-screen clip editor: shows WHICH source segments a clip was cut from, +// lets the user trim/extend/split/reorder them (word-snapped), and re-renders +// through POST /api/clip/rerender. The recipe (EDL) comes from GET .../edl. + +const MIN_SEGMENT_SECONDS = 0.5; +const SNAP_WINDOW_SECONDS = 0.35; +const WORD_CONTEXT_SECONDS = 15; + +const SEGMENT_COLORS = [ + 'oklch(76% .17 50)', // brass + 'oklch(70% .12 200)', + 'oklch(72% .13 140)', + 'oklch(70% .14 300)', + 'oklch(74% .13 90)', + 'oklch(68% .13 250)', +]; + +function fmt(t) { + if (!Number.isFinite(t)) return '–:––'; + const m = Math.floor(t / 60); + const s = t - m * 60; + return `${m}:${s.toFixed(1).padStart(4, '0')}`; +} + +function totalOf(segments) { + return segments.reduce((acc, s) => acc + (s.end - s.start), 0); +} + +function editorReducer(state, action) { + switch (action.type) { + case 'init': + return { segments: action.segments, selected: 0, past: [], future: [], pendingBase: null }; + case 'select': + return { ...state, selected: action.index }; + // Live drag feedback: replaces segments without touching history; the + // pre-drag snapshot is kept so the whole drag undoes as ONE step. + case 'preview': + return { ...state, segments: action.segments, pendingBase: state.pendingBase || state.segments }; + case 'commit': { + const base = state.pendingBase || state.segments; + return { + ...state, + segments: action.segments, + selected: Math.min(action.select ?? state.selected, action.segments.length - 1), + past: [...state.past, base], + future: [], + pendingBase: null, + }; + } + case 'undo': { + if (!state.past.length) return state; + const prev = state.past[state.past.length - 1]; + return { + ...state, + segments: prev, + selected: Math.min(state.selected, prev.length - 1), + past: state.past.slice(0, -1), + future: [state.segments, ...state.future], + pendingBase: null, + }; + } + case 'redo': { + if (!state.future.length) return state; + const next = state.future[0]; + return { + ...state, + segments: next, + selected: Math.min(state.selected, next.length - 1), + past: [...state.past, state.segments], + future: state.future.slice(1), + pendingBase: null, + }; + } + default: + return state; + } +} + +export default function ClipEditor({ jobId, clipIndex, clipTitle, onClose, onRerendered }) { + const [edl, setEdl] = useState(null); + const [loadError, setLoadError] = useState(null); + const [state, dispatch] = useReducer(editorReducer, { segments: [], selected: 0, past: [], future: [], pendingBase: null }); + const { segments, selected } = state; + + const [snapToWords, setSnapToWords] = useState(true); + const [reapplyCaptions, setReapplyCaptions] = useState(true); + // The recipe of the currently RENDERED preview (playhead maps onto it). + const [renderedSegments, setRenderedSegments] = useState(null); + const [previewUrl, setPreviewUrl] = useState(null); + const [rendering, setRendering] = useState(false); + const [renderSeconds, setRenderSeconds] = useState(0); + const [renderError, setRenderError] = useState(null); + const [confirmClose, setConfirmClose] = useState(false); + const [selectedWord, setSelectedWord] = useState(null); + const [playhead, setPlayhead] = useState(0); + const [showSource, setShowSource] = useState(false); + + const videoRef = useRef(null); + const sourceRef = useRef(null); + const clipTrackRef = useRef(null); + const sourceTrackRef = useRef(null); + const dragRef = useRef(null); + const [ghost, setGhost] = useState(null); // in-progress new segment on the source track + + // ---- load the EDL ------------------------------------------------------- + useEffect(() => { + let cancelled = false; + (async () => { + try { + const data = await apiJson(`/api/clip/${jobId}/${clipIndex}/edl`); + if (cancelled) return; + setEdl(data); + dispatch({ type: 'init', segments: data.segments.map((s) => ({ ...s })) }); + setRenderedSegments(data.segments.map((s) => ({ ...s }))); + setReapplyCaptions(true); + setPreviewUrl(getApiUrl(`/videos/${jobId}/${data.current_file}`)); + } catch (e) { + if (!cancelled) setLoadError(e.detail || e.message || 'could not load the clip recipe'); + } + })(); + return () => { cancelled = true; }; + }, [jobId, clipIndex]); + + const words = useMemo(() => (edl?.words || []), [edl]); + const sourceAvailable = !!edl?.source?.available; + const sourceDuration = edl?.source?.duration || 0; + const canonical = edl?.canonical_range || { start: 0, end: 0 }; + const limits = edl?.limits || { max_segments: 12, min_segment_seconds: MIN_SEGMENT_SECONDS, max_total_seconds: 180 }; + const minSeg = limits.min_segment_seconds || MIN_SEGMENT_SECONDS; + + const total = totalOf(segments); + const dirty = useMemo(() => { + if (!renderedSegments) return false; + return JSON.stringify(segments) !== JSON.stringify(renderedSegments); + }, [segments, renderedSegments]); + + // Trim bounds: with the source gone, cuts must stay inside the range the + // canonical file was rendered from. + const bounds = sourceAvailable + ? { lo: 0, hi: sourceDuration || Infinity } + : { lo: canonical.start, hi: canonical.end }; + + const outOfRange = useCallback( + (seg) => !sourceAvailable && (seg.start < canonical.start - 0.05 || seg.end > canonical.end + 0.05), + [sourceAvailable, canonical], + ); + const needsSourcePath = segments.some((s) => s.start < canonical.start - 0.05 || s.end > canonical.end + 0.05); + const invalidSegments = segments.some(outOfRange); + const overCaps = segments.length > limits.max_segments || total > limits.max_total_seconds; + const canRender = !rendering && segments.length > 0 && !invalidSegments && !overCaps + && segments.every((s) => s.end - s.start >= minSeg); + + // ---- helpers ------------------------------------------------------------ + const snapEdge = useCallback((t, kind) => { + if (!snapToWords || !words.length) return t; + let best = null; + for (const w of words) { + const c = kind === 'start' ? w.s : w.e; + if (Math.abs(c - t) <= SNAP_WINDOW_SECONDS && (best === null || Math.abs(c - t) < Math.abs(best - t))) best = c; + } + return best ?? t; + }, [snapToWords, words]); + + const clampSeg = useCallback((seg) => ({ + start: Math.max(bounds.lo, Math.min(seg.start, seg.end - minSeg)), + end: Math.min(bounds.hi, Math.max(seg.end, seg.start + minSeg)), + }), [bounds.lo, bounds.hi, minSeg]); + + const setSegment = (index, next, { snap = true } = {}) => { + const updated = segments.map((s, i) => { + if (i !== index) return s; + const seg = { ...s, ...next }; + if (snap) { + if (next.start !== undefined) seg.start = snapEdge(seg.start, 'start'); + if (next.end !== undefined) seg.end = snapEdge(seg.end, 'end'); + } + return clampSeg(seg); + }); + dispatch({ type: 'commit', segments: updated, select: index }); + }; + + const addSegment = () => { + if (segments.length >= limits.max_segments) return; + const last = segments[segments.length - 1]; + let start = last ? last.end : bounds.lo; + let end = start + 10; + if (end > bounds.hi) { end = bounds.hi; start = Math.max(bounds.lo, end - 10); } + if (end - start < minSeg) return; + dispatch({ type: 'commit', segments: [...segments, { start: Math.round(start * 1000) / 1000, end: Math.round(end * 1000) / 1000 }], select: segments.length }); + }; + + const deleteSegment = (index) => { + if (segments.length <= 1) return; + dispatch({ type: 'commit', segments: segments.filter((_, i) => i !== index), select: Math.max(0, index - 1) }); + }; + + const moveSegment = (index, dir) => { + const j = index + dir; + if (j < 0 || j >= segments.length) return; + const next = segments.slice(); + [next[index], next[j]] = [next[j], next[index]]; + dispatch({ type: 'commit', segments: next, select: j }); + }; + + const splitSegment = (index) => { + if (segments.length >= limits.max_segments) return; + const seg = segments[index]; + if (seg.end - seg.start < minSeg * 2) return; + let at = seg.start + (seg.end - seg.start) / 2; + // Prefer the playhead when it currently maps inside this segment. + if (!dirty && renderedSegments) { + let offset = 0; + for (let i = 0; i < renderedSegments.length; i += 1) { + const r = renderedSegments[i]; + const len = r.end - r.start; + if (i === index && playhead > offset + minSeg && playhead < offset + len - minSeg) { + at = r.start + (playhead - offset); + } + offset += len; + } + } + at = snapEdge(at, 'end'); + if (at - seg.start < minSeg || seg.end - at < minSeg) at = seg.start + (seg.end - seg.start) / 2; + const next = segments.flatMap((s, i) => (i === index + ? [{ start: s.start, end: Math.round(at * 1000) / 1000 }, { start: Math.round(at * 1000) / 1000, end: s.end }] + : [s])); + dispatch({ type: 'commit', segments: next, select: index }); + }; + + // ---- drag: trim handles on the clip track ------------------------------- + const onDragMove = useCallback((e) => { + const d = dragRef.current; + if (!d) return; + const dt = (e.clientX - d.startX) / d.pxPerSec; + const seg = { ...d.base[d.idx] }; + if (d.edge === 'start') seg.start = Math.max(d.lo, Math.min(seg.start + dt, seg.end - d.minSeg)); + else seg.end = Math.min(d.hi, Math.max(seg.end + dt, seg.start + d.minSeg)); + const next = d.base.map((s, i) => (i === d.idx ? seg : s)); + d.last = { seg, next }; + dispatch({ type: 'preview', segments: next }); + }, []); + + const onDragUp = useCallback(() => { + const d = dragRef.current; + dragRef.current = null; + window.removeEventListener('pointermove', onDragMove); + window.removeEventListener('pointerup', onDragUp); + if (!d || !d.last) return; + const { seg, next } = d.last; + const snapped = { ...seg }; + if (d.edge === 'start') snapped.start = Math.max(d.lo, Math.min(d.snap(seg.start, 'start'), seg.end - d.minSeg)); + else snapped.end = Math.min(d.hi, Math.max(d.snap(seg.end, 'end'), seg.start + d.minSeg)); + dispatch({ type: 'commit', segments: next.map((s, i) => (i === d.idx ? snapped : s)), select: d.idx }); + }, [onDragMove]); + + const startTrimDrag = (e, idx, edge, trackEl, secondsOnTrack) => { + e.preventDefault(); + e.stopPropagation(); + const rect = trackEl?.getBoundingClientRect(); + if (!rect || !secondsOnTrack) return; + dragRef.current = { + idx, edge, startX: e.clientX, pxPerSec: rect.width / secondsOnTrack, + base: segments.map((s) => ({ ...s })), last: null, + lo: bounds.lo, hi: bounds.hi, minSeg, snap: snapEdge, + }; + dispatch({ type: 'select', index: idx }); + window.addEventListener('pointermove', onDragMove); + window.addEventListener('pointerup', onDragUp); + }; + + // ---- drag: paint a NEW segment on the source track ---------------------- + const onGhostMove = useCallback((e) => { + const d = dragRef.current; + if (!d || d.kind !== 'ghost') return; + const t = Math.max(0, Math.min(d.duration, d.t0 + (e.clientX - d.startX) / d.pxPerSec)); + d.range = { start: Math.min(d.t0, t), end: Math.max(d.t0, t) }; + setGhost({ ...d.range }); + }, []); + + const onGhostUp = useCallback(() => { + const d = dragRef.current; + dragRef.current = null; + window.removeEventListener('pointermove', onGhostMove); + window.removeEventListener('pointerup', onGhostUp); + setGhost(null); + if (!d || !d.range) return; + const seg = { + start: Math.round(d.snap(d.range.start, 'start') * 1000) / 1000, + end: Math.round(d.snap(d.range.end, 'end') * 1000) / 1000, + }; + if (seg.end - seg.start < d.minSeg || d.count >= d.maxSegments) return; + d.commit(seg); + }, [onGhostMove]); + + const startGhostDrag = (e) => { + if (!sourceAvailable || !sourceDuration || segments.length >= limits.max_segments) return; + const rect = sourceTrackRef.current?.getBoundingClientRect(); + if (!rect) return; + const t0 = ((e.clientX - rect.left) / rect.width) * sourceDuration; + dragRef.current = { + kind: 'ghost', startX: e.clientX, pxPerSec: rect.width / sourceDuration, + t0, duration: sourceDuration, range: null, snap: snapEdge, minSeg, + count: segments.length, maxSegments: limits.max_segments, + commit: (seg) => dispatch({ type: 'commit', segments: [...segments, seg], select: segments.length }), + }; + window.addEventListener('pointermove', onGhostMove); + window.addEventListener('pointerup', onGhostUp); + }; + + // ---- keyboard ----------------------------------------------------------- + useEffect(() => { + const onKey = (e) => { + const tag = (e.target?.tagName || '').toLowerCase(); + const typing = tag === 'input' || tag === 'textarea' || tag === 'select'; + if (e.key === 'Escape') { + e.preventDefault(); + if (dirty) setConfirmClose(true); else onClose(); + return; + } + if (typing) return; + if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'z') { + e.preventDefault(); + dispatch({ type: e.shiftKey ? 'redo' : 'undo' }); + } else if (e.key === ' ') { + e.preventDefault(); + const v = videoRef.current; + if (v) { if (v.paused) v.play().catch(() => {}); else v.pause(); } + } else if (e.key === 'Backspace' || e.key === 'Delete') { + e.preventDefault(); + deleteSegment(selected); + } else if (e.key.toLowerCase() === 's') { + e.preventDefault(); + splitSegment(selected); + } + }; + window.addEventListener('keydown', onKey); + return () => window.removeEventListener('keydown', onKey); + }); + + // ---- re-render ---------------------------------------------------------- + useEffect(() => { + if (!rendering) return undefined; + setRenderSeconds(0); + const t = setInterval(() => setRenderSeconds((s) => s + 1), 1000); + return () => clearInterval(t); + }, [rendering]); + + const doRender = async () => { + if (!canRender) return; + setRendering(true); + setRenderError(null); + try { + const res = await apiFetch('/api/clip/rerender', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + job_id: jobId, + clip_index: clipIndex, + segments: segments.map((s) => ({ start: s.start, end: s.end })), + snap_to_words: false, // boundaries are already word-snapped client-side + reapply_captions: reapplyCaptions, + }), + }); + if (!res.ok) { + let detail = `re-render failed (HTTP ${res.status})`; + try { detail = (await res.json()).detail || detail; } catch { /* keep fallback */ } + throw new Error(detail); + } + const data = await res.json(); + setRenderedSegments(data.recipe.segments.map((s) => ({ ...s }))); + dispatch({ type: 'init', segments: data.recipe.segments.map((s) => ({ ...s })) }); + setPreviewUrl(`${getApiUrl(data.new_video_url)}?t=${Date.now()}`); + onRerendered?.(clipIndex, data); + } catch (e) { + if (e instanceof QuotaError) { + setRenderError(`not enough minutes left (needs ${e.minutesRequired ?? '?'}, ${e.minutesRemaining ?? 0} remaining)`); + } else { + setRenderError(e.message || 're-render failed'); + } + } finally { + setRendering(false); + } + }; + + // ---- transcript panel data --------------------------------------------- + const selectedSeg = segments[selected] || null; + const panelWords = useMemo(() => { + if (!selectedSeg) return []; + const lo = selectedSeg.start - WORD_CONTEXT_SECONDS; + const hi = selectedSeg.end + WORD_CONTEXT_SECONDS; + return words.filter((w) => w.e >= lo && w.s <= hi); + }, [words, selectedSeg]); + + // ---- render ------------------------------------------------------------- + if (loadError) { + return ( +
+
e.stopPropagation()}> +

EDITOR · CLIP {clipIndex + 1}

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

EDITOR · CLIP {clipIndex + 1}

+

edit clip

+ {clipTitle &&

{clipTitle}

} +
+
+
+

DURATION · {fmt(total)}

+

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

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

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

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

outside the original range — the source video is gone

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

Transcript · segment #{selected + 1}

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

no words near this segment

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

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

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

CLIP · {fmt(total)}

+

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

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

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

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

DRAG ON EMPTY SPACE TO ADD A SEGMENT

+ )} +
+
+ {/* canonical range marker */} + {sourceDuration > 0 && ( +
+ )} + {sourceDuration > 0 && segments.map((seg, i) => ( +
{ e.stopPropagation(); dispatch({ type: 'select', index: i }); }} + className={`absolute top-1 bottom-1 rounded-[4px] cursor-pointer ${i === selected ? 'ring-1 ring-[color:var(--color-accent)]' : ''}`} + style={{ + left: `${(seg.start / sourceDuration) * 100}%`, + width: `${Math.max(((seg.end - seg.start) / sourceDuration) * 100, 0.4)}%`, + background: SEGMENT_COLORS[i % SEGMENT_COLORS.length], + }} + title={`#${i + 1} · ${fmt(seg.start)} → ${fmt(seg.end)}`} + /> + ))} + {ghost && sourceDuration > 0 && ( +
+ )} +
+
+ 0:00 + {fmt(sourceDuration / 2)} + {fmt(sourceDuration)} +
+
+
+
+ ); +} diff --git a/dashboard/src/components/MediaInput.jsx b/dashboard/src/components/MediaInput.jsx index 41f71fe..743c4fa 100644 --- a/dashboard/src/components/MediaInput.jsx +++ b/dashboard/src/components/MediaInput.jsx @@ -1,5 +1,5 @@ import React, { useState, useEffect, useRef } from 'react'; -import { Link2, Upload, FileVideo, X, Info, Loader2 } from 'lucide-react'; +import { Link2, Upload, FileVideo, X, Info, Loader2, ChevronDown } from 'lucide-react'; import { getApiUrl } from '../config'; const SUPPORTED_PLATFORMS = [ @@ -16,6 +16,12 @@ export default function MediaInput({ onProcess, isProcessing }) { const [acknowledged, setAcknowledged] = useState(false); const [outputFormat, setOutputFormat] = useState('vertical'); // vertical | horizontal | square const [showInfo, setShowInfo] = useState(false); + // Advanced generation controls — empty string means "let the AI decide", + // which keeps the default pipeline behavior untouched. + const [showAdvanced, setShowAdvanced] = useState(false); + const [targetClips, setTargetClips] = useState(''); + const [clipMinSeconds, setClipMinSeconds] = useState(''); + const [clipMaxSeconds, setClipMaxSeconds] = useState(''); const infoRef = useRef(null); // Close the compatibility popover on any outside click. @@ -58,10 +64,15 @@ export default function MediaInput({ onProcess, isProcessing }) { const handleSubmit = (e) => { e.preventDefault(); if (!acknowledged) return; + const advanced = { + targetClips: targetClips || null, + clipMinSeconds: clipMinSeconds || null, + clipMaxSeconds: clipMaxSeconds || null, + }; if (mode === 'url' && url) { - onProcess({ type: 'url', payload: url, acknowledged: true, outputFormat }); + onProcess({ type: 'url', payload: url, acknowledged: true, outputFormat, ...advanced }); } else if (mode === 'file' && file) { - onProcess({ type: 'file', payload: file, acknowledged: true, outputFormat }); + onProcess({ type: 'file', payload: file, acknowledged: true, outputFormat, ...advanced }); } }; @@ -210,6 +221,59 @@ export default function MediaInput({ onProcess, isProcessing }) {
+ {/* Advanced generation controls — collapsed by default; blank = AI decides */} +
+ + {showAdvanced && ( +
+
+

clips to aim for

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

min length (s)

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

max length (s)

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

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

+
+ )} +
+