Merge pull request #70 from tuliovianna-lab/pr/manual-reframing
feat: manual reframing, per scene
This commit is contained in:
commit
3e8798f271
13 changed files with 1172 additions and 15 deletions
361
app.py
361
app.py
|
|
@ -14,7 +14,7 @@ import itertools
|
||||||
import asyncio
|
import asyncio
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
from typing import Dict, Optional, List
|
from typing import Any, Dict, Optional, List
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Request, Header, BackgroundTasks
|
from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Request, Header, BackgroundTasks
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
|
@ -2327,6 +2327,10 @@ _FRAMING_STRATEGIES = {"auto": None, "full": "WIDE", "track": "TRACK"}
|
||||||
# share metadata.json and the canonical files, so they must not interleave.
|
# share metadata.json and the canonical files, so they must not interleave.
|
||||||
_rerender_locks: Dict[str, asyncio.Lock] = {}
|
_rerender_locks: Dict[str, asyncio.Lock] = {}
|
||||||
|
|
||||||
|
# Scene-listing builds write stable preview/thumbnail names per job; serialize
|
||||||
|
# them so overlapping editor opens don't tear each other's files.
|
||||||
|
_scenes_locks: Dict[str, asyncio.Lock] = {}
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/clip/rerender")
|
@app.post("/api/clip/rerender")
|
||||||
async def rerender_clip(req: RerenderRequest, request: Request):
|
async def rerender_clip(req: RerenderRequest, request: Request):
|
||||||
|
|
@ -2463,6 +2467,12 @@ async def _rerender_locked(req: RerenderRequest, request: Request, job):
|
||||||
|
|
||||||
updates = {'video_url': new_video_url, 'start': new_start,
|
updates = {'video_url': new_video_url, 'start': new_start,
|
||||||
'end': new_end, 'recipe': new_recipe}
|
'end': new_end, 'recipe': new_recipe}
|
||||||
|
# Per-scene manual framing is keyed by scene indices of a specific cut;
|
||||||
|
# this render neither applied it nor can it survive a changed cut, so
|
||||||
|
# clear it rather than let /scenes serve stale overrides against the
|
||||||
|
# wrong shots (re-frame after trimming to re-apply by hand).
|
||||||
|
if clip.get('crop_overrides'):
|
||||||
|
updates['crop_overrides'] = None
|
||||||
clip.update(updates)
|
clip.update(updates)
|
||||||
data['shorts'] = clips
|
data['shorts'] = clips
|
||||||
with open(json_files[0], 'w') as f:
|
with open(json_files[0], 'w') as f:
|
||||||
|
|
@ -2491,6 +2501,355 @@ async def _rerender_locked(req: RerenderRequest, request: Request, job):
|
||||||
raise HTTPException(status_code=500, detail=str(e))
|
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]
|
||||||
|
reapply_captions: bool = True
|
||||||
|
|
||||||
|
|
||||||
|
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.
|
||||||
|
"""
|
||||||
|
# Entitlement too, not just ownership: listing scenes cuts the clip from
|
||||||
|
# source, runs scene detection and encodes a preview — real compute.
|
||||||
|
await require_managed_entitlement(request)
|
||||||
|
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")
|
||||||
|
|
||||||
|
if data.get('output_format') == 'horizontal':
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="Horizontal clips keep the full frame; there is no crop to reframe.")
|
||||||
|
|
||||||
|
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).
|
||||||
|
# temp_ prefix keeps these editor-only artifacts out of the self-host
|
||||||
|
# S3 backup (it skips temp_*); stable names still avoid accumulation.
|
||||||
|
token = str(clip_index)
|
||||||
|
work_token = f"{clip_index}_{uuid.uuid4().hex[:8]}"
|
||||||
|
preview_name = f"temp_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"temp_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",
|
||||||
|
# faststart: the editor's <video> streams the preview;
|
||||||
|
# a tail moov would stall it until fully downloaded.
|
||||||
|
"-movflags", "+faststart",
|
||||||
|
preview_path], check=True, timeout=600)
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"Scene preview failed: {exc}")
|
||||||
|
finally:
|
||||||
|
if os.path.exists(work_path):
|
||||||
|
os.remove(work_path)
|
||||||
|
|
||||||
|
# Serialized per job: two overlapping opens would run two ffmpeg writers
|
||||||
|
# on the same stable preview/thumbnail names and serve a torn file.
|
||||||
|
lock = _scenes_locks.setdefault(job_id, asyncio.Lock())
|
||||||
|
async with lock:
|
||||||
|
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 crop window as a fraction of the source width: the editor
|
||||||
|
# draws the rectangle with it and needs no pixel arithmetic of its own.
|
||||||
|
# The aspect follows the job's output format (9:16, or 1:1 for square).
|
||||||
|
aspect = 1.0 if data.get('output_format') == 'square' else 9.0 / 16.0
|
||||||
|
crop_w = min(orig_w, orig_h * aspect)
|
||||||
|
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)
|
||||||
|
|
||||||
|
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.")
|
||||||
|
|
||||||
|
# Same lock as /rerender: both read-modify-write the job's metadata.json,
|
||||||
|
# and the metadata must be read INSIDE the lock or a rerender committing
|
||||||
|
# in between gets clobbered by a write of stale data.
|
||||||
|
lock = _rerender_locks.setdefault(req.job_id, asyncio.Lock())
|
||||||
|
async with lock:
|
||||||
|
return await _reframe_locked(req, request, job, overrides)
|
||||||
|
|
||||||
|
|
||||||
|
async def _reframe_locked(req: ReframeRequest, request: Request, job, overrides):
|
||||||
|
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]
|
||||||
|
|
||||||
|
if data.get('output_format') == 'horizontal':
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="Horizontal clips keep the full frame; there is no crop to reframe.")
|
||||||
|
|
||||||
|
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.")
|
||||||
|
|
||||||
|
# Whole-clip framing (recipe.framing, the clip editor's selector) still
|
||||||
|
# applies to the scenes the user did NOT hand-position: apply_crop_overrides
|
||||||
|
# runs after force_strategy, so a per-scene choice beats the whole-clip one.
|
||||||
|
framing = (clip.get('recipe') or {}).get('framing') or 'auto'
|
||||||
|
force_strategy = _FRAMING_STRATEGIES.get(framing)
|
||||||
|
|
||||||
|
# A reframe re-renders the full cut from source — same work as a source-path
|
||||||
|
# rerender, so it meters the same.
|
||||||
|
total = recut.total_duration(segments)
|
||||||
|
rerender_minutes = (max(1, math.ceil(total / 60.0))
|
||||||
|
if BILLING_ENABLED else 0)
|
||||||
|
reservation_id = await reserve_managed_action(
|
||||||
|
request, rerender_minutes, req.job_id, "reframe")
|
||||||
|
|
||||||
|
# Every default clip ships with burned captions; re-rendering without them
|
||||||
|
# would silently hand back a caption-less file.
|
||||||
|
v_transcript = (recut.virtual_transcript(data.get('transcript') or {}, segments)
|
||||||
|
if req.reapply_captions else None)
|
||||||
|
|
||||||
|
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"
|
||||||
|
|
||||||
|
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')),
|
||||||
|
force_strategy=force_strategy,
|
||||||
|
crop_overrides=overrides,
|
||||||
|
captions_transcript=v_transcript)
|
||||||
|
|
||||||
|
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}"
|
||||||
|
new_recipe = {"v": 1, "segments": segments,
|
||||||
|
"canonical_range": canonical_range}
|
||||||
|
if framing != 'auto':
|
||||||
|
new_recipe["framing"] = framing
|
||||||
|
updates = {
|
||||||
|
'video_url': new_video_url,
|
||||||
|
'recipe': new_recipe,
|
||||||
|
'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)
|
||||||
|
if reservation_id:
|
||||||
|
await _metering.commit_reservation(reservation_id)
|
||||||
|
# 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": new_recipe,
|
||||||
|
"start": min(s['start'] for s in segments),
|
||||||
|
"end": max(s['end'] for s in segments),
|
||||||
|
"framed_scenes": sorted(overrides),
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
if reservation_id:
|
||||||
|
await _metering.release_reservation(reservation_id)
|
||||||
|
print(f"Reframe Error: {e}")
|
||||||
|
raise HTTPException(status_code=500, detail=str(e))
|
||||||
|
|
||||||
|
|
||||||
# --- Remotion Render Proxy ---
|
# --- Remotion Render Proxy ---
|
||||||
RENDER_SERVICE_URL = os.getenv("RENDER_SERVICE_URL", "http://renderer:3100")
|
RENDER_SERVICE_URL = os.getenv("RENDER_SERVICE_URL", "http://renderer:3100")
|
||||||
|
|
||||||
|
|
|
||||||
49
cli/openshorts.egg-info/PKG-INFO
Normal file
49
cli/openshorts.egg-info/PKG-INFO
Normal 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).
|
||||||
8
cli/openshorts.egg-info/SOURCES.txt
Normal file
8
cli/openshorts.egg-info/SOURCES.txt
Normal 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
|
||||||
1
cli/openshorts.egg-info/dependency_links.txt
Normal file
1
cli/openshorts.egg-info/dependency_links.txt
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
|
||||||
2
cli/openshorts.egg-info/entry_points.txt
Normal file
2
cli/openshorts.egg-info/entry_points.txt
Normal file
|
|
@ -0,0 +1,2 @@
|
||||||
|
[console_scripts]
|
||||||
|
openshorts = openshorts_cli:main
|
||||||
1
cli/openshorts.egg-info/top_level.txt
Normal file
1
cli/openshorts.egg-info/top_level.txt
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
openshorts_cli
|
||||||
|
|
@ -10,6 +10,7 @@ import SaaShortsTab from './components/SaaShortsTab';
|
||||||
import UGCGallery from './components/UGCGallery';
|
import UGCGallery from './components/UGCGallery';
|
||||||
import ScheduleWeekModal from './components/ScheduleWeekModal';
|
import ScheduleWeekModal from './components/ScheduleWeekModal';
|
||||||
import ClipEditor from './components/ClipEditor';
|
import ClipEditor from './components/ClipEditor';
|
||||||
|
import ReframeEditor from './components/ReframeEditor';
|
||||||
import UsageMeter from './components/UsageMeter';
|
import UsageMeter from './components/UsageMeter';
|
||||||
import TopUpModal from './components/TopUpModal';
|
import TopUpModal from './components/TopUpModal';
|
||||||
import StarBanner from './components/StarBanner';
|
import StarBanner from './components/StarBanner';
|
||||||
|
|
@ -231,6 +232,7 @@ function App() {
|
||||||
const [showScheduleWeek, setShowScheduleWeek] = useState(false);
|
const [showScheduleWeek, setShowScheduleWeek] = useState(false);
|
||||||
// Clip editor overlay: index of the clip being edited, or null.
|
// Clip editor overlay: index of the clip being edited, or null.
|
||||||
const [editingClip, setEditingClip] = useState(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)
|
// Silent-success "saved" states for the settings key inputs (design.md: no alert popups)
|
||||||
const [elevenLabsSaved, setElevenLabsSaved] = useState(false);
|
const [elevenLabsSaved, setElevenLabsSaved] = useState(false);
|
||||||
|
|
@ -1459,6 +1461,7 @@ function App() {
|
||||||
index={i}
|
index={i}
|
||||||
jobId={jobId}
|
jobId={jobId}
|
||||||
onEditClip={(index) => setEditingClip(index)}
|
onEditClip={(index) => setEditingClip(index)}
|
||||||
|
onReframeClip={(index) => setReframingClip(index)}
|
||||||
initialState={projectState?.clips?.find((c) => c.index === i) || null}
|
initialState={projectState?.clips?.find((c) => c.index === i) || null}
|
||||||
onStateChange={handleClipStateChange}
|
onStateChange={handleClipStateChange}
|
||||||
durableUrl={durableClips[i]}
|
durableUrl={durableClips[i]}
|
||||||
|
|
@ -1638,6 +1641,15 @@ function App() {
|
||||||
onRerendered={handleClipRerendered}
|
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)} />}
|
{showLogin && <LoginModal onClose={() => setShowLogin(false)} />}
|
||||||
{showPlanChoice && <PlanChoiceModal onClose={() => setShowPlanChoice(false)} />}
|
{showPlanChoice && <PlanChoiceModal onClose={() => setShowPlanChoice(false)} />}
|
||||||
{showTopUp && (
|
{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 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 { getApiUrl } from '../config';
|
||||||
import { apiFetch } from '../lib/api';
|
import { apiFetch } from '../lib/api';
|
||||||
import SubtitleModal from './SubtitleModal';
|
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')}`;
|
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 [showModal, setShowModal] = useState(false);
|
||||||
const [showDescModal, setShowDescModal] = useState(false);
|
const [showDescModal, setShowDescModal] = useState(false);
|
||||||
const [showSubtitleModal, setShowSubtitleModal] = useState(false);
|
const [showSubtitleModal, setShowSubtitleModal] = useState(false);
|
||||||
|
|
@ -735,6 +735,16 @@ export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostK
|
||||||
</button>
|
</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
|
<button
|
||||||
onClick={handleAutoEdit}
|
onClick={handleAutoEdit}
|
||||||
disabled={isEditing}
|
disabled={isEditing}
|
||||||
|
|
|
||||||
27
main.py
27
main.py
|
|
@ -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",
|
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.
|
"""Route a cut clip through the right renderer for the chosen output format.
|
||||||
vertical/auto -> 9:16 reframe, square -> 1:1 reframe, horizontal -> keep.
|
vertical/auto -> 9:16 reframe, square -> 1:1 reframe, horizontal -> keep.
|
||||||
``force_strategy`` (e.g. 'WIDE'/'TRACK') pins every scene's layout — the
|
``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":
|
if output_format == "horizontal":
|
||||||
return finalize_clip_passthrough(input_video, final_output_video)
|
return finalize_clip_passthrough(input_video, final_output_video)
|
||||||
aspect = 1.0 if output_format == "square" else ASPECT_RATIO
|
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,
|
||||||
force_strategy=force_strategy)
|
force_strategy=force_strategy,
|
||||||
|
crop_overrides=crop_overrides)
|
||||||
|
|
||||||
|
|
||||||
# Watermark geometry, as fractions of the clip width/height.
|
# 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,
|
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
|
Core logic to reframe a horizontal video to a target aspect ratio using
|
||||||
scene detection and Active Speaker Tracking (MediaPipe).
|
scene detection and Active Speaker Tracking (MediaPipe).
|
||||||
aspect_ratio: width/height of the output (9/16 vertical, 1.0 square).
|
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
|
force_strategy / crop_overrides pin layouts and scene crops by hand (v2
|
||||||
below has no layout concept beyond its own classifier).
|
engine only — the v1 loop below has no layout concept beyond its own
|
||||||
|
classifier).
|
||||||
"""
|
"""
|
||||||
script_start_time = time.time()
|
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
|
import reframe_v2
|
||||||
t0 = time.time()
|
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,
|
||||||
force_strategy=force_strategy)
|
force_strategy=force_strategy,
|
||||||
|
crop_overrides=crop_overrides)
|
||||||
print(f" ⏱️ Reframe v2 total: {time.time() - t0:.1f}s")
|
print(f" ⏱️ Reframe v2 total: {time.time() - t0:.1f}s")
|
||||||
return result
|
return result
|
||||||
except Exception as e:
|
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}) — "
|
print(f" ⚠️ Reframe v2 failed ({type(e).__name__}: {e}) — "
|
||||||
f"falling back to v1 frame loop")
|
f"falling back to v1 frame loop")
|
||||||
|
|
||||||
|
|
|
||||||
9
recut.py
9
recut.py
|
|
@ -265,7 +265,7 @@ def _run_ffmpeg(command):
|
||||||
def perform_recut(*, input_path, segments, output_dir, clean_name,
|
def perform_recut(*, input_path, segments, output_dir, clean_name,
|
||||||
reframe=False, output_format="auto", watermark=False,
|
reframe=False, output_format="auto", watermark=False,
|
||||||
captions_transcript=None, force_strategy=None,
|
captions_transcript=None, force_strategy=None,
|
||||||
runner=None, renderer=None,
|
crop_overrides=None, runner=None, renderer=None,
|
||||||
watermarker=None, captioner=None):
|
watermarker=None, captioner=None):
|
||||||
"""Render a recut clip. Returns (served_filename, clean_filename).
|
"""Render a recut clip. Returns (served_filename, clean_filename).
|
||||||
|
|
||||||
|
|
@ -279,6 +279,10 @@ def perform_recut(*, input_path, segments, output_dir, clean_name,
|
||||||
``virtual_transcript``); when given and non-empty, captions are burned
|
``virtual_transcript``); when given and non-empty, captions are burned
|
||||||
LAST onto a ``subtitled_<ts>_`` derivative, preserving the invariant
|
LAST onto a ``subtitled_<ts>_`` derivative, preserving the invariant
|
||||||
that the clean file stays clean for later re-styling.
|
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
|
The renderer/watermarker/captioner hooks default to main.py's
|
||||||
implementations, imported lazily so this module stays importable without
|
implementations, imported lazily so this module stays importable without
|
||||||
|
|
@ -303,7 +307,8 @@ def perform_recut(*, input_path, segments, output_dir, clean_name,
|
||||||
main_render = _main_attr("render_clip")
|
main_render = _main_attr("render_clip")
|
||||||
|
|
||||||
def render(i, o, f):
|
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):
|
if not render(work_path, out_path, output_format):
|
||||||
raise RuntimeError("reframe failed on the recut clip")
|
raise RuntimeError("reframe failed on the recut clip")
|
||||||
else:
|
else:
|
||||||
|
|
|
||||||
101
reframe_v2.py
101
reframe_v2.py
|
|
@ -147,6 +147,88 @@ def general_filtergraph(out_w, out_h, content_h=None):
|
||||||
|
|
||||||
# --- analysis ---------------------------------------------------------------
|
# --- 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,
|
def _analyze_trajectory(input_video, scenes_boundaries, scene_strategies,
|
||||||
fps, orig_w, orig_h, cameraman, tracker):
|
fps, orig_w, orig_h, cameraman, tracker):
|
||||||
"""Replays v1's per-frame decision loop on a downscaled ffmpeg-decoded
|
"""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,
|
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).
|
"""Full v2 reframe of one clip. Raises on failure (caller falls back).
|
||||||
|
|
||||||
``content_ranges`` comes from screencast_layout.detect_content_ranges() on
|
``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)
|
``force_strategy`` ('WIDE' / 'TRACK' / any layout the render loop knows)
|
||||||
applies that layout to EVERY scene, skipping the classifier and the layout
|
applies that layout to EVERY scene, skipping the classifier and the layout
|
||||||
upgrades — it exists for the clip editor's manual framing override, where
|
upgrades — the clip editor's whole-clip framing override.
|
||||||
the user's explicit choice is the whole point.
|
|
||||||
|
``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
|
import main as m
|
||||||
content_ranges = content_ranges or []
|
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(
|
xs[start_f:end_f] = active_speaker.speaker_xs(
|
||||||
held, centres, crop_w, orig_w, end_f - start_f, fps)
|
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))
|
ranges = scene_frame_ranges(scene_boundaries, strategies, len(xs))
|
||||||
if not ranges:
|
if not ranges:
|
||||||
raise RuntimeError("no usable scene ranges")
|
raise RuntimeError("no usable scene ranges")
|
||||||
|
|
|
||||||
225
tests/test_reframe_endpoint.py
Normal file
225
tests/test_reframe_endpoint.py
Normal file
|
|
@ -0,0 +1,225 @@
|
||||||
|
"""Tests for PR #70's manual per-scene reframing: the /api/clip/reframe
|
||||||
|
endpoint contract (validation, metering seam, caption reapply, persistence,
|
||||||
|
interplay with whole-clip framing) and the pure apply_crop_overrides math.
|
||||||
|
|
||||||
|
Same harness as test_rerender_endpoint.py: BILLING_ENABLED=0 self-host round
|
||||||
|
trips with the render stubbed at recut.perform_recut.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
app_module = pytest.importorskip("app")
|
||||||
|
import recut # noqa: E402
|
||||||
|
|
||||||
|
JOB_ID = "reframe-endpoint-test-job"
|
||||||
|
|
||||||
|
TRANSCRIPT = {
|
||||||
|
"language": "en",
|
||||||
|
"segments": [
|
||||||
|
{"start": 0.0, "end": 60.0, "text": "hello world",
|
||||||
|
"words": [{"word": "hello", "start": 12.0, "end": 12.5},
|
||||||
|
{"word": "world", "start": 20.0, "end": 20.4}]},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _request(method, path, json_body=None):
|
||||||
|
async def _do():
|
||||||
|
transport = httpx.ASGITransport(app=app_module.app)
|
||||||
|
async with httpx.AsyncClient(transport=transport,
|
||||||
|
base_url="http://testserver") as client:
|
||||||
|
return await client.request(method, path, json=json_body)
|
||||||
|
return asyncio.run(_do())
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def job(tmp_path, monkeypatch):
|
||||||
|
out_root = tmp_path / "output"
|
||||||
|
up_root = tmp_path / "uploads"
|
||||||
|
job_dir = out_root / JOB_ID
|
||||||
|
job_dir.mkdir(parents=True)
|
||||||
|
up_root.mkdir()
|
||||||
|
monkeypatch.setattr(app_module, "OUTPUT_DIR", str(out_root))
|
||||||
|
monkeypatch.setattr(app_module, "UPLOAD_DIR", str(up_root))
|
||||||
|
|
||||||
|
clip = {
|
||||||
|
"start": 10.0, "end": 40.0,
|
||||||
|
"video_title_for_youtube_short": "test clip",
|
||||||
|
"video_url": f"/videos/{JOB_ID}/mytitle_clip_1.mp4",
|
||||||
|
}
|
||||||
|
meta = {"shorts": [clip], "transcript": TRANSCRIPT,
|
||||||
|
"source_video": "src.mp4", "output_format": "auto",
|
||||||
|
"cost_analysis": {}}
|
||||||
|
(job_dir / "mytitle_metadata.json").write_text(json.dumps(meta))
|
||||||
|
(job_dir / "mytitle_clip_1.mp4").write_bytes(b"canonical")
|
||||||
|
(job_dir / "src.mp4").write_bytes(b"source")
|
||||||
|
|
||||||
|
app_module.jobs[JOB_ID] = {
|
||||||
|
"status": "completed", "logs": [],
|
||||||
|
"result": {"clips": [dict(clip)], "cost_analysis": {}},
|
||||||
|
"user_id": None, "watermark": False,
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
yield {"dir": job_dir, "meta_path": job_dir / "mytitle_metadata.json"}
|
||||||
|
finally:
|
||||||
|
app_module.jobs.pop(JOB_ID, None)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def fake_recut(monkeypatch):
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def fake(**kwargs):
|
||||||
|
calls.append(kwargs)
|
||||||
|
name = f"recut_1_{kwargs['clean_name']}"
|
||||||
|
with open(os.path.join(kwargs["output_dir"], name), "wb") as f:
|
||||||
|
f.write(b"recut")
|
||||||
|
return name, name
|
||||||
|
|
||||||
|
monkeypatch.setattr(recut, "perform_recut", fake)
|
||||||
|
return calls
|
||||||
|
|
||||||
|
|
||||||
|
class TestReframeValidation:
|
||||||
|
def test_no_usable_overrides_400(self, job, fake_recut):
|
||||||
|
for overrides in ({}, {"notanumber": "x"}, {"0": "garbage"}):
|
||||||
|
resp = _request("POST", "/api/clip/reframe", {
|
||||||
|
"job_id": JOB_ID, "clip_index": 0,
|
||||||
|
"crop_overrides": overrides})
|
||||||
|
assert resp.status_code == 400, overrides
|
||||||
|
assert fake_recut == []
|
||||||
|
|
||||||
|
def test_horizontal_clips_400(self, job, fake_recut):
|
||||||
|
meta = json.loads(job["meta_path"].read_text())
|
||||||
|
meta["output_format"] = "horizontal"
|
||||||
|
job["meta_path"].write_text(json.dumps(meta))
|
||||||
|
resp = _request("POST", "/api/clip/reframe", {
|
||||||
|
"job_id": JOB_ID, "clip_index": 0, "crop_overrides": {"0": 0.5}})
|
||||||
|
assert resp.status_code == 400
|
||||||
|
assert fake_recut == []
|
||||||
|
|
||||||
|
def test_gone_source_409(self, job, fake_recut):
|
||||||
|
os.remove(job["dir"] / "src.mp4")
|
||||||
|
resp = _request("POST", "/api/clip/reframe", {
|
||||||
|
"job_id": JOB_ID, "clip_index": 0, "crop_overrides": {"0": 0.5}})
|
||||||
|
assert resp.status_code == 409
|
||||||
|
assert fake_recut == []
|
||||||
|
|
||||||
|
|
||||||
|
class TestReframeRender:
|
||||||
|
def test_renders_from_source_with_overrides_and_captions(self, job, fake_recut):
|
||||||
|
resp = _request("POST", "/api/clip/reframe", {
|
||||||
|
"job_id": JOB_ID, "clip_index": 0,
|
||||||
|
"crop_overrides": {"0": 0.2, "1": {"top": 0.6, "bottom": {"x": 0.3, "y": 0.4}}}})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
data = resp.json()
|
||||||
|
assert data["framed_scenes"] == [0, 1]
|
||||||
|
|
||||||
|
call = fake_recut[0]
|
||||||
|
assert call["input_path"].endswith("src.mp4")
|
||||||
|
assert call["reframe"] is True
|
||||||
|
assert call["crop_overrides"][0] == 0.2
|
||||||
|
assert call["crop_overrides"][1]["top"] == {"x": 0.6, "y": 0.5}
|
||||||
|
assert call["crop_overrides"][1]["bottom"] == {"x": 0.3, "y": 0.4}
|
||||||
|
# Captions come back by default — every default clip ships with them.
|
||||||
|
assert call["captions_transcript"]["segments"][0]["words"]
|
||||||
|
|
||||||
|
# Overrides persisted (string keys, JSON-style) for /scenes to serve.
|
||||||
|
meta = json.loads(job["meta_path"].read_text())
|
||||||
|
assert meta["shorts"][0]["crop_overrides"]["0"] == 0.2
|
||||||
|
|
||||||
|
def test_reapply_captions_false(self, job, fake_recut):
|
||||||
|
resp = _request("POST", "/api/clip/reframe", {
|
||||||
|
"job_id": JOB_ID, "clip_index": 0, "reapply_captions": False,
|
||||||
|
"crop_overrides": {"0": 0.5}})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert fake_recut[0]["captions_transcript"] is None
|
||||||
|
|
||||||
|
def test_whole_clip_framing_carries_into_the_render(self, job, fake_recut):
|
||||||
|
# recipe.framing='full' (the clip editor's selector) must keep forcing
|
||||||
|
# WIDE on the scenes the user did not hand-position.
|
||||||
|
meta = json.loads(job["meta_path"].read_text())
|
||||||
|
meta["shorts"][0]["recipe"] = {
|
||||||
|
"v": 1, "segments": [{"start": 10.0, "end": 40.0}],
|
||||||
|
"canonical_range": {"start": 10.0, "end": 40.0},
|
||||||
|
"framing": "full"}
|
||||||
|
job["meta_path"].write_text(json.dumps(meta))
|
||||||
|
resp = _request("POST", "/api/clip/reframe", {
|
||||||
|
"job_id": JOB_ID, "clip_index": 0, "crop_overrides": {"0": 0.5}})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert fake_recut[0]["force_strategy"] == "WIDE"
|
||||||
|
assert resp.json()["recipe"]["framing"] == "full"
|
||||||
|
|
||||||
|
|
||||||
|
class TestRerenderClearsSceneOverrides:
|
||||||
|
def test_trim_clears_stale_overrides(self, job, fake_recut):
|
||||||
|
# Hand-frame first…
|
||||||
|
assert _request("POST", "/api/clip/reframe", {
|
||||||
|
"job_id": JOB_ID, "clip_index": 0,
|
||||||
|
"crop_overrides": {"0": 0.2}}).status_code == 200
|
||||||
|
# …then trim: scene indices no longer mean anything against the new
|
||||||
|
# cut, so the stale overrides must not survive for /scenes to serve.
|
||||||
|
assert _request("POST", "/api/clip/rerender", {
|
||||||
|
"job_id": JOB_ID, "clip_index": 0,
|
||||||
|
"segments": [{"start": 12, "end": 22}]}).status_code == 200
|
||||||
|
meta = json.loads(job["meta_path"].read_text())
|
||||||
|
assert not meta["shorts"][0].get("crop_overrides")
|
||||||
|
|
||||||
|
|
||||||
|
class TestApplyCropOverrides:
|
||||||
|
"""Pure math on the trajectory — no ffmpeg, no models."""
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _mod(self):
|
||||||
|
self.rf = pytest.importorskip("reframe_v2")
|
||||||
|
|
||||||
|
def test_single_crop_centres_the_window(self):
|
||||||
|
xs = [None] * 100
|
||||||
|
strategies = ["GENERAL"]
|
||||||
|
xs, strategies = self.rf.apply_crop_overrides(
|
||||||
|
xs, strategies, [(0, 100)], {"0": 0.5}, crop_w=608, orig_w=1920)
|
||||||
|
assert strategies == ["TRACK"]
|
||||||
|
assert xs[0] == xs[99] == 656 # 1920*0.5 - 608/2
|
||||||
|
|
||||||
|
def test_clamps_at_both_edges(self):
|
||||||
|
xs = [0] * 10
|
||||||
|
xs, _ = self.rf.apply_crop_overrides(
|
||||||
|
xs, ["TRACK"], [(0, 10)], {"0": 0.0}, crop_w=608, orig_w=1920)
|
||||||
|
assert xs[0] == 0
|
||||||
|
xs, _ = self.rf.apply_crop_overrides(
|
||||||
|
xs, ["TRACK"], [(0, 10)], {"0": 1.0}, crop_w=608, orig_w=1920)
|
||||||
|
assert xs[0] == 1920 - 608
|
||||||
|
|
||||||
|
def test_untouched_scenes_stay_untouched(self):
|
||||||
|
xs = [111] * 20
|
||||||
|
strategies = ["TRACK", "GENERAL"]
|
||||||
|
xs, strategies = self.rf.apply_crop_overrides(
|
||||||
|
xs, strategies, [(0, 10), (10, 20)], {"1": 0.5},
|
||||||
|
crop_w=608, orig_w=1920)
|
||||||
|
assert xs[:10] == [111] * 10 # scene 0 keeps the auto camera
|
||||||
|
assert strategies[0] == "TRACK"
|
||||||
|
assert strategies[1] == "TRACK" # scene 1 forced back from GENERAL
|
||||||
|
|
||||||
|
def test_malformed_and_unknown_indices_are_skipped(self):
|
||||||
|
xs = [7] * 10
|
||||||
|
out_xs, strategies = self.rf.apply_crop_overrides(
|
||||||
|
xs, ["TRACK"], [(0, 10)],
|
||||||
|
{"nope": 0.5, "9": 0.5, "0": "garbage"}, crop_w=608, orig_w=1920)
|
||||||
|
assert out_xs == [7] * 10
|
||||||
|
assert strategies == ["TRACK"]
|
||||||
|
|
||||||
|
def test_split_writes_into_splits_keyed_by_start_frame(self):
|
||||||
|
splits = {}
|
||||||
|
xs, strategies = self.rf.apply_crop_overrides(
|
||||||
|
[None] * 10, ["GENERAL"], [(0, 10)],
|
||||||
|
{"0": {"top": {"x": 0.6, "y": 0.3}, "bottom": 0.2}},
|
||||||
|
crop_w=608, orig_w=1920, orig_h=1080, splits=splits)
|
||||||
|
assert strategies == ["SPLIT"]
|
||||||
|
top, bottom = splits[0]
|
||||||
|
assert top == (0.6 * 1920, 0.3 * 1080)
|
||||||
|
assert bottom == (0.2 * 1920, 0.5 * 1080)
|
||||||
Loading…
Reference in a new issue