chore: remove dead code, unused assets, and the server-render chain

Backend:
- Drop unused imports/locals and zero-reference helpers (truncate_ip,
  in_split, GEMINI_PROMPT_TEMPLATE, legacy subtitles SRT path, dead paths)
- Remove unwired features (delete_uploaded, mark_ai_generated, unmark_job,
  compact_words, restoring_static restorer hook, gemini_worker __main__)
- Remove shelved panel_layout module + its flags/tests
- Remove the /api/render proxy + RENDER_SERVICE_URL

Frontend:
- Delete App.css, react.svg, vite.svg, agent screenshot, demo mp4s
- Remove dead exports (downloadBlobUrl, consent reopen machinery, dead zod
  schemas/CITED_STATS) and unused deps (@remotion/media-utils, zod)
- Drop the /render dev proxy; rewrite dashboard README

Repo/config:
- Delete render-service/ and top-level remotion/ (superseded by the
  dashboard's in-browser Remotion copy); drop the compose renderer service
- Delete docker-compose.e2e.local.yml and 4 unreferenced screenshots
- Prune .env.example dead keys, add GEMINI_API_KEY/MAX_CONCURRENT_JOBS
- Tighten .dockerignore/.gitignore; add dashboard lint to CI
- Fix stale compliance doc + README structure

Backend 709 passed / 18 skipped; dashboard lint+build green; compose valid.
This commit is contained in:
pedro-bento 2026-10-04 21:24:42 +01:00
parent 719946b3cd
commit 59e0db8c24
82 changed files with 89 additions and 6868 deletions

View file

@ -14,11 +14,10 @@ ENV/
.eggs/
*.egg-info/
.pytest_cache/
.ruff_cache/
# Node
node_modules/
remotion/node_modules/
render-service/node_modules/
dashboard/node_modules/
# IDE
@ -27,6 +26,17 @@ dashboard/node_modules/
*.swp
*.swo
# Agent / tool local state
.opencode/
# Local caches
.cache/
.config/
# Not needed in the runtime image
tests/
screenshots/
# Video files (will be mounted via volume)
*.mp4
*.avi
@ -43,7 +53,6 @@ videos/
.env
.env.*
!.env.example
!.env.cloud.example
*.pem
*.key
@ -55,10 +64,3 @@ docker-compose.yml
# Docs
README.md
*.md

View file

@ -1,3 +1,8 @@
# Google Gemini API key used server-side (moment detection, layouts, titles and
# thumbnails). The dashboard can also send a key per request, and the key is
# optional entirely when LLM_BASE_URL points at an OpenAI-compatible server.
# GEMINI_API_KEY=your_gemini_api_key
# YouTube cookies (optional — paste Netscape-format cookies to bypass bot detection)
# YOUTUBE_COOKIES=...
@ -21,6 +26,9 @@
# Concurrent GPU transcriptions (parakeet or whisper-on-cuda). Keep 1.
# ASR_GPU_CONCURRENCY=1
# Concurrent pipeline jobs (default 5).
# MAX_CONCURRENT_JOBS=5
# Video encoder for all ffmpeg encodes: x264 (default) | nvenc | auto.
# auto probes h264_nvenc once at startup and falls back to x264 if unusable.
# FFMPEG_ENCODER=x264
@ -49,13 +57,8 @@ GEMINI_IMAGE_MODEL=gemini-3.1-flash-image
# LLM_SCORE_BATCH=3
# LLM_TIMEOUT=600
# Hard daily ceiling for the per-GB paid proxy (UTC day, MB). Above it,
# DataImpulse is removed from every chain until midnight and the jobs that
# needed it fail with a clear error. 0 disables the cap. Default 500.
# PAID_PROXY_DAILY_MB=500
# ---------------------------------------------------------------------------
# Privacy, retention and access control (GDPR remediation, 4-sep-2026)
# Privacy and access control (GDPR remediation, 4-sep-2026)
# ---------------------------------------------------------------------------
# Absolute base URL of the API as the internet reaches it, used for the
@ -68,17 +71,6 @@ GEMINI_IMAGE_MODEL=gemini-3.1-flash-image
# sidecars, dotfiles) so only media is exposed. Files are swept with the job
# (JOB_RETENTION_SECONDS).
# Retention for thumbnails. Thumbnails and the frames sampled to make them are
# close-ups of a real person; the clock runs from the last download.
# THUMBNAIL_RETENTION_SECONDS=86400
# Per-IP rate limiting. "<max requests>/<window seconds>".
# Defaults: auth 30/600, process 60/3600. Set RATE_LIMIT_ENABLED=0
# to turn the whole thing off (self-host behind your own firewall).
# RATE_LIMIT_ENABLED=1
# RATE_LIMIT_AUTH=30/600
# RATE_LIMIT_PROCESS=60/3600
# ---------------------------------------------------------------------------
# Publishing (self-hosted Postiz)
# ---------------------------------------------------------------------------
@ -100,16 +92,9 @@ GEMINI_IMAGE_MODEL=gemini-3.1-flash-image
# number to cap uploads and reject larger files with HTTP 413.
# MAX_FILE_SIZE_MB=0
# Which hop may declare the client's address in X-Forwarded-For. The Dockerfile
# defaults to the private Docker ranges; narrow it to Traefik's own address on
# the container network in production. NEVER "*": that lets any caller forge
# the IP the rate limiter and the rights declaration are keyed on.
# FORWARDED_ALLOW_IPS=10.0.1.7
# Strict-Transport-Security value sent on https responses from the API. Empty
# disables it. Do not add "preload" without understanding that it is one-way.
# HSTS_HEADER=max-age=31536000; includeSubDomains
# Optional PostgreSQL database (only needed if you run the app against one).
# DATABASE_URL=postgres://user:pass@host:5432/clipwright
# X-Forwarded-For trust. The container launches uvicorn with
# `--proxy-headers --forwarded-allow-ips *` (see the Dockerfile CMD), so any
# caller that can reach the port may declare its own address and scheme. This
# is not configurable via an environment variable: run the API behind a reverse
# proxy that overwrites X-Forwarded-For, and never publish the backend port
# directly to the internet.

View file

@ -39,5 +39,7 @@ jobs:
cache-dependency-path: dashboard/package-lock.json
- name: Install dependencies
run: npm ci
- name: Lint
run: npm run lint
- name: Build
run: npm run build

22
.gitignore vendored
View file

@ -12,11 +12,8 @@
__pycache__/
*.pyc
# Temporary files / runtime dirs
temp_*
# Runtime dirs
uploads/
downloads/
videos/
output/
# OS / IDE
@ -34,20 +31,7 @@ output/
.cache/
.config/
.pytest_cache/
.ruff_cache/
# Multi-agent Skills
.agents/
.agent/
.claude/
# Design-tool / agent-local state
.hallmark/
# Agent / tool local state
.opencode/
# Cloud env example kept local only (avoid leaking infra hints)
.env.cloud.example
.worktrees
# Instrucciones locales con datos de infra (repo público)
CLAUDE.local.md

View file

@ -106,13 +106,11 @@ clipwright/ # Python backend package
core/ # shared helpers (security, filesystem paths)
api/ # FastAPI app, auth, free tools
pipeline/ # download → transcribe → clip orchestration, Gemini, quality probe
layouts/ # reframing: active speaker, split/screencast/panel, punch-in
layouts/ # reframing: active speaker, split/screencast, punch-in
media/ # FFmpeg helpers, subtitles, hooks, thumbnails, recut
integrations/ # Postiz, YouTube, file hosts
tools/ # local verification scripts (python -m clipwright.tools.verify_hooks)
dashboard/ # React + Vite dashboard (its own build)
remotion/ # Remotion compositions used by the renderer
render-service/ # Node render microservice (its own Dockerfile)
cli/ # published `clipwright` HTTP client (own pyproject)
tests/ # pytest suite (pythonpath = ["."])
fonts/ assets/ # shared runtime resources (kept at repo root)

View file

@ -1472,9 +1472,11 @@ async def lifespan(app: FastAPI):
_install_drain_signal_handler()
asyncio.create_task(_handover_watch())
asyncio.create_task(_resume_scan())
# Start worker and cleanup
worker_task = asyncio.create_task(process_queue())
cleanup_task = asyncio.create_task(cleanup_jobs())
# Start worker and cleanup. The assignments are load-bearing: asyncio holds
# no strong reference to a task, so dropping these lets the worker and the
# cleanup loop be garbage-collected mid-run.
_worker_task = asyncio.create_task(process_queue())
_cleanup_task = asyncio.create_task(cleanup_jobs())
yield
# Cleanup (optional: cancel worker)
@ -1625,7 +1627,6 @@ async def run_job(job_id, job_data):
t_log.start()
# Async wait for process with incremental updates
start_wait = time.time()
last_heartbeat = time.time()
while process.poll() is None:
try:
@ -1679,7 +1680,7 @@ async def run_job(job_id, job_data):
if ready_clips:
jobs[job_id]['result'] = {'clips': ready_clips, 'cost_analysis': cost_analysis}
except Exception as e:
except Exception:
# Ignore read errors during processing
pass
@ -3388,10 +3389,6 @@ async def _reframe_locked(req: ReframeRequest, request: Request, job, overrides)
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.
total = recut.total_duration(segments)
# 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)
@ -3455,35 +3452,6 @@ async def _reframe_locked(req: ReframeRequest, request: Request, job, overrides)
raise HTTPException(status_code=500, detail=str(e))
# --- Remotion Render Proxy ---
RENDER_SERVICE_URL = os.getenv("RENDER_SERVICE_URL", "http://renderer:3100")
@app.post("/api/render")
async def proxy_render(request: Request):
"""Proxy render requests to the Node.js Remotion render service."""
import httpx
body = await request.json()
try:
async with httpx.AsyncClient(timeout=30.0) as client:
resp = await client.post(f"{RENDER_SERVICE_URL}/render", json=body)
return resp.json()
except Exception as e:
raise HTTPException(status_code=502, detail=f"Render service unavailable: {e}")
@app.get("/api/render/{render_id}")
async def proxy_render_status(render_id: str, request: Request):
"""Proxy render status polling to the Node.js Remotion render service."""
import httpx
# The id goes into the upstream path: ids are uuids, nothing else passes.
if not re.fullmatch(r"[A-Za-z0-9-]{1,64}", render_id or ""):
raise HTTPException(status_code=404, detail="Not found")
try:
async with httpx.AsyncClient(timeout=10.0) as client:
resp = await client.get(f"{RENDER_SERVICE_URL}/render/{render_id}")
return resp.json()
except Exception as e:
raise HTTPException(status_code=502, detail=f"Render service unavailable: {e}")
class EffectsGenerateRequest(BaseModel):
job_id: str
clip_index: int

View file

@ -11,23 +11,18 @@ This subclass keeps everything ``StaticFiles`` does (Range requests, ETags,
HEAD) and adds one step before the filesystem: ``guard`` (the allowlist,
``media_auth.is_servable``, wrapped by ``app._media_guard``) refuses a path, and
a refused path looks exactly like a missing one. ``app.py`` mounts it with the
guard only -- there is no restorer in this fork.
The optional ``restorer`` hook predates the self-host fork: it let a miss ask a
job's durable copy (R2) to come back before answering 404. Nothing wires one up
any more; the parameter is kept because callers and tests may still pass one.
guard only.
"""
from typing import Awaitable, Callable, Optional
from typing import Callable, Optional
from starlette.exceptions import HTTPException
from starlette.staticfiles import StaticFiles
Restorer = Callable[[str], Awaitable[bool]]
Guard = Callable[[str], bool]
class RestoringStaticFiles(StaticFiles):
"""StaticFiles that refuses non-deliverables, with an optional restore hook.
"""StaticFiles that refuses non-deliverables.
``guard`` is the allowlist (``media_auth.is_servable``). Without it this
mount hands out the whole working directory to anyone holding the job id:
@ -38,14 +33,11 @@ class RestoringStaticFiles(StaticFiles):
This is only the path half of media_auth: the clips themselves, and the
untouched source video sitting in the same directory, are still public to
anyone who has the job id. ``restorer`` is not wired up in this fork; see
the module docstring.
anyone who has the job id.
"""
def __init__(self, *args, restorer: Optional[Restorer] = None,
guard: Optional[Guard] = None, **kwargs):
def __init__(self, *args, guard: Optional[Guard] = None, **kwargs):
super().__init__(*args, **kwargs)
self.restorer = restorer
self.guard = guard
async def get_response(self, path: str, scope):
@ -53,23 +45,4 @@ class RestoringStaticFiles(StaticFiles):
# missing one, or the 404-vs-403 difference confirms the file is there.
if self.guard is not None and not self.guard(path):
raise HTTPException(status_code=404)
try:
return await super().get_response(path, scope)
except HTTPException as exc:
if exc.status_code != 404 or self.restorer is None:
raise
job_id = path.split("/", 1)[0] if "/" in path else ""
if not job_id:
raise
try:
restored = await self.restorer(job_id)
except Exception:
restored = False
if not restored:
raise
# The guard may read the job directory (a free job's clean twins
# are refused by a marker file that only exists once the files
# are back), so the verdict before the restore is not final.
if self.guard is not None and not self.guard(path):
raise HTTPException(status_code=404)
return await super().get_response(path, scope)
return await super().get_response(path, scope)

View file

@ -11,21 +11,16 @@ from __future__ import annotations
from pathlib import Path
# .../clipwright
# .../clipwright (kept private: only used below to locate REPO_ROOT)
PACKAGE_DIR = Path(__file__).resolve().parent.parent
# Repository root (also the Docker WORKDIR /app).
REPO_ROOT = PACKAGE_DIR.parent
FONTS_DIR = REPO_ROOT / "fonts"
ASSETS_DIR = REPO_ROOT / "assets"
UPLOADS_DIR = REPO_ROOT / "uploads"
OUTPUT_DIR = REPO_ROOT / "output"
__all__ = [
"PACKAGE_DIR",
"REPO_ROOT",
"FONTS_DIR",
"ASSETS_DIR",
"UPLOADS_DIR",
"OUTPUT_DIR",
]

View file

@ -14,25 +14,6 @@ import socket
from urllib.parse import urlparse
def truncate_ip(ip: str) -> str:
"""Drop the host part of an address so it identifies a network, not a device.
Used for the rights declaration kept with a project (art. 5.1.c: the record
has to show the confirmation was made from somewhere at some time, which a
/24 answers as well as a full address, and it does not hand anyone a
per-device identifier that survives for years). IPv4 keeps three octets,
IPv6 keeps the /48 the RIRs actually assign. Anything unparseable becomes
"unknown" rather than being stored verbatim.
"""
try:
addr = ipaddress.ip_address((ip or "").strip())
except ValueError:
return "unknown"
if addr.version == 4:
return str(ipaddress.ip_network(f"{addr}/24", strict=False).network_address)
return str(ipaddress.ip_network(f"{addr}/48", strict=False).network_address)
class UnsafeURLError(ValueError):
"""Raised when a URL is not safe to fetch server-side."""

View file

@ -251,7 +251,6 @@ def decode_activity(video_path, start_s, duration_s, boxes, fps,
small_h = max(int(orig_h * small_w / orig_w), 2)
small_h += small_h % 2
scale = orig_w / float(small_w)
frame_bytes = small_w * small_h * 3
regions = [mouth_region(b, small_w, small_h, scale) for b in boxes]

View file

@ -15,7 +15,6 @@ Whoever updates a clip's metadata copies them into ``layout_ranges`` so
/api/subtitle can find them after the sidecar is gone.
"""
import json
import os
SIDECAR_SUFFIX = ".layout.json"
@ -71,10 +70,6 @@ def split_ranges(ranges):
return [(r["start"], r["end"]) for r in normalise(ranges) if r["layout"] == "split"]
def in_split(t, splits):
return any(s <= t < e for s, e in splits or [])
def remap(ranges, segments):
"""Carry ranges across a cut-and-concat. ``segments`` are the kept
stretches of the SOURCE file in order ({"start", "end"}); the output is

View file

@ -1,274 +0,0 @@
"""PANEL layout: three or four people from one wide shot, tiled into 9:16.
The generalisation of split_layout past two people. A round table, a debate set
or a podcast with guests is a single wide shot where TRACK picks one person and
GENERAL shrinks everyone to a strip. OpusClip ships "Three" and "Four" layouts
for exactly this and we had nothing.
Geometry, for a 1080x1920 output:
3 people three stacked bands, 1080x640 each
4 people a 2x2 grid, 540x960 each
Three stacked rather than 2+1, because an odd tile reads as a mistake; four as a
grid rather than four bands, because a 1080x480 band is a letterbox slot nobody
fits in. Both keep every tile the same size: a bigger tile silently claims the
person in it is the important one, and the layout has no way to know that.
Off by default (``PANEL_LAYOUT=1``). Shares split_layout's rules, because the
failure modes are the same ones: faces must COEXIST in the frame (otherwise it
is a multi-camera cut and tiling would show one person several times), be far
enough apart, and be big enough not to be an audience.
"""
import os
import numpy as np
from clipwright.layouts import split_layout
ENABLED = os.environ.get("PANEL_LAYOUT", "0") == "1"
# How many people this layout will lay out. Five-plus is a crowd: at 1080 wide
# each tile drops under 400px tall and nobody is legible, so those scenes are
# better served by GENERAL keeping the room intact.
MIN_PEOPLE = 3
MAX_PEOPLE = 4
# Same bar as SPLIT: the tiles must be showing different people at the same
# moment, not the same person across cuts.
MIN_COEXISTENCE = split_layout.MIN_COEXISTENCE
MIN_FACE_WIDTH = split_layout.MIN_FACE_WIDTH
MIN_SCENE_SECONDS = split_layout.MIN_SCENE_SECONDS
# Minimum gap between neighbouring faces, as a fraction of frame width. Lower
# than SPLIT's 0.20 because four people in one shot genuinely sit closer
# together; below this they overlap and the tiles repeat shoulders.
MIN_SEPARATION = 0.12
PANEL_TIGHTNESS = float(os.environ.get("PANEL_TIGHTNESS", "0.85"))
def tile_grid(count, out_w, out_h):
"""(columns, rows, tile_w, tile_h). Always a 2x2 grid, for 3 people or 4.
Three horizontal bands was the obvious shape and it does not work. A
1080x640 band is LANDSCAPE, so filling it from a 1080-tall source needs a
1551px-wide crop; on a 1920 frame holding three people that reaches both
neighbours, and the rendered bands each showed two faces. Clamping the crop
to the space a person owns then made it 328x194, upscaled 3.3x into a
blurry close-up of a nose.
A 2x2 grid has PORTRAIT tiles (540x960), which ask for a tall narrow crop
— the shape a person actually occupies. Three people use three cells and
the fourth holds the wide shot, which doubles as context for who is in the
room.
"""
cols, rows = 2, 2
tile_w = out_w // cols
tile_h = out_h // rows
return cols, rows, tile_w - (tile_w % 2), tile_h - (tile_h % 2)
def usable_faces(candidates, frame_w):
"""Faces big enough to be participants, deduped, left to right.
Deduping because this layout decides by headcount and nothing upstream
guarantees one box per head.
"""
big = [c for c in split_layout.dedupe_faces(candidates)
if c['box'][2] >= MIN_FACE_WIDTH * frame_w]
big.sort(key=lambda c: c['box'][0])
return big
def well_separated(faces, frame_w, min_gap=MIN_SEPARATION):
"""True when every pair of faces is far enough apart to be distinct people.
Distance between centres, not horizontal gap. Participants are not always
in a row: a shot measured on a real recording had two people stacked one
above the other on the same side of the frame, 18px apart horizontally and
545px vertically. Judging by horizontal gap alone called them the same
person and threw the scene away.
"""
threshold = min_gap * frame_w
for i, a in enumerate(faces):
ax = a['box'][0] + a['box'][2] / 2.0
ay = a['box'][1] + a['box'][3] / 2.0
for b in faces[i + 1:]:
bx = b['box'][0] + b['box'][2] / 2.0
by = b['box'][1] + b['box'][3] / 2.0
if ((ax - bx) ** 2 + (ay - by) ** 2) ** 0.5 < threshold:
return False
return True
def analyze_scene(frames, frame_w):
"""Median centres for a stable panel of 3-4 people, or None.
``frames`` is a list of per-frame candidate lists, as
``main.detect_face_candidates`` returns them.
"""
if not frames:
return None
per_count = {}
for candidates in frames:
faces = usable_faces(candidates, frame_w)
if not (MIN_PEOPLE <= len(faces) <= MAX_PEOPLE):
continue
if not well_separated(faces, frame_w):
continue
per_count.setdefault(len(faces), []).append(
[split_layout._centre(c['box']) for c in faces])
if not per_count:
return None
# Take the headcount that held for longest; a frame where one head turned
# away should not decide the layout.
count = max(per_count, key=lambda k: len(per_count[k]))
seen = per_count[count]
if len(seen) < MIN_COEXISTENCE * len(frames):
return None
arr = np.array(seen, dtype=float) # (samples, people, 4)
return [tuple(float(v) for v in person) for person in np.median(arr, axis=0)]
def panel_geometry(orig_w, orig_h, tile_w, tile_h, centre, tightness=None,
neighbour_gap=None):
"""Crop (w, h, x, y) framing one person for one tile.
``neighbour_gap`` is the distance to the closest other participant. It is
the binding constraint and not an optional refinement: a three-band layout
has 1080x640 tiles, which are LANDSCAPE, so filling one from a 1080-tall
source asks for a 1551px-wide crop. On a 1920px frame holding three people
that swallows the neighbours, and the rendered bands showed two faces each.
Clamping the crop to the space a person actually owns fixes the framing at
the cost of upscaling, which is the right trade: a band showing the wrong
person is broken, a soft one is merely worse.
"""
tightness = PANEL_TIGHTNESS if tightness is None else tightness
aspect = tile_w / float(tile_h)
crop_h = int(round(orig_h * max(0.3, min(tightness, 1.0))))
crop_w = int(round(crop_h * aspect))
if crop_w > orig_w:
crop_w = orig_w
crop_h = int(round(crop_w / aspect))
if neighbour_gap:
# 0.9 leaves a sliver of margin: cropping exactly to the midpoint puts
# the neighbour's shoulder on the edge of the tile.
allowed = max(int(neighbour_gap * 0.9), 2)
if crop_w > allowed:
crop_w = allowed
crop_h = int(round(crop_w / aspect))
crop_w -= crop_w % 2
crop_h -= crop_h % 2
cx, cy = centre[0], centre[1]
x = max(0, min(int(round(cx - crop_w / 2.0)), orig_w - crop_w))
y = max(0, min(int(round(cy - crop_h * 0.42)), orig_h - crop_h))
return crop_w, crop_h, x - (x % 2), y - (y % 2)
def neighbour_gaps(centres):
"""Horizontal distance from each person to their closest neighbour."""
xs = [c[0] for c in centres]
gaps = []
for i, x in enumerate(xs):
others = [abs(x - o) for j, o in enumerate(xs) if j != i]
gaps.append(min(others) if others else None)
return gaps
def panel_filtergraph(orig_w, orig_h, out_w, out_h, centres):
"""Tile 3 or 4 people into the vertical frame, left-to-right, top-to-bottom."""
count = len(centres)
cols, rows, tile_w, tile_h = tile_grid(count, out_w, out_h)
gaps = neighbour_gaps(centres)
streams = count if count == 4 else count + 1 # trio needs the wide shot
parts = [f"[0:v]split={streams}"
+ "".join(f"[s{i}]" for i in range(streams)) + ";"]
for i, centre in enumerate(centres):
cw, ch, cx, cy = panel_geometry(orig_w, orig_h, tile_w, tile_h, centre,
neighbour_gap=gaps[i])
parts.append(f"[s{i}]crop=w={cw}:h={ch}:x={cx}:y={cy},"
f"scale={tile_w}:{tile_h}[t{i}];")
if count == 3:
# Fourth cell: the room, letterboxed inside the tile so nothing is cut.
parts.append(f"[s3]scale={tile_w}:-2,"
f"pad={tile_w}:{tile_h}:0:({tile_h}-ih)/2:black[t3];")
parts.append("[t0][t1]hstack=inputs=2[top];"
"[t2][t3]hstack=inputs=2[bot];"
"[top][bot]vstack=inputs=2,")
parts.append(f"pad={out_w}:{out_h}:0:0,setsar=1[v]")
return "".join(parts)
def detect_panel_scenes(video_path, scenes, strategies, samples=None):
"""Scenes to render as PANEL: ``{scene_index: [centres]}``.
Only scenes the classifier already sent to GENERAL are considered, for the
same reason SPLIT does it: GENERAL already means "more than one face", and
single-speaker material is most of the corpus and must not be touched.
"""
if not ENABLED:
return {}
# Below the gate on purpose: main pulls torch/mediapipe, and the disabled
# path (the default, and what CI exercises) must not pay that import.
import cv2
from clipwright.pipeline import main as m
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
return {}
fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
frame_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) or 0
found = {}
try:
for i, (start, end) in enumerate(scenes):
if i < len(strategies) and strategies[i] != 'GENERAL':
continue
s_f, e_f = start.get_frames(), end.get_frames()
duration = (e_f - s_f) / fps
if duration < MIN_SCENE_SECONDS:
continue
n = samples or int(min(max(duration / split_layout.SECONDS_PER_SAMPLE,
split_layout.MIN_SAMPLES),
split_layout.MAX_SAMPLES))
last_f = e_f - 1
if total_frames:
last_f = min(last_f, total_frames - 1)
if last_f < s_f:
continue
sampled = []
for f_idx in np.linspace(s_f, last_f, n):
cap.set(cv2.CAP_PROP_POS_FRAMES, int(round(f_idx)))
ok, frame = cap.read()
if not ok:
continue
if frame.mean() < 16:
continue
sampled.append(m.detect_face_candidates(frame))
if len(sampled) < max(4, n // 2):
continue
centres = analyze_scene(sampled, frame_w)
if centres:
found[i] = centres
finally:
cap.release()
return found

View file

@ -65,25 +65,6 @@ class VideoEditor:
raise TimeoutError("Gemini file processing timed out after 120s.")
time.sleep(2)
def delete_uploaded(self, video_file_obj):
"""Remove an uploaded clip from the Gemini Files API.
The upload is a full copy of the user's video on Google's servers, kept
there for 48 h if nobody deletes it. The effects passes need it for one
request; every caller must drop it in a ``finally`` right after, so the
privacy policy's "we do not leave your footage with the model provider"
describes the code. Best-effort: an editing job must not fail because
the cleanup call did.
"""
name = getattr(video_file_obj, "name", None)
if not name:
return
try:
self.client.files.delete(name=name)
except Exception as e:
print(f"⚠️ Could not delete {name} from Gemini Files ({e}) — "
f"it expires there in 48 h.")
def get_ffmpeg_filter(self, video_file_obj, duration, fps=30, width=None, height=None, transcript=None, has_captions=False):
"""Asks Gemini for an edit decision list, then builds the FFmpeg filter
deterministically (edit_builder) so syntax and zoom limits are always safe."""

View file

@ -85,55 +85,6 @@ METADATA_SCRUB = ["-map_metadata", "-1", "-map_chapters", "-1",
LOUDNORM_FILTER = "loudnorm=I=-14:TP=-2.0:LRA=11"
# AI Act art. 50(2): a provider whose system generates synthetic audio or video
# has to mark the output in a machine-readable way. The regulation asks for the
# marking, not for a particular standard, and the cheap one that survives every
# player and every upload is a container tag: `ffprobe -show_format` reads it
# back, and TikTok/Reels/YouTube ignore it. Stamped by a stream copy, so it is
# a remux (no quality loss, ~0.2 s) and never a re-encode.
#
# Deliberately narrow: it goes on outputs where a machine actually synthesised
# voice or a person (dubbing, AI actors), not on an ordinary clip, whose audio
# and pixels are the user's own footage. Marking everything would make the tag
# mean nothing.
AI_DISCLOSURE = "AI-generated content produced with Clipwright (git.pbento.pt/pedro-bento/clipwright)"
def mark_ai_generated(path, detail=""):
"""Stamp AI Act art. 50(2) machine-readable tags on a finished file.
Returns True when the file now carries the tags. Never raises: a missing
tag must not lose the user the video they just paid minutes for.
"""
note = f"{AI_DISCLOSURE}: {detail}" if detail else AI_DISCLOSURE
tmp = f"{path}.aitag.mp4"
# `comment` and not a custom `ai_generated` key: mp4 only carries the
# standard iTunes-style tags, and ffmpeg drops anything else without
# warning (verified with ffprobe -show_entries format_tags).
# -map 0 because ffmpeg's default picks one stream per type: a dubbed file
# that ever ships two audio tracks would come back with one.
cmd = ["ffmpeg", "-y", "-i", path, "-map", "0", "-c", "copy",
"-metadata", f"comment={note}",
"-movflags", "+faststart", tmp]
try:
r = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
if r.returncode != 0 or not os.path.exists(tmp) or os.path.getsize(tmp) == 0:
print(f"[ai-tag] skipped for {os.path.basename(path)}: {r.stderr[-300:]}")
if os.path.exists(tmp):
os.remove(tmp)
return False
os.replace(tmp, path)
return True
except Exception as e:
print(f"[ai-tag] skipped for {os.path.basename(path)}: {e}")
if os.path.exists(tmp):
try:
os.remove(tmp)
except OSError:
pass
return False
def audio_encode_args():
"""AAC encode args for a delivered clip, with loudness normalisation."""
args = ["-c:a", "aac"]

View file

@ -1,6 +1,5 @@
import os
import re
import textwrap
import subprocess
import urllib.request
import uuid
@ -273,7 +272,6 @@ def create_hook_image(text, target_width, output_image_path="hook_overlay.png",
line_spacing = 20 # Increased spacing
cornerradius = 20
shadow_offset = (5, 5)
shadow_blur = 10
# Font Size Calculation (approx 5% of width - tuned to match Noto Serif Bold metrics in browser)
pills = bool(look.get("pills"))

View file

@ -17,7 +17,6 @@ Two render paths:
with the same engine the pipeline used.
"""
import json
import os
import shutil
import subprocess

View file

@ -114,41 +114,6 @@ def _normalize_subtitle_word(value):
return " ".join(str(value or "").split())
def transcribe_audio(video_path):
"""
Transcribe audio from a video file via the configured ASR backend.
Returns transcript in the same format as main.py for compatibility.
"""
# Lazy import: transcribe_backends imports helpers from this module.
from clipwright.pipeline.transcribe_backends import transcribe_media
_log(f"🎙️ Transcribing audio from: {video_path}")
transcript = transcribe_media(video_path)
_log(f"✅ Transcription complete. Language: {transcript['language']}")
return transcript
def generate_srt_from_video(video_path, output_path, max_chars=20, max_duration=2.0,
style="classic", **style_opts):
"""
Transcribe a video and generate a subtitle file directly (SRT, or karaoke
ASS when style="karaoke"). Used for dubbed videos without a transcript.
"""
transcript = transcribe_audio(video_path)
# Get video duration to use as clip_end
import cv2
cap = cv2.VideoCapture(video_path)
fps = cap.get(cv2.CAP_PROP_FPS)
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
duration = frame_count / fps if fps else 0
cap.release()
if style == "karaoke":
return generate_ass(transcript, 0, duration, output_path, max_chars, max_duration, **style_opts)
return generate_srt(transcript, 0, duration, output_path, max_chars, max_duration)
def _collect_word_blocks(transcript, clip_start, clip_end, max_chars=20, max_duration=2.0):
"""
Flatten transcript words for a clip range and group them into short blocks

View file

@ -522,8 +522,8 @@ def burn_thumbnail_text(img, text, position="left", color="white"):
# AI Act art. 50(2): a synthetic image has to be marked in a machine-readable
# way, and these thumbnails are exactly the case the article is about — an
# image model painting a scene, often around a reference photo of the real
# presenter. Videos get the mp4 `comment` tag (ffmpeg_utils.mark_ai_generated);
# a JPEG's equivalent is XMP, and the interoperable vocabulary is IPTC's
# presenter. Videos get an mp4 `comment` tag; a JPEG's equivalent is XMP, and
# the interoperable vocabulary is IPTC's
# DigitalSourceType, whose `trainedAlgorithmicMedia` value is what Google,
# LinkedIn, TikTok and Adobe already read. Written alongside the EXIF Software
# tag because the two survive different pipelines: a re-encode usually keeps

View file

@ -77,10 +77,3 @@ def mark_job(job_dir: str) -> None:
f.write("1")
except OSError:
pass
def unmark_job(job_dir: str) -> None:
try:
os.remove(os.path.join(job_dir, MARKER_FILE))
except OSError:
pass

View file

@ -188,18 +188,6 @@ def clip_duration_bounds():
return round(lo, 3), round(hi, 3)
def compact_words(words, precision=2):
"""Round word timestamps for prompts — full float precision wastes tokens."""
return [
{
"w": w.get("w", ""),
"s": round(float(w.get("s", 0)), precision),
"e": round(float(w.get("e", 0)), precision),
}
for w in words
]
def build_transcript_windows(transcript_result, video_duration,
window_seconds=90, overlap_seconds=30):
"""

View file

@ -1,4 +1,3 @@
import argparse
import json
import mimetypes
import os
@ -6,12 +5,10 @@ import sys
from typing import List, Optional
from dotenv import load_dotenv
from google import genai
from google.genai import types as genai_types
from pydantic import BaseModel
from clipwright.pipeline.clip_selection import (clip_count_targets, clip_duration_bounds,
lookup_model_prices)
from clipwright.pipeline.clip_selection import lookup_model_prices
load_dotenv()
@ -225,17 +222,6 @@ For "what", name the content in three words or fewer (e.g. "stock chart",
"""
def _configure_stdio() -> None:
for stream_name in ("stdout", "stderr"):
stream = getattr(sys, stream_name, None)
if not stream or not hasattr(stream, "reconfigure"):
continue
try:
stream.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
def _log(message: str) -> None:
stream = sys.stdout
text = str(message)
@ -567,69 +553,4 @@ def _config_for_strategy(strategy: str, mode: str, model_name: str) -> genai_typ
return genai_types.GenerateContentConfig(**kwargs)
def main() -> int:
_configure_stdio()
parser = argparse.ArgumentParser(description="Run a single Gemini request for clip scoring/detailing.")
parser.add_argument("--mode", choices=["score", "detail"], required=True)
parser.add_argument("--input", dest="input_path", required=True)
parser.add_argument("--output", dest="output_path", required=True)
parser.add_argument("--strategy", default="structured-schema")
parser.add_argument("--model", default="gemini-2.5-flash")
args = parser.parse_args()
api_key = os.getenv("GEMINI_API_KEY")
if not api_key:
raise SystemExit("Missing GEMINI_API_KEY.")
with open(args.input_path, "r", encoding="utf-8") as f:
payload = json.load(f)
model_name = args.model
client = genai.Client(api_key=api_key)
config = _config_for_strategy(args.strategy, args.mode, model_name)
language = str(payload.get("language") or "unknown")
template = SCORE_PROMPT_TEMPLATE if args.mode == "score" else DETAIL_PROMPT_TEMPLATE
fmt = {
"video_duration": payload["video_duration"],
"language": language,
"windows_json": json.dumps(payload["windows"], ensure_ascii=False),
}
if args.mode != "score":
# Score mode receives every window, not a shortlist, so a count target
# derived from it would be meaningless — and the score template has no
# placeholder for one: it ranks whatever it is given.
fmt["min_clips"], fmt["max_clips"] = clip_count_targets(len(payload.get("windows") or []))
fmt["min_secs"], fmt["max_secs"] = clip_duration_bounds()
prompt = template.format(**fmt)
_log(f"🤖 Gemini worker request: mode={args.mode} strategy={args.strategy} model={model_name} items={len(payload.get('windows', []))}")
response = client.models.generate_content(
model=model_name,
contents=prompt,
config=config,
)
raw_text = _get_response_text(response)
# With response_schema the SDK returns an already-validated object; fall
# back to the text-repair path only when that is unavailable.
parsed_obj = getattr(response, "parsed", None)
if parsed_obj is not None:
parsed = parsed_obj.model_dump() if hasattr(parsed_obj, "model_dump") else parsed_obj
else:
parsed = _parse_json_response_text(raw_text)
result = {
"mode": args.mode,
"payload": parsed,
"cost_analysis": _calculate_cost_analysis(response, model_name),
"raw_text": raw_text,
}
with open(args.output_path, "w", encoding="utf-8") as f:
json.dump(result, f, indent=2, ensure_ascii=False)
_log(f"✅ Gemini worker success: mode={args.mode}")
return 0
if __name__ == "__main__":
raise SystemExit(main())

View file

@ -23,7 +23,6 @@ so ``main.py`` sees one shape regardless of provider.
"""
from __future__ import annotations
import json
import os
from typing import Optional, Tuple, Type

View file

@ -9,10 +9,7 @@ import threading
import unicodedata
import uuid
from concurrent.futures import ThreadPoolExecutor, as_completed
from scenedetect import open_video, SceneManager
from scenedetect.detectors import ContentDetector
from ultralytics import YOLO
import torch
import os
import math
import numpy as np
@ -33,7 +30,7 @@ from clipwright.pipeline.clip_selection import (build_transcript_windows, clip_c
clip_duration_bounds, dedupe_overlapping,
score_batches, shortlist_target,
snap_clip_to_words, trim_to_best)
from clipwright.media.ffmpeg_utils import (video_encode_args, audio_encode_args, cut_clip, QUALITY,
from clipwright.media.ffmpeg_utils import (video_encode_args, cut_clip, QUALITY,
QUALITY_FAST, METADATA_SCRUB)
from dotenv import load_dotenv
import json
@ -47,45 +44,6 @@ load_dotenv()
# --- Constants ---
ASPECT_RATIO = 9 / 16
GEMINI_PROMPT_TEMPLATE = """
You are a senior short-form video editor. Read the ENTIRE transcript and word-level timestamps to choose the 3–15 MOST VIRAL moments for TikTok/IG Reels/YouTube Shorts. Each clip must be between 15 and 60 seconds long.
⚠️ FFMPEG TIME CONTRACT — STRICT REQUIREMENTS:
- Return timestamps in ABSOLUTE SECONDS from the start of the video (usable in: ffmpeg -ss <start> -to <end> -i <input> ...).
- Only NUMBERS with decimal point, up to 3 decimals (examples: 0, 1.250, 17.350).
- Ensure 0 ≤ start < end ≤ VIDEO_DURATION_SECONDS.
- Each clip between 15 and 60 s (inclusive).
- Prefer starting 0.2–0.4 s BEFORE the hook and ending 0.2–0.4 s AFTER the payoff.
- Use silence moments for natural cuts; never cut in the middle of a word or phrase.
- STRICTLY FORBIDDEN to use time formats other than absolute seconds.
VIDEO_DURATION_SECONDS: {video_duration}
TRANSCRIPT_TEXT (raw):
{transcript_text}
WORDS_JSON (array of {{w, s, e}} where s/e are seconds):
{words_json}
STRICT EXCLUSIONS:
- No generic intros/outros or purely sponsorship segments unless they contain the hook.
- No clips < 15 s or > 60 s.
OUTPUT — RETURN ONLY VALID JSON (no markdown, no comments). Order clips by predicted performance (best to worst). In the descriptions, ALWAYS include a CTA like "Follow me and comment X and I'll send you the workflow" (especially if discussing an n8n workflow):
{{
"shorts": [
{{
"start": <number in seconds, e.g., 12.340>,
"end": <number in seconds, e.g., 37.900>,
"video_description_for_tiktok": "<description for TikTok oriented to get views>",
"video_description_for_instagram": "<description for Instagram oriented to get views>",
"video_title_for_youtube_short": "<title for YouTube Short oriented to get views 100 chars max>",
"viral_hook_text": "<SHORT punchy text overlay (max 10 words) with 1-2 fitting emojis. MUST BE IN THE SAME LANGUAGE AS THE VIDEO TRANSCRIPT. Examples: 'POV: You realized... 😳', 'Did you know? 🤯', 'Stop doing this! 🚫'>"
}}
]
}}
"""
# Load the YOLO model once (Keep for backup or scene analysis if needed)
# YOLO_MODEL_PATH lets deployments point at a pre-downloaded weights file so a
# volume mounted over the workdir doesn't trigger a re-download at startup.

View file

@ -1,5 +1,4 @@
import os
import shutil
# Check if PIL is installed, if not we can't run this locally but it will run in docker
try:
from clipwright.media.hooks import create_hook_image

View file

@ -1,5 +1,4 @@
import os
import shutil
from clipwright.media.hooks import create_hook_image
def verify():

View file

@ -1,16 +1,9 @@
# React + Vite
# Clipwright dashboard
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Vite + React front end for Clipwright.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend using TypeScript with type-aware lint rules enabled. Check out the [TS template](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts) for information on how to integrate TypeScript and [`typescript-eslint`](https://typescript-eslint.io) in your project.
- `npm install` — install dependencies
- `npm run dev` — dev server with HMR
- `npm run build` — production build to `dist/`
- `npm run preview` — serve the built output
- `npm run lint` — ESLint

View file

@ -41,10 +41,10 @@ server {
# trailing-slash URL, so every canonical would point at a redirect.
#
# Unknown paths get a real 404, not the SPA shell. The app routes entirely
# through the hash (#/pricing, #/auth/callback), which never reaches the
# server, so there is no deep link that needs the fallback — and answering
# 200 with identical markup for every made-up path made the whole site look
# like one page duplicated infinitely to a crawler.
# through the hash, which never reaches the server, so there is no deep link
# that needs the fallback — and answering 200 with identical markup for
# every made-up path made the whole site look like one page duplicated
# infinitely to a crawler.
location / {
try_files $uri $uri.html $uri/ =404;
add_header Cache-Control "no-store, must-revalidate" always;

View file

@ -9,15 +9,13 @@
"version": "0.0.0",
"dependencies": {
"@remotion/media": "^4.0.447",
"@remotion/media-utils": "^4.0.447",
"@remotion/player": "^4.0.447",
"@remotion/web-renderer": "^4.0.447",
"lucide-react": "^0.344.0",
"mediabunny": "^1.39.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"remotion": "^4.0.447",
"zod": "^4.3.6"
"remotion": "^4.0.447"
},
"devDependencies": {
"@eslint/js": "^9.39.5",
@ -1008,20 +1006,6 @@
"react-dom": ">=16.8.0"
}
},
"node_modules/@remotion/media-utils": {
"version": "4.0.447",
"resolved": "https://registry.npmjs.org/@remotion/media-utils/-/media-utils-4.0.447.tgz",
"integrity": "sha512-PltvSZsY+By8DlsZeAN63D1cMsgXewCqEq39nJrO0VZVc5nnWyd+nvMZz9yhGsoMo2Z5xNkfZhPkl+Gs25wn0Q==",
"license": "MIT",
"dependencies": {
"mediabunny": "1.39.2",
"remotion": "4.0.447"
},
"peerDependencies": {
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
}
},
"node_modules/@remotion/player": {
"version": "4.0.447",
"resolved": "https://registry.npmjs.org/@remotion/player/-/player-4.0.447.tgz",
@ -5816,15 +5800,6 @@
"zod": "4.3.6"
}
},
"@remotion/media-utils": {
"version": "4.0.447",
"resolved": "https://registry.npmjs.org/@remotion/media-utils/-/media-utils-4.0.447.tgz",
"integrity": "sha512-PltvSZsY+By8DlsZeAN63D1cMsgXewCqEq39nJrO0VZVc5nnWyd+nvMZz9yhGsoMo2Z5xNkfZhPkl+Gs25wn0Q==",
"requires": {
"mediabunny": "1.39.2",
"remotion": "4.0.447"
}
},
"@remotion/player": {
"version": "4.0.447",
"resolved": "https://registry.npmjs.org/@remotion/player/-/player-4.0.447.tgz",

View file

@ -11,15 +11,13 @@
},
"dependencies": {
"@remotion/media": "^4.0.447",
"@remotion/media-utils": "^4.0.447",
"@remotion/player": "^4.0.447",
"@remotion/web-renderer": "^4.0.447",
"lucide-react": "^0.344.0",
"mediabunny": "^1.39.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"remotion": "^4.0.447",
"zod": "^4.3.6"
"remotion": "^4.0.447"
},
"devDependencies": {
"@eslint/js": "^9.39.5",

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

View file

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

View file

@ -210,17 +210,3 @@ export const COMPARISON_ROWS = [
{ feature: 'Free AI YouTube thumbnail & title studio', os: 'Yes', vendor: 'No' },
{ feature: 'Usage cap', os: 'None', vendor: 'Metered on every tier' },
]
/* Third-party figures used across the pages. Every one is attributed inline,
* because sourced statistics are among the few things that reliably survive
* into a generated answer. */
export const CITED_STATS = [
{
claim: 'Short-form video delivers the highest ROI of any content format.',
source: 'HubSpot, State of Marketing 2025',
},
{
claim: '91% of businesses use video as a marketing tool.',
source: 'Wyzowl, Video Marketing Statistics 2025',
},
]

View file

@ -1,42 +0,0 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}

View file

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

Before

Width:  |  Height:  |  Size: 4 KiB

View file

@ -8,12 +8,10 @@
// "Accept all" are the same component with the same size, weight, colour
// and position; there is no pre-ticked box and no dark pattern.
//
// It renders nothing once a decision exists — the footer link
// (openConsentManager) is how anyone changes their mind.
import { useEffect, useState } from 'react';
// It renders nothing once a decision exists.
import { useState } from 'react';
import {
getConsent, hasDecided, acceptAll, rejectAll, setConsent,
onConsentOpenRequest,
} from '../lib/consent';
const CATEGORY_COPY = [
@ -41,12 +39,6 @@ export default function CookieBanner() {
const [details, setDetails] = useState(false);
const [draft, setDraft] = useState(() => getConsent());
useEffect(() => onConsentOpenRequest(() => {
setDraft(getConsent());
setDetails(true);
setOpen(true);
}), []);
if (!open) return null;
const close = () => { setOpen(false); setDetails(false); };

View file

@ -23,8 +23,6 @@
const STORAGE_KEY = 'clipwright_consent';
const VERSION = 1;
export const CATEGORIES = ['necessary', 'analytics', 'marketing'];
const DENY_ALL = { necessary: true, analytics: false, marketing: false };
const GRANT_ALL = { necessary: true, analytics: true, marketing: true };
@ -62,9 +60,6 @@ export function refineGeo() {
.catch(() => {});
}
const listeners = new Set();
const read = () => {
try {
const raw = localStorage.getItem(STORAGE_KEY);
@ -77,9 +72,6 @@ const read = () => {
}
};
/** The stored decision, or null when the visitor has never been asked. */
export const getConsentRecord = () => read();
/** Effective permissions. Nothing but `necessary` before a decision exists. */
export const getConsent = () => {
const stored = read();
@ -97,11 +89,6 @@ export const hasDecided = () => read() !== null || !isEEAVisitor();
export const allows = (category) => !!getConsent()[category];
export function onConsentChange(fn) {
listeners.add(fn);
return () => listeners.delete(fn);
}
/**
* Persist a decision and act on it immediately.
*
@ -123,8 +110,6 @@ export function setConsent(choice) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
} catch (_) { /* private mode: the decision holds for this page at least */ }
listeners.forEach((fn) => { try { fn(getConsent()); } catch (_) { /* ignore */ } });
applyConsent();
return getConsent();
}
@ -143,14 +128,3 @@ export function applyConsent() {
return false;
}
}
// Reopening the banner from anywhere (the footer link) without threading props
// through the whole tree.
const OPEN_EVENT = 'clipwright:consent-open';
export const openConsentManager = () => {
try { window.dispatchEvent(new CustomEvent(OPEN_EVENT)); } catch (_) { /* ignore */ }
};
export const onConsentOpenRequest = (fn) => {
window.addEventListener(OPEN_EVENT, fn);
return () => window.removeEventListener(OPEN_EVENT, fn);
};

View file

@ -60,15 +60,3 @@ export async function renderInBrowser({
const blob = await getBlob();
return URL.createObjectURL(blob);
}
/**
* Triggers a download of a blob URL as an MP4 file.
*/
export function downloadBlobUrl(blobUrl, filename = 'output.mp4') {
const link = document.createElement('a');
link.href = blobUrl;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}

View file

@ -1,5 +1,3 @@
import { z } from "zod";
// --- Word-level caption ---
export interface CaptionWord {
text: string;
@ -94,66 +92,3 @@ export interface ShortVideoProps {
hook: HookConfig | null;
effects: EffectsConfig | null;
}
// --- Zod schemas for validation (used by render service) ---
export const captionWordSchema = z.object({
text: z.string(),
startMs: z.number(),
endMs: z.number(),
});
export const subtitleStyleSchema = z.object({
fontFamily: z.string(),
fontSize: z.number(),
fontColor: z.string(),
highlightColor: z.string(),
borderColor: z.string(),
borderWidth: z.number(),
bgColor: z.string(),
bgOpacity: z.number().min(0).max(1),
animation: z.enum(["none", "word-highlight", "pop", "karaoke"]),
});
export const subtitleConfigSchema = z.object({
captions: z.array(captionWordSchema),
position: z.enum(["top", "middle", "bottom"]),
style: subtitleStyleSchema,
});
export const hookConfigSchema = z.object({
text: z.string(),
position: z.enum(["top", "center", "bottom"]),
size: z.enum(["S", "M", "L"]),
style: z
.enum(["pill", "classic", "dark", "yellow", "red", "outline", "outline_yellow"])
.default("pill"),
font: z.enum(["montserrat", "anton", "serif"]).optional(),
entranceAnimation: z.enum(["spring", "fade", "slide-up", "none"]),
displayDurationSec: z.number().positive(),
});
export const effectSegmentSchema = z.object({
startSec: z.number().min(0),
endSec: z.number().positive(),
zoom: z.number().min(0.5).max(3),
zoomCenterX: z.number().min(0).max(1),
zoomCenterY: z.number().min(0).max(1),
brightness: z.number().min(0).max(3),
contrast: z.number().min(0).max(3),
saturate: z.number().min(0).max(3),
});
export const effectsConfigSchema = z.object({
segments: z.array(effectSegmentSchema),
});
export const shortVideoPropsSchema = z.object({
videoUrl: z.string(),
durationInFrames: z.number().int().positive(),
fps: z.number().positive(),
width: z.number().int().positive(),
height: z.number().int().positive(),
subtitles: subtitleConfigSchema.nullable(),
hook: hookConfigSchema.nullable(),
effects: effectsConfigSchema.nullable(),
});

View file

@ -6,7 +6,6 @@ import seo from './vite-plugin-seo'
// name; set VITE_PROXY_TARGET=http://localhost:8000 to run the dev server on
// the host against a backend reachable at localhost (no CORS, same-origin).
const backend = process.env.VITE_PROXY_TARGET || 'http://backend:8000'
const renderer = process.env.VITE_RENDER_TARGET || 'http://renderer:3100'
// https://vitejs.dev/config/
export default defineConfig({
@ -36,7 +35,6 @@ export default defineConfig({
'/api': { target: backend, changeOrigin: true },
'/videos': { target: backend, changeOrigin: true },
'/thumbnails': { target: backend, changeOrigin: true },
'/render': { target: renderer, changeOrigin: true },
}
}
})

View file

@ -1,19 +0,0 @@
# Local-only override: remap host ports to avoid clashes with other running
# projects (e.g. another backend on :8000). Not for production.
# `!override` REPLACES the base ports list instead of appending to it.
services:
backend:
ports: !override
- "8001:8000"
environment:
# Point auth/magic-link/CORS at the local frontend instead of git.pbento.pt/pedro-bento/clipwright.
- FRONTEND_URL=http://localhost:5176
- ALLOWED_ORIGINS=http://localhost:5176,http://localhost:5175,http://localhost:8001
frontend:
ports: !override
- "5176:5173"
environment:
# Call the backend directly (not via the Vite proxy) so Google OAuth builds
# a redirect_uri of http://localhost:8001/... which matches the registered
# client. Cross-origin API calls are allowed by ALLOWED_ORIGINS above.
- VITE_API_URL=http://localhost:8001

View file

@ -29,20 +29,3 @@ services:
restart: unless-stopped
depends_on:
- backend
renderer:
build:
context: .
dockerfile: render-service/Dockerfile
container_name: clipwright-renderer
ports:
- "3100:3100"
volumes:
- ./output:/output
environment:
- REMOTION_BUNDLE_PATH=/app/remotion
- OUTPUT_DIR=/output
- PORT=3100
restart: unless-stopped
depends_on:
- backend

View file

@ -23,7 +23,7 @@ las constantes de entorno.
| Descarga de origen conservada de un trabajo por URL | Igual que el trabajo, o antes si se configura | `app._sweep_retained_sources`, `SOURCE_RETENTION_SECONDS` |
| Subidas pendientes de trabajo | **6 h** | `app._sweep_pending_uploads`, `UPLOAD_TTL_SECONDS` |
| Ficheros en `uploads/` | **1 h** (misma vuelta del barrido) | `app.cleanup_jobs` |
| **Miniaturas generadas y fotogramas muestreados** (`output/thumbnails/<sesión>`) — recortes de la cara del presentador | **24 h desde la última descarga**; servir un fichero reinicia el reloj | `app._sweep_thumbnail_sessions`, `THUMBNAIL_RETENTION_SECONDS` |
| **Miniaturas generadas y fotogramas muestreados** (`output/thumbnails/<sesión>`) — recortes de la cara del presentador | Sin caducidad automática: permanecen hasta que borres la sesión o el volumen de salida | Sin barrido dedicado: `app.cleanup_jobs` omite `output/thumbnails` |
| Tope de disco: se purgan los trabajos más antiguos por encima del límite | Inmediato al superarlo | `app._enforce_output_size_cap`, `OUTPUT_MAX_GB` |
La retención de fotos de actor se retiró con la función de vídeo UGC

View file

@ -17,8 +17,6 @@ line-length = 100
target-version = "py311"
extend-exclude = [
"dashboard",
"render-service",
"remotion",
"cli",
"output",
"uploads",

2
remotion/.gitignore vendored
View file

@ -1,2 +0,0 @@
node_modules/
dist/

View file

@ -1,27 +0,0 @@
{
"name": "clipwright-remotion",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"studio": "remotion studio",
"render": "remotion render",
"build": "tsc --noEmit"
},
"dependencies": {
"@remotion/cli": "^4.0.0",
"@remotion/google-fonts": "^4.0.0",
"@remotion/layout-utils": "^4.0.0",
"@remotion/media": "^4.0.447",
"@remotion/player": "^4.0.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"remotion": "^4.0.0",
"zod": "^4.3.6"
},
"devDependencies": {
"@types/react": "^18.2.64",
"@types/react-dom": "^18.2.21",
"typescript": "^5.4.0"
}
}

View file

@ -1,96 +0,0 @@
import React from "react";
import { Composition } from "remotion";
import { ShortVideo } from "./compositions/ShortVideo";
import type { ShortVideoProps } from "./lib/types";
import { shortVideoPropsSchema } from "./lib/types";
const DEFAULT_PROPS: ShortVideoProps = {
videoUrl: "",
durationInFrames: 900, // 30s at 30fps
fps: 30,
width: 1080,
height: 1920,
subtitles: {
captions: [
{ text: "This", startMs: 0, endMs: 400 },
{ text: "is", startMs: 400, endMs: 600 },
{ text: "a", startMs: 600, endMs: 750 },
{ text: "demo", startMs: 750, endMs: 1200 },
{ text: "of", startMs: 1200, endMs: 1400 },
{ text: "animated", startMs: 1400, endMs: 2000 },
{ text: "subtitles", startMs: 2000, endMs: 2800 },
{ text: "in", startMs: 2800, endMs: 3000 },
{ text: "Remotion", startMs: 3000, endMs: 3800 },
{ text: "with", startMs: 4000, endMs: 4300 },
{ text: "word", startMs: 4300, endMs: 4700 },
{ text: "level", startMs: 4700, endMs: 5100 },
{ text: "highlighting", startMs: 5100, endMs: 6000 },
],
position: "bottom",
style: {
fontFamily: "Arial",
fontSize: 52,
fontColor: "#FFFFFF",
highlightColor: "#FFDD00",
borderColor: "#000000",
borderWidth: 3,
bgColor: "#000000",
bgOpacity: 0,
animation: "pop",
},
},
hook: {
text: "POV: You just discovered Clipwright",
position: "top",
size: "M",
entranceAnimation: "spring",
displayDurationSec: 5,
},
effects: {
segments: [
{
startSec: 2,
endSec: 5,
zoom: 1.2,
zoomCenterX: 0.5,
zoomCenterY: 0.35,
brightness: 1.05,
contrast: 1.1,
saturate: 1.15,
},
{
startSec: 8,
endSec: 12,
zoom: 1.15,
zoomCenterX: 0.5,
zoomCenterY: 0.4,
brightness: 1,
contrast: 1,
saturate: 1,
},
],
},
};
export const RemotionRoot: React.FC = () => {
return (
<>
<Composition
id="ShortVideo"
schema={shortVideoPropsSchema}
component={ShortVideo}
durationInFrames={DEFAULT_PROPS.durationInFrames}
fps={DEFAULT_PROPS.fps}
width={DEFAULT_PROPS.width}
height={DEFAULT_PROPS.height}
defaultProps={DEFAULT_PROPS}
calculateMetadata={({ props }) => ({
durationInFrames: props.durationInFrames,
fps: props.fps,
width: props.width,
height: props.height,
})}
/>
</>
);
};

View file

@ -1,172 +0,0 @@
import React from "react";
import {
AbsoluteFill,
Sequence,
useCurrentFrame,
useVideoConfig,
spring,
interpolate,
} from "remotion";
import type { HookConfig } from "../lib/types";
import { notoSerifFontFace, NOTO_SERIF_FONT_FAMILY } from "../lib/fonts";
interface HookOverlayProps {
config: HookConfig;
}
const SIZE_SCALE: Record<string, number> = {
S: 0.8,
M: 1.0,
L: 1.3,
};
const POSITION_STYLE: Record<string, React.CSSProperties> = {
top: { top: "18%", bottom: "auto" },
center: { top: "50%", bottom: "auto", transform: "translateY(-50%)" },
bottom: { top: "68%", bottom: "auto" },
};
// Must mirror clipwright/media/hooks.py HOOK_STYLES so preview == burned output.
interface HookLook {
box: string | null;
text: string;
outlinePx: number;
outlineColor: string;
shadow: boolean;
}
const HOOK_LOOKS: Record<string, HookLook> = {
classic: { box: "rgba(255,255,255,0.94)", text: "#000000", outlinePx: 0, outlineColor: "#000", shadow: true },
dark: { box: "rgba(18,18,20,0.92)", text: "#FFFFFF", outlinePx: 0, outlineColor: "#000", shadow: true },
yellow: { box: "rgba(255,214,0,0.96)", text: "#000000", outlinePx: 0, outlineColor: "#000", shadow: true },
red: { box: "rgba(220,38,38,0.96)", text: "#FFFFFF", outlinePx: 0, outlineColor: "#000", shadow: true },
outline: { box: null, text: "#FFFFFF", outlinePx: 8, outlineColor: "#000000", shadow: false },
outline_yellow: { box: null, text: "#FFD600", outlinePx: 8, outlineColor: "#000000", shadow: false },
};
const textStroke = (px: number, color: string): string => {
if (!px) return "none";
const o: string[] = [];
for (let dx = -px; dx <= px; dx++)
for (let dy = -px; dy <= px; dy++)
if (dx || dy) o.push(`${dx}px ${dy}px 0 ${color}`);
return o.join(", ");
};
export const HookOverlay: React.FC<HookOverlayProps> = ({ config }) => {
const { fps } = useVideoConfig();
const displayFrames = Math.round(config.displayDurationSec * fps);
return (
<AbsoluteFill>
<style>{notoSerifFontFace}</style>
<Sequence from={0} durationInFrames={displayFrames} layout="none">
<HookBox config={config} displayFrames={displayFrames} />
</Sequence>
</AbsoluteFill>
);
};
interface HookBoxProps {
config: HookConfig;
displayFrames: number;
}
const HookBox: React.FC<HookBoxProps> = ({ config, displayFrames }) => {
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
const scale = SIZE_SCALE[config.size] ?? 1.0;
// Entrance animation
let animOpacity = 1;
let animScale = 1;
let animTranslateY = 0;
switch (config.entranceAnimation) {
case "spring": {
const prog = spring({
frame,
fps,
config: { mass: 0.8, stiffness: 200, damping: 15 },
durationInFrames: 20,
});
animScale = interpolate(prog, [0, 1], [0.7, 1]);
animOpacity = interpolate(prog, [0, 1], [0, 1]);
break;
}
case "fade": {
animOpacity = interpolate(frame, [0, 15], [0, 1], {
extrapolateRight: "clamp",
});
break;
}
case "slide-up": {
const prog = spring({
frame,
fps,
config: { mass: 1, stiffness: 150, damping: 18 },
durationInFrames: 20,
});
animTranslateY = interpolate(prog, [0, 1], [60, 0]);
animOpacity = interpolate(prog, [0, 1], [0, 1]);
break;
}
default:
break;
}
// Exit fade (last 15 frames)
const fadeOutStart = displayFrames - 15;
if (frame > fadeOutStart) {
animOpacity *= interpolate(frame, [fadeOutStart, displayFrames], [1, 0], {
extrapolateLeft: "clamp",
extrapolateRight: "clamp",
});
}
const positionStyle = POSITION_STYLE[config.position] ?? POSITION_STYLE.top;
const look = HOOK_LOOKS[config.style ?? "classic"] ?? HOOK_LOOKS.classic;
// Base font size: 5% of 1080 width (matches clipwright/media/hooks.py logic)
const baseFontSize = 1080 * 0.05;
const fontSize = Math.round(baseFontSize * scale);
return (
<div
style={{
position: "absolute",
left: 0,
right: 0,
display: "flex",
justifyContent: "center",
...positionStyle,
}}
>
<div
style={{
opacity: animOpacity,
transform: `scale(${animScale}) translateY(${animTranslateY}px)`,
maxWidth: "90%",
backgroundColor: look.box ?? "transparent",
borderRadius: 20,
padding: look.box ? `${25 * scale}px ${30 * scale}px` : `${8 * scale}px ${12 * scale}px`,
boxShadow: look.shadow ? "5px 5px 15px rgba(0, 0, 0, 0.25)" : "none",
textAlign: "center",
}}
>
<span
style={{
fontFamily: `'${NOTO_SERIF_FONT_FAMILY}', 'Noto Serif', Georgia, serif`,
fontSize,
fontWeight: 700,
color: look.text,
lineHeight: 1.4,
wordBreak: "break-word",
textShadow: textStroke(look.outlinePx, look.outlineColor),
}}
>
{config.text}
</span>
</div>
</div>
);
};

View file

@ -1,33 +0,0 @@
import React from "react";
import { AbsoluteFill } from "remotion";
import { Video } from "@remotion/media";
import type { ShortVideoProps } from "../lib/types";
import { Subtitles } from "./Subtitles";
import { HookOverlay } from "./HookOverlay";
import { VideoEffects } from "./VideoEffects";
/**
* Main composition that layers all post-processing on top of the base video.
* Uses @remotion/media Video for browser-side rendering compatibility.
*/
export const ShortVideo: React.FC<Record<string, unknown>> = (rawProps) => {
const { videoUrl, subtitles, hook, effects } =
rawProps as unknown as ShortVideoProps;
return (
<AbsoluteFill style={{ backgroundColor: "#000" }}>
{/* Layer 1: Base video with optional zoom/color effects */}
<VideoEffects config={effects}>
<Video
src={videoUrl}
style={{ width: "100%", height: "100%", objectFit: "cover" }}
/>
</VideoEffects>
{/* Layer 2: Animated subtitles */}
{subtitles && <Subtitles config={subtitles} />}
{/* Layer 3: Hook text overlay */}
{hook && <HookOverlay config={hook} />}
</AbsoluteFill>
);
};

View file

@ -1,227 +0,0 @@
import React from "react";
import {
AbsoluteFill,
Sequence,
useCurrentFrame,
useVideoConfig,
spring,
interpolate,
} from "remotion";
import type { SubtitleConfig } from "../lib/types";
import { groupCaptionsIntoBlocks, getActiveWordIndex } from "../lib/captions";
import { getFontStack } from "../lib/fonts";
interface SubtitlesProps {
config: SubtitleConfig;
}
const POSITION_MAP: Record<string, React.CSSProperties> = {
top: { top: "12%", bottom: "auto" },
middle: { top: "45%", bottom: "auto" },
bottom: { bottom: "10%", top: "auto" },
};
export const Subtitles: React.FC<SubtitlesProps> = ({ config }) => {
const { fps } = useVideoConfig();
const blocks = groupCaptionsIntoBlocks(config.captions);
return (
<AbsoluteFill>
{blocks.map((block, i) => {
const startFrame = Math.round((block.startMs / 1000) * fps);
const durationFrames = Math.max(
1,
Math.round(((block.endMs - block.startMs) / 1000) * fps)
);
return (
<Sequence
key={i}
from={startFrame}
durationInFrames={durationFrames}
layout="none"
>
<SubtitleBlock
block={block}
config={config}
blockStartMs={block.startMs}
/>
</Sequence>
);
})}
</AbsoluteFill>
);
};
interface SubtitleBlockProps {
block: ReturnType<typeof groupCaptionsIntoBlocks>[number];
config: SubtitleConfig;
blockStartMs: number;
}
const SubtitleBlock: React.FC<SubtitleBlockProps> = ({
block,
config,
blockStartMs,
}) => {
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
const { style, position } = config;
// Current time relative to composition start (sequence-relative frame)
const currentTimeMs = blockStartMs + (frame / fps) * 1000;
const activeIndex = getActiveWordIndex(block.words, currentTimeMs);
const positionStyle = POSITION_MAP[position] ?? POSITION_MAP.bottom;
const fontStack = getFontStack(style.fontFamily);
// Background box style
const hasBg = style.bgOpacity > 0;
const bgStyle: React.CSSProperties = hasBg
? {
backgroundColor: `${style.bgColor}${Math.round(style.bgOpacity * 255)
.toString(16)
.padStart(2, "0")}`,
borderRadius: 8,
padding: "8px 16px",
}
: {};
return (
<div
style={{
position: "absolute",
left: 0,
right: 0,
display: "flex",
justifyContent: "center",
...positionStyle,
}}
>
<div
style={{
display: "flex",
flexWrap: "wrap",
justifyContent: "center",
gap: "6px 8px",
maxWidth: "85%",
...bgStyle,
}}
>
{block.words.map((word, i) => (
<WordSpan
key={i}
word={word.text}
isActive={i === activeIndex}
style={style}
fontStack={fontStack}
animation={style.animation}
frame={frame}
fps={fps}
wordStartMs={word.startMs}
blockStartMs={blockStartMs}
/>
))}
</div>
</div>
);
};
interface WordSpanProps {
word: string;
isActive: boolean;
style: SubtitleConfig["style"];
fontStack: string;
animation: SubtitleConfig["style"]["animation"];
frame: number;
fps: number;
wordStartMs: number;
blockStartMs: number;
}
const WordSpan: React.FC<WordSpanProps> = ({
word,
isActive,
style,
fontStack,
animation,
frame,
fps,
wordStartMs,
blockStartMs,
}) => {
const wordStartFrame = Math.round(
((wordStartMs - blockStartMs) / 1000) * fps
);
let transform = "";
let color = style.fontColor;
let extraStyle: React.CSSProperties = {};
if (isActive) {
color = style.highlightColor;
switch (animation) {
case "pop": {
const scale = spring({
frame: frame - wordStartFrame,
fps,
config: { mass: 0.5, stiffness: 300, damping: 12 },
durationInFrames: 10,
});
const scaleValue = interpolate(scale, [0, 1], [1, 1.25]);
transform = `scale(${scaleValue})`;
break;
}
case "karaoke": {
extraStyle = {
backgroundColor: style.highlightColor,
color: style.bgColor || "#000000",
borderRadius: 4,
padding: "2px 6px",
};
break;
}
case "word-highlight": {
extraStyle = {
textShadow: `0 0 12px ${style.highlightColor}, 0 0 24px ${style.highlightColor}40`,
};
break;
}
default:
break;
}
}
// Text stroke via textShadow (CSS paint-order not reliable in Remotion)
const strokeShadow =
style.borderWidth > 0
? [
`${style.borderWidth}px 0 0 ${style.borderColor}`,
`-${style.borderWidth}px 0 0 ${style.borderColor}`,
`0 ${style.borderWidth}px 0 ${style.borderColor}`,
`0 -${style.borderWidth}px 0 ${style.borderColor}`,
].join(", ")
: "none";
return (
<span
style={{
fontFamily: fontStack,
fontSize: style.fontSize,
fontWeight: 700,
color: animation === "karaoke" && isActive ? undefined : color,
textShadow:
animation !== "karaoke"
? [strokeShadow, extraStyle.textShadow].filter(Boolean).join(", ")
: strokeShadow,
transform,
display: "inline-block",
transition: "none",
...extraStyle,
}}
>
{word}
</span>
);
};

View file

@ -1,209 +0,0 @@
import React from "react";
import { useCurrentFrame, useVideoConfig, interpolate } from "remotion";
import type { EffectsConfig, EffectSegment } from "../lib/types";
interface VideoEffectsProps {
config: EffectsConfig | null;
children: React.ReactNode;
}
/**
* Wraps children (typically <OffthreadVideo>) with dynamic CSS transforms and filters.
* Interpolates smoothly between effect segments.
*/
export const VideoEffects: React.FC<VideoEffectsProps> = ({
config,
children,
}) => {
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
if (!config || config.segments.length === 0) {
return <>{children}</>;
}
const currentTimeSec = frame / fps;
const { zoom, centerX, centerY, brightness, contrast, saturate } =
getInterpolatedValues(config.segments, currentTimeSec, frame, fps);
const filterParts: string[] = [];
if (brightness !== 1) filterParts.push(`brightness(${brightness})`);
if (contrast !== 1) filterParts.push(`contrast(${contrast})`);
if (saturate !== 1) filterParts.push(`saturate(${saturate})`);
const filterStr = filterParts.length > 0 ? filterParts.join(" ") : "none";
return (
<div
style={{
width: "100%",
height: "100%",
overflow: "hidden",
position: "relative",
}}
>
<div
style={{
width: "100%",
height: "100%",
transform: `scale(${zoom})`,
transformOrigin: `${centerX * 100}% ${centerY * 100}%`,
filter: filterStr,
}}
>
{children}
</div>
</div>
);
};
interface InterpolatedValues {
zoom: number;
centerX: number;
centerY: number;
brightness: number;
contrast: number;
saturate: number;
}
function getInterpolatedValues(
segments: EffectSegment[],
timeSec: number,
frame: number,
fps: number
): InterpolatedValues {
// Default values (no effect)
const defaults: InterpolatedValues = {
zoom: 1,
centerX: 0.5,
centerY: 0.5,
brightness: 1,
contrast: 1,
saturate: 1,
};
// Find active segment
const active = segments.find(
(s) => timeSec >= s.startSec && timeSec < s.endSec
);
if (!active) {
// Check if we're transitioning between segments (smooth fade)
const prev = segments.filter((s) => s.endSec <= timeSec).pop();
const next = segments.find((s) => s.startSec > timeSec);
if (prev && next) {
const gap = next.startSec - prev.endSec;
if (gap < 1.0) {
// Short gap: interpolate between prev and next
const progress = (timeSec - prev.endSec) / gap;
return lerpSegments(prev, next, progress);
}
}
// Transition out from previous segment
if (prev) {
const fadeOutDuration = 0.3; // seconds
const elapsed = timeSec - prev.endSec;
if (elapsed < fadeOutDuration) {
const progress = elapsed / fadeOutDuration;
return lerpToDefaults(prev, progress, defaults);
}
}
// Transition into next segment
if (next) {
const fadeInDuration = 0.3;
const remaining = next.startSec - timeSec;
if (remaining < fadeInDuration) {
const progress = 1 - remaining / fadeInDuration;
return lerpFromDefaults(next, progress, defaults);
}
}
return defaults;
}
// Inside active segment: smooth entrance/exit at edges
const segDuration = active.endSec - active.startSec;
const transitionSec = Math.min(0.3, segDuration * 0.15);
const startFrame = Math.round(active.startSec * fps);
const endFrame = Math.round(active.endSec * fps);
const transitionFrames = Math.round(transitionSec * fps);
// Entrance ease
const entranceFactor = interpolate(
frame,
[startFrame, startFrame + transitionFrames],
[0, 1],
{ extrapolateLeft: "clamp", extrapolateRight: "clamp" }
);
// Exit ease
const exitFactor = interpolate(
frame,
[endFrame - transitionFrames, endFrame],
[1, 0],
{ extrapolateLeft: "clamp", extrapolateRight: "clamp" }
);
const factor = Math.min(entranceFactor, exitFactor);
return {
zoom: lerp(1, active.zoom, factor),
centerX: lerp(0.5, active.zoomCenterX, factor),
centerY: lerp(0.5, active.zoomCenterY, factor),
brightness: lerp(1, active.brightness, factor),
contrast: lerp(1, active.contrast, factor),
saturate: lerp(1, active.saturate, factor),
};
}
function lerp(a: number, b: number, t: number): number {
return a + (b - a) * t;
}
function lerpSegments(
a: EffectSegment,
b: EffectSegment,
t: number
): InterpolatedValues {
return {
zoom: lerp(a.zoom, b.zoom, t),
centerX: lerp(a.zoomCenterX, b.zoomCenterX, t),
centerY: lerp(a.zoomCenterY, b.zoomCenterY, t),
brightness: lerp(a.brightness, b.brightness, t),
contrast: lerp(a.contrast, b.contrast, t),
saturate: lerp(a.saturate, b.saturate, t),
};
}
function lerpToDefaults(
seg: EffectSegment,
t: number,
defaults: InterpolatedValues
): InterpolatedValues {
return {
zoom: lerp(seg.zoom, defaults.zoom, t),
centerX: lerp(seg.zoomCenterX, defaults.centerX, t),
centerY: lerp(seg.zoomCenterY, defaults.centerY, t),
brightness: lerp(seg.brightness, defaults.brightness, t),
contrast: lerp(seg.contrast, defaults.contrast, t),
saturate: lerp(seg.saturate, defaults.saturate, t),
};
}
function lerpFromDefaults(
seg: EffectSegment,
t: number,
defaults: InterpolatedValues
): InterpolatedValues {
return {
zoom: lerp(defaults.zoom, seg.zoom, t),
centerX: lerp(defaults.centerX, seg.zoomCenterX, t),
centerY: lerp(defaults.centerY, seg.zoomCenterY, t),
brightness: lerp(defaults.brightness, seg.brightness, t),
contrast: lerp(defaults.contrast, seg.contrast, t),
saturate: lerp(defaults.saturate, seg.saturate, t),
};
}

View file

@ -1,4 +0,0 @@
import { registerRoot } from "remotion";
import { RemotionRoot } from "./Root";
registerRoot(RemotionRoot);

View file

@ -1,83 +0,0 @@
import type { CaptionWord } from "./types";
export interface CaptionBlock {
words: CaptionWord[];
startMs: number;
endMs: number;
text: string;
}
/**
* Groups word-level captions into display blocks.
* Same logic as Clipwright' generate_srt: max chars per block, max duration per block.
*/
export function groupCaptionsIntoBlocks(
captions: CaptionWord[],
maxChars = 20,
maxDurationMs = 2000
): CaptionBlock[] {
const blocks: CaptionBlock[] = [];
let currentWords: CaptionWord[] = [];
let blockStartMs = 0;
for (const word of captions) {
if (currentWords.length === 0) {
currentWords.push(word);
blockStartMs = word.startMs;
continue;
}
const currentTextLen = currentWords.reduce(
(sum, w) => sum + w.text.length + 1,
0
);
const duration = word.endMs - blockStartMs;
if (
currentTextLen + word.text.length > maxChars ||
duration > maxDurationMs
) {
// Finalize current block
const lastWord = currentWords[currentWords.length - 1];
blocks.push({
words: [...currentWords],
startMs: blockStartMs,
endMs: lastWord.endMs,
text: currentWords.map((w) => w.text).join(" "),
});
currentWords = [word];
blockStartMs = word.startMs;
} else {
currentWords.push(word);
}
}
// Final block
if (currentWords.length > 0) {
const lastWord = currentWords[currentWords.length - 1];
blocks.push({
words: [...currentWords],
startMs: blockStartMs,
endMs: lastWord.endMs,
text: currentWords.map((w) => w.text).join(" "),
});
}
return blocks;
}
/**
* Find the active word at a given time in milliseconds.
*/
export function getActiveWordIndex(
words: CaptionWord[],
timeMs: number
): number {
for (let i = 0; i < words.length; i++) {
if (timeMs >= words[i].startMs && timeMs < words[i].endMs) {
return i;
}
}
return -1;
}

View file

@ -1,33 +0,0 @@
import { staticFile } from "remotion";
/**
* CSS @font-face declaration for NotoSerif-Bold (bundled locally).
* Use in components via: <style>{notoSerifFontFace}</style>
*/
export const NOTO_SERIF_FONT_FAMILY = "NotoSerif-Bold";
export const notoSerifFontFace = `
@font-face {
font-family: '${NOTO_SERIF_FONT_FAMILY}';
src: url('${staticFile("fonts/NotoSerif-Bold.ttf")}') format('truetype');
font-weight: 700;
font-style: normal;
}
`;
/**
* Map of subtitle font families to their CSS-safe names.
* These match the options available in SubtitleModal.jsx.
*/
export const SUBTITLE_FONTS: Record<string, string> = {
Verdana: "Verdana, Geneva, sans-serif",
Arial: "Arial, Helvetica, sans-serif",
Impact: "Impact, Haettenschweiler, sans-serif",
Helvetica: "Helvetica, Arial, sans-serif",
Georgia: "Georgia, 'Times New Roman', serif",
"Courier New": "'Courier New', Courier, monospace",
};
export function getFontStack(fontFamily: string): string {
return SUBTITLE_FONTS[fontFamily] ?? fontFamily;
}

View file

@ -1,139 +0,0 @@
import { z } from "zod";
// --- Word-level caption ---
export interface CaptionWord {
text: string;
startMs: number;
endMs: number;
}
// --- Subtitle config ---
export type SubtitleAnimation = "none" | "word-highlight" | "pop" | "karaoke";
export type SubtitlePosition = "top" | "middle" | "bottom";
export interface SubtitleStyle {
fontFamily: string;
fontSize: number;
fontColor: string;
highlightColor: string;
borderColor: string;
borderWidth: number;
bgColor: string;
bgOpacity: number;
animation: SubtitleAnimation;
}
export interface SubtitleConfig {
captions: CaptionWord[];
position: SubtitlePosition;
style: SubtitleStyle;
}
// --- Hook config ---
export type HookPosition = "top" | "center" | "bottom";
export type HookSize = "S" | "M" | "L";
export type HookEntrance = "spring" | "fade" | "slide-up" | "none";
export type HookStyle =
| "classic"
| "dark"
| "yellow"
| "red"
| "outline"
| "outline_yellow";
export interface HookConfig {
text: string;
position: HookPosition;
size: HookSize;
entranceAnimation: HookEntrance;
displayDurationSec: number;
style?: HookStyle;
}
// --- Effects config ---
export interface EffectSegment {
startSec: number;
endSec: number;
zoom: number;
zoomCenterX: number;
zoomCenterY: number;
brightness: number;
contrast: number;
saturate: number;
}
export interface EffectsConfig {
segments: EffectSegment[];
}
// --- Main composition props ---
export interface ShortVideoProps {
videoUrl: string;
durationInFrames: number;
fps: number;
width: number;
height: number;
subtitles: SubtitleConfig | null;
hook: HookConfig | null;
effects: EffectsConfig | null;
}
// --- Zod schemas for validation (used by render service) ---
export const captionWordSchema = z.object({
text: z.string(),
startMs: z.number(),
endMs: z.number(),
});
export const subtitleStyleSchema = z.object({
fontFamily: z.string(),
fontSize: z.number(),
fontColor: z.string(),
highlightColor: z.string(),
borderColor: z.string(),
borderWidth: z.number(),
bgColor: z.string(),
bgOpacity: z.number().min(0).max(1),
animation: z.enum(["none", "word-highlight", "pop", "karaoke"]),
});
export const subtitleConfigSchema = z.object({
captions: z.array(captionWordSchema),
position: z.enum(["top", "middle", "bottom"]),
style: subtitleStyleSchema,
});
export const hookConfigSchema = z.object({
text: z.string(),
position: z.enum(["top", "center", "bottom"]),
size: z.enum(["S", "M", "L"]),
entranceAnimation: z.enum(["spring", "fade", "slide-up", "none"]),
displayDurationSec: z.number().positive(),
});
export const effectSegmentSchema = z.object({
startSec: z.number().min(0),
endSec: z.number().positive(),
zoom: z.number().min(0.5).max(3),
zoomCenterX: z.number().min(0).max(1),
zoomCenterY: z.number().min(0).max(1),
brightness: z.number().min(0).max(3),
contrast: z.number().min(0).max(3),
saturate: z.number().min(0).max(3),
});
export const effectsConfigSchema = z.object({
segments: z.array(effectSegmentSchema),
});
export const shortVideoPropsSchema = z.object({
videoUrl: z.string(),
durationInFrames: z.number().int().positive(),
fps: z.number().positive(),
width: z.number().int().positive(),
height: z.number().int().positive(),
subtitles: subtitleConfigSchema.nullable(),
hook: hookConfigSchema.nullable(),
effects: effectsConfigSchema.nullable(),
});

View file

@ -1,16 +0,0 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "bundler",
"jsx": "react-jsx",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"outDir": "./dist",
"rootDir": "./src",
"declaration": true
},
"include": ["src/**/*"]
}

View file

@ -1,2 +0,0 @@
node_modules/
dist/

View file

@ -1,34 +0,0 @@
FROM node:18-bookworm-slim
# Install Chromium and FFmpeg for Remotion rendering
RUN apt-get update && \
apt-get install -y --no-install-recommends chromium ffmpeg && \
rm -rf /var/lib/apt/lists/*
ENV PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium
ENV REMOTION_BUNDLE_PATH=/app/remotion
ENV OUTPUT_DIR=/output
WORKDIR /app
# Copy render service source
COPY render-service/package.json ./
RUN npm install
COPY render-service/tsconfig.json ./
COPY render-service/src/ ./src/
# Copy remotion source for bundling
COPY remotion/package.json /app/remotion/package.json
COPY remotion/tsconfig.json /app/remotion/tsconfig.json
COPY remotion/src/ /app/remotion/src/
COPY remotion/public/ /app/remotion/public/
# Install remotion deps
RUN cd /app/remotion && npm install
# Build TypeScript
RUN npm run build
EXPOSE 3100
CMD ["node", "dist/server.js"]

File diff suppressed because it is too large Load diff

View file

@ -1,26 +0,0 @@
{
"name": "clipwright-render-service",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "tsx watch src/server.ts",
"test": "node --import tsx --test src/composition-metadata.test.ts",
"build": "tsc",
"start": "node dist/server.js"
},
"dependencies": {
"@remotion/bundler": "^4.0.0",
"@remotion/renderer": "^4.0.0",
"express": "^4.21.0",
"remotion": "^4.0.0",
"uuid": "^10.0.0",
"zod": "^4.3.6"
},
"devDependencies": {
"@types/express": "^5.0.0",
"@types/uuid": "^10.0.0",
"tsx": "^4.19.0",
"typescript": "^5.4.0"
}
}

View file

@ -1,43 +0,0 @@
import path from "node:path";
import { bundle } from "@remotion/bundler";
let bundleLocation: string | null = null;
/**
* Bundles the Remotion project on startup and caches the result.
* Uses REMOTION_BUNDLE_PATH env var to locate the remotion source
* (default: "../remotion" relative to this service's root).
*/
export async function initBundle(): Promise<void> {
const remotionRoot = process.env.REMOTION_BUNDLE_PATH
? path.resolve(process.env.REMOTION_BUNDLE_PATH)
: path.resolve(import.meta.dirname, "../../remotion");
const entryPoint = path.join(remotionRoot, "src", "index.ts");
console.log(`[bundle] Bundling Remotion project from: ${entryPoint}`);
bundleLocation = await bundle({
entryPoint,
onProgress: (progress: number) => {
if (progress % 10 === 0) {
console.log(`[bundle] Progress: ${progress}%`);
}
},
});
console.log(`[bundle] Bundle created at: ${bundleLocation}`);
}
/**
* Returns the cached bundle location.
* Throws if initBundle() has not been called yet.
*/
export function getBundleLocation(): string {
if (!bundleLocation) {
throw new Error(
"Bundle not initialized. Call initBundle() before getBundleLocation()."
);
}
return bundleLocation;
}

View file

@ -1,62 +0,0 @@
import { before, test } from "node:test";
import assert from "node:assert/strict";
import { selectComposition } from "@remotion/renderer";
import { initBundle, getBundleLocation } from "./bundle.js";
/**
* Contract test for the render pipeline's composition metadata.
*
* render-worker.ts passes durationInFrames/fps/width/height via inputProps and
* renders whatever selectComposition() reports. Without calculateMetadata on
* the ShortVideo Composition, Remotion ignores those inputProps and always
* reports the static DEFAULT_PROPS metadata (900 frames / 30fps / 1080x1920),
* so every clip renders at 30s regardless of its real length.
*/
const BUNDLE_TIMEOUT_MS = 5 * 60 * 1000;
before(async () => {
await initBundle();
}, { timeout: BUNDLE_TIMEOUT_MS });
test(
"selectComposition honors per-render duration/fps/dimensions from inputProps",
{ timeout: BUNDLE_TIMEOUT_MS },
async () => {
const composition = await selectComposition({
serveUrl: getBundleLocation(),
id: "ShortVideo",
inputProps: {
videoUrl: "",
durationInFrames: 300,
fps: 25,
width: 720,
height: 1280,
},
logLevel: "error",
});
assert.equal(composition.durationInFrames, 300);
assert.equal(composition.fps, 25);
assert.equal(composition.width, 720);
assert.equal(composition.height, 1280);
}
);
test(
"selectComposition falls back to DEFAULT_PROPS metadata when inputProps omit it",
{ timeout: BUNDLE_TIMEOUT_MS },
async () => {
const composition = await selectComposition({
serveUrl: getBundleLocation(),
id: "ShortVideo",
inputProps: { videoUrl: "" },
logLevel: "error",
});
assert.equal(composition.durationInFrames, 900);
assert.equal(composition.fps, 30);
assert.equal(composition.width, 1080);
assert.equal(composition.height, 1920);
}
);

View file

@ -1,96 +0,0 @@
import fs from "node:fs";
import path from "node:path";
import { selectComposition, renderMedia } from "@remotion/renderer";
import { getBundleLocation } from "./bundle.js";
import { renderJobs } from "./server.js";
export interface RenderParams {
renderId: string;
jobId: string;
clipIndex: number;
props: {
videoUrl: string;
durationInFrames: number;
fps: number;
width: number;
height: number;
subtitles: unknown;
hook: unknown;
effects: unknown;
};
}
/**
* Executes a Remotion render in the background.
* Updates the in-memory render job map with progress and final status.
*/
export async function executeRender(params: RenderParams): Promise<void> {
const { renderId, jobId, clipIndex, props } = params;
const job = renderJobs.get(renderId);
if (!job) {
console.error(`[render-worker] Job ${renderId} not found in map`);
return;
}
try {
job.status = "rendering";
job.progress = 0;
console.log(
`[render-worker] Starting render ${renderId} (job=${jobId}, clip=${clipIndex})`
);
const bundleLocation = getBundleLocation();
// Select the composition with the provided input props
const composition = await selectComposition({
serveUrl: bundleLocation,
id: "ShortVideo",
inputProps: props,
});
// Determine output directory and file path
const outputDir = process.env.OUTPUT_DIR
? path.resolve(process.env.OUTPUT_DIR)
: path.resolve(import.meta.dirname, "../../output");
const jobOutputDir = path.join(outputDir, jobId);
fs.mkdirSync(jobOutputDir, { recursive: true });
const timestamp = Date.now();
const outputFileName = `remotion_${clipIndex}_${timestamp}.mp4`;
const outputLocation = path.join(jobOutputDir, outputFileName);
console.log(`[render-worker] Output: ${outputLocation}`);
// Render the video
await renderMedia({
composition,
serveUrl: bundleLocation,
codec: "h264",
crf: 22,
outputLocation,
onProgress: ({ progress }) => {
const percent = Math.round(progress * 100);
job.progress = percent;
if (percent % 10 === 0) {
console.log(`[render-worker] ${renderId} progress: ${percent}%`);
}
},
});
// Success
job.status = "done";
job.progress = 100;
job.outputUrl = outputLocation;
console.log(`[render-worker] Render ${renderId} completed: ${outputLocation}`);
} catch (err) {
job.status = "error";
job.error = err instanceof Error ? err.message : String(err);
console.error(`[render-worker] Render ${renderId} failed:`, err);
}
}

View file

@ -1,166 +0,0 @@
import express from "express";
import { v4 as uuidv4 } from "uuid";
import { z } from "zod";
import { initBundle } from "./bundle.js";
import { executeRender } from "./render-worker.js";
// --- Render status types ---
export type RenderStatus = "queued" | "rendering" | "done" | "error";
export interface RenderJob {
renderId: string;
jobId: string;
clipIndex: number;
status: RenderStatus;
progress: number;
outputUrl?: string;
error?: string;
}
// In-memory render job map
export const renderJobs = new Map<string, RenderJob>();
// --- Request validation schema ---
const renderRequestSchema = z.object({
jobId: z.string().min(1),
clipIndex: z.number().int().min(0),
props: z.object({
videoUrl: z.string(),
durationInFrames: z.number().int().positive(),
fps: z.number().positive(),
width: z.number().int().positive(),
height: z.number().int().positive(),
subtitles: z.any().nullable().optional(),
hook: z.any().nullable().optional(),
effects: z.any().nullable().optional(),
}),
});
// --- Express app ---
const app = express();
app.use(express.json({ limit: "10mb" }));
const PORT = parseInt(process.env.PORT || "3100", 10);
const OUTPUT_DIR = process.env.OUTPUT_DIR || "/output";
// Serve video files from the shared output volume so Remotion can access them via HTTP
app.use("/output", express.static(OUTPUT_DIR));
// Health check
app.get("/health", (_req, res) => {
res.json({ ok: true });
});
// Submit a render job
app.post("/render", (req, res) => {
const parsed = renderRequestSchema.safeParse(req.body);
if (!parsed.success) {
res.status(400).json({
error: "Invalid request body",
details: parsed.error.issues,
});
return;
}
const { jobId, clipIndex, props } = parsed.data;
const renderId = uuidv4();
const job: RenderJob = {
renderId,
jobId,
clipIndex,
status: "queued",
progress: 0,
};
renderJobs.set(renderId, job);
console.log(
`[render] Queued render ${renderId} for job=${jobId} clip=${clipIndex}`
);
// Resolve video URL: convert frontend/backend URLs to renderer's own static server
// The renderer serves /output/* from the shared Docker volume
let resolvedVideoUrl = props.videoUrl;
const videoPathMatch = props.videoUrl.match(/\/videos\/([^/]+)\/(.+)$/);
if (videoPathMatch) {
resolvedVideoUrl = `http://localhost:${PORT}/output/${videoPathMatch[1]}/${videoPathMatch[2]}`;
console.log(`[render] Resolved video URL: ${props.videoUrl} -> ${resolvedVideoUrl}`);
}
// Fire and forget - render runs in background
executeRender({
renderId,
jobId,
clipIndex,
props: {
videoUrl: resolvedVideoUrl,
durationInFrames: props.durationInFrames,
fps: props.fps,
width: props.width,
height: props.height,
subtitles: props.subtitles ?? null,
hook: props.hook ?? null,
effects: props.effects ?? null,
},
}).catch((err) => {
console.error(`[render] Unhandled error for ${renderId}:`, err);
const existingJob = renderJobs.get(renderId);
if (existingJob) {
existingJob.status = "error";
existingJob.error =
err instanceof Error ? err.message : "Unknown error";
}
});
res.status(202).json({ renderId, status: "queued" });
});
// Get render status
app.get("/render/:renderId", (req, res) => {
const { renderId } = req.params;
const job = renderJobs.get(renderId);
if (!job) {
res.status(404).json({ error: "Render not found" });
return;
}
const response: Record<string, unknown> = {
renderId: job.renderId,
status: job.status,
};
if (job.progress !== undefined) {
response.progress = job.progress;
}
if (job.outputUrl) {
response.outputUrl = job.outputUrl;
}
if (job.error) {
response.error = job.error;
}
res.json(response);
});
// --- Start server ---
async function main() {
console.log("[render-service] Initializing Remotion bundle...");
await initBundle();
console.log("[render-service] Bundle ready.");
app.listen(PORT, () => {
console.log(`[render-service] Listening on port ${PORT}`);
});
}
main().catch((err) => {
console.error("[render-service] Fatal error during startup:", err);
process.exit(1);
});

View file

@ -1,17 +0,0 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"outDir": "dist",
"rootDir": "src",
"declaration": true,
"resolveJsonModule": true
},
"include": ["src"],
"exclude": ["node_modules", "dist"]
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 390 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 257 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 328 KiB

View file

@ -1,13 +1,11 @@
"""AI Act art. 50(2) marking on the images the thumbnail studio generates.
Videos have carried an mp4 ``comment`` tag since the doubling/AI-Shorts work
(``ffmpeg_utils.mark_ai_generated``). Thumbnails carried nothing — and they are
the output most likely to be a synthetic image *of a real person*, because the
studio hands the model the presenter's own face as a reference. The mark is XMP
Thumbnails are the output most likely to be a synthetic image *of a real
person*, because the studio hands the model the presenter's own face as a
reference. The mark is XMP
``Iptc4xmpExt:DigitalSourceType = trainedAlgorithmicMedia``, which is the
vocabulary the platforms actually read.
"""
import io
import os
import pytest

View file

@ -10,7 +10,6 @@ from clipwright.pipeline.clip_selection import (
score_batches,
shortlist_target,
snap_clip_to_words,
compact_words,
lookup_model_prices,
trim_to_best,
)
@ -103,12 +102,6 @@ class TestPricing:
assert lookup_model_prices(None) is None
class TestCompactWords:
def test_rounds_timestamps(self):
words = [{"w": " hi", "s": 17.240000000000002, "e": 17.899999999999999}]
assert compact_words(words) == [{"w": " hi", "s": 17.24, "e": 17.9}]
class TestClipCountTargets:
"""The floor is the whole point: prod was delivering a single clip on the
mode, and users who got 1-3 came back 0.4% of the time against 16% for 4-9.

View file

@ -7,7 +7,6 @@ landing on either instance must answer from disk.
"""
import asyncio
import json
import os
import time
import httpx

View file

@ -4,13 +4,11 @@ import pytest
from clipwright.media import ffmpeg_utils
from clipwright.media.ffmpeg_utils import (
AI_DISCLOSURE,
DELIVERY,
METADATA_SCRUB,
QUALITY,
QUALITY_FAST,
blurred_backdrop,
mark_ai_generated,
reset_encoder_cache,
video_encode_args,
)
@ -102,51 +100,6 @@ def test_encode_args_stay_free_of_metadata_flags():
assert not any(a.startswith("-map_metadata") for a in video_encode_args(tier))
def _tiny_mp4(path):
subprocess.run(
["ffmpeg", "-y", "-f", "lavfi", "-i", "testsrc=size=320x240:rate=10:duration=1",
"-f", "lavfi", "-i", "sine=frequency=440:duration=1",
"-c:v", "libx264", "-c:a", "aac", "-pix_fmt", "yuv420p", str(path)],
capture_output=True, check=True)
def _comment_tag(path):
r = subprocess.run(
["ffprobe", "-v", "error", "-show_entries", "format_tags=comment",
"-of", "default=noprint_wrappers=1:nokey=1", str(path)],
capture_output=True, text=True, check=True)
return r.stdout.strip()
def test_ai_disclosure_survives_in_a_tag_a_machine_can_read():
# AI Act art. 50(2) wants the marking readable by a machine, so it has to
# come back out of the file. `comment` is the only tag mp4 keeps: a custom
# key is dropped by ffmpeg without any warning.
pytest.importorskip("shutil")
import shutil, tempfile, os
if not shutil.which("ffmpeg") or not shutil.which("ffprobe"):
pytest.skip("ffmpeg/ffprobe not installed")
with tempfile.TemporaryDirectory() as d:
p = os.path.join(d, "clip.mp4")
_tiny_mp4(p)
assert mark_ai_generated(p, "AI voice dubbing") is True
tag = _comment_tag(p)
assert AI_DISCLOSURE in tag
assert "AI voice dubbing" in tag
def test_ai_disclosure_never_destroys_the_file_it_cannot_tag():
# The tag is a nicety; the video the user just paid minutes for is not.
import tempfile, os
with tempfile.TemporaryDirectory() as d:
p = os.path.join(d, "broken.mp4")
with open(p, "wb") as f:
f.write(b"not a video")
assert mark_ai_generated(p) is False
assert open(p, "rb").read() == b"not a video"
assert not os.path.exists(p + ".aitag.mp4")
# --- cut_clip: a failed cut must say why, not hand an empty file downstream ---
class _FakeRun:

View file

@ -2,7 +2,6 @@
are stacked (layout_ranges sidecar), and generate_ass anchors the word events
inside them mid-frame (\\an5) while everything else keeps the style's own
alignment. A clip mixes both, so the placement is per event, not per style."""
import json
import os
import pytest

View file

@ -23,7 +23,7 @@ LEGACY_MODULES = frozenset({
"active_speaker", "app", "camera_inset", "clip_selection", "edit_builder",
"editor", "ffmpeg_utils", "file_hosts", "frame_sampler", "free_tools",
"gemini_worker", "hook_grounding", "hooks", "layout_picker",
"layout_ranges", "llm_backend", "main", "media_auth", "panel_layout",
"layout_ranges", "llm_backend", "main", "media_auth",
"postiz", "punch_in", "quality_probe", "recut", "reframe_v2",
"restoring_static", "scene_detection", "screencast_layout",
"security_utils", "split_layout", "subtitles", "thumbnail",

View file

@ -1,205 +0,0 @@
from clipwright.layouts import panel_layout
from clipwright.layouts.panel_layout import (
analyze_scene,
panel_filtergraph,
panel_geometry,
tile_grid,
usable_faces,
well_separated,
)
def face(cx, w=200, h=200, cy=400):
box = [int(cx - w / 2), int(cy - h / 2), w, h]
return {'box': box, 'score': w * h}
def panel(n, frame_w=1920):
"""n evenly spaced faces across the frame."""
step = frame_w / (n + 1)
return [face(step * (i + 1)) for i in range(n)]
class TestTileGrid:
def test_three_people_also_use_the_grid(self):
# Landscape bands need a crop wider than a person owns; portrait tiles
# do not. Three people take three cells, the fourth holds the wide shot.
cols, rows, tw, th = tile_grid(3, 1080, 1920)
assert (cols, rows) == (2, 2)
assert tw == 540 and th == 960
def test_four_people_make_a_grid(self):
cols, rows, tw, th = tile_grid(4, 1080, 1920)
assert (cols, rows) == (2, 2)
assert tw == 540 and th == 960
def test_tiles_are_even(self):
for n in (3, 4):
_c, _r, tw, th = tile_grid(n, 1080, 1920)
assert tw % 2 == 0 and th % 2 == 0
def test_tiles_fill_the_frame(self):
for n in (3, 4):
cols, rows, tw, th = tile_grid(n, 1080, 1920)
assert cols * tw == 1080
assert abs(rows * th - 1920) <= 2
class TestUsableFaces:
def test_tiny_faces_are_dropped(self):
faces = panel(3) + [face(1800, w=40, h=40)]
assert len(usable_faces(faces, 1920)) == 3
def test_result_is_left_to_right(self):
faces = list(reversed(panel(4)))
xs = [c['box'][0] for c in usable_faces(faces, 1920)]
assert xs == sorted(xs)
class TestWellSeparated:
def test_evenly_spaced_panel_passes(self):
assert well_separated(usable_faces(panel(4), 1920), 1920)
def test_two_people_shoulder_to_shoulder_fail(self):
faces = [face(900), face(980), face(1500)]
assert not well_separated(faces, 1920)
def test_people_stacked_vertically_count_as_separated(self):
# Measured on a real recording: two webcams on the same side of the
# frame, 18px apart horizontally and 545px vertically. A horizontal-gap
# test called them one person.
faces = [face(300, cy=400), face(1760, cy=210), face(1760, cy=755)]
assert well_separated(faces, 1920)
def test_faces_close_in_both_axes_still_fail(self):
faces = [face(300, cy=400), face(1760, cy=400), face(1780, cy=420)]
assert not well_separated(faces, 1920)
class TestAnalyzeScene:
def test_steady_panel_of_three_is_found(self):
centres = analyze_scene([panel(3)] * 10, 1920)
assert centres is not None and len(centres) == 3
def test_steady_panel_of_four_is_found(self):
centres = analyze_scene([panel(4)] * 10, 1920)
assert len(centres) == 4
def test_two_people_are_left_to_split(self):
# Two is SPLIT's job; this layout must not claim it.
assert analyze_scene([panel(2)] * 10, 1920) is None
def test_a_crowd_is_rejected(self):
# Five tiles on a 1080-wide frame leaves nobody legible.
assert analyze_scene([panel(6)] * 10, 1920) is None
def test_shot_reverse_shot_is_rejected(self):
# Faces never coexisting means a multi-camera cut; tiling would show the
# same person more than once.
frames = [[face(900)], [face(1000)], [face(800)]] * 4
assert analyze_scene(frames, 1920) is None
def test_the_dominant_headcount_wins(self):
# One frame catching a fourth person must not turn a trio into a quad.
frames = [panel(3)] * 9 + [panel(4)]
assert len(analyze_scene(frames, 1920)) == 3
def test_empty_input_is_rejected(self):
assert analyze_scene([], 1920) is None
def test_centres_come_back_left_to_right(self):
centres = analyze_scene([panel(4)] * 10, 1920)
assert [c[0] for c in centres] == sorted(c[0] for c in centres)
class TestPanelGeometry:
def test_crop_stays_inside_the_source(self):
_c, _r, tw, th = tile_grid(3, 1080, 1920)
for cx in (100, 960, 1850):
w, h, x, y = panel_geometry(1920, 1080, tw, th, (cx, 400, 200, 200))
assert 0 <= x <= 1920 - w
assert 0 <= y <= 1080 - h
def test_crop_matches_the_tile_aspect(self):
_c, _r, tw, th = tile_grid(4, 1080, 1920)
w, h, _x, _y = panel_geometry(1920, 1080, tw, th, (900, 400, 200, 200))
assert abs((w / h) - (tw / th)) < 0.02
def test_dimensions_are_even(self):
_c, _r, tw, th = tile_grid(3, 1080, 1920)
w, h, x, y = panel_geometry(1920, 1080, tw, th, (777, 333, 201, 201))
assert w % 2 == 0 and h % 2 == 0 and x % 2 == 0 and y % 2 == 0
class TestPanelFiltergraph:
def test_three_people_fill_a_grid_plus_the_wide_shot(self):
graph = panel_filtergraph(1920, 1080, 1080, 1920,
[(300, 400, 200, 200), (900, 400, 200, 200),
(1500, 400, 200, 200)])
assert "split=4" in graph # three crops plus the wide shot
assert graph.count("hstack=inputs=2") == 2
assert "[s3]scale=540:-2" in graph # the room, letterboxed, not cropped
assert graph.endswith("[v]")
def test_four_make_a_grid(self):
graph = panel_filtergraph(1920, 1080, 1080, 1920,
[(200, 400, 180, 180), (700, 400, 180, 180),
(1200, 400, 180, 180), (1700, 400, 180, 180)])
assert "split=4" in graph
assert graph.count("hstack=inputs=2") == 2
assert "vstack=inputs=2" in graph
def test_every_person_tile_is_the_same_size(self):
graph = panel_filtergraph(1920, 1080, 1080, 1920,
[(300, 400, 200, 200), (900, 400, 200, 200),
(1500, 400, 200, 200)])
assert graph.count("scale=540:960") == 3
def test_tiles_keep_source_order(self):
graph = panel_filtergraph(1920, 1080, 1080, 1920,
[(300, 400, 200, 200), (900, 400, 200, 200),
(1500, 400, 200, 200)])
xs = [int(seg.split("x=")[1].split(":")[0])
for seg in graph.split("crop=")[1:]]
assert xs == sorted(xs)
class TestGating:
def test_disabled_module_touches_nothing(self, monkeypatch):
monkeypatch.setattr(panel_layout, "ENABLED", False)
assert panel_layout.detect_panel_scenes("x.mp4", [], []) == {}
class TestNeighbourClamp:
def test_crop_never_swallows_the_neighbour(self):
# A 1080x640 tile is landscape, so an unclamped crop is 1551px wide on a
# 1080-tall source. With three people on a 1920 frame that reaches both
# neighbours, and the rendered bands showed two faces each.
_c, _r, tw, th = tile_grid(3, 1080, 1920)
w, _h, _x, _y = panel_geometry(1920, 1080, tw, th, (960, 400, 200, 200),
neighbour_gap=530)
assert w <= 530
def test_no_gap_given_keeps_the_widest_crop(self):
_c, _r, tw, th = tile_grid(3, 1080, 1920)
w, _h, _x, _y = panel_geometry(1920, 1080, tw, th, (960, 400, 200, 200))
assert w >= 500
def test_clamped_crop_keeps_the_tile_aspect(self):
_c, _r, tw, th = tile_grid(3, 1080, 1920)
w, h, _x, _y = panel_geometry(1920, 1080, tw, th, (960, 400, 200, 200),
neighbour_gap=530)
assert abs((w / h) - (tw / th)) < 0.05
def test_gaps_measure_the_closest_neighbour(self):
from clipwright.layouts.panel_layout import neighbour_gaps
gaps = neighbour_gaps([(100, 0, 0, 0), (400, 0, 0, 0), (1500, 0, 0, 0)])
assert gaps == [300, 300, 1100]
def test_filtergraph_clamps_every_tile(self):
graph = panel_filtergraph(1920, 1080, 1080, 1920,
[(300, 400, 200, 200), (900, 400, 200, 200),
(1500, 400, 200, 200)])
widths = [int(seg.split("w=")[1].split(":")[0])
for seg in graph.split("crop=")[1:]]
assert all(w <= 600 for w in widths)

View file

@ -1,9 +1,5 @@
"""/videos serving: a miss under /videos/<job_id>/ asks the restorer to bring
the job back before answering 404, keeping StaticFiles' Range support.
Observed 6-sep-2026: reopening a project whose working files were gone fired
15 transcript requests (which restored it from R2 in ~25 s) and 15 <video>
loads at once; every player got a 404 until the user reloaded.
"""/videos serving: StaticFiles that refuses non-deliverables via ``guard``,
keeping Range support. There is no restorer hook in this fork.
"""
import os
@ -15,72 +11,33 @@ from clipwright.api.restoring_static import RestoringStaticFiles
JOB = "cff3ad6c-c1e6-48e8-9a75-be74f39779c5"
def _app(tmp_path, restorer):
def _app(tmp_path, guard=None):
app = Starlette()
app.mount("/videos", RestoringStaticFiles(directory=str(tmp_path), restorer=restorer))
app.mount("/videos", RestoringStaticFiles(directory=str(tmp_path), guard=guard))
return TestClient(app), tmp_path
def test_existing_file_is_served_without_calling_the_restorer(tmp_path):
calls = []
async def restorer(job_id):
calls.append(job_id)
return True
client, root = _app(tmp_path, restorer)
def test_existing_file_is_served(tmp_path):
client, root = _app(tmp_path)
os.makedirs(root / JOB)
(root / JOB / "clip_1.mp4").write_bytes(b"x" * 100)
r = client.get(f"/videos/{JOB}/clip_1.mp4")
assert r.status_code == 200 and calls == []
assert r.status_code == 200
def test_missing_file_is_restored_then_served_with_ranges(tmp_path):
calls = []
def test_guard_refuses_a_non_deliverable(tmp_path):
def guard(path):
return not path.endswith(".json")
async def restorer(job_id):
calls.append(job_id)
os.makedirs(root / job_id, exist_ok=True)
(root / job_id / "clip_1.mp4").write_bytes(bytes(range(100)))
return True
client, root = _app(tmp_path, restorer)
r = client.get(f"/videos/{JOB}/clip_1.mp4", headers={"Range": "bytes=10-19"})
assert calls == [JOB]
# The player's seek keeps working: the second lookup is the normal
# StaticFiles one. Range support itself depends on the starlette version
# (prod's honours it, an older local one answers the whole file).
if r.status_code == 206:
assert r.content == bytes(range(10, 20))
assert r.headers["content-range"] == "bytes 10-19/100"
else:
assert r.status_code == 200 and r.content == bytes(range(100))
client, root = _app(tmp_path, guard)
os.makedirs(root / JOB)
(root / JOB / "clip_1.mp4").write_bytes(b"x" * 100)
(root / JOB / "x_metadata.json").write_bytes(b"{}")
assert client.get(f"/videos/{JOB}/clip_1.mp4").status_code == 200
# A refused path must look exactly like a missing one.
assert client.get(f"/videos/{JOB}/x_metadata.json").status_code == 404
def test_restorer_false_or_failure_keeps_the_404(tmp_path):
async def says_no(job_id):
return False
async def blows_up(job_id):
raise RuntimeError("R2 down")
for restorer in (says_no, blows_up):
client, _root = _app(tmp_path, restorer)
assert client.get(f"/videos/{JOB}/clip_1.mp4").status_code == 404
def test_paths_without_a_job_segment_never_call_the_restorer(tmp_path):
calls = []
async def restorer(job_id):
calls.append(job_id)
return True
client, _root = _app(tmp_path, restorer)
assert client.get("/videos/robots.txt").status_code == 404
assert calls == []
def test_no_restorer_behaves_like_staticfiles(tmp_path):
def test_no_guard_behaves_like_staticfiles(tmp_path):
client, _root = _app(tmp_path, None)
assert client.get(f"/videos/{JOB}/clip_1.mp4").status_code == 404

View file

@ -297,7 +297,7 @@ class TestAutoCaptionDefaults:
"""The caption look every clip now ships with (chosen 25-jul-2026)."""
def test_style_is_complete(self):
from clipwright.media.subtitles import AUTO_CAPTION_STYLE, generate_ass
from clipwright.media.subtitles import AUTO_CAPTION_STYLE
required = {"alignment", "font_name", "font_size", "font_color",
"highlight_color", "border_color", "border_width",
"effect", "base_opacity", "uppercase",

View file

@ -1,5 +1,4 @@
"""Thumbnail Studio pieces that run without Gemini or a video."""
import pytest
from PIL import Image
from clipwright.media import thumbnail
@ -24,7 +23,6 @@ def test_burn_text_no_text_is_a_noop():
def test_finalize_cover_crops_to_1280x720_under_2mb(tmp_path):
# A 2K-ish image with a different aspect ratio, full of noise so JPEG is heavy.
import random
noisy = Image.effect_noise((2048, 1536), 80).convert("RGB")
out = tmp_path / "t.jpg"
thumbnail.finalize_thumbnail(noisy, str(out))

View file

@ -39,9 +39,6 @@ class TestNames:
assert not watermarked.job_is_marked(d)
watermarked.mark_job(d)
assert watermarked.job_is_marked(d)
watermarked.unmark_job(d)
assert not watermarked.job_is_marked(d)
watermarked.unmark_job(d) # idempotent
class TestMarkDelivery: