chore: simplify repo — drop agent skills, n8n examples, ops/hallmark and demo assets #2
115 changed files with 557 additions and 305 deletions
|
|
@ -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.
|
# close-ups of a real person; the clock runs from the last download.
|
||||||
# THUMBNAIL_RETENTION_SECONDS=86400
|
# 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
|
# Defaults: auth 30/600, process 60/3600. Set RATE_LIMIT_ENABLED=0
|
||||||
# to turn the whole thing off (self-host behind your own firewall).
|
# to turn the whole thing off (self-host behind your own firewall).
|
||||||
# RATE_LIMIT_ENABLED=1
|
# RATE_LIMIT_ENABLED=1
|
||||||
|
|
|
||||||
15
.github/workflows/ci.yml
vendored
15
.github/workflows/ci.yml
vendored
|
|
@ -16,17 +16,12 @@ jobs:
|
||||||
container: nikolaik/python-nodejs:python3.11-nodejs20
|
container: nikolaik/python-nodejs:python3.11-nodejs20
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
# Everything the collected tests import at module level, WITHOUT the
|
# Shared thin test environment (see requirements-test.txt): everything the
|
||||||
# heavy ML stack (torch/ultralytics/mediapipe/faster-whisper) — the
|
# collected tests import at module level, WITHOUT the heavy ML stack
|
||||||
# pipeline modules import those lazily behind their feature gates, and
|
# (torch/ultralytics/mediapipe/faster-whisper), which the pipeline modules
|
||||||
# the tests exercise the gated-off paths. numpy+opencv cover the layout
|
# import lazily behind their feature gates.
|
||||||
# modules, fastapi/python-multipart cover importing app.py for the MCP
|
|
||||||
# endpoint tests, google-genai covers gemini_worker.
|
|
||||||
- name: Install test dependencies
|
- name: Install test dependencies
|
||||||
run: >
|
run: pip install -r requirements-test.txt
|
||||||
pip install pytest pillow httpx pydantic numpy
|
|
||||||
opencv-python-headless python-dotenv google-genai fastapi
|
|
||||||
python-multipart
|
|
||||||
- name: Run tests
|
- name: Run tests
|
||||||
run: pytest tests/ -v
|
run: pytest tests/ -v
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -31,6 +31,11 @@ FROM python:3.11-slim
|
||||||
|
|
||||||
WORKDIR /app
|
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).
|
# Install FFmpeg, OpenCV deps, Node.js + npm + git (for yt-dlp JS + bgutil build).
|
||||||
# fontconfig + fonts-liberation back the subtitle font choices: without real
|
# fontconfig + fonts-liberation back the subtitle font choices: without real
|
||||||
# fonts libass falls back to DejaVu for every UI option (issue #57).
|
# 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 \
|
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 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"]
|
||||||
|
|
|
||||||
21
README.md
21
README.md
|
|
@ -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`.
|
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
|
## Tech stack
|
||||||
|
|
||||||
Python 3.11 · FastAPI · google-genai · faster-whisper · ultralytics (YOLOv8) · MediaPipe · FFmpeg · React 18 · Vite · Tailwind · Docker Compose.
|
Python 3.11 · FastAPI · google-genai · faster-whisper · ultralytics (YOLOv8) · MediaPipe · FFmpeg · React 18 · Vite · Tailwind · Docker Compose.
|
||||||
|
|
|
||||||
1
clipwright/__init__.py
Normal file
1
clipwright/__init__.py
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
"""Clipwright backend."""
|
||||||
1
clipwright/api/__init__.py
Normal file
1
clipwright/api/__init__.py
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
"""Clipwright backend."""
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import os
|
import os
|
||||||
import llm_backend
|
from clipwright.pipeline import llm_backend
|
||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
import uuid
|
import uuid
|
||||||
|
|
@ -26,11 +26,12 @@ from fastapi.responses import FileResponse, JSONResponse
|
||||||
from starlette.background import BackgroundTask
|
from starlette.background import BackgroundTask
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
import httpx
|
import httpx
|
||||||
import recut
|
from clipwright.media import recut
|
||||||
import layout_ranges
|
from clipwright.layouts import layout_ranges
|
||||||
import watermarked
|
from clipwright.media import watermarked
|
||||||
import media_auth
|
from clipwright.api import media_auth
|
||||||
import postiz
|
from clipwright.integrations import postiz
|
||||||
|
from clipwright.core.paths import REPO_ROOT
|
||||||
|
|
||||||
load_dotenv()
|
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
|
# 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).
|
# failures were exactly this, one user retrying the same 24s video).
|
||||||
MIN_SOURCE_SECONDS = int(os.environ.get("MIN_SOURCE_SECONDS", "45"))
|
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
|
# Server credentials the pipeline subprocesses (main.py, quality_probe.py) never
|
||||||
# read: main.py and everything it imports use GEMINI_API_KEY / LLM_* / the
|
# 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)
|
env = dict(os.environ if base is None else base)
|
||||||
for name in CHILD_ENV_DENYLIST:
|
for name in CHILD_ENV_DENYLIST:
|
||||||
env.pop(name, None)
|
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
|
return env
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -466,7 +471,7 @@ def _reapply_captions(job_id, clip_index, video_path):
|
||||||
if not transcript or clip_index >= len(clips):
|
if not transcript or clip_index >= len(clips):
|
||||||
return None
|
return None
|
||||||
clip = clips[clip_index]
|
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
|
# A recut clip is a concatenation of source segments, so the flat
|
||||||
# start..end window is wrong for it — caption against the clip-relative
|
# start..end window is wrong for it — caption against the clip-relative
|
||||||
# remapped transcript instead (same trick /api/subtitle uses).
|
# 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"}
|
headers = {"Content-Type": "application/json", "User-Agent": "Clipwright-Webhook/1.0"}
|
||||||
if secret:
|
if secret:
|
||||||
headers["X-Clipwright-Signature"] = _sign_webhook(body, 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()
|
loop = asyncio.get_event_loop()
|
||||||
for attempt, delay in enumerate(WEBHOOK_RETRY_DELAYS, 1):
|
for attempt, delay in enumerate(WEBHOOK_RETRY_DELAYS, 1):
|
||||||
if delay:
|
if delay:
|
||||||
|
|
@ -1477,7 +1482,7 @@ app = FastAPI(lifespan=lifespan)
|
||||||
|
|
||||||
# Free public tools behind the /tools SEO pages: YouTube transcript (existing
|
# Free public tools behind the /tools SEO pages: YouTube transcript (existing
|
||||||
# captions only, never the GPU) and the title/description/tag generator.
|
# 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)
|
app.include_router(_free_tools.router)
|
||||||
|
|
||||||
# Enable CORS for frontend. Self-host allows any origin (permissive wildcard).
|
# 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
|
# Mount static files for serving videos. ``guard`` refuses non-deliverables
|
||||||
# (``*_metadata.json``, ``.owner``, ``.resume.json``) so they are never served.
|
# (``*_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(
|
app.mount("/videos", RestoringStaticFiles(
|
||||||
directory=OUTPUT_DIR,
|
directory=OUTPUT_DIR,
|
||||||
guard=_media_guard), name="videos")
|
guard=_media_guard), name="videos")
|
||||||
|
|
@ -1761,7 +1766,7 @@ async def _probe_youtube_quality(url: str) -> dict:
|
||||||
def _run():
|
def _run():
|
||||||
try:
|
try:
|
||||||
proc = subprocess.run(
|
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(),
|
capture_output=True, timeout=75, env=child_env(),
|
||||||
)
|
)
|
||||||
return json.loads(proc.stdout.decode(errors="replace").strip() or "{}")
|
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
|
search / playlist / channel page (yt_clients). The download and the
|
||||||
metering probe check the same things again; this is the one in front of
|
metering probe check the same things again; this is the one in front of
|
||||||
the quality probe, which used to have none."""
|
the quality probe, which used to have none."""
|
||||||
from security_utils import assert_public_url, UnsafeURLError
|
from clipwright.core.security_utils import assert_public_url, UnsafeURLError
|
||||||
from yt_clients import youtube_non_video_reason
|
from clipwright.integrations.yt_clients import youtube_non_video_reason
|
||||||
try:
|
try:
|
||||||
await asyncio.get_event_loop().run_in_executor(None, assert_public_url, url)
|
await asyncio.get_event_loop().run_in_executor(None, assert_public_url, url)
|
||||||
except UnsafeURLError as e:
|
except UnsafeURLError as e:
|
||||||
|
|
@ -2103,7 +2108,7 @@ async def process_endpoint(
|
||||||
# Completion callback: reject unsafe targets NOW (clear 400) — delivery
|
# Completion callback: reject unsafe targets NOW (clear 400) — delivery
|
||||||
# re-validates anyway, but failing at submit is the debuggable behavior.
|
# re-validates anyway, but failing at submit is the debuggable behavior.
|
||||||
if webhook_url:
|
if webhook_url:
|
||||||
from security_utils import assert_public_url, UnsafeURLError
|
from clipwright.core.security_utils import assert_public_url, UnsafeURLError
|
||||||
try:
|
try:
|
||||||
await asyncio.get_event_loop().run_in_executor(
|
await asyncio.get_event_loop().run_in_executor(
|
||||||
None, assert_public_url, webhook_url)
|
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
|
# outside Docker is whatever interpreter happens to be first — not the venv
|
||||||
# running this server. Every job then dies on `import cv2`. The quality
|
# running this server. Every job then dies on `import cv2`. The quality
|
||||||
# probe above already gets this right.
|
# 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()
|
env = child_env()
|
||||||
if api_key:
|
if api_key:
|
||||||
env["GEMINI_API_KEY"] = api_key # Override with key from request
|
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.
|
# byte-for-byte; the dashboard sends an explicit value either way.
|
||||||
if str(auto_hook).lower() in ("1", "true", "yes"):
|
if str(auto_hook).lower() in ("1", "true", "yes"):
|
||||||
env["AUTO_HOOK"] = "1"
|
env["AUTO_HOOK"] = "1"
|
||||||
from hooks import HOOK_STYLES
|
from clipwright.media.hooks import HOOK_STYLES
|
||||||
if auto_hook_style in HOOK_STYLES:
|
if auto_hook_style in HOOK_STYLES:
|
||||||
env["AUTO_HOOK_STYLE"] = auto_hook_style
|
env["AUTO_HOOK_STYLE"] = auto_hook_style
|
||||||
print(f"[auto-hook] job={job_id} style={env.get('AUTO_HOOK_STYLE', 'classic')}")
|
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.
|
# Files live on local disk in this self-host fork, so there is nothing to restore.
|
||||||
|
|
||||||
|
|
||||||
from editor import VideoEditor
|
from clipwright.media.editor import VideoEditor
|
||||||
from subtitles import generate_srt, generate_ass, burn_subtitles, CAPTION_PRESETS
|
from clipwright.media.subtitles import generate_srt, generate_ass, burn_subtitles, CAPTION_PRESETS
|
||||||
from hooks import add_hook_to_video
|
from clipwright.media.hooks import add_hook_to_video
|
||||||
from thumbnail import (analyze_video_for_titles, refine_titles, generate_thumbnail,
|
from clipwright.media.thumbnail import (analyze_video_for_titles, refine_titles, generate_thumbnail,
|
||||||
generate_youtube_description, extract_face_frames)
|
generate_youtube_description, extract_face_frames)
|
||||||
|
|
||||||
class EditRequest(BaseModel):
|
class EditRequest(BaseModel):
|
||||||
|
|
@ -3195,7 +3200,7 @@ async def get_clip_scenes(job_id: str, clip_index: int, request: Request):
|
||||||
|
|
||||||
def build():
|
def build():
|
||||||
import cv2
|
import cv2
|
||||||
import main as m
|
from clipwright.pipeline import main as m
|
||||||
|
|
||||||
# Stable for the files the browser fetches (no accumulation), unique
|
# Stable for the files the browser fetches (no accumulation), unique
|
||||||
# for the temp cut (no collision between overlapping requests).
|
# for the temp cut (no collision between overlapping requests).
|
||||||
|
|
@ -4413,19 +4418,19 @@ async def thumbnail_upload(
|
||||||
vpath = video_path
|
vpath = video_path
|
||||||
# Download YouTube video if URL was provided
|
# Download YouTube video if URL was provided
|
||||||
if not vpath and url:
|
if not vpath and url:
|
||||||
from main import download_youtube_video
|
from clipwright.pipeline.main import download_youtube_video
|
||||||
loop = asyncio.get_event_loop()
|
loop = asyncio.get_event_loop()
|
||||||
vpath, _ = await loop.run_in_executor(None, download_youtube_video, url, UPLOAD_DIR)
|
vpath, _ = await loop.run_in_executor(None, download_youtube_video, url, UPLOAD_DIR)
|
||||||
thumbnail_sessions[session_id]["video_path"] = vpath
|
thumbnail_sessions[session_id]["video_path"] = vpath
|
||||||
|
|
||||||
from main import transcribe_video
|
from clipwright.pipeline.main import transcribe_video
|
||||||
loop = asyncio.get_event_loop()
|
loop = asyncio.get_event_loop()
|
||||||
try:
|
try:
|
||||||
transcript = await loop.run_in_executor(None, transcribe_video, vpath)
|
transcript = await loop.run_in_executor(None, transcribe_video, vpath)
|
||||||
finally:
|
finally:
|
||||||
# See transcribe_backends.release_models: the API process is
|
# See transcribe_backends.release_models: the API process is
|
||||||
# long-lived and the GPU is shared with every running job.
|
# 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)
|
await loop.run_in_executor(None, transcribe_backends.release_models)
|
||||||
segments = transcript.get("segments", [])
|
segments = transcript.get("segments", [])
|
||||||
duration = segments[-1]["end"] if segments else 0
|
duration = segments[-1]["end"] if segments else 0
|
||||||
|
|
@ -4492,7 +4497,7 @@ async def thumbnail_analyze(
|
||||||
session_id = str(uuid.uuid4())
|
session_id = str(uuid.uuid4())
|
||||||
|
|
||||||
if url:
|
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(
|
video_path, _ = await asyncio.get_event_loop().run_in_executor(
|
||||||
None, download_youtube_video, url, UPLOAD_DIR)
|
None, download_youtube_video, url, UPLOAD_DIR)
|
||||||
else:
|
else:
|
||||||
1
clipwright/core/__init__.py
Normal file
1
clipwright/core/__init__.py
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
"""Clipwright backend."""
|
||||||
31
clipwright/core/paths.py
Normal file
31
clipwright/core/paths.py
Normal 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",
|
||||||
|
]
|
||||||
1
clipwright/integrations/__init__.py
Normal file
1
clipwright/integrations/__init__.py
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
"""Clipwright backend."""
|
||||||
1
clipwright/layouts/__init__.py
Normal file
1
clipwright/layouts/__init__.py
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
"""Clipwright backend."""
|
||||||
|
|
@ -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):
|
def verdicts_for_scene(video_path, start_f, end_f, fps, centres):
|
||||||
"""Per-window speaker verdicts for one scene, from its two face 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
|
start_s = start_f / fps
|
||||||
duration_s = (end_f - start_f) / fps
|
duration_s = (end_f - start_f) / fps
|
||||||
|
|
@ -20,7 +20,7 @@ them with margin.
|
||||||
"""
|
"""
|
||||||
import os
|
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
|
CORNER_MARGIN = 0.20 # a subject this far from an edge (as a fraction of the
|
||||||
# frame) still counts as anchored to it
|
# frame) still counts as anchored to it
|
||||||
|
|
@ -159,8 +159,8 @@ def detect(video_path, samples=10):
|
||||||
"""
|
"""
|
||||||
import cv2
|
import cv2
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import main as m
|
from clipwright.pipeline import main as m
|
||||||
import screencast_layout
|
from clipwright.layouts import screencast_layout
|
||||||
|
|
||||||
cap = cv2.VideoCapture(video_path)
|
cap = cv2.VideoCapture(video_path)
|
||||||
if not cap.isOpened():
|
if not cap.isOpened():
|
||||||
|
|
@ -82,9 +82,9 @@ def apply(decision):
|
||||||
stacking regardless of what the model thinks, and a model that says "none"
|
stacking regardless of what the model thinks, and a model that says "none"
|
||||||
must not quietly undo that.
|
must not quietly undo that.
|
||||||
"""
|
"""
|
||||||
import active_speaker
|
from clipwright.layouts import active_speaker
|
||||||
import screencast_layout
|
from clipwright.layouts import screencast_layout
|
||||||
import split_layout
|
from clipwright.layouts import split_layout
|
||||||
|
|
||||||
modules = {"split_layout": split_layout,
|
modules = {"split_layout": split_layout,
|
||||||
"screencast_layout": screencast_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.
|
# raises, and an unimportable SDK is just one more reason to fall back.
|
||||||
from google import genai
|
from google import genai
|
||||||
from google.genai import types as genai_types
|
from google.genai import types as genai_types
|
||||||
import gemini_worker
|
from clipwright.pipeline import gemini_worker
|
||||||
|
|
||||||
frames = sample_frames(video_path)
|
frames = sample_frames(video_path)
|
||||||
if not frames:
|
if not frames:
|
||||||
|
|
@ -24,7 +24,7 @@ import os
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
import split_layout
|
from clipwright.layouts import split_layout
|
||||||
|
|
||||||
ENABLED = os.environ.get("PANEL_LAYOUT", "0") == "1"
|
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
|
# Below the gate on purpose: main pulls torch/mediapipe, and the disabled
|
||||||
# path (the default, and what CI exercises) must not pay that import.
|
# path (the default, and what CI exercises) must not pay that import.
|
||||||
import cv2
|
import cv2
|
||||||
import main as m
|
from clipwright.pipeline import main as m
|
||||||
|
|
||||||
cap = cv2.VideoCapture(video_path)
|
cap = cv2.VideoCapture(video_path)
|
||||||
if not cap.isOpened():
|
if not cap.isOpened():
|
||||||
|
|
@ -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
|
A stand-in for the hook words until the transcript is wired through. Returns
|
||||||
[] for silent or unreadable audio, which simply means no punches.
|
[] 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,
|
envelope = active_speaker.audio_envelope(video_path, 0.0, duration,
|
||||||
window_s=window)
|
window_s=window)
|
||||||
|
|
@ -21,13 +21,13 @@ import os
|
||||||
import subprocess
|
import subprocess
|
||||||
import tempfile
|
import tempfile
|
||||||
|
|
||||||
import active_speaker
|
from clipwright.layouts import active_speaker
|
||||||
import camera_inset
|
from clipwright.layouts import camera_inset
|
||||||
import punch_in
|
from clipwright.layouts import punch_in
|
||||||
import screencast_layout
|
from clipwright.layouts import screencast_layout
|
||||||
import layout_ranges
|
from clipwright.layouts import layout_ranges
|
||||||
import split_layout
|
from clipwright.layouts import split_layout
|
||||||
from ffmpeg_utils import (video_encode_args, blurred_backdrop, escape_filter_value,
|
from clipwright.media.ffmpeg_utils import (video_encode_args, blurred_backdrop, escape_filter_value,
|
||||||
QUALITY_FAST, METADATA_SCRUB)
|
QUALITY_FAST, METADATA_SCRUB)
|
||||||
|
|
||||||
ANALYSIS_MAX_WIDTH = 640
|
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
|
"""Replays v1's per-frame decision loop on a downscaled ffmpeg-decoded
|
||||||
stream. Returns xs: crop x per frame (None on GENERAL frames)."""
|
stream. Returns xs: crop x per frame (None on GENERAL frames)."""
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import main as m
|
from clipwright.pipeline import main as m
|
||||||
|
|
||||||
small_w = min(ANALYSIS_MAX_WIDTH, orig_w)
|
small_w = min(ANALYSIS_MAX_WIDTH, orig_w)
|
||||||
if small_w % 2:
|
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
|
segment's own encode, instead of main.apply_watermark re-encoding the
|
||||||
finished clip once more.
|
finished clip once more.
|
||||||
"""
|
"""
|
||||||
import main as m
|
from clipwright.pipeline import main as m
|
||||||
content_ranges = content_ranges or []
|
content_ranges = content_ranges or []
|
||||||
|
|
||||||
print(" 🚀 Reframe engine v2 (ffmpeg-native render)")
|
print(" 🚀 Reframe engine v2 (ffmpeg-native render)")
|
||||||
|
|
@ -123,7 +123,7 @@ def detect_faces_full_res(frame):
|
||||||
screencast candidates only.
|
screencast candidates only.
|
||||||
"""
|
"""
|
||||||
import cv2
|
import cv2
|
||||||
import main as m
|
from clipwright.pipeline import main as m
|
||||||
|
|
||||||
h, w, _ = frame.shape
|
h, w, _ = frame.shape
|
||||||
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
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 import genai
|
||||||
from google.genai import types as genai_types
|
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'
|
model_name = os.environ.get("GEMINI_MODEL") or 'gemini-3.1-flash-lite'
|
||||||
print("🔎 Checking for full-width on-screen content…")
|
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
|
# Below the gate on purpose: main pulls torch/mediapipe, and the disabled
|
||||||
# path (the default, and what CI exercises) must not pay that import.
|
# path (the default, and what CI exercises) must not pay that import.
|
||||||
import cv2
|
import cv2
|
||||||
import main as m
|
from clipwright.pipeline import main as m
|
||||||
|
|
||||||
cap = cv2.VideoCapture(video_path)
|
cap = cv2.VideoCapture(video_path)
|
||||||
if not cap.isOpened():
|
if not cap.isOpened():
|
||||||
|
|
@ -18,7 +18,7 @@ import os
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
import frame_sampler
|
from clipwright.media import frame_sampler
|
||||||
|
|
||||||
ENABLED = os.environ.get("SPLIT_LAYOUT", "0") == "1"
|
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.
|
touching the single-speaker material that is most of the corpus.
|
||||||
"""
|
"""
|
||||||
import cv2
|
import cv2
|
||||||
import main as m
|
from clipwright.pipeline import main as m
|
||||||
|
|
||||||
if not ENABLED:
|
if not ENABLED:
|
||||||
return {}
|
return {}
|
||||||
1
clipwright/media/__init__.py
Normal file
1
clipwright/media/__init__.py
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
"""Clipwright backend."""
|
||||||
|
|
@ -8,9 +8,9 @@ from google import genai
|
||||||
from google.genai import types
|
from google.genai import types
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
import gemini_worker
|
from clipwright.pipeline import gemini_worker
|
||||||
from edit_builder import build_filter_string
|
from clipwright.media.edit_builder import build_filter_string
|
||||||
from ffmpeg_utils import video_encode_args, QUALITY, METADATA_SCRUB
|
from clipwright.media.ffmpeg_utils import video_encode_args, QUALITY, METADATA_SCRUB
|
||||||
|
|
||||||
|
|
||||||
class EditDecision(BaseModel):
|
class EditDecision(BaseModel):
|
||||||
|
|
@ -6,7 +6,8 @@ import urllib.request
|
||||||
import uuid
|
import uuid
|
||||||
from PIL import Image, ImageDraw, ImageFont, ImageFilter
|
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):
|
def _truncate_bytes(text, max_bytes):
|
||||||
|
|
@ -21,7 +22,7 @@ def _truncate_bytes(text, max_bytes):
|
||||||
return encoded[:max_bytes].decode("utf-8", "ignore")
|
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_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")
|
FONT_PATH = os.path.join(FONT_DIR, "NotoSerif-Bold.ttf")
|
||||||
# Bundled (SIL OFL, see fonts/Montserrat-OFL.txt): the "pill" look's sans.
|
# Bundled (SIL OFL, see fonts/Montserrat-OFL.txt): the "pill" look's sans.
|
||||||
PILL_FONT_PATH = os.path.join(FONT_DIR, "Montserrat-ExtraBold.ttf")
|
PILL_FONT_PATH = os.path.join(FONT_DIR, "Montserrat-ExtraBold.ttf")
|
||||||
|
|
@ -24,7 +24,7 @@ import subprocess
|
||||||
import time
|
import time
|
||||||
import uuid
|
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)
|
video_encode_args)
|
||||||
|
|
||||||
# EDL limits. Deliberately generous — the editor is for humans fixing cuts,
|
# 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):
|
def snap_segments(segments, transcript, source_duration):
|
||||||
"""Snap each segment's bounds onto word boundaries (ground truth beats
|
"""Snap each segment's bounds onto word boundaries (ground truth beats
|
||||||
millisecond arithmetic — same rationale as the pipeline's snapping)."""
|
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)
|
words = transcript_words(transcript)
|
||||||
if not words:
|
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
|
# No reframe means no fresh layout sidecar; the captions would fall
|
||||||
# back to the bottom on a stacked clip. Carry the input's layout
|
# back to the bottom on a stacked clip. Carry the input's layout
|
||||||
# ranges through the cut instead (empty when the input has none).
|
# 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, [
|
layout_ranges.write(out_path, [
|
||||||
(r["start"], r["end"], r["layout"])
|
(r["start"], r["end"], r["layout"])
|
||||||
for r in layout_ranges.remap(layout_ranges.read(input_path), segments)])
|
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):
|
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)
|
return getattr(main, name)
|
||||||
|
|
@ -3,8 +3,9 @@ import re
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
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)
|
METADATA_SCRUB)
|
||||||
|
from clipwright.core.paths import FONTS_DIR
|
||||||
|
|
||||||
|
|
||||||
_STDIO_CONFIGURED = False
|
_STDIO_CONFIGURED = False
|
||||||
|
|
@ -119,7 +120,7 @@ def transcribe_audio(video_path):
|
||||||
Returns transcript in the same format as main.py for compatibility.
|
Returns transcript in the same format as main.py for compatibility.
|
||||||
"""
|
"""
|
||||||
# Lazy import: transcribe_backends imports helpers from this module.
|
# 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}")
|
_log(f"🎙️ Transcribing audio from: {video_path}")
|
||||||
transcript = transcribe_media(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)
|
# Let libass see the fonts bundled with the app (e.g. Anton for Impact)
|
||||||
# even when the system fontconfig has no cache for them.
|
# 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)
|
safe_fonts_dir = _escape_ffmpeg_filter_value(fonts_dir)
|
||||||
|
|
||||||
# The first option is named explicitly (filename=) rather than positional:
|
# The first option is named explicitly (filename=) rather than positional:
|
||||||
|
|
@ -9,6 +9,7 @@ from google import genai
|
||||||
from google.genai import types
|
from google.genai import types
|
||||||
from google.genai import errors as genai_errors
|
from google.genai import errors as genai_errors
|
||||||
from PIL import Image, ImageDraw, ImageFont, ImageFilter
|
from PIL import Image, ImageDraw, ImageFont, ImageFilter
|
||||||
|
from clipwright.core.paths import FONTS_DIR
|
||||||
|
|
||||||
# Text/analysis model (titles, concepts, description). Deliberately NOT tied to
|
# Text/analysis model (titles, concepts, description). Deliberately NOT tied to
|
||||||
# GEMINI_MODEL: the pipeline runs flash-lite for a closed-choice layout pick,
|
# 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_W, THUMB_H = 1280, 720
|
||||||
THUMB_MAX_BYTES = 2 * 1024 * 1024 # YouTube's upload limit
|
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")
|
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):
|
def _frame_parts(video_path, n=TITLE_FRAMES, width=TITLE_FRAME_WIDTH):
|
||||||
"""Evenly spaced frames as Gemini image parts (empty list on any failure)."""
|
"""Evenly spaced frames as Gemini image parts (empty list on any failure)."""
|
||||||
try:
|
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")
|
return [types.Part.from_bytes(data=b, mime_type="image/jpeg")
|
||||||
for b in sample_frames(video_path, n=n, width=width)]
|
for b in sample_frames(video_path, n=n, width=width)]
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|
@ -70,7 +71,7 @@ def analyze_video_for_titles(api_key, video_path, transcript=None):
|
||||||
"segments", "video_duration", "recommended" }
|
"segments", "video_duration", "recommended" }
|
||||||
"""
|
"""
|
||||||
if transcript is None:
|
if transcript is None:
|
||||||
from main import transcribe_video
|
from clipwright.pipeline.main import transcribe_video
|
||||||
print("🎬 [Thumbnail] Transcribing video...")
|
print("🎬 [Thumbnail] Transcribing video...")
|
||||||
transcript = transcribe_video(video_path)
|
transcript = transcribe_video(video_path)
|
||||||
else:
|
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]}].
|
thumbnails dir. Returns [{"url", "path", "time", "face": [x, y, w, h]}].
|
||||||
"""
|
"""
|
||||||
import cv2
|
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")
|
out_dir = os.path.join("output", "thumbnails", session_id, "frames")
|
||||||
os.makedirs(out_dir, exist_ok=True)
|
os.makedirs(out_dir, exist_ok=True)
|
||||||
1
clipwright/pipeline/__init__.py
Normal file
1
clipwright/pipeline/__init__.py
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
"""Clipwright backend."""
|
||||||
|
|
@ -10,7 +10,7 @@ from google import genai
|
||||||
from google.genai import types as genai_types
|
from google.genai import types as genai_types
|
||||||
from pydantic import BaseModel
|
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)
|
lookup_model_prices)
|
||||||
|
|
||||||
load_dotenv()
|
load_dotenv()
|
||||||
|
|
@ -42,7 +42,7 @@ def screen_video() -> bool:
|
||||||
(verified on a product update video: every GENERAL scene was a stats
|
(verified on a product update video: every GENERAL scene was a stats
|
||||||
card), even when the width gate did not upgrade it to SCREENCAST."""
|
card), even when the width gate did not upgrade it to SCREENCAST."""
|
||||||
try:
|
try:
|
||||||
import screencast_layout
|
from clipwright.layouts import screencast_layout
|
||||||
return bool(getattr(screencast_layout, "ENABLED", False))
|
return bool(getattr(screencast_layout, "ENABLED", False))
|
||||||
except Exception:
|
except Exception:
|
||||||
return False
|
return False
|
||||||
|
|
@ -50,7 +50,7 @@ def screen_video() -> bool:
|
||||||
|
|
||||||
def screen_ranges(ranges, on_screen_video=None):
|
def screen_ranges(ranges, on_screen_video=None):
|
||||||
"""(start, end) pairs, clip seconds, of the stretches rendered on-screen."""
|
"""(start, end) pairs, clip seconds, of the stretches rendered on-screen."""
|
||||||
import layout_ranges
|
from clipwright.layouts import layout_ranges
|
||||||
layouts = set(SCREEN_LAYOUTS)
|
layouts = set(SCREEN_LAYOUTS)
|
||||||
if screen_video() if on_screen_video is None else on_screen_video:
|
if screen_video() if on_screen_video is None else on_screen_video:
|
||||||
layouts.add("general")
|
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."""
|
"""One vision call; returns the parsed dict. Split out so tests can stub it."""
|
||||||
from google import genai
|
from google import genai
|
||||||
from google.genai import types as genai_types
|
from google.genai import types as genai_types
|
||||||
import gemini_worker
|
from clipwright.pipeline import gemini_worker
|
||||||
|
|
||||||
client = genai.Client(api_key=api_key)
|
client = genai.Client(api_key=api_key)
|
||||||
model_name = os.environ.get("GEMINI_MODEL") or "gemini-3.1-flash-lite"
|
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.")
|
"keeping the transcript hook.")
|
||||||
return None
|
return None
|
||||||
try:
|
try:
|
||||||
import gemini_worker
|
from clipwright.pipeline import gemini_worker
|
||||||
|
|
||||||
times = sample_times(clip.get("layout_ranges"), float(end) - float(start))
|
times = sample_times(clip.get("layout_ranges"), float(end) - float(start))
|
||||||
frames = frames_at(clip_path, times)
|
frames = frames_at(clip_path, times)
|
||||||
|
|
@ -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
|
provider. Raises on HTTP errors, empty bodies and schema violations; the
|
||||||
retry policy lives in the caller, same as for Gemini.
|
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"
|
url = f"{base_url()}/chat/completions"
|
||||||
model = model or model_name()
|
model = model or model_name()
|
||||||
|
|
@ -23,16 +23,17 @@ import mediapipe as mp
|
||||||
from google import genai
|
from google import genai
|
||||||
from google.genai import types as genai_types
|
from google.genai import types as genai_types
|
||||||
|
|
||||||
import frame_sampler
|
from clipwright.media import frame_sampler
|
||||||
import gemini_worker
|
from clipwright.pipeline import gemini_worker
|
||||||
import hook_grounding
|
from clipwright.pipeline import hook_grounding
|
||||||
import layout_picker
|
from clipwright.layouts import layout_picker
|
||||||
import llm_backend
|
from clipwright.pipeline import llm_backend
|
||||||
from clip_selection import (build_transcript_windows, clip_count_targets,
|
from clipwright.core.paths import ASSETS_DIR
|
||||||
|
from clipwright.pipeline.clip_selection import (build_transcript_windows, clip_count_targets,
|
||||||
clip_duration_bounds, dedupe_overlapping,
|
clip_duration_bounds, dedupe_overlapping,
|
||||||
score_batches, shortlist_target,
|
score_batches, shortlist_target,
|
||||||
snap_clip_to_words, trim_to_best)
|
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)
|
QUALITY_FAST, METADATA_SCRUB)
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
import json
|
import json
|
||||||
|
|
@ -633,7 +634,7 @@ def analyze_scenes_strategy(video_path, scenes):
|
||||||
return strategies
|
return strategies
|
||||||
|
|
||||||
def detect_scenes(video_path):
|
def detect_scenes(video_path):
|
||||||
import scene_detection
|
from clipwright.media import scene_detection
|
||||||
return scene_detection.detect_scenes(video_path)
|
return scene_detection.detect_scenes(video_path)
|
||||||
|
|
||||||
def get_video_resolution(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
|
# SSRF guard: block non-http(s) schemes and private/loopback/metadata hosts
|
||||||
# before handing the URL to yt-dlp.
|
# 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)
|
assert_public_url(url)
|
||||||
# Throwaway hosts agents fall back to (tmpfiles.org) hand out short-lived
|
# 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.
|
# 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)
|
url = file_hosts.resolve(url)
|
||||||
# Reject non-video YouTube links before the download starts.
|
# 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)
|
reason = youtube_non_video_reason(url)
|
||||||
if reason:
|
if reason:
|
||||||
raise NotASingleVideo(f"This link is {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
|
# explicit `default,mweb` because the authed defaults alone return
|
||||||
# "Video unavailable" on a share of videos, from every IP, and that was
|
# "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).
|
# 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)
|
hd_args = hd_extractor_args(_bgutil_http, _bgutil_script)
|
||||||
fallback_args = fallback_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'):
|
if not transcript or not transcript.get('segments'):
|
||||||
return None # silent video: nothing to caption
|
return None # silent video: nothing to caption
|
||||||
try:
|
try:
|
||||||
import subtitles as _subs
|
from clipwright.media import subtitles as _subs
|
||||||
style = _subs.AUTO_CAPTION_STYLE
|
style = _subs.AUTO_CAPTION_STYLE
|
||||||
output_dir = os.path.dirname(clip_path)
|
output_dir = os.path.dirname(clip_path)
|
||||||
stem = os.path.basename(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}")
|
out_path = os.path.join(output_dir, f"subtitled_{generation_id}_{stem}")
|
||||||
|
|
||||||
if split_ranges is None:
|
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))
|
split_ranges = _layouts.split_ranges(_layouts.read(clip_path))
|
||||||
if not _subs.generate_ass(
|
if not _subs.generate_ass(
|
||||||
transcript, clip_start, clip_end, ass_path,
|
transcript, clip_start, clip_end, ass_path,
|
||||||
|
|
@ -1302,7 +1303,7 @@ def auto_hook_clip(clip_path, clip, captions=None):
|
||||||
except ValueError:
|
except ValueError:
|
||||||
seconds = 5.0
|
seconds = 5.0
|
||||||
try:
|
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:
|
if style not in HOOK_STYLES:
|
||||||
style = "pill"
|
style = "pill"
|
||||||
output_dir = os.path.dirname(clip_path)
|
output_dir = os.path.dirname(clip_path)
|
||||||
|
|
@ -1378,8 +1379,7 @@ WATERMARK_OPACITY = 0.85
|
||||||
|
|
||||||
|
|
||||||
def watermark_logo_path():
|
def watermark_logo_path():
|
||||||
return os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
return str(ASSETS_DIR / "watermark.png")
|
||||||
"assets", "watermark.png")
|
|
||||||
|
|
||||||
|
|
||||||
def watermark_filter(vw, vh, video="[0:v]", logo="[1:v]", out=""):
|
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
|
be made: the mark must never cost the user the clip (same fail-open rule
|
||||||
apply_watermark has always had).
|
apply_watermark has always had).
|
||||||
"""
|
"""
|
||||||
import watermarked
|
from clipwright.media import watermarked
|
||||||
out_path = os.path.join(os.path.dirname(final_path),
|
out_path = os.path.join(os.path.dirname(final_path),
|
||||||
watermarked.marked_name(final_path))
|
watermarked.marked_name(final_path))
|
||||||
if os.path.exists(out_path) and os.path.getsize(out_path) > 0:
|
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.
|
# 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":
|
if os.environ.get("REFRAME_ENGINE", "v2").strip().lower() != "v1":
|
||||||
try:
|
try:
|
||||||
import reframe_v2
|
from clipwright.layouts import reframe_v2
|
||||||
t0 = time.time()
|
t0 = time.time()
|
||||||
result = reframe_v2.render(input_video, final_output_video, aspect_ratio,
|
result = reframe_v2.render(input_video, final_output_video, aspect_ratio,
|
||||||
force_strategy=force_strategy,
|
force_strategy=force_strategy,
|
||||||
|
|
@ -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
|
# 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
|
# 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.
|
# 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,
|
OUTPUT_WIDTH, OUTPUT_HEIGHT = delivery_size(original_width, original_height,
|
||||||
aspect_ratio)
|
aspect_ratio)
|
||||||
|
|
||||||
|
|
@ -1776,7 +1776,7 @@ def _free_gpu_cache():
|
||||||
|
|
||||||
def transcribe_video(video_path):
|
def transcribe_video(video_path):
|
||||||
print("🎙️ Transcribing video...")
|
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.
|
# 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
|
# 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))
|
_w = int(_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
||||||
_h = int(_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
_h = int(_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
||||||
_cap.release()
|
_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
|
# A source already shot vertical has no width to reorganise, and
|
||||||
# the render passes it through whatever the model says. Asking
|
# the render passes it through whatever the model says. Asking
|
||||||
# anyway costs a Gemini call per upload to be ignored.
|
# 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
|
# 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).
|
# 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
|
transcript = None
|
||||||
# Module handover (issue #68): another module already transcribed this
|
# Module handover (issue #68): another module already transcribed this
|
||||||
# exact source with the same backend, so reuse its output. Any problem
|
# exact source with the same backend, so reuse its output. Any problem
|
||||||
|
|
@ -2453,7 +2453,7 @@ if __name__ == '__main__':
|
||||||
deliver_path = clip_final_path
|
deliver_path = clip_final_path
|
||||||
# Which stretches were stacked (SPLIT): captions go on the
|
# Which stretches were stacked (SPLIT): captions go on the
|
||||||
# seam there, and /api/subtitle needs it again later.
|
# 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)
|
clip['layout_ranges'] = _layouts.read(clip_final_path)
|
||||||
# The hook was written from the transcript alone. When the
|
# The hook was written from the transcript alone. When the
|
||||||
# render put this clip's meaning on the screen, rewrite hook
|
# render put this clip's meaning on the screen, rewrite hook
|
||||||
|
|
@ -2505,7 +2505,7 @@ if __name__ == '__main__':
|
||||||
if os.environ.get("WATERMARK") == "1":
|
if os.environ.get("WATERMARK") == "1":
|
||||||
# Tells the /videos guard that the clean twins in this
|
# Tells the /videos guard that the clean twins in this
|
||||||
# directory are not for serving (watermarked.MARKER_FILE).
|
# directory are not for serving (watermarked.MARKER_FILE).
|
||||||
import watermarked
|
from clipwright.media import watermarked
|
||||||
watermarked.mark_job(output_dir)
|
watermarked.mark_job(output_dir)
|
||||||
with ThreadPoolExecutor(max_workers=min(clip_workers, len(shorts))) as pool:
|
with ThreadPoolExecutor(max_workers=min(clip_workers, len(shorts))) as pool:
|
||||||
# Best clip first: the pool starts work in submission order, so
|
# Best clip first: the pool starts work in submission order, so
|
||||||
|
|
@ -16,15 +16,16 @@ import sys
|
||||||
|
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
from clipwright.core.paths import REPO_ROOT
|
||||||
|
|
||||||
load_dotenv()
|
load_dotenv()
|
||||||
|
|
||||||
|
|
||||||
def _find_cookies_path():
|
def _find_cookies_path():
|
||||||
# Mirrors main.py's cookie discovery.
|
# Mirrors main.py's cookie discovery.
|
||||||
script_dir = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
for candidate in [
|
for candidate in [
|
||||||
os.path.join(script_dir, 'www.youtube.com_cookies.txt'),
|
str(REPO_ROOT / 'www.youtube.com_cookies.txt'),
|
||||||
os.path.join(script_dir, 'cookies.txt'),
|
str(REPO_ROOT / 'cookies.txt'),
|
||||||
'/app/cookies.txt',
|
'/app/cookies.txt',
|
||||||
]:
|
]:
|
||||||
if os.path.exists(candidate):
|
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
|
# result is the fail-open "unknown", so the caller carries on and the
|
||||||
# real probe / download refuse the URL with their own message.
|
# real probe / download refuse the URL with their own message.
|
||||||
try:
|
try:
|
||||||
from security_utils import assert_public_url
|
from clipwright.core.security_utils import assert_public_url
|
||||||
from yt_clients import youtube_non_video_reason
|
from clipwright.integrations.yt_clients import youtube_non_video_reason
|
||||||
assert_public_url(args.url)
|
assert_public_url(args.url)
|
||||||
if youtube_non_video_reason(args.url):
|
if youtube_non_video_reason(args.url):
|
||||||
raise ValueError("not a single video")
|
raise ValueError("not a single video")
|
||||||
|
|
@ -32,7 +32,7 @@ import tempfile
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
|
|
||||||
from subtitles import (
|
from clipwright.media.subtitles import (
|
||||||
get_whisper_config,
|
get_whisper_config,
|
||||||
WHISPER_TRANSCRIBE_PARAMS,
|
WHISPER_TRANSCRIBE_PARAMS,
|
||||||
merge_continuation_words,
|
merge_continuation_words,
|
||||||
|
|
@ -368,7 +368,7 @@ def release_models():
|
||||||
del whisper, parakeet
|
del whisper, parakeet
|
||||||
# TransNetV2 is the other torch tenant an in-process pipeline leaves
|
# TransNetV2 is the other torch tenant an in-process pipeline leaves
|
||||||
# behind (scene_detection keeps it as a module singleton too).
|
# 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:
|
if tn2 is not None:
|
||||||
tn2._tn2_model = None
|
tn2._tn2_model = None
|
||||||
import gc
|
import gc
|
||||||
1
clipwright/tools/__init__.py
Normal file
1
clipwright/tools/__init__.py
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
"""Clipwright backend."""
|
||||||
|
|
@ -2,7 +2,7 @@ import os
|
||||||
import shutil
|
import shutil
|
||||||
# Check if PIL is installed, if not we can't run this locally but it will run in docker
|
# Check if PIL is installed, if not we can't run this locally but it will run in docker
|
||||||
try:
|
try:
|
||||||
from hooks import create_hook_image
|
from clipwright.media.hooks import create_hook_image
|
||||||
except ImportError:
|
except ImportError:
|
||||||
print("⚠️ PIL not found locally. Please run this inside the Docker container.")
|
print("⚠️ PIL not found locally. Please run this inside the Docker container.")
|
||||||
# Mocking for local check if needed or just exit
|
# Mocking for local check if needed or just exit
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
import os
|
import os
|
||||||
try:
|
try:
|
||||||
from hooks import create_hook_image
|
from clipwright.media.hooks import create_hook_image
|
||||||
except ImportError:
|
except ImportError:
|
||||||
print("⚠️ PIL not found locally. Run inside Docker.")
|
print("⚠️ PIL not found locally. Run inside Docker.")
|
||||||
exit(1)
|
exit(1)
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
import os
|
import os
|
||||||
import shutil
|
import shutil
|
||||||
from hooks import create_hook_image
|
from clipwright.media.hooks import create_hook_image
|
||||||
|
|
||||||
def verify():
|
def verify():
|
||||||
print("🧪 Verifying Hook Image Generation...")
|
print("🧪 Verifying Hook Image Generation...")
|
||||||
|
|
@ -1754,7 +1754,7 @@ ${faqBlock([
|
||||||
${sources([
|
${sources([
|
||||||
'Opus Clip tier minutes and prices checked 2026-07-27 on their public pricing page.',
|
'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.',
|
'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>.`,
|
`Inset, WIDE and screencast layout implementations in the project source at <a href="${SITE.repo}" rel="noopener">git.pbento.pt/pedro-bento/clipwright</a>.`,
|
||||||
])}
|
])}
|
||||||
`,
|
`,
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ const ENTRANCE_OPTIONS = [
|
||||||
{ value: 'none', label: 'None' },
|
{ value: 'none', label: 'None' },
|
||||||
];
|
];
|
||||||
|
|
||||||
// Must mirror hooks.py HOOK_STYLES.
|
// Must mirror clipwright/media/hooks.py HOOK_STYLES.
|
||||||
const HOOK_STYLES = [
|
const HOOK_STYLES = [
|
||||||
{ value: 'pill', label: 'Pills', box: 'rgba(255,255,255,0.98)', text: '#000', sans: true },
|
{ 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' },
|
{ 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 },
|
{ 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 = [
|
const FONT_OPTIONS = [
|
||||||
{ value: 'montserrat', label: 'Montserrat' },
|
{ value: 'montserrat', label: 'Montserrat' },
|
||||||
{ value: 'anton', label: 'Anton' },
|
{ value: 'anton', label: 'Anton' },
|
||||||
|
|
@ -33,7 +33,7 @@ const FONT_CSS = {
|
||||||
anton: { fontFamily: "'Anton-Regular', Impact, sans-serif", fontWeight: 400 },
|
anton: { fontFamily: "'Anton-Regular', Impact, sans-serif", fontWeight: 400 },
|
||||||
serif: { fontFamily: "'Noto Serif', Georgia, serif", fontWeight: 700 },
|
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 styleFont = (st) => (st === 'pill' ? 'montserrat' : 'serif');
|
||||||
|
|
||||||
const POSITION_OPTIONS = [
|
const POSITION_OPTIONS = [
|
||||||
|
|
|
||||||
|
|
@ -25,7 +25,7 @@ const SIZE_SCALE: Record<string, number> = {
|
||||||
L: 1.3,
|
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.
|
// or the preview drifts from what the server path renders.
|
||||||
const POSITION_STYLE: Record<string, React.CSSProperties> = {
|
const POSITION_STYLE: Record<string, React.CSSProperties> = {
|
||||||
top: { top: "20%", bottom: "auto" },
|
top: { top: "20%", bottom: "auto" },
|
||||||
|
|
@ -33,13 +33,13 @@ const POSITION_STYLE: Record<string, React.CSSProperties> = {
|
||||||
bottom: { top: "70%", bottom: "auto" },
|
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 {
|
interface HookLook {
|
||||||
box: string | null;
|
box: string | null;
|
||||||
text: string;
|
text: string;
|
||||||
outlinePx: number;
|
outlinePx: number;
|
||||||
shadow: boolean;
|
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;
|
pills?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -127,7 +127,7 @@ const HookBox: React.FC<HookBoxProps> = ({ config, displayFrames }) => {
|
||||||
const positionStyle = POSITION_STYLE[config.position] ?? POSITION_STYLE.top;
|
const positionStyle = POSITION_STYLE[config.position] ?? POSITION_STYLE.top;
|
||||||
const look = HOOK_LOOKS[config.style ?? "pill"] ?? HOOK_LOOKS.pill;
|
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.
|
// font size = factor x the 90%-of-width box.
|
||||||
const typeface = HOOK_FONTS[config.font ?? (look.pills ? "montserrat" : "serif")] ?? HOOK_FONTS.serif;
|
const typeface = HOOK_FONTS[config.font ?? (look.pills ? "montserrat" : "serif")] ?? HOOK_FONTS.serif;
|
||||||
const fontSize = Math.round(1080 * 0.9 * typeface.factor * scale);
|
const fontSize = Math.round(1080 * 0.9 * typeface.factor * scale);
|
||||||
|
|
@ -135,7 +135,7 @@ const HookBox: React.FC<HookBoxProps> = ({ config, displayFrames }) => {
|
||||||
|
|
||||||
if (look.pills) {
|
if (look.pills) {
|
||||||
// box-decoration-break: clone gives every wrapped line its own padded,
|
// 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 (
|
return (
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
|
|
|
||||||
|
|
@ -41,7 +41,7 @@ export const antonFontFace = `
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Hook typefaces: CSS family + share of the 90% box width used as font size.
|
* 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 }> = {
|
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 },
|
montserrat: { family: `'${MONTSERRAT_FONT_FAMILY}', 'Montserrat', sans-serif`, weight: 800, factor: 0.064 },
|
||||||
|
|
|
||||||
|
|
@ -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 |
|
| 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)
|
## 3. Base de datos de la aplicación (si usas cuentas)
|
||||||
|
|
||||||
| Qué | Plazo | Dónde se aplica |
|
| 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 |
|
| 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 | `app.py` (captura) → `Project.state.rights_attestation` |
|
| **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` |
|
||||||
| `proxy_usage` (host de la URL, id de trabajo; **sin usuario**) | Contabilidad de costes; sin datos personales | `metering.py` |
|
|
||||||
|
|
||||||
## 4. Navegador del usuario (localStorage, nunca cookies de terceros)
|
## 4. Navegador del usuario (localStorage, nunca cookies de terceros)
|
||||||
|
|
||||||
|
|
|
||||||
30
pyproject.toml
Normal file
30
pyproject.toml
Normal 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"]
|
||||||
|
|
@ -26,7 +26,7 @@ const POSITION_STYLE: Record<string, React.CSSProperties> = {
|
||||||
bottom: { top: "68%", bottom: "auto" },
|
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 {
|
interface HookLook {
|
||||||
box: string | null;
|
box: string | null;
|
||||||
text: string;
|
text: string;
|
||||||
|
|
@ -126,7 +126,7 @@ const HookBox: React.FC<HookBoxProps> = ({ config, displayFrames }) => {
|
||||||
const positionStyle = POSITION_STYLE[config.position] ?? POSITION_STYLE.top;
|
const positionStyle = POSITION_STYLE[config.position] ?? POSITION_STYLE.top;
|
||||||
const look = HOOK_LOOKS[config.style ?? "classic"] ?? HOOK_LOOKS.classic;
|
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 baseFontSize = 1080 * 0.05;
|
||||||
const fontSize = Math.round(baseFontSize * scale);
|
const fontSize = Math.round(baseFontSize * scale);
|
||||||
|
|
||||||
|
|
|
||||||
14
requirements-test.txt
Normal file
14
requirements-test.txt
Normal 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
|
||||||
|
|
@ -1,5 +1,7 @@
|
||||||
import os
|
"""Shared pytest configuration.
|
||||||
import sys
|
|
||||||
|
|
||||||
# Make the repo root importable so tests can import the app modules directly.
|
The repo-root ``clipwright/`` package is made importable by
|
||||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
``[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.
|
||||||
|
"""
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
from active_speaker import (
|
from clipwright.layouts.active_speaker import (
|
||||||
attribute_windows,
|
attribute_windows,
|
||||||
hold,
|
hold,
|
||||||
is_conversation,
|
is_conversation,
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,7 @@ import os
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
Image = pytest.importorskip("PIL.Image")
|
Image = pytest.importorskip("PIL.Image")
|
||||||
thumbnail = pytest.importorskip("thumbnail")
|
thumbnail = pytest.importorskip("clipwright.media.thumbnail")
|
||||||
|
|
||||||
TRAINED = b"trainedAlgorithmicMedia"
|
TRAINED = b"trainedAlgorithmicMedia"
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,9 @@ import os
|
||||||
import httpx
|
import httpx
|
||||||
import pytest
|
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):
|
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)
|
probed.append(u)
|
||||||
return {}
|
return {}
|
||||||
monkeypatch.setattr(app_module, "_probe_youtube_quality", _probe)
|
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",
|
resp = _post_process({"url": "https://www.youtube.com/results?search_query=x",
|
||||||
"acknowledged": True})
|
"acknowledged": True})
|
||||||
assert resp.status_code == 400
|
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():
|
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."""
|
denylist would silently break jobs: fail here instead."""
|
||||||
import ast
|
import ast
|
||||||
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
from pathlib import Path
|
||||||
local = {f[:-3] for f in os.listdir(root) if f.endswith(".py")}
|
|
||||||
seen, stack = set(), ["main", "quality_probe"]
|
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:
|
while stack:
|
||||||
mod = stack.pop()
|
mod = stack.pop()
|
||||||
if mod in seen:
|
if mod in seen or mod not in sources:
|
||||||
continue
|
continue
|
||||||
seen.add(mod)
|
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:
|
for name in app_module.CHILD_ENV_DENYLIST:
|
||||||
assert f'"{name}"' not in src and f"'{name}'" not in src, (mod, name)
|
assert f'"{name}"' not in src and f"'{name}'" not in src, (mod, name)
|
||||||
for node in ast.walk(ast.parse(src)):
|
for node in ast.walk(ast.parse(src)):
|
||||||
names = []
|
|
||||||
if isinstance(node, ast.Import):
|
if isinstance(node, ast.Import):
|
||||||
names = [a.name.split(".")[0] for a in node.names]
|
targets = [a.name for a in node.names]
|
||||||
elif isinstance(node, ast.ImportFrom) and node.module:
|
elif isinstance(node, ast.ImportFrom):
|
||||||
names = [node.module.split(".")[0]]
|
if node.level:
|
||||||
for n in names:
|
base = mod.split(".")[:-1]
|
||||||
if n in local:
|
base = base[: len(base) - (node.level - 1)]
|
||||||
stack.append(n)
|
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):
|
def test_job_env_has_no_server_secrets(dirs, calls, monkeypatch):
|
||||||
|
|
@ -240,7 +264,7 @@ import subprocess
|
||||||
class TestSafetyCap:
|
class TestSafetyCap:
|
||||||
@pytest.fixture()
|
@pytest.fixture()
|
||||||
def source(self, tmp_path):
|
def source(self, tmp_path):
|
||||||
main = pytest.importorskip("main")
|
main = pytest.importorskip("clipwright.pipeline.main")
|
||||||
path = tmp_path / "src.mp4"
|
path = tmp_path / "src.mp4"
|
||||||
subprocess.run([
|
subprocess.run([
|
||||||
"ffmpeg", "-y", "-loglevel", "error",
|
"ffmpeg", "-y", "-loglevel", "error",
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ import json
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
app_module = pytest.importorskip("app")
|
app_module = pytest.importorskip("clipwright.api.app")
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
from camera_inset import (
|
from clipwright.layouts.camera_inset import (
|
||||||
INSET_ASPECT,
|
INSET_ASPECT,
|
||||||
inset_box,
|
inset_box,
|
||||||
inset_filtergraph,
|
inset_filtergraph,
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
import asyncio
|
import asyncio
|
||||||
import re
|
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():
|
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():
|
def test_unknown_preset_is_a_400():
|
||||||
import pytest
|
import pytest
|
||||||
from fastapi import HTTPException
|
from fastapi import HTTPException
|
||||||
from app import SubtitleRequest, add_subtitles
|
from clipwright.api.app import SubtitleRequest, add_subtitles
|
||||||
with pytest.raises(HTTPException) as exc:
|
with pytest.raises(HTTPException) as exc:
|
||||||
asyncio.run(add_subtitles(SubtitleRequest(job_id="j", clip_index=0, preset="nope"), None))
|
asyncio.run(add_subtitles(SubtitleRequest(job_id="j", clip_index=0, preset="nope"), None))
|
||||||
assert exc.value.status_code == 400
|
assert exc.value.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
def test_preset_fills_only_fields_not_sent():
|
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")
|
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()
|
merged = req.model_copy(update={k: v for k, v in CAPTION_PRESETS["hormozi"].items()
|
||||||
if k not in req.model_fields_set})
|
if k not in req.model_fields_set})
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ import time
|
||||||
|
|
||||||
import pytest
|
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
|
OLD = 2 * 3600 # older than the 1 h JOB_RETENTION_SECONDS the fixture sets
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ import json
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
main = pytest.importorskip("main")
|
main = pytest.importorskip("clipwright.pipeline.main")
|
||||||
|
|
||||||
|
|
||||||
def _transcript(n_segments=40):
|
def _transcript(n_segments=40):
|
||||||
|
|
|
||||||
|
|
@ -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.
|
to serve; app.py consumes the marker the way it already consumes PROXY_BYTES.
|
||||||
"""
|
"""
|
||||||
import io
|
import io
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
import pytest
|
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):
|
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
|
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.
|
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(")
|
caption_at = main_src.index("captioned = auto_caption_clip(")
|
||||||
# The free plan's served file is a wm_ copy of the captioned final
|
# 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.
|
# (mark_delivery), so the marker must also come after that step.
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
"""The strongest clip renders first, so it is the first one the user sees."""
|
"""The strongest clip renders first, so it is the first one the user sees."""
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
main = pytest.importorskip("main")
|
main = pytest.importorskip("clipwright.pipeline.main")
|
||||||
|
|
||||||
|
|
||||||
def test_best_score_first():
|
def test_best_score_first():
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@ import re
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from clip_selection import (
|
from clipwright.pipeline.clip_selection import (
|
||||||
build_transcript_windows,
|
build_transcript_windows,
|
||||||
clip_count_targets,
|
clip_count_targets,
|
||||||
dedupe_overlapping,
|
dedupe_overlapping,
|
||||||
|
|
@ -157,7 +157,7 @@ class TestClipCountTargets:
|
||||||
|
|
||||||
class TestDetailPromptCarriesTheCount:
|
class TestDetailPromptCarriesTheCount:
|
||||||
def test_template_formats_with_the_targets(self):
|
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)
|
low, high = clip_count_targets(5)
|
||||||
prompt = gw.DETAIL_PROMPT_TEMPLATE.format(
|
prompt = gw.DETAIL_PROMPT_TEMPLATE.format(
|
||||||
video_duration=300, language="es", min_clips=low, max_clips=high,
|
video_duration=300, language="es", min_clips=low, max_clips=high,
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,7 @@ import time
|
||||||
import httpx
|
import httpx
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
app_module = pytest.importorskip("app")
|
app_module = pytest.importorskip("clipwright.api.app")
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@ bytes) -> per-GB paid proxy (720p cost cap) -> conservative fallback. The
|
||||||
"""
|
"""
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
main = pytest.importorskip("main")
|
main = pytest.importorskip("clipwright.pipeline.main")
|
||||||
|
|
||||||
plan = main.plan_download_attempts
|
plan = main.plan_download_attempts
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
import pytest
|
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):
|
def _edit(type_, start, end, strength=0.0):
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,8 @@ import subprocess
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
import ffmpeg_utils
|
from clipwright.media import ffmpeg_utils
|
||||||
from ffmpeg_utils import (
|
from clipwright.media.ffmpeg_utils import (
|
||||||
AI_DISCLOSURE,
|
AI_DISCLOSURE,
|
||||||
DELIVERY,
|
DELIVERY,
|
||||||
METADATA_SCRUB,
|
METADATA_SCRUB,
|
||||||
|
|
|
||||||
|
|
@ -6,8 +6,8 @@ already being ~300 bytes, and the derived temp name pushed it further.
|
||||||
"""
|
"""
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
main = pytest.importorskip("main") # cv2 etc., absent in minimal CI
|
main = pytest.importorskip("clipwright.pipeline.main") # cv2 etc., absent in minimal CI
|
||||||
hooks = pytest.importorskip("hooks")
|
hooks = pytest.importorskip("clipwright.media.hooks")
|
||||||
|
|
||||||
# ext4/APFS cap a single name at 255 bytes.
|
# ext4/APFS cap a single name at 255 bytes.
|
||||||
FS_LIMIT = 255
|
FS_LIMIT = 255
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@ import cv2
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
import frame_sampler
|
from clipwright.media import frame_sampler
|
||||||
|
|
||||||
N_FRAMES = 60
|
N_FRAMES = 60
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ import pytest
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from fastapi.testclient import TestClient
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
import free_tools as ft
|
from clipwright.api import free_tools as ft
|
||||||
|
|
||||||
|
|
||||||
class TestExtractVideoId:
|
class TestExtractVideoId:
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
"""A policy block on a batch of windows must bisect, not kill the job."""
|
"""A policy block on a batch of windows must bisect, not kill the job."""
|
||||||
import pytest
|
import pytest
|
||||||
main = pytest.importorskip("main")
|
main = pytest.importorskip("clipwright.pipeline.main")
|
||||||
import gemini_worker
|
from clipwright.pipeline import gemini_worker
|
||||||
|
|
||||||
|
|
||||||
def _windows(n):
|
def _windows(n):
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ import pytest
|
||||||
|
|
||||||
# main pulls in cv2/torch/mediapipe at import time; the minimal CI env lacks
|
# 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.
|
# 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:
|
class _FakeResponse:
|
||||||
|
|
@ -112,7 +112,7 @@ def test_policy_block_fails_fast_without_retrying():
|
||||||
_Models.calls += 1
|
_Models.calls += 1
|
||||||
return _BlockedResponse()
|
return _BlockedResponse()
|
||||||
|
|
||||||
import gemini_worker
|
from clipwright.pipeline import gemini_worker
|
||||||
with pytest.raises(gemini_worker.GeminiBlockedError) as exc:
|
with pytest.raises(gemini_worker.GeminiBlockedError) as exc:
|
||||||
main._run_gemini_stage(_client(_Models()), "m", "prompt", object)
|
main._run_gemini_stage(_client(_Models()), "m", "prompt", object)
|
||||||
assert _Models.calls == 1
|
assert _Models.calls == 1
|
||||||
|
|
@ -120,7 +120,7 @@ def test_policy_block_fails_fast_without_retrying():
|
||||||
|
|
||||||
|
|
||||||
def test_blocked_finish_reason_also_raises():
|
def test_blocked_finish_reason_also_raises():
|
||||||
import gemini_worker
|
from clipwright.pipeline import gemini_worker
|
||||||
|
|
||||||
class _Cand:
|
class _Cand:
|
||||||
class _FR:
|
class _FR:
|
||||||
|
|
@ -137,7 +137,7 @@ def test_blocked_finish_reason_also_raises():
|
||||||
|
|
||||||
|
|
||||||
def test_clean_response_is_not_flagged_as_blocked():
|
def test_clean_response_is_not_flagged_as_blocked():
|
||||||
import gemini_worker
|
from clipwright.pipeline import gemini_worker
|
||||||
|
|
||||||
class _Resp:
|
class _Resp:
|
||||||
prompt_feedback = None
|
prompt_feedback = None
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,7 @@ import io
|
||||||
import httpx
|
import httpx
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
import gemini_worker
|
from clipwright.pipeline import gemini_worker
|
||||||
|
|
||||||
|
|
||||||
def _prepared_headers(file_arg, mime_type=None):
|
def _prepared_headers(file_arg, mime_type=None):
|
||||||
|
|
@ -77,7 +77,12 @@ def test_every_whole_file_upload_goes_through_the_helper():
|
||||||
import re
|
import re
|
||||||
root = pathlib.Path(__file__).resolve().parent.parent
|
root = pathlib.Path(__file__).resolve().parent.parent
|
||||||
offenders = []
|
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()
|
src = (root / name).read_text()
|
||||||
if re.search(r"\.files\.upload\(", src):
|
if re.search(r"\.files\.upload\(", src):
|
||||||
offenders.append(name)
|
offenders.append(name)
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ import os
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
import clip_selection
|
from clipwright.pipeline import clip_selection
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(autouse=True)
|
@pytest.fixture(autouse=True)
|
||||||
|
|
@ -49,6 +49,7 @@ def _templates():
|
||||||
"""The prompt template constants, read without importing gemini_worker
|
"""The prompt template constants, read without importing gemini_worker
|
||||||
(which pulls google-genai — absent in the thin CI env)."""
|
(which pulls google-genai — absent in the thin CI env)."""
|
||||||
mod = ast.parse(open(os.path.join(os.path.dirname(__file__), "..",
|
mod = ast.parse(open(os.path.join(os.path.dirname(__file__), "..",
|
||||||
|
"clipwright", "pipeline",
|
||||||
"gemini_worker.py")).read())
|
"gemini_worker.py")).read())
|
||||||
return {
|
return {
|
||||||
node.targets[0].id: node.value.value
|
node.targets[0].id: node.value.value
|
||||||
|
|
|
||||||
|
|
@ -7,8 +7,8 @@ detail pass only ever reads the transcript.
|
||||||
"""
|
"""
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
import gemini_worker
|
from clipwright.pipeline import gemini_worker
|
||||||
import hook_grounding as hg
|
from clipwright.pipeline import hook_grounding as hg
|
||||||
|
|
||||||
|
|
||||||
SCREEN = [{"start": 0, "end": 30, "layout": "screencast"}]
|
SCREEN = [{"start": 0, "end": 30, "layout": "screencast"}]
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ import time
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
app_module = pytest.importorskip("app")
|
app_module = pytest.importorskip("clipwright.api.app")
|
||||||
|
|
||||||
_strip_burned_captions = app_module._strip_burned_captions
|
_strip_burned_captions = app_module._strip_burned_captions
|
||||||
_strip_burned_hook = app_module._strip_burned_hook
|
_strip_burned_hook = app_module._strip_burned_hook
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ import os
|
||||||
|
|
||||||
from PIL import Image, ImageDraw, ImageFont
|
from PIL import Image, ImageDraw, ImageFont
|
||||||
|
|
||||||
from hooks import (
|
from clipwright.media.hooks import (
|
||||||
HOOK_STYLES,
|
HOOK_STYLES,
|
||||||
_break_long_word,
|
_break_long_word,
|
||||||
_emoji_scale,
|
_emoji_scale,
|
||||||
|
|
@ -135,7 +135,7 @@ class TestCreateHookImage:
|
||||||
def test_pill_hook_image_stacks_one_box_per_line(tmp_path):
|
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
|
"""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)."""
|
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
|
from PIL import Image
|
||||||
out = tmp_path / "pill.png"
|
out = tmp_path / "pill.png"
|
||||||
path, w, h = create_hook_image("una frase bastante larga para partirse en dos lineas",
|
path, w, h = create_hook_image("una frase bastante larga para partirse en dos lineas",
|
||||||
|
|
|
||||||
|
|
@ -1,18 +1,30 @@
|
||||||
import sys
|
import sys
|
||||||
import types
|
import types
|
||||||
|
|
||||||
import layout_picker
|
from clipwright import layouts
|
||||||
from layout_picker import _module_flags, apply, pick
|
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):
|
def fake_modules(monkeypatch, **initial):
|
||||||
"""Install stand-in layout modules so apply() can be tested without them."""
|
"""Install stand-in layout modules so apply() can be tested without them."""
|
||||||
made = {}
|
made = {}
|
||||||
for name in ("split_layout", "screencast_layout", "active_speaker"):
|
for label, dotted in _FAKE_LAYOUT_MODULES.items():
|
||||||
module = types.ModuleType(name)
|
module = types.ModuleType(dotted)
|
||||||
module.ENABLED = initial.get(name, False)
|
module.ENABLED = initial.get(label, False)
|
||||||
monkeypatch.setitem(sys.modules, name, module)
|
monkeypatch.setitem(sys.modules, dotted, module)
|
||||||
made[name] = 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
|
return made
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -41,8 +53,8 @@ class TestApply:
|
||||||
mods = fake_modules(monkeypatch)
|
mods = fake_modules(monkeypatch)
|
||||||
touched = apply("screencast")
|
touched = apply("screencast")
|
||||||
assert touched == ["screencast_layout"]
|
assert touched == ["screencast_layout"]
|
||||||
assert mods["screencast_layout"].ENABLED is True
|
assert mods["clipwright.layouts.screencast_layout"].ENABLED is True
|
||||||
assert mods["split_layout"].ENABLED is False
|
assert mods["clipwright.layouts.split_layout"].ENABLED is False
|
||||||
|
|
||||||
def test_apply_none_touches_nothing(self, monkeypatch):
|
def test_apply_none_touches_nothing(self, monkeypatch):
|
||||||
mods = fake_modules(monkeypatch)
|
mods = fake_modules(monkeypatch)
|
||||||
|
|
@ -54,7 +66,7 @@ class TestApply:
|
||||||
# says "none". The picker only ever adds.
|
# says "none". The picker only ever adds.
|
||||||
mods = fake_modules(monkeypatch, split_layout=True)
|
mods = fake_modules(monkeypatch, split_layout=True)
|
||||||
apply("none")
|
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):
|
def test_already_enabled_modules_are_not_reported_as_touched(self, monkeypatch):
|
||||||
fake_modules(monkeypatch, screencast_layout=True)
|
fake_modules(monkeypatch, screencast_layout=True)
|
||||||
|
|
@ -63,8 +75,8 @@ class TestApply:
|
||||||
def test_split_enables_both_modules(self, monkeypatch):
|
def test_split_enables_both_modules(self, monkeypatch):
|
||||||
mods = fake_modules(monkeypatch)
|
mods = fake_modules(monkeypatch)
|
||||||
assert set(apply("split")) == {"split_layout", "active_speaker"}
|
assert set(apply("split")) == {"split_layout", "active_speaker"}
|
||||||
assert mods["split_layout"].ENABLED is True
|
assert mods["clipwright.layouts.split_layout"].ENABLED is True
|
||||||
assert mods["active_speaker"].ENABLED is True
|
assert mods["clipwright.layouts.active_speaker"].ENABLED is True
|
||||||
|
|
||||||
|
|
||||||
class TestPick:
|
class TestPick:
|
||||||
|
|
@ -134,7 +146,7 @@ class TestShadowMode:
|
||||||
monkeypatch.setattr(layout_picker, "SHADOW", False)
|
monkeypatch.setattr(layout_picker, "SHADOW", False)
|
||||||
monkeypatch.setattr(layout_picker, "pick", lambda *a, **k: "screencast")
|
monkeypatch.setattr(layout_picker, "pick", lambda *a, **k: "screencast")
|
||||||
layout_picker.pick_and_apply("v.mp4", 60)
|
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):
|
def test_shadow_logs_one_greppable_line(self, monkeypatch, capsys):
|
||||||
fake_modules(monkeypatch)
|
fake_modules(monkeypatch)
|
||||||
|
|
|
||||||
|
|
@ -7,8 +7,8 @@ import os
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
import layout_ranges
|
from clipwright.layouts import layout_ranges
|
||||||
import subtitles
|
from clipwright.media import subtitles
|
||||||
|
|
||||||
|
|
||||||
def _transcript(words):
|
def _transcript(words):
|
||||||
|
|
@ -78,7 +78,7 @@ class TestSeamCaptions:
|
||||||
|
|
||||||
class TestCaptionerReadsSidecar:
|
class TestCaptionerReadsSidecar:
|
||||||
def test_auto_caption_uses_sidecar_when_not_told(self, tmp_path, monkeypatch):
|
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")
|
clip = str(tmp_path / "x.mp4")
|
||||||
open(clip, "wb").close()
|
open(clip, "wb").close()
|
||||||
layout_ranges.write(clip, [(0, 3, "SPLIT")])
|
layout_ranges.write(clip, [(0, 3, "SPLIT")])
|
||||||
|
|
@ -110,7 +110,7 @@ class TestRemapAcrossCut:
|
||||||
|
|
||||||
def test_fast_recut_carries_the_sidecar(self, tmp_path, monkeypatch):
|
def test_fast_recut_carries_the_sidecar(self, tmp_path, monkeypatch):
|
||||||
import shutil
|
import shutil
|
||||||
import recut
|
from clipwright.media import recut
|
||||||
src = tmp_path / "canon.mp4"
|
src = tmp_path / "canon.mp4"
|
||||||
src.write_bytes(b"x")
|
src.write_bytes(b"x")
|
||||||
layout_ranges.write(str(src), [(0, 4, "SPLIT"), (4, 8, "TRACK")])
|
layout_ranges.write(str(src), [(0, 4, "SPLIT"), (4, 8, "TRACK")])
|
||||||
|
|
@ -127,7 +127,7 @@ class TestRemapAcrossCut:
|
||||||
|
|
||||||
class TestLayoutEnvNone:
|
class TestLayoutEnvNone:
|
||||||
def test_none_switches_the_picker_off_for_the_job(self):
|
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(["none"]) == {"AUTO_LAYOUT": "0"}
|
||||||
assert app_module.layout_env(["auto"]) == {"AUTO_LAYOUT": "1"}
|
assert app_module.layout_env(["auto"]) == {"AUTO_LAYOUT": "1"}
|
||||||
assert app_module.layout_env(["split"])["SPLIT_LAYOUT"] == "1"
|
assert app_module.layout_env(["split"])["SPLIT_LAYOUT"] == "1"
|
||||||
|
|
|
||||||
|
|
@ -10,8 +10,8 @@ import json
|
||||||
import httpx
|
import httpx
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
import gemini_worker
|
from clipwright.pipeline import gemini_worker
|
||||||
import llm_backend
|
from clipwright.pipeline import llm_backend
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@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) ------------
|
# --- main.py routing (needs the heavy deps; skipped on minimal CI) ------------
|
||||||
|
|
||||||
def test_stage_routes_to_local_backend_and_retries_transient(local, monkeypatch):
|
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)
|
monkeypatch.setattr(main.time, "sleep", lambda *_: None)
|
||||||
calls = {"n": 0}
|
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):
|
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)
|
monkeypatch.delenv("LLM_SCORE_BATCH", raising=False)
|
||||||
assert main.score_batch_size() == 3
|
assert main.score_batch_size() == 3
|
||||||
monkeypatch.setenv("LLM_SCORE_BATCH", "5")
|
monkeypatch.setenv("LLM_SCORE_BATCH", "5")
|
||||||
|
|
|
||||||
|
|
@ -12,13 +12,13 @@ same directory are still public to whoever has the job id.
|
||||||
"""
|
"""
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
media_auth = pytest.importorskip("media_auth")
|
media_auth = pytest.importorskip("clipwright.api.media_auth")
|
||||||
restoring_static = pytest.importorskip("restoring_static")
|
restoring_static = pytest.importorskip("clipwright.api.restoring_static")
|
||||||
|
|
||||||
|
|
||||||
class TestTheGuardIsWiredIn:
|
class TestTheGuardIsWiredIn:
|
||||||
def test_the_videos_mount_carries_the_allowlist(self):
|
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
|
mount = next(r for r in app.app.routes
|
||||||
if getattr(r, "name", None) == "videos")
|
if getattr(r, "name", None) == "videos")
|
||||||
# app._media_guard wraps the allowlist (and adds the free-plan rule
|
# app._media_guard wraps the allowlist (and adds the free-plan rule
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ handed to the thread).
|
||||||
import ast
|
import ast
|
||||||
from pathlib import Path
|
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:
|
def _is_blocking_call(node: ast.Call) -> bool:
|
||||||
|
|
|
||||||
94
tests/test_package_layout.py
Normal file
94
tests/test_package_layout.py
Normal 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())
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import panel_layout
|
from clipwright.layouts import panel_layout
|
||||||
from panel_layout import (
|
from clipwright.layouts.panel_layout import (
|
||||||
analyze_scene,
|
analyze_scene,
|
||||||
panel_filtergraph,
|
panel_filtergraph,
|
||||||
panel_geometry,
|
panel_geometry,
|
||||||
|
|
@ -192,7 +192,7 @@ class TestNeighbourClamp:
|
||||||
assert abs((w / h) - (tw / th)) < 0.05
|
assert abs((w / h) - (tw / th)) < 0.05
|
||||||
|
|
||||||
def test_gaps_measure_the_closest_neighbour(self):
|
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)])
|
gaps = neighbour_gaps([(100, 0, 0, 0), (400, 0, 0, 0), (1500, 0, 0, 0)])
|
||||||
assert gaps == [300, 300, 1100]
|
assert gaps == [300, 300, 1100]
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -20,7 +20,7 @@ import os
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
app = pytest.importorskip("app")
|
app = pytest.importorskip("clipwright.api.app")
|
||||||
|
|
||||||
|
|
||||||
def _clip(title):
|
def _clip(title):
|
||||||
|
|
|
||||||
|
|
@ -12,13 +12,13 @@ from datetime import datetime, timedelta, timezone
|
||||||
import httpx
|
import httpx
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
import postiz
|
from clipwright.integrations import postiz
|
||||||
|
|
||||||
POSTIZ_HEADERS = {"X-Postiz-Url": "https://postiz.example", "X-Postiz-Key": "k"}
|
POSTIZ_HEADERS = {"X-Postiz-Url": "https://postiz.example", "X-Postiz-Key": "k"}
|
||||||
|
|
||||||
|
|
||||||
def _app():
|
def _app():
|
||||||
return pytest.importorskip("app")
|
return pytest.importorskip("clipwright.api.app")
|
||||||
|
|
||||||
|
|
||||||
# --- postiz.py -------------------------------------------------------------
|
# --- postiz.py -------------------------------------------------------------
|
||||||
|
|
|
||||||
|
|
@ -15,7 +15,7 @@ import os
|
||||||
import httpx
|
import httpx
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
app_module = pytest.importorskip("app")
|
app_module = pytest.importorskip("clipwright.api.app")
|
||||||
|
|
||||||
TRANSCRIPT = {
|
TRANSCRIPT = {
|
||||||
"text": "hello world again",
|
"text": "hello world again",
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import punch_in
|
from clipwright.layouts import punch_in
|
||||||
from punch_in import MAX_ZOOM, crop_boxes, sendcmd_lines, zoom_curve
|
from clipwright.layouts.punch_in import MAX_ZOOM, crop_boxes, sendcmd_lines, zoom_curve
|
||||||
|
|
||||||
|
|
||||||
class TestZoomCurve:
|
class TestZoomCurve:
|
||||||
|
|
@ -87,19 +87,19 @@ class TestSendcmdLines:
|
||||||
|
|
||||||
class TestEmphasisTimes:
|
class TestEmphasisTimes:
|
||||||
def test_silent_or_unreadable_audio_yields_no_beats(self, monkeypatch):
|
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",
|
monkeypatch.setattr(active_speaker, "audio_envelope",
|
||||||
lambda *a, **k: [])
|
lambda *a, **k: [])
|
||||||
assert punch_in.emphasis_times("x.mp4", 30.0) == []
|
assert punch_in.emphasis_times("x.mp4", 30.0) == []
|
||||||
|
|
||||||
def test_flat_audio_yields_no_beats(self, monkeypatch):
|
def test_flat_audio_yields_no_beats(self, monkeypatch):
|
||||||
import active_speaker
|
from clipwright.layouts import active_speaker
|
||||||
monkeypatch.setattr(active_speaker, "audio_envelope",
|
monkeypatch.setattr(active_speaker, "audio_envelope",
|
||||||
lambda *a, **k: [0.5] * 50)
|
lambda *a, **k: [0.5] * 50)
|
||||||
assert punch_in.emphasis_times("x.mp4", 10.0) == []
|
assert punch_in.emphasis_times("x.mp4", 10.0) == []
|
||||||
|
|
||||||
def test_beats_respect_the_minimum_gap(self, monkeypatch):
|
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)]
|
envelope = [1.0 if i % 2 == 0 else 0.0 for i in range(100)]
|
||||||
monkeypatch.setattr(active_speaker, "audio_envelope",
|
monkeypatch.setattr(active_speaker, "audio_envelope",
|
||||||
lambda *a, **k: envelope)
|
lambda *a, **k: envelope)
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ import os
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
import recut
|
from clipwright.media import recut
|
||||||
|
|
||||||
|
|
||||||
def _seg(start, end):
|
def _seg(start, end):
|
||||||
|
|
|
||||||
|
|
@ -13,8 +13,8 @@ import os
|
||||||
import httpx
|
import httpx
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
app_module = pytest.importorskip("app")
|
app_module = pytest.importorskip("clipwright.api.app")
|
||||||
import recut # noqa: E402
|
from clipwright.media import recut # noqa: E402
|
||||||
|
|
||||||
JOB_ID = "reframe-endpoint-test-job"
|
JOB_ID = "reframe-endpoint-test-job"
|
||||||
|
|
||||||
|
|
@ -176,7 +176,7 @@ class TestApplyCropOverrides:
|
||||||
|
|
||||||
@pytest.fixture(autouse=True)
|
@pytest.fixture(autouse=True)
|
||||||
def _mod(self):
|
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):
|
def test_single_crop_centres_the_window(self):
|
||||||
xs = [None] * 100
|
xs = [None] * 100
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
from reframe_v2 import (
|
from clipwright.layouts.reframe_v2 import (
|
||||||
DELIVERY_MIN_WIDTH,
|
DELIVERY_MIN_WIDTH,
|
||||||
concat_list_content,
|
concat_list_content,
|
||||||
dedupe_sendcmd_lines,
|
dedupe_sendcmd_lines,
|
||||||
|
|
@ -93,7 +93,7 @@ class TestGeneralLayout:
|
||||||
"""GENERAL used to leave the content at 32% of the frame, floating in blur."""
|
"""GENERAL used to leave the content at 32% of the frame, floating in blur."""
|
||||||
|
|
||||||
def test_content_is_scaled_by_height_not_width(self):
|
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)
|
graph = general_filtergraph(1080, 1920)
|
||||||
expected = int(1920 * GENERAL_CONTENT_HEIGHT_RATIO)
|
expected = int(1920 * GENERAL_CONTENT_HEIGHT_RATIO)
|
||||||
expected += expected % 2
|
expected += expected % 2
|
||||||
|
|
@ -116,14 +116,14 @@ class TestGeneralLayout:
|
||||||
def test_content_fills_more_than_the_old_full_width_fit(self):
|
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
|
# 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.
|
# = 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
|
old_ratio = (1080 * 9 / 16) / 1920
|
||||||
assert GENERAL_CONTENT_HEIGHT_RATIO > old_ratio
|
assert GENERAL_CONTENT_HEIGHT_RATIO > old_ratio
|
||||||
|
|
||||||
def test_keeps_most_of_the_source_width(self):
|
def test_keeps_most_of_the_source_width(self):
|
||||||
# GENERAL is for groups and landscapes: cropping the sides too hard
|
# 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.
|
# 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)
|
scaled_w = 1920 * GENERAL_CONTENT_HEIGHT_RATIO * (16 / 9)
|
||||||
assert 1080 / scaled_w > 0.70, "keeps less than 70% of the source width"
|
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):
|
def test_landscape_keeps_the_presence_ratio(self):
|
||||||
# The floor must not disturb the case the ratio was tuned for: a 16:9
|
# 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.
|
# 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 = int(1920 * GENERAL_CONTENT_HEIGHT_RATIO)
|
||||||
expected += expected % 2
|
expected += expected % 2
|
||||||
graph = general_filtergraph(1080, 1920, orig_w=1920, orig_h=1080)
|
graph = general_filtergraph(1080, 1920, orig_w=1920, orig_h=1080)
|
||||||
|
|
|
||||||
|
|
@ -14,8 +14,8 @@ import os
|
||||||
import httpx
|
import httpx
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
app_module = pytest.importorskip("app")
|
app_module = pytest.importorskip("clipwright.api.app")
|
||||||
import recut # noqa: E402
|
from clipwright.media import recut # noqa: E402
|
||||||
|
|
||||||
JOB_ID = "recut-endpoint-test-job"
|
JOB_ID = "recut-endpoint-test-job"
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ import os
|
||||||
from starlette.applications import Starlette
|
from starlette.applications import Starlette
|
||||||
from starlette.testclient import TestClient
|
from starlette.testclient import TestClient
|
||||||
|
|
||||||
from restoring_static import RestoringStaticFiles
|
from clipwright.api.restoring_static import RestoringStaticFiles
|
||||||
|
|
||||||
JOB = "cff3ad6c-c1e6-48e8-9a75-be74f39779c5"
|
JOB = "cff3ad6c-c1e6-48e8-9a75-be74f39779c5"
|
||||||
|
|
||||||
|
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue