diff --git a/app.py b/app.py index a0f84e5..b6d7ccf 100644 --- a/app.py +++ b/app.py @@ -14,7 +14,7 @@ import itertools import asyncio from datetime import datetime, timezone from dotenv import load_dotenv -from typing import Dict, Optional, List +from typing import Any, Dict, Optional, List from contextlib import asynccontextmanager from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Request, Header, BackgroundTasks from fastapi.middleware.cors import CORSMiddleware @@ -2454,6 +2454,294 @@ async def _rerender_locked(req: RerenderRequest, request: Request, job): raise HTTPException(status_code=500, detail=str(e)) +# --- Manual framing ----------------------------------------------------------- +# +# The reframe engine picks the crop automatically, and on a podcast it is right +# most of the time and grossly wrong occasionally: a wide shot of the whole +# table averages over one face, so the scene falls to GENERAL (letterboxed) or +# tracks the wrong person. There was no way to say "no, frame it here". +# +# The unit is the SCENE, not the clip, because a podcast cuts between a fixed +# close camera and a fixed wide one, and the right crop differs per camera. +# Scene boundaries already are the camera changes: PySceneDetect finds them. +# +# Scenes the user never touches keep the automatic camera, so correcting one +# bad shot cannot spoil the ones the tracker got right. + +class ReframeRequest(BaseModel): + job_id: str + clip_index: int + # scene index (string key, JSON-style) -> either a crop centre as a + # fraction of the source width, or {"top": f, "bottom": f} to stack two + # regions. Fractions travel instead of pixels so the editor never needs to + # know the source dimensions. + crop_overrides: Dict[str, Any] + + +def _clip_scene_workfile(source_path, segments, output_dir, token): + """Cut the clip out of the source so scenes can be detected on it. + + The name is unique per call, unlike the thumbnails and the preview: two + editor opens on the same clip would otherwise write the same temp file at + once, and the first to finish deletes it out from under the second. + """ + work_path = os.path.join(output_dir, f"scenes_{token}.mp4") + recut.run_cut_concat(source_path, segments, work_path, output_dir) + return work_path + + +@app.get("/api/clip/{job_id}/{clip_index}/scenes") +async def get_clip_scenes(job_id: str, clip_index: int, request: Request): + """Scenes of a clip, each with a SOURCE frame to frame it against. + + The frames come from the uncropped cut, not the delivered clip: the point + is to show what the automatic crop threw away, which the 9:16 file no + longer contains. + """ + 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) + # What was applied last time. Without this the editor reopens blank, and + # since a re-render rebuilds from source using ONLY what it is sent, the + # next save would silently drop every earlier adjustment. + saved_overrides = clip.get('crop_overrides') or {} + source_path = _locate_source(job_id) + if not source_path: + raise HTTPException( + status_code=409, + detail="The source video is no longer on the server, so the " + "framing of this clip can no longer be changed.") + + def build(): + import cv2 + import main as m + + # Stable for the files the browser fetches (no accumulation), unique + # for the temp cut (no collision between overlapping requests). + token = str(clip_index) + work_token = f"{clip_index}_{uuid.uuid4().hex[:8]}" + preview_name = f"preview_{clip_index}.mp4" + preview_path = os.path.join(output_dir, preview_name) + work_path = _clip_scene_workfile(source_path, segments, output_dir, work_token) + try: + scenes, fps = m.detect_scenes(work_path) + fps = float(fps) or 30.0 + orig_w, orig_h = m.get_video_resolution(work_path) + + cap = cv2.VideoCapture(work_path) + if not scenes: + total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) or 1 + bounds = [(0, total)] + else: + bounds = [(s.get_frames(), e.get_frames()) for s, e in scenes] + + out = [] + for idx, (start_f, end_f) in enumerate(bounds): + mid = (start_f + end_f) // 2 + cap.set(cv2.CAP_PROP_POS_FRAMES, mid) + ok, frame = cap.read() + thumb_name = f"scene_{token}_{idx:03d}.jpg" + suggested = 0.5 + suggested_y = 0.5 + if ok: + cv2.imwrite(os.path.join(output_dir, thumb_name), frame, + [int(cv2.IMWRITE_JPEG_QUALITY), 80]) + # Start the rectangle on the biggest face in the shot, so + # the common case is a nudge rather than a hunt. + try: + faces = m.detect_face_candidates(frame) + if faces: + box = max(faces, + key=lambda f: f['box'][2] * f['box'][3])['box'] + suggested = min(1.0, max(0.0, + (box[0] + box[2] / 2) / orig_w)) + # SPLIT halves crop vertically too, so the face's + # height matters there (TRACK ignores it). + suggested_y = min(1.0, max(0.0, + (box[1] + box[3] / 2) / orig_h)) + except Exception: + pass + else: + thumb_name = None + + out.append({ + "index": idx, + "start": round(start_f / fps, 3), + "end": round(end_f / fps, 3), + "thumbnail_url": (f"/videos/{job_id}/{thumb_name}" + if thumb_name else None), + "suggested_center": round(suggested, 4), + "suggested_center_y": round(suggested_y, 4), + }) + cap.release() + return orig_w, orig_h, out, preview_name + finally: + # The uncropped cut becomes a light preview instead of being + # discarded: judging the framing means knowing who is talking, and + # the delivered 9:16 file no longer shows the rest of the room. + try: + if os.path.exists(work_path): + subprocess.run( + ["ffmpeg", "-y", "-loglevel", "error", "-i", work_path, + "-vf", "scale=640:-2", "-c:v", "libx264", "-preset", + "veryfast", "-crf", "30", "-c:a", "aac", "-b:a", "96k", + preview_path], check=True) + except Exception as exc: + print(f"Scene preview failed: {exc}") + finally: + if os.path.exists(work_path): + os.remove(work_path) + + try: + loop = asyncio.get_event_loop() + orig_w, orig_h, scenes_out, preview_name = await loop.run_in_executor(None, build) + except Exception as e: + print(f"Scene listing error: {e}") + raise HTTPException(status_code=500, detail=str(e)) + + # Width of the 9:16 window as a fraction of the source width: the editor + # draws the rectangle with it and needs no pixel arithmetic of its own. + crop_w = min(orig_w, orig_h * (9.0 / 16.0)) + return { + "job_id": job_id, + "clip_index": clip_index, + "source_width": orig_w, + "source_height": orig_h, + "crop_width_fraction": round(crop_w / orig_w, 4), + "preview_url": f"/videos/{job_id}/{preview_name}", + "saved_overrides": saved_overrides, + "scenes": scenes_out, + } + + +@app.post("/api/clip/reframe") +async def reframe_clip(req: ReframeRequest, request: Request): + """Re-render a clip with hand-framed scenes, leaving its cut untouched. + + Deliberately separate from /api/clip/rerender: the overrides are keyed by + scene index, and a scene index only means anything against a given cut. If + framing rode along with a trim save, changing the trim would silently move + every override onto the wrong shot. + """ + await require_managed_entitlement(request) + await _ensure_job_files(req.job_id, request) + if req.job_id not in jobs: + raise HTTPException(status_code=404, detail="Job not found") + job = jobs[req.job_id] + await _assert_job_owner(request, job) + + output_dir = os.path.join(OUTPUT_DIR, req.job_id) + json_files = glob.glob(os.path.join(output_dir, "*_metadata.json")) + if not json_files: + raise HTTPException(status_code=404, detail="Metadata not found") + with open(json_files[0], 'r') as f: + data = json.load(f) + + clips = data.get('shorts', []) + if req.clip_index < 0 or req.clip_index >= len(clips): + raise HTTPException(status_code=404, detail="Clip not found") + clip = clips[req.clip_index] + + def _fraction(v): + return min(1.0, max(0.0, float(v))) + + overrides = {} + for key, value in (req.crop_overrides or {}).items(): + try: + idx = int(key) + if isinstance(value, dict): + def _half(h): + if isinstance(h, dict): + return {"x": _fraction(h["x"]), "y": _fraction(h.get("y", 0.5))} + return {"x": _fraction(h), "y": 0.5} + overrides[idx] = {"top": _half(value["top"]), + "bottom": _half(value["bottom"])} + else: + overrides[idx] = _fraction(value) + except (KeyError, TypeError, ValueError): + continue + if not overrides: + raise HTTPException(status_code=400, + detail="No scene framing was provided.") + + segments, canonical_range = _clip_recipe_parts(clip) + source_path = _locate_source(req.job_id) + if not source_path: + raise HTTPException( + status_code=409, + detail="The source video is no longer on the server, so the " + "framing of this clip can no longer be changed.") + + base_name = os.path.basename(json_files[0]).replace('_metadata.json', '') + # The CLEAN base name, exactly as /api/clip/rerender does — never the + # current derived file. perform_recut prefixes whatever it is given, so + # feeding it the newest derivative made every re-render add another + # recut___ in front of the previous one. A few rounds of framing + # and captioning and the path blew past the filesystem limit: + # "Error opening output ...: File name too long". + clean_name = f"{base_name}_clip_{req.clip_index + 1}.mp4" + + lock = _rerender_locks.setdefault(req.job_id, asyncio.Lock()) + async with lock: + def run(): + 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')), + crop_overrides=overrides) + + try: + loop = asyncio.get_event_loop() + served_name, _clean = await loop.run_in_executor(None, run) + + new_video_url = f"/videos/{req.job_id}/{served_name}" + updates = { + 'video_url': new_video_url, + 'crop_overrides': {str(k): v for k, v in overrides.items()}, + } + 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) + # The cut is untouched, but the response mirrors /rerender's shape + # so the dashboard can reuse one handler without clearing the + # clip's timing fields. + return { + "success": True, + "new_video_url": new_video_url, + "recipe": {"v": 1, "segments": segments, + "canonical_range": canonical_range}, + "start": min(s['start'] for s in segments), + "end": max(s['end'] for s in segments), + "framed_scenes": sorted(overrides), + } + except Exception as e: + print(f"Reframe Error: {e}") + raise HTTPException(status_code=500, detail=str(e)) + + # --- Remotion Render Proxy --- RENDER_SERVICE_URL = os.getenv("RENDER_SERVICE_URL", "http://renderer:3100") diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index 76ef611..49eb87d 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -10,6 +10,7 @@ import SaaShortsTab from './components/SaaShortsTab'; import UGCGallery from './components/UGCGallery'; import ScheduleWeekModal from './components/ScheduleWeekModal'; import ClipEditor from './components/ClipEditor'; +import ReframeEditor from './components/ReframeEditor'; import UsageMeter from './components/UsageMeter'; import TopUpModal from './components/TopUpModal'; import StarBanner from './components/StarBanner'; @@ -231,6 +232,7 @@ function App() { const [showScheduleWeek, setShowScheduleWeek] = useState(false); // Clip editor overlay: index of the clip being edited, or null. const [editingClip, setEditingClip] = useState(null); + const [reframingClip, setReframingClip] = useState(null); // Silent-success "saved" states for the settings key inputs (design.md: no alert popups) const [elevenLabsSaved, setElevenLabsSaved] = useState(false); @@ -1459,6 +1461,7 @@ function App() { index={i} jobId={jobId} onEditClip={(index) => setEditingClip(index)} + onReframeClip={(index) => setReframingClip(index)} initialState={projectState?.clips?.find((c) => c.index === i) || null} onStateChange={handleClipStateChange} durableUrl={durableClips[i]} @@ -1638,6 +1641,15 @@ function App() { onRerendered={handleClipRerendered} /> )} + {reframingClip !== null && results?.clips?.[reframingClip] && ( + setReframingClip(null)} + onReframed={handleClipRerendered} + /> + )} {showLogin && setShowLogin(false)} />} {showPlanChoice && setShowPlanChoice(false)} />} {showTopUp && ( diff --git a/dashboard/src/components/ReframeEditor.jsx b/dashboard/src/components/ReframeEditor.jsx new file mode 100644 index 0000000..f832f99 --- /dev/null +++ b/dashboard/src/components/ReframeEditor.jsx @@ -0,0 +1,377 @@ +import React, { useState, useEffect, useCallback, useRef } from 'react'; +import { X, Loader2, Crosshair, RotateCcw, AlertCircle, Play, Pause, Columns2 } from 'lucide-react'; +import { getApiUrl } from '../config'; +import { apiJson } from '../lib/api'; + +// Manual reframing: the automatic crop is right most of the time and grossly +// wrong occasionally, and until now there was no way to say "frame it here". +// +// The unit is the scene, because a podcast cuts between a fixed close camera +// and a fixed wide one and the right crop differs per camera. Scenes the user +// does not touch stay automatic, so fixing one bad shot cannot spoil the good +// ones — only adjusted scenes are sent. +// +// Two things a still frame cannot tell you, and both are handled here: +// - WHO is talking. Each scene plays its own range of an uncropped preview, +// with sound, and the rectangle stays overlaid while it plays. +// - Whether one window is even enough. A scene can be split into two stacked +// regions, positioned independently. + +const fmt = (s) => { + const m = Math.floor(s / 60); + const r = Math.floor(s % 60); + return `${m}:${String(r).padStart(2, '0')}`; +}; + +export default function ReframeEditor({ jobId, clipIndex, clipTitle, onClose, onReframed }) { + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [data, setData] = useState(null); + const [overrides, setOverrides] = useState({}); // idx -> number | {top,bottom} + const [playing, setPlaying] = useState(null); // scene index being played + const [saving, setSaving] = useState(false); + + useEffect(() => { + let alive = true; + (async () => { + try { + const res = await apiJson(`/api/clip/${jobId}/${clipIndex}/scenes`); + if (!alive) return; + setData(res); + // Start from what is already applied. A re-render rebuilds + // from source with only what it receives, so opening blank + // would quietly discard every earlier adjustment on the next + // save. + const salvos = res.saved_overrides || {}; + setOverrides(Object.fromEntries( + Object.entries(salvos).map(([k, v]) => [Number(k), v]) + )); + } catch (e) { + if (alive) setError(e?.message || 'Could not read the scenes of this clip.'); + } finally { + if (alive) setLoading(false); + } + })(); + return () => { alive = false; }; + }, [jobId, clipIndex]); + + const half = (data?.crop_width_fraction ?? 0.5) / 2; + const clamp = useCallback((v) => Math.min(1 - half, Math.max(half, v)), [half]); + + // What a scene shows right now: the user's value, else the backend's + // suggestion (the biggest face in the shot). + const valueOf = useCallback((scene) => ( + overrides[scene.index] ?? clamp(scene.suggested_center) + ), [overrides, clamp]); + + const setSingle = useCallback((idx, fraction) => { + setOverrides((o) => ({ ...o, [idx]: clamp(fraction) })); + }, [clamp]); + + const setSplitHalf = useCallback((idx, which, fraction) => { + setOverrides((o) => { + const cur = o[idx]; + const base = (cur && typeof cur === 'object') + ? cur + : { top: { x: clamp(0.3), y: 0.5 }, bottom: { x: clamp(0.7), y: 0.5 } }; + const anterior = base[which] || { y: 0.5 }; + return { ...o, [idx]: { + ...base, + [which]: { x: clamp(fraction), y: anterior.y ?? 0.5 }, + } }; + }); + }, [clamp]); + + const toggleSplit = useCallback((idx, scene) => { + setOverrides((o) => { + const cur = o[idx]; + if (cur && typeof cur === 'object') { + // back to a single window, kept where the top half was + return { ...o, [idx]: cur.top?.x ?? 0.5 }; + } + const centre = typeof cur === 'number' ? cur : clamp(scene.suggested_center); + // SPLIT halves crop vertically as well, so each carries the face + // height the backend measured for this scene. + const y = scene.suggested_center_y ?? 0.5; + return { ...o, [idx]: { + top: { x: clamp(centre - 0.2), y }, + bottom: { x: clamp(centre + 0.2), y }, + } }; + }); + }, [clamp]); + + const resetScene = useCallback((idx) => { + setOverrides((o) => { + const next = { ...o }; + delete next[idx]; + return next; + }); + }, []); + + const adjusted = Object.keys(overrides).length; + + const handleSave = async () => { + if (!adjusted || saving) return; + setSaving(true); + setError(null); + try { + const payload = Object.fromEntries(Object.entries(overrides).map(([k, v]) => [ + String(k), + typeof v === 'object' + ? { top: { x: Number(v.top.x.toFixed(4)), y: Number(v.top.y.toFixed(4)) }, + bottom: { x: Number(v.bottom.x.toFixed(4)), y: Number(v.bottom.y.toFixed(4)) } } + : Number(v.toFixed(4)), + ])); + const res = await apiJson('/api/clip/reframe', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ job_id: jobId, clip_index: clipIndex, crop_overrides: payload }), + }); + if (onReframed) onReframed(clipIndex, res); + onClose(); + } catch (e) { + setError(e?.message || 'The re-render failed.'); + } finally { + setSaving(false); + } + }; + + return ( +
+
+
+
+ +
+

reframing

+ {clipTitle &&

{clipTitle}

} +
+
+ +
+ +
+

+ Play a scene to hear who is talking, then drag the rectangle over + the person you want. Each scene is one camera. Scenes you leave + alone keep the automatic camera. +

+ + {loading && ( +
+ + reading the scenes… +
+ )} + + {error && ( +
+ + {error} +
+ )} + + {data?.scenes?.map((scene) => ( + setPlaying((p) => (p === scene.index ? null : scene.index))} + onMoveSingle={(f) => setSingle(scene.index, f)} + onMoveHalf={(which, f) => setSplitHalf(scene.index, which, f)} + onToggleSplit={() => toggleSplit(scene.index, scene)} + onReset={() => resetScene(scene.index)} + /> + ))} +
+ +
+ + {adjusted === 0 + ? 'nothing adjusted yet' + : `${adjusted} scene${adjusted > 1 ? 's' : ''} reframed by hand`} + +
+ + +
+
+
+
+ ); +} + + +// One scene. While it plays, the frame is replaced by the uncropped preview +// seeked to this scene, so the rectangle can be judged against moving pictures +// and sound rather than a single still. +function SceneRow({ scene, value, widthFraction, previewUrl, touched, playing, + onPlayToggle, onMoveSingle, onMoveHalf, onToggleSplit, onReset }) { + const boxRef = useRef(null); + const videoRef = useRef(null); + const [dragging, setDragging] = useState(null); // null | 'single' | 'top' | 'bottom' + + const isSplit = value && typeof value === 'object'; + + // Play only this scene's slice of the shared preview. + useEffect(() => { + const v = videoRef.current; + if (!v) return; + if (!playing) { v.pause(); return; } + v.currentTime = scene.start; + v.play().catch(() => {}); + const stopAtEnd = () => { if (v.currentTime >= scene.end) { v.pause(); } }; + v.addEventListener('timeupdate', stopAtEnd); + return () => v.removeEventListener('timeupdate', stopAtEnd); + }, [playing, scene.start, scene.end]); + + const fractionFromEvent = useCallback((clientX) => { + const el = boxRef.current; + if (!el) return 0.5; + const rect = el.getBoundingClientRect(); + return (clientX - rect.left) / rect.width; + }, []); + + useEffect(() => { + if (!dragging) return; + const move = (e) => { + const x = e.touches ? e.touches[0].clientX : e.clientX; + const f = fractionFromEvent(x); + if (dragging === 'single') onMoveSingle(f); + else onMoveHalf(dragging, f); + }; + const up = () => setDragging(null); + window.addEventListener('mousemove', move); + window.addEventListener('mouseup', up); + window.addEventListener('touchmove', move); + window.addEventListener('touchend', up); + return () => { + window.removeEventListener('mousemove', move); + window.removeEventListener('mouseup', up); + window.removeEventListener('touchmove', move); + window.removeEventListener('touchend', up); + }; + }, [dragging, fractionFromEvent, onMoveSingle, onMoveHalf]); + + const startDrag = (which) => (e) => { + e.stopPropagation(); + setDragging(which); + const x = e.touches ? e.touches[0].clientX : e.clientX; + if (which === 'single') onMoveSingle(fractionFromEvent(x)); + else onMoveHalf(which, fractionFromEvent(x)); + }; + + const win = (centre, label, which) => { + const leftPct = (centre - widthFraction / 2) * 100; + return ( +
+ {label && ( + + {label} + + )} +
+ ); + }; + + return ( +
+
+
+ + + scene {scene.index + 1} · {fmt(scene.start)}–{fmt(scene.end)} + +
+
+ + {touched ? ( + + ) : ( + automatic + )} +
+
+ +
+ {playing && previewUrl ? ( +