Merge PR #70 (manual per-scene reframing) onto current main

Conflicts were the parallel override parameters: render_clip /
process_video_to_vertical / reframe_v2.render / perform_recut now carry
BOTH force_strategy (whole-clip framing, main) and crop_overrides
(per-scene manual framing, PR #70). The v1-fallback safety net now also
raises for force_strategy, which had the same silent-revert hole the PR
fixed for crop_overrides.
This commit is contained in:
juancarlos.cavero 2026-08-19 12:01:02 +02:00
commit 0bfe27561d
12 changed files with 876 additions and 15 deletions

290
app.py
View file

@ -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
@ -2491,6 +2491,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")

View file

@ -0,0 +1,49 @@
Metadata-Version: 2.4
Name: openshorts
Version: 0.1.0
Summary: CLI for OpenShorts: clip long videos into vertical shorts and publish them, from the terminal
Author: OpenShorts
License: MIT
Project-URL: Homepage, https://www.openshorts.app
Project-URL: Source, https://github.com/mutonby/openshorts
Project-URL: Documentation, https://www.openshorts.app/mcp
Keywords: video,clips,shorts,ai,tiktok,youtube-shorts,cli
Classifier: Environment :: Console
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Multimedia :: Video
Requires-Python: >=3.9
Description-Content-Type: text/markdown
# OpenShorts CLI
Clip long videos into vertical 9:16 shorts from the terminal. Zero
dependencies; talks to the same API the dashboard, the MCP server and the
webhooks use.
```bash
pip install openshorts # or: uvx openshorts / pipx run openshorts
export OPENSHORTS_API_KEY=osk_... # from your account page at openshorts.app
openshorts process "https://youtube.com/watch?v=..." --wait
openshorts clips <job_id>
openshorts publish <job_id> 0 --platforms tiktok,youtube
openshorts quota
```
Self-hosted instance? Point it at your own machine and skip the key:
```bash
export OPENSHORTS_API_URL=http://localhost:8000
openshorts process "https://youtube.com/watch?v=..." --wait
```
For pipelines, prefer the webhook to `--wait`: pass `--webhook` and
`--webhook-secret` and OpenShorts POSTs once (HMAC-signed,
`X-OpenShorts-Signature: sha256=<hex>`) when the job ends, with clip titles
and durable download links.
The hosted free tier is 20 minutes/month with a watermark; paid plans from
$12/month. The self-hosted edition is MIT and has no meter. Agent-native
version of the same surface: [openshorts.app/mcp](https://www.openshorts.app/mcp).

View file

@ -0,0 +1,8 @@
README.md
openshorts_cli.py
pyproject.toml
openshorts.egg-info/PKG-INFO
openshorts.egg-info/SOURCES.txt
openshorts.egg-info/dependency_links.txt
openshorts.egg-info/entry_points.txt
openshorts.egg-info/top_level.txt

View file

@ -0,0 +1 @@

View file

@ -0,0 +1,2 @@
[console_scripts]
openshorts = openshorts_cli:main

View file

@ -0,0 +1 @@
openshorts_cli

View file

@ -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 && (

View 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>
);
}

View file

@ -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);
@ -735,6 +735,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}

27
main.py
View file

@ -883,16 +883,19 @@ def auto_caption_clip(clip_path, transcript, clip_start, clip_end):
def render_clip(input_video, final_output_video, output_format="auto",
force_strategy=None):
force_strategy=None, 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.
``force_strategy`` (e.g. 'WIDE'/'TRACK') pins every scene's layout — the
clip editor's manual framing override."""
clip editor's whole-clip framing override. ``crop_overrides`` positions
individual scenes by hand (the per-scene reframing editor) and wins over
``force_strategy`` for the scenes it names."""
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,
force_strategy=force_strategy)
force_strategy=force_strategy,
crop_overrides=crop_overrides)
# Watermark geometry, as fractions of the clip width/height.
@ -961,13 +964,14 @@ def apply_watermark(video_path):
def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPECT_RATIO,
force_strategy=None):
force_strategy=None, crop_overrides=None):
"""
Core logic to reframe a horizontal video to a target aspect ratio using
scene detection and Active Speaker Tracking (MediaPipe).
aspect_ratio: width/height of the output (9/16 vertical, 1.0 square).
force_strategy pins every scene's layout (v2 engine only — the v1 loop
below has no layout concept beyond its own classifier).
force_strategy / crop_overrides pin layouts and scene crops by hand (v2
engine only — the v1 loop below has no layout concept beyond its own
classifier).
"""
script_start_time = time.time()
@ -978,10 +982,19 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE
import reframe_v2
t0 = time.time()
result = reframe_v2.render(input_video, final_output_video, aspect_ratio,
force_strategy=force_strategy)
force_strategy=force_strategy,
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 and forced layouts. 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 discarding their input.
if crop_overrides or force_strategy:
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")

View file

@ -261,7 +261,7 @@ def _run_ffmpeg(command):
def perform_recut(*, input_path, segments, output_dir, clean_name,
reframe=False, output_format="auto", watermark=False,
captions_transcript=None, force_strategy=None,
runner=None, renderer=None,
crop_overrides=None, runner=None, renderer=None,
watermarker=None, captioner=None):
"""Render a recut clip. Returns (served_filename, clean_filename).
@ -275,6 +275,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
@ -299,7 +303,8 @@ def perform_recut(*, input_path, segments, output_dir, clean_name,
main_render = _main_attr("render_clip")
def render(i, o, f):
return main_render(i, o, f, force_strategy=force_strategy)
return main_render(i, o, f, force_strategy=force_strategy,
crop_overrides=crop_overrides)
if not render(work_path, out_path, output_format):
raise RuntimeError("reframe failed on the recut clip")
else:

View file

@ -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
@ -231,7 +313,7 @@ def _run(cmd):
def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
force_strategy=None):
force_strategy=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
@ -240,8 +322,13 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
``force_strategy`` ('WIDE' / 'TRACK' / any layout the render loop knows)
applies that layout to EVERY scene, skipping the classifier and the layout
upgrades — it exists for the clip editor's manual framing override, where
the user's explicit choice is the whole point.
upgrades — the clip editor's whole-clip framing override.
``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. Applied AFTER force_strategy: a per-scene
hand position always beats the whole-clip choice for the scenes it names.
"""
import main as m
content_ranges = content_ranges or []
@ -383,6 +470,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")