Merge remote-tracking branch 'origin/main' into chore/repo-cleanup
All checks were successful
CI / backend-tests (pull_request) Successful in 29s
CI / frontend-build (pull_request) Successful in 9m47s

# Conflicts:
#	README.md
This commit is contained in:
pedro-bento 2026-10-04 20:48:40 +01:00
commit 72965f616b
115 changed files with 557 additions and 305 deletions

View file

@ -72,7 +72,7 @@ GEMINI_IMAGE_MODEL=gemini-3.1-flash-image
# close-ups of a real person; the clock runs from the last download.
# THUMBNAIL_RETENTION_SECONDS=86400
# Per-IP rate limiting (rate_limit.py). "<max requests>/<window seconds>".
# 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

View file

@ -16,17 +16,12 @@ jobs:
container: nikolaik/python-nodejs:python3.11-nodejs20
steps:
- uses: actions/checkout@v4
# Everything the collected tests import at module level, WITHOUT the
# heavy ML stack (torch/ultralytics/mediapipe/faster-whisper) — the
# pipeline modules import those lazily behind their feature gates, and
# the tests exercise the gated-off paths. numpy+opencv cover the layout
# modules, fastapi/python-multipart cover importing app.py for the MCP
# endpoint tests, google-genai covers gemini_worker.
# Shared thin test environment (see requirements-test.txt): everything the
# collected tests import at module level, WITHOUT the heavy ML stack
# (torch/ultralytics/mediapipe/faster-whisper), which the pipeline modules
# import lazily behind their feature gates.
- name: Install test dependencies
run: >
pip install pytest pillow httpx pydantic numpy
opencv-python-headless python-dotenv google-genai fastapi
python-multipart
run: pip install -r requirements-test.txt
- name: Run tests
run: pytest tests/ -v

View file

@ -31,6 +31,11 @@ FROM python:3.11-slim
WORKDIR /app
# The FastAPI app lives in the `clipwright` package and job workers are launched
# as `python -m clipwright.pipeline.main`, so the repo root must be importable
# regardless of the process cwd.
ENV PYTHONPATH=/app
# Install FFmpeg, OpenCV deps, Node.js + npm + git (for yt-dlp JS + bgutil build).
# fontconfig + fonts-liberation back the subtitle font choices: without real
# fonts libass falls back to DejaVu for every UI option (issue #57).
@ -126,4 +131,4 @@ EXPOSE 8000
HEALTHCHECK --interval=5s --timeout=3s --start-period=30s --retries=2 \
CMD curl -sf http://127.0.0.1:8000/health/ready > /dev/null || exit 1
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers", "--forwarded-allow-ips", "*", "--timeout-graceful-shutdown", "15"]
CMD ["uvicorn", "clipwright.api.app:app", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers", "--forwarded-allow-ips", "*", "--timeout-graceful-shutdown", "15"]

View file

@ -99,6 +99,27 @@ curl -X POST http://localhost:8000/api/process \
Add `webhook_url` for exactly one callback when the job ends; with `webhook_secret` the body is signed `X-Clipwright-Signature: sha256=…`. Interactive docs are at `/docs`.
## Project structure
```
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
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)
```
The backend runs from the source tree (no install step): `uvicorn clipwright.api.app:app` serves the API and clip jobs run as `python -m clipwright.pipeline.main`.
## Tech stack
Python 3.11 · FastAPI · google-genai · faster-whisper · ultralytics (YOLOv8) · MediaPipe · FFmpeg · React 18 · Vite · Tailwind · Docker Compose.

1
clipwright/__init__.py Normal file
View file

@ -0,0 +1 @@
"""Clipwright backend."""

View file

@ -0,0 +1 @@
"""Clipwright backend."""

View file

@ -1,5 +1,5 @@
import os
import llm_backend
from clipwright.pipeline import llm_backend
import re
import sys
import uuid
@ -26,11 +26,12 @@ from fastapi.responses import FileResponse, JSONResponse
from starlette.background import BackgroundTask
from pydantic import BaseModel
import httpx
import recut
import layout_ranges
import watermarked
import media_auth
import postiz
from clipwright.media import recut
from clipwright.layouts import layout_ranges
from clipwright.media import watermarked
from clipwright.api import media_auth
from clipwright.integrations import postiz
from clipwright.core.paths import REPO_ROOT
load_dotenv()
@ -61,7 +62,6 @@ QUALITY_GATE_MIN_HEIGHT = int(os.environ.get("QUALITY_GATE_MIN_HEIGHT", "720"))
# managed minutes and dies with "no usable clips" (prod 20-ago: 3 of 5 recent
# failures were exactly this, one user retrying the same 24s video).
MIN_SOURCE_SECONDS = int(os.environ.get("MIN_SOURCE_SECONDS", "45"))
QUALITY_PROBE_SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "quality_probe.py")
# Server credentials the pipeline subprocesses (main.py, quality_probe.py) never
# read: main.py and everything it imports use GEMINI_API_KEY / LLM_* / the
@ -88,6 +88,11 @@ def child_env(base=None):
env = dict(os.environ if base is None else base)
for name in CHILD_ENV_DENYLIST:
env.pop(name, None)
# The pipeline modules run as ``-m clipwright.pipeline.<mod>``; make the
# package importable regardless of the child's cwd.
env["PYTHONPATH"] = os.pathsep.join(
filter(None, [env.get("PYTHONPATH"), str(REPO_ROOT)])
)
return env
@ -466,7 +471,7 @@ def _reapply_captions(job_id, clip_index, video_path):
if not transcript or clip_index >= len(clips):
return None
clip = clips[clip_index]
import main as _main
from clipwright.pipeline import main as _main
# A recut clip is a concatenation of source segments, so the flat
# start..end window is wrong for it — caption against the clip-relative
# remapped transcript instead (same trick /api/subtitle uses).
@ -1409,7 +1414,7 @@ async def _deliver_webhook(url, body: bytes, secret):
headers = {"Content-Type": "application/json", "User-Agent": "Clipwright-Webhook/1.0"}
if secret:
headers["X-Clipwright-Signature"] = _sign_webhook(body, secret)
from security_utils import assert_public_url, UnsafeURLError
from clipwright.core.security_utils import assert_public_url, UnsafeURLError
loop = asyncio.get_event_loop()
for attempt, delay in enumerate(WEBHOOK_RETRY_DELAYS, 1):
if delay:
@ -1477,7 +1482,7 @@ app = FastAPI(lifespan=lifespan)
# Free public tools behind the /tools SEO pages: YouTube transcript (existing
# captions only, never the GPU) and the title/description/tag generator.
import free_tools as _free_tools
from clipwright.api import free_tools as _free_tools
app.include_router(_free_tools.router)
# Enable CORS for frontend. Self-host allows any origin (permissive wildcard).
@ -1495,7 +1500,7 @@ app.add_middleware(
# Mount static files for serving videos. ``guard`` refuses non-deliverables
# (``*_metadata.json``, ``.owner``, ``.resume.json``) so they are never served.
from restoring_static import RestoringStaticFiles
from clipwright.api.restoring_static import RestoringStaticFiles
app.mount("/videos", RestoringStaticFiles(
directory=OUTPUT_DIR,
guard=_media_guard), name="videos")
@ -1761,7 +1766,7 @@ async def _probe_youtube_quality(url: str) -> dict:
def _run():
try:
proc = subprocess.run(
[sys.executable, QUALITY_PROBE_SCRIPT, "--url", url],
[sys.executable, "-m", "clipwright.pipeline.quality_probe", "--url", url],
capture_output=True, timeout=75, env=child_env(),
)
return json.loads(proc.stdout.decode(errors="replace").strip() or "{}")
@ -1779,8 +1784,8 @@ async def _validate_source_url(url: str):
search / playlist / channel page (yt_clients). The download and the
metering probe check the same things again; this is the one in front of
the quality probe, which used to have none."""
from security_utils import assert_public_url, UnsafeURLError
from yt_clients import youtube_non_video_reason
from clipwright.core.security_utils import assert_public_url, UnsafeURLError
from clipwright.integrations.yt_clients import youtube_non_video_reason
try:
await asyncio.get_event_loop().run_in_executor(None, assert_public_url, url)
except UnsafeURLError as e:
@ -2103,7 +2108,7 @@ async def process_endpoint(
# Completion callback: reject unsafe targets NOW (clear 400) — delivery
# re-validates anyway, but failing at submit is the debuggable behavior.
if webhook_url:
from security_utils import assert_public_url, UnsafeURLError
from clipwright.core.security_utils import assert_public_url, UnsafeURLError
try:
await asyncio.get_event_loop().run_in_executor(
None, assert_public_url, webhook_url)
@ -2146,7 +2151,7 @@ async def process_endpoint(
# outside Docker is whatever interpreter happens to be first — not the venv
# running this server. Every job then dies on `import cv2`. The quality
# probe above already gets this right.
cmd = [sys.executable, "-u", "main.py"] # -u for unbuffered
cmd = [sys.executable, "-u", "-m", "clipwright.pipeline.main"] # -u for unbuffered
env = child_env()
if api_key:
env["GEMINI_API_KEY"] = api_key # Override with key from request
@ -2170,7 +2175,7 @@ async def process_endpoint(
# byte-for-byte; the dashboard sends an explicit value either way.
if str(auto_hook).lower() in ("1", "true", "yes"):
env["AUTO_HOOK"] = "1"
from hooks import HOOK_STYLES
from clipwright.media.hooks import HOOK_STYLES
if auto_hook_style in HOOK_STYLES:
env["AUTO_HOOK_STYLE"] = auto_hook_style
print(f"[auto-hook] job={job_id} style={env.get('AUTO_HOOK_STYLE', 'classic')}")
@ -2540,10 +2545,10 @@ async def download_all_clips(job_id: str, request: Request):
# Files live on local disk in this self-host fork, so there is nothing to restore.
from editor import VideoEditor
from subtitles import generate_srt, generate_ass, burn_subtitles, CAPTION_PRESETS
from hooks import add_hook_to_video
from thumbnail import (analyze_video_for_titles, refine_titles, generate_thumbnail,
from clipwright.media.editor import VideoEditor
from clipwright.media.subtitles import generate_srt, generate_ass, burn_subtitles, CAPTION_PRESETS
from clipwright.media.hooks import add_hook_to_video
from clipwright.media.thumbnail import (analyze_video_for_titles, refine_titles, generate_thumbnail,
generate_youtube_description, extract_face_frames)
class EditRequest(BaseModel):
@ -3195,7 +3200,7 @@ async def get_clip_scenes(job_id: str, clip_index: int, request: Request):
def build():
import cv2
import main as m
from clipwright.pipeline import main as m
# Stable for the files the browser fetches (no accumulation), unique
# for the temp cut (no collision between overlapping requests).
@ -4413,19 +4418,19 @@ async def thumbnail_upload(
vpath = video_path
# Download YouTube video if URL was provided
if not vpath and url:
from main import download_youtube_video
from clipwright.pipeline.main import download_youtube_video
loop = asyncio.get_event_loop()
vpath, _ = await loop.run_in_executor(None, download_youtube_video, url, UPLOAD_DIR)
thumbnail_sessions[session_id]["video_path"] = vpath
from main import transcribe_video
from clipwright.pipeline.main import transcribe_video
loop = asyncio.get_event_loop()
try:
transcript = await loop.run_in_executor(None, transcribe_video, vpath)
finally:
# See transcribe_backends.release_models: the API process is
# long-lived and the GPU is shared with every running job.
import transcribe_backends
from clipwright.pipeline import transcribe_backends
await loop.run_in_executor(None, transcribe_backends.release_models)
segments = transcript.get("segments", [])
duration = segments[-1]["end"] if segments else 0
@ -4492,7 +4497,7 @@ async def thumbnail_analyze(
session_id = str(uuid.uuid4())
if url:
from main import download_youtube_video
from clipwright.pipeline.main import download_youtube_video
video_path, _ = await asyncio.get_event_loop().run_in_executor(
None, download_youtube_video, url, UPLOAD_DIR)
else:

View file

@ -0,0 +1 @@
"""Clipwright backend."""

31
clipwright/core/paths.py Normal file
View file

@ -0,0 +1,31 @@
"""Canonical filesystem locations for the Clipwright backend.
The importable package lives at ``<repo>/clipwright`` while the shared runtime
resources (``fonts/``, ``assets/``, ``yolov8n.pt``) stay at the repository root.
Keeping the constants here means every module resolves them the same way,
independently of the current working directory or of how deep a module sits in
the package.
"""
from __future__ import annotations
from pathlib import Path
# .../clipwright
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

@ -0,0 +1 @@
"""Clipwright backend."""

View file

@ -0,0 +1 @@
"""Clipwright backend."""

View file

@ -220,7 +220,7 @@ def speaker_xs(held, centres, crop_w, orig_w, n_frames, fps,
def verdicts_for_scene(video_path, start_f, end_f, fps, centres):
"""Per-window speaker verdicts for one scene, from its two face centres."""
import split_layout
from clipwright.layouts import split_layout
start_s = start_f / fps
duration_s = (end_f - start_f) / fps

View file

@ -20,7 +20,7 @@ them with margin.
"""
import os
from ffmpeg_utils import blurred_backdrop
from clipwright.media.ffmpeg_utils import blurred_backdrop
CORNER_MARGIN = 0.20 # a subject this far from an edge (as a fraction of the
# frame) still counts as anchored to it
@ -159,8 +159,8 @@ def detect(video_path, samples=10):
"""
import cv2
import numpy as np
import main as m
import screencast_layout
from clipwright.pipeline import main as m
from clipwright.layouts import screencast_layout
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():

View file

@ -82,9 +82,9 @@ def apply(decision):
stacking regardless of what the model thinks, and a model that says "none"
must not quietly undo that.
"""
import active_speaker
import screencast_layout
import split_layout
from clipwright.layouts import active_speaker
from clipwright.layouts import screencast_layout
from clipwright.layouts import split_layout
modules = {"split_layout": split_layout,
"screencast_layout": screencast_layout,
@ -191,7 +191,7 @@ def pick(video_path, video_duration):
# raises, and an unimportable SDK is just one more reason to fall back.
from google import genai
from google.genai import types as genai_types
import gemini_worker
from clipwright.pipeline import gemini_worker
frames = sample_frames(video_path)
if not frames:

View file

@ -24,7 +24,7 @@ import os
import numpy as np
import split_layout
from clipwright.layouts import split_layout
ENABLED = os.environ.get("PANEL_LAYOUT", "0") == "1"
@ -223,7 +223,7 @@ def detect_panel_scenes(video_path, scenes, strategies, samples=None):
# 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
import main as m
from clipwright.pipeline import main as m
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():

View file

@ -162,7 +162,7 @@ def emphasis_times(video_path, duration, window=BEAT_WINDOW,
A stand-in for the hook words until the transcript is wired through. Returns
[] for silent or unreadable audio, which simply means no punches.
"""
import active_speaker
from clipwright.layouts import active_speaker
envelope = active_speaker.audio_envelope(video_path, 0.0, duration,
window_s=window)

View file

@ -21,13 +21,13 @@ import os
import subprocess
import tempfile
import active_speaker
import camera_inset
import punch_in
import screencast_layout
import layout_ranges
import split_layout
from ffmpeg_utils import (video_encode_args, blurred_backdrop, escape_filter_value,
from clipwright.layouts import active_speaker
from clipwright.layouts import camera_inset
from clipwright.layouts import punch_in
from clipwright.layouts import screencast_layout
from clipwright.layouts import layout_ranges
from clipwright.layouts import split_layout
from clipwright.media.ffmpeg_utils import (video_encode_args, blurred_backdrop, escape_filter_value,
QUALITY_FAST, METADATA_SCRUB)
ANALYSIS_MAX_WIDTH = 640
@ -255,7 +255,7 @@ def _analyze_trajectory(input_video, scenes_boundaries, scene_strategies,
"""Replays v1's per-frame decision loop on a downscaled ffmpeg-decoded
stream. Returns xs: crop x per frame (None on GENERAL frames)."""
import numpy as np
import main as m
from clipwright.pipeline import main as m
small_w = min(ANALYSIS_MAX_WIDTH, orig_w)
if small_w % 2:
@ -362,7 +362,7 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
segment's own encode, instead of main.apply_watermark re-encoding the
finished clip once more.
"""
import main as m
from clipwright.pipeline import main as m
content_ranges = content_ranges or []
print(" 🚀 Reframe engine v2 (ffmpeg-native render)")

View file

@ -123,7 +123,7 @@ def detect_faces_full_res(frame):
screencast candidates only.
"""
import cv2
import main as m
from clipwright.pipeline import main as m
h, w, _ = frame.shape
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
@ -178,7 +178,7 @@ def detect_content_ranges(video_path, video_duration):
from google import genai
from google.genai import types as genai_types
import gemini_worker
from clipwright.pipeline import gemini_worker
model_name = os.environ.get("GEMINI_MODEL") or 'gemini-3.1-flash-lite'
print("🔎 Checking for full-width on-screen content…")
@ -268,7 +268,7 @@ def detect_screencast_scenes(video_path, scenes, strategies, ranges, samples=6):
# 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
import main as m
from clipwright.pipeline import main as m
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():

View file

@ -18,7 +18,7 @@ import os
import numpy as np
import frame_sampler
from clipwright.media import frame_sampler
ENABLED = os.environ.get("SPLIT_LAYOUT", "0") == "1"
@ -221,7 +221,7 @@ def detect_split_scenes(video_path, scenes, strategies, samples=None):
touching the single-speaker material that is most of the corpus.
"""
import cv2
import main as m
from clipwright.pipeline import main as m
if not ENABLED:
return {}

View file

@ -0,0 +1 @@
"""Clipwright backend."""

View file

@ -8,9 +8,9 @@ from google import genai
from google.genai import types
from pydantic import BaseModel
import gemini_worker
from edit_builder import build_filter_string
from ffmpeg_utils import video_encode_args, QUALITY, METADATA_SCRUB
from clipwright.pipeline import gemini_worker
from clipwright.media.edit_builder import build_filter_string
from clipwright.media.ffmpeg_utils import video_encode_args, QUALITY, METADATA_SCRUB
class EditDecision(BaseModel):

View file

@ -6,7 +6,8 @@ import urllib.request
import uuid
from PIL import Image, ImageDraw, ImageFont, ImageFilter
from ffmpeg_utils import video_encode_args, QUALITY, METADATA_SCRUB
from clipwright.media.ffmpeg_utils import video_encode_args, QUALITY, METADATA_SCRUB
from clipwright.core.paths import FONTS_DIR
def _truncate_bytes(text, max_bytes):
@ -21,7 +22,7 @@ def _truncate_bytes(text, max_bytes):
return encoded[:max_bytes].decode("utf-8", "ignore")
FONT_URL = "https://github.com/googlefonts/noto-fonts/raw/main/hinted/ttf/NotoSerif/NotoSerif-Bold.ttf"
FONT_DIR = "fonts"
FONT_DIR = str(FONTS_DIR)
FONT_PATH = os.path.join(FONT_DIR, "NotoSerif-Bold.ttf")
# Bundled (SIL OFL, see fonts/Montserrat-OFL.txt): the "pill" look's sans.
PILL_FONT_PATH = os.path.join(FONT_DIR, "Montserrat-ExtraBold.ttf")

View file

@ -24,7 +24,7 @@ import subprocess
import time
import uuid
from ffmpeg_utils import (METADATA_SCRUB, QUALITY_FAST, audio_encode_args,
from clipwright.media.ffmpeg_utils import (METADATA_SCRUB, QUALITY_FAST, audio_encode_args,
video_encode_args)
# EDL limits. Deliberately generous — the editor is for humans fixing cuts,
@ -109,7 +109,7 @@ def rebase_segments(segments, range_start, range_end=None):
def snap_segments(segments, transcript, source_duration):
"""Snap each segment's bounds onto word boundaries (ground truth beats
millisecond arithmetic — same rationale as the pipeline's snapping)."""
from clip_selection import snap_clip_to_words
from clipwright.pipeline.clip_selection import snap_clip_to_words
words = transcript_words(transcript)
if not words:
@ -316,7 +316,7 @@ def perform_recut(*, input_path, segments, output_dir, clean_name,
# No reframe means no fresh layout sidecar; the captions would fall
# back to the bottom on a stacked clip. Carry the input's layout
# ranges through the cut instead (empty when the input has none).
import layout_ranges
from clipwright.layouts import layout_ranges
layout_ranges.write(out_path, [
(r["start"], r["end"], r["layout"])
for r in layout_ranges.remap(layout_ranges.read(input_path), segments)])
@ -338,5 +338,5 @@ def perform_recut(*, input_path, segments, output_dir, clean_name,
def _main_attr(name):
import main # heavy — resolved only when a real render/caption runs
from clipwright.pipeline import main # heavy — resolved only when a real render/caption runs
return getattr(main, name)

View file

@ -3,8 +3,9 @@ import re
import subprocess
import sys
from ffmpeg_utils import (video_encode_args, escape_filter_value, QUALITY,
from clipwright.media.ffmpeg_utils import (video_encode_args, escape_filter_value, QUALITY,
METADATA_SCRUB)
from clipwright.core.paths import FONTS_DIR
_STDIO_CONFIGURED = False
@ -119,7 +120,7 @@ def transcribe_audio(video_path):
Returns transcript in the same format as main.py for compatibility.
"""
# Lazy import: transcribe_backends imports helpers from this module.
from transcribe_backends import transcribe_media
from clipwright.pipeline.transcribe_backends import transcribe_media
_log(f"🎙️ Transcribing audio from: {video_path}")
transcript = transcribe_media(video_path)
@ -629,7 +630,7 @@ def subtitles_filter(srt_path, alignment=2, fontsize=16,
# Let libass see the fonts bundled with the app (e.g. Anton for Impact)
# even when the system fontconfig has no cache for them.
fonts_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fonts")
fonts_dir = str(FONTS_DIR)
safe_fonts_dir = _escape_ffmpeg_filter_value(fonts_dir)
# The first option is named explicitly (filename=) rather than positional:

View file

@ -9,6 +9,7 @@ from google import genai
from google.genai import types
from google.genai import errors as genai_errors
from PIL import Image, ImageDraw, ImageFont, ImageFilter
from clipwright.core.paths import FONTS_DIR
# Text/analysis model (titles, concepts, description). Deliberately NOT tied to
# GEMINI_MODEL: the pipeline runs flash-lite for a closed-choice layout pick,
@ -30,7 +31,7 @@ TITLE_MAX_CHARS = 65
THUMB_W, THUMB_H = 1280, 720
THUMB_MAX_BYTES = 2 * 1024 * 1024 # YouTube's upload limit
THUMB_FONT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fonts", "Anton-Regular.ttf")
THUMB_FONT = str(FONTS_DIR / "Anton-Regular.ttf")
TEXT_POSITIONS = ("left", "right", "top", "bottom")
@ -49,7 +50,7 @@ def _parse_json(text):
def _frame_parts(video_path, n=TITLE_FRAMES, width=TITLE_FRAME_WIDTH):
"""Evenly spaced frames as Gemini image parts (empty list on any failure)."""
try:
from layout_picker import sample_frames
from clipwright.layouts.layout_picker import sample_frames
return [types.Part.from_bytes(data=b, mime_type="image/jpeg")
for b in sample_frames(video_path, n=n, width=width)]
except Exception as e:
@ -70,7 +71,7 @@ def analyze_video_for_titles(api_key, video_path, transcript=None):
"segments", "video_duration", "recommended" }
"""
if transcript is None:
from main import transcribe_video
from clipwright.pipeline.main import transcribe_video
print("🎬 [Thumbnail] Transcribing video...")
transcript = transcribe_video(video_path)
else:
@ -265,7 +266,7 @@ def extract_face_frames(video_path, session_id, n=5, samples=40):
thumbnails dir. Returns [{"url", "path", "time", "face": [x, y, w, h]}].
"""
import cv2
from main import detect_face_candidates
from clipwright.pipeline.main import detect_face_candidates
out_dir = os.path.join("output", "thumbnails", session_id, "frames")
os.makedirs(out_dir, exist_ok=True)

View file

@ -0,0 +1 @@
"""Clipwright backend."""

View file

@ -10,7 +10,7 @@ from google import genai
from google.genai import types as genai_types
from pydantic import BaseModel
from clip_selection import (clip_count_targets, clip_duration_bounds,
from clipwright.pipeline.clip_selection import (clip_count_targets, clip_duration_bounds,
lookup_model_prices)
load_dotenv()

View file

@ -42,7 +42,7 @@ def screen_video() -> bool:
(verified on a product update video: every GENERAL scene was a stats
card), even when the width gate did not upgrade it to SCREENCAST."""
try:
import screencast_layout
from clipwright.layouts import screencast_layout
return bool(getattr(screencast_layout, "ENABLED", False))
except Exception:
return False
@ -50,7 +50,7 @@ def screen_video() -> bool:
def screen_ranges(ranges, on_screen_video=None):
"""(start, end) pairs, clip seconds, of the stretches rendered on-screen."""
import layout_ranges
from clipwright.layouts import layout_ranges
layouts = set(SCREEN_LAYOUTS)
if screen_video() if on_screen_video is None else on_screen_video:
layouts.add("general")
@ -125,7 +125,7 @@ def _ask_gemini(frames, prompt, api_key):
"""One vision call; returns the parsed dict. Split out so tests can stub it."""
from google import genai
from google.genai import types as genai_types
import gemini_worker
from clipwright.pipeline import gemini_worker
client = genai.Client(api_key=api_key)
model_name = os.environ.get("GEMINI_MODEL") or "gemini-3.1-flash-lite"
@ -151,7 +151,7 @@ def reground(clip_path, clip, transcript, start, end) -> Optional[dict]:
"keeping the transcript hook.")
return None
try:
import gemini_worker
from clipwright.pipeline import gemini_worker
times = sample_times(clip.get("layout_ranges"), float(end) - float(start))
frames = frames_at(clip_path, times)

View file

@ -108,7 +108,7 @@ def generate_json(prompt: str, schema: Type[BaseModel], model: Optional[str] = N
provider. Raises on HTTP errors, empty bodies and schema violations; the
retry policy lives in the caller, same as for Gemini.
"""
import gemini_worker # local import: keeps this module free of the google SDK
from clipwright.pipeline import gemini_worker # local import: keeps this module free of the google SDK
url = f"{base_url()}/chat/completions"
model = model or model_name()

View file

@ -23,16 +23,17 @@ import mediapipe as mp
from google import genai
from google.genai import types as genai_types
import frame_sampler
import gemini_worker
import hook_grounding
import layout_picker
import llm_backend
from clip_selection import (build_transcript_windows, clip_count_targets,
from clipwright.media import frame_sampler
from clipwright.pipeline import gemini_worker
from clipwright.pipeline import hook_grounding
from clipwright.layouts import layout_picker
from clipwright.pipeline import llm_backend
from clipwright.core.paths import ASSETS_DIR
from clipwright.pipeline.clip_selection import (build_transcript_windows, clip_count_targets,
clip_duration_bounds, dedupe_overlapping,
score_batches, shortlist_target,
snap_clip_to_words, trim_to_best)
from ffmpeg_utils import (video_encode_args, audio_encode_args, cut_clip, QUALITY,
from clipwright.media.ffmpeg_utils import (video_encode_args, audio_encode_args, cut_clip, QUALITY,
QUALITY_FAST, METADATA_SCRUB)
from dotenv import load_dotenv
import json
@ -633,7 +634,7 @@ def analyze_scenes_strategy(video_path, scenes):
return strategies
def detect_scenes(video_path):
import scene_detection
from clipwright.media import scene_detection
return scene_detection.detect_scenes(video_path)
def get_video_resolution(video_path):
@ -836,14 +837,14 @@ def download_youtube_video(url, output_dir=".", on_audio=None):
"""
# SSRF guard: block non-http(s) schemes and private/loopback/metadata hosts
# before handing the URL to yt-dlp.
from security_utils import assert_public_url
from clipwright.core.security_utils import assert_public_url
assert_public_url(url)
# Throwaway hosts agents fall back to (tmpfiles.org) hand out short-lived
# signed links; refresh through the host's page so yt-dlp gets the file.
import file_hosts
from clipwright.integrations import file_hosts
url = file_hosts.resolve(url)
# Reject non-video YouTube links before the download starts.
from yt_clients import NotASingleVideo, youtube_non_video_reason
from clipwright.integrations.yt_clients import NotASingleVideo, youtube_non_video_reason
reason = youtube_non_video_reason(url)
if reason:
raise NotASingleVideo(f"This link is {reason}.")
@ -899,7 +900,7 @@ def download_youtube_video(url, output_dir=".", on_audio=None):
# explicit `default,mweb` because the authed defaults alone return
# "Video unavailable" on a share of videos, from every IP, and that was
# what fed the per-GB proxy (6-sep-2026, verified in the prod container).
from yt_clients import hd_extractor_args, fallback_extractor_args
from clipwright.integrations.yt_clients import hd_extractor_args, fallback_extractor_args
hd_args = hd_extractor_args(_bgutil_http, _bgutil_script)
fallback_args = fallback_extractor_args(_bgutil_http, _bgutil_script)
@ -1210,7 +1211,7 @@ def auto_caption_clip(clip_path, transcript, clip_start, clip_end, split_ranges=
if not transcript or not transcript.get('segments'):
return None # silent video: nothing to caption
try:
import subtitles as _subs
from clipwright.media import subtitles as _subs
style = _subs.AUTO_CAPTION_STYLE
output_dir = os.path.dirname(clip_path)
stem = os.path.basename(clip_path)
@ -1242,7 +1243,7 @@ def auto_caption_clip(clip_path, transcript, clip_start, clip_end, split_ranges=
out_path = os.path.join(output_dir, f"subtitled_{generation_id}_{stem}")
if split_ranges is None:
import layout_ranges as _layouts
from clipwright.layouts import layout_ranges as _layouts
split_ranges = _layouts.split_ranges(_layouts.read(clip_path))
if not _subs.generate_ass(
transcript, clip_start, clip_end, ass_path,
@ -1302,7 +1303,7 @@ def auto_hook_clip(clip_path, clip, captions=None):
except ValueError:
seconds = 5.0
try:
from hooks import add_hook_to_video, HOOK_STYLES
from clipwright.media.hooks import add_hook_to_video, HOOK_STYLES
if style not in HOOK_STYLES:
style = "pill"
output_dir = os.path.dirname(clip_path)
@ -1378,8 +1379,7 @@ WATERMARK_OPACITY = 0.85
def watermark_logo_path():
return os.path.join(os.path.dirname(os.path.abspath(__file__)),
"assets", "watermark.png")
return str(ASSETS_DIR / "watermark.png")
def watermark_filter(vw, vh, video="[0:v]", logo="[1:v]", out=""):
@ -1451,7 +1451,7 @@ def mark_delivery(final_path, marker=None):
be made: the mark must never cost the user the clip (same fail-open rule
apply_watermark has always had).
"""
import watermarked
from clipwright.media import watermarked
out_path = os.path.join(os.path.dirname(final_path),
watermarked.marked_name(final_path))
if os.path.exists(out_path) and os.path.getsize(out_path) > 0:
@ -1484,7 +1484,7 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE
# falls back to the v1 frame loop below so a v2 edge case can't kill jobs.
if os.environ.get("REFRAME_ENGINE", "v2").strip().lower() != "v1":
try:
import reframe_v2
from clipwright.layouts import reframe_v2
t0 = time.time()
result = reframe_v2.render(input_video, final_output_video, aspect_ratio,
force_strategy=force_strategy,
@ -1536,7 +1536,7 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE
# Same delivery floor as the v2 engine — a fallback render is still the clip
# the user posts, so it must not ship sub-HD. The frame loop below already
# resizes every cropped frame to these dims, so nothing else changes.
from reframe_v2 import delivery_size
from clipwright.layouts.reframe_v2 import delivery_size
OUTPUT_WIDTH, OUTPUT_HEIGHT = delivery_size(original_width, original_height,
aspect_ratio)
@ -1776,7 +1776,7 @@ def _free_gpu_cache():
def transcribe_video(video_path):
print("🎙️ Transcribing video...")
from transcribe_backends import transcribe_media, release_models, host_asr_slot
from clipwright.pipeline.transcribe_backends import transcribe_media, release_models, host_asr_slot
# At most ASR_HOST_SLOTS jobs transcribe on the GPU at once, host-wide.
# Inside the slot, the model's VRAM is handed back before the long render
@ -2308,7 +2308,7 @@ if __name__ == '__main__':
_w = int(_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
_h = int(_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
_cap.release()
from reframe_v2 import source_already_fits # imports main back
from clipwright.layouts.reframe_v2 import source_already_fits # imports main back
# A source already shot vertical has no width to reorganise, and
# the render passes it through whatever the model says. Asking
# anyway costs a Gemini call per upload to be ignored.
@ -2340,7 +2340,7 @@ if __name__ == '__main__':
# 3. Transcribe — unless the video has no audio, in which case fall back
# to Gemini vision (picks clips from the imagery instead of the speech).
from transcribe_backends import NoAudioError
from clipwright.pipeline.transcribe_backends import NoAudioError
transcript = None
# Module handover (issue #68): another module already transcribed this
# exact source with the same backend, so reuse its output. Any problem
@ -2453,7 +2453,7 @@ if __name__ == '__main__':
deliver_path = clip_final_path
# Which stretches were stacked (SPLIT): captions go on the
# seam there, and /api/subtitle needs it again later.
import layout_ranges as _layouts
from clipwright.layouts import layout_ranges as _layouts
clip['layout_ranges'] = _layouts.read(clip_final_path)
# The hook was written from the transcript alone. When the
# render put this clip's meaning on the screen, rewrite hook
@ -2505,7 +2505,7 @@ if __name__ == '__main__':
if os.environ.get("WATERMARK") == "1":
# Tells the /videos guard that the clean twins in this
# directory are not for serving (watermarked.MARKER_FILE).
import watermarked
from clipwright.media import watermarked
watermarked.mark_job(output_dir)
with ThreadPoolExecutor(max_workers=min(clip_workers, len(shorts))) as pool:
# Best clip first: the pool starts work in submission order, so

View file

@ -16,15 +16,16 @@ import sys
from dotenv import load_dotenv
from clipwright.core.paths import REPO_ROOT
load_dotenv()
def _find_cookies_path():
# Mirrors main.py's cookie discovery.
script_dir = os.path.dirname(os.path.abspath(__file__))
for candidate in [
os.path.join(script_dir, 'www.youtube.com_cookies.txt'),
os.path.join(script_dir, 'cookies.txt'),
str(REPO_ROOT / 'www.youtube.com_cookies.txt'),
str(REPO_ROOT / 'cookies.txt'),
'/app/cookies.txt',
]:
if os.path.exists(candidate):
@ -44,8 +45,8 @@ def main() -> int:
# result is the fail-open "unknown", so the caller carries on and the
# real probe / download refuse the URL with their own message.
try:
from security_utils import assert_public_url
from yt_clients import youtube_non_video_reason
from clipwright.core.security_utils import assert_public_url
from clipwright.integrations.yt_clients import youtube_non_video_reason
assert_public_url(args.url)
if youtube_non_video_reason(args.url):
raise ValueError("not a single video")

View file

@ -32,7 +32,7 @@ import tempfile
import threading
import time
from subtitles import (
from clipwright.media.subtitles import (
get_whisper_config,
WHISPER_TRANSCRIBE_PARAMS,
merge_continuation_words,
@ -368,7 +368,7 @@ def release_models():
del whisper, parakeet
# TransNetV2 is the other torch tenant an in-process pipeline leaves
# behind (scene_detection keeps it as a module singleton too).
tn2 = sys.modules.get("scene_detection")
tn2 = sys.modules.get("clipwright.media.scene_detection")
if tn2 is not None:
tn2._tn2_model = None
import gc

View file

@ -0,0 +1 @@
"""Clipwright backend."""

View file

@ -2,7 +2,7 @@ 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 hooks import create_hook_image
from clipwright.media.hooks import create_hook_image
except ImportError:
print("⚠️ PIL not found locally. Please run this inside the Docker container.")
# Mocking for local check if needed or just exit

View file

@ -1,6 +1,6 @@
import os
try:
from hooks import create_hook_image
from clipwright.media.hooks import create_hook_image
except ImportError:
print("⚠️ PIL not found locally. Run inside Docker.")
exit(1)

View file

@ -1,6 +1,6 @@
import os
import shutil
from hooks import create_hook_image
from clipwright.media.hooks import create_hook_image
def verify():
print("🧪 Verifying Hook Image Generation...")

View file

@ -1754,7 +1754,7 @@ ${faqBlock([
${sources([
'Opus Clip tier minutes and prices checked 2026-07-27 on their public pricing page.',
'Inset detection and layout accuracy figures are our own measurements on a 48-video internal corpus, 2026-08.',
'Silent-footage thresholds (8 words, 5 words per minute) and the vision fallback are in <code>main.py</code>; Gemini video token rates from Google\'s published pricing.',
'Silent-footage thresholds (8 words, 5 words per minute) and the vision fallback are in <code>clipwright/pipeline/main.py</code>; Gemini video token rates from Google\'s published pricing.',
`Inset, WIDE and screencast layout implementations in the project source at <a href="${SITE.repo}" rel="noopener">git.pbento.pt/pedro-bento/clipwright</a>.`,
])}
`,

View file

@ -11,7 +11,7 @@ const ENTRANCE_OPTIONS = [
{ value: 'none', label: 'None' },
];
// Must mirror hooks.py HOOK_STYLES.
// Must mirror clipwright/media/hooks.py HOOK_STYLES.
const HOOK_STYLES = [
{ value: 'pill', label: 'Pills', box: 'rgba(255,255,255,0.98)', text: '#000', sans: true },
{ value: 'classic', label: 'Classic', box: 'rgba(255,255,255,0.94)', text: '#000' },
@ -22,7 +22,7 @@ const HOOK_STYLES = [
{ value: 'outline_yellow', label: 'Outline+', box: 'transparent', text: '#FFD600', outline: true },
];
// Must mirror hooks.py HOOK_FONTS (all bundled: /fonts/*.ttf).
// Must mirror clipwright/media/hooks.py HOOK_FONTS (all bundled: /fonts/*.ttf).
const FONT_OPTIONS = [
{ value: 'montserrat', label: 'Montserrat' },
{ value: 'anton', label: 'Anton' },
@ -33,7 +33,7 @@ const FONT_CSS = {
anton: { fontFamily: "'Anton-Regular', Impact, sans-serif", fontWeight: 400 },
serif: { fontFamily: "'Noto Serif', Georgia, serif", fontWeight: 700 },
};
// The style's own typeface when none is picked (what hooks.py renders).
// The style's own typeface when none is picked (what clipwright/media/hooks.py renders).
const styleFont = (st) => (st === 'pill' ? 'montserrat' : 'serif');
const POSITION_OPTIONS = [

View file

@ -25,7 +25,7 @@ const SIZE_SCALE: Record<string, number> = {
L: 1.3,
};
// Percentages must match hooks.py's overlay_y math (top 20% / bottom 70%),
// Percentages must match clipwright/media/hooks.py's overlay_y math (top 20% / bottom 70%),
// or the preview drifts from what the server path renders.
const POSITION_STYLE: Record<string, React.CSSProperties> = {
top: { top: "20%", bottom: "auto" },
@ -33,13 +33,13 @@ const POSITION_STYLE: Record<string, React.CSSProperties> = {
bottom: { top: "70%", bottom: "auto" },
};
// Must mirror hooks.py HOOK_STYLES (the server-side FFmpeg fallback).
// Must mirror clipwright/media/hooks.py HOOK_STYLES (the server-side FFmpeg fallback).
interface HookLook {
box: string | null;
text: string;
outlinePx: number;
shadow: boolean;
/** One rounded box per line (hooks.py _draw_pills) instead of one card. */
/** One rounded box per line (clipwright/media/hooks.py _draw_pills) instead of one card. */
pills?: boolean;
}
@ -127,7 +127,7 @@ const HookBox: React.FC<HookBoxProps> = ({ config, displayFrames }) => {
const positionStyle = POSITION_STYLE[config.position] ?? POSITION_STYLE.top;
const look = HOOK_LOOKS[config.style ?? "pill"] ?? HOOK_LOOKS.pill;
// Typeface and size as hooks.py: the chosen font, else the style's own;
// Typeface and size as clipwright/media/hooks.py: the chosen font, else the style's own;
// font size = factor x the 90%-of-width box.
const typeface = HOOK_FONTS[config.font ?? (look.pills ? "montserrat" : "serif")] ?? HOOK_FONTS.serif;
const fontSize = Math.round(1080 * 0.9 * typeface.factor * scale);
@ -135,7 +135,7 @@ const HookBox: React.FC<HookBoxProps> = ({ config, displayFrames }) => {
if (look.pills) {
// box-decoration-break: clone gives every wrapped line its own padded,
// rounded box, the same stack hooks.py draws for the FFmpeg path.
// rounded box, the same stack clipwright/media/hooks.py draws for the FFmpeg path.
return (
<div
style={{

View file

@ -41,7 +41,7 @@ export const antonFontFace = `
/**
* Hook typefaces: CSS family + share of the 90% box width used as font size.
* Must mirror hooks.py HOOK_FONTS.
* Must mirror clipwright/media/hooks.py HOOK_FONTS.
*/
export const HOOK_FONTS: Record<string, { family: string; weight: number; factor: number }> = {
montserrat: { family: `'${MONTSERRAT_FONT_FAMILY}', 'Montserrat', sans-serif`, weight: 800, factor: 0.064 },

View file

@ -33,15 +33,14 @@ La retención de fotos de actor se retiró con la función de vídeo UGC
| Qué | Plazo | Dónde se aplica |
|---|---|---|
| Clips y proyectos en el disco local | Hasta que los borres o caduque el barrido de trabajos | `app.cleanup_jobs`, `JOB_RETENTION_SECONDS` |
| Clips y proyectos en el disco local | Hasta que los borres o caduque el barrido de trabajos | `clipwright.api.app.cleanup_jobs`, `JOB_RETENTION_SECONDS` |
## 3. Base de datos de la aplicación (si usas cuentas)
| Qué | Plazo | Dónde se aplica |
|---|---|---|
| Datos de cuenta y proyectos | Mientras exista la cuenta; **inmediato** al borrarla | `app.py`, la ruta de borrado de cuenta |
| **Declaración de derechos** (IP truncada a /24, user-agent, fecha, origen) | Con el proyecto al que pertenece → hasta 5 años | `app.py` (captura) → `Project.state.rights_attestation` |
| `proxy_usage` (host de la URL, id de trabajo; **sin usuario**) | Contabilidad de costes; sin datos personales | `metering.py` |
| Datos de cuenta y proyectos | Mientras exista la cuenta; **inmediato** al borrarla | `clipwright/api/app.py`, la ruta de borrado de cuenta |
| **Declaración de derechos** (IP truncada a /24, user-agent, fecha, origen) | Con el proyecto al que pertenece → hasta 5 años | `clipwright/api/app.py` (captura) → `Project.state.rights_attestation` |
## 4. Navegador del usuario (localStorage, nunca cookies de terceros)

30
pyproject.toml Normal file
View file

@ -0,0 +1,30 @@
# The backend is not packaged or published: it runs from a bind-mounted source
# tree (docker-compose.yml) and `requirements.txt` is the single runtime
# dependency source for the Docker image. This file therefore carries tool
# configuration only — no [build-system] and no [project] table — which also
# avoids colliding with the published `clipwright` CLI distribution under
# `cli/`.
[tool.pytest.ini_options]
minversion = "7.0"
testpaths = ["tests"]
# Makes the repo-root `clipwright/` package importable without a sys.path hack
# in tests/conftest.py.
pythonpath = ["."]
[tool.ruff]
line-length = 100
target-version = "py311"
extend-exclude = [
"dashboard",
"render-service",
"remotion",
"cli",
"output",
"uploads",
]
[tool.ruff.lint]
# Correctness only for now: keep this migration reviewable. Style/import rules
# can be ratcheted later without conflicting with the structural change.
select = ["E4", "E7", "E9", "F"]

View file

@ -26,7 +26,7 @@ const POSITION_STYLE: Record<string, React.CSSProperties> = {
bottom: { top: "68%", bottom: "auto" },
};
// Must mirror hooks.py HOOK_STYLES so preview == burned output.
// Must mirror clipwright/media/hooks.py HOOK_STYLES so preview == burned output.
interface HookLook {
box: string | null;
text: string;
@ -126,7 +126,7 @@ const HookBox: React.FC<HookBoxProps> = ({ config, displayFrames }) => {
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 hooks.py logic)
// Base font size: 5% of 1080 width (matches clipwright/media/hooks.py logic)
const baseFontSize = 1080 * 0.05;
const fontSize = Math.round(baseFontSize * scale);

14
requirements-test.txt Normal file
View file

@ -0,0 +1,14 @@
# Thin test environment: everything the collected tests import at module level,
# WITHOUT the heavy ML stack (torch/ultralytics/mediapipe/faster-whisper). The
# pipeline modules import those lazily behind their feature gates, and the tests
# exercise the gated-off paths.
pytest
pillow
httpx
pydantic
numpy
opencv-python-headless
python-dotenv
google-genai
fastapi
python-multipart

View file

@ -1,5 +1,7 @@
import os
import sys
"""Shared pytest configuration.
# Make the repo root importable so tests can import the app modules directly.
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
The repo-root ``clipwright/`` package is made importable by
``[tool.pytest.ini_options] pythonpath = ["."]`` in the root ``pyproject.toml``,
so no manual ``sys.path`` manipulation is needed here. This module is kept for
future shared fixtures.
"""

View file

@ -1,4 +1,4 @@
from active_speaker import (
from clipwright.layouts.active_speaker import (
attribute_windows,
hold,
is_conversation,

View file

@ -13,7 +13,7 @@ import os
import pytest
Image = pytest.importorskip("PIL.Image")
thumbnail = pytest.importorskip("thumbnail")
thumbnail = pytest.importorskip("clipwright.media.thumbnail")
TRAINED = b"trainedAlgorithmicMedia"

View file

@ -14,7 +14,9 @@ import os
import httpx
import pytest
app_module = pytest.importorskip("app")
app_module = pytest.importorskip("clipwright.api.app")
from clipwright.core import security_utils # noqa: E402
def _client_call(method, path, **kw):
@ -105,7 +107,7 @@ def test_youtube_search_page_is_refused_before_any_probe(dirs, monkeypatch):
probed.append(u)
return {}
monkeypatch.setattr(app_module, "_probe_youtube_quality", _probe)
monkeypatch.setattr("security_utils.assert_public_url", lambda u: u)
monkeypatch.setattr(security_utils, "assert_public_url", lambda u: u)
resp = _post_process({"url": "https://www.youtube.com/results?search_query=x",
"acknowledged": True})
assert resp.status_code == 400
@ -194,29 +196,51 @@ def test_child_env_drops_server_secrets(monkeypatch):
def test_pipeline_code_reads_none_of_the_dropped_secrets():
"""If main.py (or anything it imports) ever needs one of these, the
"""If the pipeline (or anything it imports) ever needs one of these, the
denylist would silently break jobs: fail here instead."""
import ast
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
local = {f[:-3] for f in os.listdir(root) if f.endswith(".py")}
seen, stack = set(), ["main", "quality_probe"]
from pathlib import Path
root = Path(__file__).resolve().parents[1]
package = root / "clipwright"
# Every importable module name -> its source file, e.g.
# ``clipwright.media.subtitles`` -> clipwright/media/subtitles.py.
sources = {}
for path in package.rglob("*.py"):
parts = list(path.relative_to(root).with_suffix("").parts)
if parts[-1] == "__init__":
parts = parts[:-1]
sources[".".join(parts)] = path
seen, stack = set(), ["clipwright.pipeline.main", "clipwright.pipeline.quality_probe"]
while stack:
mod = stack.pop()
if mod in seen:
if mod in seen or mod not in sources:
continue
seen.add(mod)
src = open(os.path.join(root, mod + ".py"), encoding="utf-8").read()
src = sources[mod].read_text(encoding="utf-8")
for name in app_module.CHILD_ENV_DENYLIST:
assert f'"{name}"' not in src and f"'{name}'" not in src, (mod, name)
for node in ast.walk(ast.parse(src)):
names = []
if isinstance(node, ast.Import):
names = [a.name.split(".")[0] for a in node.names]
elif isinstance(node, ast.ImportFrom) and node.module:
names = [node.module.split(".")[0]]
for n in names:
if n in local:
stack.append(n)
targets = [a.name for a in node.names]
elif isinstance(node, ast.ImportFrom):
if node.level:
base = mod.split(".")[:-1]
base = base[: len(base) - (node.level - 1)]
prefix = ".".join(base)
base_mod = f"{prefix}.{node.module}" if node.module else prefix
else:
base_mod = node.module or ""
if node.module:
targets = [base_mod] + [f"{base_mod}.{a.name}" for a in node.names]
else:
targets = [f"{base_mod}.{a.name}" for a in node.names]
else:
continue
for target in targets:
if target in sources:
stack.append(target)
def test_job_env_has_no_server_secrets(dirs, calls, monkeypatch):
@ -240,7 +264,7 @@ import subprocess
class TestSafetyCap:
@pytest.fixture()
def source(self, tmp_path):
main = pytest.importorskip("main")
main = pytest.importorskip("clipwright.pipeline.main")
path = tmp_path / "src.mp4"
subprocess.run([
"ffmpeg", "-y", "-loglevel", "error",

View file

@ -9,7 +9,7 @@ import json
import pytest
app_module = pytest.importorskip("app")
app_module = pytest.importorskip("clipwright.api.app")
@pytest.fixture

View file

@ -1,4 +1,4 @@
from camera_inset import (
from clipwright.layouts.camera_inset import (
INSET_ASPECT,
inset_box,
inset_filtergraph,

View file

@ -2,7 +2,7 @@
import asyncio
import re
from subtitles import AUTO_CAPTION_STYLE, CAPTION_PRESETS, line_budget
from clipwright.media.subtitles import AUTO_CAPTION_STYLE, CAPTION_PRESETS, line_budget
def test_dashboard_offers_every_server_preset():
@ -28,14 +28,14 @@ def test_line_budget_shrinks_with_size_and_wide_fonts():
def test_unknown_preset_is_a_400():
import pytest
from fastapi import HTTPException
from app import SubtitleRequest, add_subtitles
from clipwright.api.app import SubtitleRequest, add_subtitles
with pytest.raises(HTTPException) as exc:
asyncio.run(add_subtitles(SubtitleRequest(job_id="j", clip_index=0, preset="nope"), None))
assert exc.value.status_code == 400
def test_preset_fills_only_fields_not_sent():
from app import SubtitleRequest
from clipwright.api.app import SubtitleRequest
req = SubtitleRequest(job_id="j", clip_index=0, preset="hormozi", highlight_color="#00FF00")
merged = req.model_copy(update={k: v for k, v in CAPTION_PRESETS["hormozi"].items()
if k not in req.model_fields_set})

View file

@ -9,7 +9,7 @@ import time
import pytest
app_module = pytest.importorskip("app")
app_module = pytest.importorskip("clipwright.api.app")
OLD = 2 * 3600 # older than the 1 h JOB_RETENTION_SECONDS the fixture sets

View file

@ -9,7 +9,7 @@ import json
import pytest
main = pytest.importorskip("main")
main = pytest.importorskip("clipwright.pipeline.main")
def _transcript(n_segments=40):

View file

@ -10,10 +10,13 @@ main.py now announces each clip once its whole chain is done and names the file
to serve; app.py consumes the marker the way it already consumes PROXY_BYTES.
"""
import io
from pathlib import Path
import pytest
app = pytest.importorskip("app")
app = pytest.importorskip("clipwright.api.app")
MAIN_PY = Path(__file__).resolve().parents[1] / "clipwright" / "pipeline" / "main.py"
def _feed(job_id, *lines):
@ -69,7 +72,7 @@ class TestMainAnnouncesTheDeliveredFile:
Announcing the pre-caption path would put the poller back on a file the
pipeline is about to supersede, which is the bug this fixes.
"""
main_src = open("main.py", encoding="utf-8").read()
main_src = MAIN_PY.read_text(encoding="utf-8")
caption_at = main_src.index("captioned = auto_caption_clip(")
# The free plan's served file is a wm_ copy of the captioned final
# (mark_delivery), so the marker must also come after that step.

View file

@ -1,7 +1,7 @@
"""The strongest clip renders first, so it is the first one the user sees."""
import pytest
main = pytest.importorskip("main")
main = pytest.importorskip("clipwright.pipeline.main")
def test_best_score_first():

View file

@ -3,7 +3,7 @@ import re
import pytest
from clip_selection import (
from clipwright.pipeline.clip_selection import (
build_transcript_windows,
clip_count_targets,
dedupe_overlapping,
@ -157,7 +157,7 @@ class TestClipCountTargets:
class TestDetailPromptCarriesTheCount:
def test_template_formats_with_the_targets(self):
gw = pytest.importorskip("gemini_worker")
gw = pytest.importorskip("clipwright.pipeline.gemini_worker")
low, high = clip_count_targets(5)
prompt = gw.DETAIL_PROMPT_TEMPLATE.format(
video_duration=300, language="es", min_clips=low, max_clips=high,

View file

@ -13,7 +13,7 @@ import time
import httpx
import pytest
app_module = pytest.importorskip("app")
app_module = pytest.importorskip("clipwright.api.app")
@pytest.fixture

View file

@ -7,7 +7,7 @@ bytes) -> per-GB paid proxy (720p cost cap) -> conservative fallback. The
"""
import pytest
main = pytest.importorskip("main")
main = pytest.importorskip("clipwright.pipeline.main")
plan = main.plan_download_attempts

View file

@ -1,6 +1,6 @@
import pytest
from edit_builder import EFFECT_LIMITS, build_filter_string, normalize_edits
from clipwright.media.edit_builder import EFFECT_LIMITS, build_filter_string, normalize_edits
def _edit(type_, start, end, strength=0.0):

View file

@ -2,8 +2,8 @@ import subprocess
import pytest
import ffmpeg_utils
from ffmpeg_utils import (
from clipwright.media import ffmpeg_utils
from clipwright.media.ffmpeg_utils import (
AI_DISCLOSURE,
DELIVERY,
METADATA_SCRUB,

View file

@ -6,8 +6,8 @@ already being ~300 bytes, and the derived temp name pushed it further.
"""
import pytest
main = pytest.importorskip("main") # cv2 etc., absent in minimal CI
hooks = pytest.importorskip("hooks")
main = pytest.importorskip("clipwright.pipeline.main") # cv2 etc., absent in minimal CI
hooks = pytest.importorskip("clipwright.media.hooks")
# ext4/APFS cap a single name at 255 bytes.
FS_LIMIT = 255

View file

@ -2,7 +2,7 @@ import cv2
import numpy as np
import pytest
import frame_sampler
from clipwright.media import frame_sampler
N_FRAMES = 60

View file

@ -10,7 +10,7 @@ import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
import free_tools as ft
from clipwright.api import free_tools as ft
class TestExtractVideoId:

View file

@ -1,7 +1,7 @@
"""A policy block on a batch of windows must bisect, not kill the job."""
import pytest
main = pytest.importorskip("main")
import gemini_worker
main = pytest.importorskip("clipwright.pipeline.main")
from clipwright.pipeline import gemini_worker
def _windows(n):

View file

@ -9,7 +9,7 @@ import pytest
# main pulls in cv2/torch/mediapipe at import time; the minimal CI env lacks
# them, so skip there. Runs fully in the container/local where deps exist.
main = pytest.importorskip("main")
main = pytest.importorskip("clipwright.pipeline.main")
class _FakeResponse:
@ -112,7 +112,7 @@ def test_policy_block_fails_fast_without_retrying():
_Models.calls += 1
return _BlockedResponse()
import gemini_worker
from clipwright.pipeline import gemini_worker
with pytest.raises(gemini_worker.GeminiBlockedError) as exc:
main._run_gemini_stage(_client(_Models()), "m", "prompt", object)
assert _Models.calls == 1
@ -120,7 +120,7 @@ def test_policy_block_fails_fast_without_retrying():
def test_blocked_finish_reason_also_raises():
import gemini_worker
from clipwright.pipeline import gemini_worker
class _Cand:
class _FR:
@ -137,7 +137,7 @@ def test_blocked_finish_reason_also_raises():
def test_clean_response_is_not_flagged_as_blocked():
import gemini_worker
from clipwright.pipeline import gemini_worker
class _Resp:
prompt_feedback = None

View file

@ -12,7 +12,7 @@ import io
import httpx
import pytest
import gemini_worker
from clipwright.pipeline import gemini_worker
def _prepared_headers(file_arg, mime_type=None):
@ -77,7 +77,12 @@ def test_every_whole_file_upload_goes_through_the_helper():
import re
root = pathlib.Path(__file__).resolve().parent.parent
offenders = []
for name in ("main.py", "editor.py", "screencast_layout.py", "thumbnail.py"):
for name in (
"clipwright/pipeline/main.py",
"clipwright/media/editor.py",
"clipwright/layouts/screencast_layout.py",
"clipwright/media/thumbnail.py",
):
src = (root / name).read_text()
if re.search(r"\.files\.upload\(", src):
offenders.append(name)

View file

@ -9,7 +9,7 @@ import os
import pytest
import clip_selection
from clipwright.pipeline import clip_selection
@pytest.fixture(autouse=True)
@ -49,6 +49,7 @@ def _templates():
"""The prompt template constants, read without importing gemini_worker
(which pulls google-genai — absent in the thin CI env)."""
mod = ast.parse(open(os.path.join(os.path.dirname(__file__), "..",
"clipwright", "pipeline",
"gemini_worker.py")).read())
return {
node.targets[0].id: node.value.value

View file

@ -7,8 +7,8 @@ detail pass only ever reads the transcript.
"""
import pytest
import gemini_worker
import hook_grounding as hg
from clipwright.pipeline import gemini_worker
from clipwright.pipeline import hook_grounding as hg
SCREEN = [{"start": 0, "end": 30, "layout": "screencast"}]

View file

@ -10,7 +10,7 @@ import time
import pytest
app_module = pytest.importorskip("app")
app_module = pytest.importorskip("clipwright.api.app")
_strip_burned_captions = app_module._strip_burned_captions
_strip_burned_hook = app_module._strip_burned_hook

View file

@ -4,7 +4,7 @@ import os
from PIL import Image, ImageDraw, ImageFont
from hooks import (
from clipwright.media.hooks import (
HOOK_STYLES,
_break_long_word,
_emoji_scale,
@ -135,7 +135,7 @@ class TestCreateHookImage:
def test_pill_hook_image_stacks_one_box_per_line(tmp_path):
"""Two lines of text -> two rows of box pixels with a boxless column
beside the shorter one (it is its own pill, not one shared card)."""
from hooks import create_hook_image
from clipwright.media.hooks import create_hook_image
from PIL import Image
out = tmp_path / "pill.png"
path, w, h = create_hook_image("una frase bastante larga para partirse en dos lineas",

View file

@ -1,18 +1,30 @@
import sys
import types
import layout_picker
from layout_picker import _module_flags, apply, pick
from clipwright import layouts
from clipwright.layouts import layout_picker
from clipwright.layouts.layout_picker import _module_flags, apply, pick
# Decision labels are bare layout names; the modules they switch on live in the
# ``clipwright.layouts`` package and are imported lazily by apply().
_FAKE_LAYOUT_MODULES = {
"split_layout": "clipwright.layouts.split_layout",
"screencast_layout": "clipwright.layouts.screencast_layout",
"active_speaker": "clipwright.layouts.active_speaker",
}
def fake_modules(monkeypatch, **initial):
"""Install stand-in layout modules so apply() can be tested without them."""
made = {}
for name in ("split_layout", "screencast_layout", "active_speaker"):
module = types.ModuleType(name)
module.ENABLED = initial.get(name, False)
monkeypatch.setitem(sys.modules, name, module)
made[name] = module
for label, dotted in _FAKE_LAYOUT_MODULES.items():
module = types.ModuleType(dotted)
module.ENABLED = initial.get(label, False)
monkeypatch.setitem(sys.modules, dotted, module)
# apply() does ``from clipwright.layouts import <label>``; make that
# attribute lookup resolve to the stand-in too.
monkeypatch.setattr(layouts, label, module, raising=False)
made[dotted] = module
return made
@ -41,8 +53,8 @@ class TestApply:
mods = fake_modules(monkeypatch)
touched = apply("screencast")
assert touched == ["screencast_layout"]
assert mods["screencast_layout"].ENABLED is True
assert mods["split_layout"].ENABLED is False
assert mods["clipwright.layouts.screencast_layout"].ENABLED is True
assert mods["clipwright.layouts.split_layout"].ENABLED is False
def test_apply_none_touches_nothing(self, monkeypatch):
mods = fake_modules(monkeypatch)
@ -54,7 +66,7 @@ class TestApply:
# says "none". The picker only ever adds.
mods = fake_modules(monkeypatch, split_layout=True)
apply("none")
assert mods["split_layout"].ENABLED is True
assert mods["clipwright.layouts.split_layout"].ENABLED is True
def test_already_enabled_modules_are_not_reported_as_touched(self, monkeypatch):
fake_modules(monkeypatch, screencast_layout=True)
@ -63,8 +75,8 @@ class TestApply:
def test_split_enables_both_modules(self, monkeypatch):
mods = fake_modules(monkeypatch)
assert set(apply("split")) == {"split_layout", "active_speaker"}
assert mods["split_layout"].ENABLED is True
assert mods["active_speaker"].ENABLED is True
assert mods["clipwright.layouts.split_layout"].ENABLED is True
assert mods["clipwright.layouts.active_speaker"].ENABLED is True
class TestPick:
@ -134,7 +146,7 @@ class TestShadowMode:
monkeypatch.setattr(layout_picker, "SHADOW", False)
monkeypatch.setattr(layout_picker, "pick", lambda *a, **k: "screencast")
layout_picker.pick_and_apply("v.mp4", 60)
assert mods["screencast_layout"].ENABLED is True
assert mods["clipwright.layouts.screencast_layout"].ENABLED is True
def test_shadow_logs_one_greppable_line(self, monkeypatch, capsys):
fake_modules(monkeypatch)

View file

@ -7,8 +7,8 @@ import os
import pytest
import layout_ranges
import subtitles
from clipwright.layouts import layout_ranges
from clipwright.media import subtitles
def _transcript(words):
@ -78,7 +78,7 @@ class TestSeamCaptions:
class TestCaptionerReadsSidecar:
def test_auto_caption_uses_sidecar_when_not_told(self, tmp_path, monkeypatch):
main = pytest.importorskip("main")
main = pytest.importorskip("clipwright.pipeline.main")
clip = str(tmp_path / "x.mp4")
open(clip, "wb").close()
layout_ranges.write(clip, [(0, 3, "SPLIT")])
@ -110,7 +110,7 @@ class TestRemapAcrossCut:
def test_fast_recut_carries_the_sidecar(self, tmp_path, monkeypatch):
import shutil
import recut
from clipwright.media import recut
src = tmp_path / "canon.mp4"
src.write_bytes(b"x")
layout_ranges.write(str(src), [(0, 4, "SPLIT"), (4, 8, "TRACK")])
@ -127,7 +127,7 @@ class TestRemapAcrossCut:
class TestLayoutEnvNone:
def test_none_switches_the_picker_off_for_the_job(self):
app_module = pytest.importorskip("app")
app_module = pytest.importorskip("clipwright.api.app")
assert app_module.layout_env(["none"]) == {"AUTO_LAYOUT": "0"}
assert app_module.layout_env(["auto"]) == {"AUTO_LAYOUT": "1"}
assert app_module.layout_env(["split"])["SPLIT_LAYOUT"] == "1"

View file

@ -10,8 +10,8 @@ import json
import httpx
import pytest
import gemini_worker
import llm_backend
from clipwright.pipeline import gemini_worker
from clipwright.pipeline import llm_backend
@pytest.fixture
@ -123,7 +123,7 @@ def test_server_errors_surface_with_status_and_url(local, monkeypatch):
# --- main.py routing (needs the heavy deps; skipped on minimal CI) ------------
def test_stage_routes_to_local_backend_and_retries_transient(local, monkeypatch):
main = pytest.importorskip("main")
main = pytest.importorskip("clipwright.pipeline.main")
monkeypatch.setattr(main.time, "sleep", lambda *_: None)
calls = {"n": 0}
@ -141,7 +141,7 @@ def test_stage_routes_to_local_backend_and_retries_transient(local, monkeypatch)
def test_score_batch_shrinks_for_local_models(local, monkeypatch):
main = pytest.importorskip("main")
main = pytest.importorskip("clipwright.pipeline.main")
monkeypatch.delenv("LLM_SCORE_BATCH", raising=False)
assert main.score_batch_size() == 3
monkeypatch.setenv("LLM_SCORE_BATCH", "5")

View file

@ -12,13 +12,13 @@ same directory are still public to whoever has the job id.
"""
import pytest
media_auth = pytest.importorskip("media_auth")
restoring_static = pytest.importorskip("restoring_static")
media_auth = pytest.importorskip("clipwright.api.media_auth")
restoring_static = pytest.importorskip("clipwright.api.restoring_static")
class TestTheGuardIsWiredIn:
def test_the_videos_mount_carries_the_allowlist(self):
app = pytest.importorskip("app")
app = pytest.importorskip("clipwright.api.app")
mount = next(r for r in app.app.routes
if getattr(r, "name", None) == "videos")
# app._media_guard wraps the allowlist (and adds the free-plan rule

View file

@ -11,7 +11,7 @@ handed to the thread).
import ast
from pathlib import Path
APP = Path(__file__).resolve().parent.parent / "app.py"
APP = Path(__file__).resolve().parents[1] / "clipwright" / "api" / "app.py"
def _is_blocking_call(node: ast.Call) -> bool:

View file

@ -0,0 +1,94 @@
"""Architecture guard for the package-layout refactor.
The backend's 37 top-level modules moved under ``clipwright/``. These tests pin
the invariants that made the move worth doing:
1. the repo root holds no importable ``*.py`` module any more;
2. every package ``__init__`` is a pure docstring (no code, no re-exports);
3. nothing under ``clipwright/`` or ``tests/`` still imports a module by its
old bare top-level name.
Failure messages name the offending files.
"""
import ast
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[1]
PACKAGE = REPO_ROOT / "clipwright"
TESTS = REPO_ROOT / "tests"
# The old top-level module names. ``from clipwright.<group> import <name>`` is
# the supported spelling; importing any of these bare names is a regression.
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",
"postiz", "punch_in", "quality_probe", "recut", "reframe_v2",
"restoring_static", "scene_detection", "screencast_layout",
"security_utils", "split_layout", "subtitles", "thumbnail",
"transcribe_backends", "verify_aesthetic", "verify_custom_hook",
"verify_hooks", "watermarked", "yt_clients",
})
def _legacy_imports(path):
"""The legacy bare module names imported by the source at ``path``."""
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
found = set()
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
root = alias.name.split(".")[0]
if root in LEGACY_MODULES:
found.add(root)
elif isinstance(node, ast.ImportFrom):
# A relative import inside the package (``from . import x``) is
# not a bare top-level import; only absolute ones can be legacy.
if node.level:
continue
root = (node.module or "").split(".")[0]
if root in LEGACY_MODULES:
found.add(root)
return found
def test_repo_root_has_no_python_modules():
offenders = sorted(p.name for p in REPO_ROOT.glob("*.py"))
assert not offenders, (
"stray top-level modules at the repo root (move them under clipwright/): "
+ ", ".join(offenders)
)
def test_package_inits_are_docstring_only():
offenders = []
for init in sorted(PACKAGE.rglob("__init__.py")):
tree = ast.parse(init.read_text(encoding="utf-8"), filename=str(init))
for node in tree.body:
is_docstring = (
isinstance(node, ast.Expr)
and isinstance(node.value, ast.Constant)
and isinstance(node.value.value, str)
)
if not is_docstring:
offenders.append(f"{init.relative_to(REPO_ROOT)}:{node.lineno}")
assert not offenders, (
"package __init__ files must contain only a docstring: "
+ ", ".join(offenders)
)
def test_no_legacy_bare_module_imports():
offenders = {}
sources = sorted(PACKAGE.rglob("*.py")) + sorted(TESTS.glob("*.py"))
for path in sources:
found = _legacy_imports(path)
if found:
offenders[str(path.relative_to(REPO_ROOT))] = sorted(found)
assert not offenders, (
"legacy bare module imports (use clipwright.<group> instead): "
+ ", ".join(
f"{name} -> {mods}" for name, mods in sorted(offenders.items())
)
)

View file

@ -1,5 +1,5 @@
import panel_layout
from panel_layout import (
from clipwright.layouts import panel_layout
from clipwright.layouts.panel_layout import (
analyze_scene,
panel_filtergraph,
panel_geometry,
@ -192,7 +192,7 @@ class TestNeighbourClamp:
assert abs((w / h) - (tw / th)) < 0.05
def test_gaps_measure_the_closest_neighbour(self):
from panel_layout import neighbour_gaps
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]

View file

@ -20,7 +20,7 @@ import os
import pytest
app = pytest.importorskip("app")
app = pytest.importorskip("clipwright.api.app")
def _clip(title):

View file

@ -12,13 +12,13 @@ from datetime import datetime, timedelta, timezone
import httpx
import pytest
import postiz
from clipwright.integrations import postiz
POSTIZ_HEADERS = {"X-Postiz-Url": "https://postiz.example", "X-Postiz-Key": "k"}
def _app():
return pytest.importorskip("app")
return pytest.importorskip("clipwright.api.app")
# --- postiz.py -------------------------------------------------------------

View file

@ -15,7 +15,7 @@ import os
import httpx
import pytest
app_module = pytest.importorskip("app")
app_module = pytest.importorskip("clipwright.api.app")
TRANSCRIPT = {
"text": "hello world again",

View file

@ -1,5 +1,5 @@
import punch_in
from punch_in import MAX_ZOOM, crop_boxes, sendcmd_lines, zoom_curve
from clipwright.layouts import punch_in
from clipwright.layouts.punch_in import MAX_ZOOM, crop_boxes, sendcmd_lines, zoom_curve
class TestZoomCurve:
@ -87,19 +87,19 @@ class TestSendcmdLines:
class TestEmphasisTimes:
def test_silent_or_unreadable_audio_yields_no_beats(self, monkeypatch):
import active_speaker
from clipwright.layouts import active_speaker
monkeypatch.setattr(active_speaker, "audio_envelope",
lambda *a, **k: [])
assert punch_in.emphasis_times("x.mp4", 30.0) == []
def test_flat_audio_yields_no_beats(self, monkeypatch):
import active_speaker
from clipwright.layouts import active_speaker
monkeypatch.setattr(active_speaker, "audio_envelope",
lambda *a, **k: [0.5] * 50)
assert punch_in.emphasis_times("x.mp4", 10.0) == []
def test_beats_respect_the_minimum_gap(self, monkeypatch):
import active_speaker
from clipwright.layouts import active_speaker
envelope = [1.0 if i % 2 == 0 else 0.0 for i in range(100)]
monkeypatch.setattr(active_speaker, "audio_envelope",
lambda *a, **k: envelope)

View file

@ -9,7 +9,7 @@ import os
import pytest
import recut
from clipwright.media import recut
def _seg(start, end):

View file

@ -13,8 +13,8 @@ import os
import httpx
import pytest
app_module = pytest.importorskip("app")
import recut # noqa: E402
app_module = pytest.importorskip("clipwright.api.app")
from clipwright.media import recut # noqa: E402
JOB_ID = "reframe-endpoint-test-job"
@ -176,7 +176,7 @@ class TestApplyCropOverrides:
@pytest.fixture(autouse=True)
def _mod(self):
self.rf = pytest.importorskip("reframe_v2")
self.rf = pytest.importorskip("clipwright.layouts.reframe_v2")
def test_single_crop_centres_the_window(self):
xs = [None] * 100

View file

@ -1,4 +1,4 @@
from reframe_v2 import (
from clipwright.layouts.reframe_v2 import (
DELIVERY_MIN_WIDTH,
concat_list_content,
dedupe_sendcmd_lines,
@ -93,7 +93,7 @@ class TestGeneralLayout:
"""GENERAL used to leave the content at 32% of the frame, floating in blur."""
def test_content_is_scaled_by_height_not_width(self):
from reframe_v2 import GENERAL_CONTENT_HEIGHT_RATIO
from clipwright.layouts.reframe_v2 import GENERAL_CONTENT_HEIGHT_RATIO
graph = general_filtergraph(1080, 1920)
expected = int(1920 * GENERAL_CONTENT_HEIGHT_RATIO)
expected += expected % 2
@ -116,14 +116,14 @@ class TestGeneralLayout:
def test_content_fills_more_than_the_old_full_width_fit(self):
# A 16:9 source fitted to full width was 9/16 of it — 0.5625 * 1080
# = 608px, i.e. 32% of a 1920 frame. The new layout must beat that.
from reframe_v2 import GENERAL_CONTENT_HEIGHT_RATIO
from clipwright.layouts.reframe_v2 import GENERAL_CONTENT_HEIGHT_RATIO
old_ratio = (1080 * 9 / 16) / 1920
assert GENERAL_CONTENT_HEIGHT_RATIO > old_ratio
def test_keeps_most_of_the_source_width(self):
# GENERAL is for groups and landscapes: cropping the sides too hard
# cuts people out of frame, which is the whole thing it exists to avoid.
from reframe_v2 import GENERAL_CONTENT_HEIGHT_RATIO
from clipwright.layouts.reframe_v2 import GENERAL_CONTENT_HEIGHT_RATIO
scaled_w = 1920 * GENERAL_CONTENT_HEIGHT_RATIO * (16 / 9)
assert 1080 / scaled_w > 0.70, "keeps less than 70% of the source width"
@ -160,7 +160,7 @@ class TestVerticalSource:
def test_landscape_keeps_the_presence_ratio(self):
# The floor must not disturb the case the ratio was tuned for: a 16:9
# source fills the width at 608, below the 806 the ratio asks for.
from reframe_v2 import GENERAL_CONTENT_HEIGHT_RATIO
from clipwright.layouts.reframe_v2 import GENERAL_CONTENT_HEIGHT_RATIO
expected = int(1920 * GENERAL_CONTENT_HEIGHT_RATIO)
expected += expected % 2
graph = general_filtergraph(1080, 1920, orig_w=1920, orig_h=1080)

View file

@ -14,8 +14,8 @@ import os
import httpx
import pytest
app_module = pytest.importorskip("app")
import recut # noqa: E402
app_module = pytest.importorskip("clipwright.api.app")
from clipwright.media import recut # noqa: E402
JOB_ID = "recut-endpoint-test-job"

View file

@ -10,7 +10,7 @@ import os
from starlette.applications import Starlette
from starlette.testclient import TestClient
from restoring_static import RestoringStaticFiles
from clipwright.api.restoring_static import RestoringStaticFiles
JOB = "cff3ad6c-c1e6-48e8-9a75-be74f39779c5"

Some files were not shown because too many files have changed in this diff Show more