feat: manual reframing, per scene
The reframe engine picks the crop automatically and is right most of the
time. When it is wrong it is badly wrong, and there was no way to say
"no, frame it here".
The unit is the SCENE, not the clip. A podcast cuts between a fixed close
camera and a fixed wide one, and the right crop differs per camera; scene
boundaries already are those camera changes. Scenes the user never touches
keep the automatic camera, so correcting one bad shot cannot spoil the
shots the tracker got right.
Backend:
- reframe_v2.apply_crop_overrides() replaces a scene's slice of the camera
trajectory with a constant and forces it to TRACK, so a scene the
classifier had sent to GENERAL comes back to a vertical crop. It runs
after every automatic pass, including the ALTERNATE writes, so a manual
choice always wins.
- A scene can also be split by hand: the override writes straight into
`splits`, which means the user can stack a scene the detector never
proposed, with no dependency on SPLIT_LAYOUT being enabled.
- GET /api/clip/{job}/{i}/scenes returns the scenes with a frame from the
UNCROPPED cut plus a light preview with audio, and suggests a centre from
the largest face in each shot.
- POST /api/clip/reframe re-renders with the clip's cut untouched. It is
deliberately separate from /api/clip/rerender: a scene index only means
something against a given cut, so letting framing ride along with a trim
save would move every override onto the wrong shot.
- render_clip raises instead of falling back to the v1 engine when manual
framing is present, since v1 ignores it and would silently return an
automatically framed clip.
Frontend:
- ReframeEditor lists the scenes, each with the source frame, a draggable
9:16 window, and a play button that plays that scene from the preview so
the user can hear who is talking before choosing.
- Saved overrides are loaded when the editor reopens. Without that the next
save would discard every earlier adjustment, because a re-render rebuilds
from source using only what it receives.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
parent
4611ca119b
commit
b92012d824
7 changed files with 814 additions and 11 deletions
290
app.py
290
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_<ts>_<hex>_ 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")
|
||||
|
||||
|
|
|
|||
|
|
@ -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] && (
|
||||
<ReframeEditor
|
||||
jobId={jobId}
|
||||
clipIndex={reframingClip}
|
||||
clipTitle={results.clips[reframingClip].video_title_for_youtube_short || ''}
|
||||
onClose={() => setReframingClip(null)}
|
||||
onReframed={handleClipRerendered}
|
||||
/>
|
||||
)}
|
||||
{showLogin && <LoginModal onClose={() => setShowLogin(false)} />}
|
||||
{showPlanChoice && <PlanChoiceModal onClose={() => setShowPlanChoice(false)} />}
|
||||
{showTopUp && (
|
||||
|
|
|
|||
377
dashboard/src/components/ReframeEditor.jsx
Normal file
377
dashboard/src/components/ReframeEditor.jsx
Normal file
|
|
@ -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 (
|
||||
<div className="fixed inset-0 z-50 bg-black/80 flex items-center justify-center p-4">
|
||||
<div className="card w-full max-w-3xl max-h-[90vh] flex flex-col">
|
||||
<div className="flex items-center justify-between p-4 border-b border-rule">
|
||||
<div className="flex items-center gap-2.5 min-w-0">
|
||||
<Crosshair size={18} className="text-brass shrink-0" />
|
||||
<div className="min-w-0">
|
||||
<h2 className="text-base font-medium text-ink lowercase truncate">reframing</h2>
|
||||
{clipTitle && <p className="text-xs text-muted truncate">{clipTitle}</p>}
|
||||
</div>
|
||||
</div>
|
||||
<button onClick={onClose} className="p-1.5 hover:bg-paper3 rounded-input transition-colors">
|
||||
<X size={18} className="text-muted" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-4 space-y-5">
|
||||
<p className="text-xs text-muted leading-relaxed">
|
||||
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.
|
||||
</p>
|
||||
|
||||
{loading && (
|
||||
<div className="flex items-center gap-2 text-sm text-muted py-8 justify-center">
|
||||
<Loader2 size={18} className="animate-spin text-brass" />
|
||||
reading the scenes…
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="flex items-start gap-2 text-xs text-warn border border-warn/40 rounded-input p-3">
|
||||
<AlertCircle size={14} className="shrink-0 mt-0.5" />
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{data?.scenes?.map((scene) => (
|
||||
<SceneRow
|
||||
key={scene.index}
|
||||
scene={scene}
|
||||
value={valueOf(scene)}
|
||||
widthFraction={data.crop_width_fraction}
|
||||
previewUrl={data.preview_url}
|
||||
touched={scene.index in overrides}
|
||||
playing={playing === scene.index}
|
||||
onPlayToggle={() => 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)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between gap-3 p-4 border-t border-rule">
|
||||
<span className="text-xs text-muted">
|
||||
{adjusted === 0
|
||||
? 'nothing adjusted yet'
|
||||
: `${adjusted} scene${adjusted > 1 ? 's' : ''} reframed by hand`}
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<button onClick={onClose} className="btn-quiet py-2 px-4 text-sm">cancel</button>
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={!adjusted || saving}
|
||||
className="btn-primary py-2 px-4 text-sm disabled:opacity-40"
|
||||
>
|
||||
{saving ? <Loader2 size={16} className="animate-spin" /> : null}
|
||||
{saving ? 're-rendering…' : 'apply reframing'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
// 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 (
|
||||
<div
|
||||
key={which}
|
||||
onMouseDown={startDrag(which)}
|
||||
onTouchStart={startDrag(which)}
|
||||
className="absolute inset-y-0 border-2 border-brass cursor-ew-resize"
|
||||
style={{ left: `${leftPct}%`, width: `${widthFraction * 100}%` }}
|
||||
>
|
||||
{label && (
|
||||
<span className="absolute top-1 left-1 text-[10px] px-1 rounded bg-brass text-paper lowercase">
|
||||
{label}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center justify-between text-xs gap-2">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<button
|
||||
onClick={onPlayToggle}
|
||||
className="flex items-center gap-1 text-ink2 hover:text-brass transition-colors"
|
||||
title="play this scene with sound"
|
||||
>
|
||||
{playing ? <Pause size={13} /> : <Play size={13} />}
|
||||
</button>
|
||||
<span className="readout text-muted truncate">
|
||||
scene {scene.index + 1} · {fmt(scene.start)}–{fmt(scene.end)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 shrink-0">
|
||||
<button
|
||||
onClick={onToggleSplit}
|
||||
className={`flex items-center gap-1 transition-colors ${
|
||||
isSplit ? 'text-brass' : 'text-muted hover:text-ink2'}`}
|
||||
title="stack two regions instead of one window"
|
||||
>
|
||||
<Columns2 size={12} /> split
|
||||
</button>
|
||||
{touched ? (
|
||||
<button onClick={onReset} className="flex items-center gap-1 text-brass hover:underline">
|
||||
<RotateCcw size={12} /> automatic
|
||||
</button>
|
||||
) : (
|
||||
<span className="text-muted">automatic</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
ref={boxRef}
|
||||
className={`relative overflow-hidden rounded-input select-none border ${
|
||||
touched ? 'border-brass' : 'border-rule'}`}
|
||||
>
|
||||
{playing && previewUrl ? (
|
||||
<video
|
||||
ref={videoRef}
|
||||
src={getApiUrl(previewUrl)}
|
||||
playsInline
|
||||
className="w-full block"
|
||||
/>
|
||||
) : scene.thumbnail_url ? (
|
||||
<img
|
||||
src={getApiUrl(scene.thumbnail_url)}
|
||||
alt=""
|
||||
draggable={false}
|
||||
className="w-full block pointer-events-none"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-full aspect-video bg-paper3" />
|
||||
)}
|
||||
|
||||
{/* Everything outside the kept region is dimmed, so what survives
|
||||
the crop is what stays bright. */}
|
||||
{!isSplit && (
|
||||
<>
|
||||
<div className="absolute inset-y-0 left-0 bg-black/65 pointer-events-none"
|
||||
style={{ width: `${Math.max(0, (value - widthFraction / 2) * 100)}%` }} />
|
||||
<div className="absolute inset-y-0 right-0 bg-black/65 pointer-events-none"
|
||||
style={{ width: `${Math.max(0, 100 - (value + widthFraction / 2) * 100)}%` }} />
|
||||
</>
|
||||
)}
|
||||
|
||||
{isSplit
|
||||
? [win(value.top.x, 'top', 'top'), win(value.bottom.x, 'bottom', 'bottom')]
|
||||
: win(value, null, 'single')}
|
||||
</div>
|
||||
|
||||
{isSplit && (
|
||||
<p className="text-[11px] text-muted leading-snug">
|
||||
Two regions stacked in the vertical frame: <strong>top</strong> above,
|
||||
<strong> bottom</strong> below. Drag each one onto the person it should hold.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import React, { useState, useEffect } from 'react';
|
||||
import { Download, Share2, Instagram, Youtube, Video, AlertCircle, Loader2, Copy, Check, Wand2, Type, Calendar, Languages, FileText, Link2, Scissors } from 'lucide-react';
|
||||
import { Download, Share2, Instagram, Youtube, Video, AlertCircle, Loader2, Copy, Check, Wand2, Type, Calendar, Languages, FileText, Link2, Scissors, Crosshair } from 'lucide-react';
|
||||
import { getApiUrl } from '../config';
|
||||
import { apiFetch } from '../lib/api';
|
||||
import SubtitleModal from './SubtitleModal';
|
||||
|
|
@ -35,7 +35,7 @@ function formatDuration(clip) {
|
|||
return `${String(Math.floor(secs / 60)).padStart(2, '0')}:${String(secs % 60).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostKey, uploadUserId, geminiApiKey, elevenLabsKey, isManaged, onPlay, onPause, onBulkSubtitle, clipCount = 1, bulkProgress, initialState = null, onStateChange, connectedPlatforms = null, onConnectSocials, onEditClip = null }) {
|
||||
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, onReframeClip = null }) {
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
const [showDescModal, setShowDescModal] = useState(false);
|
||||
const [showSubtitleModal, setShowSubtitleModal] = useState(false);
|
||||
|
|
@ -732,6 +732,16 @@ export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostK
|
|||
</button>
|
||||
)}
|
||||
|
||||
{onReframeClip && (
|
||||
<button
|
||||
onClick={() => onReframeClip(index)}
|
||||
className={QUIET_BTN}
|
||||
>
|
||||
<Crosshair size={16} className="text-muted group-hover:text-brass transition-colors shrink-0" />
|
||||
reframing
|
||||
</button>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={handleAutoEdit}
|
||||
disabled={isEditing}
|
||||
|
|
|
|||
20
main.py
20
main.py
|
|
@ -882,13 +882,15 @@ def auto_caption_clip(clip_path, transcript, clip_start, clip_end):
|
|||
return None
|
||||
|
||||
|
||||
def render_clip(input_video, final_output_video, output_format="auto"):
|
||||
def render_clip(input_video, final_output_video, output_format="auto",
|
||||
crop_overrides=None):
|
||||
"""Route a cut clip through the right renderer for the chosen output format.
|
||||
vertical/auto -> 9:16 reframe, square -> 1:1 reframe, horizontal -> keep."""
|
||||
if output_format == "horizontal":
|
||||
return finalize_clip_passthrough(input_video, final_output_video)
|
||||
aspect = 1.0 if output_format == "square" else ASPECT_RATIO
|
||||
return process_video_to_vertical(input_video, final_output_video, aspect_ratio=aspect)
|
||||
return process_video_to_vertical(input_video, final_output_video, aspect_ratio=aspect,
|
||||
crop_overrides=crop_overrides)
|
||||
|
||||
|
||||
# Watermark geometry, as fractions of the clip width/height.
|
||||
|
|
@ -956,7 +958,8 @@ def apply_watermark(video_path):
|
|||
return False
|
||||
|
||||
|
||||
def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPECT_RATIO):
|
||||
def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPECT_RATIO,
|
||||
crop_overrides=None):
|
||||
"""
|
||||
Core logic to reframe a horizontal video to a target aspect ratio using
|
||||
scene detection and Active Speaker Tracking (MediaPipe).
|
||||
|
|
@ -970,10 +973,19 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE
|
|||
try:
|
||||
import reframe_v2
|
||||
t0 = time.time()
|
||||
result = reframe_v2.render(input_video, final_output_video, aspect_ratio)
|
||||
result = reframe_v2.render(input_video, final_output_video, aspect_ratio,
|
||||
crop_overrides=crop_overrides)
|
||||
print(f" ⏱️ Reframe v2 total: {time.time() - t0:.1f}s")
|
||||
return result
|
||||
except Exception as e:
|
||||
# Only v2 honours hand-framed scenes. Falling through to v1 would
|
||||
# quietly return an automatically framed clip, and the user would
|
||||
# see their correction vanish with no reason given — so surface the
|
||||
# failure instead of silently discarding their input.
|
||||
if crop_overrides:
|
||||
raise RuntimeError(
|
||||
f"manual framing needs the v2 reframe engine, which failed "
|
||||
f"({type(e).__name__}: {e})") from e
|
||||
print(f" ⚠️ Reframe v2 failed ({type(e).__name__}: {e}) — "
|
||||
f"falling back to v1 frame loop")
|
||||
|
||||
|
|
|
|||
14
recut.py
14
recut.py
|
|
@ -260,8 +260,8 @@ def _run_ffmpeg(command):
|
|||
|
||||
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):
|
||||
captions_transcript=None, crop_overrides=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
|
||||
|
|
@ -274,6 +274,10 @@ def perform_recut(*, input_path, segments, output_dir, clean_name,
|
|||
``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.
|
||||
- ``crop_overrides``: scene index -> crop centre as a fraction of the
|
||||
source width, for scenes the user framed by hand. Source path only, for
|
||||
the same reason as ``reframe``: the canonical file is already cropped, so
|
||||
its framing can no longer be changed.
|
||||
|
||||
The renderer/watermarker/captioner hooks default to main.py's
|
||||
implementations, imported lazily so this module stays importable without
|
||||
|
|
@ -293,7 +297,11 @@ def perform_recut(*, input_path, segments, output_dir, clean_name,
|
|||
|
||||
if reframe:
|
||||
render = renderer or _main_attr("render_clip")
|
||||
if not render(work_path, out_path, output_format):
|
||||
# Passed only when there is something to pass: injected test
|
||||
# renderers take the three positional arguments and would break on
|
||||
# an unexpected keyword.
|
||||
extra = {"crop_overrides": crop_overrides} if crop_overrides else {}
|
||||
if not render(work_path, out_path, output_format, **extra):
|
||||
raise RuntimeError("reframe failed on the recut clip")
|
||||
else:
|
||||
shutil.move(work_path, out_path)
|
||||
|
|
|
|||
|
|
@ -147,6 +147,88 @@ def general_filtergraph(out_w, out_h, content_h=None):
|
|||
|
||||
# --- analysis ---------------------------------------------------------------
|
||||
|
||||
def apply_crop_overrides(xs, strategies, scene_boundaries, overrides,
|
||||
crop_w, orig_w, orig_h=None, splits=None):
|
||||
"""Frame the scenes the user positioned by hand.
|
||||
|
||||
``overrides`` maps a scene index to either
|
||||
|
||||
* a number — the crop CENTRE as a fraction of the source width, giving a
|
||||
single locked 9:16 window for that scene; or
|
||||
* ``{"top": v, "bottom": v}`` — two centres, stacking those two regions
|
||||
one above the other (the SPLIT layout). Each half is either a bare
|
||||
fraction (horizontal only) or ``{"x": f, "y": f}``; SPLIT crops are
|
||||
SHORTER than the source, so they carry a vertical centre too.
|
||||
|
||||
Fractions travel instead of pixels because the editor knows where it
|
||||
dropped the rectangle, not the source's dimensions, and the same number
|
||||
survives a source re-encode at another resolution.
|
||||
|
||||
A hand-framed scene overrides its automatic verdict outright: the single
|
||||
form forces TRACK so a scene the detector had sent to GENERAL (blurred
|
||||
background) comes back to a vertical crop, and the split form writes
|
||||
straight into ``splits``, so the user can stack a scene the detector never
|
||||
proposed — no dependency on SPLIT_LAYOUT being switched on.
|
||||
|
||||
Runs after every automatic pass, including the ALTERNATE writes, so a
|
||||
manual choice always wins. Unknown scene indices and malformed values are
|
||||
skipped rather than rejected: a stale editor tab must not fail the render.
|
||||
"""
|
||||
max_x = max(0, orig_w - crop_w)
|
||||
|
||||
def to_x(fraction):
|
||||
return max(0, min(int(round(float(fraction) * orig_w - crop_w / 2)), max_x))
|
||||
|
||||
for raw_idx, value in (overrides or {}).items():
|
||||
try:
|
||||
idx = int(raw_idx)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if not 0 <= idx < len(scene_boundaries):
|
||||
continue
|
||||
start_f, end_f = scene_boundaries[idx]
|
||||
end_f = min(end_f, len(xs))
|
||||
if end_f <= start_f:
|
||||
continue
|
||||
|
||||
if isinstance(value, dict):
|
||||
# Split: the halves are centres in SOURCE PIXELS, which is what
|
||||
# split_filtergraph expects — unlike the single-crop path, there is
|
||||
# no crop window to offset by.
|
||||
# split_geometry reads centre[0]/centre[1]: each half is a POINT,
|
||||
# not a horizontal position, because its crop is shorter than the
|
||||
# source and has to be placed vertically as well.
|
||||
def point(half):
|
||||
if isinstance(half, dict):
|
||||
fx, fy = float(half['x']), float(half.get('y', 0.5))
|
||||
else:
|
||||
fx, fy = float(half), 0.5
|
||||
return (fx * orig_w, fy * orig_h)
|
||||
|
||||
try:
|
||||
centres = (point(value['top']), point(value['bottom']))
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
if splits is None or not orig_h:
|
||||
continue
|
||||
splits[start_f] = centres
|
||||
strategies[idx] = 'SPLIT'
|
||||
continue
|
||||
|
||||
try:
|
||||
x = to_x(value)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
xs[start_f:end_f] = [x] * (end_f - start_f)
|
||||
strategies[idx] = 'TRACK'
|
||||
# A scene taken over by a single locked crop must not also carry a
|
||||
# stale split recipe from the detector.
|
||||
if splits is not None:
|
||||
splits.pop(start_f, None)
|
||||
|
||||
return xs, strategies
|
||||
|
||||
|
||||
def _analyze_trajectory(input_video, scenes_boundaries, scene_strategies,
|
||||
fps, orig_w, orig_h, cameraman, tracker):
|
||||
"""Replays v1's per-frame decision loop on a downscaled ffmpeg-decoded
|
||||
|
|
@ -230,12 +312,18 @@ def _run(cmd):
|
|||
stderr=subprocess.PIPE, timeout=1800)
|
||||
|
||||
|
||||
def render(input_video, final_output_video, aspect_ratio, content_ranges=None):
|
||||
def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
|
||||
crop_overrides=None):
|
||||
"""Full v2 reframe of one clip. Raises on failure (caller falls back).
|
||||
|
||||
``content_ranges`` comes from screencast_layout.detect_content_ranges() on
|
||||
the SOURCE video, already translated into this clip's timeline. None or []
|
||||
means the layout never triggers, which is the default.
|
||||
|
||||
``crop_overrides`` maps scene index -> crop centre as a fraction of the
|
||||
source width, for scenes the user framed by hand in the editor. Scenes not
|
||||
listed keep the automatic camera, so correcting one bad shot never disturbs
|
||||
the ones the tracker got right.
|
||||
"""
|
||||
import main as m
|
||||
content_ranges = content_ranges or []
|
||||
|
|
@ -372,6 +460,14 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None):
|
|||
xs[start_f:end_f] = active_speaker.speaker_xs(
|
||||
held, centres, crop_w, orig_w, end_f - start_f, fps)
|
||||
|
||||
# Last word on the trajectory: a scene the user framed by hand beats every
|
||||
# automatic verdict above, including the ALTERNATE writes.
|
||||
if crop_overrides:
|
||||
xs, strategies = apply_crop_overrides(
|
||||
xs, strategies, scene_boundaries, crop_overrides, crop_w,
|
||||
orig_w, orig_h=orig_h, splits=splits)
|
||||
print(f" ✋ Manual framing on {len(crop_overrides)} scene(s)")
|
||||
|
||||
ranges = scene_frame_ranges(scene_boundaries, strategies, len(xs))
|
||||
if not ranges:
|
||||
raise RuntimeError("no usable scene ranges")
|
||||
|
|
|
|||
Loading…
Reference in a new issue