Compare commits

...

3 commits

Author SHA1 Message Date
245a27c7a3 chore: drop watermark feature, CLI, docs, design.md; consolidate requirements
- Remove the watermark feature end to end (watermarked.py, apply_watermark/
  mark_delivery/watermark_filter, WATERMARK env, assets/) and its tests; self-host
  delivery is now unconditionally clean.
- Delete the unused cli/ package and .github/workflows/publish-cli.yml.
- Delete docs/ (compliance) and design.md; drop the dangling references in the
  legal page and the design-token/ui comments.
- Consolidate requirements: requirements.txt (runtime) + requirements-test.txt
  (unit + E2E); remove requirements-e2e.txt and requirements-ml-e2e.txt and
  point both CI jobs at the single test file. Add libgl1 to the unit job
  (scenedetect -> opencv-python links libGL).

Verified in the CI container: unit 701 passed; API E2E 209; pipeline E2E 127;
Playwright 19 passed / 1 skipped.
2026-10-05 09:53:47 +01:00
1551371626 ci: exclude the E2E tree from unit-test collection
All checks were successful
CI / unit (pull_request) Successful in 29s
CI / backend-e2e (pull_request) Successful in 1m20s
CI / dashboard-e2e (pull_request) Successful in 1m45s
pytest still imports every module to collect it, and -m "not e2e" only filters
execution; the pipeline E2E modules import the pipeline (tqdm/scenedetect/ML)
which is absent from the unit environment. Fixes the CI unit job.
2026-10-04 22:12:21 +01:00
97f813553d test: add full E2E coverage (API, pipeline, browser)
Three-level end-to-end suite, all deterministic (no retries, no sleeps, no
unmocked network):

- tests/e2e/api (209 tests): every route in clipwright/api/app.py +
  free_tools — health/config, uploads, process submit matrix + worker/webhook/
  auto-retry/resume, status/source/download-all, edit/effects, transcript/EDL/
  rerender, scenes/reframe, subtitle, hook, Postiz, thumbnails, free tools,
  and the security/path guards.
- tests/e2e/pipeline (136 tests): every stage with real ffmpeg and stubbed
  Gemini/yt-dlp/ASR/ML — download, transcribe, scene detect, selection,
  layout, reframe/render, subtitles, hooks, watermark, thumbnails, plus the
  real CLI full pipeline via stub_env.
- dashboard/e2e (19 Playwright specs): route-interception state machine
  covering every dashboard flow; one real-backend spec left test.fixme.
- Foundation: tests/e2e/conftest.py (state isolation, no-network guard, ffmpeg
  media factory, disk-seeded jobs), FakePopen worker harness, child-process
  stub_env, architecture-consistent fixtures.
- CI: unit + backend-e2e + dashboard-e2e jobs in the python+node container;
  ffmpeg + Playwright installed in-job; no setup-node/cache (act runner).

Verified: unit 790 passed; API E2E 209 passed; pipeline E2E 136 passed;
Playwright 19 passed / 1 skipped.
2026-10-04 22:12:21 +01:00
89 changed files with 7407 additions and 1191 deletions

View file

@ -5,43 +5,82 @@ on:
branches: [main]
pull_request:
env:
PYTHONHASHSEED: "0"
TZ: UTC
PIP_DISABLE_PIP_VERSION_CHECK: "1"
jobs:
backend-tests:
# Fast unit suite. No ffmpeg, no ML stack.
unit:
runs-on: ubuntu-latest
timeout-minutes: 15
# The Forgejo runner cannot provision Python 3.11 via actions/setup-python
# ("Version 3.11 was not found in the local cache"), so the job runs inside
# a container that already has Python 3.11. It must also ship Node and git:
# ("Version 3.11 was not found in the local cache"), so every job runs in a
# container that already has Python 3.11. It must also ship Node and git:
# the runner executes JS actions (actions/checkout) by invoking `node`
# inside the job container, so a python-only image fails at checkout.
# inside the job container.
container: nikolaik/python-nodejs:python3.11-nodejs20
steps:
- uses: actions/checkout@v4
# Shared thin test environment (see requirements-test.txt): everything the
# collected tests import at module level, WITHOUT the heavy ML stack
# (torch/ultralytics/mediapipe/faster-whisper), which the pipeline modules
# import lazily behind their feature gates.
# scenedetect (in requirements-test.txt) pulls the full opencv-python,
# whose cv2 binary links libGL.so.1 — absent from the base image. The
# pipeline modules the unit tests import need it at import time.
- name: Install opencv system libs
run: apt-get update -qq && apt-get install -y -qq --no-install-recommends libgl1
- name: Install test dependencies
run: pip install -r requirements-test.txt
- name: Run tests
run: pytest tests/ -v
- name: Run unit tests
# Exclude the E2E tree from *collection*: `-m "not e2e"` only filters
# execution, but pytest still imports every module to collect it, and
# the pipeline E2E modules import the pipeline (tqdm/scenedetect/ML),
# which would pull in fixtures the unit suite does not exercise.
run: pytest tests/ --ignore=tests/e2e -m "not e2e" -q
frontend-build:
# Backend E2E: API + pipeline. ffmpeg/ffprobe must be installed in-job.
# requirements-test.txt already carries pytest-asyncio/asgi-lifespan/
# pytest-timeout and the pure-Python scene engine. API and pipeline run as
# separate processes so the pipeline tests' fake `clipwright.pipeline.main`
# can never leak into the API process. No ML stack: detectors are stubbed,
# only ffmpeg is real.
backend-e2e:
runs-on: ubuntu-latest
# Same reason as backend-tests: the Forgejo runner cannot use
# actions/setup-node's Node download + GitHub artifact-cache service (both
# time out against the act runner: "connect ETIMEDOUT ...:41759"), and
# actions/setup-python cannot provision 3.11 either. This container already
# ships Node 20 + npm + git, so actions/checkout works and setup-node is
# dropped entirely.
timeout-minutes: 30
container: nikolaik/python-nodejs:python3.11-nodejs20
steps:
- uses: actions/checkout@v4
- name: Install ffmpeg
run: apt-get update -qq && apt-get install -y -qq --no-install-recommends ffmpeg && ffmpeg -version | head -1
- name: Install test dependencies
run: pip install -r requirements-test.txt
- name: Run API E2E
run: pytest tests/e2e/api -m e2e -q --timeout=120
- name: Run pipeline E2E (non-ML)
run: pytest tests/e2e/pipeline -m "e2e and not ml" -q --timeout=120
# Dashboard E2E (Playwright). The container already ships Node 20 + npm + git,
# so actions/setup-node and actions/cache are deliberately NOT used (their
# Node download / cache endpoints time out against the act runner:
# "connect ETIMEDOUT 172.27.0.4:41759"). Playwright is retry-free by config;
# install browsers fresh each run.
dashboard-e2e:
runs-on: ubuntu-latest
timeout-minutes: 30
container: nikolaik/python-nodejs:python3.11-nodejs20
defaults:
run:
working-directory: dashboard
steps:
- uses: actions/checkout@v4
- name: Install ffmpeg (E2E media fixture)
run: apt-get update -qq && apt-get install -y -qq --no-install-recommends ffmpeg
- name: Install dependencies
run: npm ci
- name: Install Playwright browsers
run: npx playwright install --with-deps chromium
- name: Lint
run: npm run lint
- name: Build
run: npm run build
- name: Browser E2E
run: npm run test:e2e

View file

@ -1,42 +0,0 @@
name: Publish CLI to PyPI
# Push a tag cli-vX.Y.Z (matching `version` in cli/pyproject.toml) to publish
# the `clipwright` CLI. Uses PyPI Trusted Publishing (OIDC): no API token.
on:
push:
tags:
- "cli-v*.*.*"
workflow_dispatch:
jobs:
publish:
runs-on: ubuntu-latest
environment: pypi
permissions:
id-token: write
contents: read
defaults:
run:
working-directory: cli
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Tag matches cli/pyproject.toml version
if: startsWith(github.ref, 'refs/tags/')
run: |
v=$(python -c "import tomllib;print(tomllib.load(open('pyproject.toml','rb'))['project']['version'])")
[ "cli-v$v" = "${GITHUB_REF_NAME}" ] || { echo "tag ${GITHUB_REF_NAME} != cli-v$v"; exit 1; }
- name: Build
run: |
pip install build
python -m build
- name: Smoke test the wheel
run: |
pip install dist/*.whl
clipwright --help
- name: Publish
uses: pypa/gh-action-pypi-publish@release/v1
with:
packages-dir: cli/dist/

View file

@ -111,7 +111,6 @@ clipwright/ # Python backend package
integrations/ # Postiz, YouTube, file hosts
tools/ # local verification scripts (python -m clipwright.tools.verify_hooks)
dashboard/ # React + Vite dashboard (its own build)
cli/ # published `clipwright` HTTP client (own pyproject)
tests/ # pytest suite (pythonpath = ["."])
fonts/ assets/ # shared runtime resources (kept at repo root)
```

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

View file

@ -1,55 +0,0 @@
# Clipwright CLI
Clip long videos into vertical 9:16 shorts from the terminal. Zero
dependencies; talks to the same self-hosted REST API the dashboard uses.
```bash
pip install clipwright # or: uvx clipwright / pipx run clipwright
```
## Use it against your own instance
Clipwright is free, open source under MIT and self-hosted with Docker. There is
no hosted edition and no paid plan, so there is no account to create. Point the
CLI at your instance:
```bash
export CLIPWRIGHT_API_URL=http://localhost:8000
clipwright process "https://youtube.com/watch?v=..." --wait
clipwright clips <job_id>
clipwright publish <job_id> 0 --platforms tiktok,youtube
clipwright quota
```
Self-hosted instances are open by default and need no API key. You do need a
Google Gemini key: put it in the server's environment, or send it per call as an
`X-Gemini-Key` header. If you put your own instance behind a key, the CLI sends
`CLIPWRIGHT_API_KEY` (`clw_...`) as a bearer token.
## Publish through Postiz
Publishing goes through your self-hosted Postiz instance. Pass the base URL and
API key with `--postiz-url` / `--postiz-key`, or set `POSTIZ_URL` /
`POSTIZ_API_KEY`; the CLI forwards them to the server as `X-Postiz-Url` /
`X-Postiz-Key`.
```bash
clipwright publish <job_id> 0 --platforms tiktok,youtube \
--postiz-url https://postiz.example.com --postiz-key <key>
```
## Quota
`clipwright quota` prints the instance config it reads from `GET /api/config`:
the job-retention window, whether YouTube-URL ingest is enabled, and the
local-LLM setting. A self-hosted instance has no minute quota, so none is
reported.
## Pipelines and webhooks
Prefer the webhook to `--wait`: pass `--webhook` and `--webhook-secret` and
Clipwright POSTs once (HMAC-signed, `X-Clipwright-Signature: sha256=<hex>`) when
the job ends, with each clip's title and `video_url`. Set `PUBLIC_API_URL` on
the server so those links are absolute; otherwise they are relative to your
instance.

View file

@ -1,251 +0,0 @@
"""Clipwright CLI: clip long videos into vertical shorts from the terminal.
Zero dependencies by design so `uvx clipwright` and `pipx run clipwright`
start instantly. Talks to the same REST API the dashboard uses; nothing here
can drift from what the app actually does.
Auth and target come from the environment:
CLIPWRIGHT_API_KEY clw_... key for a deploy that requires one (optional;
a self-hosted instance needs none)
CLIPWRIGHT_API_URL defaults to http://localhost:8000 for a self-hosted
instance, where no key is needed.
Publishing goes through Postiz. The base URL and API key come from the
--postiz-url / --postiz-key flags, then POSTIZ_URL / POSTIZ_API_KEY.
"""
import argparse
import json
import os
import sys
import time
import urllib.error
import urllib.request
DEFAULT_API = "http://localhost:8000"
POLL_SECONDS = 10
def _base():
return os.environ.get("CLIPWRIGHT_API_URL", DEFAULT_API).rstrip("/")
def _request(method, path, body=None, extra_headers=None):
headers = {"Accept": "application/json"}
if extra_headers:
headers.update(extra_headers)
key = os.environ.get("CLIPWRIGHT_API_KEY")
if key:
headers["Authorization"] = f"Bearer {key}"
data = None
if body is not None:
data = json.dumps(body).encode()
headers["Content-Type"] = "application/json"
req = urllib.request.Request(_base() + path, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(req, timeout=120) as resp:
return resp.status, json.loads(resp.read().decode() or "{}")
except urllib.error.HTTPError as e:
try:
payload = json.loads(e.read().decode() or "{}")
except Exception:
payload = {"detail": str(e.reason)}
return e.code, payload
except urllib.error.URLError as e:
print(f"error: cannot reach {_base()} ({e.reason})", file=sys.stderr)
sys.exit(2)
def _die(status, payload):
detail = payload.get("detail", payload) if isinstance(payload, dict) else payload
if not isinstance(detail, str):
detail = json.dumps(detail)
print(f"error ({status}): {detail}", file=sys.stderr)
sys.exit(1)
def _absolutize(url):
if url and url.startswith("/"):
return _base() + url
return url
def _print_clips(result):
clips = (result or {}).get("clips") or []
if not clips:
print("no clips in result")
return
for i, clip in enumerate(clips):
title = clip.get("title") or clip.get("video_title_for_youtube_short") or f"clip {i}"
print(f"[{i}] {title}")
print(f" {_absolutize(clip.get('video_url') or '')}")
def cmd_process(args):
body = {"url": args.url, "acknowledged": True}
if args.layouts:
body["layouts"] = args.layouts
if args.format:
body["output_format"] = args.format
if args.webhook:
body["webhook_url"] = args.webhook
if args.webhook_secret:
body["webhook_secret"] = args.webhook_secret
status, payload = _request("POST", "/api/process", body)
if status >= 400:
_die(status, payload)
job_id = payload.get("job_id")
if args.json and not args.wait:
print(json.dumps(payload))
return
print(f"job queued: {job_id}")
if args.wait:
_watch(job_id, as_json=args.json)
else:
print(f"follow it with: clipwright status {job_id} --watch")
def _watch(job_id, as_json=False):
seen_logs = 0
while True:
status, payload = _request("GET", f"/api/status/{job_id}")
if status >= 400:
_die(status, payload)
logs = payload.get("logs") or []
for line in logs[seen_logs:]:
print(f" {line}")
seen_logs = len(logs)
state = payload.get("status")
if state == "completed":
if as_json:
print(json.dumps(payload.get("result") or {}))
else:
print("completed:")
_print_clips(payload.get("result"))
return
if state == "failed":
print("job failed; last log lines above", file=sys.stderr)
sys.exit(1)
time.sleep(POLL_SECONDS)
def cmd_status(args):
if args.watch:
_watch(args.job_id, as_json=args.json)
return
status, payload = _request("GET", f"/api/status/{args.job_id}")
if status >= 400:
_die(status, payload)
if args.json:
print(json.dumps(payload))
return
print(f"status: {payload.get('status')}")
logs = payload.get("logs") or []
if logs:
print(f"last log: {logs[-1]}")
def cmd_clips(args):
status, payload = _request("GET", f"/api/status/{args.job_id}")
if status >= 400:
_die(status, payload)
if payload.get("status") != "completed":
print(f"job is {payload.get('status')}, no clips yet", file=sys.stderr)
sys.exit(1)
if args.json:
print(json.dumps((payload.get("result") or {}).get("clips") or []))
return
_print_clips(payload.get("result"))
def cmd_quota(args):
# Self-host has no minute quota: the cloud account/quota router is gone.
# Report the instance config instead so the command stays useful.
status, payload = _request("GET", "/api/config")
if status >= 400:
_die(status, payload)
if args.json:
print(json.dumps(payload))
return
print("self-hosted: no minute quota")
print(f"job retention: {payload.get('jobRetentionSeconds')}s")
print(f"youtube url: {'enabled' if payload.get('youtubeUrlEnabled') else 'disabled'}")
local_llm = payload.get("localLlm")
if local_llm:
print(f"local llm: {local_llm}")
def cmd_publish(args):
body = {
"job_id": args.job_id,
"clip_index": args.clip_index,
"platforms": [p.strip() for p in args.platforms.split(",") if p.strip()],
}
if args.title:
body["title"] = args.title
if args.schedule:
body["scheduled_date"] = args.schedule
if args.timezone:
body["timezone"] = args.timezone
postiz_key = args.postiz_key or os.environ.get("POSTIZ_API_KEY")
if not postiz_key:
print("error: no Postiz API key: pass --postiz-key or set POSTIZ_API_KEY",
file=sys.stderr)
sys.exit(1)
postiz_url = (args.postiz_url or os.environ.get("POSTIZ_URL") or "").rstrip("/")
headers = {"X-Postiz-Key": postiz_key}
if postiz_url:
headers["X-Postiz-Url"] = postiz_url
status, payload = _request("POST", "/api/postiz/post", body,
extra_headers=headers)
if status >= 400:
_die(status, payload)
print(json.dumps(payload) if args.json else f"publishing: {payload}")
def main(argv=None):
parser = argparse.ArgumentParser(
prog="clipwright",
description="Clip long videos into vertical shorts via the Clipwright API.",
)
parser.add_argument("--json", action="store_true", help="raw JSON output")
sub = parser.add_subparsers(dest="command", required=True)
p = sub.add_parser("process", help="submit a video URL for clipping")
p.add_argument("url", help="YouTube or direct video URL")
p.add_argument("--layouts", help="comma list: auto,split,screencast,speaker_cut,punch_in")
p.add_argument("--format", help="output format, e.g. 1080p")
p.add_argument("--webhook", help="webhook URL fired once when the job ends")
p.add_argument("--webhook-secret", help="HMAC secret for X-Clipwright-Signature")
p.add_argument("--wait", action="store_true", help="stream logs until the job ends")
p.set_defaults(func=cmd_process)
p = sub.add_parser("status", help="job status and last log line")
p.add_argument("job_id")
p.add_argument("--watch", action="store_true", help="stream logs until the job ends")
p.set_defaults(func=cmd_status)
p = sub.add_parser("clips", help="list finished clips with links")
p.add_argument("job_id")
p.set_defaults(func=cmd_clips)
p = sub.add_parser("quota", help="instance config (self-host has no quota)")
p.set_defaults(func=cmd_quota)
p = sub.add_parser("publish", help="post or schedule one clip through Postiz")
p.add_argument("job_id")
p.add_argument("clip_index", type=int)
p.add_argument("--platforms", required=True, help="comma list: tiktok,instagram,youtube")
p.add_argument("--title")
p.add_argument("--schedule", help="ISO datetime for scheduled posting")
p.add_argument("--timezone", help="IANA timezone for --schedule")
p.add_argument("--postiz-url", help="Postiz base URL (env POSTIZ_URL)")
p.add_argument("--postiz-key", help="Postiz API key (env POSTIZ_API_KEY)")
p.set_defaults(func=cmd_publish)
args = parser.parse_args(argv)
args.func(args)
if __name__ == "__main__":
main()

View file

@ -1,30 +0,0 @@
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
[project]
name = "clipwright"
version = "0.1.0"
description = "CLI for Clipwright: clip long videos into vertical shorts and publish them, from the terminal"
readme = "README.md"
requires-python = ">=3.9"
license = { text = "MIT" }
authors = [{ name = "Clipwright" }]
keywords = ["video", "clips", "shorts", "ai", "tiktok", "youtube-shorts", "cli"]
classifiers = [
"Environment :: Console",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Topic :: Multimedia :: Video",
]
[project.urls]
Homepage = "https://git.pbento.pt/pedro-bento/clipwright"
Source = "https://git.pbento.pt/pedro-bento/clipwright"
Documentation = "https://git.pbento.pt/pedro-bento/clipwright/tree/main/cli"
[project.scripts]
clipwright = "clipwright_cli:main"
[tool.setuptools]
py-modules = ["clipwright_cli"]

View file

@ -28,7 +28,6 @@ from pydantic import BaseModel
import httpx
from clipwright.media import recut
from clipwright.layouts import layout_ranges
from clipwright.media import watermarked
from clipwright.api import media_auth
from clipwright.integrations import postiz
from clipwright.core.paths import REPO_ROOT
@ -332,13 +331,10 @@ def _canonical_clip_file(output_dir, base_name, index):
# captioned hooks; the bare recut_/hooked_/hook_ patterns cover
# derivations that shipped uncaptioned (hook_ is the legacy manual-
# hook prefix, kept so old jobs still resolve).
# wm_*{clean} is the free plan's marked copy of any of those (or of
# the clean file itself: the * matches nothing), written last.
derived = (glob.glob(os.path.join(output_dir, f"subtitled_*_{clean}"))
+ glob.glob(os.path.join(output_dir, f"recut_*_{clean}"))
+ glob.glob(os.path.join(output_dir, f"hooked_*_{clean}"))
+ glob.glob(os.path.join(output_dir, f"hook_{clean}"))
+ glob.glob(os.path.join(output_dir, f"wm_*{clean}")))
+ glob.glob(os.path.join(output_dir, f"hook_{clean}")))
except Exception:
derived = []
if not derived:
@ -369,8 +365,8 @@ def _clips_actually_rendered(job_id, output_dir, base_name, clips):
Trust the disk, not the promise.
"""
# main.py announces the file it actually finished for each clip
# (CLIP_READY, printed after the whole reframe/watermark/hook/caption
# chain). Prefer it over rebuilding the name: the marker is what the file
# (CLIP_READY, printed after the whole reframe/hook/caption chain).
# Prefer it over rebuilding the name: the marker is what the file
# IS, _canonical_clip_file is a guess from the naming convention.
ready_files = (jobs.get(job_id) or {}).get('ready_files') or {}
kept = []
@ -391,21 +387,6 @@ def _clips_actually_rendered(job_id, output_dir, base_name, clips):
return kept, len(clips) - len(kept)
def _strip_watermark_copy(output_dir, filename):
"""``wm_<final>`` -> ``<final>`` when the clean twin is on disk.
The free plan serves a marked copy of the final file and keeps the clean
one next to it (see the ``watermarked`` module); every derivation starts
from the clean one, so the mark is always the outermost layer to strip.
Same fail-safe contract as the other walk-backs: unchanged when there is
nothing to strip or the twin is gone."""
if watermarked.is_marked(filename):
clean = watermarked.clean_name(filename)
if os.path.exists(os.path.join(output_dir, clean)):
return clean
return filename
def _strip_burned_captions(output_dir, filename):
"""Walk ``subtitled_<ts>_`` prefixes back to the file without burned captions.
@ -413,7 +394,6 @@ def _strip_burned_captions(output_dir, filename):
underlying file is gone, e.g. a library restore that only kept the current
version).
"""
filename = _strip_watermark_copy(output_dir, filename)
while True:
m = re.match(r'^subtitled_\d+_(.+)$', filename)
if not m or not os.path.exists(os.path.join(output_dir, m.group(1))):
@ -426,7 +406,6 @@ def _strip_burned_hook(output_dir, filename):
without a burned hook. Same fail-safe contract as _strip_burned_captions:
the name is returned unchanged when there is nothing to strip or the
underlying file is gone."""
filename = _strip_watermark_copy(output_dir, filename)
while True:
m = re.match(r'^(?:hooked_\d+_|hook_)(.+)$', filename)
if not m or not os.path.exists(os.path.join(output_dir, m.group(1))):
@ -435,18 +414,13 @@ def _strip_burned_hook(output_dir, filename):
async def _deliver(request, job_id, filename):
"""Self-host shim: clips are always served clean (no watermark)."""
"""Self-host shim: clips are always served as written (no mark applied)."""
return filename
def _media_guard(path: str) -> bool:
"""``/videos`` allowlist: deliverable types only (media_auth)."""
if not media_auth.is_servable(path):
return False
job_id, _, filename = path.replace("\\", "/").strip("/").partition("/")
if not filename or not watermarked.is_clean_deliverable(filename):
return True
return not watermarked.job_is_marked(os.path.join(OUTPUT_DIR, job_id))
return media_auth.is_servable(path)
def _reapply_captions(job_id, clip_index, video_path):
@ -2906,8 +2880,7 @@ async def get_clip_edl(job_id: str, clip_index: int, request: Request):
"canonical_range": canonical_range,
"duration": total,
"current_file": current_file,
"has_captions": bool(re.match(r'^subtitled_\d+_',
watermarked.clean_name(current_file))),
"has_captions": bool(re.match(r'^subtitled_\d+_', current_file)),
"words": words_out,
"source": {
"available": bool(source_path),
@ -3794,8 +3767,8 @@ async def remove_subtitles(req: RemoveSubtitlesRequest, request: Request):
raise HTTPException(status_code=404,
detail="The original clip is no longer available.")
# Free plan: the un-captioned file is served through its wm_ copy, which
# is reused when the clip shipped that way (no encode).
# The un-captioned file is served as-is; captions were stripped above so
# a later restyle does not stack a second caption layer.
filename = await _deliver(request, req.job_id, filename)
new_url = f"/videos/{req.job_id}/{filename}"
if req.clip_index < len(job.get('result', {}).get('clips', [])):

View file

@ -1,7 +1,7 @@
"""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.
resources (``fonts/``, ``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.
@ -17,10 +17,8 @@ PACKAGE_DIR = Path(__file__).resolve().parent.parent
REPO_ROOT = PACKAGE_DIR.parent
FONTS_DIR = REPO_ROOT / "fonts"
ASSETS_DIR = REPO_ROOT / "assets"
__all__ = [
"REPO_ROOT",
"FONTS_DIR",
"ASSETS_DIR",
]

View file

@ -341,7 +341,7 @@ def _run(cmd):
def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
force_strategy=None, crop_overrides=None, watermark=False):
force_strategy=None, crop_overrides=None):
"""Full v2 reframe of one clip. Raises on failure (caller falls back).
``content_ranges`` comes from screencast_layout.detect_content_ranges() on
@ -357,10 +357,6 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
listed keep the automatic camera, so correcting one bad shot never disturbs
the ones the tracker got right. Applied AFTER force_strategy: a per-scene
hand position always beats the whole-clip choice for the scenes it names.
``watermark`` overlays the free-plan mark (main.watermark_filter) in every
segment's own encode, instead of main.apply_watermark re-encoding the
finished clip once more.
"""
from clipwright.pipeline import main as m
content_ranges = content_ranges or []
@ -525,10 +521,6 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
ranges = scene_frame_ranges(scene_boundaries, strategies, len(xs))
if not ranges:
raise RuntimeError("no usable scene ranges")
logo = m.watermark_logo_path() if watermark else None
if logo and not os.path.exists(logo):
print(f" ⚠️ Watermark asset missing ({logo}); clip kept unmarked.")
logo = None
workdir = tempfile.mkdtemp(prefix="reframe_v2_")
segments = []
@ -584,10 +576,6 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
)
inputs, out_label = ["-i", input_video], "[v]"
if logo:
inputs += ["-i", logo]
graph += ";" + m.watermark_filter(out_w, out_h, video="[v]", out="[vw]")
out_label = "[vw]"
_run([
"ffmpeg", "-y", "-loglevel", "error",
"-ss", f"{ss:.4f}", "-t", f"{dur:.4f}", *inputs,

View file

@ -4,7 +4,7 @@ turned into a rendered clip.
The pure helpers here are standard-library only (plus ffmpeg_utils, which is
also light) so the module imports in the thin CI environment; everything heavy
(reframing, watermark, auto-captions live in main.py) is imported lazily and
(reframing, auto-captions live in main.py) is imported lazily and
only on the paths that need it.
Two render paths:
@ -243,8 +243,8 @@ def run_cut_concat(input_path, segments, out_path, workdir, runner=None):
return out_path
# Same ceiling as apply_watermark's: a hung ffmpeg must not pin the executor
# thread (and the caller's quota reservation) until a server restart.
# A hung ffmpeg must not pin the executor thread (and the caller's quota
# reservation) until a server restart.
FFMPEG_TIMEOUT_SECONDS = 1800
@ -262,18 +262,16 @@ def _run_ffmpeg(command):
def perform_recut(*, input_path, segments, output_dir, clean_name,
reframe=False, output_format="auto", watermark=False,
reframe=False, output_format="auto",
captions_transcript=None, force_strategy=None,
crop_overrides=None, runner=None, renderer=None,
watermarker=None, captioner=None):
captioner=None):
"""Render a recut clip. Returns (served_filename, clean_filename).
- ``input_path``/``segments``: the file to cut from and the times ON THAT
FILE (the caller rebases for the fast path).
- ``reframe``: run the reframe engine on the joined cut (source path only —
the canonical file is already framed).
- ``watermark``: re-apply the free-plan watermark (source path only — the
canonical file already carries it).
- ``captions_transcript``: a clip-relative transcript (see
``virtual_transcript``); when given and non-empty, captions are burned
LAST onto a ``subtitled_<ts>_`` derivative, preserving the invariant
@ -283,9 +281,9 @@ def perform_recut(*, input_path, segments, output_dir, clean_name,
the same reason as ``reframe``: the canonical file is already cropped, so
its framing can no longer be changed.
The renderer/watermarker/captioner hooks default to main.py's
implementations, imported lazily so this module stays importable without
the ML stack; tests inject fakes.
The renderer/captioner hooks default to main.py's implementations, imported
lazily so this module stays importable without the ML stack; tests inject
fakes.
"""
# The uuid token keeps two same-second saves of one clip from writing (and
# then serving) the same filename; the timestamp keeps "newest derived
@ -320,9 +318,6 @@ def perform_recut(*, input_path, segments, output_dir, clean_name,
(r["start"], r["end"], r["layout"])
for r in layout_ranges.remap(layout_ranges.read(input_path), segments)])
if watermark:
(watermarker or _main_attr("apply_watermark"))(out_path)
served_name = out_name
if captions_transcript and captions_transcript.get("segments"):
caption = captioner or _main_attr("auto_caption_clip")

View file

@ -612,7 +612,7 @@ def _generate_one(client, concept, reference_images, out_path, burn_text):
if burn_text:
pos = concept['text_position']
share = "45% of the width" if pos in ("left", "right") else "40% of the height"
text_rule = ("Do NOT render any text, letters, numbers, captions, logos or watermarks anywhere "
text_rule = ("Do NOT render any text, letters, numbers, captions, logos or branding marks anywhere "
f"in the image. The {pos} {share} of the frame must be clean, simple negative space "
"(plain, dark or softly blurred, no objects, no detail): a headline will be placed "
"there afterwards. Put the subject and every object in the remaining part.")
@ -626,7 +626,7 @@ def _generate_one(client, concept, reference_images, out_path, burn_text):
{text_rule}
Style: high contrast, saturated colours, crisp subject separation, cinematic lighting, sharp focus on the subject, readable at 168x94 pixels. No clutter, no small details, no borders, no watermark."""
Style: high contrast, saturated colours, crisp subject separation, cinematic lighting, sharp focus on the subject, readable at 168x94 pixels. No clutter, no small details, no borders, no branding mark."""
if reference_images:
prompt += ("\nIDENTITY: the person in the provided photo must appear as EXACTLY the same real person: "
"identical face shape, skin, eyes, glasses, facial hair, hairstyle and hair length, age and "

View file

@ -1,79 +0,0 @@
"""Names for watermarked delivery copies.
Every file the pipeline and the clip editor write is CLEAN. When a job is
rendered with the mark (``WATERMARK=1``) the served name is a copy of the final
one with the mark burned in, ``wm_<final>``, kept next to it (and in R2 beside
it). Self-host serves clips clean (``app._deliver`` is a no-op), but the
``wm_`` prefix and the ``.marked`` job marker are still what the rest of the
app keys off:
* the walk-backs that find the editable master under a served name
(``app._strip_burned_captions`` and friends) treat the ``wm_`` prefix as the
outermost layer, and the ``/videos`` guard refuses the clean twins of a
marked job so a marked copy cannot be fetched by stripping the prefix from a
URL.
Before 30-sep-2026 the mark was burned into the canonical reframe, so the
only way to lose it was to run the whole job again: the first cancellation
for "clip quality" was a user who paid 15 minutes after their first job and
found the mark still there on every download and every restyle.
No imports beyond the standard library on purpose: ``main.py`` and ``app.py``
use it and only the first of those has ffmpeg.
"""
import os
import re
PREFIX = "wm_"
# The dotfile ``main.py`` writes in a job directory rendered for the free plan.
# Read by the ``/videos`` guard (a dotfile is never servable itself); removed
# when the library is unmarked after an upgrade.
MARKER_FILE = ".marked"
_VIDEO_EXTENSIONS = frozenset({".mp4", ".webm", ".mov", ".m4v", ".mkv", ".ogv"})
# Names that are a deliverable clip or one of its derivatives. The editor's
# own scratch files (``temp_preview_<i>.mp4``, ``temp_scene_*.jpg``) are not
# clips and stay servable on a marked job.
_DELIVERABLE_RE = re.compile(
r'^(?:subtitled_\d+_|hooked_\d+_|hook_|recut_|edited_|translated_)|_clip_\d+\.[A-Za-z0-9]+$'
)
def is_marked(filename: str) -> bool:
return bool(filename) and os.path.basename(filename).startswith(PREFIX)
def marked_name(filename: str) -> str:
"""``wm_<filename>``; idempotent."""
base = os.path.basename(filename)
return base if base.startswith(PREFIX) else PREFIX + base
def clean_name(filename: str) -> str:
"""The clean twin of a served name (the name itself when not marked)."""
base = os.path.basename(filename)
return base[len(PREFIX):] if base.startswith(PREFIX) else base
def is_clean_deliverable(filename: str) -> bool:
"""True for a clip file (canonical or derived) that carries no mark."""
base = os.path.basename(filename or "")
if not base or base.startswith(PREFIX):
return False
if os.path.splitext(base)[1].lower() not in _VIDEO_EXTENSIONS:
return False
return bool(_DELIVERABLE_RE.search(base))
def job_is_marked(job_dir: str) -> bool:
return os.path.exists(os.path.join(job_dir, MARKER_FILE))
def mark_job(job_dir: str) -> None:
try:
with open(os.path.join(job_dir, MARKER_FILE), "w") as f:
f.write("1")
except OSError:
pass

View file

@ -25,12 +25,11 @@ from clipwright.pipeline import gemini_worker
from clipwright.pipeline import hook_grounding
from clipwright.layouts import layout_picker
from clipwright.pipeline import llm_backend
from clipwright.core.paths import ASSETS_DIR
from clipwright.pipeline.clip_selection import (build_transcript_windows, clip_count_targets,
clip_duration_bounds, dedupe_overlapping,
score_batches, shortlist_target,
snap_clip_to_words, trim_to_best)
from clipwright.media.ffmpeg_utils import (video_encode_args, cut_clip, QUALITY,
from clipwright.media.ffmpeg_utils import (video_encode_args, cut_clip,
QUALITY_FAST, METADATA_SCRUB)
from dotenv import load_dotenv
import json
@ -1301,135 +1300,23 @@ def auto_hook_clip(clip_path, clip, captions=None):
def render_clip(input_video, final_output_video, output_format="auto",
force_strategy=None, crop_overrides=None, watermark=False):
force_strategy=None, crop_overrides=None):
"""Route a cut clip through the right renderer for the chosen output format.
vertical/auto -> 9:16 reframe, square -> 1:1 reframe, horizontal -> keep.
``force_strategy`` (e.g. 'WIDE'/'TRACK') pins every scene's layout — the
clip editor's whole-clip framing override. ``crop_overrides`` positions
individual scenes by hand (the per-scene reframing editor) and wins over
``force_strategy`` for the scenes it names.
``watermark`` burns the free-plan mark into the result: inside the reframe
encode on the v2 path, as a separate pass (apply_watermark) otherwise."""
``force_strategy`` for the scenes it names."""
if output_format == "horizontal":
ok = finalize_clip_passthrough(input_video, final_output_video)
if ok and watermark:
apply_watermark(final_output_video)
return ok
return finalize_clip_passthrough(input_video, final_output_video)
aspect = 1.0 if output_format == "square" else ASPECT_RATIO
return process_video_to_vertical(input_video, final_output_video, aspect_ratio=aspect,
force_strategy=force_strategy,
crop_overrides=crop_overrides,
watermark=watermark)
# Watermark geometry, as fractions of the clip width/height.
#
# Vertical placement is the whole point: the top and bottom strips of a 9:16
# clip are either black bars or blurred filler (GENERAL layout), so a mark up
# there is cropped away without touching a single pixel of real footage. At 40%
# of the height it sits inside the content band — a 16:9 source letterboxed
# into 9:16 spans roughly 34%-66% — so removing the mark means cutting into the
# picture. Left-aligned, like OpusClip's.
WATERMARK_WIDTH_RATIO = 0.30
WATERMARK_MARGIN_RATIO = 0.05
WATERMARK_Y_RATIO = 0.40
WATERMARK_OPACITY = 0.85
def watermark_logo_path():
return str(ASSETS_DIR / "watermark.png")
def watermark_filter(vw, vh, video="[0:v]", logo="[1:v]", out=""):
"""filter_complex chain overlaying the logo input on a vw x vh video."""
wm_w = max(80, int(vw * WATERMARK_WIDTH_RATIO))
x = int(vw * WATERMARK_MARGIN_RATIO)
y = int(vh * WATERMARK_Y_RATIO)
return (
f"{logo}scale={wm_w}:-1,format=rgba,"
f"colorchannelmixer=aa={WATERMARK_OPACITY}[wm];"
f"{video}[wm]overlay=x={x}:y={y}{out}"
)
def apply_watermark(video_path, output_path=None):
"""Burn the Clipwright watermark into a finished clip (free plan).
One re-encode pass over the final file so every output format (TRACK,
GENERAL, horizontal passthrough) gets the mark. In place by default; with
``output_path`` the source stays untouched and the marked copy is written
there, which is how the pipeline keeps the clean file next to the served
one (see ``mark_delivery``).
"""
logo_path = watermark_logo_path()
if not os.path.exists(logo_path):
print(f" ⚠️ Watermark asset missing ({logo_path}); clip kept unmarked.")
return False
# Scale the lockup from the clip's real width: overlay can't read the other
# input's size, and computing it here avoids the deprecated scale2ref.
try:
probe = subprocess.check_output(
["ffprobe", "-v", "error", "-select_streams", "v:0",
"-show_entries", "stream=width,height", "-of", "csv=p=0:s=x", video_path],
stderr=subprocess.STDOUT, timeout=60,
).decode().strip().split("x")
vw, vh = int(probe[0]), int(probe[1])
except Exception as e:
print(f" ⚠️ Could not probe clip for watermark ({e}); clip kept unmarked.")
return False
filt = watermark_filter(vw, vh)
tmp_path = (output_path or video_path) + ".wm.mp4"
cmd = ["ffmpeg", "-y", "-i", video_path, "-i", logo_path,
"-filter_complex", filt,
*video_encode_args(QUALITY), "-c:a", "copy", *METADATA_SCRUB,
"-movflags", "+faststart", tmp_path]
result = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
timeout=1800)
if result.returncode == 0 and os.path.exists(tmp_path):
os.replace(tmp_path, output_path or video_path)
return True
err = (result.stderr or b"").decode(errors="ignore")[-300:]
print(f" ⚠️ Watermark pass failed (clip kept unmarked): {err}")
if os.path.exists(tmp_path):
os.remove(tmp_path)
return False
def mark_delivery(final_path, marker=None):
"""The free-plan copy of a finished clip to serve: ``wm_<final>`` next to it.
The clean ``final_path`` is left as it is. That is the whole point: an
upgrade re-points the clip at the clean twin instead of re-running the
job (``watermarked`` module). An existing copy is reused, so re-choosing
a file the user already had (captions off, hook off) costs no encode.
Returns the marked path, or ``final_path`` itself when the copy could not
be made: the mark must never cost the user the clip (same fail-open rule
apply_watermark has always had).
"""
from clipwright.media import watermarked
out_path = os.path.join(os.path.dirname(final_path),
watermarked.marked_name(final_path))
if os.path.exists(out_path) and os.path.getsize(out_path) > 0:
return out_path
ok = (marker or apply_watermark)(final_path, out_path)
if ok and os.path.exists(out_path):
return out_path
# Still the wm_ name: the /videos guard refuses the clean deliverables of
# a free job, so serving the clean name here would be a clip the user
# cannot play. The copy simply carries no mark.
print(f" ⚠️ Serving {os.path.basename(final_path)} unmarked (copy).")
try:
shutil.copyfile(final_path, out_path)
return out_path
except OSError:
return final_path
crop_overrides=crop_overrides)
def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPECT_RATIO,
force_strategy=None, crop_overrides=None, watermark=False):
force_strategy=None, crop_overrides=None):
"""
Core logic to reframe a horizontal video to a target aspect ratio using
scene detection and Active Speaker Tracking (MediaPipe).
@ -1446,8 +1333,7 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE
t0 = time.time()
result = reframe_v2.render(input_video, final_output_video, aspect_ratio,
force_strategy=force_strategy,
crop_overrides=crop_overrides,
watermark=watermark)
crop_overrides=crop_overrides)
print(f" ⏱️ Reframe v2 total: {time.time() - t0:.1f}s")
return result
except Exception as e:
@ -1642,8 +1528,6 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE
if os.path.exists(leftover):
os.remove(leftover)
if watermark:
apply_watermark(final_output_video)
return True
# --- Transcript checkpoint (survive a redeploy without paying twice) ---------
@ -2398,13 +2282,9 @@ if __name__ == '__main__':
cut_clip(input_video, clip_temp_path, start, end, i + 1)
# Layer order: the canonical reframe stays CLEAN, the hook
# is a derived hooked_ file, captions go last on top of
# whichever is current, and on the free plan the served
# file is a wm_ copy of that final (mark_delivery). The
# mark used to ride the reframe encode, which made it
# permanent: paying could not remove it from clips already
# made. Each worker writes only its own clip dict, so the
# re-dump after the pool is race-free.
# is a derived hooked_ file, and captions go last on top of
# whichever is current. Each worker writes only its own clip
# dict, so the re-dump after the pool is race-free.
success = render_clip(clip_temp_path, clip_final_path, output_format)
if success:
print(f" 🎞️ Clip {i+1} framed")
@ -2437,16 +2317,14 @@ if __name__ == '__main__':
deliver_path, transcript, start, end,
split_ranges=split_ranges)
served = captioned or deliver_path
if os.environ.get("WATERMARK") == "1":
served = mark_delivery(served)
print(f" ✅ Clip {i+1} ready: {clip_final_path}")
# Hand the API the file to actually serve for this clip.
# Without it the status poller guesses the clean reframe
# name, so a job in flight showed every clip stripped of
# its hook and captions until the WHOLE job finished and
# the result got rebuilt through _canonical_clip_file.
# Printed only after the full chain (reframe, watermark,
# hook, captions) so the file is complete when it is
# Printed only after the full chain (reframe, hook,
# captions) so the file is complete when it is
# announced, never one that ffmpeg is still writing.
print(f"CLIP_READY {i} {os.path.basename(served)}")
return success
@ -2460,11 +2338,6 @@ if __name__ == '__main__':
clip_workers = max(int(os.environ.get("CLIP_WORKERS", "6")), 1)
shorts = clips_data['shorts']
failed = []
if os.environ.get("WATERMARK") == "1":
# Tells the /videos guard that the clean twins in this
# directory are not for serving (watermarked.MARKER_FILE).
from clipwright.media import watermarked
watermarked.mark_job(output_dir)
with ThreadPoolExecutor(max_workers=min(clip_workers, len(shorts))) as pool:
# Best clip first: the pool starts work in submission order, so
# the user's first delivered clip is the strongest one instead

2
dashboard/e2e/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
.artifacts/
.test-results/

View file

@ -0,0 +1,389 @@
// State-machine route interception for the dashboard's backend.
//
// Every spec runs against the built dashboard with **zero unmocked network**:
// this fixture installs a catch-all that aborts anything off-origin, then the
// specific /api, /videos and /thumbnails handlers that answer with deterministic
// fixtures. The only "state" is a counter per endpoint, which is enough to model
// queued -> processing -> completed without a single timer or sleep in a spec —
// the app's own 2s poll drives it, and Playwright's auto-wait absorbs the gap.
export const BASE_ORIGIN = 'http://127.0.0.1:4173';
export const JOB_ID = '11111111-1111-4111-8111-111111111111';
// 1x1 transparent PNG, decoded by the browser at route.fulfill time.
const TINY_PNG =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M8AAAMBAQDJ/pLvAAAAAElFTkSuQmCC';
export function defaultClips() {
return [
{
video_url: `/videos/${JOB_ID}/clip_1.mp4`,
video_title_for_youtube_short: 'First viral clip',
video_description_for_tiktok: 'TikTok caption one #viral #shorts',
video_description_for_instagram: 'Instagram caption one #reels',
start: 0,
end: 30,
predicted_score: 91,
why: 'Opens on a strong claim the rest of the clip pays off.',
auto_hook: { text: 'Watch this' },
},
{
video_url: `/videos/${JOB_ID}/clip_2.mp4`,
video_title_for_youtube_short: 'Second viral clip',
video_description_for_tiktok: 'TikTok caption two #viral',
video_description_for_instagram: 'Instagram caption two #reels',
start: 40,
end: 70,
predicted_score: 77,
why: 'A clean story beat with a natural ending.',
auto_hook: null,
},
];
}
export function defaultResults() {
return {
clips: defaultClips(),
cost_analysis: { input_tokens: 1200, output_tokens: 400, total_cost: 0.00123 },
};
}
export function defaultEdl() {
return {
job_id: JOB_ID,
clip_index: 0,
title: 'First viral clip',
segments: [{ start: 0, end: 30 }],
framing: 'auto',
canonical_range: { start: 0, end: 30 },
duration: 30,
current_file: 'clip_1.mp4',
has_captions: false,
words: [
{ w: 'Hello', s: 0, e: 0.6 },
{ w: 'world', s: 0.6, e: 1.2 },
{ w: 'this', s: 1.2, e: 1.6 },
{ w: 'is', s: 1.6, e: 1.9 },
{ w: 'a', s: 1.9, e: 2.1 },
{ w: 'clip', s: 2.1, e: 2.7 },
],
source: { available: true, url: `/api/source/${JOB_ID}`, duration: 120, duration_estimated: false },
limits: { max_segments: 12, min_segment_seconds: 0.5, max_total_seconds: 180 },
};
}
export function defaultScenes() {
return {
job_id: JOB_ID,
clip_index: 0,
crop_width_fraction: 0.5,
preview_url: `/videos/${JOB_ID}/scenes_preview.mp4`,
saved_overrides: {},
scenes: [
{
index: 0,
start: 0,
end: 15,
suggested_center: 0.5,
suggested_center_y: 0.5,
thumbnail_url: `/thumbnails/${JOB_ID}/scene_0.png`,
},
{
index: 1,
start: 15,
end: 30,
suggested_center: 0.4,
suggested_center_y: 0.5,
thumbnail_url: `/thumbnails/${JOB_ID}/scene_1.png`,
},
],
};
}
export function defaultIntegrations() {
return [
{ id: 'int-yt', identifier: 'youtube', name: 'My YouTube', disabled: false },
{ id: 'int-tt', identifier: 'tiktok', name: 'My TikTok', disabled: false },
];
}
function json(route, data, status = 200) {
return route.fulfill({
status,
contentType: 'application/json',
body: JSON.stringify(data),
});
}
function video(route) {
return route.fulfill({ status: 200, contentType: 'video/mp4', body: '' });
}
function png(route) {
return route.fulfill({ status: 200, contentType: 'image/png', body: atob(TINY_PNG) });
}
/**
* Install all network handlers on `page`. Returns a mutable `state` object so a
* spec can assert on call counts (e.g. the quality gate resend).
*/
export async function installApiMocks(page, options = {}) {
const opts = {
config: {
youtubeUrlEnabled: true,
billingEnabled: false,
jobRetentionSeconds: 86400,
localLlm: null,
},
clips: defaultClips(),
// 'queued' | 'needs_confirmation', consumed in order.
processSequence: ['queued'],
// 'processing' | 'completed' | 'failed', consumed in order; the last
// entry repeats once exhausted.
statusSequence: ['processing', 'completed'],
transcript: { captions: [], durationSec: 30, language: 'en' },
edl: defaultEdl(),
scenes: defaultScenes(),
integrations: defaultIntegrations(),
thumbnail: {
analyze: {
session_id: 'session-e2e',
titles: ['Mock title one', 'Mock title two'],
thumbnail_texts: ['Big win', 'How to'],
context: '',
language: 'en',
recommended: [{ index: 0, reason: 'clearest promise' }],
},
generate: {
thumbnails: [
{ url: '/thumbnails/e2e/thumb_1.png', text: 'Big win', why: 'bright and readable' },
{ url: '/thumbnails/e2e/thumb_2.png', text: 'How to', why: 'strong contrast' },
],
},
describe: { description: 'A generated description with 00:00 chapters.' },
},
tools: {
transcript: {
title: 'Mock Video',
channel: 'Mock Channel',
duration: 125,
kind: 'auto',
language: 'en',
video_id: 'dQw4w9WgXcQ',
cached: false,
languages: [{ code: 'en', kind: 'auto', name: 'English', request: 'en' }],
segments: [
{ start: 0, dur: 2, text: 'Hello world' },
{ start: 2, dur: 2, text: 'Second line' },
],
},
},
...options,
};
const state = {
processCalls: 0,
statusCalls: 0,
rerenderCalls: 0,
reframeCalls: 0,
subtitleCalls: 0,
hookCalls: 0,
postCalls: 0,
thumbnailPublishCalls: 0,
thumbnailPublishStatusCalls: 0,
};
// Catch-all: allow same-origin and in-page schemes, abort everything else.
// Registered first so the specific handlers below (registered later) win.
await page.route('**/*', (route) => {
const url = new URL(route.request().url());
if (url.origin === BASE_ORIGIN || url.protocol === 'data:' || url.protocol === 'blob:') {
return route.continue();
}
return route.abort();
});
await page.route('**/api/**', async (route) => {
const req = route.request();
const method = req.method();
const path = new URL(req.url()).pathname;
if (method === 'GET' && path === '/api/config') return json(route, opts.config);
if (method === 'POST' && path === '/api/process') {
const phase = opts.processSequence[Math.min(state.processCalls, opts.processSequence.length - 1)];
state.processCalls += 1;
if (phase === 'needs_confirmation') {
return json(route, {
needs_confirmation: true,
quality_check: { max_height: 360, min_height: 720, cookies_invalid: false },
});
}
return json(route, { job_id: JOB_ID, status: 'queued', partial: null });
}
if (method === 'GET' && path.startsWith('/api/status/')) {
const phase = opts.statusSequence[Math.min(state.statusCalls, opts.statusSequence.length - 1)];
state.statusCalls += 1;
if (phase === 'failed') {
return json(route, {
status: 'failed',
logs: ['boom'],
log_times: [Date.now() / 1000],
result: null,
queue: null,
partial: null,
error: 'The video is too short to clip.',
});
}
const result = phase === 'completed'
? { clips: opts.clips, cost_analysis: defaultResults().cost_analysis }
: { clips: opts.clips.slice(0, 1), cost_analysis: null };
return json(route, {
status: phase,
logs: phase === 'completed' ? ['Done.'] : ['Rendering clip 1...'],
log_times: [Date.now() / 1000],
result,
queue: null,
partial: null,
});
}
if (method === 'GET' && path.startsWith('/api/source-url/')) {
return json(route, { url: `/videos/${JOB_ID}/source.mp4` });
}
if (method === 'GET' && path.startsWith('/api/source/')) return video(route);
if (method === 'GET' && /^\/api\/jobs\/[^/]+\/download-all$/.test(path)) {
return route.fulfill({ status: 200, contentType: 'application/zip', body: 'PK-e2e-zip' });
}
const clipMatch = path.match(/^\/api\/clip\/([^/]+)\/(\d+)\/(transcript|edl|scenes)$/);
if (method === 'GET' && clipMatch) {
const kind = clipMatch[3];
if (kind === 'transcript') return json(route, opts.transcript);
if (kind === 'edl') return json(route, opts.edl);
return json(route, opts.scenes);
}
if (method === 'POST' && path === '/api/clip/rerender') {
state.rerenderCalls += 1;
const body = req.postDataJSON();
const segments = body?.segments || [{ start: 0, end: 30 }];
return json(route, {
new_video_url: `/videos/${JOB_ID}/recut_e2e_clip_1.mp4`,
recipe: { v: 1, segments, canonical_range: { start: 0, end: 30 } },
framing: body?.framing || 'auto',
});
}
if (method === 'POST' && path === '/api/clip/reframe') {
state.reframeCalls += 1;
return json(route, {
new_video_url: `/videos/${JOB_ID}/recut_e2e_reframe_clip_1.mp4`,
recipe: { v: 1, segments: [{ start: 0, end: 30 }], canonical_range: { start: 0, end: 30 } },
framing: 'auto',
framed_scenes: [0],
});
}
if (method === 'POST' && path === '/api/subtitle/remove') {
state.subtitleCalls += 1;
return json(route, { success: true, new_video_url: `/videos/${JOB_ID}/clean_clip_1.mp4` });
}
if (method === 'POST' && path === '/api/subtitle') {
state.subtitleCalls += 1;
return json(route, { new_video_url: `/videos/${JOB_ID}/subtitled_e2e_clip_1.mp4` });
}
if (method === 'POST' && path === '/api/hook') {
state.hookCalls += 1;
const body = req.postDataJSON();
return json(route, {
new_video_url: `/videos/${JOB_ID}/hooked_e2e_clip_1.mp4`,
burned_hook: body?.remove ? null : { text: body?.text || 'Hook' },
});
}
if (method === 'POST' && path === '/api/effects/generate') {
return json(route, { effects: { segments: [{ start: 0, end: 2, zoom: 1.2 }] } });
}
if (method === 'POST' && path === '/api/edit') {
return json(route, { new_video_url: `/videos/${JOB_ID}/edited_e2e_clip_1.mp4` });
}
if (method === 'GET' && path === '/api/postiz/integrations') {
return json(route, { integrations: opts.integrations });
}
if (method === 'POST' && path === '/api/postiz/post') {
state.postCalls += 1;
return json(route, {
success: true,
results: {},
posted: [{ id: 'int-yt', name: 'My YouTube', identifier: 'youtube' }],
});
}
if (method === 'GET' && path === '/api/postiz/scheduled') {
return json(route, { scheduled_posts: [] });
}
if (method === 'POST' && path === '/api/thumbnail/upload') {
return json(route, { session_id: 'session-e2e' });
}
if (method === 'POST' && path === '/api/thumbnail/analyze') {
return json(route, opts.thumbnail.analyze);
}
if (method === 'POST' && path === '/api/thumbnail/titles') {
return json(route, {
session_id: 'session-e2e',
titles: opts.thumbnail.analyze.titles,
thumbnail_texts: opts.thumbnail.analyze.thumbnail_texts,
recommended: [],
});
}
if (method === 'POST' && path === '/api/thumbnail/generate') {
return json(route, opts.thumbnail.generate);
}
if (method === 'GET' && path.startsWith('/api/thumbnail/frames/')) {
return json(route, { frames: [] });
}
if (method === 'POST' && path === '/api/thumbnail/describe') {
return json(route, opts.thumbnail.describe);
}
if (method === 'POST' && path === '/api/thumbnail/publish') {
state.thumbnailPublishCalls += 1;
return json(route, { publish_id: 'pub-e2e', status: 'uploading' });
}
if (method === 'GET' && path.startsWith('/api/thumbnail/publish/status/')) {
state.thumbnailPublishStatusCalls += 1;
return json(route, { status: 'done', result: { id: 'post-e2e' }, error: null });
}
if (method === 'GET' && path === '/api/tools/youtube-transcript') {
return json(route, opts.tools.transcript);
}
if (method === 'POST' && path === '/api/tools/youtube-metadata') {
const body = req.postDataJSON() || {};
if (body.mode === 'titles') {
return json(route, { mode: 'titles', titles: [{ title: 'Mock title', angle: 'how-to' }] });
}
if (body.mode === 'description') {
return json(route, { mode: 'description', description: 'Mock description for the video.' });
}
return json(route, { mode: 'tags', tags: ['mock', 'tags', 'example'], characters: 17 });
}
return json(route, { detail: `no e2e mock for ${method} ${path}` }, 404);
});
await page.route('**/videos/**', (route) => video(route));
await page.route('**/thumbnails/**', (route) => png(route));
return state;
}

View file

@ -0,0 +1,63 @@
// App-level helpers shared by the specs: localStorage seeding (Gemini key,
// Postiz config, a restored session), the in-browser render seam, and a single
// `openApp` that installs mocks, seeds storage and navigates.
import { installApiMocks, JOB_ID, defaultClips, defaultResults } from './api-mocks.js';
// Mirrors SECRET_KEY in src/App.jsx (no VITE_ENCRYPTION_KEY is set by the build).
const SECRET_KEY = 'Clipwright-Static-Salt-Change-Me';
export function encryptSecret(text) {
let xor = '';
for (let i = 0; i < text.length; i += 1) {
xor += String.fromCharCode(text.charCodeAt(i) ^ SECRET_KEY.charCodeAt(i % SECRET_KEY.length));
}
return `ENC:${btoa(xor)}`;
}
export async function seedApp(page, { geminiKey = 'e2e-gemini-key', postizUrl, postizKey, session } = {}) {
await page.addInitScript((payload) => {
try {
// A stored consent decision keeps the cookie banner out of the way
// (the banner is otherwise shown to EEA timezones, which the CI
// runner's TZ would make nondeterministic).
window.localStorage.setItem('clipwright_consent', JSON.stringify({
v: 1, ts: new Date().toISOString(), necessary: true, analytics: true, marketing: false,
}));
if (payload.geminiKey) window.localStorage.setItem('gemini_key', payload.geminiKey);
if (payload.postizUrl) window.localStorage.setItem('postiz_url', payload.postizUrl);
if (payload.encryptedPostizKey) window.localStorage.setItem('postiz_key_v1', payload.encryptedPostizKey);
if (payload.session) window.localStorage.setItem('clipwright_session', JSON.stringify(payload.session));
} catch (_) { /* storage unavailable */ }
}, {
geminiKey,
postizUrl,
encryptedPostizKey: postizKey ? encryptSecret(postizKey) : null,
session,
});
// Replace the WebCodecs/Remotion render with a deterministic blob URL so the
// specs never depend on hardware encoders. See src/lib/renderInBrowser.js.
await page.addInitScript(() => {
window.__CW_E2E_RENDER__ = () => 'blob:http://127.0.0.1:4173/e2e-render';
});
}
export function completedSession({ jobId = JOB_ID, clips = defaultClips() } = {}) {
return {
jobId,
status: 'complete',
results: { clips, cost_analysis: defaultResults().cost_analysis },
processingMedia: null,
activeTab: 'dashboard',
timestamp: Date.now(),
};
}
export async function openApp(page, { hash = '#app', seed, mocks } = {}) {
const state = await installApiMocks(page, mocks);
await seedApp(page, seed);
await page.goto(`/${hash}`);
return state;
}
export { installApiMocks, JOB_ID, defaultClips, defaultResults };

View file

@ -0,0 +1,26 @@
// Builds the tiny media the specs upload. ffmpeg is required by the plan; when
// it is absent (a bare `npm test` on a machine without it) we still write a
// non-empty placeholder so the upload path is exercised rather than skipped.
import { execFileSync } from 'node:child_process';
import fs from 'node:fs';
import { ARTIFACTS_DIR, SIXTY_MP4 } from './media.js';
export default function globalSetup() {
fs.mkdirSync(ARTIFACTS_DIR, { recursive: true });
try {
execFileSync('ffmpeg', [
'-y',
'-f', 'lavfi', '-i', 'testsrc=size=160x90:rate=30:duration=60',
'-f', 'lavfi', '-i', 'sine=frequency=440:duration=60',
'-c:v', 'libx264', '-pix_fmt', 'yuv420p',
'-c:a', 'aac', '-shortest',
SIXTY_MP4,
], { stdio: 'ignore' });
console.log(`[e2e] built ${SIXTY_MP4}`);
} catch (err) {
if (!fs.existsSync(SIXTY_MP4)) {
fs.writeFileSync(SIXTY_MP4, 'clipwright-e2e-placeholder');
}
console.warn(`[e2e] ffmpeg unavailable, wrote a placeholder media file: ${err.message}`);
}
}

View file

@ -0,0 +1,15 @@
// Media used by the browser E2E specs.
//
// Nothing binary is committed: global-setup builds a tiny mp4 with ffmpeg into
// e2e/.artifacts (git-ignored) and the specs read the path from here. The file
// only has to be a real, non-empty video container — the dashboard's upload
// path reads its duration from the browser and falls back gracefully when the
// browser cannot decode the codec, so an undecodable build still exercises the
// flow.
import { fileURLToPath } from 'node:url';
import path from 'node:path';
const here = path.dirname(fileURLToPath(import.meta.url));
export const ARTIFACTS_DIR = path.join(here, '..', '.artifacts');
export const SIXTY_MP4 = path.join(ARTIFACTS_DIR, 'sixty.mp4');

View file

@ -0,0 +1,53 @@
// Browser E2E config. Two projects:
// - `mock` (default): every network edge is intercepted, no retries, one
// worker. This is the lane that must stay green in CI.
// - `real`: drives the real backend (uvicorn + stub pipeline). Kept separate
// so the mocked lane never depends on Python.
/* global process */
import { defineConfig, devices } from '@playwright/test';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
const dashboardDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
export default defineConfig({
testDir: './specs',
// No retries anywhere: a flaky test is a bug, not a coin flip.
retries: 0,
// One worker keeps the shared preview server and the deterministic fixtures
// predictable.
workers: 1,
fullyParallel: false,
timeout: 30_000,
expect: { timeout: 5_000 },
reporter: [['list']],
outputDir: './.test-results',
globalSetup: './fixtures/global-setup.js',
use: {
baseURL: 'http://127.0.0.1:4173',
trace: 'retain-on-failure',
screenshot: 'only-on-failure',
video: 'retain-on-failure',
},
projects: [
{
name: 'mock',
testIgnore: /real-backend\.spec\.js/,
use: { ...devices['Desktop Chrome'] },
},
{
name: 'real',
testMatch: /real-backend\.spec\.js/,
use: { ...devices['Desktop Chrome'] },
},
],
webServer: {
command: 'npm run build && npx vite preview --port 4173 --strictPort --host 127.0.0.1',
cwd: dashboardDir,
url: 'http://127.0.0.1:4173',
reuseExistingServer: !process.env.CI,
timeout: 120_000,
stdout: 'ignore',
stderr: 'pipe',
},
});

View file

@ -0,0 +1,35 @@
import { test, expect } from '@playwright/test';
import { openApp, completedSession, JOB_ID } from '../fixtures/app.js';
test.describe('clip editor', () => {
test('edits the recipe and re-renders through /api/clip/rerender', async ({ page }) => {
await openApp(page, { seed: { session: completedSession() } });
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
await page.getByRole('button', { name: 'edit clip' }).first().click();
await expect(page.getByRole('heading', { name: 'edit clip' })).toBeVisible();
// The EDL loaded (the loading state is gone) and its segment is listed.
await expect(page.getByRole('button', { name: /add segment/i })).toBeVisible();
await expect(page.getByLabel('segment 1 start')).toHaveValue('0');
// Add a second segment so the recipe is dirty and renderable.
await page.getByRole('button', { name: /add segment/i }).click();
await expect(page.getByLabel('segment 2 start')).toBeVisible();
const requestPromise = page.waitForRequest(
(r) => r.method() === 'POST' && r.url().includes('/api/clip/rerender'),
);
await page.getByRole('button', { name: /re-render/i }).click();
const request = await requestPromise;
const body = request.postDataJSON();
expect(body.job_id).toBe(JOB_ID);
expect(body.clip_index).toBe(0);
expect(body.segments).toHaveLength(2);
expect(body.framing).toBe('auto');
expect(body.reapply_captions).toBe(true);
// The new preview URL is adopted; the editor stays open.
await expect(page.getByRole('heading', { name: 'edit clip' })).toBeVisible();
});
});

View file

@ -0,0 +1,45 @@
import { test, expect } from '@playwright/test';
import { installApiMocks } from '../fixtures/app.js';
// The free tools are static, no-React pages emitted by vite-plugin-seo. They
// talk to the same /api origin, so the same route mocks apply.
test.describe('free tools', () => {
test('youtube transcript generator renders captions', async ({ page }) => {
await installApiMocks(page);
await page.goto('/youtube-transcript-generator.html');
const requestPromise = page.waitForRequest(
(r) => r.url().includes('/api/tools/youtube-transcript'),
);
await page.fill('#yt-url', 'https://www.youtube.com/watch?v=dQw4w9WgXcQ');
await page.click('#yt-form button[type="submit"]');
const request = await requestPromise;
expect(new URL(request.url()).searchParams.get('url'))
.toBe('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
await expect(page.locator('#yt-title')).toHaveText('Mock Video');
await expect(page.locator('#yt-result')).toBeVisible();
await expect(page.locator('#yt-text')).toContainText('Hello world');
});
test('youtube tag generator returns tags', async ({ page }) => {
await installApiMocks(page);
await page.goto('/youtube-tag-generator.html');
await page.fill('#md-topic', 'A detailed topic sentence about sourdough bread for beginners.');
await page.click('#md-go');
await expect(page.locator('#md-out')).toBeVisible();
await expect(page.locator('#md-out')).toContainText('mock');
await expect(page.locator('#md-out')).toContainText('tags');
});
test('video aspect ratio converter loads its client-side tool', async ({ page }) => {
await installApiMocks(page);
await page.goto('/video-aspect-ratio-converter.html');
await expect(page.locator('#vc-file')).toBeAttached();
await expect(page.locator('#vc-drop')).toBeVisible();
});
});

View file

@ -0,0 +1,52 @@
import { test, expect } from '@playwright/test';
import { openApp } from '../fixtures/app.js';
import { SIXTY_MP4 } from '../fixtures/media.js';
test.describe('generate flow', () => {
test('uploads a file, posts it to /api/process and renders the clips', async ({ page }) => {
await openApp(page, { mocks: { statusSequence: ['processing', 'completed'] } });
await page.setInputFiles('input[type="file"][accept="video/*"]', SIXTY_MP4);
await page.locator('form input[type="checkbox"]').first().check();
const requestPromise = page.waitForRequest(
(r) => r.method() === 'POST' && r.url().includes('/api/process'),
);
await page.getByRole('button', { name: /generate clips/i }).click();
const request = await requestPromise;
expect(request.headers()['x-gemini-key']).toBe('e2e-gemini-key');
expect(request.headers()['content-type']).toContain('multipart/form-data');
// The multipart body carries the chosen file and the attestation.
const body = request.postDataBuffer().toString('latin1');
expect(body).toContain('sixty.mp4');
expect(body).toContain('acknowledged');
// Polling is driven by the app's own 2s interval; auto-wait absorbs it.
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
await expect(page.getByRole('heading', { name: 'Second viral clip' })).toBeVisible();
await expect(page.getByText('2 Clips')).toBeVisible();
});
test('submits a YouTube URL as JSON with the Gemini header', async ({ page }) => {
await openApp(page);
await page.getByRole('button', { name: /video url/i }).click();
await page.getByPlaceholder(/paste a video link/i).fill('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
await page.locator('form input[type="checkbox"]').first().check();
const requestPromise = page.waitForRequest(
(r) => r.method() === 'POST' && r.url().includes('/api/process'),
);
await page.getByRole('button', { name: /generate clips/i }).click();
const request = await requestPromise;
expect(request.postDataJSON()).toMatchObject({
url: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
acknowledged: true,
force_low_quality: false,
});
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
});
});

View file

@ -0,0 +1,37 @@
import { test, expect } from '@playwright/test';
import { openApp, completedSession, JOB_ID } from '../fixtures/app.js';
test.describe('postiz publish', () => {
test('publishes a clip to the connected channels through /api/postiz/post', async ({ page }) => {
await openApp(page, {
seed: {
session: completedSession(),
postizUrl: 'http://postiz.e2e.local',
postizKey: 'postiz-e2e-key',
},
});
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
await page.getByRole('button', { name: 'post', exact: true }).first().click();
const dialog = page.getByRole('dialog');
await expect(dialog.getByText('PUBLISH', { exact: true })).toBeVisible();
// Connected channels load from the mocked integrations endpoint.
await expect(dialog.getByText('My YouTube')).toBeVisible();
const requestPromise = page.waitForRequest(
(r) => r.method() === 'POST' && r.url().includes('/api/postiz/post'),
);
await dialog.getByRole('button', { name: /publish now/i }).click();
const request = await requestPromise;
const body = request.postDataJSON();
expect(body.job_id).toBe(JOB_ID);
expect(body.clip_index).toBe(0);
expect(body.integration_ids).toContain('int-yt');
expect(body.title).toBe('First viral clip');
expect(request.headers()['x-postiz-url']).toBe('http://postiz.e2e.local');
await expect(page.getByText(/Posted to My YouTube/)).toBeVisible();
});
});

View file

@ -0,0 +1,38 @@
import { test, expect } from '@playwright/test';
import { openApp } from '../fixtures/app.js';
test.describe('quality gate', () => {
test('asks before processing a low-resolution source and resends with force_low_quality', async ({ page }) => {
await openApp(page, { mocks: { processSequence: ['needs_confirmation', 'queued'] } });
await page.getByRole('button', { name: /video url/i }).click();
await page.getByPlaceholder(/paste a video link/i).fill('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
await page.locator('form input[type="checkbox"]').first().check();
const firstPromise = page.waitForRequest(
(r) => r.method() === 'POST' && r.url().includes('/api/process'),
);
await page.getByRole('button', { name: /generate clips/i }).click();
const first = await firstPromise;
expect(first.postDataJSON()).toMatchObject({ force_low_quality: false });
// The gate opens instead of starting the job.
const dialog = page.getByRole('dialog');
await expect(dialog.getByText(/low source quality/i)).toBeVisible();
await expect(dialog.getByText(/360p/)).toBeVisible();
const secondPromise = page.waitForRequest(
(r) => r.method() === 'POST'
&& r.url().includes('/api/process')
&& JSON.parse(r.postData()).force_low_quality === true,
);
await page.getByRole('button', { name: /process anyway/i }).click();
const second = await secondPromise;
expect(second.postDataJSON()).toMatchObject({
url: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
force_low_quality: true,
});
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
});
});

View file

@ -0,0 +1,17 @@
import { test, expect } from '@playwright/test';
// Real-backend lane.
//
// The plan calls for driving a real `uvicorn clipwright.api.app:app` with the
// pipeline's stub_env (tests/e2e/pipeline/stub_env) so the browser talks to the
// actual API instead of route mocks. That pipeline/stub environment is owned by
// the backend E2E lanes, and the dashboard CI job provisions Node + Chromium
// only (no Python deps, no ffmpeg), so this stays fixme until the backend lane
// exposes a server the dashboard job can launch. The same routes are covered
// end-to-end over HTTP by tests/e2e/api.
test.describe('real backend', () => {
test.fixme('generates clips against a real uvicorn + stub_env server', async ({ page }) => {
await page.goto('/');
await expect(page).toHaveTitle(/Clipwright/);
});
});

View file

@ -0,0 +1,35 @@
import { test, expect } from '@playwright/test';
import { openApp, completedSession, JOB_ID } from '../fixtures/app.js';
test.describe('reframe editor', () => {
test('splits a scene and applies reframing through /api/clip/reframe', async ({ page }) => {
await openApp(page, { seed: { session: completedSession() } });
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
await page.getByRole('button', { name: 'reframing' }).first().click();
await expect(page.getByRole('heading', { name: 'reframing' })).toBeVisible();
// Scenes came back from the mocked /scenes endpoint.
await expect(page.getByText(/scene 1 ·/)).toBeVisible();
await expect(page.getByText(/nothing adjusted yet/i)).toBeVisible();
await page.getByTitle('stack two regions instead of one window').first().click();
await expect(page.getByText(/1 scene reframed by hand/i)).toBeVisible();
const requestPromise = page.waitForRequest(
(r) => r.method() === 'POST' && r.url().includes('/api/clip/reframe'),
);
await page.getByRole('button', { name: /apply reframing/i }).click();
const request = await requestPromise;
const body = request.postDataJSON();
expect(body.job_id).toBe(JOB_ID);
expect(body.clip_index).toBe(0);
expect(body.crop_overrides['0']).toBeTruthy();
expect(body.crop_overrides['0'].top).toBeTruthy();
expect(body.crop_overrides['0'].bottom).toBeTruthy();
// A successful save closes the editor.
await expect(page.getByRole('heading', { name: 'reframing' })).toHaveCount(0);
});
});

View file

@ -0,0 +1,38 @@
import { test, expect } from '@playwright/test';
import { openApp, completedSession, JOB_ID } from '../fixtures/app.js';
test.describe('results actions', () => {
test('downloads all clips as a zip', async ({ page }) => {
await openApp(page, { seed: { session: completedSession() } });
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
const requestPromise = page.waitForRequest(
(r) => r.method() === 'GET' && r.url().includes(`/api/jobs/${JOB_ID}/download-all`),
);
const downloadPromise = page.waitForEvent('download');
await page.getByRole('button', { name: /download all/i }).click();
await requestPromise;
const download = await downloadPromise;
expect(download.suggestedFilename()).toContain('clipwright_clips_');
});
test('opens the generated descriptions', async ({ page }) => {
await openApp(page, { seed: { session: completedSession() } });
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
await page.getByRole('button', { name: /view descriptions/i }).first().click();
const dialog = page.getByRole('dialog');
await expect(dialog.getByText('GENERATED COPY')).toBeVisible();
await expect(dialog.getByText('TikTok caption one #viral #shorts')).toBeVisible();
await expect(dialog.getByText('First viral clip')).toBeVisible();
});
test('removes a generated clip and resets the workspace', async ({ page }) => {
await openApp(page, { seed: { session: completedSession() } });
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
await page.getByRole('button', { name: /new project/i }).click();
await expect(page.getByRole('heading', { name: /create viral shorts/i })).toBeVisible();
});
});

View file

@ -0,0 +1,23 @@
import { test, expect } from '@playwright/test';
import { openApp, completedSession } from '../fixtures/app.js';
test.describe('session restore', () => {
test('restores a completed job from localStorage and shows its clips', async ({ page }) => {
await openApp(page, { seed: { session: completedSession() } });
await expect(page.getByText('Session recovered')).toBeVisible();
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
await expect(page.getByRole('heading', { name: 'Second viral clip' })).toBeVisible();
await expect(page.getByText('2 Clips')).toBeVisible();
});
test('discards a session older than the retention window', async ({ page }) => {
const stale = completedSession();
stale.timestamp = Date.now() - 25 * 60 * 60 * 1000; // 25h > 24h
await openApp(page, { seed: { session: stale } });
await expect(page.getByRole('heading', { name: /create viral shorts/i })).toBeVisible();
await expect(page.getByText('Session recovered')).toHaveCount(0);
await expect(page.getByRole('heading', { name: 'First viral clip' })).toHaveCount(0);
});
});

View file

@ -0,0 +1,28 @@
import { test, expect } from '@playwright/test';
import { openApp } from '../fixtures/app.js';
test.describe('smoke', () => {
test('boots the app, renders the generator and reaches Settings', async ({ page }) => {
const pageErrors = [];
page.on('pageerror', (err) => pageErrors.push(err.message));
await openApp(page, { hash: '#app' });
await expect(page.getByRole('heading', { name: /create viral shorts/i })).toBeVisible();
// The Gemini key is seeded, so the "keys missing" banners must not show.
await expect(page.getByText(/Required API keys missing/i)).toHaveCount(0);
await expect(page.getByText(/Gemini API Key Missing/i)).toHaveCount(0);
// Settings is a full view reachable from the rail.
await page.getByRole('button', { name: /settings/i }).first().click();
await expect(page.getByRole('heading', { name: 'Settings' })).toBeVisible();
await expect(page.getByText(/Publishing \(Postiz\)/i)).toBeVisible();
expect(pageErrors).toEqual([]);
});
test('asks for the Gemini key when none is stored', async ({ page }) => {
await openApp(page, { seed: { geminiKey: '' } });
await expect(page.getByText(/Required API keys missing/i)).toBeVisible();
});
});

View file

@ -0,0 +1,46 @@
import { test, expect } from '@playwright/test';
import { openApp, completedSession, JOB_ID } from '../fixtures/app.js';
test.describe('subtitle modal', () => {
test('applies a caption style to one clip and posts the style to /api/subtitle', async ({ page }) => {
await openApp(page, { seed: { session: completedSession() } });
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
await page.getByRole('button', { name: 'subtitles' }).first().click();
const dialog = page.getByRole('dialog');
await expect(dialog.getByText('EDITOR · SUBTITLES')).toBeVisible();
const requestPromise = page.waitForRequest(
(r) => r.method() === 'POST' && r.url().includes('/api/subtitle'),
);
await dialog.getByRole('button', { name: /apply to this clip/i }).click();
const request = await requestPromise;
expect(request.postDataJSON()).toMatchObject({
job_id: JOB_ID,
clip_index: 0,
style: 'karaoke',
input_filename: 'clip_1.mp4',
});
// Success closes the editor.
await expect(page.getByText('EDITOR · SUBTITLES')).toHaveCount(0);
});
test('applies one style to every clip', async ({ page }) => {
await openApp(page, { seed: { session: completedSession() }, mocks: { statusSequence: ['completed'] } });
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
const bodies = [];
page.on('request', (r) => {
if (r.method() === 'POST' && r.url().includes('/api/subtitle')) bodies.push(r.postDataJSON());
});
await page.getByRole('button', { name: 'subtitles' }).first().click();
const dialog = page.getByRole('dialog');
await dialog.getByRole('button', { name: /apply this style to all 2 clips/i }).click();
await expect.poll(() => bodies.length).toBe(2);
expect(bodies.map((b) => b.clip_index).sort()).toEqual([0, 1]);
});
});

View file

@ -0,0 +1,43 @@
import { test, expect } from '@playwright/test';
import { openApp } from '../fixtures/app.js';
test.describe('thumbnail studio', () => {
test('manual title -> generate -> describe -> publish to YouTube', async ({ page }) => {
await openApp(page, {
hash: '#app?tab=thumbnails',
seed: { postizUrl: 'http://postiz.e2e.local', postizKey: 'postiz-e2e-key' },
});
await expect(page.getByRole('heading', { name: /youtube studio/i })).toBeVisible();
// Mode B: write a title by hand.
await page.getByPlaceholder(/Enter your YouTube title/i).fill('My manual e2e title');
await page.getByRole('button', { name: /use this title/i }).click();
await page.getByRole('button', { name: /continue to thumbnails/i }).click();
// Step 2: generate thumbnails.
const generatePromise = page.waitForRequest(
(r) => r.method() === 'POST' && r.url().includes('/api/thumbnail/generate'),
);
await page.getByRole('button', { name: /generate thumbnails/i }).click();
await generatePromise;
await expect(page.getByAltText('Thumbnail 1')).toBeVisible();
await page.getByAltText('Thumbnail 1').click({ force: true });
await page.getByRole('button', { name: /next: description/i }).click();
// Step 3: write a description and continue.
await page.locator('textarea').first().fill('A hand written e2e description.');
await page.getByRole('button', { name: /next: publish/i }).click();
// Step 4: publish (Postiz is configured).
const publishPromise = page.waitForRequest(
(r) => r.method() === 'POST' && r.url().includes('/api/thumbnail/publish'),
);
await page.getByRole('button', { name: /publish to youtube/i }).click();
const publish = await publishPromise;
expect(publish.postDataBuffer().toString('latin1')).toContain('My manual e2e title');
await expect(page.getByText(/published successfully/i)).toBeVisible();
});
});

View file

@ -19,6 +19,7 @@
},
"devDependencies": {
"@eslint/js": "^9.39.5",
"@playwright/test": "^1.63.0",
"@types/react": "^18.2.64",
"@types/react-dom": "^18.2.21",
"@vitejs/plugin-react": "^4.2.1",
@ -986,6 +987,22 @@
"node": ">= 8"
}
},
"node_modules/@playwright/test": {
"version": "1.63.0",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.63.0.tgz",
"integrity": "sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright": "1.63.0"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/@remotion/licensing": {
"version": "4.0.447",
"resolved": "https://registry.npmjs.org/@remotion/licensing/-/licensing-4.0.447.tgz",
@ -3895,6 +3912,35 @@
"node": ">= 6"
}
},
"node_modules/playwright": {
"version": "1.63.0",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz",
"integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.63.0"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/playwright-core": {
"version": "1.63.0",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",
"integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/possible-typed-array-names": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",
@ -5785,6 +5831,15 @@
"fastq": "^1.6.0"
}
},
"@playwright/test": {
"version": "1.63.0",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.63.0.tgz",
"integrity": "sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ==",
"dev": true,
"requires": {
"playwright": "1.63.0"
}
},
"@remotion/licensing": {
"version": "4.0.447",
"resolved": "https://registry.npmjs.org/@remotion/licensing/-/licensing-4.0.447.tgz",
@ -7742,6 +7797,21 @@
"integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==",
"dev": true
},
"playwright": {
"version": "1.63.0",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz",
"integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==",
"dev": true,
"requires": {
"playwright-core": "1.63.0"
}
},
"playwright-core": {
"version": "1.63.0",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",
"integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",
"dev": true
},
"possible-typed-array-names": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",

View file

@ -7,7 +7,8 @@
"dev": "vite",
"build": "vite build",
"lint": "eslint . --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
"preview": "vite preview",
"test:e2e": "playwright test --config e2e/playwright.config.js"
},
"dependencies": {
"@remotion/media": "^4.0.447",
@ -21,6 +22,7 @@
},
"devDependencies": {
"@eslint/js": "^9.39.5",
"@playwright/test": "^1.63.0",
"@types/react": "^18.2.64",
"@types/react-dom": "^18.2.21",
"@vitejs/plugin-react": "^4.2.1",

View file

@ -623,9 +623,7 @@ switched off.</p>
<h2>4. Who receives data (processors) and where</h2>
<p>Depending on how you configure it, the software can send data to these
third-party providers. The machine-readable list, with the transfer safeguard
for each, is kept in the public repository at
<a href="https://git.pbento.pt/pedro-bento/clipwright/blob/main/docs/compliance/subprocessors.md">docs/compliance/subprocessors.md</a>
and changes are recorded there.</p>
for each, is kept in the public repository, and changes are recorded there.</p>
<ul>
<li><strong>Google (Gemini API)</strong> — AI analysis to select moments,
layouts, titles and thumbnails. It receives your video's transcript and
@ -672,8 +670,7 @@ analytics data: 25 months.</li>
<p>The retention constants are configurable in the environment; the defaults
above are what the code enforces.</p>
<p>The full, per-item version of this table, written against the actual code
that enforces it, is in the public repository at
<a href="https://git.pbento.pt/pedro-bento/clipwright/blob/main/docs/compliance/retencion.md">docs/compliance/retencion.md</a>.</p>
that enforces it, is kept in the public repository.</p>
<h2>6. Your rights</h2>
<p>You can ask us for access, rectification, erasure, restriction, portability
@ -841,9 +838,8 @@ añadiéramos alguno, empiece desactivado.</p>
<h2>4. Quién recibe datos (encargados) y dónde</h2>
<p>Según cómo lo configures, el software puede enviar datos a estos
proveedores externos. La versión detallada de esta lista, con la garantía de
transferencia de cada uno, se mantiene en el repositorio público en
<a href="https://git.pbento.pt/pedro-bento/clipwright/blob/main/docs/compliance/subprocessors.md">docs/compliance/subprocessors.md</a>,
donde también se registran los cambios.</p>
transferencia de cada uno, se mantiene en el repositorio público, donde
también se registran los cambios.</p>
<ul>
<li><strong>Google (API Gemini)</strong> — análisis con IA para seleccionar
momentos, encuadres, títulos y miniaturas. Recibe la transcripción de tu vídeo
@ -893,8 +889,7 @@ datos brutos de analítica: 25 meses.</li>
<p>Las constantes de retención se configuran en el entorno; los valores por
defecto de arriba son los que aplica el código.</p>
<p>La versión completa y detallada de esta tabla, escrita contra el código que
realmente la aplica, está en el repositorio público en
<a href="https://git.pbento.pt/pedro-bento/clipwright/blob/main/docs/compliance/retencion.md">docs/compliance/retencion.md</a>.</p>
realmente la aplica, está en el repositorio público.</p>
<h2>6. Tus derechos</h2>
<p>Puedes pedirnos acceso, rectificación, supresión, limitación y portabilidad

View file

@ -1,7 +1,7 @@
import { X } from 'lucide-react';
/**
* The single modal shell for the app (design.md).
* The single modal shell for the app.
* Plain dark overlay (no backdrop-blur), hairline paper2 panel.
*
* Props:

View file

@ -1,5 +1,5 @@
/**
* The single option-toggle group (design.md). Replaces every ad-hoc
* The single option-toggle group. Replaces every ad-hoc
* grid of toggle buttons (position/size/animation pickers, platform
* selectors, mode switches).
*

View file

@ -1,7 +1,7 @@
import { Check } from 'lucide-react';
/**
* The single wizard stepper (design.md) — used by ThumbnailStudio. Mono
* The single wizard stepper — used by ThumbnailStudio. Mono
* ordinals, hairline connectors, brass current step.
*
* Props:

View file

@ -1,4 +1,4 @@
/* Hallmark · genre: atmospheric · theme: lumen (night foundry) · design-system: design.md · designed-as-app */
/* Hallmark · genre: atmospheric · theme: lumen (night foundry) · designed-as-app */
/* Noto Serif (hook-overlay font, burned into videos — not UI) is self-hosted
with the rest of the faces in public/fonts.css: no request to Google. */
@import './tokens.css';

View file

@ -24,6 +24,7 @@ export async function renderInBrowser({
onProgress,
signal,
}) {
if (window.__CW_E2E_RENDER__) return window.__CW_E2E_RENDER__();
const fps = 30;
const durationInFrames = Math.max(1, Math.round(durationInSeconds * fps));

View file

@ -1,4 +1,4 @@
/* Hallmark · genre: atmospheric · theme: lumen (night foundry) · design-system: design.md · designed-as-app
/* Hallmark · genre: atmospheric · theme: lumen (night foundry) · designed-as-app
* macrostructure: Marquee Hero (marketing) / Workbench (app) / Long Document (content)
* nav: N9 edge-aligned · footer: Ft5 statement · enrichment: filament apparatus (landing only)
* pre-emit critique: P5 H4 E4 S5 R5 V4

168
design.md
View file

@ -1,168 +0,0 @@
# Design — Clipwright
A locked design system for this app (dashboard + landing). Every page redesign
reads this file before emitting code. Do not regenerate per page — extend or
amend this file when the system needs to grow.
Theme: **Lumen · Night Foundry** (Hallmark catalog, atmospheric genre).
Register: premium AI-tool instrument (Modal / Anthropic / ElevenLabs school).
The product's own numbers — timecodes, aspect ratios, clip counts, costs —
are the decoration: they render as UPPERCASE mono readouts.
## Genre
atmospheric
## Macrostructure family
- Marketing pages (Landing): **Marquee Hero, Lumen-canonical** — lowercase
serif headline hero-left with one coral verb-landmark, hand-built CSS
apparatus hero-right, meter strip below the fold, then sections with mono
eyebrows. Nav: N9 edge-aligned minimal. Footer: Ft5 Statement.
- App pages (dashboard tabs, modals): **Workbench** — small functional
headings, hairline cards lit from within, mono readouts, zero enrichment.
Function carries the page.
- Content pages (Legal): **Long Document** — single column, 65ch measure,
inline headings, typographic links.
## Theme tokens (Night Foundry)
- `--color-paper` oklch(13% 0.014 265) — page canvas, late-night violet
- `--color-paper-2` oklch(16.5% 0.015 265) — elevated surface (cards, modals, sidebar)
- `--color-paper-3` oklch(20% 0.016 265) — hover surface / inset chips
- `--color-ink` oklch(96% 0.006 262) — headlines, near-white
- `--color-ink-2` oklch(86% 0.01 262) — body text
- `--color-muted` oklch(64% 0.012 262) — secondary text
- `--color-rule` oklch(96% 0.006 262 / 0.08) — hairline borders
- `--color-rule-2` oklch(96% 0.006 262 / 0.14) — stronger hairline
- `--rule-blueprint` oklch(96% 0.006 262 / 0.04) — blueprint grid lines
- `--color-accent` oklch(76% 0.17 50) — molten brass (THE accent)
- `--color-accent-ink` oklch(17% 0.03 50) — text on brass fills
- `--color-accent-2` oklch(68% 0.16 18) — coral chord (verb landmark ONLY + rare secondary)
- `--color-glow` oklch(80% 0.16 50 / 0.42) — apparatus halo
- `--color-paper-emit` oklch(76% 0.17 50 / 0.04) — inner-emission wash
- `--color-focus` oklch(76% 0.17 50) — focus rings
- `--color-ok` oklch(75% 0.11 150) — success states
- `--color-warn` oklch(78% 0.14 75) — warnings (keys missing, low quota)
- `--color-danger` oklch(66% 0.18 25) — errors, destructive
Tailwind names: `paper, paper2, paper3, ink, ink2, muted, brass, brassink,
coral, ok, warn, danger` (+ legacy aliases `background→paper`, `surface→paper2`,
`primary→brass`, `accent→coral` so untouched files degrade gracefully).
Borders: use `border-rule` / `border-rule2` utilities (defined in index.css).
## Typography
- Display: **Instrument Serif 400**, `font-display`, always roman (never italic),
**lowercase**, tracking -0.032em, line-height 1.02.
- Body: **Geist** 400/500/600, `font-body`.
- Mono: **JetBrains Mono** 400/500, `font-mono` — UPPERCASE labels only.
- Two-register rule: UI prose (headings, buttons, nav, empty states, helper
text) renders **lowercase**; mono labels (eyebrows, badges, readouts, stat
labels, keyboard hints) render **UPPERCASE** 10.5–11px tracking 0.10em at
~55% opacity. That contrast is the typographic signature.
- **NEVER lowercase user content**: video titles, captions, transcripts,
descriptions, emails, API keys, log output, filenames, prices in legal copy.
Apply `lowercase` class per-element on UI chrome only — no global
text-transform on body.
- Numerals: `font-variant-numeric: tabular-nums` wherever numbers appear
(`tabular-nums` utility). Big stats: Instrument Serif + tabular-nums.
- Type scale anchor: `--text-display: clamp(3rem, 6vw + 1rem, 6rem)` (landing
hero only). App headings stay small: text-xl/2xl max, serif lowercase.
## Spacing
4-point scale via Tailwind defaults (p-2/3/4/6/8/12/16). No arbitrary
`text-[9px]`-style values — minimum readable label is 10.5px (`text-micro`
utility). Radii: `--radius-card: 10px` (rounded-card), `--radius-input: 8px`
(rounded-input), pills `rounded-full` for CTAs and status chips only.
## Motion
- Easings: `--ease-out: cubic-bezier(0.16, 1, 0.3, 1)` only. Never `ease`.
- Durations: 220ms UI state, 600ms section reveals, 4s apparatus pulse.
- Reveal pattern: fade only (`animate-fade`), optional 12px translateY on
section entry. No slide-ins, no bounce, no scale-pops.
- Cards hover: `translateY(-4px)` + inner-glow brighten, 220ms.
- Reduced motion: everything collapses to instant final state.
- Focus ring: 2px brass, appears INSTANTLY (never animated).
## Microinteractions stance
- Silent success (inline check, quiet state change) — never celebratory.
- Buttons: `active:translate-y-px`, no scale tricks.
- Hover tooltips delay 800ms; focus tooltips 0ms.
- Loaders: `Loader2` lucide spin is fine, tinted `text-muted` or `text-brass`.
## CTA voice
- Primary: `.btn-primary` — brass fill, `text-brassink`, `rounded-full`,
lowercase label, font-medium. One per view section.
- Secondary: `.btn-ghost` — hairline `border-rule2`, ink text, rounded-full.
- Tertiary/utility: `.btn-quiet` — `bg-paper3` fill, no border.
- Destructive: `.btn-danger` — danger outline, fills on hover.
- Labels are verbs, lowercase: "start clipping", "generate", "publish",
"download". Never "Get Started!", never Title Case.
## Component recipes (shared — use these, don't reinvent)
- `.card` — hairline border + inner emission (radial brass 4–5%), rounded-card,
bg-paper2. Hover variant `.card-hover` lifts and brightens. Replaces ALL
glass-panel / bg-surface/50 / backdrop-blur cards.
- `.eyebrow` — mono UPPERCASE micro label. Section pattern: eyebrow stacked
ABOVE the heading, same column (`01 · TOOLS` then the serif heading). Never
tag-left/heading-right.
- `<Modal>` from `src/components/ui/Modal.jsx` — the ONLY modal shell
(overlay plain `bg-black/70`, NO backdrop-blur; panel bg-paper2 hairline).
- `<SegmentedControl>` from `src/components/ui/SegmentedControl.jsx` — all
option-button grids (position/size/animation pickers, platform toggles).
Active state = brass hairline + paper3 fill + ink text. Never bg-white
text-black, never per-feature colors.
- `<StepIndicator>` from `src/components/ui/StepIndicator.jsx` — the single
wizard stepper (ThumbnailStudio + SaaShortsTab share it). Mono ordinals.
- `.input-field` — inset bg-paper, hairline, focus brass ring (redefined in
index.css; existing class name kept).
- `.readout` — mono UPPERCASE value chip for machine data (timecodes, costs,
ratios, model names): `00:42 · 9:16 · $0.65`.
- Status: `.badge-ok` / `.badge-warn` / `.badge-danger` — tinted 10% fills,
mono uppercase.
## What pages MUST share
- Single accent: brass. Coral ONLY as the headline verb-landmark (landing) and
at most one small secondary highlight per view. NOTHING ELSE gets a hue.
- Zero gradients (text or background). Zero glassmorphism / backdrop-blur
panels. Zero per-feature identity colors (the old violet/emerald/amber/teal
per-tab coding is retired — tools are differentiated by mono eyebrow ordinals
`01 · CLIPS`, `02 · PUBLISHING`, not by hue).
- The two-register typography (lowercase prose / UPPERCASE mono labels).
- The CTA voice, radii, hairline card language.
- English copy everywhere (ScheduleWeekModal migrates from Spanish).
- Lucide icons at 16–18px, `text-muted` default, brass when active.
## What pages MAY differ on
- Landing may use enrichment: ONE hand-built CSS apparatus (filament chamber
reading as a 9:16 clip instrument) + blueprint grid + meter strip. App pages
get NONE of these (no grid bg, no apparatus, no meter) — except ProcessingAnimation,
which keeps its scanner HUD but re-tinted to brass/ink tokens.
- Legal is typography-only.
## Hard bans (Lumen)
No italics anywhere. No gradient text. No gradient buttons. No backdrop-blur.
No glowing orbs. No invented metrics (existing cited stats/prices are the
brief's real copy — keep them). No emoji as icons in chrome (existing emoji
option labels in SaaShorts pickers may stay as content). No rounded-2xl
soup — use rounded-card/rounded-input/rounded-full deliberately. No
`bg-[#121214]`-style hardcoded colors — tokens only. No Title Case UI copy.
## Functional contract (NEVER break)
Hash routing (`#app`, `#/pricing`, `#/account`, `#legal`, `#features`,
`#how-it-works`, `#pricing`, `#comparison`, `#faq` anchors), `billingEnabled` /
`isManaged` / `isSignedIn` gating, all handlers and props, localStorage keys
(`gemini_key`, `postiz_url`, `postiz_key_v1`, `elevenLabsKey_v1`,
`uploadUserId`, `clipwright_session`, `clipwright_auth`,
`clipwright_skip_landing`), API calls and BYOK headers, QuotaError flows,
Remotion preview/render wiring. Redesign is classes + markup structure only.

View file

@ -1,72 +0,0 @@
# Plazos de conservación reales
**Clipwright (autoalojado) · proyecto mantenido por TONVI TECH SL, B-19780394 · versión de 4 de octubre de 2026**
Esta tabla es la versión larga del apartado 5 de la
[política de privacidad](/privacidad). Cada fila
nombra **el código que aplica el plazo**, porque un plazo que no está en el
código no es un plazo: es una intención. Si cambias una constante, cambia esta
tabla y la política en el mismo commit.
Clipwright se ejecuta en tu propia máquina y **tú eres el responsable del
tratamiento**: los plazos de abajo son los valores por defecto de la aplicación,
no una obligación de TONVI TECH SL. Puedes acortarlos (o alargarlos) cambiando
las constantes de entorno.
---
## 1. Archivos de trabajo en el servidor de procesado
| Qué | Plazo | Dónde se aplica |
|---|---|---|
| Directorio del trabajo (`output/<job_id>`): vídeo de origen descargado, clips renderizados, checkpoint de transcripción, sidecars | **1 h** desde la última escritura | `app.cleanup_jobs`, `JOB_RETENTION_SECONDS` (por defecto 86400 en autoalojado) |
| Descarga de origen conservada de un trabajo por URL | Igual que el trabajo, o antes si se configura | `app._sweep_retained_sources`, `SOURCE_RETENTION_SECONDS` |
| Subidas pendientes de trabajo | **6 h** | `app._sweep_pending_uploads`, `UPLOAD_TTL_SECONDS` |
| Ficheros en `uploads/` | **1 h** (misma vuelta del barrido) | `app.cleanup_jobs` |
| **Miniaturas generadas y fotogramas muestreados** (`output/thumbnails/<sesión>`) — recortes de la cara del presentador | Sin caducidad automática: permanecen hasta que borres la sesión o el volumen de salida | Sin barrido dedicado: `app.cleanup_jobs` omite `output/thumbnails` |
| Tope de disco: se purgan los trabajos más antiguos por encima del límite | Inmediato al superarlo | `app._enforce_output_size_cap`, `OUTPUT_MAX_GB` |
La retención de fotos de actor se retiró con la función de vídeo UGC
(4-oct-2026).
## 2. Almacenamiento local
| Qué | Plazo | Dónde se aplica |
|---|---|---|
| Clips y proyectos en el disco local | Hasta que los borres o caduque el barrido de trabajos | `clipwright.api.app.cleanup_jobs`, `JOB_RETENTION_SECONDS` |
## 3. Base de datos de la aplicación (si usas cuentas)
| Qué | Plazo | Dónde se aplica |
|---|---|---|
| Datos de cuenta y proyectos | Mientras exista la cuenta; **inmediato** al borrarla | `clipwright/api/app.py`, la ruta de borrado de cuenta |
| **Declaración de derechos** (IP truncada a /24, user-agent, fecha, origen) | Con el proyecto al que pertenece → hasta 5 años | `clipwright/api/app.py` (captura) → `Project.state.rights_attestation` |
## 4. Navegador del usuario (localStorage, nunca cookies de terceros)
| Qué | Plazo | Dónde |
|---|---|---|
| Token de sesión (JWT) | 30 días o hasta cerrar sesión | `dashboard/src/lib/api.js` |
| Decisión sobre cookies | Hasta que la cambies, o hasta que cambie la versión del banner | `dashboard/src/lib/consent.js` |
| Preferencias de interfaz, atribución de primera visita | Hasta que borres los datos del sitio | `dashboard/src/lib/attribution.js` |
| Claves BYOK de proveedores de IA y de Postiz | Hasta que las borres. **Ofuscadas, no cifradas** | `dashboard/src/App.jsx` |
## 5. Registros, alertas y copias
| Qué | Plazo | Nota |
|---|---|---|
| Log de aplicación (stdout del contenedor) | **7 días** en el log rotatorio de Docker | Requiere `max-size`/`max-file` en el runtime — ver "pendiente" abajo |
| Alertas operativas | Las conserva el canal que configures | No contienen email ni título de vídeo |
| Analítica (OpenPanel, opcional, solo con consentimiento) | Identificadores 13 meses; datos brutos 25 meses | Instancia propia |
---
## Pendiente (para quien despliegue)
- **Rotación del log del contenedor**: fijar `max-size=50m`, `max-file=3` (o el
equivalente en tu runtime) en el contenedor de la API. La fila de 7 días de
arriba describe la intención; hasta que esté configurado, el plazo real depende
del demonio de Docker del host.
- **Retención en OpenPanel**: si activas la analítica, confirma en tu instancia
que los perfiles caducan a 13 meses y los eventos a 25, y borra el perfil por
`profileId` cuando llega el evento `AccountDeleted`.

View file

@ -1,89 +0,0 @@
# Terceros que tratan datos — Clipwright (autoalojado)
**Proyecto:** Clipwright · mantenido por TONVI TECH SL · NIF B-19780394 ·
Calle Puerta del Mar 18, 5º, 29005 Málaga (España) · https://git.pbento.pt/pedro-bento/clipwright
**Versión:** 4 de octubre de 2026
Clipwright es un producto **autoalojado**: lo ejecutas en tu propia máquina y
**tú eres el responsable del tratamiento** de los datos que procesas. TONVI TECH
SL no opera ninguna instancia ni recibe el contenido que procesas. Esta lista
enumera los terceros a los que el software puede enviar datos según cómo lo
configures, para que puedas documentarlos en tu propio registro de actividades
(arts. 28 y 44-49 RGPD).
Es la versión de referencia del apartado 4 de la
[política de privacidad](/privacidad).
---
## 1. Procesado de vídeo e IA (opcional según configuración)
| Proveedor | Entidad y país | Qué recibe | Garantía de transferencia | DPA |
|---|---|---|---|---|
| **Google (Gemini API)** | Google LLC / Google Ireland Ltd. — EE. UU. | Transcripción, fotogramas muestreados (pueden incluir caras), foto de referencia del presentador para miniaturas, y el **archivo de vídeo completo** solo en la comprobación de encuadre "screencast" (se borra del File API en cuanto responde) | EU-US Data Privacy Framework (Google LLC certificado) + CCT | Google Cloud / AI Studio paid data terms — **usa una clave de un proyecto de pago**: los términos gratuitos permiten entrenamiento |
## 2. Almacenamiento local
| Proveedor | Entidad y país | Qué recibe | Garantía | DPA |
|---|---|---|---|---|
| **Almacenamiento local** | Tu propia máquina | Clips, proyectos y miniaturas | Bajo tu control | No aplica |
## 3. Publicación en redes
| Proveedor | Entidad y país | Qué recibe | Garantía | DPA |
|---|---|---|---|---|
| **Postiz** (autoalojado por ti) | Tu instancia | Publicación en las redes que conectes; **custodia los tokens OAuth** de TikTok/YouTube/Instagram. Clipwright no almacena ningún token: el backend sube el clip a tu instancia de Postiz | Lo operas tú | No aplica a TONVI TECH SL |
| **TikTok / Instagram / YouTube** | Cada plataforma | El clip y los metadatos que decidas publicar, a través de Postiz | Términos de cada plataforma | Los de cada plataforma |
## 4. Analítica (opcional)
| Proveedor | Entidad y país | Qué recibe | Garantía | DPA |
|---|---|---|---|---|
| **OpenPanel** (instancia propia) | Tú | Eventos de uso. **Nunca el email.** Solo tras consentimiento | Bajo tu control; script servido desde tu propio dominio | No aplica |
## 5. Descarga de vídeo (proxies, opcional)
| Proveedor | País | Qué recibe | Garantía |
|---|---|---|---|
| **DataImpulse** (proxy residencial por GB) | ❓ **verificar sede y términos** | La URL del vídeo y sus bytes. Ningún dato de cuenta | CCT si está fuera del EEE |
| **Proxies ISP estáticos** (proveedor por confirmar) | ❓ **verificar** | Igual | CCT si está fuera del EEE |
Si no configuras `PROXY_URL` ni los proxies estáticos, todo esto queda
desactivado y las descargas salen directamente desde tu máquina.
## 6. Terceros que YA NO intervienen
| Proveedor | Qué recibía | Retirado |
|---|---|---|
| **fal.ai** | Imágenes y vídeo generados para la función de vídeo UGC con actores | Función retirada; el proyecto ya no usa fal.ai |
| **Upload-Post** | Publicación en redes y custodia de tokens | Sustituido por una instancia de Postiz autoalojada por el usuario |
| **Stripe / Aikount** | Pagos y facturación de la edición alojada | La edición alojada y la facturación se retiraron |
| **Cloudflare R2 / Cloudflare CDN** | Almacenamiento y CDN de la edición alojada | La edición alojada se retiró; el almacenamiento es local |
| **Hetzner / Contabo** | Servidores de la edición alojada | La edición alojada se retiró |
| **Google Fonts** (`fonts.googleapis.com`, `fonts.gstatic.com`) | La IP de cada visitante, en cada carga de página, sin consentimiento y sin base jurídica | 4-sep-2026 — las tipografías se sirven desde el propio dominio (`dashboard/public/fonts.css`) |
| **openpanel.dev** (script de terceros) | La IP de cada visitante antes de cualquier consentimiento | 4-sep-2026 — `op1.js` se sirve desde el propio dominio y solo tras aceptar |
| **Telegram Bot API** (Telegram FZ-LLC, Dubái, EAU) | Direcciones de email de clientes y títulos de vídeos, en las alertas operativas | 4-sep-2026 — las alertas identifican al usuario por los 8 primeros caracteres de su uuid y ya no citan títulos |
## 7. Pendiente de verificación o firma (para quien despliegue)
Nada de esto se puede hacer desde el repositorio; queda para quien opera una
instancia:
1. **Usar una clave de Gemini de un proyecto de pago.** Los términos gratuitos de
AI Studio permiten usar los datos para mejorar los modelos, lo que haría falsa
la frase "no se entrena con tu contenido".
2. **Identificar al proveedor de proxies estáticos** y el país de DataImpulse, y
firmar CCT si están fuera del EEE.
3. **Comprobar que tu instancia de Postiz** describe la custodia de tokens de
redes sociales; al ser autoalojada, no pasa por TONVI TECH SL.
4. **Sirve los emails de servicio** desde un proveedor con garantías si los
activas.
## Historial de cambios
| Fecha | Cambio |
|---|---|
| 2026-09-04 | Primera versión publicada. Altas documentadas: fal.ai, Cloudflare CDN/DNS, Aikount, OpenPanel, proxies de descarga, Google OAuth. Bajas: Google Fonts, script de openpanel.dev y datos personales hacia Telegram. |
| 2026-10-04 | Baja de fal.ai y de la galería pública UGC/imágenes de actor (función retirada). Sustitución de Upload-Post por una instancia de Postiz autoalojada por el usuario para la publicación en redes. |
| 2026-10-04 | Reformulado para la edición autoalojada: se eliminan la infraestructura alojada (Hetzner/Contabo, Cloudflare R2/CDN), los pagos (Stripe, Aikount), el correo gestionado (Namecheap) y el inicio de sesión con Google. El usuario es el responsable del tratamiento. |
| 2026-10-04 | Baja de la copia de seguridad en S3 y del doblaje de voz (funciones retiradas): se eliminan sus proveedores y variables de entorno. El almacenamiento es siempre local. |

View file

@ -1,9 +1,7 @@
# 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/`.
# configuration only — no [build-system] and no [project] table.
[tool.pytest.ini_options]
minversion = "7.0"
@ -11,13 +9,25 @@ testpaths = ["tests"]
# Makes the repo-root `clipwright/` package importable without a sys.path hack
# in tests/conftest.py.
pythonpath = ["."]
# E2E taxonomy. The fast unit suite (`tests/test_*.py`) is selected with
# `-m "not e2e"`; the E2E lanes live under `tests/e2e/` and mark themselves.
# `ml` gates the heavy ML stack (torch/ultralytics/mediapipe/faster-whisper).
markers = [
"e2e: end-to-end tests, run separately from the fast unit suite",
"pipeline: end-to-end tests that exercise the pipeline stages",
"ml: tests that need the heavy ML stack (torch/ultralytics/mediapipe/faster-whisper)",
]
# Safe: `grep -rn "async def test_" tests/` found no existing async tests, so
# auto mode does not change the behaviour of the unit suite. pytest-timeout is
# passed on the CI command line (`--timeout=120`) instead of an ini key so the
# thin unit environment (which may lack pytest-timeout) still collects.
asyncio_mode = "auto"
[tool.ruff]
line-length = 100
target-version = "py311"
extend-exclude = [
"dashboard",
"cli",
"output",
"uploads",
]

View file

@ -1,7 +1,10 @@
# 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.
# Thin test environment for BOTH the unit and E2E suites: 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. The tail adds what only the E2E lanes need: the async HTTP
# client, the ASGI lifespan helper, the ffmpeg-driven media/scene helpers and
# the download helpers.
pytest
pillow
httpx
@ -12,3 +15,9 @@ python-dotenv
google-genai
fastapi
python-multipart
pytest-asyncio==1.4.0
asgi-lifespan==2.1.0
pytest-timeout==2.4.0
scenedetect==0.7
tqdm==4.67.3
yt-dlp==2026.8.19

1
tests/e2e/__init__.py Normal file
View file

@ -0,0 +1 @@
"""End-to-end tests (API, pipeline, browser). See tests/e2e/conftest.py."""

View file

@ -0,0 +1 @@
"""API-level end-to-end tests (one module per route family)."""

152
tests/e2e/api/conftest.py Normal file
View file

@ -0,0 +1,152 @@
"""API E2E fixtures: an in-process ASGI client, a fake pipeline subprocess, and
an event-based queue helper.
``httpx.ASGITransport`` is used on purpose: ``starlette.testclient.TestClient``
runs the app's lifespan (which starts the queue worker, the resume scanner and
the drain signal handler) on its own event loop, which leaks tasks and fights
the test's loop. The client below never runs lifespan; the startup-recovery
test is the one place that opts into ``LifespanManager`` explicitly.
"""
import asyncio
import contextlib
import io
import json
import pytest
class FakePopen:
"""Stand-in for ``subprocess.Popen`` on the real worker path.
Parses the ``-o``/``--output`` directory out of ``cmd``, writes a canonical
``<base>_clip_1.mp4`` plus a metadata JSON there, and exposes the surface
``run_job`` needs (``stdout``, ``poll()``, ``returncode``, ``kill()``).
The canonical filename keeps ``_clips_actually_rendered`` deterministic
even though ``enqueue_output`` runs on a thread and may not have consumed
the ``CLIP_READY`` line yet.
"""
# Per-test knobs.
base_name = "clipwright"
clips = 1
returncode = 0
lines = None
instances = []
def __init__(self, cmd, stdout=None, stderr=None, env=None, cwd=None, **kwargs):
self.cmd = list(cmd)
self.returncode = type(self).returncode
self.killed = False
type(self).instances.append(self)
output_dir = self._output_dir(self.cmd)
if output_dir:
self._write_outputs(output_dir)
self.stdout = io.BytesIO(self._stdout_bytes())
@staticmethod
def _output_dir(cmd):
for flag in ("-o", "--output"):
if flag in cmd:
idx = cmd.index(flag)
if idx + 1 < len(cmd):
return cmd[idx + 1]
return None
def _stdout_bytes(self):
lines = self.lines
if lines is None:
lines = [f"CLIP_READY 0 {self.base_name}_clip_1.mp4", "done"]
return ("\n".join(lines) + "\n").encode("utf-8")
def _write_outputs(self, output_dir):
import os
os.makedirs(output_dir, exist_ok=True)
shorts = []
for i in range(self.clips):
shorts.append({
"start": float(i * 10),
"end": float(i * 10 + 8),
"predicted_score": 80 - i,
"video_title_for_youtube_short": f"Fake clip {i + 1}",
"viral_hook_text": f"Hook {i + 1}",
"video_description_for_tiktok": "Fake #test",
"video_description_for_instagram": "Fake #test",
})
with open(os.path.join(output_dir, f"{self.base_name}_clip_{i + 1}.mp4"), "wb") as fh:
fh.write(b"\x00" * 2048)
with open(os.path.join(output_dir, f"{self.base_name}_metadata.json"), "w") as fh:
json.dump({"shorts": shorts, "cost_analysis": {"total_cost": 0.0}}, fh)
def poll(self):
return self.returncode
def kill(self):
self.killed = True
def wait(self, timeout=None):
return self.returncode
@pytest.fixture
def fake_popen(monkeypatch):
"""Install ``FakePopen`` as ``app.subprocess.Popen`` for one test.
``app.subprocess`` is the shared ``subprocess`` module, so this also covers
any other module that resolves ``subprocess.Popen`` at call time.
"""
import clipwright.api.app as app
FakePopen.instances = []
monkeypatch.setattr(app.subprocess, "Popen", FakePopen)
return FakePopen
@pytest.fixture
async def client(app_state):
"""In-process HTTP client bound to the app under test (no lifespan)."""
from httpx import ASGITransport, AsyncClient
app = app_state.app
transport = ASGITransport(app=app.app)
async with AsyncClient(transport=transport, base_url="http://testserver") as c:
yield c
@pytest.fixture
def job_done(monkeypatch):
"""Return ``await job_done(job_id)``: run the queue until that job ends.
Wraps ``app.run_job_wrapper`` (resolved by global name at call time) so the
wrapper can set an ``asyncio.Event`` once the original returns, then runs
``app.process_queue()`` as a task and waits on the event with a bound. No
sleeps. The worker is cancelled in ``finally``.
"""
async def _wait(job_id, timeout=10.0):
import clipwright.api.app as app
done = asyncio.Event()
original = app.run_job_wrapper
async def wrapper(jid):
try:
await original(jid)
finally:
if jid == job_id:
done.set()
monkeypatch.setattr(app, "run_job_wrapper", wrapper)
worker = asyncio.create_task(app.process_queue())
try:
await asyncio.wait_for(done.wait(), timeout)
finally:
worker.cancel()
with contextlib.suppress(asyncio.CancelledError):
await worker
return _wait

View file

@ -0,0 +1,46 @@
"""L1 API core: the per-job "download all clips" ZIP bundle."""
import io
import json
import zipfile
import pytest
pytestmark = pytest.mark.e2e
async def test_download_all_returns_a_zip_of_every_clip(client, app_state, seeded_job):
job_id = seeded_job(job_id="job-zip", base="bundle", clips=2)
resp = await client.get(f"/api/jobs/{job_id}/download-all")
assert resp.status_code == 200
assert resp.headers["content-type"] == "application/zip"
with zipfile.ZipFile(io.BytesIO(resp.content)) as zf:
names = sorted(zf.namelist())
assert names == [
"clip_01_bundle_clip_1.mp4",
"clip_02_bundle_clip_2.mp4",
]
for name in names:
assert zf.read(name)
async def test_download_all_without_metadata_is_404(client):
resp = await client.get("/api/jobs/nobody-home/download-all")
assert resp.status_code == 404
assert resp.json()["detail"] == "Job not found"
async def test_download_all_without_clip_files_is_404(client, app_state):
job_id = "job-empty"
job_dir = app_state.out / job_id
job_dir.mkdir()
# Metadata promises a clip; the file itself was never rendered.
(job_dir / "empty_metadata.json").write_text(json.dumps({
"shorts": [{"start": 0.0, "end": 5.0, "video_title_for_youtube_short": "x"}],
}))
resp = await client.get(f"/api/jobs/{job_id}/download-all")
assert resp.status_code == 404
assert resp.json()["detail"] == "No clip files found for this job"

View file

@ -0,0 +1,263 @@
"""L2 API editing E2E: ``POST /api/edit`` and ``POST /api/effects/generate``.
Both routes resolve their heavy ``VideoEditor`` by module-global name at call
time, so the editor (Gemini upload + ffmpeg filter build/apply) is stubbed at
``app.VideoEditor``. The clip on disk is a REAL ffmpeg video because the edit
route probes it with OpenCV and the effects route probes it with ffprobe.
"""
import json
import os
import shutil
import pytest
pytestmark = pytest.mark.e2e
app_module = pytest.importorskip("clipwright.api.app")
class StubVideoEditor:
"""Records calls; writes the edited output; can fail at any stage."""
filter_data = {"filter_string": "hue=s=0", "edits": [{"type": "bw_moment"}]}
effects_config = {
"segments": [{
"startSec": 0, "endSec": 6, "zoom": 1.1,
"zoomCenterX": 0.5, "zoomCenterY": 0.5,
"brightness": 1.0, "contrast": 1.0, "saturate": 1.0,
}]
}
error_stage = None
instances = []
def __init__(self, api_key=None):
self.api_key = api_key
self.uploaded = []
type(self).instances.append(self)
def upload_video(self, path):
if self.error_stage == "upload":
raise RuntimeError("upload exploded")
self.uploaded.append(path)
return {"name": "files/fake"}
def get_ffmpeg_filter(self, vid, duration, **kwargs):
if self.error_stage == "filter":
raise RuntimeError("filter exploded")
self.filter_kwargs = kwargs
return self.filter_data
def get_effects_config(self, vid, duration, **kwargs):
if self.error_stage == "effects":
raise RuntimeError("effects exploded")
self.effects_kwargs = kwargs
return self.effects_config
def apply_edits(self, input_path, output_path, filter_data):
if self.error_stage == "apply":
raise RuntimeError("apply exploded")
with open(output_path, "wb") as fh:
fh.write(b"edited-bytes")
@pytest.fixture
def stub_editor(monkeypatch):
StubVideoEditor.instances = []
StubVideoEditor.error_stage = None
StubVideoEditor.filter_data = {
"filter_string": "hue=s=0", "edits": [{"type": "bw_moment"}]}
StubVideoEditor.effects_config = {
"segments": [{
"startSec": 0, "endSec": 6, "zoom": 1.1,
"zoomCenterX": 0.5, "zoomCenterY": 0.5,
"brightness": 1.0, "contrast": 1.0, "saturate": 1.0,
}]
}
monkeypatch.setattr(app_module, "VideoEditor", StubVideoEditor)
return StubVideoEditor
def _make_job(app_state, media_factory, job_id="job-edit", base="edit",
output_format="auto"):
"""A completed job whose canonical clip is a real, probeable video."""
job_dir = app_state.out / job_id
job_dir.mkdir(parents=True, exist_ok=True)
shutil.copy(media_factory.six, job_dir / f"{base}_clip_1.mp4")
clip = {
"start": 0.0,
"end": 6.0,
"video_title_for_youtube_short": "Edit clip",
"viral_hook_text": "Hook",
"video_url": f"/videos/{job_id}/{base}_clip_1.mp4",
}
(job_dir / f"{base}_metadata.json").write_text(json.dumps({
"shorts": [clip],
"transcript": {
"language": "en",
"segments": [{"start": 0.0, "end": 6.0, "text": "hi there",
"words": [{"word": "hi", "start": 1.0, "end": 1.4}]}],
},
"output_format": output_format,
"cost_analysis": {"total_cost": 0.0},
}))
app_module.jobs[job_id] = {
"status": "completed",
"logs": [],
"result": {"clips": [dict(clip)], "cost_analysis": {}},
"user_id": None,
}
return {"job_id": job_id, "base": base, "dir": job_dir, "clip": clip}
@pytest.fixture
def editor_job(app_state, media_factory):
return _make_job(app_state, media_factory)
# --- POST /api/edit ---------------------------------------------------------
class TestEdit:
async def test_success_writes_file_and_persists(self, client, app_state,
stub_editor, editor_job):
job_id, base = editor_job["job_id"], editor_job["base"]
resp = await client.post("/api/edit", json={
"job_id": job_id, "clip_index": 0, "api_key": "test-key"})
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["success"] is True
assert data["edit_plan"] == stub_editor.filter_data
assert data["new_video_url"] == (
f"/videos/{job_id}/edited_{base}_clip_1.mp4")
# The edited file exists on disk...
assert (editor_job["dir"] / f"edited_{base}_clip_1.mp4").is_file()
# ...and the new current version is persisted to metadata + memory.
meta = json.loads((editor_job["dir"] / f"{base}_metadata.json").read_text())
assert meta["shorts"][0]["video_url"] == data["new_video_url"]
mem = app_module.jobs[job_id]["result"]["clips"][0]
assert mem["video_url"] == data["new_video_url"]
# The temp ASCII copy the editor used was cleaned up.
assert not (editor_job["dir"] / f"temp_input_{job_id}.mp4").exists()
async def test_404_unknown_job(self, client, stub_editor):
resp = await client.post("/api/edit", json={
"job_id": "nope", "clip_index": 0, "api_key": "k"})
assert resp.status_code == 404
async def test_missing_file_is_wrapped_as_500(self, client, stub_editor,
editor_job):
# The route raises its 404 INSIDE the try that ends in a catch-all
# `except Exception -> 500`, so a missing input file surfaces as 500
# (documented deviation from the 404 the spec expected).
resp = await client.post("/api/edit", json={
"job_id": editor_job["job_id"], "clip_index": 0, "api_key": "k",
"input_filename": "does-not-exist.mp4"})
assert resp.status_code == 500
async def test_400_no_result(self, client, stub_editor):
app_module.jobs["job-noresult"] = {
"status": "completed", "result": {}, "user_id": None}
resp = await client.post("/api/edit", json={
"job_id": "job-noresult", "clip_index": 0, "api_key": "k"})
assert resp.status_code == 400
async def test_400_missing_key(self, client, monkeypatch, stub_editor,
editor_job):
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
resp = await client.post("/api/edit", json={
"job_id": editor_job["job_id"], "clip_index": 0})
assert resp.status_code == 400
assert "Gemini" in resp.json()["detail"]
async def test_500_editor_error(self, client, stub_editor, editor_job):
stub_editor.error_stage = "filter"
resp = await client.post("/api/edit", json={
"job_id": editor_job["job_id"], "clip_index": 0, "api_key": "k"})
assert resp.status_code == 500
async def test_input_filename_is_basenamed(self, client, app_state,
stub_editor, editor_job):
# The target exists ONLY inside the job dir; the traversal path one
# level up does not. Success proves the name was basenamed.
(editor_job["dir"] / "secret.mp4").write_bytes(b"inside")
assert not (app_state.out / "secret.mp4").exists()
resp = await client.post("/api/edit", json={
"job_id": editor_job["job_id"], "clip_index": 0, "api_key": "k",
"input_filename": "../secret.mp4"})
assert resp.status_code == 200, resp.text
assert resp.json()["new_video_url"].endswith("/edited_secret.mp4")
assert (editor_job["dir"] / "edited_secret.mp4").is_file()
# --- POST /api/effects/generate --------------------------------------------
class TestEffects:
async def test_success_returns_config(self, client, stub_editor,
editor_job):
resp = await client.post(
"/api/effects/generate",
headers={"X-Gemini-Key": "test-key"},
json={"job_id": editor_job["job_id"], "clip_index": 0})
assert resp.status_code == 200, resp.text
assert resp.json() == {"effects": stub_editor.effects_config}
# The real clip was probed and the transcript from metadata was loaded.
assert stub_editor.instances[-1].effects_kwargs["width"] == 320
assert stub_editor.instances[-1].effects_kwargs["height"] == 180
assert stub_editor.instances[-1].effects_kwargs["transcript"] is not None
async def test_404_unknown_job(self, client, stub_editor):
resp = await client.post(
"/api/effects/generate", headers={"X-Gemini-Key": "k"},
json={"job_id": "nope", "clip_index": 0})
assert resp.status_code == 404
async def test_404_missing_file(self, client, stub_editor, editor_job):
resp = await client.post(
"/api/effects/generate", headers={"X-Gemini-Key": "k"},
json={"job_id": editor_job["job_id"], "clip_index": 0,
"input_filename": "nope.mp4"})
assert resp.status_code == 404
async def test_400_no_result(self, client, stub_editor):
app_module.jobs["job-noresult-2"] = {
"status": "completed", "result": {}, "user_id": None}
resp = await client.post(
"/api/effects/generate", headers={"X-Gemini-Key": "k"},
json={"job_id": "job-noresult-2", "clip_index": 0})
assert resp.status_code == 400
async def test_400_missing_key(self, client, monkeypatch, stub_editor,
editor_job):
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
resp = await client.post(
"/api/effects/generate",
json={"job_id": editor_job["job_id"], "clip_index": 0})
assert resp.status_code == 400
async def test_500_editor_error(self, client, stub_editor, editor_job):
stub_editor.error_stage = "effects"
resp = await client.post(
"/api/effects/generate", headers={"X-Gemini-Key": "k"},
json={"job_id": editor_job["job_id"], "clip_index": 0})
assert resp.status_code == 500
async def test_500_none_config(self, client, stub_editor, editor_job):
stub_editor.effects_config = None
resp = await client.post(
"/api/effects/generate", headers={"X-Gemini-Key": "k"},
json={"job_id": editor_job["job_id"], "clip_index": 0})
assert resp.status_code == 500
async def test_input_filename_is_basenamed(self, client, app_state,
media_factory, stub_editor,
editor_job):
# Real video only inside the job dir; the traversal target one level
# up is absent, so success proves the name was basenamed.
shutil.copy(media_factory.six, editor_job["dir"] / "secret.mp4")
assert not (app_state.out / "secret.mp4").exists()
resp = await client.post(
"/api/effects/generate", headers={"X-Gemini-Key": "k"},
json={"job_id": editor_job["job_id"], "clip_index": 0,
"input_filename": "../secret.mp4"})
assert resp.status_code == 200, resp.text

View file

@ -0,0 +1,82 @@
"""Phase-0 foundation smoke test.
Proves the shared E2E scaffolding works before the per-route lanes are built:
1. ``/health`` answers through the in-process ASGI client.
2. ``app_state`` gives each test a private ``jobs`` dict (isolation).
3. A disk-seeded completed job is recoverable the same way a restart recovers.
4. The session ``media_factory`` produces ffprobe-able fixture videos.
"""
import json
import subprocess
import pytest
pytestmark = pytest.mark.e2e
async def test_health_ok(client):
resp = await client.get("/health")
assert resp.status_code == 200
assert resp.json() == {"status": "ok"}
async def test_app_state_isolation_a(app_state):
# Fresh per test: nothing seeded this dict.
assert app_state.app.jobs == {}
app_state.app.jobs["isolation-a"] = {"status": "sentinel"}
async def test_app_state_isolation_b(app_state):
# If the previous test's write leaked, this dict would not be empty.
assert app_state.app.jobs == {}
app_state.app.jobs["isolation-b"] = {"status": "sentinel"}
async def test_disk_seeded_job_is_recoverable(app_state, seeded_job, client):
job_id = seeded_job(job_id="job-smoke", base="smoke", clips=1)
job = app_state.app.jobs[job_id]
assert job["status"] == "completed"
assert job["output_dir"] == str(app_state.out / job_id)
clips = job["result"]["clips"]
assert len(clips) == 1
assert clips[0]["video_url"].endswith("/smoke_clip_1.mp4")
clip_path = app_state.out / job_id / "smoke_clip_1.mp4"
assert clip_path.is_file() and clip_path.stat().st_size > 0
# The recovered clip is actually servable: this proves the /videos mount was
# repointed at the per-test output tree (it captures its directory at
# import time, so the app_state rebind has to move it explicitly).
resp = await client.get(clips[0]["video_url"])
assert resp.status_code == 200
assert resp.content
def _probe(path):
out = subprocess.run(
["ffprobe", "-v", "error", "-show_entries",
"format=duration:stream=codec_type", "-of", "json", str(path)],
capture_output=True, text=True, check=True,
)
return json.loads(out.stdout)
def test_media_factory_files_are_probeable(media_factory):
sixty = _probe(media_factory.sixty)
assert float(sixty["format"]["duration"]) == pytest.approx(60.0, abs=1.0)
assert {"video", "audio"} <= {s["codec_type"] for s in sixty["streams"]}
six = _probe(media_factory.six)
assert float(six["format"]["duration"]) == pytest.approx(6.0, abs=1.0)
assert {"video", "audio"} <= {s["codec_type"] for s in six["streams"]}
silent = _probe(media_factory.silent)
assert {s["codec_type"] for s in silent["streams"]} == {"video"}
cuts = _probe(media_factory.cuts)
assert float(cuts["format"]["duration"]) == pytest.approx(6.0, abs=1.0)
assert {"video"} <= {s["codec_type"] for s in cuts["streams"]}

View file

@ -0,0 +1,65 @@
"""L1 API core: liveness/readiness probes and the dashboard bootstrap config.
Drives the real app through ``httpx.ASGITransport`` (no lifespan), so the
``_stopping`` flag is flipped by hand the same way SIGTERM does at runtime.
"""
import pytest
pytestmark = pytest.mark.e2e
async def test_health_is_ok(client):
resp = await client.get("/health")
assert resp.status_code == 200
assert resp.json() == {"status": "ok"}
async def test_health_ready_when_running(client, app_state):
app_state.app._stopping = False
resp = await client.get("/health/ready")
assert resp.status_code == 200
assert resp.json() == {"status": "ready"}
async def test_health_ready_is_503_while_stopping(client, app_state, monkeypatch):
monkeypatch.setattr(app_state.app, "_stopping", True)
resp = await client.get("/health/ready")
assert resp.status_code == 503
assert resp.json() == {"status": "stopping"}
async def test_config_youtube_enabled(client, app_state, monkeypatch):
monkeypatch.setattr(app_state.app, "DISABLE_YOUTUBE_URL", False)
monkeypatch.delenv("LLM_BASE_URL", raising=False)
monkeypatch.delenv("LLM_PROVIDER", raising=False)
resp = await client.get("/api/config")
assert resp.status_code == 200
body = resp.json()
assert body["youtubeUrlEnabled"] is True
assert body["billingEnabled"] is False
assert body["jobRetentionSeconds"] == app_state.app.JOB_RETENTION_SECONDS
# No OpenAI-compatible server configured -> the dashboard is told nothing.
assert body["localLlm"] is None
async def test_config_youtube_disabled(client, app_state, monkeypatch):
monkeypatch.setattr(app_state.app, "DISABLE_YOUTUBE_URL", True)
resp = await client.get("/api/config")
assert resp.status_code == 200
assert resp.json()["youtubeUrlEnabled"] is False
async def test_config_describes_local_llm(client, app_state, monkeypatch):
monkeypatch.setenv("LLM_PROVIDER", "openai")
monkeypatch.setenv("LLM_BASE_URL", "http://127.0.0.1:11434")
monkeypatch.delenv("LLM_MODEL", raising=False)
resp = await client.get("/api/config")
assert resp.status_code == 200
assert resp.json()["localLlm"] == {
"provider": "openai",
"model": "llama3.1:8b",
"baseUrl": "http://127.0.0.1:11434",
}

150
tests/e2e/api/test_hook.py Normal file
View file

@ -0,0 +1,150 @@
"""L2 API editing E2E: POST /api/hook (add / update / remove).
The overlay is a REAL ffmpeg pass using the repo's bundled fonts (the fonts/
directory is present in the test checkout, so no network fetch happens). The
clip is a real fixture video with audio.
"""
import json
import os
import shutil
import subprocess
import pytest
pytestmark = pytest.mark.e2e
app_module = pytest.importorskip("clipwright.api.app")
def _probe(path):
out = subprocess.run(
["ffprobe", "-v", "error", "-show_entries",
"stream=codec_type:format=duration", "-of", "json", str(path)],
capture_output=True, text=True, check=True)
return json.loads(out.stdout)
def _make_job(app_state, media_factory, job_id="job-hook", base="hk"):
job_dir = app_state.out / job_id
job_dir.mkdir(parents=True, exist_ok=True)
shutil.copy(media_factory.six, job_dir / f"{base}_clip_1.mp4")
clip = {
"start": 0.0,
"end": 6.0,
"video_title_for_youtube_short": "Hook clip",
"video_url": f"/videos/{job_id}/{base}_clip_1.mp4",
}
(job_dir / f"{base}_metadata.json").write_text(json.dumps({
"shorts": [clip], "output_format": "auto", "cost_analysis": {}}))
app_module.jobs[job_id] = {
"status": "completed",
"logs": [],
"result": {"clips": [dict(clip)], "cost_analysis": {}},
"user_id": None,
}
return {"job_id": job_id, "base": base, "dir": job_dir,
"meta": job_dir / f"{base}_metadata.json"}
@pytest.fixture
def hook_job(app_state, media_factory):
return _make_job(app_state, media_factory)
def _hooked_files(job):
return sorted(job["dir"].glob("hooked_*_hk_clip_1.mp4"))
# --- POST /api/hook ---------------------------------------------------------
class TestHook:
async def test_add_burns_hook(self, client, hook_job):
resp = await client.post("/api/hook", json={
"job_id": hook_job["job_id"], "clip_index": 0,
"text": "HELLO WORLD", "style": "pill", "position": "top",
"size": "M", "font": "anton"})
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["success"] is True
assert data["burned_hook"]["text"] == "HELLO WORLD"
assert data["burned_hook"]["style"] == "pill"
assert data["new_video_url"].startswith(
f"/videos/{hook_job['job_id']}/hooked_")
assert data["new_video_url"].endswith("_hk_clip_1.mp4")
out = _hooked_files(hook_job)
assert len(out) == 1
assert out[0].stat().st_size > 0
assert "video" in {s["codec_type"] for s in _probe(out[0])["streams"]}
meta = json.loads(hook_job["meta"].read_text())
assert meta["shorts"][0]["auto_hook"]["text"] == "HELLO WORLD"
assert meta["shorts"][0]["video_url"] == data["new_video_url"]
mem = app_module.jobs[hook_job["job_id"]]["result"]["clips"][0]
assert mem["auto_hook"]["text"] == "HELLO WORLD"
async def test_update_replaces_without_stacking(self, client, hook_job):
first = await client.post("/api/hook", json={
"job_id": hook_job["job_id"], "clip_index": 0,
"text": "FIRST", "style": "pill"})
assert first.status_code == 200, first.text
second = await client.post("/api/hook", json={
"job_id": hook_job["job_id"], "clip_index": 0,
"text": "SECOND", "style": "dark"})
assert second.status_code == 200, second.text
name = second.json()["new_video_url"].split("/")[-1]
# Exactly one hooked_ prefix: the old burn was walked back, not stacked.
assert name.count("hooked_") == 1
assert name.endswith("_hk_clip_1.mp4")
meta = json.loads(hook_job["meta"].read_text())
assert meta["shorts"][0]["auto_hook"]["text"] == "SECOND"
assert meta["shorts"][0]["auto_hook"]["style"] == "dark"
async def test_remove_strips_hook(self, client, hook_job):
add = await client.post("/api/hook", json={
"job_id": hook_job["job_id"], "clip_index": 0,
"text": "REMOVE ME", "style": "pill"})
assert add.status_code == 200
resp = await client.post("/api/hook", json={
"job_id": hook_job["job_id"], "clip_index": 0, "remove": True})
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["burned_hook"] is None
assert data["new_video_url"] == (
f"/videos/{hook_job['job_id']}/hk_clip_1.mp4")
meta = json.loads(hook_job["meta"].read_text())
assert "auto_hook" not in meta["shorts"][0]
mem = app_module.jobs[hook_job["job_id"]]["result"]["clips"][0]
assert "auto_hook" not in mem
async def test_empty_text_400(self, client, hook_job):
resp = await client.post("/api/hook", json={
"job_id": hook_job["job_id"], "clip_index": 0, "text": " "})
assert resp.status_code == 400
assert "Hook text" in resp.json()["detail"]
async def test_404_unknown_job(self, client):
resp = await client.post("/api/hook", json={
"job_id": "nope", "clip_index": 0, "text": "x"})
assert resp.status_code == 404
async def test_404_missing_metadata(self, client, hook_job):
os.remove(hook_job["meta"])
resp = await client.post("/api/hook", json={
"job_id": hook_job["job_id"], "clip_index": 0, "text": "x"})
assert resp.status_code == 404
async def test_404_clip_out_of_range(self, client, hook_job):
resp = await client.post("/api/hook", json={
"job_id": hook_job["job_id"], "clip_index": 5, "text": "x"})
assert resp.status_code == 404
async def test_404_missing_file(self, client, hook_job):
resp = await client.post("/api/hook", json={
"job_id": hook_job["job_id"], "clip_index": 0, "text": "x",
"input_filename": "gone.mp4"})
assert resp.status_code == 404

View file

@ -0,0 +1,423 @@
"""L3 E2E: the Postiz integration routes.
Everything outbound is stubbed at the ``clipwright.integrations.postiz`` seam
(``app.py`` calls the module functions through ``asyncio.to_thread``), so the
tests exercise the real route logic: credential resolution, channel selection
by id vs the legacy ``platforms`` fallback, the per-provider ``settings``
mapping, the schedule window and the error translation.
The unit suite (``tests/test_postiz.py``) already pins the helper functions;
these are the ASGI-level contracts through the shared ``client`` fixture.
"""
import functools
from datetime import datetime, timedelta, timezone
from types import SimpleNamespace
import pytest
pytestmark = pytest.mark.e2e
POSTIZ_HEADERS = {"X-Postiz-Url": "https://postiz.example", "X-Postiz-Key": "k"}
@pytest.fixture
def postiz_stub(monkeypatch):
"""Capture every Postiz call and return scripted responses.
Mutate ``stub.integrations`` / ``stub.*_result`` / ``stub.errors`` per test.
"""
from clipwright.integrations import postiz as postiz_mod
class Stub:
def __init__(self):
self.calls = {}
self.integrations = [
{"id": "yt-1", "name": "Main", "identifier": "youtube", "disabled": False},
{"id": "yt-2", "name": "Second", "identifier": "youtube", "disabled": False},
{"id": "ig-1", "name": "IG", "identifier": "instagram-standalone",
"disabled": False},
{"id": "tt-1", "name": "TT", "identifier": "tiktok-business",
"disabled": False},
]
self.upload_result = {"id": "media-1", "path": "media/path"}
self.create_result = [{"postId": "p1", "integration": "yt-1"}]
self.posts_result = [
{"id": "sched-1", "date": "2030-01-01T00:00:00.000Z",
"integration": {"id": "yt-1"}},
]
self.delete_result = None
self.analytics_result = {"views": 5, "likes": 1}
self.analytics_post_result = {"likes": 3}
self.errors = {}
def _record(self, name, *args, **kwargs):
self.calls.setdefault(name, []).append((args, kwargs))
if name in self.errors:
raise self.errors[name]
return {
"list_integrations": self.integrations,
"upload_media": self.upload_result,
"create_post": self.create_result,
"list_posts": self.posts_result,
"delete_post": self.delete_result,
"analytics": self.analytics_result,
"analytics_post": self.analytics_post_result,
}[name]
stub = Stub()
for name in ("list_integrations", "upload_media", "create_post",
"list_posts", "delete_post", "analytics", "analytics_post"):
monkeypatch.setattr(postiz_mod, name, functools.partial(stub._record, name))
return stub
def _payload(stub):
"""The payload handed to ``create_post`` (base, key, payload)."""
return stub.calls["create_post"][0][0][2]
# --------------------------------------------------------------------------- #
# POST /api/postiz/post
# --------------------------------------------------------------------------- #
async def test_post_success_by_integration_id(client, seeded_job, postiz_stub):
job_id = seeded_job(job_id="job-post", base="pw", clips=1)
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": job_id, "clip_index": 0,
"integration_ids": ["ig-1", "tt-1"],
"title": "My Title", "description": "Watch this #fun #clips"},
)
assert resp.status_code == 200, resp.text
body = resp.json()
assert body["success"] is True
assert body["results"] == postiz_stub.create_result
assert [p["platform"] for p in body["posted"]] == ["instagram", "tiktok"]
assert [p["name"] for p in body["posted"]] == ["IG", "TT"]
payload = _payload(postiz_stub)
assert payload["type"] == "now"
assert payload["shortLink"] is False
posts = payload["posts"]
assert [p["integration"]["id"] for p in posts] == ["ig-1", "tt-1"]
# __type echoes the real identifier, not the mapped platform.
assert [p["settings"]["__type"] for p in posts] == \
["instagram-standalone", "tiktok-business"]
assert posts[0]["settings"] == {"__type": "instagram-standalone", "post_type": "post"}
assert posts[1]["settings"]["content_posting_method"] == "DIRECT_POST"
assert posts[0]["value"][0]["content"] == "Watch this #fun #clips"
assert posts[0]["value"][0]["image"][0] == {"id": "media-1", "path": "media/path"}
# The local clip was re-uploaded to Postiz first.
assert postiz_stub.calls["upload_media"][0][0][2].endswith("pw_clip_1.mp4")
async def test_post_legacy_platforms_use_the_identifier_map(client, seeded_job, postiz_stub):
job_id = seeded_job(job_id="job-legacy", base="pw")
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": job_id, "clip_index": 0,
"platforms": ["instagram", "tiktok"]},
)
assert resp.status_code == 200, resp.text
posts = _payload(postiz_stub)["posts"]
assert [p["integration"]["id"] for p in posts] == ["ig-1", "tt-1"]
assert [p["settings"]["__type"] for p in posts] == \
["instagram-standalone", "tiktok-business"]
assert [e["platform"] for e in resp.json()["posted"]] == ["instagram", "tiktok"]
async def test_post_future_schedule_sets_schedule_type(client, seeded_job, postiz_stub):
job_id = seeded_job(job_id="job-sched", base="pw")
future = datetime.now(timezone.utc) + timedelta(days=2)
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": job_id, "clip_index": 0, "integration_ids": ["yt-1"],
"scheduled_date": future.isoformat()},
)
assert resp.status_code == 200, resp.text
payload = _payload(postiz_stub)
assert payload["type"] == "schedule"
assert payload["date"] == future.astimezone(timezone.utc).strftime(
"%Y-%m-%dT%H:%M:%S.000Z")
async def test_post_schedule_accepts_an_iso_offset(client, seeded_job, postiz_stub):
job_id = seeded_job(job_id="job-tz", base="pw")
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": job_id, "clip_index": 0, "integration_ids": ["yt-1"],
"scheduled_date": "2030-06-01T12:00:00+02:00"},
)
assert resp.status_code == 200, resp.text
# The offset is normalised to UTC.
assert _payload(postiz_stub)["date"] == "2030-06-01T10:00:00.000Z"
async def test_post_past_schedule_is_400_before_upload(client, seeded_job, postiz_stub):
job_id = seeded_job(job_id="job-past", base="pw")
past = (datetime.now(timezone.utc) - timedelta(hours=1)).isoformat()
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": job_id, "clip_index": 0, "integration_ids": ["yt-1"],
"scheduled_date": past},
)
assert resp.status_code == 400
assert "past" in resp.json()["detail"].lower()
assert "upload_media" not in postiz_stub.calls
assert "create_post" not in postiz_stub.calls
async def test_post_unparseable_schedule_is_400(client, seeded_job, postiz_stub):
job_id = seeded_job(job_id="job-bad-date", base="pw")
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": job_id, "clip_index": 0, "integration_ids": ["yt-1"],
"scheduled_date": "tomorrow"},
)
assert resp.status_code == 400
async def test_post_unknown_integration_id_is_400(client, seeded_job, postiz_stub):
job_id = seeded_job(job_id="job-unknown", base="pw")
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": job_id, "clip_index": 0, "integration_ids": ["nope"]},
)
assert resp.status_code == 400
assert "nope" in resp.json()["detail"]
assert "upload_media" not in postiz_stub.calls
async def test_post_disabled_integration_id_is_400(client, seeded_job, postiz_stub):
job_id = seeded_job(job_id="job-disabled", base="pw")
postiz_stub.integrations = [
{"id": "ig-1", "name": "IG", "identifier": "instagram-standalone",
"disabled": True},
]
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": job_id, "clip_index": 0, "integration_ids": ["ig-1"]},
)
assert resp.status_code == 400
assert "Disabled" in resp.json()["detail"]
assert "upload_media" not in postiz_stub.calls
async def test_post_not_connected_platform_is_400(client, seeded_job, postiz_stub):
job_id = seeded_job(job_id="job-notconn", base="pw")
postiz_stub.integrations = [
{"id": "yt-1", "name": "Main", "identifier": "youtube", "disabled": False},
]
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": job_id, "clip_index": 0, "platforms": ["instagram"]},
)
assert resp.status_code == 400
assert "Not connected" in resp.json()["detail"]
assert "upload_media" not in postiz_stub.calls
async def test_post_missing_credentials_is_400(client, seeded_job, postiz_stub,
monkeypatch):
monkeypatch.delenv("POSTIZ_URL", raising=False)
monkeypatch.delenv("POSTIZ_API_KEY", raising=False)
job_id = seeded_job(job_id="job-creds", base="pw")
body = {"job_id": job_id, "clip_index": 0, "platforms": ["youtube"]}
r = await client.post("/api/postiz/post", headers={"X-Postiz-Key": "k"}, json=body)
assert r.status_code == 400 and "URL" in r.json()["detail"]
r = await client.post("/api/postiz/post",
headers={"X-Postiz-Url": "https://p.example"}, json=body)
assert r.status_code == 400 and "key" in r.json()["detail"].lower()
async def test_post_no_channels_is_400(client, seeded_job, postiz_stub):
job_id = seeded_job(job_id="job-nochan", base="pw")
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": job_id, "clip_index": 0},
)
assert resp.status_code == 400
assert "No channels" in resp.json()["detail"]
assert "upload_media" not in postiz_stub.calls
async def test_post_unknown_job_is_404(client, postiz_stub):
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": "nobody-home", "clip_index": 0, "integration_ids": ["yt-1"]},
)
assert resp.status_code == 404
assert resp.json()["detail"] == "Job not found"
assert postiz_stub.calls == {}
async def test_post_missing_clip_file_is_404(client, app_state, postiz_stub):
app_state.app.jobs["job-nofile"] = {
"result": {"clips": [{"video_url": "/videos/job-nofile/missing.mp4"}]},
}
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": "job-nofile", "clip_index": 0, "integration_ids": ["yt-1"]},
)
assert resp.status_code == 404
assert "not found" in resp.json()["detail"].lower()
assert "upload_media" not in postiz_stub.calls
async def test_post_clip_index_out_of_range_is_400(client, seeded_job, postiz_stub):
job_id = seeded_job(job_id="job-index", base="pw")
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": job_id, "clip_index": 9, "integration_ids": ["yt-1"]},
)
assert resp.status_code == 400
assert "range" in resp.json()["detail"].lower()
async def test_post_upload_failure_is_502(client, seeded_job, postiz_stub):
job_id = seeded_job(job_id="job-upfail", base="pw")
postiz_stub.upload_result = {}
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": job_id, "clip_index": 0, "integration_ids": ["yt-1"]},
)
assert resp.status_code == 502
assert "upload failed" in resp.json()["detail"].lower()
assert "create_post" not in postiz_stub.calls
async def test_post_postiz_error_is_translated(client, seeded_job, postiz_stub):
from clipwright.integrations import postiz
job_id = seeded_job(job_id="job-err", base="pw")
postiz_stub.errors["create_post"] = postiz.PostizError(
429, "Postiz API Error: slow down")
resp = await client.post(
"/api/postiz/post",
headers=POSTIZ_HEADERS,
json={"job_id": job_id, "clip_index": 0, "integration_ids": ["yt-1"]},
)
assert resp.status_code == 429
assert resp.json()["detail"] == "Postiz API Error: slow down"
# --------------------------------------------------------------------------- #
# Other Postiz routes
# --------------------------------------------------------------------------- #
async def test_integrations_route_normalises_disabled(client, postiz_stub):
postiz_stub.integrations = [
{"id": "a", "identifier": "youtube", "disabled": 1},
{"id": "b", "identifier": "youtube", "disabled": 0},
{"id": "c", "identifier": "youtube"},
]
resp = await client.get("/api/postiz/integrations", headers=POSTIZ_HEADERS)
assert resp.status_code == 200
integrations = resp.json()["integrations"]
assert [i["disabled"] for i in integrations] == [True, False, False]
async def test_integrations_route_translates_postiz_error(client, postiz_stub):
from clipwright.integrations import postiz
postiz_stub.errors["list_integrations"] = postiz.PostizError(
401, "Postiz API Error: bad key")
resp = await client.get("/api/postiz/integrations", headers=POSTIZ_HEADERS)
assert resp.status_code == 401
assert "bad key" in resp.json()["detail"]
async def test_scheduled_route_backfills_and_widens_window(client, postiz_stub):
resp = await client.get("/api/postiz/scheduled", headers=POSTIZ_HEADERS,
params={"days": 30})
assert resp.status_code == 200
posts = resp.json()["scheduled_posts"]
# Postiz calls it ``date``; the consumer reads ``scheduled_date``.
assert posts[0]["scheduled_date"] == "2030-01-01T00:00:00.000Z"
assert posts[0]["date"] == "2030-01-01T00:00:00.000Z"
args = postiz_stub.calls["list_posts"][0][0]
start = datetime.fromisoformat(args[2].replace("Z", "+00:00"))
end = datetime.fromisoformat(args[3].replace("Z", "+00:00"))
# The default window is widened to at least POSTIZ_SCHEDULED_MIN_DAYS (90).
assert (end - start) >= timedelta(days=89)
async def test_scheduled_route_forwards_explicit_dates(client, postiz_stub):
resp = await client.get(
"/api/postiz/scheduled", headers=POSTIZ_HEADERS,
params={"start_date": "2030-01-01T00:00:00.000Z",
"end_date": "2030-02-01T00:00:00.000Z"})
assert resp.status_code == 200
args = postiz_stub.calls["list_posts"][0][0]
assert args[2] == "2030-01-01T00:00:00.000Z"
assert args[3] == "2030-02-01T00:00:00.000Z"
async def test_scheduled_route_translates_postiz_error(client, postiz_stub):
from clipwright.integrations import postiz
postiz_stub.errors["list_posts"] = postiz.PostizError(500, "Postiz API Error: boom")
resp = await client.get("/api/postiz/scheduled", headers=POSTIZ_HEADERS)
assert resp.status_code == 500
assert "boom" in resp.json()["detail"]
async def test_cancel_scheduled_deletes_and_reports(client, postiz_stub):
resp = await client.delete("/api/postiz/scheduled/sched-9",
headers=POSTIZ_HEADERS)
assert resp.status_code == 200
assert resp.json() == {"success": True, "id": "sched-9"}
assert postiz_stub.calls["delete_post"][0][0][2] == "sched-9"
async def test_analytics_route_forwards_channel_and_days(client, postiz_stub):
resp = await client.get("/api/postiz/analytics", headers=POSTIZ_HEADERS,
params={"integration": "yt-1", "days": 7})
assert resp.status_code == 200
assert resp.json() == postiz_stub.analytics_result
args = postiz_stub.calls["analytics"][0][0]
assert args[2] == "yt-1" and args[3] == 7
async def test_analytics_posts_route_forwards_post_id(client, postiz_stub):
resp = await client.get("/api/postiz/analytics/posts", headers=POSTIZ_HEADERS,
params={"post_id": "post-9", "days": 3})
assert resp.status_code == 200
assert resp.json() == postiz_stub.analytics_post_result
args = postiz_stub.calls["analytics_post"][0][0]
assert args[2] == "post-9" and args[3] == 3
# --------------------------------------------------------------------------- #
# The identifier -> platform map that drives settings.__type
# --------------------------------------------------------------------------- #
def test_settings_echo_the_real_identifier(app_state):
app = app_state.app
assert app._identifier_platform("instagram-standalone") == "instagram"
assert app._identifier_platform("tiktok-business") == "tiktok"
assert app._identifier_platform("youtube") == "youtube"
ig = app._postiz_settings("instagram-standalone", "T", "caption", [])
assert ig == {"__type": "instagram-standalone", "post_type": "post"}
tt = app._postiz_settings("tiktok-business", "T", "caption", [])
assert tt["__type"] == "tiktok-business"
assert tt["content_posting_method"] == "DIRECT_POST"

View file

@ -0,0 +1,340 @@
"""L1 API core: the /api/process submit matrix.
The worker never runs here (ASGITransport skips lifespan), so every assertion is
about the QUEUED record: validation branches, the chosen ingest path, the env
overrides handed to the child, the attestation, and the on-disk resume manifest.
URL tests stub ``assert_public_url`` (the autouse no-network guard would abort a
real DNS lookup) and/or ``_probe_youtube_quality``; IP-literal URLs exercise the
real SSRF guard without touching DNS.
"""
import json
import os
import pytest
pytestmark = pytest.mark.e2e
WATCH = "https://www.youtube.com/watch?v=abcdefghijk"
KEY = {"X-Gemini-Key": "test-key"}
@pytest.fixture
def allow_urls(monkeypatch):
"""Let hostname URLs pass the SSRF guard without a DNS lookup."""
import clipwright.core.security_utils as security_utils
monkeypatch.setattr(security_utils, "assert_public_url", lambda url: url)
def _job(client, resp):
assert resp.status_code == 200, resp.text
body = resp.json()
assert "job_id" in body
return body["job_id"]
async def _submit_json(client, body):
return await client.post("/api/process", json=body, headers=KEY)
async def _submit_file(client, data, files, headers=KEY):
return await client.post("/api/process", data=data, files=files, headers=headers)
# --------------------------------------------------------------------------- #
# Happy paths: one per ingest source
# --------------------------------------------------------------------------- #
async def test_submit_url_queues_with_attestation_and_manifest(
client, app_state, allow_urls, monkeypatch):
monkeypatch.delenv("PUBLIC_API_URL", raising=False)
resp = await _submit_json(client, {"url": WATCH, "acknowledged": True})
job_id = _job(client, resp)
job = app_state.app.jobs[job_id]
assert job["status"] == "queued"
assert WATCH in job["cmd"] and "--keep-original" in job["cmd"]
assert job["env"]["GEMINI_API_KEY"] == "test-key"
assert job["attestation"]["acknowledged"] is True
assert job["attestation"]["source"] == "url"
assert job["attestation"]["ip"] # client host (testserver / 127.0.0.1)
manifest = json.loads((app_state.out / job_id / ".resume.json").read_text())
assert manifest["cmd"] == job["cmd"]
assert manifest["priority"] == 2
# Queued, not run: the queue holds exactly this one entry.
assert app_state.app.job_queue.qsize() == 1
async def test_submit_multipart_file(client, app_state, media_factory):
resp = await _submit_file(
client,
{"acknowledged": "true"},
{"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")},
)
job_id = _job(client, resp)
job = app_state.app.jobs[job_id]
input_path = job["cmd"][job["cmd"].index("-i") + 1]
assert os.path.dirname(input_path) == str(app_state.up)
assert os.path.basename(input_path).startswith(job_id)
assert os.path.basename(input_path).endswith("clip.mp4")
assert os.path.exists(input_path)
assert job["attestation"]["source"] == "file"
async def test_submit_completed_upload_id(client, app_state, media_factory):
reserved = await client.post("/api/uploads", json={"filename": "clip.mp4"})
uid = reserved.json()["upload_id"]
assert (await client.put(f"/api/uploads/{uid}",
content=media_factory.six.read_bytes())).status_code == 200
resp = await _submit_json(client, {"upload_id": uid, "acknowledged": True})
job_id = _job(client, resp)
job = app_state.app.jobs[job_id]
input_path = job["cmd"][job["cmd"].index("-i") + 1]
assert os.path.exists(input_path)
assert os.path.basename(input_path) == f"{job_id}_clip.mp4"
assert uid not in app_state.app.pending_uploads
assert job["attestation"]["source"] == "upload_id"
async def test_submit_thumbnail_session_id(client, app_state, media_factory, monkeypatch):
sid = "sess-e2e"
app_state.app.thumbnail_sessions[sid] = {
"user_id": None,
"video_path": str(media_factory.six),
"transcript_ready": False,
"transcript": None,
}
resp = await _submit_json(client, {"thumbnail_session_id": sid, "acknowledged": True})
job_id = _job(client, resp)
job = app_state.app.jobs[job_id]
assert "-i" in job["cmd"]
assert os.path.exists(job["cmd"][job["cmd"].index("-i") + 1])
assert job["attestation"]["source"] == "thumbnail_session"
async def test_submit_thumbnail_session_missing_404(client, app_state):
resp = await _submit_json(client, {"thumbnail_session_id": "nope", "acknowledged": True})
assert resp.status_code == 404
# --------------------------------------------------------------------------- #
# Validation branches
# --------------------------------------------------------------------------- #
async def test_submit_without_input_is_400(client):
resp = await _submit_json(client, {"acknowledged": True})
assert resp.status_code == 400
assert "Must provide URL, File or upload_id" in resp.json()["detail"]
async def test_submit_without_ack_is_400(client, allow_urls):
resp = await _submit_json(client, {"url": WATCH})
assert resp.status_code == 400
assert "confirm you own the content" in resp.json()["detail"]
async def test_submit_without_key_is_400(client, media_factory, monkeypatch):
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
monkeypatch.delenv("LLM_BASE_URL", raising=False)
monkeypatch.delenv("LLM_PROVIDER", raising=False)
resp = await _submit_file(
client,
{"acknowledged": "true"},
{"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")},
headers={},
)
assert resp.status_code == 400
assert resp.json()["detail"] == "Missing X-Gemini-Key header"
async def test_submit_without_key_but_local_llm_queues(
client, app_state, media_factory, monkeypatch):
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
monkeypatch.setenv("LLM_PROVIDER", "openai")
monkeypatch.setenv("LLM_BASE_URL", "http://127.0.0.1:9")
resp = await _submit_file(
client,
{"acknowledged": "true"},
{"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")},
headers={},
)
job_id = _job(client, resp)
# A local-LLM job must not leak a stale Google key into the child env.
assert "GEMINI_API_KEY" not in app_state.app.jobs[job_id]["env"]
async def test_submit_youtube_disabled_is_403(client, app_state, allow_urls, monkeypatch):
monkeypatch.setattr(app_state.app, "DISABLE_YOUTUBE_URL", True)
resp = await _submit_json(client, {"url": WATCH, "acknowledged": True})
assert resp.status_code == 403
assert "disabled on this deployment" in resp.json()["detail"]
async def test_submit_playlist_is_400(client, allow_urls):
resp = await _submit_json(client, {
"url": "https://www.youtube.com/playlist?list=PLabc",
"acknowledged": True,
})
assert resp.status_code == 400
assert "playlist" in resp.json()["detail"]
async def test_submit_ssrf_url_is_400(client):
# Real guard, IP literal -> no DNS, rejected as non-public.
resp = await _submit_json(client, {
"url": "http://169.254.169.254/latest/meta-data",
"acknowledged": True,
})
assert resp.status_code == 400
assert "can't be processed" in resp.json()["detail"]
async def test_submit_short_source_is_400(client, app_state, allow_urls, monkeypatch):
monkeypatch.setattr(app_state.app, "MIN_SOURCE_SECONDS", 45)
monkeypatch.setattr(app_state.app, "QUALITY_GATE_MIN_HEIGHT", 0)
async def probe(url):
return {"duration": 10, "max_height": 1080}
monkeypatch.setattr(app_state.app, "_probe_youtube_quality", probe)
resp = await _submit_json(client, {"url": WATCH, "acknowledged": True})
assert resp.status_code == 400
assert "10s" in resp.json()["detail"]
# The aborted job dir must not linger (only the thumbnails mount remains).
assert [p.name for p in app_state.out.iterdir()] == ["thumbnails"]
async def test_quality_gate_needs_confirmation_then_force_low_quality(
client, app_state, allow_urls, monkeypatch):
monkeypatch.setattr(app_state.app, "QUALITY_GATE_MIN_HEIGHT", 720)
monkeypatch.setattr(app_state.app, "MIN_SOURCE_SECONDS", 0)
async def probe(url):
return {"duration": 600, "max_height": 480}
monkeypatch.setattr(app_state.app, "_probe_youtube_quality", probe)
first = await _submit_json(client, {"url": WATCH, "acknowledged": True})
assert first.status_code == 200
assert first.json()["needs_confirmation"] is True
assert first.json()["quality_check"]["max_height"] == 480
assert first.json()["quality_check"]["min_height"] == 720
assert app_state.app.jobs == {}
forced = await _submit_json(client, {
"url": WATCH, "acknowledged": True, "force_low_quality": True,
})
job_id = _job(client, forced)
assert app_state.app.jobs[job_id]["status"] == "queued"
async def test_submit_bad_webhook_is_400(client, media_factory):
resp = await _submit_file(
client,
{"acknowledged": "true", "webhook_url": "http://127.0.0.1/hook"},
{"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")},
)
assert resp.status_code == 400
assert "Invalid webhook_url" in resp.json()["detail"]
async def test_target_clips_validation(client, media_factory):
bad_type = await _submit_file(
client,
{"acknowledged": "true", "target_clips": "lots"},
{"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")},
)
assert bad_type.status_code == 400
assert "target_clips must be a number" in bad_type.json()["detail"]
out_of_range = await _submit_file(
client,
{"acknowledged": "true", "target_clips": "0"},
{"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")},
)
assert out_of_range.status_code == 400
assert "target_clips must be between 1 and 15" in out_of_range.json()["detail"]
async def test_clip_range_validation(client, media_factory):
too_short = await _submit_file(
client,
{"acknowledged": "true", "clip_min_seconds": "2"},
{"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")},
)
assert too_short.status_code == 400
assert "clip_min_seconds must be between 5 and 175" in too_short.json()["detail"]
inverted = await _submit_file(
client,
{"acknowledged": "true", "clip_min_seconds": "10", "clip_max_seconds": "12"},
{"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")},
)
assert inverted.status_code == 400
assert "at least 5s above" in inverted.json()["detail"]
# --------------------------------------------------------------------------- #
# Env mapping: layouts, hooks, captions, format, generation controls
# --------------------------------------------------------------------------- #
async def test_env_mapping_for_layouts_hooks_captions_and_format(
client, app_state, media_factory):
resp = await _submit_file(
client,
{
"acknowledged": "true",
"layouts": "split,auto",
"auto_hook": "true",
"auto_hook_style": "classic",
"captions": "false",
"output_format": "vertical",
"target_clips": "3",
"clip_min_seconds": "10",
"clip_max_seconds": "30",
},
{"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")},
)
job_id = _job(client, resp)
env = app_state.app.jobs[job_id]["env"]
assert env["SPLIT_LAYOUT"] == "1"
assert env["SPEAKER_SIGNAL"] == "1" # implied by split
assert env["AUTO_LAYOUT"] == "1"
assert env["AUTO_HOOK"] == "1"
assert env["AUTO_HOOK_STYLE"] == "classic"
assert env["AUTO_CAPTIONS"] == "0"
assert env["CLIP_TARGET_MIN"] == "3" and env["CLIP_TARGET_MAX"] == "3"
assert env["CLIP_MIN_SECONDS"] == "10.0"
assert env["CLIP_MAX_SECONDS"] == "30.0"
assert "--format" in app_state.app.jobs[job_id]["cmd"]
assert app_state.app.jobs[job_id]["cmd"][
app_state.app.jobs[job_id]["cmd"].index("--format") + 1] == "vertical"
async def test_layout_none_switches_picker_off(client, app_state, media_factory):
resp = await _submit_file(
client,
{"acknowledged": "true", "layouts": "none"},
{"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")},
)
job_id = _job(client, resp)
assert app_state.app.jobs[job_id]["env"]["AUTO_LAYOUT"] == "0"
async def test_unknown_output_format_is_normalised_to_auto(client, app_state, media_factory):
resp = await _submit_file(
client,
{"acknowledged": "true", "output_format": "widescreen"},
{"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")},
)
job_id = _job(client, resp)
assert "--format" not in app_state.app.jobs[job_id]["cmd"]

View file

@ -0,0 +1,188 @@
"""L1 API core: the real worker path.
``fake_popen`` replaces ``subprocess.Popen`` so ``run_job`` sees a finished
child that already wrote a canonical clip + metadata; ``job_done`` runs
``process_queue`` as a task and waits on an event set by a wrapper around
``run_job_wrapper`` (no sleeps, bounded wait). Webhook delivery, transient
auto-retry, and resume-from-manifest are covered here too.
"""
import asyncio
import json
import os
import sys
import pytest
pytestmark = pytest.mark.e2e
KEY = {"X-Gemini-Key": "test-key"}
async def _submit_file(client, media_factory, **form):
data = {"acknowledged": "true", **form}
return await client.post(
"/api/process",
data=data,
files={"file": ("clip.mp4", media_factory.six.read_bytes(), "video/mp4")},
headers=KEY,
)
async def test_queued_job_runs_to_completion(client, app_state, media_factory,
fake_popen, job_done):
resp = await _submit_file(client, media_factory)
assert resp.status_code == 200, resp.text
job_id = resp.json()["job_id"]
assert app_state.app.jobs[job_id]["status"] == "queued"
await job_done(job_id)
job = app_state.app.jobs[job_id]
assert job["status"] == "completed"
clips = job["result"]["clips"]
assert len(clips) == 1
assert clips[0]["video_url"] == f"/videos/{job_id}/clipwright_clip_1.mp4"
assert (app_state.out / job_id / "clipwright_clip_1.mp4").stat().st_size > 0
# Terminal state drops the resume manifest.
assert not (app_state.out / job_id / ".resume.json").exists()
# The fake was actually invoked with the queued command (other FakePopen
# instances are the ffprobe duration probes, which share the module Popen).
workers = [i for i in fake_popen.instances if "clipwright.pipeline.main" in i.cmd]
assert workers and workers[0].cmd[0] == sys.executable
async def test_webhook_delivered_with_signature(client, app_state, media_factory,
fake_popen, job_done, monkeypatch):
captured = {}
class FakeAsyncClient:
def __init__(self, *a, **k):
pass
async def __aenter__(self):
return self
async def __aexit__(self, *exc):
return False
async def post(self, url, content=None, headers=None):
captured["url"] = url
captured["body"] = content
captured["headers"] = headers
delivered.set()
class _Resp:
status_code = 200
return _Resp()
delivered = asyncio.Event()
monkeypatch.setattr(app_state.app.httpx, "AsyncClient", FakeAsyncClient)
monkeypatch.delenv("PUBLIC_API_URL", raising=False)
resp = await _submit_file(
client, media_factory,
webhook_url="http://8.8.8.8/hook",
webhook_secret="s3cret",
)
assert resp.status_code == 200, resp.text
job_id = resp.json()["job_id"]
await job_done(job_id)
await asyncio.wait_for(delivered.wait(), 5)
payload = json.loads(captured["body"].decode())
assert payload["event"] == "job.completed"
assert payload["job_id"] == job_id
assert payload["status"] == "completed"
assert payload["clips"][0]["index"] == 0
assert payload["clips"][0]["title"] == "Fake clip 1"
assert payload["clips"][0]["video_url"] == (
f"http://testserver/videos/{job_id}/clipwright_clip_1.mp4")
expected = app_state.app._sign_webhook(captured["body"], "s3cret")
assert captured["headers"]["X-Clipwright-Signature"] == expected
async def test_transient_failure_is_auto_retried(app_state, media_factory,
fake_popen, monkeypatch):
app = app_state.app
monkeypatch.setattr(app, "AUTO_RETRY_DELAY_SECONDS", 0)
fake_popen.returncode = 1
fake_popen.lines = ["CUDA out of memory while starting"]
job_id = "job-retry"
out_dir = app_state.out / job_id
out_dir.mkdir()
app.jobs[job_id] = {
"status": "queued",
"logs": app._TimedLog(["❌ CUDA out of memory while starting"]),
"cmd": [sys.executable, "-m", "clipwright.pipeline.main",
"-i", "x", "-o", str(out_dir)],
"env": {},
"output_dir": str(out_dir),
"webhook_url": None,
"webhook_secret": None,
"user_id": None,
}
enqueued = []
retried = asyncio.Event()
original_enqueue = app._enqueue_job
def capture(jid, priority=2):
original_enqueue(jid, priority)
enqueued.append((jid, priority))
retried.set()
monkeypatch.setattr(app, "_enqueue_job", capture)
# Balance the queue's task_done() and the semaphore's release().
await app.concurrency_semaphore.acquire()
app.job_queue.put_nowait((2, 0, job_id))
await app.job_queue.get()
await app.run_job_wrapper(job_id)
await asyncio.wait_for(retried.wait(), 5)
job = app.jobs[job_id]
assert job["status"] == "queued"
assert job["auto_retries"] == 1
assert enqueued == [(job_id, 1)]
# Half-made outputs are cleared; the source survives for the retry.
assert not (out_dir / "clipwright_clip_1.mp4").exists()
assert not (out_dir / "clipwright_metadata.json").exists()
async def test_manifest_resumes_an_interrupted_job(app_state):
app = app_state.app
job_id = "job-resume"
job_dir = app_state.out / job_id
job_dir.mkdir()
app._write_resume_manifest(job_id, ["python", "-m", "clipwright.pipeline.main"],
priority=2, user_id=None, reservation_id=None)
keep = app._resume_interrupted_jobs()
assert keep == set()
job = app.jobs[job_id]
assert job["status"] == "queued"
assert any("Resuming" in line for line in job["logs"])
assert app.job_queue.qsize() == 1
assert app._read_manifest(job_id)["attempts"] == 1
async def test_manifest_gives_up_after_max_attempts(app_state):
app = app_state.app
job_id = "job-poison"
job_dir = app_state.out / job_id
job_dir.mkdir()
(job_dir / ".resume.json").write_text(json.dumps({
"cmd": ["python"], "priority": 2, "attempts": app.MAX_RESUME_ATTEMPTS,
}))
app._resume_interrupted_jobs()
assert job_id not in app.jobs
assert app.job_queue.qsize() == 0
assert not (job_dir / ".resume.json").exists()

View file

@ -0,0 +1,256 @@
"""L2 API editing E2E: GET .../scenes and POST /api/clip/reframe.
``/scenes`` cuts the clip from source with real ffmpeg and encodes a preview,
but the ML detectors it calls live in the heavy ``clipwright.pipeline.main``
module (absent in the thin E2E env). A fake module is injected into
``sys.modules`` returning deterministic scene/face data — the real module is
never imported. The re-render path is stubbed at ``recut.perform_recut``.
"""
import json
import os
import shutil
import sys
import types
import pytest
pytestmark = pytest.mark.e2e
app_module = pytest.importorskip("clipwright.api.app")
from clipwright.media import recut # noqa: E402
TRANSCRIPT = {
"language": "en",
"segments": [{
"start": 0.0, "end": 6.0, "text": "hello there",
"words": [{"word": "hello", "start": 1.0, "end": 1.4},
{"word": "there", "start": 3.0, "end": 3.4}],
}],
}
class _Frames:
def __init__(self, n):
self._n = n
def get_frames(self):
return self._n
def _fake_main():
"""The three functions app.py's scenes builder actually calls."""
fake = types.ModuleType("clipwright.pipeline.main")
def detect_scenes(path):
return [(_Frames(0), _Frames(30)), (_Frames(30), _Frames(60))], 10.0
def get_video_resolution(path):
return 320, 180
def detect_face_candidates(frame):
return [{"box": [100, 40, 60, 60]}]
fake.detect_scenes = detect_scenes
fake.get_video_resolution = get_video_resolution
fake.detect_face_candidates = detect_face_candidates
return fake
@pytest.fixture
def fake_pipeline_main(monkeypatch):
import clipwright.pipeline as pipeline_pkg
fake = _fake_main()
monkeypatch.setitem(sys.modules, "clipwright.pipeline.main", fake)
# Belt and braces: `from clipwright.pipeline import main` resolves the
# parent attribute before falling back to the sys.modules entry.
monkeypatch.setattr(pipeline_pkg, "main", fake, raising=False)
return fake
def _make_job(app_state, media_factory, job_id="job-scenes", base="scenes",
output_format="auto", crop_overrides=None):
job_dir = app_state.out / job_id
job_dir.mkdir(parents=True, exist_ok=True)
shutil.copy(media_factory.six, job_dir / f"{base}_clip_1.mp4")
# Source lives in uploads/<job_id>_*, which is where _locate_source looks
# first for an upload job.
shutil.copy(media_factory.six, app_state.up / f"{job_id}_source.mp4")
clip = {
"start": 0.0,
"end": 6.0,
"video_title_for_youtube_short": "Scenes clip",
"video_url": f"/videos/{job_id}/{base}_clip_1.mp4",
}
if crop_overrides is not None:
clip["crop_overrides"] = crop_overrides
(job_dir / f"{base}_metadata.json").write_text(json.dumps({
"shorts": [clip],
"transcript": TRANSCRIPT,
"output_format": output_format,
"cost_analysis": {},
}))
app_module.jobs[job_id] = {
"status": "completed",
"logs": [],
"result": {"clips": [dict(clip)], "cost_analysis": {}},
"user_id": None,
}
return {"job_id": job_id, "base": base, "dir": job_dir,
"meta": job_dir / f"{base}_metadata.json",
"source": app_state.up / f"{job_id}_source.mp4"}
@pytest.fixture
def scenes_job(app_state, media_factory):
return _make_job(app_state, media_factory)
@pytest.fixture
def fake_recut(monkeypatch):
calls = []
def fake(**kwargs):
calls.append(kwargs)
name = f"recut_1_{kwargs['clean_name']}"
with open(os.path.join(kwargs["output_dir"], name), "wb") as fh:
fh.write(b"recut")
return name, name
monkeypatch.setattr(recut, "perform_recut", fake)
return calls
# --- GET /api/clip/{job}/{clip}/scenes --------------------------------------
class TestScenes:
async def test_success_lists_scenes_and_preview(self, client, scenes_job,
fake_pipeline_main):
resp = await client.get(f"/api/clip/{scenes_job['job_id']}/0/scenes")
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["source_width"] == 320
assert data["source_height"] == 180
# 9:16 crop of a 320x180 source: min(320, 180*9/16) / 320.
assert data["crop_width_fraction"] == pytest.approx(
(180 * 9 / 16) / 320, abs=1e-3)
assert data["saved_overrides"] == {}
assert len(data["scenes"]) == 2
first = data["scenes"][0]
assert first["index"] == 0
assert (first["start"], first["end"]) == (0.0, 3.0)
# The face box [100,40,60,60] centres at x=130/320, y=70/180.
assert first["suggested_center"] == pytest.approx(130 / 320, abs=1e-3)
assert first["suggested_center_y"] == pytest.approx(70 / 180, abs=1e-3)
# The preview and the per-scene thumbnails were really written.
assert data["preview_url"] == (
f"/videos/{scenes_job['job_id']}/temp_preview_0.mp4")
assert (scenes_job["dir"] / "temp_preview_0.mp4").is_file()
assert first["thumbnail_url"].endswith("temp_scene_0_000.jpg")
assert (scenes_job["dir"] / "temp_scene_0_000.jpg").is_file()
# The temp cut was cleaned up (the canonical clip is scenes_clip_1.mp4,
# so scope the glob to the per-call work token).
assert not list(scenes_job["dir"].glob("scenes_0_*.mp4"))
async def test_serves_saved_overrides(self, client, app_state,
media_factory, fake_pipeline_main):
job = _make_job(app_state, media_factory, job_id="job-scenes-ov",
base="ov", crop_overrides={"0": 0.25})
data = (await client.get(f"/api/clip/{job['job_id']}/0/scenes")).json()
assert data["saved_overrides"] == {"0": 0.25}
async def test_horizontal_400(self, client, app_state, media_factory,
fake_pipeline_main):
job = _make_job(app_state, media_factory, job_id="job-scenes-h",
base="h", output_format="horizontal")
resp = await client.get(f"/api/clip/{job['job_id']}/0/scenes")
assert resp.status_code == 400
async def test_no_source_409(self, client, scenes_job, fake_pipeline_main):
os.remove(scenes_job["source"])
resp = await client.get(f"/api/clip/{scenes_job['job_id']}/0/scenes")
assert resp.status_code == 409
async def test_404_unknown_job(self, client, fake_pipeline_main):
assert (await client.get(
"/api/clip/nope/0/scenes")).status_code == 404
async def test_404_missing_metadata(self, client, scenes_job,
fake_pipeline_main):
os.remove(scenes_job["meta"])
assert (await client.get(
f"/api/clip/{scenes_job['job_id']}/0/scenes")).status_code == 404
async def test_404_clip_out_of_range(self, client, scenes_job,
fake_pipeline_main):
assert (await client.get(
f"/api/clip/{scenes_job['job_id']}/4/scenes")).status_code == 404
# --- POST /api/clip/reframe -------------------------------------------------
class TestReframe:
async def test_success_persists_overrides(self, client, scenes_job,
fake_recut):
resp = await client.post("/api/clip/reframe", json={
"job_id": scenes_job["job_id"], "clip_index": 0,
"crop_overrides": {
"0": 0.2,
"1": {"top": 0.6, "bottom": {"x": 0.3, "y": 0.4}},
}})
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["framed_scenes"] == [0, 1]
call = fake_recut[0]
assert call["input_path"].endswith(f"{scenes_job['job_id']}_source.mp4")
assert call["reframe"] is True
assert call["crop_overrides"][0] == 0.2
assert call["crop_overrides"][1]["top"] == {"x": 0.6, "y": 0.5}
assert call["crop_overrides"][1]["bottom"] == {"x": 0.3, "y": 0.4}
assert call["captions_transcript"]["segments"][0]["words"]
meta = json.loads(scenes_job["meta"].read_text())
stored = meta["shorts"][0]
assert stored["crop_overrides"]["0"] == 0.2
assert stored["video_url"] == data["new_video_url"]
mem = app_module.jobs[scenes_job["job_id"]]["result"]["clips"][0]
assert mem["crop_overrides"]["0"] == 0.2
async def test_400_no_usable_overrides(self, client, scenes_job,
fake_recut):
for overrides in ({}, {"nope": "x"}, {"0": "garbage"}):
resp = await client.post("/api/clip/reframe", json={
"job_id": scenes_job["job_id"], "clip_index": 0,
"crop_overrides": overrides})
assert resp.status_code == 400, overrides
assert fake_recut == []
async def test_horizontal_400(self, client, app_state, media_factory,
fake_recut):
job = _make_job(app_state, media_factory, job_id="job-reframe-h",
base="rh", output_format="horizontal")
resp = await client.post("/api/clip/reframe", json={
"job_id": job["job_id"], "clip_index": 0,
"crop_overrides": {"0": 0.5}})
assert resp.status_code == 400
assert fake_recut == []
async def test_409_no_source(self, client, scenes_job, fake_recut):
os.remove(scenes_job["source"])
resp = await client.post("/api/clip/reframe", json={
"job_id": scenes_job["job_id"], "clip_index": 0,
"crop_overrides": {"0": 0.5}})
assert resp.status_code == 409
assert fake_recut == []
async def test_404_unknown_job(self, client, fake_recut):
assert (await client.post("/api/clip/reframe", json={
"job_id": "nope", "clip_index": 0,
"crop_overrides": {"0": 0.5}})).status_code == 404
async def test_404_clip_out_of_range(self, client, scenes_job, fake_recut):
assert (await client.post("/api/clip/reframe", json={
"job_id": scenes_job["job_id"], "clip_index": 4,
"crop_overrides": {"0": 0.5}})).status_code == 404

View file

@ -0,0 +1,125 @@
"""L3 E2E: security cross-cuts shared by the API surface.
Pins the path allowlist on the ``/videos`` mount, the traversal refusal on the
``/thumbnails`` mount, the basename sanitisation of client-supplied filenames,
the credential scrubbing of logs, and the deliberate absence of an auth gate in
this single-tenant fork (so a future accidental gate fails loudly here).
"""
import os
import pytest
pytestmark = pytest.mark.e2e
# --------------------------------------------------------------------------- #
# /videos allowlist
# --------------------------------------------------------------------------- #
async def test_videos_serves_clips_but_refuses_sidecars(client, app_state, seeded_job):
job_id = seeded_job(job_id="job-sec", base="pw", clips=1)
job_dir = app_state.out / job_id
# The sensitive sidecars the old plain-StaticFiles mount handed out.
(job_dir / ".owner").write_text("user-uuid")
(job_dir / ".resume.json").write_text('{"webhook_secret": "s"}')
(job_dir / ".instance").write_text("instance-id")
(job_dir / ".transcript_checkpoint.json").write_text("{}")
(job_dir / "notes.json").write_text("{}")
served = await client.get(f"/videos/{job_id}/pw_clip_1.mp4")
assert served.status_code == 200
assert served.content
for name in (".owner", ".resume.json", ".instance",
".transcript_checkpoint.json", "pw_metadata.json", "notes.json"):
resp = await client.get(f"/videos/{job_id}/{name}")
assert resp.status_code == 404, f"{name} leaked from /videos"
async def test_media_guard_rejects_traversal_and_hidden_paths(app_state):
app = app_state.app
assert app._media_guard("job/pw_clip_1.mp4")
for bad in ("../app.py", "job/../../app.py", "job/../.resume.json",
"job/.owner", "job/pw_metadata.json", "/etc/passwd"):
assert not app._media_guard(bad), bad
async def test_videos_encoded_traversal_is_404(client, app_state, seeded_job):
seeded_job(job_id="job-trav", base="pw")
for path in ("/videos/%2e%2e/%2e%2e/etc/passwd",
"/videos/job-trav/..%2f..%2fetc%2fpasswd.mp4",
"/videos/job-trav/%2e%2e/%2e%2e/etc/passwd.mp4"):
resp = await client.get(path)
assert resp.status_code == 404, path
# --------------------------------------------------------------------------- #
# /thumbnails mount
# --------------------------------------------------------------------------- #
async def test_thumbnails_serves_files_but_blocks_traversal(client, app_state):
(app_state.out / "thumbnails" / "ok.jpg").write_bytes(b"jpeg")
ok = await client.get("/thumbnails/ok.jpg")
assert ok.status_code == 200
assert ok.content == b"jpeg"
for path in ("/thumbnails/%2e%2e/%2e%2e/etc/passwd",
"/thumbnails/..%2f..%2fetc%2fpasswd",
"/thumbnails/%2e%2e/secret.txt"):
resp = await client.get(path)
assert resp.status_code == 404, path
# --------------------------------------------------------------------------- #
# Client-supplied filenames are basenamed
# --------------------------------------------------------------------------- #
async def test_edit_input_filename_traversal_is_basenamed(client, app_state, seeded_job):
job_id = seeded_job(job_id="job-edit", base="pw", clips=1)
# A traversal name must resolve under OUTPUT_DIR/<job>/ after basename().
resp = await client.post(
"/api/edit",
json={"job_id": job_id, "clip_index": 0, "api_key": "k",
"input_filename": "../../outside.mp4"},
)
# The route's broad except turns the missing-file 404 into a 500, but the
# detail still shows which path it resolved: the basenamed one.
detail = resp.json()["detail"]
assert detail.endswith(os.path.join(job_id, "outside.mp4"))
assert ".." not in detail
# --------------------------------------------------------------------------- #
# Log credential scrubbing
# --------------------------------------------------------------------------- #
def test_scrub_secrets_masks_embedded_credentials(app_state):
scrub = app_state.app._scrub_secrets
assert scrub("proxy http://user:pass@host:8080/x") == \
"proxy http://***:***@host:8080/x"
assert scrub("socks5://alice:s3cr3t@proxy.example:1080") == \
"socks5://***:***@proxy.example:1080"
assert scrub("no credentials here") == "no credentials here"
assert scrub("https://host/path") == "https://host/path"
# --------------------------------------------------------------------------- #
# No auth gate (single-tenant fork) — pin the intentional openness
# --------------------------------------------------------------------------- #
async def test_public_endpoints_need_no_auth(client, app_state, seeded_job):
# No Authorization / API-key header on any of these.
cfg = await client.get("/api/config")
assert cfg.status_code == 200
job_id = seeded_job(job_id="job-open", base="pw", clips=1)
status = await client.get(f"/api/status/{job_id}")
assert status.status_code == 200
clip = await client.get(f"/videos/{job_id}/pw_clip_1.mp4")
assert clip.status_code == 200
bundle = await client.get(f"/api/jobs/{job_id}/download-all")
assert bundle.status_code == 200
assert bundle.headers["content-type"] == "application/zip"

View file

@ -0,0 +1,66 @@
"""L1 API core: job status polling and source-video streaming."""
import pytest
pytestmark = pytest.mark.e2e
async def test_status_of_a_queued_job(client, app_state):
job_id = "job-status"
app_state.app.jobs[job_id] = {
"status": "queued",
"logs": app_state.app._TimedLog(["Job queued."]),
"result": None,
"partial": None,
}
app_state.app._enqueue_job(job_id)
resp = await client.get(f"/api/status/{job_id}")
assert resp.status_code == 200
body = resp.json()
assert body["status"] == "queued"
assert body["logs"] == ["Job queued."]
assert body["log_times"] is not None and len(body["log_times"]) == 1
assert body["queue"]["position"] == 1
assert body["result"] is None
async def test_status_of_a_disk_recovered_job(client, app_state, seeded_job):
job_id = seeded_job(job_id="job-status-disk", base="status", clips=1)
resp = await client.get(f"/api/status/{job_id}")
assert resp.status_code == 200
body = resp.json()
assert body["status"] == "completed"
assert body["result"]["clips"][0]["video_url"].endswith("/status_clip_1.mp4")
# A completed job is not on the queue.
assert body["queue"] is None
async def test_status_unknown_job_is_404(client):
resp = await client.get("/api/status/nobody-home")
assert resp.status_code == 404
assert resp.json()["detail"] == "Job not found"
async def test_source_url_returns_the_plain_path(client):
resp = await client.get("/api/source-url/any-job")
assert resp.status_code == 200
assert resp.json() == {"url": "/api/source/any-job"}
async def test_source_without_a_file_is_404(client):
resp = await client.get("/api/source/nobody-home")
assert resp.status_code == 404
assert resp.json()["detail"] == "Source not found"
async def test_source_streams_an_upload(client, app_state):
job_id = "job-source"
payload = b"pretend this is a video"
(app_state.up / f"{job_id}_source.mp4").write_bytes(payload)
resp = await client.get(f"/api/source/{job_id}")
assert resp.status_code == 200
assert resp.content == payload
assert resp.headers["content-type"] == "video/mp4"

View file

@ -0,0 +1,209 @@
"""L2 API editing E2E: POST /api/subtitle and POST /api/subtitle/remove.
The burn is REAL ffmpeg over a real fixture video (the whole point of this
lane): the endpoint's SRT/ASS generation, the burn filter and the persistence
all run for real. Only the clip itself is supplied by the media factory.
"""
import json
import os
import shutil
import subprocess
import pytest
pytestmark = pytest.mark.e2e
app_module = pytest.importorskip("clipwright.api.app")
TRANSCRIPT = {
"language": "en",
"segments": [{
"start": 0.0, "end": 6.0, "text": "hello world",
"words": [{"word": "hello", "start": 1.0, "end": 1.4},
{"word": "world", "start": 2.0, "end": 2.4}],
}],
}
def _probe(path):
out = subprocess.run(
["ffprobe", "-v", "error", "-show_entries",
"stream=codec_type:format=duration", "-of", "json", str(path)],
capture_output=True, text=True, check=True)
return json.loads(out.stdout)
def _make_job(app_state, media_factory, job_id="job-sub", base="sub",
transcript=TRANSCRIPT):
job_dir = app_state.out / job_id
job_dir.mkdir(parents=True, exist_ok=True)
shutil.copy(media_factory.six, job_dir / f"{base}_clip_1.mp4")
clip = {
"start": 0.0,
"end": 6.0,
"video_title_for_youtube_short": "Sub clip",
"video_url": f"/videos/{job_id}/{base}_clip_1.mp4",
}
meta = {"shorts": [clip], "output_format": "auto", "cost_analysis": {}}
if transcript is not None:
meta["transcript"] = transcript
(job_dir / f"{base}_metadata.json").write_text(json.dumps(meta))
app_module.jobs[job_id] = {
"status": "completed",
"logs": [],
"result": {"clips": [dict(clip)], "cost_analysis": {}},
"user_id": None,
}
return {"job_id": job_id, "base": base, "dir": job_dir,
"meta": job_dir / f"{base}_metadata.json"}
@pytest.fixture
def sub_job(app_state, media_factory):
return _make_job(app_state, media_factory)
def _output_file(job):
matches = list(job["dir"].glob("subtitled_*_sub_clip_1.mp4"))
assert len(matches) == 1, matches
return matches[0]
# --- POST /api/subtitle -----------------------------------------------------
class TestSubtitle:
async def test_preset_unknown_400(self, client, sub_job):
resp = await client.post("/api/subtitle", json={
"job_id": sub_job["job_id"], "clip_index": 0, "preset": "nope"})
assert resp.status_code == 400
assert "preset" in resp.json()["detail"].lower()
async def test_classic_burn_is_playable(self, client, sub_job):
resp = await client.post("/api/subtitle", json={
"job_id": sub_job["job_id"], "clip_index": 0, "style": "classic"})
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["success"] is True
assert data["new_video_url"].startswith(
f"/videos/{sub_job['job_id']}/subtitled_")
assert data["new_video_url"].endswith("_sub_clip_1.mp4")
out = _output_file(sub_job)
assert out.stat().st_size > 0
assert "video" in {s["codec_type"] for s in _probe(out)["streams"]}
# The SRT sidecar was generated too.
assert list(sub_job["dir"].glob("subs_0_*.srt"))
meta = json.loads(sub_job["meta"].read_text())
assert meta["shorts"][0]["video_url"] == data["new_video_url"]
mem = app_module.jobs[sub_job["job_id"]]["result"]["clips"][0]
assert mem["video_url"] == data["new_video_url"]
async def test_karaoke_preset_burns_ass(self, client, sub_job):
resp = await client.post("/api/subtitle", json={
"job_id": sub_job["job_id"], "clip_index": 0, "preset": "default"})
assert resp.status_code == 200, resp.text
assert _output_file(sub_job).is_file()
# Karaoke renders an ASS sidecar (its own per-word styles).
assert list(sub_job["dir"].glob("subs_0_*.ass"))
async def test_words_path_burns_edited_captions(self, client, sub_job):
resp = await client.post("/api/subtitle", json={
"job_id": sub_job["job_id"], "clip_index": 0, "style": "classic",
"words": [
{"text": "edited", "startMs": 500, "endMs": 900},
{"text": "captions", "startMs": 1200, "endMs": 1800},
]})
assert resp.status_code == 200, resp.text
assert _output_file(sub_job).is_file()
srt = list(sub_job["dir"].glob("subs_0_*.srt"))[0]
assert "edited" in srt.read_text(encoding="utf-8-sig").lower()
async def test_too_many_words_400(self, client, sub_job):
words = [{"text": "w", "startMs": i, "endMs": i + 1}
for i in range(2001)]
resp = await client.post("/api/subtitle", json={
"job_id": sub_job["job_id"], "clip_index": 0, "words": words})
assert resp.status_code == 400
assert "Too many" in resp.json()["detail"]
async def test_no_words_in_range_is_wrapped_as_500(self, client, app_state,
media_factory):
# generate_srt() returns False and the route raises its 400 INSIDE the
# try whose catch-all turns it into a 500 (documented deviation from
# the 400 the spec expected).
job = _make_job(app_state, media_factory, job_id="job-sub-nowords",
base="nw", transcript={
"language": "en",
"segments": [{
"start": 100.0, "end": 106.0, "text": "late",
"words": [{"word": "late", "start": 100.0,
"end": 100.4}],
}],
})
resp = await client.post("/api/subtitle", json={
"job_id": job["job_id"], "clip_index": 0, "style": "classic"})
assert resp.status_code == 500
assert "words" in resp.json()["detail"].lower()
async def test_missing_transcript_400(self, client, app_state,
media_factory):
job = _make_job(app_state, media_factory, job_id="job-sub-notx",
base="nt", transcript=None)
resp = await client.post("/api/subtitle", json={
"job_id": job["job_id"], "clip_index": 0})
assert resp.status_code == 400
async def test_404_unknown_job(self, client):
resp = await client.post("/api/subtitle", json={
"job_id": "nope", "clip_index": 0})
assert resp.status_code == 404
async def test_404_missing_metadata(self, client, sub_job):
os.remove(sub_job["meta"])
resp = await client.post("/api/subtitle", json={
"job_id": sub_job["job_id"], "clip_index": 0})
assert resp.status_code == 404
async def test_404_clip_out_of_range(self, client, sub_job):
resp = await client.post("/api/subtitle", json={
"job_id": sub_job["job_id"], "clip_index": 5})
assert resp.status_code == 404
async def test_404_missing_file(self, client, sub_job):
os.remove(sub_job["dir"] / "sub_clip_1.mp4")
resp = await client.post("/api/subtitle", json={
"job_id": sub_job["job_id"], "clip_index": 0})
assert resp.status_code == 404
# --- POST /api/subtitle/remove ----------------------------------------------
class TestRemoveSubtitles:
async def test_points_back_at_clean_file(self, client, sub_job):
burn = await client.post("/api/subtitle", json={
"job_id": sub_job["job_id"], "clip_index": 0, "style": "classic"})
assert burn.status_code == 200
resp = await client.post("/api/subtitle/remove", json={
"job_id": sub_job["job_id"], "clip_index": 0})
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["new_video_url"] == (
f"/videos/{sub_job['job_id']}/sub_clip_1.mp4")
meta = json.loads(sub_job["meta"].read_text())
assert meta["shorts"][0]["video_url"] == data["new_video_url"]
mem = app_module.jobs[sub_job["job_id"]]["result"]["clips"][0]
assert mem["video_url"] == data["new_video_url"]
async def test_404_original_gone(self, client, sub_job):
resp = await client.post("/api/subtitle/remove", json={
"job_id": sub_job["job_id"], "clip_index": 0,
"input_filename": "gone.mp4"})
assert resp.status_code == 404
async def test_404_unknown_job(self, client):
resp = await client.post("/api/subtitle/remove", json={
"job_id": "nope", "clip_index": 0})
assert resp.status_code == 404

View file

@ -0,0 +1,585 @@
"""L3 E2E: the Thumbnail Studio routes.
The Gemini seams (``analyze_video_for_titles`` / ``refine_titles`` /
``generate_thumbnail`` / ``generate_youtube_description`` / ``extract_face_frames``)
and the Postiz client are stubbed; the Whisper background path is kept off the
heavy ``clipwright.pipeline.main`` module by injecting a fake one. The routes
themselves — session bookkeeping, background tasks, path validation — run for
real through the shared ``client`` fixture.
"""
import asyncio
import os
import sys
import types
from types import SimpleNamespace
import pytest
pytestmark = pytest.mark.e2e
POSTIZ_HEADERS = {"X-Postiz-Url": "https://postiz.example", "X-Postiz-Key": "k"}
@pytest.fixture
def fake_pipeline(monkeypatch):
"""Fake ``clipwright.pipeline.main`` + ``transcribe_backends``.
``main`` imports ultralytics/mediapipe at module level, so it must never be
imported in the thin E2E environment. The upload route imports it lazily
inside its background task; this fixture puts a light stand-in in
``sys.modules`` first.
"""
import clipwright.pipeline as pkg
calls = SimpleNamespace(download=[], transcribe=[], release=[])
main = types.ModuleType("clipwright.pipeline.main")
def download_youtube_video(url, out_dir):
calls.download.append((url, out_dir))
path = os.path.join(out_dir, "downloaded.mp4")
with open(path, "wb") as fh:
fh.write(b"\x00" * 32)
return path, {"title": "Downloaded"}
def transcribe_video(path):
calls.transcribe.append(path)
return {"language": "en", "text": "hi there",
"segments": [{"start": 0.0, "end": 2.0, "text": "hi there"}]}
main.download_youtube_video = download_youtube_video
main.transcribe_video = transcribe_video
monkeypatch.setitem(sys.modules, "clipwright.pipeline.main", main)
backends = types.ModuleType("clipwright.pipeline.transcribe_backends")
backends.release_models = lambda: calls.release.append(True)
monkeypatch.setitem(sys.modules, "clipwright.pipeline.transcribe_backends", backends)
monkeypatch.setattr(pkg, "transcribe_backends", backends, raising=False)
return calls
@pytest.fixture
def thumb_stubs(monkeypatch):
"""Stub every thumbnail Gemini seam and record the calls."""
import clipwright.api.app as app
calls = SimpleNamespace(analyze=[], refine=[], generate=[], describe=[], frames=[])
results = SimpleNamespace(
analyze={"titles": ["T1", "T2"], "thumbnail_texts": ["TT1"],
"transcript_summary": "sum", "language": "en",
"segments": [{"start": 0.0, "end": 1.0, "text": "hi"}],
"video_duration": 1.0, "recommended": []},
refine={"titles": ["R1"], "thumbnail_texts": ["RT1"], "language": "es"},
generate=[{"url": "/thumbnails/gen1.jpg"}],
describe={"description": "A description"},
frames=[{"url": "/videos/x/frame1.jpg", "score": 1.0}],
)
errors = SimpleNamespace(analyze=None, refine=None, generate=None,
describe=None, frames=None)
def make(name):
def fn(*args, **kwargs):
getattr(calls, name).append((args, kwargs))
err = getattr(errors, name)
if err:
raise err
return getattr(results, name)
return fn
monkeypatch.setattr(app, "analyze_video_for_titles", make("analyze"))
monkeypatch.setattr(app, "refine_titles", make("refine"))
monkeypatch.setattr(app, "generate_thumbnail", make("generate"))
monkeypatch.setattr(app, "generate_youtube_description", make("describe"))
monkeypatch.setattr(app, "extract_face_frames", make("frames"))
return SimpleNamespace(calls=calls, results=results, errors=errors)
@pytest.fixture
def thumb_postiz(monkeypatch):
"""Minimal Postiz stub for the publish route."""
from clipwright.integrations import postiz as postiz_mod
state = SimpleNamespace(
integrations=[{"id": "yt-1", "name": "Chan", "identifier": "youtube",
"disabled": False}],
upload_result={"id": "m-1", "path": "media/p"},
create_result=[{"id": "post-1"}],
calls=SimpleNamespace(list=[], upload=[], create=[]),
)
def list_integrations(base, key, *a, **k):
state.calls.list.append((base, key))
return state.integrations
def upload_media(base, key, path, *a, **k):
state.calls.upload.append(path)
return state.upload_result
def create_post(base, key, payload, *a, **k):
state.calls.create.append(payload)
return state.create_result
monkeypatch.setattr(postiz_mod, "list_integrations", list_integrations)
monkeypatch.setattr(postiz_mod, "upload_media", upload_media)
monkeypatch.setattr(postiz_mod, "create_post", create_post)
return state
async def _wait_session(app, session_id, timeout=10.0):
"""Await the background Whisper task's completion event (bounded)."""
event = app.thumbnail_sessions[session_id].get("transcript_event")
if event is not None:
await asyncio.wait_for(event.wait(), timeout)
async def _poll_publish(client, publish_id, attempts=50):
for _ in range(attempts):
resp = await client.get(f"/api/thumbnail/publish/status/{publish_id}")
assert resp.status_code == 200
body = resp.json()
if body["status"] != "uploading":
return body
await asyncio.sleep(0)
raise AssertionError("publish background task did not finish")
def _video_file(app_state, name="video.mp4"):
path = app_state.up / name
path.write_bytes(b"fake-video-bytes")
return path
# --------------------------------------------------------------------------- #
# POST /api/thumbnail/upload
# --------------------------------------------------------------------------- #
async def test_upload_file_starts_background_transcription(client, app_state,
fake_pipeline):
resp = await client.post(
"/api/thumbnail/upload",
files={"file": ("clip.mp4", b"video-bytes", "video/mp4")})
assert resp.status_code == 200, resp.text
session_id = resp.json()["session_id"]
session = app_state.app.thumbnail_sessions[session_id]
assert session["video_path"].endswith("clip.mp4")
assert os.path.exists(session["video_path"])
await _wait_session(app_state.app, session_id)
session = app_state.app.thumbnail_sessions[session_id]
assert session["transcript_ready"] is True
assert session["video_duration"] == 2.0
assert session["language"] == "en"
assert fake_pipeline.transcribe == [session["video_path"]]
assert fake_pipeline.release == [True]
async def test_upload_url_defers_download_to_the_background_task(client, app_state,
fake_pipeline):
resp = await client.post("/api/thumbnail/upload",
data={"url": "https://youtu.be/arj7oStGLkU"})
assert resp.status_code == 200, resp.text
session_id = resp.json()["session_id"]
await _wait_session(app_state.app, session_id)
session = app_state.app.thumbnail_sessions[session_id]
assert session["video_path"].endswith("downloaded.mp4")
assert fake_pipeline.download == [
("https://youtu.be/arj7oStGLkU", app_state.app.UPLOAD_DIR)]
assert session["transcript_ready"] is True
async def test_upload_without_input_is_400(client, app_state, fake_pipeline):
resp = await client.post("/api/thumbnail/upload", data={})
assert resp.status_code == 400
assert "URL or File" in resp.json()["detail"]
async def test_upload_oversized_file_is_413(client, app_state, fake_pipeline,
monkeypatch):
monkeypatch.setattr(app_state.app, "MAX_FILE_SIZE_MB", 1)
big = b"x" * (1024 * 1024 + 64)
resp = await client.post(
"/api/thumbnail/upload",
files={"file": ("big.mp4", big, "video/mp4")})
assert resp.status_code == 413
assert "too large" in resp.json()["detail"].lower()
# Nothing was registered: the upload failed before the session existed.
assert app_state.app.thumbnail_sessions == {}
# --------------------------------------------------------------------------- #
# POST /api/thumbnail/analyze
# --------------------------------------------------------------------------- #
async def test_analyze_missing_key_is_400(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
resp = await client.post("/api/thumbnail/analyze",
files={"file": ("v.mp4", b"x", "video/mp4")})
assert resp.status_code == 400
assert "X-Gemini-Key" in resp.json()["detail"]
async def test_analyze_without_input_is_400(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
resp = await client.post("/api/thumbnail/analyze", data={})
assert resp.status_code == 400
assert "URL, File, or session_id" in resp.json()["detail"]
async def test_analyze_file_success_stores_session(client, app_state, thumb_stubs,
monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
resp = await client.post(
"/api/thumbnail/analyze",
files={"file": ("v.mp4", b"video", "video/mp4")})
assert resp.status_code == 200, resp.text
body = resp.json()
assert body["titles"] == ["T1", "T2"]
assert body["thumbnail_texts"] == ["TT1"]
assert body["context"] == "sum"
session = app_state.app.thumbnail_sessions[body["session_id"]]
assert session["titles"] == ["T1", "T2"]
assert session["video_duration"] == 1.0
args = thumb_stubs.calls.analyze[0][0]
assert args[1].endswith("v.mp4")
assert args[2] is None # no pre-transcript on the direct-file path
async def test_analyze_reuses_a_session_transcript(client, app_state, thumb_stubs,
monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
event = asyncio.Event()
event.set()
video = _video_file(app_state, "pre.mp4")
app_state.app.thumbnail_sessions["sess-1"] = {
"video_path": str(video),
"transcript_event": event,
"transcript_ready": True,
"transcript": {"segments": [{"start": 0.0, "end": 1.0, "text": "pre"}]},
"transcript_segments": [{"start": 0.0, "end": 1.0, "text": "pre"}],
}
resp = await client.post("/api/thumbnail/analyze", data={"session_id": "sess-1"})
assert resp.status_code == 200, resp.text
# The pre-existing transcript is handed to the analyzer instead of re-Whispering.
assert thumb_stubs.calls.analyze[0][0][2] == \
{"segments": [{"start": 0.0, "end": 1.0, "text": "pre"}]}
async def test_analyze_session_without_video_is_404(client, app_state, thumb_stubs,
monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
event = asyncio.Event()
event.set()
app_state.app.thumbnail_sessions["sess-novideo"] = {
"video_path": None,
"transcript_event": event,
"transcript_ready": False,
}
resp = await client.post("/api/thumbnail/analyze",
data={"session_id": "sess-novideo"})
assert resp.status_code == 404
assert "Video file not found" in resp.json()["detail"]
async def test_analyze_session_with_transcription_error_is_500(client, app_state,
thumb_stubs, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
event = asyncio.Event()
event.set()
app_state.app.thumbnail_sessions["sess-err"] = {
"video_path": None,
"transcript_event": event,
"transcript_error": "whisper died",
}
resp = await client.post("/api/thumbnail/analyze", data={"session_id": "sess-err"})
assert resp.status_code == 500
assert "Transcription failed" in resp.json()["detail"]
async def test_analyze_backend_error_is_500(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
thumb_stubs.errors.analyze = RuntimeError("gemini down")
resp = await client.post(
"/api/thumbnail/analyze",
files={"file": ("v.mp4", b"video", "video/mp4")})
assert resp.status_code == 500
assert "gemini down" in resp.json()["detail"]
# --------------------------------------------------------------------------- #
# POST /api/thumbnail/titles
# --------------------------------------------------------------------------- #
async def test_titles_manual_title_creates_session(client, app_state, thumb_stubs,
monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
resp = await client.post("/api/thumbnail/titles", json={"title": "Manual Title"})
assert resp.status_code == 200, resp.text
body = resp.json()
assert body["titles"] == ["Manual Title"]
assert app_state.app.thumbnail_sessions[body["session_id"]]["titles"] == \
["Manual Title"]
async def test_titles_missing_key_is_400(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
resp = await client.post("/api/thumbnail/titles", json={"title": "T"})
assert resp.status_code == 400
async def test_titles_unknown_session_is_404(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
resp = await client.post("/api/thumbnail/titles",
json={"session_id": "nope", "message": "shorter"})
assert resp.status_code == 404
assert "Session not found" in resp.json()["detail"]
async def test_titles_without_message_is_400(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
app_state.app.thumbnail_sessions["t1"] = {
"context": "ctx", "titles": ["a"], "language": "en", "conversation": []}
resp = await client.post("/api/thumbnail/titles", json={"session_id": "t1"})
assert resp.status_code == 400
assert "message or title" in resp.json()["detail"]
async def test_titles_refinement_updates_the_session(client, app_state, thumb_stubs,
monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
app_state.app.thumbnail_sessions["t1"] = {
"context": "ctx", "titles": ["a"], "language": "en", "conversation": []}
resp = await client.post("/api/thumbnail/titles",
json={"session_id": "t1", "message": "make it shorter"})
assert resp.status_code == 200, resp.text
assert resp.json()["titles"] == ["R1"]
assert resp.json()["language"] == "es"
session = app_state.app.thumbnail_sessions["t1"]
assert session["titles"] == ["R1"]
assert session["conversation"][-1]["role"] == "assistant"
args = thumb_stubs.calls.refine[0][0]
assert args[1] == "ctx" and args[2] == "make it shorter"
async def test_titles_refinement_error_is_500(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
app_state.app.thumbnail_sessions["t1"] = {
"context": "ctx", "titles": ["a"], "language": "en", "conversation": []}
thumb_stubs.errors.refine = RuntimeError("refine failed")
resp = await client.post("/api/thumbnail/titles",
json={"session_id": "t1", "message": "x"})
assert resp.status_code == 500
assert "refine failed" in resp.json()["detail"]
# --------------------------------------------------------------------------- #
# POST /api/thumbnail/generate
# --------------------------------------------------------------------------- #
async def test_generate_missing_key_is_400(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
resp = await client.post("/api/thumbnail/generate",
data={"session_id": "s", "title": "T"})
assert resp.status_code == 400
async def test_generate_success_clamps_and_passes_session_context(client, app_state,
thumb_stubs, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
app_state.app.thumbnail_sessions["g1"] = {
"context": "ctx", "titles": ["My Title"], "thumbnail_texts": ["HOOK"],
"language": "en", "frames": [{"url": "/videos/x/f.jpg"}]}
resp = await client.post(
"/api/thumbnail/generate",
data={"session_id": "g1", "title": "My Title", "count": "9",
"frame": "/videos/x/f.jpg"})
assert resp.status_code == 200, resp.text
assert resp.json()["thumbnails"] == [{"url": "/thumbnails/gen1.jpg"}]
args, kwargs = thumb_stubs.calls.generate[0]
assert args[1] == "My Title"
assert args[6] == 6 # count is clamped to 6
assert kwargs["thumbnail_text_hint"] == "HOOK"
assert kwargs["frame_reference"] == {"url": "/videos/x/f.jpg"}
assert kwargs["burn_text"] is True
async def test_generate_empty_result_is_500(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
thumb_stubs.results.generate = []
resp = await client.post("/api/thumbnail/generate",
data={"session_id": "g", "title": "T"})
assert resp.status_code == 500
assert "generation failed" in resp.json()["detail"].lower()
# --------------------------------------------------------------------------- #
# GET /api/thumbnail/frames/{session_id}
# --------------------------------------------------------------------------- #
async def test_frames_unknown_session_is_404(client, app_state, thumb_stubs):
resp = await client.get("/api/thumbnail/frames/nope")
assert resp.status_code == 404
assert "Session not found" in resp.json()["detail"]
async def test_frames_are_extracted_once_and_cached(client, app_state, thumb_stubs):
app_state.app.thumbnail_sessions["f1"] = {"video_path": str(_video_file(app_state))}
r1 = await client.get("/api/thumbnail/frames/f1")
assert r1.status_code == 200
assert r1.json()["frames"] == [{"url": "/videos/x/frame1.jpg", "score": 1.0}]
r2 = await client.get("/api/thumbnail/frames/f1")
assert r2.json()["frames"] == r1.json()["frames"]
assert len(thumb_stubs.calls.frames) == 1 # cached on the session
async def test_frames_without_video_are_empty(client, app_state, thumb_stubs):
app_state.app.thumbnail_sessions["f2"] = {"video_path": None}
resp = await client.get("/api/thumbnail/frames/f2")
assert resp.status_code == 200
assert resp.json()["frames"] == []
assert thumb_stubs.calls.frames == []
# --------------------------------------------------------------------------- #
# POST /api/thumbnail/describe
# --------------------------------------------------------------------------- #
async def test_describe_missing_key_is_400(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
resp = await client.post("/api/thumbnail/describe",
json={"session_id": "s", "title": "T"})
assert resp.status_code == 400
async def test_describe_unknown_session_is_404(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
resp = await client.post("/api/thumbnail/describe",
json={"session_id": "nope", "title": "T"})
assert resp.status_code == 404
async def test_describe_without_segments_is_400(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
app_state.app.thumbnail_sessions["d1"] = {"transcript_segments": []}
resp = await client.post("/api/thumbnail/describe",
json={"session_id": "d1", "title": "T"})
assert resp.status_code == 400
assert "transcript segments" in resp.json()["detail"]
async def test_describe_success(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
segments = [{"start": 0.0, "end": 5.0, "text": "hello"}]
app_state.app.thumbnail_sessions["d1"] = {
"transcript_segments": segments, "language": "en", "video_duration": 5.0}
resp = await client.post("/api/thumbnail/describe",
json={"session_id": "d1", "title": "My Title"})
assert resp.status_code == 200
assert resp.json()["description"] == "A description"
args = thumb_stubs.calls.describe[0][0]
assert args[1] == "My Title" and args[2] == segments
# --------------------------------------------------------------------------- #
# POST /api/thumbnail/publish + GET status
# --------------------------------------------------------------------------- #
async def test_publish_unknown_session_is_404(client, app_state, thumb_postiz):
resp = await client.post(
"/api/thumbnail/publish", headers=POSTIZ_HEADERS,
data={"session_id": "nope", "title": "T", "description": "D",
"thumbnail_url": "/thumbnails/t.jpg"})
assert resp.status_code == 404
async def test_publish_missing_video_is_404(client, app_state, thumb_postiz):
app_state.app.thumbnail_sessions["p1"] = {"video_path": None}
resp = await client.post(
"/api/thumbnail/publish", headers=POSTIZ_HEADERS,
data={"session_id": "p1", "title": "T", "description": "D",
"thumbnail_url": "/thumbnails/t.jpg"})
assert resp.status_code == 404
assert "video file" in resp.json()["detail"].lower()
async def test_publish_thumbnail_path_traversal_is_400(client, app_state, thumb_postiz):
_video_file(app_state, "pub.mp4")
app_state.app.thumbnail_sessions["p1"] = {
"video_path": str(app_state.up / "pub.mp4")}
resp = await client.post(
"/api/thumbnail/publish", headers=POSTIZ_HEADERS,
data={"session_id": "p1", "title": "T", "description": "D",
"thumbnail_url": "../../etc/passwd"})
assert resp.status_code == 400
assert "Invalid thumbnail path" in resp.json()["detail"]
assert thumb_postiz.calls.create == []
async def test_publish_missing_thumbnail_file_is_404(client, app_state, thumb_postiz):
_video_file(app_state, "pub.mp4")
app_state.app.thumbnail_sessions["p1"] = {
"video_path": str(app_state.up / "pub.mp4")}
resp = await client.post(
"/api/thumbnail/publish", headers=POSTIZ_HEADERS,
data={"session_id": "p1", "title": "T", "description": "D",
"thumbnail_url": "/thumbnails/missing.jpg"})
assert resp.status_code == 404
assert "Thumbnail file not found" in resp.json()["detail"]
async def test_publish_success_runs_the_background_post(client, app_state, thumb_postiz):
_video_file(app_state, "pub.mp4")
(app_state.out / "thumbnails" / "t.jpg").write_bytes(b"jpeg-bytes")
app_state.app.thumbnail_sessions["p1"] = {
"video_path": str(app_state.up / "pub.mp4")}
resp = await client.post(
"/api/thumbnail/publish", headers=POSTIZ_HEADERS,
data={"session_id": "p1", "title": "My Title", "description": "My description #tag",
"thumbnail_url": "/thumbnails/t.jpg"})
assert resp.status_code == 200, resp.text
publish_id = resp.json()["publish_id"]
status = await _poll_publish(client, publish_id)
assert status["status"] == "done"
assert status["result"] == thumb_postiz.create_result
assert thumb_postiz.calls.upload[0].endswith("pub.mp4")
payload = thumb_postiz.calls.create[0]
assert payload["type"] == "now"
assert payload["posts"][0]["integration"]["id"] == "yt-1"
settings = payload["posts"][0]["settings"]
assert settings["__type"] == "youtube"
assert settings["title"] == "My Title"
assert settings["tags"] == [{"value": "tag", "label": "tag"}]
async def test_publish_failure_marks_the_job_failed(client, app_state, thumb_postiz):
_video_file(app_state, "pub.mp4")
(app_state.out / "thumbnails" / "t.jpg").write_bytes(b"jpeg-bytes")
app_state.app.thumbnail_sessions["p1"] = {
"video_path": str(app_state.up / "pub.mp4")}
thumb_postiz.upload_result = {} # no media id -> PostizError(502)
resp = await client.post(
"/api/thumbnail/publish", headers=POSTIZ_HEADERS,
data={"session_id": "p1", "title": "T", "description": "D",
"thumbnail_url": "/thumbnails/t.jpg"})
assert resp.status_code == 200
publish_id = resp.json()["publish_id"]
status = await _poll_publish(client, publish_id)
assert status["status"] == "failed"
assert "upload failed" in status["error"].lower()
async def test_publish_status_unknown_is_404(client, app_state):
resp = await client.get("/api/thumbnail/publish/status/nope")
assert resp.status_code == 404
assert "Publish job not found" in resp.json()["detail"]

View file

@ -0,0 +1,242 @@
"""L3 E2E: the anonymous free tools (``clipwright.api.free_tools``).
The network seams are stubbed (``_fetch_with_slot`` for the transcript, the
``_generate`` Gemini call for metadata), so the real route logic runs: URL
validation, caption/error mapping, the 24 h cache, the in-process rate limiter
and the metadata mode/shape handling.
"""
import asyncio
from collections import OrderedDict
from types import SimpleNamespace
import pytest
pytestmark = pytest.mark.e2e
VIDEO_A = "arj7oStGLkU"
VIDEO_B = "dQw4w9WgXcQ"
@pytest.fixture
def ft(monkeypatch):
"""A clean free_tools module: fresh cache and a fresh limiter per test."""
from clipwright.api import free_tools
monkeypatch.setattr(free_tools, "_TRANSCRIPT_CACHE", OrderedDict())
monkeypatch.setattr(free_tools, "_limiter", free_tools.RateLimiter(free_tools.LIMITS))
return free_tools
@pytest.fixture
def transcript_stub(monkeypatch, ft):
"""Stub ``_fetch_with_slot`` (what the route hands to ``to_thread``)."""
state = SimpleNamespace(
calls=[],
error=None,
result={"video_id": "x", "title": "A video", "channel": "Chan",
"duration": 12, "languages": [], "language": "en", "kind": "manual",
"segments": [{"start": 0.0, "dur": 1.0, "text": "hello"}]},
)
def fake(video_id, lang):
state.calls.append((video_id, lang))
if state.error:
raise state.error
return state.result
monkeypatch.setattr(ft, "_fetch_with_slot", fake)
return state
@pytest.fixture
def generate_stub(monkeypatch, ft):
"""Stub the Gemini ``_generate`` seam used by the metadata route."""
state = SimpleNamespace(calls=[], result={"titles": [{"title": "A", "angle": "x"}]},
error=None)
def fake(prompt):
state.calls.append(prompt)
if state.error:
raise state.error
return state.result
monkeypatch.setattr(ft, "_generate", fake)
return state
# --------------------------------------------------------------------------- #
# GET /api/tools/youtube-transcript
# --------------------------------------------------------------------------- #
async def test_transcript_success_then_served_from_cache(client, ft, transcript_stub):
r1 = await client.get("/api/tools/youtube-transcript",
params={"url": f"https://youtu.be/{VIDEO_A}"})
assert r1.status_code == 200, r1.text
assert r1.json()["cached"] is False
assert r1.json()["segments"] == [{"start": 0.0, "dur": 1.0, "text": "hello"}]
# A bare id resolves to the same video id -> cache hit, no second fetch.
r2 = await client.get("/api/tools/youtube-transcript", params={"url": VIDEO_A})
assert r2.status_code == 200
assert r2.json()["cached"] is True
assert len(transcript_stub.calls) == 1
assert transcript_stub.calls[0][0] == VIDEO_A
async def test_transcript_bad_url_is_400_without_work(client, ft, transcript_stub):
r = await client.get("/api/tools/youtube-transcript",
params={"url": "https://youtube.com/@ted"})
assert r.status_code == 400
assert r.json()["detail"]["code"] == "bad_url"
assert transcript_stub.calls == []
async def test_transcript_no_captions_is_404_and_cached(client, ft, transcript_stub):
transcript_stub.error = ft.TranscriptError("no_captions", "none", 404)
r1 = await client.get("/api/tools/youtube-transcript", params={"url": VIDEO_A})
assert r1.status_code == 404
assert r1.json()["detail"]["code"] == "no_captions"
# The verdict about the video is cached: no second fetch, same 404.
r2 = await client.get("/api/tools/youtube-transcript", params={"url": VIDEO_A})
assert r2.status_code == 404
assert r2.json()["detail"]["code"] == "no_captions"
assert len(transcript_stub.calls) == 1
async def test_transcript_unavailable_is_422(client, ft, transcript_stub):
transcript_stub.error = ft.TranscriptError("unavailable", "private", 422)
r = await client.get("/api/tools/youtube-transcript", params={"url": VIDEO_A})
assert r.status_code == 422
assert r.json()["detail"]["code"] == "unavailable"
async def test_transcript_blocked_is_503(client, ft, transcript_stub):
transcript_stub.error = ft.TranscriptError("youtube_blocked", "blocked", 503)
r = await client.get("/api/tools/youtube-transcript", params={"url": VIDEO_A})
assert r.status_code == 503
assert r.json()["detail"]["code"] == "youtube_blocked"
async def test_transcript_busy_is_503(client, ft, transcript_stub):
transcript_stub.error = ft.TranscriptError("busy", "busy", 503)
r = await client.get("/api/tools/youtube-transcript", params={"url": VIDEO_A})
assert r.status_code == 503
assert r.json()["detail"]["code"] == "busy"
async def test_transcript_timeout_is_504(client, ft, transcript_stub):
transcript_stub.error = asyncio.TimeoutError()
r = await client.get("/api/tools/youtube-transcript", params={"url": VIDEO_A})
assert r.status_code == 504
assert r.json()["detail"]["code"] == "timeout"
async def test_transcript_per_ip_rate_limit_is_429(client, ft, transcript_stub, monkeypatch):
monkeypatch.setattr(
ft, "_limiter",
ft.RateLimiter({"transcript": {"per_ip": [(600, 1)], "global_day": 1000}}))
r1 = await client.get("/api/tools/youtube-transcript", params={"url": VIDEO_A})
assert r1.status_code == 200
r2 = await client.get("/api/tools/youtube-transcript", params={"url": VIDEO_B})
assert r2.status_code == 429
assert r2.json()["detail"]["code"] == "rate_limited"
async def test_transcript_global_rate_limit_is_429_busy(client, ft, transcript_stub,
monkeypatch):
monkeypatch.setattr(
ft, "_limiter",
ft.RateLimiter({"transcript": {"per_ip": [(600, 100)], "global_day": 1}}))
r1 = await client.get("/api/tools/youtube-transcript", params={"url": VIDEO_A})
assert r1.status_code == 200
r2 = await client.get("/api/tools/youtube-transcript", params={"url": VIDEO_B})
assert r2.status_code == 429
assert r2.json()["detail"]["code"] == "busy"
# --------------------------------------------------------------------------- #
# POST /api/tools/youtube-metadata
# --------------------------------------------------------------------------- #
async def test_metadata_bad_mode_is_400(client, ft, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
r = await client.post("/api/tools/youtube-metadata",
json={"mode": "bogus", "topic": "a" * 40})
assert r.status_code == 400
assert r.json()["detail"]["code"] == "bad_mode"
async def test_metadata_too_short_topic_is_400(client, ft, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
r = await client.post("/api/tools/youtube-metadata",
json={"mode": "titles", "topic": "short"})
assert r.status_code == 400
assert r.json()["detail"]["code"] == "too_short"
async def test_metadata_not_configured_is_503(client, ft, monkeypatch):
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
r = await client.post("/api/tools/youtube-metadata",
json={"mode": "titles", "topic": "A video about sourdough bread"})
assert r.status_code == 503
assert r.json()["detail"]["code"] == "not_configured"
async def test_metadata_titles_mode(client, ft, generate_stub, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
generate_stub.result = {"titles": [{"title": "How to bake", "angle": "how-to"}]}
r = await client.post("/api/tools/youtube-metadata",
json={"mode": "titles", "topic": "A video about sourdough bread",
"keyword": "sourdough"})
assert r.status_code == 200, r.text
assert r.json()["mode"] == "titles"
assert r.json()["titles"] == [{"title": "How to bake", "angle": "how-to"}]
# The keyword rides into the prompt.
assert "sourdough" in generate_stub.calls[0]
async def test_metadata_description_mode(client, ft, generate_stub, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
generate_stub.result = {"description": "A long enough description."}
r = await client.post("/api/tools/youtube-metadata",
json={"mode": "description",
"topic": "A video about sourdough bread"})
assert r.status_code == 200
assert r.json()["description"] == "A long enough description."
async def test_metadata_tags_mode(client, ft, generate_stub, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
generate_stub.result = {"tags": ["sourdough", "baking"]}
r = await client.post("/api/tools/youtube-metadata",
json={"mode": "tags", "topic": "A video about sourdough bread"})
assert r.status_code == 200
assert r.json()["tags"] == ["sourdough", "baking"]
assert r.json()["characters"] == len("sourdough,baking")
async def test_metadata_generation_failure_is_502_after_retry(client, ft, generate_stub,
monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
generate_stub.error = RuntimeError("model exploded")
r = await client.post("/api/tools/youtube-metadata",
json={"mode": "titles", "topic": "A video about sourdough bread"})
assert r.status_code == 502
assert r.json()["detail"]["code"] == "generation_failed"
assert len(generate_stub.calls) == 2 # one retry
async def test_metadata_rate_limit_is_429(client, ft, generate_stub, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
monkeypatch.setattr(
ft, "_limiter",
ft.RateLimiter({"metadata": {"per_ip": [(600, 1)], "global_day": 1000}}))
generate_stub.result = {"titles": [{"title": "A", "angle": "x"}]}
body = {"mode": "titles", "topic": "A video about sourdough bread"}
r1 = await client.post("/api/tools/youtube-metadata", json=body)
assert r1.status_code == 200
r2 = await client.post("/api/tools/youtube-metadata", json=body)
assert r2.status_code == 429
assert r2.json()["detail"]["code"] == "rate_limited"

View file

@ -0,0 +1,288 @@
"""L2 API editing E2E: transcript, EDL and the clip-editor re-render.
The render work is stubbed at the ``recut.perform_recut`` seam (the endpoint's
own contract is what these tests own): request validation, the fast/source path
choice, the 409 on a gone source, and the recipe persisted to metadata.json and
the in-memory job. The source is a real ffmpeg video so duration probing is
genuine.
"""
import json
import os
import shutil
import pytest
pytestmark = pytest.mark.e2e
app_module = pytest.importorskip("clipwright.api.app")
from clipwright.media import recut # noqa: E402
TRANSCRIPT = {
"language": "en",
"segments": [
{
"start": 0.0, "end": 60.0, "text": "hello world again tail",
"words": [
{"word": "hello", "start": 1.0, "end": 1.4},
{"word": "world", "start": 2.0, "end": 2.4},
{"word": "again", "start": 4.0, "end": 4.4},
{"word": "tail", "start": 5.2, "end": 5.6},
],
},
],
}
def _make_job(app_state, media_factory, job_id="job-edl", base="edl"):
job_dir = app_state.out / job_id
job_dir.mkdir(parents=True, exist_ok=True)
shutil.copy(media_factory.six, job_dir / f"{base}_clip_1.mp4") # canonical
shutil.copy(media_factory.six, job_dir / "src.mp4") # source
clip = {
"start": 1.0,
"end": 5.0,
"video_title_for_youtube_short": "EDL clip",
"video_url": f"/videos/{job_id}/{base}_clip_1.mp4",
}
(job_dir / f"{base}_metadata.json").write_text(json.dumps({
"shorts": [clip],
"transcript": TRANSCRIPT,
"source_video": "src.mp4",
"output_format": "auto",
"cost_analysis": {},
}))
app_module.jobs[job_id] = {
"status": "completed",
"logs": [],
"result": {"clips": [dict(clip)], "cost_analysis": {}},
"user_id": None,
}
return {"job_id": job_id, "base": base, "dir": job_dir,
"meta": job_dir / f"{base}_metadata.json"}
@pytest.fixture
def edl_job(app_state, media_factory):
return _make_job(app_state, media_factory)
@pytest.fixture
def fake_recut(monkeypatch):
calls = []
def fake(**kwargs):
calls.append(kwargs)
name = f"recut_1_{kwargs['clean_name']}"
with open(os.path.join(kwargs["output_dir"], name), "wb") as fh:
fh.write(b"recut")
return name, name
monkeypatch.setattr(recut, "perform_recut", fake)
return calls
# --- GET /api/clip/{job}/{clip}/transcript ----------------------------------
class TestTranscript:
async def test_returns_words_in_clip_range(self, client, edl_job):
resp = await client.get(
f"/api/clip/{edl_job['job_id']}/0/transcript")
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["durationSec"] == 4.0
assert data["language"] == "en"
by_text = {c["text"]: c for c in data["captions"]}
# Clip starts at source 1.0s -> "hello" is 0ms into the clip.
assert by_text["hello"]["startMs"] == 0
assert by_text["world"]["startMs"] == 1000
assert by_text["again"]["startMs"] == 3000
# "tail" (5.2s) is past the clip end.
assert "tail" not in by_text
async def test_404_unknown_job(self, client, edl_job):
resp = await client.get("/api/clip/nope/0/transcript")
assert resp.status_code == 404
async def test_404_missing_metadata(self, client, edl_job):
os.remove(edl_job["meta"])
resp = await client.get(f"/api/clip/{edl_job['job_id']}/0/transcript")
assert resp.status_code == 404
async def test_400_missing_transcript(self, client, edl_job):
meta = json.loads(edl_job["meta"].read_text())
meta.pop("transcript")
edl_job["meta"].write_text(json.dumps(meta))
resp = await client.get(f"/api/clip/{edl_job['job_id']}/0/transcript")
assert resp.status_code == 400
async def test_404_clip_index_out_of_range(self, client, edl_job):
resp = await client.get(f"/api/clip/{edl_job['job_id']}/5/transcript")
assert resp.status_code == 404
# --- GET /api/clip/{job}/{clip}/edl -----------------------------------------
class TestEdl:
async def test_source_present(self, client, edl_job):
resp = await client.get(f"/api/clip/{edl_job['job_id']}/0/edl")
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["segments"] == [{"start": 1.0, "end": 5.0}]
assert data["canonical_range"] == {"start": 1.0, "end": 5.0}
assert data["duration"] == 4.0
assert data["current_file"] == "edl_clip_1.mp4"
assert data["source"]["available"] is True
assert data["source"]["url"] == f"/api/source/{edl_job['job_id']}"
assert data["source"]["duration_estimated"] is False
assert data["source"]["duration"] == pytest.approx(6.0, abs=0.5)
assert [w["w"] for w in data["words"]] == [
"hello", "world", "again", "tail"]
assert data["limits"]["max_segments"] == recut.MAX_SEGMENTS
async def test_deleted_source_is_estimated(self, client, edl_job):
os.remove(edl_job["dir"] / "src.mp4")
data = (await client.get(
f"/api/clip/{edl_job['job_id']}/0/edl")).json()
assert data["source"]["available"] is False
assert data["source"]["url"] is None
assert data["source"]["duration_estimated"] is True
# Best remaining scale: the last word or the recipe end.
assert data["source"]["duration"] == pytest.approx(5.6, abs=0.01)
async def test_404_unknown_job(self, client, edl_job):
assert (await client.get("/api/clip/nope/0/edl")).status_code == 404
async def test_404_missing_metadata(self, client, edl_job):
os.remove(edl_job["meta"])
assert (await client.get(
f"/api/clip/{edl_job['job_id']}/0/edl")).status_code == 404
async def test_404_clip_index_out_of_range(self, client, edl_job):
assert (await client.get(
f"/api/clip/{edl_job['job_id']}/9/edl")).status_code == 404
# --- POST /api/clip/rerender ------------------------------------------------
class TestRerenderValidation:
async def test_404_unknown_job(self, client, fake_recut):
resp = await client.post("/api/clip/rerender", json={
"job_id": "nope", "clip_index": 0,
"segments": [{"start": 1, "end": 3}]})
assert resp.status_code == 404
async def test_404_clip_out_of_range(self, client, edl_job, fake_recut):
resp = await client.post("/api/clip/rerender", json={
"job_id": edl_job["job_id"], "clip_index": 5,
"segments": [{"start": 1, "end": 3}]})
assert resp.status_code == 404
async def test_400_bad_segments(self, client, edl_job, fake_recut):
for segments in ([], [{"start": 2, "end": 2.1}]):
resp = await client.post("/api/clip/rerender", json={
"job_id": edl_job["job_id"], "clip_index": 0,
"segments": segments})
assert resp.status_code == 400, segments
assert fake_recut == []
async def test_400_bad_framing(self, client, edl_job, fake_recut):
resp = await client.post("/api/clip/rerender", json={
"job_id": edl_job["job_id"], "clip_index": 0,
"framing": "cinematic",
"segments": [{"start": 1, "end": 3}]})
assert resp.status_code == 400
assert fake_recut == []
async def test_409_source_gone_outside_segment(self, client, edl_job,
fake_recut):
os.remove(edl_job["dir"] / "src.mp4")
resp = await client.post("/api/clip/rerender", json={
"job_id": edl_job["job_id"], "clip_index": 0,
"segments": [{"start": 5, "end": 6}]})
assert resp.status_code == 409
assert fake_recut == []
async def test_409_framing_without_source(self, client, edl_job,
fake_recut):
os.remove(edl_job["dir"] / "src.mp4")
resp = await client.post("/api/clip/rerender", json={
"job_id": edl_job["job_id"], "clip_index": 0,
"framing": "full",
"segments": [{"start": 1, "end": 3}]})
assert resp.status_code == 409
assert "framing" in resp.json()["detail"]
assert fake_recut == []
class TestRerenderPaths:
async def test_fast_path_cuts_from_canonical(self, client, edl_job,
fake_recut):
resp = await client.post("/api/clip/rerender", json={
"job_id": edl_job["job_id"], "clip_index": 0,
"segments": [{"start": 1, "end": 3}, {"start": 3, "end": 5}]})
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["render_path"] == "fast"
assert data["duration"] == 4.0
call = fake_recut[0]
assert call["input_path"].endswith("edl_clip_1.mp4")
assert call["reframe"] is False
# Rebated onto the canonical file (t=0 == source 1.0s).
assert call["segments"] == [{"start": 0.0, "end": 2.0},
{"start": 2.0, "end": 4.0}]
assert call["captions_transcript"]["segments"][0]["words"]
async def test_source_path_reframes(self, client, edl_job, fake_recut):
resp = await client.post("/api/clip/rerender", json={
"job_id": edl_job["job_id"], "clip_index": 0,
"segments": [{"start": 5, "end": 6}]})
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["render_path"] == "source"
call = fake_recut[0]
assert call["input_path"].endswith("src.mp4")
assert call["reframe"] is True
assert call["segments"] == [{"start": 5.0, "end": 6.0}]
async def test_reapply_captions_false(self, client, edl_job, fake_recut):
resp = await client.post("/api/clip/rerender", json={
"job_id": edl_job["job_id"], "clip_index": 0,
"reapply_captions": False,
"segments": [{"start": 1, "end": 3}]})
assert resp.status_code == 200
assert fake_recut[0]["captions_transcript"] is None
async def test_framing_forces_source_and_persists(self, client, edl_job,
fake_recut):
resp = await client.post("/api/clip/rerender", json={
"job_id": edl_job["job_id"], "clip_index": 0, "framing": "full",
"segments": [{"start": 1, "end": 3}]})
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["render_path"] == "source"
assert data["framing"] == "full"
assert data["recipe"]["framing"] == "full"
assert fake_recut[0]["force_strategy"] == "WIDE"
class TestRerenderPersistence:
async def test_recipe_lands_in_metadata_and_memory(self, client, edl_job,
fake_recut):
resp = await client.post("/api/clip/rerender", json={
"job_id": edl_job["job_id"], "clip_index": 0,
"segments": [{"start": 1, "end": 3}, {"start": 4.5, "end": 6}]})
assert resp.status_code == 200, resp.text
data = resp.json()
expected = [{"start": 1.0, "end": 3.0}, {"start": 4.5, "end": 6.0}]
assert data["recipe"]["segments"] == expected
assert data["recipe"]["canonical_range"] == {"start": 1.0, "end": 5.0}
assert (data["start"], data["end"]) == (1.0, 6.0)
meta = json.loads(edl_job["meta"].read_text())
stored = meta["shorts"][0]
assert stored["recipe"]["segments"] == expected
assert stored["video_url"] == data["new_video_url"]
mem = app_module.jobs[edl_job["job_id"]]["result"]["clips"][0]
assert mem["recipe"]["segments"] == expected
assert mem["video_url"] == data["new_video_url"]

View file

@ -0,0 +1,130 @@
"""L1 API core: the two-step agent upload path (POST reserve, PUT bytes,
DELETE drop).
The PUT is capped at ``MAX_FILE_SIZE_MB`` (0 = unlimited) and probes the body
with ffprobe, so a non-video is refused with 400 rather than queued.
"""
import os
import pytest
pytestmark = pytest.mark.e2e
async def _reserve(client, filename=None):
body = {} if filename is None else {"filename": filename}
resp = await client.post("/api/uploads", json=body)
assert resp.status_code == 200, resp.text
return resp.json()
async def test_reserve_returns_slot_shape_and_sanitises_basename(client, app_state):
data = await _reserve(client, "../../etc/evil.mp4")
uid = data["upload_id"]
slot = app_state.app.pending_uploads[uid]
# basename() strips every path component the client tried to smuggle in.
assert slot["filename"] == "evil.mp4"
assert os.path.basename(slot["path"]).startswith(f"pending_{uid}_")
assert os.path.basename(slot["path"]).endswith("evil.mp4")
assert slot["complete"] is False and slot["bytes"] == 0
assert data["upload_url"].endswith(f"/api/uploads/{uid}")
assert data["method"] == "PUT"
assert data["max_mb"] == app_state.app.MAX_FILE_SIZE_MB
assert data["expires_in"] == app_state.app.UPLOAD_TTL_SECONDS
assert "PUT the raw video bytes" in data["hint"]
async def test_reserve_defaults_filename_when_body_absent(client, app_state):
resp = await client.post("/api/uploads")
assert resp.status_code == 200
uid = resp.json()["upload_id"]
assert app_state.app.pending_uploads[uid]["filename"] == "video.mp4"
async def test_put_unknown_id_is_404(client, app_state):
resp = await client.put("/api/uploads/does-not-exist", content=b"x")
assert resp.status_code == 404
assert "Unknown or expired" in resp.json()["detail"]
async def test_put_expired_slot_is_404_and_dropped(client, app_state):
uid = (await _reserve(client))["upload_id"]
slot = app_state.app.pending_uploads[uid]
slot["created"] -= app_state.app.UPLOAD_TTL_SECONDS + 10
resp = await client.put(f"/api/uploads/{uid}", content=b"anything")
assert resp.status_code == 404
assert uid not in app_state.app.pending_uploads
async def test_put_empty_body_is_400_and_removes_file(client, app_state):
uid = (await _reserve(client))["upload_id"]
path = app_state.app.pending_uploads[uid]["path"]
resp = await client.put(f"/api/uploads/{uid}", content=b"")
assert resp.status_code == 400
assert resp.json()["detail"] == "Empty body"
assert not os.path.exists(path)
assert app_state.app.pending_uploads[uid]["complete"] is False
async def test_put_unreadable_body_is_400_and_removes_file(client, app_state):
uid = (await _reserve(client))["upload_id"]
path = app_state.app.pending_uploads[uid]["path"]
resp = await client.put(f"/api/uploads/{uid}", content=b"this is not a video")
assert resp.status_code == 400
assert "not a readable video file" in resp.json()["detail"]
assert not os.path.exists(path)
assert app_state.app.pending_uploads[uid]["complete"] is False
async def test_put_oversized_body_is_413_and_removes_file(client, app_state, monkeypatch):
monkeypatch.setattr(app_state.app, "MAX_FILE_SIZE_MB", 1)
uid = (await _reserve(client))["upload_id"]
path = app_state.app.pending_uploads[uid]["path"]
oversized = b"x" * (1024 * 1024 + 1)
resp = await client.put(f"/api/uploads/{uid}", content=oversized)
assert resp.status_code == 413
assert "File too large" in resp.json()["detail"]
assert not os.path.exists(path)
async def test_second_put_replaces_the_first(client, app_state, media_factory):
uid = (await _reserve(client))["upload_id"]
path = app_state.app.pending_uploads[uid]["path"]
first = media_factory.six.read_bytes()
resp = await client.put(f"/api/uploads/{uid}", content=first)
assert resp.status_code == 200
assert resp.json()["bytes"] == len(first)
assert resp.json()["duration_seconds"] == pytest.approx(6.0, abs=1.0)
second = media_factory.silent.read_bytes()
resp = await client.put(f"/api/uploads/{uid}", content=second)
assert resp.status_code == 200
assert resp.json()["bytes"] == len(second)
# The slot now points at the replacement, not the first body.
assert open(path, "rb").read() == second
async def test_delete_removes_slot_and_file(client, app_state, media_factory):
uid = (await _reserve(client))["upload_id"]
path = app_state.app.pending_uploads[uid]["path"]
assert (await client.put(f"/api/uploads/{uid}",
content=media_factory.six.read_bytes())).status_code == 200
resp = await client.delete(f"/api/uploads/{uid}")
assert resp.status_code == 200
assert resp.json() == {"deleted": uid}
assert uid not in app_state.app.pending_uploads
assert not os.path.exists(path)
async def test_delete_unknown_id_is_404(client, app_state):
resp = await client.delete("/api/uploads/nope")
assert resp.status_code == 404

199
tests/e2e/conftest.py Normal file
View file

@ -0,0 +1,199 @@
"""Shared E2E fixtures: state isolation, a no-network guard, ffmpeg media, and
disk-seeded jobs.
Design notes
------------
* ``no_network`` (autouse) makes any unmocked DNS lookup fail loudly. The API
tests drive the app through ``httpx.ASGITransport``, which never touches a
socket; the pipeline tests run the real CLI with the stub_env fakes.
* ``app_state`` rebinds the module globals in ``clipwright.api.app`` per test so
two tests never share a ``jobs`` dict, a queue, or a semaphore. All names were
verified against ``clipwright/api/app.py`` (see the note in the report).
* ``media_factory`` is session-scoped and generates the fixture videos with
ffmpeg ``lavfi`` sources, so no binaries live in git. Tests assert on
globs/ffprobe values, never on exact ``<timestamp>`` filenames.
"""
import asyncio
import json
import socket
import subprocess
from types import SimpleNamespace
import pytest
@pytest.fixture(autouse=True)
def no_network(monkeypatch):
"""Fail on any unmocked outbound DNS lookup.
Loopback is allowed so local servers (an OpenAI-compatible LLM, a test
Postiz) can be reached; everything else must be mocked explicitly.
"""
real = socket.getaddrinfo
def guard(host, *args, **kwargs):
if host in ("127.0.0.1", "localhost", "::1", None, "", b"127.0.0.1"):
return real(host, *args, **kwargs)
raise AssertionError(f"unmocked network access to {host!r}")
monkeypatch.setattr(socket, "getaddrinfo", guard)
@pytest.fixture
def app_state(tmp_path, monkeypatch):
"""Point ``clipwright.api.app`` at a per-test output/upload tree.
Rebind the module globals the routes read at call time. ``job_queue`` and
``concurrency_semaphore`` are recreated because asyncio primitives latch
onto the first event loop they touch, and each test gets a fresh loop.
"""
import clipwright.api.app as app
out = tmp_path / "output"
up = tmp_path / "uploads"
out.mkdir()
up.mkdir()
(out / "thumbnails").mkdir()
monkeypatch.setattr(app, "OUTPUT_DIR", str(out))
monkeypatch.setattr(app, "UPLOAD_DIR", str(up))
monkeypatch.setattr(app, "THUMBNAILS_DIR", str(out / "thumbnails"))
# The /videos and /thumbnails mounts captured their directory at import
# time (`app.mount(..., directory=OUTPUT_DIR)`), so rebinding the module
# globals is not enough: repoint the mounted StaticFiles instances too or
# route tests would read the real `output/` tree. Both `.directory` (used
# for the directory-redirect check) and `.all_directories` (used by
# lookup_path) must move together.
def _repoint(name, directory):
for route in getattr(app.app, "routes", []):
if getattr(route, "name", None) == name:
sub = getattr(route, "app", None)
if sub is not None and hasattr(sub, "all_directories"):
sub.directory = str(directory)
sub.all_directories = [str(directory)]
_repoint("videos", out)
_repoint("thumbnails", out / "thumbnails")
for name, empty in (
("jobs", {}),
("thumbnail_sessions", {}),
("publish_jobs", {}),
("pending_uploads", {}),
("_rerender_locks", {}),
("_scenes_locks", {}),
("_recent_job_seconds", []),
("_admitting", set()),
("_running_jobs", set()),
):
monkeypatch.setattr(app, name, empty)
# Rebind loop-bound primitives (see docstring).
monkeypatch.setattr(app, "job_queue", asyncio.PriorityQueue())
monkeypatch.setattr(app, "concurrency_semaphore", asyncio.Semaphore(5))
monkeypatch.setattr(app, "_draining", False)
monkeypatch.setattr(app, "_stopping", False)
# Hermetic defaults: never gate on source height/length/size in tests.
monkeypatch.setattr(app, "QUALITY_GATE_MIN_HEIGHT", 0)
monkeypatch.setattr(app, "MIN_SOURCE_SECONDS", 0)
monkeypatch.setattr(app, "MAX_FILE_SIZE_MB", 0)
return SimpleNamespace(out=out, up=up, app=app)
@pytest.fixture(scope="session")
def media_factory(tmp_path_factory):
"""Generate the shared E2E fixture videos once per session.
Returns a ``SimpleNamespace`` whose attributes are ``pathlib.Path``s:
* ``sixty`` — 160x90, 60 s, with audio (uploads / process)
* ``six`` — 320x180, 6 s, with audio (fast stage tests)
* ``cuts`` — 320x180, 4 hard-colour segments (scene detection)
* ``silent`` — 320x180, 6 s, no audio (vision / no-audio paths)
"""
root = tmp_path_factory.mktemp("media")
def _run(args):
subprocess.run(
["ffmpeg", "-y", "-hide_banner", "-loglevel", "error", *args],
check=True,
)
sixty = root / "sixty.mp4"
six = root / "six.mp4"
cuts = root / "cuts.mp4"
silent = root / "silent.mp4"
if not sixty.exists():
_run([
"-f", "lavfi", "-i", "testsrc=size=160x90:rate=10:duration=60",
"-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100:duration=60",
"-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p",
"-c:a", "aac", "-shortest", str(sixty),
])
if not six.exists():
_run([
"-f", "lavfi", "-i", "testsrc=size=320x180:rate=10:duration=6",
"-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100:duration=6",
"-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p",
"-c:a", "aac", "-shortest", str(six),
])
if not cuts.exists():
_run([
"-f", "lavfi", "-i", "color=c=red:s=320x180:d=1.5",
"-f", "lavfi", "-i", "color=c=green:s=320x180:d=1.5",
"-f", "lavfi", "-i", "color=c=blue:s=320x180:d=1.5",
"-f", "lavfi", "-i", "color=c=yellow:s=320x180:d=1.5",
"-filter_complex", "[0:v][1:v][2:v][3:v]concat=n=4:v=1:a=0[v]",
"-map", "[v]", "-c:v", "libx264", "-preset", "ultrafast",
"-pix_fmt", "yuv420p", str(cuts),
])
if not silent.exists():
_run([
"-f", "lavfi", "-i", "testsrc=size=320x180:rate=10:duration=6",
"-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p",
str(silent),
])
return SimpleNamespace(sixty=sixty, six=six, cuts=cuts, silent=silent)
@pytest.fixture
def seeded_job(app_state):
"""Factory: write a completed job to disk and recover it into ``jobs``.
Mirrors the restart path: ``output/<job_id>/<base>_metadata.json`` plus a
non-empty ``<base>_clip_<n>.mp4`` per clip, then
``app._recover_jobs_from_disk()``. Returns the ``job_id`` (the recovered
record is available as ``app_state.app.jobs[job_id]``).
"""
def _seed(job_id="job-seeded", base="clipwright", clips=1):
import clipwright.api.app as app
job_dir = app_state.out / job_id
job_dir.mkdir(parents=True, exist_ok=True)
shorts = []
for i in range(clips):
shorts.append({
"start": float(i * 10),
"end": float(i * 10 + 8),
"predicted_score": 80 - i,
"video_title_for_youtube_short": f"Seeded clip {i + 1}",
"viral_hook_text": f"Hook {i + 1}",
"video_description_for_tiktok": "Seeded #test",
"video_description_for_instagram": "Seeded #test",
})
(job_dir / f"{base}_clip_{i + 1}.mp4").write_bytes(b"\x00" * 2048)
(job_dir / f"{base}_metadata.json").write_text(json.dumps({
"shorts": shorts,
"cost_analysis": {"total_cost": 0.0, "model": "seeded"},
}))
app._recover_jobs_from_disk()
return job_id
return _seed

View file

@ -0,0 +1 @@
"""Pipeline-stage end-to-end tests (real CLI, real ffmpeg, stubbed ML/LLM)."""

View file

@ -0,0 +1,69 @@
"""Pipeline E2E fixtures.
The tests here run the REAL CLI (``python -m clipwright.pipeline.main``) with
real ffmpeg, but the child interpreter is started with ``stub_env`` on
``PYTHONPATH``. ``stub_env/sitecustomize.py`` swaps the ML and network edges
(ultralytics/mediapipe, ASR, Gemini) for deterministic fakes, so no model is
downloaded and no request leaves the process. Mark ML-backed variants with
``pytest.mark.ml``; those need the heavy ML stack from ``requirements.txt``.
"""
import os
import subprocess
import sys
from pathlib import Path
import pytest
pytestmark = pytest.mark.pipeline
REPO_ROOT = Path(__file__).resolve().parents[3]
STUB_ENV = Path(__file__).resolve().parent / "stub_env"
@pytest.fixture(scope="session")
def stub_env_dir():
"""Directory holding ``sitecustomize.py`` for the pipeline child."""
assert (STUB_ENV / "sitecustomize.py").is_file()
return STUB_ENV
@pytest.fixture
def pipeline_env(stub_env_dir, tmp_path):
"""Environment for a pipeline subprocess: stub env on PYTHONPATH, no LLM."""
env = dict(os.environ)
env.pop("LLM_BASE_URL", None)
env.pop("LLM_MODEL", None)
env["GEMINI_API_KEY"] = "stub-gemini-key"
env["PYTHONPATH"] = os.pathsep.join(
[str(stub_env_dir), str(REPO_ROOT), env.get("PYTHONPATH", "")]
).strip(os.pathsep)
env["PYTHONHASHSEED"] = "0"
env["TZ"] = "UTC"
# Keep output inside the test's tmp tree unless the caller overrides it.
env.setdefault("TRANSCRIBE_BACKEND", "whisper")
return env
@pytest.fixture
def run_pipeline(pipeline_env):
"""Run the real CLI; returns the CompletedProcess.
Usage: ``run_pipeline(media.six, "-o", str(out))``.
"""
def _run(input_path, *extra, timeout=180):
cmd = [
sys.executable, "-u", "-m", "clipwright.pipeline.main",
"-i", str(input_path), *extra,
]
return subprocess.run(
cmd,
cwd=str(REPO_ROOT),
env=pipeline_env,
capture_output=True,
text=True,
timeout=timeout,
)
return _run

View file

@ -0,0 +1,281 @@
"""Interpreter-startup stubs injected into the pipeline CLI child via PYTHONPATH.
This file is named ``sitecustomize`` so CPython imports it automatically at
startup, *before* the ``-m clipwright.pipeline.main`` module body runs. That
lets us satisfy the heavy imports at the top of ``main.py`` (``ultralytics``,
``mediapipe``) and replace the two network/ML edges — ASR and Gemini — with
deterministic fakes. The real CLI then runs the real pipeline with real ffmpeg
and zero network / zero ML.
Kept intentionally dependency-free (stdlib only) so it imports cleanly in the
thin ``requirements-test.txt`` environment.
"""
import json
import sys
import types
from types import SimpleNamespace
# ---------------------------------------------------------------------------
# Fake ultralytics / mediapipe: main.py imports these at module level.
# ---------------------------------------------------------------------------
class _FakeYOLO:
def __init__(self, *args, **kwargs):
self.args = args
def __call__(self, *args, **kwargs):
return []
def predict(self, *args, **kwargs):
return []
def track(self, *args, **kwargs):
return []
class _FakeFaceDetection:
def __init__(self, *args, **kwargs):
pass
def process(self, *args, **kwargs):
return SimpleNamespace(detections=None)
def close(self):
pass
def _install_module(name, module):
sys.modules[name] = module
def _fake_ultralytics():
mod = types.ModuleType("ultralytics")
mod.YOLO = _FakeYOLO
return mod
def _fake_mediapipe():
mp = types.ModuleType("mediapipe")
solutions = types.ModuleType("mediapipe.solutions")
face_detection = types.ModuleType("mediapipe.solutions.face_detection")
face_detection.FaceDetection = _FakeFaceDetection
solutions.face_detection = face_detection
mp.solutions = solutions
return mp
_install_module("ultralytics", _fake_ultralytics())
_install_module("mediapipe", _fake_mediapipe())
_install_module("mediapipe.solutions", sys.modules["mediapipe"].solutions)
_install_module("mediapipe.solutions.face_detection",
sys.modules["mediapipe"].solutions.face_detection)
# ---------------------------------------------------------------------------
# Canned transcript: patch transcribe_backends so no ASR model is loaded.
# ---------------------------------------------------------------------------
_CANNED_TRANSCRIPT = {
"text": "This is a canned transcript for the end-to-end pipeline tests.",
"language": "en",
"segments": [
{
"start": 0.0,
"end": 3.0,
"text": " This is a canned transcript",
"words": [
{"word": " This", "start": 0.0, "end": 0.4},
{"word": " is", "start": 0.4, "end": 0.7},
{"word": " a", "start": 0.7, "end": 0.9},
{"word": " canned", "start": 0.9, "end": 1.4},
{"word": " transcript", "start": 1.4, "end": 2.2},
],
},
{
"start": 3.0,
"end": 6.0,
"text": " for the end-to-end pipeline tests.",
"words": [
{"word": " for", "start": 3.0, "end": 3.3},
{"word": " the", "start": 3.3, "end": 3.5},
{"word": " end-to-end", "start": 3.5, "end": 4.4},
{"word": " pipeline", "start": 4.4, "end": 5.1},
{"word": " tests.", "start": 5.1, "end": 5.9},
],
},
],
}
def _fake_transcribe_media(media_path):
return json.loads(json.dumps(_CANNED_TRANSCRIPT))
def _fake_release_models():
return None
try:
from clipwright.pipeline import transcribe_backends as _tb
_tb.transcribe_media = _fake_transcribe_media
_tb.release_models = _fake_release_models
except Exception as _exc: # pragma: no cover - surfaced in the child's stderr
print(f"[stub_env] could not patch transcribe_backends: {_exc}", file=sys.stderr)
# ---------------------------------------------------------------------------
# Scripted Gemini client. The real SDK is imported by main.py and the stage
# modules; we replace only ``genai.Client`` (they all call ``genai.Client(...)``
# on the module object, so the patch reaches every caller).
# ---------------------------------------------------------------------------
class _FakeResponse:
"""Surface consumed by gemini_worker / main._run_gemini_stage.
``parsed`` is None so the real JSON parser runs against ``.text`` — this
exercises the production parse path instead of bypassing it.
"""
def __init__(self, text):
self.text = text
self.parsed = None
self.prompt_feedback = None
self.candidates = []
self.usage_metadata = None
def _prompt_text(contents):
if isinstance(contents, str):
return contents
parts = []
for item in contents or []:
text = getattr(item, "text", None)
if isinstance(item, str):
parts.append(item)
elif text:
parts.append(text)
return "\n".join(parts)
def _extract_windows(prompt):
"""Parse the JSON array embedded after ``WINDOWS_JSON:`` / ``..._WINDOWS_JSON:``."""
for marker in ("WINDOWS_JSON:", "CANDIDATE_WINDOWS_JSON:"):
if marker not in prompt:
continue
tail = prompt.split(marker, 1)[1]
for stop in ("\n\nReturn only:", "\n\nReturn only"):
if stop in tail:
tail = tail.split(stop, 1)[0]
try:
return json.loads(tail.strip())
except Exception:
return []
return []
def _score_response(prompt):
windows = _extract_windows(prompt)
return json.dumps({
"windows": [
{
"id": w.get("id"),
"start": float(w.get("start", 0)),
"end": float(w.get("end", 1)),
"score": 85,
"reason": "stub score",
}
for w in windows
]
})
def _detail_response(prompt):
windows = _extract_windows(prompt)
if not windows:
windows = [{"start": 0, "end": 6, "id": "w0"}]
return json.dumps({
"shorts": [
{
"start": float(w.get("start", 0)),
"end": float(w.get("end", 1)),
"source_window_id": w.get("id") or "w0",
"predicted_score": 85,
"video_description_for_tiktok": "Stub #test #clip",
"video_description_for_instagram": "Stub #test #clip",
"video_title_for_youtube_short": "Stub clip",
"viral_hook_text": "Stub hook",
"why": "stub moment",
}
for w in windows
]
})
def _visual_response(prompt):
return json.dumps({
"shorts": [
{
"start": 0.0,
"end": 5.0,
"predicted_score": 80,
"video_description_for_tiktok": "Stub #test #clip",
"video_description_for_instagram": "Stub #test #clip",
"video_title_for_youtube_short": "Stub visual clip",
"viral_hook_text": "Stub visual hook",
}
]
})
def _response_for(prompt):
if "RANK these candidate windows" in prompt:
return _score_response(prompt)
if "Choose the BEST short clips" in prompt:
return _detail_response(prompt)
if "This video has NO speech/audio" in prompt:
return _visual_response(prompt)
if "These frames come from ONE short clip" in prompt:
return json.dumps({
"on_screen": "a screen",
"viral_hook_text": "Stub grounded hook",
"video_title_for_youtube_short": "Stub grounded title",
})
if "You are choosing how to re-frame" in prompt:
return json.dumps({"layout": "none", "confidence": 0.95, "why": "talking head"})
if "preparing a landscape video" in prompt:
return json.dumps({"ranges": []})
return "{}"
class _FakeModels:
def generate_content(self, model=None, contents=None, config=None):
return _FakeResponse(_response_for(_prompt_text(contents)))
class _FakeFiles:
def upload(self, file=None, config=None):
return SimpleNamespace(name="files/stub-video")
def get(self, name=None):
return SimpleNamespace(state=SimpleNamespace(name="ACTIVE"))
def delete(self, name=None):
return None
class _FakeClient:
def __init__(self, api_key=None, **kwargs):
self.models = _FakeModels()
self.files = _FakeFiles()
try:
from google import genai as _genai
_genai.Client = _FakeClient
except Exception as _exc: # pragma: no cover - surfaced in the child's stderr
print(f"[stub_env] could not patch google.genai.Client: {_exc}", file=sys.stderr)

View file

@ -0,0 +1,119 @@
"""L4 — full CLI pipeline (the keystone test).
Runs the REAL ``python -m clipwright.pipeline.main`` end to end with real
ffmpeg. The child interpreter is started with ``stub_env`` first on
``PYTHONPATH``, so ``sitecustomize.py`` injects the fake ultralytics/mediapipe
modules, stubs ASR, and patches the Gemini client. The test asserts on exit
code, metadata JSON, real clip files (ffprobe, never bytes) and the
``CLIP_READY`` markers — plus a failure variant that must write no metadata.
"""
import json
import subprocess
from pathlib import Path
import pytest
pytestmark = [pytest.mark.e2e, pytest.mark.pipeline]
def _cli_env(pipeline_env, **overrides):
"""Pin the deterministic, no-ML pipeline environment for the child."""
pipeline_env.update({
"GEMINI_API_KEY": "test",
"AUTO_LAYOUT": "0",
"SCENE_ENGINE": "pyscenedetect",
"FFMPEG_ENCODER": "x264",
"ASR_HOST_SLOTS": "0",
"CLIP_WORKERS": "2",
})
for var in ("AUTO_HOOK", "MAX_SOURCE_MINUTES",
"SOURCE_CAP_MINUTES", "DOWNLOAD_SKIP_STATICS"):
pipeline_env.pop(var, None)
pipeline_env.update(overrides)
return pipeline_env
def _probe(path):
out = subprocess.run(
["ffprobe", "-v", "error", "-select_streams", "v:0",
"-show_entries", "stream=width,height", "-of", "csv=p=0:s=x", str(path)],
capture_output=True, text=True, check=True)
width, height = out.stdout.strip().split("x")
return int(width), int(height)
def _ready_lines(stdout):
return [line for line in stdout.splitlines() if line.startswith("CLIP_READY ")]
def _assert_success(result, out, media, fmt):
assert result.returncode == 0, (
f"CLI failed ({result.returncode})\nSTDOUT:\n{result.stdout[-4000:]}\n"
f"STDERR:\n{result.stderr[-4000:]}")
metadata_files = list(out.glob("*_metadata.json"))
assert len(metadata_files) == 1
meta = json.loads(metadata_files[0].read_text())
assert meta["shorts"], "expected at least one clip"
assert meta["transcript"]["segments"], "expected the transcript in metadata"
assert meta["source_video"] == media.name
assert meta["output_format"] == fmt
base = media.stem
clips = sorted(out.glob(f"{base}_clip_*.mp4"))
assert len(clips) == len(meta["shorts"])
for clip in clips:
assert clip.stat().st_size > 1024
assert _probe(clip)[0] > 0
ready = _ready_lines(result.stdout)
assert len(ready) == len(meta["shorts"])
return meta, clips
def test_cli_full_pipeline_vertical(run_pipeline, pipeline_env, media_factory, tmp_path):
_cli_env(pipeline_env)
out = tmp_path / "out"
result = run_pipeline(media_factory.six, "-o", str(out), "--format", "vertical")
meta, clips = _assert_success(result, out, media_factory.six, "vertical")
width, height = _probe(clips[0])
assert height > width, f"vertical clip should be portrait, got {width}x{height}"
def test_cli_full_pipeline_horizontal(run_pipeline, pipeline_env, media_factory, tmp_path):
_cli_env(pipeline_env)
out = tmp_path / "out"
result = run_pipeline(media_factory.six, "-o", str(out), "--format", "horizontal")
meta, clips = _assert_success(result, out, media_factory.six, "horizontal")
width, height = _probe(clips[0])
assert width > height, f"horizontal clip should be landscape, got {width}x{height}"
def test_cli_failure_writes_no_metadata(run_pipeline, pipeline_env, media_factory, tmp_path):
# No Gemini key + no clips available -> the pipeline raises instead of
# shipping a silent render; nothing must be written to the output dir.
_cli_env(pipeline_env, GEMINI_API_KEY="")
out = tmp_path / "out"
result = run_pipeline(media_factory.silent, "-o", str(out), "--format", "vertical")
assert result.returncode != 0
assert not list(out.glob("*_metadata.json"))
assert not list(out.glob("*_clip_*.mp4"))
def test_cli_missing_input_exits_nonzero(run_pipeline, pipeline_env, tmp_path):
_cli_env(pipeline_env)
out = tmp_path / "out"
result = run_pipeline(tmp_path / "does-not-exist.mp4", "-o", str(out))
assert result.returncode != 0
assert not list(out.glob("*_metadata.json"))

View file

@ -0,0 +1,347 @@
"""L4 — download stage.
Covers the pure attempt planner, the real-ffmpeg duration cap, and the
``download_youtube_video`` orchestration with a fake ``yt_dlp.YoutubeDL`` (no
network, no real yt-dlp download). The download path imports ``main`` lazily,
so ``heavy_stubs`` injects the fake ``ultralytics``/``mediapipe`` modules first
(the heavy deps are not installed in the thin E2E environment).
"""
import json
import os
import shutil
import subprocess
from types import SimpleNamespace
import pytest
pytestmark = [pytest.mark.e2e, pytest.mark.pipeline]
# A public, literal IP so ``assert_public_url`` passes without a DNS lookup
# (the shared ``no_network`` guard blocks hostname resolution).
_DIRECT_URL = "http://93.184.216.34/video.mp4"
@pytest.fixture(scope="session")
def heavy_stubs():
"""Inject fake ``ultralytics``/``mediapipe`` then import ``main`` lazily."""
import sys
import types
if "ultralytics" not in sys.modules:
ul = types.ModuleType("ultralytics")
class _YOLO:
def __init__(self, *args, **kwargs):
pass
def __call__(self, *args, **kwargs):
return []
def predict(self, *args, **kwargs):
return []
ul.YOLO = _YOLO
sys.modules["ultralytics"] = ul
if "mediapipe" not in sys.modules:
mp = types.ModuleType("mediapipe")
solutions = types.ModuleType("mediapipe.solutions")
face_detection = types.ModuleType("mediapipe.solutions.face_detection")
class _FaceDetection:
def __init__(self, *args, **kwargs):
pass
def process(self, *args, **kwargs):
return SimpleNamespace(detections=None)
def close(self):
pass
face_detection.FaceDetection = _FaceDetection
solutions.face_detection = face_detection
mp.solutions = solutions
sys.modules["mediapipe"] = mp
sys.modules["mediapipe.solutions"] = solutions
sys.modules["mediapipe.solutions.face_detection"] = face_detection
import clipwright.pipeline.main as main
return main
# ---------------------------------------------------------------------------
# plan_download_attempts — pure
# ---------------------------------------------------------------------------
def test_plan_direct_file_url(heavy_stubs):
plan = heavy_stubs.plan_download_attempts(False, [], None, False, youtube=False)
assert plan == [("direct", False, None)]
def test_plan_direct_file_url_with_static_fallback(heavy_stubs):
plan = heavy_stubs.plan_download_attempts(
False, ["http://s1", "http://s2"], "http://paid", True, youtube=False)
assert plan == [("direct", False, None),
("static-fallback", False, "http://s1")]
def test_plan_youtube_full_ladder(heavy_stubs):
plan = heavy_stubs.plan_download_attempts(
True, ["s1", "s2"], "P", True, youtube=True)
assert plan == [
("HD-direct", False, None),
("HD-static1", False, "s1"),
("HD-static2", False, "s2"),
("fallback-static", False, "s1"),
("HD", True, "P"),
("fallback", True, "P"),
]
def test_plan_youtube_paid_only_no_hd(heavy_stubs):
plan = heavy_stubs.plan_download_attempts(
False, [], "P", False, youtube=True)
assert plan == [("fallback", True, "P")]
def test_plan_youtube_static_only_hd(heavy_stubs):
plan = heavy_stubs.plan_download_attempts(
False, ["s1"], None, True, youtube=True)
assert plan == [
("HD-static1", False, "s1"),
("HD", False, None),
("fallback", False, "s1"),
]
def test_plan_skip_statics_goes_straight_to_paid(heavy_stubs):
plan = heavy_stubs.plan_download_attempts(
True, ["s1"], "P", True, youtube=True, skip_statics=True)
assert plan == [("HD", True, "P"), ("fallback", True, "P")]
def test_plan_skip_statics_ignored_without_paid(heavy_stubs):
plan = heavy_stubs.plan_download_attempts(
False, ["s1"], None, True, youtube=True, skip_statics=True)
assert plan == [
("HD-static1", False, "s1"),
("HD", False, None),
("fallback", False, "s1"),
]
# ---------------------------------------------------------------------------
# cap_source_duration — real ffmpeg
# ---------------------------------------------------------------------------
def _duration_seconds(path):
out = subprocess.run(
["ffprobe", "-v", "error", "-show_entries", "format=duration",
"-of", "default=nw=1:nk=1", str(path)],
capture_output=True, text=True, check=True)
return float(out.stdout.strip())
def test_cap_source_duration_leaves_short_source_untouched(heavy_stubs, media_factory, tmp_path):
src = tmp_path / "six.mp4"
shutil.copy(media_factory.six, src)
before = (src.stat().st_size, src.stat().st_mtime_ns)
result = heavy_stubs.cap_source_duration(str(src), 10)
assert result == str(src)
assert (src.stat().st_size, src.stat().st_mtime_ns) == before
def test_cap_source_duration_cuts_long_source(heavy_stubs, media_factory, tmp_path):
src = tmp_path / "sixty.mp4"
shutil.copy(media_factory.sixty, src)
assert _duration_seconds(src) > 55
result = heavy_stubs.cap_source_duration(str(src), 0.5)
assert result == str(src)
# Stream-copy lands on a packet boundary a fraction past the cap.
assert _duration_seconds(src) <= 32.0
def test_cap_source_duration_safety_within_margin_untouched(heavy_stubs, media_factory, tmp_path):
src = tmp_path / "sixty.mp4"
shutil.copy(media_factory.sixty, src)
before = src.stat().st_size
result = heavy_stubs.cap_source_duration(str(src), 0.5, safety=True)
# 60s is within the 30s safety margin of a 30s cap: left alone.
assert result == str(src)
assert src.stat().st_size == before
def test_cap_source_duration_degenerate_inputs(heavy_stubs, tmp_path):
src = tmp_path / "x.mp4"
src.write_bytes(b"not a video")
assert heavy_stubs.cap_source_duration(str(src), 0) == str(src)
assert heavy_stubs.cap_source_duration(str(src), "abc") == str(src)
# ---------------------------------------------------------------------------
# _content_block — user-facing reasons
# ---------------------------------------------------------------------------
def test_content_block_private(heavy_stubs):
msg = heavy_stubs._content_block("ERROR: Private video. Sign in if you've been granted access")
assert "private on YouTube" in msg
assert "Unlisted" in msg
def test_content_block_members_only(heavy_stubs):
assert "members only" in heavy_stubs._content_block("Join this channel to get access")
assert "members only" in heavy_stubs._content_block("This video is members-only")
def test_content_block_none_for_network_error(heavy_stubs):
assert heavy_stubs._content_block("Video unavailable") is None
assert heavy_stubs._content_block("HTTP Error 429") is None
# ---------------------------------------------------------------------------
# download_youtube_video — fake yt-dlp
# ---------------------------------------------------------------------------
class _FakeYoutubeDL:
"""Minimal YoutubeDL double: ``process_ie_result`` writes the merged mp4."""
mode = "success"
title = "My Video"
def __init__(self, opts):
self.opts = opts
def __enter__(self):
return self
def __exit__(self, *exc):
return False
def extract_info(self, url, download=False, process=False):
if _FakeYoutubeDL.mode == "private":
raise Exception(
"ERROR: Private video. Sign in if you've been granted access to this video")
if _FakeYoutubeDL.mode == "unavailable":
raise Exception("ERROR: Video unavailable")
return {
"title": _FakeYoutubeDL.title,
"formats": [{"format_id": "18"}],
"duration": 60,
"_type": "video",
}
def _write(self):
outtmpl = self.opts.get("outtmpl") or ""
path = outtmpl.replace("%(ext)s", "mp4")
if path:
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "wb") as fh:
fh.write(b"\x00" * 4096)
return path
def process_ie_result(self, info, download=True):
path = self._write()
return {"requested_downloads": [{"filepath": path}]}
def download(self, urls):
self._write()
return 0
@pytest.fixture
def fake_ytdlp(monkeypatch, heavy_stubs):
_FakeYoutubeDL.mode = "success"
_FakeYoutubeDL.title = "My Video"
monkeypatch.setattr(heavy_stubs.yt_dlp, "YoutubeDL", _FakeYoutubeDL)
for var in ("PROXY_URL", "STATIC_PROXY_URLS", "DIRECT_FIRST",
"DOWNLOAD_SKIP_STATICS", "YOUTUBE_COOKIES",
"MAX_SOURCE_MINUTES", "SOURCE_CAP_MINUTES", "BGUTIL_BASE_URL",
"BGUTIL_SCRIPT_PATH"):
monkeypatch.delenv(var, raising=False)
return _FakeYoutubeDL
def _route_from_stdout(text):
line = next(l for l in text.splitlines() if l.startswith("PROXY_ROUTE="))
return json.loads(line.split("=", 1)[1])
def test_download_direct_success(heavy_stubs, fake_ytdlp, tmp_path, capsys):
path, title = heavy_stubs.download_youtube_video(_DIRECT_URL, str(tmp_path))
assert title == "My_Video"
assert path == str(tmp_path / "My_Video.mp4")
assert os.path.getsize(path) > 0
route = _route_from_stdout(capsys.readouterr().out)
assert route["winner"] == "direct"
assert route["paid_bytes"] == 0
def test_download_static_proxy_wins_before_paid(heavy_stubs, fake_ytdlp, monkeypatch,
tmp_path, capsys):
import clipwright.core.security_utils as security
# Avoid DNS for the youtube hostname; the guard itself is unit-tested elsewhere.
monkeypatch.setattr(security, "assert_public_url", lambda url: url)
monkeypatch.setenv("STATIC_PROXY_URLS", "http://static-1:8080")
monkeypatch.setenv("PROXY_URL", "http://paid-proxy:8080")
path, title = heavy_stubs.download_youtube_video(
"https://www.youtube.com/watch?v=abc123", str(tmp_path))
assert title == "My_Video"
assert os.path.exists(path)
out = capsys.readouterr().out
route = _route_from_stdout(out)
assert route["winner"] == "fallback-static"
assert route["attempts"][0]["paid"] is False
assert "PROXY_BYTES=" not in out
def test_download_paid_proxy_used_without_statics(heavy_stubs, fake_ytdlp, monkeypatch,
tmp_path, capsys):
import clipwright.core.security_utils as security
monkeypatch.setattr(security, "assert_public_url", lambda url: url)
monkeypatch.setenv("PROXY_URL", "http://paid-proxy:8080")
heavy_stubs.download_youtube_video(
"https://www.youtube.com/watch?v=abc123", str(tmp_path))
route = _route_from_stdout(capsys.readouterr().out)
assert route["winner"] == "fallback"
assert route["attempts"][0]["paid"] is True
def test_download_private_video_raises_with_message(heavy_stubs, fake_ytdlp,
tmp_path, capsys):
_FakeYoutubeDL.mode = "private"
with pytest.raises(Exception) as excinfo:
heavy_stubs.download_youtube_video(_DIRECT_URL, str(tmp_path))
assert "Private video" in str(excinfo.value)
out = capsys.readouterr().out
assert "private on YouTube" in out
assert not (tmp_path / "My_Video.mp4").exists()
def test_download_all_attempts_failed_raises(heavy_stubs, fake_ytdlp, tmp_path, capsys):
_FakeYoutubeDL.mode = "unavailable"
with pytest.raises(Exception):
heavy_stubs.download_youtube_video(_DIRECT_URL, str(tmp_path))
out = capsys.readouterr().out
assert "YOUTUBE DOWNLOAD FAILED" in out
assert not (tmp_path / "My_Video.mp4").exists()

View file

@ -0,0 +1,150 @@
"""L5 Pipeline media — HOOK stage.
The overlay image is drawn from the repo's bundled fonts (never downloaded), the
real ffmpeg overlay must land next to the clip under the ``hooked_<ts>_`` name,
the combined hook+captions pass writes both files from one decode, and a bad
hook fails open (returns None) instead of costing the clip.
"""
import os
import shutil
import subprocess
import sys
import types
from types import SimpleNamespace
import pytest
from PIL import Image
from clipwright.media import hooks
pytestmark = [pytest.mark.e2e, pytest.mark.pipeline]
def _install_ml_stubs():
if "ultralytics" in sys.modules and "mediapipe" in sys.modules:
return
class _FakeYOLO:
def __init__(self, *a, **k):
pass
def __call__(self, *a, **k):
return []
def predict(self, *a, **k):
return []
def track(self, *a, **k):
return []
class _FakeFaceDetection:
def __init__(self, *a, **k):
pass
def process(self, *a, **k):
return SimpleNamespace(detections=None)
def close(self):
pass
ul = types.ModuleType("ultralytics")
ul.YOLO = _FakeYOLO
sys.modules["ultralytics"] = ul
mp = types.ModuleType("mediapipe")
solutions = types.ModuleType("mediapipe.solutions")
fd = types.ModuleType("mediapipe.solutions.face_detection")
fd.FaceDetection = _FakeFaceDetection
solutions.face_detection = fd
mp.solutions = solutions
sys.modules["mediapipe"] = mp
sys.modules["mediapipe.solutions"] = solutions
sys.modules["mediapipe.solutions.face_detection"] = fd
_install_ml_stubs()
from clipwright.pipeline import main # noqa: E402
TRANSCRIPT = {
"language": "en",
"segments": [{
"start": 0.0, "end": 3.0, "text": " hello world",
"words": [
{"word": " hello", "start": 0.0, "end": 0.6},
{"word": " world", "start": 0.7, "end": 1.4},
],
}],
}
def _probe_dims(path):
out = subprocess.check_output(
["ffprobe", "-v", "error", "-select_streams", "v:0",
"-show_entries", "stream=width,height", "-of", "csv=p=0:s=x", str(path)],
text=True).strip()
w, h = out.split("x")
return int(w), int(h)
@pytest.fixture
def clip(tmp_path, media_factory):
dest = tmp_path / "clip.mp4"
shutil.copyfile(media_factory.six, dest)
return dest
class TestCreateHookImage:
def test_repo_font_draws_a_nonempty_png(self, tmp_path):
out = tmp_path / "hook.png"
path, w, h = hooks.create_hook_image("Big news today", 1080, str(out))
assert os.path.exists(path) and w > 0 and h > 0
with Image.open(out) as img:
assert img.size == (w, h)
def test_classic_style_also_renders(self, tmp_path):
out = tmp_path / "classic.png"
path, _w, _h = hooks.create_hook_image("Hello", 720, str(out), style="classic")
assert os.path.exists(path)
class TestAddHookToVideo:
def test_overlay_writes_a_playable_file(self, clip, tmp_path):
out = tmp_path / "hooked.mp4"
assert hooks.add_hook_to_video(str(clip), "Watch this", str(out)) is True
assert out.exists() and out.stat().st_size > 0
assert _probe_dims(out) == (320, 180)
class TestAutoHookClip:
def test_writes_a_hooked_derivative_next_to_the_clip(self, clip, tmp_path):
result = main.auto_hook_clip(str(clip), {"viral_hook_text": "Must see this"})
assert result is not None
out_path, config = result
assert os.path.basename(out_path).startswith("hooked_")
assert os.path.basename(out_path).endswith("_clip.mp4")
assert os.path.exists(out_path)
assert config["text"] == "Must see this"
def test_combined_hook_and_captions_write_both_files(self, clip, tmp_path):
plan = main.auto_caption_clip(str(clip), TRANSCRIPT, 0.0, 3.0, plan_only=True)
assert plan is not None
vf, generation_id = plan
result = main.auto_hook_clip(str(clip), {"viral_hook_text": "Combined"},
captions=(vf, generation_id))
assert result is not None
out_path, config = result
assert "_captioned" in config
captioned = config["_captioned"]
assert os.path.exists(out_path)
assert os.path.exists(captioned)
assert os.path.basename(captioned).startswith("subtitled_")
assert os.path.basename(captioned).endswith(os.path.basename(out_path))
def test_empty_text_is_skipped(self, clip):
assert main.auto_hook_clip(str(clip), {"viral_hook_text": " "}) is None
def test_missing_clip_fails_open(self, tmp_path):
missing = tmp_path / "nope.mp4"
assert main.auto_hook_clip(str(missing), {"viral_hook_text": "hi"}) is None

View file

@ -0,0 +1,245 @@
"""L5 Pipeline media — LAYOUT stage.
Covers the layout picker's flag mapping (``layout_picker.apply`` / the API's
``layout_env``), the pure geometry every layout engine hands to ffmpeg
(``reframe_v2``, ``split_layout``, ``screencast_layout``, ``punch_in``) and the
``layout_ranges`` sidecar round-trip. No ML: ``apply`` is exercised with stand-in
modules so a real ``ENABLED`` flag is never flipped for a later test.
"""
import sys
import types
import pytest
from clipwright.layouts import layout_ranges
from clipwright.layouts import layout_picker
from clipwright.layouts import punch_in
from clipwright.layouts import screencast_layout
from clipwright.layouts import split_layout
from clipwright.layouts import reframe_v2
pytestmark = [pytest.mark.e2e, pytest.mark.pipeline]
VERTICAL = 9 / 16
_FAKE_LAYOUT_MODULES = {
"split_layout": "clipwright.layouts.split_layout",
"screencast_layout": "clipwright.layouts.screencast_layout",
"active_speaker": "clipwright.layouts.active_speaker",
}
def fake_modules(monkeypatch, **initial):
"""Install stand-in layout modules so ``apply`` never mutates real globals."""
from clipwright import layouts
made = {}
for label, dotted in _FAKE_LAYOUT_MODULES.items():
module = types.ModuleType(dotted)
module.ENABLED = initial.get(label, False)
monkeypatch.setitem(sys.modules, dotted, module)
monkeypatch.setattr(layouts, label, module, raising=False)
made[dotted] = module
return made
# --- layout_picker.apply ----------------------------------------------------
class TestPickerFlagMapping:
def test_split_enables_both_modules(self, monkeypatch):
mods = fake_modules(monkeypatch)
assert set(layout_picker.apply("split")) == {"split_layout", "active_speaker"}
assert mods["clipwright.layouts.split_layout"].ENABLED is True
assert mods["clipwright.layouts.active_speaker"].ENABLED is True
def test_screencast_enables_only_its_module(self, monkeypatch):
mods = fake_modules(monkeypatch)
assert layout_picker.apply("screencast") == ["screencast_layout"]
assert mods["clipwright.layouts.screencast_layout"].ENABLED is True
assert mods["clipwright.layouts.split_layout"].ENABLED is False
def test_none_is_inert(self, monkeypatch):
mods = fake_modules(monkeypatch)
assert layout_picker.apply("none") == []
assert not any(m.ENABLED for m in mods.values())
def test_unknown_decision_is_inert(self, monkeypatch):
fake_modules(monkeypatch)
assert layout_picker.apply("gameplay") == []
def test_already_enabled_is_not_reported(self, monkeypatch):
fake_modules(monkeypatch, screencast_layout=True)
assert layout_picker.apply("screencast") == []
def test_pick_and_apply_uses_the_stubbed_pick(self, monkeypatch):
mods = fake_modules(monkeypatch)
monkeypatch.setattr(layout_picker, "ENABLED", True)
monkeypatch.setattr(layout_picker, "SHADOW", False)
monkeypatch.setattr(layout_picker, "pick", lambda *a, **k: "screencast")
assert layout_picker.pick_and_apply("v.mp4", 60) == "screencast"
assert mods["clipwright.layouts.screencast_layout"].ENABLED is True
def test_shadow_mode_decides_but_applies_nothing(self, monkeypatch):
mods = fake_modules(monkeypatch)
monkeypatch.setattr(layout_picker, "ENABLED", True)
monkeypatch.setattr(layout_picker, "SHADOW", True)
monkeypatch.setattr(layout_picker, "pick", lambda *a, **k: "split")
assert layout_picker.pick_and_apply("v.mp4", 90) == "split"
assert not any(m.ENABLED for m in mods.values())
@pytest.fixture
def layout_env():
"""``layout_env`` is the request -> env-flag bridge the API hands the job."""
app = pytest.importorskip("clipwright.api.app")
return app.layout_env
class TestApiLayoutEnv:
def test_none_and_auto_toggle_the_picker(self, layout_env):
assert layout_env(["none"]) == {"AUTO_LAYOUT": "0"}
assert layout_env(["auto"]) == {"AUTO_LAYOUT": "1"}
def test_explicit_picks_map_to_their_env_vars(self, layout_env):
assert layout_env(["split"])["SPLIT_LAYOUT"] == "1"
assert layout_env(["screencast"])["SCREENCAST_LAYOUT"] == "1"
assert layout_env(["punch_in"])["PUNCH_IN"] == "1"
def test_split_implies_the_speaker_signal(self, layout_env):
assert layout_env(["split"]).get("SPEAKER_SIGNAL") == "1"
def test_unknown_names_are_ignored(self, layout_env):
assert layout_env(["teleport", ""]) == {}
def test_auto_composes_with_explicit_picks(self, layout_env):
env = layout_env(["auto", "punch_in"])
assert env["AUTO_LAYOUT"] == "1" and env["PUNCH_IN"] == "1"
# --- reframe_v2 pure geometry ----------------------------------------------
class TestReframeGeometry:
def test_delivery_size_upscales_a_720p_source_to_the_floor(self):
assert reframe_v2.delivery_size(1280, 720, VERTICAL) == (1080, 1920)
def test_delivery_size_never_downscales_a_4k_source(self):
assert reframe_v2.delivery_size(3840, 2160, VERTICAL) == (1216, 2160)
def test_delivery_size_always_even(self):
for w, h in [(320, 180), (854, 480), (641, 361)]:
out_w, out_h = reframe_v2.delivery_size(w, h, VERTICAL)
assert out_w % 2 == 0 and out_h % 2 == 0
def test_general_filtergraph_blurs_background_and_centres(self):
graph = reframe_v2.general_filtergraph(1080, 1920, orig_w=1920, orig_h=1080)
assert "gblur" in graph
assert "overlay=x=(W-w)/2:y=(H-h)/2" in graph
def test_scene_ranges_clamp_and_keep_strategy(self):
ranges = reframe_v2.scene_frame_ranges(
[(0, 100), (100, 250), (250, 400)],
["TRACK", "GENERAL", "TRACK"], total_frames=200)
assert ranges == [(0, 100, "TRACK"), (100, 200, "GENERAL")]
def test_source_already_fits_vertical(self):
assert reframe_v2.source_already_fits(1080, 1920, VERTICAL)
assert not reframe_v2.source_already_fits(1920, 1080, VERTICAL)
def test_sendcmd_lines_dedupe_to_change_points(self):
assert reframe_v2.dedupe_sendcmd_lines([100, 100, 104], fps=30.0) == [
"0.0000 crop@c x 100;",
"0.0667 crop@c x 104;",
]
# --- split_layout pure geometry --------------------------------------------
class TestSplitGeometry:
def test_two_shot_qualifies_and_is_ordered(self):
frames = [[{"box": [500, 300, 200, 200], "score": 40000},
{"box": [1300, 300, 200, 200], "score": 40000}] for _ in range(10)]
left, right = split_layout.analyze_scene(frames, frame_w=1920)
assert left[0] < right[0]
def test_single_speaker_is_rejected(self):
frames = [[{"box": [800, 300, 200, 200], "score": 40000}] for _ in range(10)]
assert split_layout.analyze_scene(frames, frame_w=1920) is None
def test_split_geometry_stays_inside_the_source(self):
w, h, x, y, half_h = split_layout.split_geometry(1920, 1080, 1080, 1920, (600, 400))
assert w <= 1920 and h <= 1080
assert 0 <= x <= 1920 - w and 0 <= y <= 1080 - h
assert w % 2 == 0 and h % 2 == 0 and half_h == 960
def test_split_filtergraph_stacks_into_the_output(self):
graph = split_layout.split_filtergraph(1920, 1080, 1080, 1920,
(600, 400), (1400, 400))
assert "vstack=inputs=2" in graph
assert "pad=1080:1920" in graph
# --- screencast_layout pure geometry ---------------------------------------
class TestScreencastGeometry:
def test_content_bands_keep_full_width(self):
content_h, speaker_h = screencast_layout.content_bands(1920, 1080, 1080, 1920)
assert content_h == 608 and speaker_h == 1312
assert content_h % 2 == 0
def test_speaker_crop_is_inside_the_frame(self):
w, h, x, y = screencast_layout.speaker_crop(1920, 1080, 1080, 1312, (600, 400))
assert w <= 1920 and h <= 1080
assert 0 <= x <= 1920 - w and 0 <= y <= 1080 - h
def test_screencast_filtergraph_stacks_content_over_speaker(self):
graph = screencast_layout.screencast_filtergraph(1920, 1080, 1080, 1920, (600, 400))
assert "[ca]scale=1080:608" in graph
assert "vstack=inputs=2" in graph
# --- punch_in pure geometry -------------------------------------------------
class TestPunchIn:
def test_zoom_curve_is_flat_without_beats(self):
assert punch_in.zoom_curve(10, 30.0, []) == [1.0] * 10
def test_zoom_curve_peaks_on_a_beat_and_returns(self):
zooms = punch_in.zoom_curve(300, 30.0, [2.0], max_zoom=1.2)
assert max(zooms) > 1.0
# The push starts at 1.0 and has fully relaxed long before the end.
assert zooms[0] == 1.0 and zooms[-1] == 1.0
def test_crop_boxes_zoom_about_the_crop_centre(self):
boxes = punch_in.crop_boxes([100, 100], [1.0, 1.25], 320, 180, 640, 360)
assert boxes[0][0] == 320 and boxes[1][0] < 320
assert all(b[0] % 2 == 0 and b[1] % 2 == 0 for b in boxes)
def test_sendcmd_lines_emit_only_changes(self):
boxes = [(320, 180, 0, 0), (320, 180, 0, 0), (256, 144, 32, 18)]
lines = punch_in.sendcmd_lines(boxes, fps=30.0)
assert lines[0] == "0.0000 crop@c w 320;"
assert any("crop@c x 32;" in line for line in lines)
# The unchanged middle frame adds nothing.
assert not any(line.startswith("0.0333") for line in lines)
# --- layout_ranges sidecar round-trip --------------------------------------
class TestLayoutRangesRoundTrip:
def test_write_read_and_split_ranges(self, tmp_path):
clip = str(tmp_path / "clip_1.mp4")
layout_ranges.write(clip, [(0, 4.5, "TRACK"), (4.5, 10, "SPLIT")])
got = layout_ranges.read(clip)
assert got == [{"start": 0.0, "end": 4.5, "layout": "track"},
{"start": 4.5, "end": 10.0, "layout": "split"}]
assert layout_ranges.split_ranges(got) == [(4.5, 10.0)]
def test_missing_sidecar_reads_empty(self, tmp_path):
assert layout_ranges.read(str(tmp_path / "nope.mp4")) == []
def test_remap_across_a_cut(self):
ranges = [(0, 10, "split"), (10, 20, "track")]
got = layout_ranges.remap(ranges, [{"start": 5, "end": 12}])
assert got == [{"start": 0.0, "end": 5.0, "layout": "split"},
{"start": 5.0, "end": 7.0, "layout": "track"}]

View file

@ -0,0 +1,180 @@
"""L5 Pipeline media — RENDER / REFRAME stage.
Real ffmpeg throughout. ``clipwright.pipeline.main`` imports ``ultralytics`` and
``mediapipe`` at module level (heavy deps absent in this thin env), so fake
modules are injected into ``sys.modules`` *before* importing it. With the fakes
in place no detector finds a face, so every scene classifies GENERAL and the
reframe runs the blurred-background layout — exactly the path we probe.
"""
import os
import shutil
import subprocess
import sys
import types
from types import SimpleNamespace
import pytest
pytestmark = [pytest.mark.e2e, pytest.mark.pipeline]
def _install_ml_stubs():
"""Mirror stub_env/sitecustomize.py for in-process imports of main.py."""
if "ultralytics" in sys.modules and "mediapipe" in sys.modules:
return
class _FakeYOLO:
def __init__(self, *a, **k):
pass
def __call__(self, *a, **k):
return []
def predict(self, *a, **k):
return []
def track(self, *a, **k):
return []
class _FakeFaceDetection:
def __init__(self, *a, **k):
pass
def process(self, *a, **k):
return SimpleNamespace(detections=None)
def close(self):
pass
ul = types.ModuleType("ultralytics")
ul.YOLO = _FakeYOLO
sys.modules["ultralytics"] = ul
mp = types.ModuleType("mediapipe")
solutions = types.ModuleType("mediapipe.solutions")
fd = types.ModuleType("mediapipe.solutions.face_detection")
fd.FaceDetection = _FakeFaceDetection
solutions.face_detection = fd
mp.solutions = solutions
sys.modules["mediapipe"] = mp
sys.modules["mediapipe.solutions"] = solutions
sys.modules["mediapipe.solutions.face_detection"] = fd
_install_ml_stubs()
from clipwright.layouts import layout_ranges # noqa: E402
from clipwright.layouts import reframe_v2 # noqa: E402
from clipwright.media import recut # noqa: E402
from clipwright.pipeline import main # noqa: E402
def _probe_dims(path):
out = subprocess.check_output(
["ffprobe", "-v", "error", "-select_streams", "v:0",
"-show_entries", "stream=width,height", "-of", "csv=p=0:s=x", str(path)],
text=True).strip()
w, h = out.split("x")
return int(w), int(h)
@pytest.fixture(autouse=True)
def _pyscenedetect(monkeypatch):
"""TransNetV2 is ML; use the installed PySceneDetect fallback."""
monkeypatch.setenv("SCENE_ENGINE", "pyscenedetect")
@pytest.fixture
def clip(tmp_path, media_factory):
"""A real, playable 320x180 6s clip with audio in the test's tmp tree."""
dest = tmp_path / "clip.mp4"
shutil.copyfile(media_factory.six, dest)
return dest
class TestReframeRender:
def test_render_produces_a_vertical_delivery_and_sidecar(self, clip, tmp_path):
out = tmp_path / "out.mp4"
assert reframe_v2.render(str(clip), str(out), 9 / 16) is True
assert out.exists() and out.stat().st_size > 0
assert _probe_dims(out) == (1080, 1920)
# The render records which stretches used which layout for the
# caption pass.
ranges = layout_ranges.read(str(out))
assert ranges and all(r["layout"] == "general" for r in ranges)
def test_render_force_strategy_track_uses_the_crop_path(self, clip, tmp_path):
out = tmp_path / "track.mp4"
assert reframe_v2.render(str(clip), str(out), 9 / 16,
force_strategy="TRACK") is True
assert _probe_dims(out) == (1080, 1920)
class TestRecut:
def test_fast_path_real_ffmpeg_keeps_source_dimensions(self, clip, tmp_path):
served, clean = recut.perform_recut(
input_path=str(clip), segments=[{"start": 0, "end": 3}],
output_dir=str(tmp_path), clean_name="clip_1.mp4")
assert served == clean
assert served.startswith("recut_") and served.endswith("_clip_1.mp4")
assert _probe_dims(tmp_path / served) == (320, 180)
def test_source_path_wires_the_renderer(self, tmp_path):
events = []
def fake_runner(cmd):
with open(cmd[-1], "wb") as f:
f.write(b"x")
def fake_renderer(work, out, output_format):
events.append(("reframe", output_format))
with open(out, "wb") as f:
f.write(b"x")
return True
served, clean = recut.perform_recut(
input_path="source.mp4", segments=[{"start": 5, "end": 15}],
output_dir=str(tmp_path), clean_name="clip_1.mp4",
reframe=True, output_format="vertical",
runner=fake_runner, renderer=fake_renderer)
assert events == [("reframe", "vertical")]
assert served == clean
def test_captioner_is_invoked_last_and_wins_the_served_name(self, tmp_path):
seen = []
def fake_runner(cmd):
with open(cmd[-1], "wb") as f:
f.write(b"x")
def fake_captioner(path, transcript, start, end):
seen.append((os.path.basename(path), start, end))
out = os.path.join(os.path.dirname(path),
f"subtitled_1_{os.path.basename(path)}")
with open(out, "wb") as f:
f.write(b"x")
return out
transcript = {"segments": [{"words": [{"word": " a", "start": 0, "end": 1}]}]}
served, clean = recut.perform_recut(
input_path="clip.mp4", segments=[{"start": 0, "end": 10}],
output_dir=str(tmp_path), clean_name="clip_1.mp4",
captions_transcript=transcript,
runner=fake_runner, captioner=fake_captioner)
assert served == f"subtitled_1_{clean}"
assert seen == [(clean, 0.0, 10.0)]
class TestMainClipHelpers:
def test_cut_clip_writes_a_playable_slice(self, clip, tmp_path):
out = tmp_path / "cut.mp4"
main.cut_clip(str(clip), str(out), 1.0, 3.0, 1)
assert out.exists() and out.stat().st_size > 1024
assert _probe_dims(out) == (320, 180)
def test_finalize_passthrough_stream_copies_native_framing(self, clip, tmp_path):
out = tmp_path / "horizontal.mp4"
assert main.finalize_clip_passthrough(str(clip), str(out)) is True
assert out.exists()
assert _probe_dims(out) == _probe_dims(clip)

View file

@ -0,0 +1,115 @@
"""L4 — scene stage.
Covers PySceneDetect on a clip with three hard cuts, the TransNetV2 ->
PySceneDetect fallback, and ``main.detect_scenes`` delegation. No torch / no
TransNetV2 model is loaded: the engine is either selected via env or stubbed.
"""
from types import SimpleNamespace
import pytest
from clipwright.media import scene_detection
pytestmark = [pytest.mark.e2e, pytest.mark.pipeline]
@pytest.fixture(scope="session")
def heavy_stubs():
"""Inject fake ``ultralytics``/``mediapipe`` then import ``main`` lazily."""
import sys
import types
if "ultralytics" not in sys.modules:
ul = types.ModuleType("ultralytics")
class _YOLO:
def __init__(self, *args, **kwargs):
pass
def __call__(self, *args, **kwargs):
return []
ul.YOLO = _YOLO
sys.modules["ultralytics"] = ul
if "mediapipe" not in sys.modules:
mp = types.ModuleType("mediapipe")
solutions = types.ModuleType("mediapipe.solutions")
face_detection = types.ModuleType("mediapipe.solutions.face_detection")
class _FaceDetection:
def __init__(self, *args, **kwargs):
pass
def process(self, *args, **kwargs):
return SimpleNamespace(detections=None)
def close(self):
pass
face_detection.FaceDetection = _FaceDetection
solutions.face_detection = face_detection
mp.solutions = solutions
sys.modules["mediapipe"] = mp
sys.modules["mediapipe.solutions"] = solutions
sys.modules["mediapipe.solutions.face_detection"] = face_detection
import clipwright.pipeline.main as main
return main
def test_pyscenedetect_finds_three_hard_cuts(media_factory, monkeypatch):
monkeypatch.setenv("SCENE_ENGINE", "pyscenedetect")
scenes, fps = scene_detection.detect_scenes(str(media_factory.cuts))
# Four colour segments -> three cuts -> four scenes.
assert len(scenes) == 4
assert float(fps) == pytest.approx(25.0, abs=1.0)
# Scene boundaries are ordered, non-empty and cover the clip.
for (start, end) in scenes:
assert end.frame_num > start.frame_num
assert scenes[0][0].frame_num == 0
assert scenes[-1][1].frame_num == sum(
end.frame_num - start.frame_num for start, end in scenes)
def test_transnetv2_failure_falls_back_to_pyscenedetect(media_factory, monkeypatch, capsys):
monkeypatch.setenv("SCENE_ENGINE", "transnetv2")
def _boom(path):
raise RuntimeError("torch unavailable")
monkeypatch.setattr(scene_detection, "_detect_transnetv2", _boom)
scenes, fps = scene_detection.detect_scenes(str(media_factory.cuts))
assert len(scenes) == 4
assert float(fps) == pytest.approx(25.0, abs=1.0)
assert "falling back to PySceneDetect" in capsys.readouterr().out
def test_transnetv2_success_is_used_when_available(media_factory, monkeypatch):
monkeypatch.setenv("SCENE_ENGINE", "transnetv2")
sentinel = ([("a", "b")], 30.0)
monkeypatch.setattr(scene_detection, "_detect_transnetv2", lambda path: sentinel)
assert scene_detection.detect_scenes(str(media_factory.cuts)) == sentinel
def test_merge_short_scenes_absorbs_short_neighbours():
# fps 10, min_sec 0.5 -> min_frames 5. The 2-frame scene folds into its
# predecessor; the long neighbours stay put.
merged = scene_detection._merge_short_scenes(
[(0, 20), (20, 22), (22, 40)], fps=10.0, min_sec=0.5)
assert merged == [(0, 22), (22, 40)]
def test_main_detect_scenes_delegates(heavy_stubs, monkeypatch):
sentinel = (["scene"], 29.97)
monkeypatch.setattr(scene_detection, "detect_scenes", lambda path: sentinel)
assert heavy_stubs.detect_scenes("/tmp/whatever.mp4") == sentinel

View file

@ -0,0 +1,320 @@
"""L4 — selection stage.
Pure ``clip_selection`` helpers plus ``main.get_viral_clips`` driven by a
stubbed ``main._run_gemini_stage`` (score -> detail -> floor recovery -> empty)
and ``main.speech_is_sparse``. No Gemini call, no network.
"""
import json
from types import SimpleNamespace
import pytest
from clipwright.pipeline import clip_selection as cs
from clipwright.pipeline import gemini_worker
pytestmark = [pytest.mark.e2e, pytest.mark.pipeline]
@pytest.fixture(scope="session")
def heavy_stubs():
"""Inject fake ``ultralytics``/``mediapipe`` then import ``main`` lazily."""
import sys
import types
if "ultralytics" not in sys.modules:
ul = types.ModuleType("ultralytics")
class _YOLO:
def __init__(self, *args, **kwargs):
pass
def __call__(self, *args, **kwargs):
return []
ul.YOLO = _YOLO
sys.modules["ultralytics"] = ul
if "mediapipe" not in sys.modules:
mp = types.ModuleType("mediapipe")
solutions = types.ModuleType("mediapipe.solutions")
face_detection = types.ModuleType("mediapipe.solutions.face_detection")
class _FaceDetection:
def __init__(self, *args, **kwargs):
pass
def process(self, *args, **kwargs):
return SimpleNamespace(detections=None)
def close(self):
pass
face_detection.FaceDetection = _FaceDetection
solutions.face_detection = face_detection
mp.solutions = solutions
sys.modules["mediapipe"] = mp
sys.modules["mediapipe.solutions"] = solutions
sys.modules["mediapipe.solutions.face_detection"] = face_detection
import clipwright.pipeline.main as main
return main
# ---------------------------------------------------------------------------
# Pure helpers
# ---------------------------------------------------------------------------
def test_lookup_model_prices_longest_prefix():
assert cs.lookup_model_prices("gemini-3.1-flash-lite") == (0.25, 1.50)
assert cs.lookup_model_prices("gemini-3.1-flash-lite-002") == (0.25, 1.50)
assert cs.lookup_model_prices("GEMINI-2.5-FLASH") == (0.30, 2.50)
assert cs.lookup_model_prices("unknown-model") is None
assert cs.lookup_model_prices(None) is None
def test_clip_count_targets_floor_and_ceiling():
assert cs.clip_count_targets(1) == (2, 4)
assert cs.clip_count_targets(3) == (3, 6)
assert cs.clip_count_targets(10) == (6, 12)
def test_clip_count_targets_env_override(monkeypatch):
monkeypatch.setenv("CLIP_TARGET_MIN", "5")
monkeypatch.setenv("CLIP_TARGET_MAX", "7")
assert cs.clip_count_targets(3) == (5, 7)
def test_shortlist_target_scales_and_is_bounded():
assert cs.shortlist_target(0) == 3
assert cs.shortlist_target(90) == 3
assert cs.shortlist_target(180) == 4
assert cs.shortlist_target(9000) == 10
def test_score_batches_near_equal_and_remainder():
assert cs.score_batches([], 8) == []
assert cs.score_batches(list(range(8)), 8) == [list(range(8))]
batches = cs.score_batches(list(range(9)), 8)
assert [len(b) for b in batches] == [5, 4]
assert sum(batches, []) == list(range(9))
def test_trim_to_best_keeps_top_scores_in_transcript_order():
shorts = [
{"start": 0, "predicted_score": 10},
{"start": 10, "predicted_score": 90},
{"start": 20, "predicted_score": 80},
{"start": 30, "predicted_score": 70},
]
kept = cs.trim_to_best(shorts, 2)
assert [s["predicted_score"] for s in kept] == [90, 80]
assert [s["start"] for s in kept] == [10, 20]
# Under the cap: unchanged.
assert cs.trim_to_best(shorts[:2], 5) == shorts[:2]
def test_clip_duration_bounds_defaults_and_overrides(monkeypatch):
for var in ("CLIP_MIN_SECONDS", "CLIP_MAX_SECONDS"):
monkeypatch.delenv(var, raising=False)
assert cs.clip_duration_bounds() == (15.0, 60.0)
monkeypatch.setenv("CLIP_MIN_SECONDS", "5")
monkeypatch.setenv("CLIP_MAX_SECONDS", "10")
assert cs.clip_duration_bounds() == (5.0, 10.0)
# Degenerate band widens to the minimum 5s spread.
monkeypatch.setenv("CLIP_MIN_SECONDS", "100")
monkeypatch.setenv("CLIP_MAX_SECONDS", "10")
assert cs.clip_duration_bounds() == (100.0, 105.0)
def test_build_transcript_windows_aligns_to_segments():
transcript = {
"text": "a b c d",
"segments": [
{"start": 0, "end": 30, "text": "a"},
{"start": 30, "end": 60, "text": "b"},
{"start": 60, "end": 90, "text": "c"},
{"start": 90, "end": 120, "text": "d"},
],
}
windows = cs.build_transcript_windows(transcript, 120, window_seconds=90,
overlap_seconds=30)
assert [w["id"] for w in windows] == ["window_001", "window_002"]
assert windows[0]["start"] == 0 and windows[0]["end"] == 90
assert windows[1]["start"] == 60 and windows[1]["end"] == 120
def test_build_transcript_windows_empty_falls_back_to_full_video():
windows = cs.build_transcript_windows({"text": "hi", "segments": []}, 42)
assert len(windows) == 1
assert windows[0]["end"] == 42.0
def test_dedupe_overlapping_keeps_higher_score():
a = {"start": 0, "end": 30, "predicted_score": 50}
b = {"start": 10, "end": 40, "predicted_score": 80}
assert cs.dedupe_overlapping([a, b]) == [b]
# Non-overlapping clips both survive, in transcript order.
c = {"start": 100, "end": 130, "predicted_score": 10}
assert cs.dedupe_overlapping([a, c]) == [a, c]
def test_snap_clip_to_words_no_words_returns_original():
assert cs.snap_clip_to_words(4.8, 21.2, [], 60) == (4.8, 21.2)
def test_snap_clip_to_words_snaps_and_repairs_duration():
words = [{"s": 0, "e": 1}, {"s": 5, "e": 6},
{"s": 20, "e": 21}, {"s": 40, "e": 41}]
# Snap start to 5 (lead 0.35) and end to 21 (trail 0.45).
assert cs.snap_clip_to_words(4.8, 21.2, words, 60) == (4.65, 21.45)
# Too short after snapping -> extended to the next word end + 0.2.
assert cs.snap_clip_to_words(0.0, 5.0, words, 60) == (0.0, 21.2)
# ---------------------------------------------------------------------------
# speech_is_sparse — pure
# ---------------------------------------------------------------------------
def test_speech_is_sparse_thin_transcript(heavy_stubs):
thin = {"segments": [{"text": "uh uh"}]}
assert heavy_stubs.speech_is_sparse(thin, 60) is True
def test_speech_is_sparse_dense_transcript(heavy_stubs):
dense = {"segments": [{"text": " ".join(["word"] * 200)}]}
assert heavy_stubs.speech_is_sparse(dense, 60) is False
def test_speech_is_sparse_none_transcript(heavy_stubs):
assert heavy_stubs.speech_is_sparse(None, 60) is True
# ---------------------------------------------------------------------------
# get_viral_clips — stub _run_gemini_stage
# ---------------------------------------------------------------------------
def _dense_transcript():
return {
"text": "alpha beta gamma delta",
"language": "en",
"segments": [
{"start": 0, "end": 30, "text": "alpha",
"words": [{"word": " alpha", "start": 0.0, "end": 1.0}]},
{"start": 30, "end": 60, "text": "beta",
"words": [{"word": " beta", "start": 30.0, "end": 31.0}]},
{"start": 60, "end": 90, "text": "gamma",
"words": [{"word": " gamma", "start": 60.0, "end": 61.0}]},
{"start": 90, "end": 120, "text": "delta",
"words": [{"word": " delta", "start": 90.0, "end": 91.0}]},
],
}
def _short(start, end, score, window):
return {
"start": start, "end": end, "source_window_id": window,
"predicted_score": score,
"video_description_for_tiktok": "t #x",
"video_description_for_instagram": "i #x",
"video_title_for_youtube_short": "title",
"viral_hook_text": "hook",
"why": "why",
}
def _prompt_windows(prompt, marker):
tail = prompt.split(marker, 1)[1]
tail = tail.split("\n\nReturn only", 1)[0]
return json.loads(tail.strip())
def _prepare_gemini(monkeypatch, main):
monkeypatch.setenv("GEMINI_API_KEY", "test")
monkeypatch.setattr(main.llm_backend, "active", lambda: False)
monkeypatch.setattr(main.genai, "Client", lambda **kwargs: object())
def _stub_gemini(monkeypatch, main, detail_plan, score_plan=None):
calls = []
def fake(client, model_name, prompt, schema):
calls.append(schema)
if schema is gemini_worker.ScoreResponse:
windows = _prompt_windows(prompt, "WINDOWS_JSON:")
return {"windows": score_plan(windows) if score_plan
else [{"id": w["id"], "start": w["start"], "end": w["end"],
"score": 85, "reason": "r"} for w in windows]}, None
if schema is gemini_worker.DetailResponse:
windows = _prompt_windows(prompt, "CANDIDATE_WINDOWS_JSON:")
return {"shorts": detail_plan(windows)}, None
raise AssertionError(f"unexpected schema {schema}")
monkeypatch.setattr(main, "_run_gemini_stage", fake)
return calls
def test_get_viral_clips_score_then_detail(heavy_stubs, monkeypatch):
main = heavy_stubs
_prepare_gemini(monkeypatch, main)
def plan(windows):
# One clip per shortlisted window plus one extra non-overlapping clip.
return [_short(0, 30, 90, "window_001"),
_short(60, 90, 80, "window_002"),
_short(90, 120, 70, "window_002")]
_stub_gemini(monkeypatch, main, plan)
result = main.get_viral_clips(_dense_transcript(), 120)
assert result is not None
assert len(result["shorts"]) == 3
assert all("proposed" in s for s in result["shorts"])
def test_get_viral_clips_floor_recovery(heavy_stubs, monkeypatch, capsys):
main = heavy_stubs
_prepare_gemini(monkeypatch, main)
def plan(windows):
if len(windows) == 2: # first detail call over the full shortlist
return [_short(0, 30, 90, "window_001")]
return [_short(60, 90, 80, "window_002"),
_short(90, 120, 70, "window_002")]
_stub_gemini(monkeypatch, main, plan)
result = main.get_viral_clips(_dense_transcript(), 120)
assert result is not None
assert len(result["shorts"]) == 3
assert "Recovered 2 clip(s)" in capsys.readouterr().out
def test_get_viral_clips_empty_returns_none(heavy_stubs, monkeypatch):
main = heavy_stubs
_prepare_gemini(monkeypatch, main)
_stub_gemini(monkeypatch, main, lambda windows: [])
assert main.get_viral_clips(_dense_transcript(), 120) is None
def test_get_viral_clips_score_empty_shortlists_all_windows(heavy_stubs, monkeypatch):
main = heavy_stubs
_prepare_gemini(monkeypatch, main)
# Score returns nothing usable -> shortlist falls back to the windows themselves.
_stub_gemini(monkeypatch, main,
lambda windows: [_short(0, 30, 90, "window_001"),
_short(60, 90, 80, "window_002"),
_short(90, 120, 70, "window_002")],
score_plan=lambda windows: [])
result = main.get_viral_clips(_dense_transcript(), 120)
assert result is not None
assert len(result["shorts"]) == 3

View file

@ -0,0 +1,185 @@
"""L5 Pipeline media — SUBTITLE stage.
Pure SRT/ASS/filter generation, a real ffmpeg burn that must stay playable, and
``main.auto_caption_clip``'s fail-open contract (AUTO_CAPTIONS=0, no words in
range). ``main`` needs the ML stubs before import; see test_render_stage.py.
"""
import os
import shutil
import subprocess
import sys
import types
from types import SimpleNamespace
import pytest
from clipwright.media import subtitles
pytestmark = [pytest.mark.e2e, pytest.mark.pipeline]
def _install_ml_stubs():
if "ultralytics" in sys.modules and "mediapipe" in sys.modules:
return
class _FakeYOLO:
def __init__(self, *a, **k):
pass
def __call__(self, *a, **k):
return []
def predict(self, *a, **k):
return []
def track(self, *a, **k):
return []
class _FakeFaceDetection:
def __init__(self, *a, **k):
pass
def process(self, *a, **k):
return SimpleNamespace(detections=None)
def close(self):
pass
ul = types.ModuleType("ultralytics")
ul.YOLO = _FakeYOLO
sys.modules["ultralytics"] = ul
mp = types.ModuleType("mediapipe")
solutions = types.ModuleType("mediapipe.solutions")
fd = types.ModuleType("mediapipe.solutions.face_detection")
fd.FaceDetection = _FakeFaceDetection
solutions.face_detection = fd
mp.solutions = solutions
sys.modules["mediapipe"] = mp
sys.modules["mediapipe.solutions"] = solutions
sys.modules["mediapipe.solutions.face_detection"] = fd
_install_ml_stubs()
from clipwright.pipeline import main # noqa: E402
TRANSCRIPT = {
"language": "en",
"segments": [{
"start": 0.0, "end": 3.0,
"text": " This is a canned transcript",
"words": [
{"word": " This", "start": 0.0, "end": 0.4},
{"word": " is", "start": 0.4, "end": 0.7},
{"word": " a", "start": 0.7, "end": 0.9},
{"word": " canned", "start": 0.9, "end": 1.4},
{"word": " transcript", "start": 1.4, "end": 2.2},
],
}],
}
def _probe_dims(path):
out = subprocess.check_output(
["ffprobe", "-v", "error", "-select_streams", "v:0",
"-show_entries", "stream=width,height", "-of", "csv=p=0:s=x", str(path)],
text=True).strip()
w, h = out.split("x")
return int(w), int(h)
class TestGenerateSrt:
def test_words_are_grouped_into_short_blocks(self, tmp_path):
out = tmp_path / "subs.srt"
assert subtitles.generate_srt(TRANSCRIPT, 0.0, 3.0, str(out),
max_chars=20, max_duration=2.0) is True
text = out.read_text(encoding="utf-8-sig")
assert "This is a canned" in text
assert "transcript" in text
assert " --> " in text
def test_no_words_in_range_writes_nothing(self, tmp_path):
out = tmp_path / "empty.srt"
assert subtitles.generate_srt(TRANSCRIPT, 100.0, 110.0, str(out)) is False
assert not out.exists()
class TestGenerateAss:
def test_ass_carries_a_style_and_word_events(self, tmp_path):
out = tmp_path / "subs.ass"
assert subtitles.generate_ass(TRANSCRIPT, 0.0, 3.0, str(out),
max_chars=8, uppercase=True) is True
text = out.read_text(encoding="utf-8-sig")
assert "[V4+ Styles]" in text and "[Events]" in text
assert "Dialogue: 0," in text
def test_split_ranges_anchor_events_on_the_seam(self, tmp_path):
out = tmp_path / "seam.ass"
# The whole clip is a SPLIT stretch: every event gets the mid-frame \an5.
assert subtitles.generate_ass(TRANSCRIPT, 0.0, 3.0, str(out),
split_ranges=[(0.0, 3.0)]) is True
events = [l for l in out.read_text(encoding="utf-8-sig").splitlines()
if l.startswith("Dialogue:")]
assert events and all("{\\an5}" in e for e in events)
def test_no_words_returns_false(self, tmp_path):
assert subtitles.generate_ass(TRANSCRIPT, 50.0, 60.0,
str(tmp_path / "x.ass")) is False
class TestSubtitlesFilter:
def test_srt_uses_subtitles_filter_with_style(self):
vf = subtitles.subtitles_filter("/tmp/a.srt", alignment="bottom", fontsize=44,
font_name="Anton")
assert vf.startswith("subtitles=filename=")
assert "force_style=" in vf and "Fontname=Anton" in vf
def test_ass_uses_the_ass_filter_and_its_own_styles(self):
vf = subtitles.subtitles_filter("/tmp/a.ass")
assert vf.startswith("ass=filename=")
assert "force_style" not in vf
class TestBurnSubtitles:
def test_real_burn_produces_a_playable_file(self, tmp_path, media_factory):
clip = tmp_path / "clip.mp4"
shutil.copyfile(media_factory.six, clip)
srt = tmp_path / "subs.srt"
assert subtitles.generate_srt(TRANSCRIPT, 0.0, 3.0, str(srt))
out = tmp_path / "burned.mp4"
assert subtitles.burn_subtitles(str(clip), str(srt), str(out),
font_name="Anton") is True
assert out.exists() and out.stat().st_size > 0
assert _probe_dims(out) == (320, 180)
class TestAutoCaptionClip:
def _clip(self, tmp_path, media_factory):
clip = tmp_path / "clip.mp4"
shutil.copyfile(media_factory.six, clip)
return clip
def test_disabled_by_env_returns_none(self, tmp_path, media_factory, monkeypatch):
monkeypatch.setenv("AUTO_CAPTIONS", "0")
clip = self._clip(tmp_path, media_factory)
assert main.auto_caption_clip(str(clip), TRANSCRIPT, 0.0, 3.0) is None
def test_no_words_in_range_returns_none(self, tmp_path, media_factory):
clip = self._clip(tmp_path, media_factory)
assert main.auto_caption_clip(str(clip), TRANSCRIPT, 100.0, 110.0) is None
def test_silent_transcript_returns_none(self, tmp_path, media_factory):
clip = self._clip(tmp_path, media_factory)
assert main.auto_caption_clip(str(clip), {"segments": []}, 0.0, 3.0) is None
def test_real_caption_writes_a_subtitled_derivative(self, tmp_path, media_factory):
clip = self._clip(tmp_path, media_factory)
out = main.auto_caption_clip(str(clip), TRANSCRIPT, 0.0, 3.0)
assert out is not None
name = os.path.basename(out)
assert name.startswith("subtitled_") and name.endswith("_clip.mp4")
assert _probe_dims(out) == (320, 180)
# The clean original stays untouched next to the derivative.
assert clip.exists()

View file

@ -0,0 +1,190 @@
"""L5 Pipeline media — THUMBNAIL stage.
``extract_face_frames`` runs the real cv2/ffmpeg path and must degrade to ``[]``
when no face is found. The pure ranking/spread/text/concept helpers are checked
directly, and ``generate_thumbnail`` runs end to end against a stubbed Gemini
client that returns a scripted concept list and a PIL image — the saved artifact
must be a 1280x720 JPEG under YouTube's 2 MB ceiling.
"""
import base64
import io
import os
import sys
import types
from types import SimpleNamespace
import pytest
from PIL import Image
from clipwright.media import thumbnail
pytestmark = [pytest.mark.e2e, pytest.mark.pipeline]
def _install_ml_stubs():
if "ultralytics" in sys.modules and "mediapipe" in sys.modules:
return
class _FakeYOLO:
def __init__(self, *a, **k):
pass
def __call__(self, *a, **k):
return []
def predict(self, *a, **k):
return []
def track(self, *a, **k):
return []
class _FakeFaceDetection:
def __init__(self, *a, **k):
pass
def process(self, *a, **k):
return SimpleNamespace(detections=None)
def close(self):
pass
ul = types.ModuleType("ultralytics")
ul.YOLO = _FakeYOLO
sys.modules["ultralytics"] = ul
mp = types.ModuleType("mediapipe")
solutions = types.ModuleType("mediapipe.solutions")
fd = types.ModuleType("mediapipe.solutions.face_detection")
fd.FaceDetection = _FakeFaceDetection
solutions.face_detection = fd
mp.solutions = solutions
sys.modules["mediapipe"] = mp
sys.modules["mediapipe.solutions"] = solutions
sys.modules["mediapipe.solutions.face_detection"] = fd
_install_ml_stubs()
# extract_face_frames imports main lazily; import it here so the stubs are in
# place even when this file runs on its own.
from clipwright.pipeline import main # noqa: E402,F401
# --- stubbed Gemini client --------------------------------------------------
_CONCEPTS_JSON = (
'{"concepts": ['
'{"text": "BIG WIN", "text_position": "left", "text_color": "yellow",'
' "scene": "a bright desk with a laptop", "why": "bold"},'
'{"text": "HOW TO", "text_position": "right", "text_color": "white",'
' "scene": "a person seen from behind at a screen", "why": "curious"}'
']}'
)
def _png_bytes(width=2048, height=1152):
img = Image.effect_noise((width, height), 60).convert("RGB")
buf = io.BytesIO()
img.save(buf, "PNG")
return buf.getvalue()
class _FakeModels:
def generate_content(self, model=None, contents=None, config=None):
return SimpleNamespace(text=_CONCEPTS_JSON)
class _FakeInteractions:
def create(self, model=None, input=None, response_format=None):
data = base64.b64encode(_png_bytes()).decode("ascii")
return SimpleNamespace(output_text=None,
output_image=SimpleNamespace(data=data),
status=None, errors=None)
class _FakeClient:
def __init__(self, api_key=None, **kwargs):
self.models = _FakeModels()
self.interactions = _FakeInteractions()
# --- helpers ----------------------------------------------------------------
class TestExtractFaceFrames:
def test_no_faces_returns_empty_list(self, tmp_path, media_factory, monkeypatch):
monkeypatch.chdir(tmp_path)
assert thumbnail.extract_face_frames(str(media_factory.six), "sess") == []
class TestRankingAndSpread:
def test_rank_frame_rejects_tiny_faces(self):
assert thumbnail.rank_frame(0, 0.0, None, [0, 0, 50, 50],
(1920, 1080), 100) is None
big = thumbnail.rank_frame(0, 0.0, None, [0, 0, 400, 400],
(1920, 1080), 100)
assert big and big["score"] > 0
def test_pick_spread_keeps_picks_apart_in_time(self):
scored = [
{"idx": 500, "score": 1.0}, {"idx": 505, "score": 0.99},
{"idx": 510, "score": 0.98}, {"idx": 100, "score": 0.5},
{"idx": 900, "score": 0.4},
]
picked = thumbnail.pick_spread(scored, 3, 1000)
assert [p["idx"] for p in picked] == [100, 500, 900]
class TestTextAndFinalize:
def test_burn_text_draws_only_on_its_side(self):
img = Image.new("RGB", (1280, 720), (20, 20, 20))
out = thumbnail.burn_thumbnail_text(img, "0 A 10K", "left", "yellow")
px = out.convert("RGB")
assert max(px.crop((0, 0, 640, 720)).getextrema()[0]) > 200
assert max(px.crop((700, 0, 1280, 720)).getextrema()[0]) < 60
def test_finalize_cover_crops_to_1280x720_under_2mb(self, tmp_path):
noisy = Image.effect_noise((2048, 1536), 80).convert("RGB")
out = tmp_path / "t.jpg"
thumbnail.finalize_thumbnail(noisy, str(out))
with Image.open(out) as saved:
assert saved.size == (1280, 720)
assert out.stat().st_size <= thumbnail.THUMB_MAX_BYTES
class TestConcepts:
def test_normalise_clamps_and_pads(self):
raw = [
{"text": "esto funciona", "text_position": "diagonal",
"text_color": "red", "scene": "a desk"},
{"scene": ""},
"garbage",
]
out = thumbnail.normalise_concepts(raw, 3, "My title",
thumbnail_text_hint="hint")
assert len(out) == 3
assert out[0]["text"] == "ESTO FUNCIONA"
assert out[0]["text_position"] == "left"
assert out[1]["why"] == "fallback"
def test_plan_thumbnail_concepts_parses_the_client_json(self):
concepts = thumbnail.plan_thumbnail_concepts(_FakeClient(), "A title", 2)
assert len(concepts) == 2
assert concepts[0]["text"] == "BIG WIN"
assert concepts[0]["text_color"] == "yellow"
class TestGenerateThumbnail:
def test_end_to_end_against_a_stubbed_image_client(self, tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
monkeypatch.setattr(thumbnail, "genai",
SimpleNamespace(Client=lambda api_key=None, **kw: _FakeClient()))
results = thumbnail.generate_thumbnail("stub-key", "A title", "sess", count=2)
assert len(results) == 2
for r in results:
path = os.path.join("output", "thumbnails", "sess",
os.path.basename(r["url"]))
assert os.path.exists(path)
with Image.open(path) as img:
assert img.size == (1280, 720)
assert os.path.getsize(path) <= thumbnail.THUMB_MAX_BYTES
assert r["url"].startswith("/thumbnails/sess/")

View file

@ -0,0 +1,200 @@
"""L4 — transcribe stage.
Covers the audio-stream probe (real ffmpeg), the backend dispatcher with a
stubbed ASR backend, ``main.transcribe_video`` wiring, and the transcript
checkpoint round-trip. No ASR model is ever loaded.
"""
import json
from types import SimpleNamespace
import pytest
from clipwright.pipeline import transcribe_backends as tb
pytestmark = [pytest.mark.e2e, pytest.mark.pipeline]
@pytest.fixture(scope="session")
def heavy_stubs():
"""Inject fake ``ultralytics``/``mediapipe`` then import ``main`` lazily."""
import sys
import types
if "ultralytics" not in sys.modules:
ul = types.ModuleType("ultralytics")
class _YOLO:
def __init__(self, *args, **kwargs):
pass
def __call__(self, *args, **kwargs):
return []
ul.YOLO = _YOLO
sys.modules["ultralytics"] = ul
if "mediapipe" not in sys.modules:
mp = types.ModuleType("mediapipe")
solutions = types.ModuleType("mediapipe.solutions")
face_detection = types.ModuleType("mediapipe.solutions.face_detection")
class _FaceDetection:
def __init__(self, *args, **kwargs):
pass
def process(self, *args, **kwargs):
return SimpleNamespace(detections=None)
def close(self):
pass
face_detection.FaceDetection = _FaceDetection
solutions.face_detection = face_detection
mp.solutions = solutions
sys.modules["mediapipe"] = mp
sys.modules["mediapipe.solutions"] = solutions
sys.modules["mediapipe.solutions.face_detection"] = face_detection
import clipwright.pipeline.main as main
return main
CANNED = {
"text": "hello world this is a canned transcript for tests",
"language": "en",
"segments": [
{"start": 0.0, "end": 2.0, "text": " hello world",
"words": [{"word": " hello", "start": 0.0, "end": 1.0},
{"word": " world", "start": 1.0, "end": 2.0}]},
{"start": 2.0, "end": 4.0, "text": " this is a canned transcript for tests",
"words": [{"word": " this", "start": 2.0, "end": 2.5}]},
],
}
def _clone():
return json.loads(json.dumps(CANNED))
# ---------------------------------------------------------------------------
# _has_audio_stream / NoAudioError — real ffmpeg
# ---------------------------------------------------------------------------
def test_has_audio_stream_true(media_factory):
assert tb._has_audio_stream(str(media_factory.six)) is True
def test_has_audio_stream_false(media_factory):
assert tb._has_audio_stream(str(media_factory.silent)) is False
def test_transcribe_media_raises_no_audio(media_factory):
with pytest.raises(tb.NoAudioError) as excinfo:
tb.transcribe_media(str(media_factory.silent))
assert "no audio track" in str(excinfo.value)
# ---------------------------------------------------------------------------
# transcribe_media dispatcher — stub the backends
# ---------------------------------------------------------------------------
def test_transcribe_media_dispatches_to_whisper(monkeypatch, media_factory):
monkeypatch.setenv("TRANSCRIBE_BACKEND", "whisper")
monkeypatch.setattr(tb, "_transcribe_with_whisper", lambda path: _clone())
assert tb.transcribe_media(str(media_factory.six)) == CANNED
def test_transcribe_media_parakeet_falls_back(monkeypatch, media_factory, capsys):
monkeypatch.setenv("TRANSCRIBE_BACKEND", "parakeet")
def _boom(path):
raise RuntimeError("onnxruntime not available")
monkeypatch.setattr(tb, "_transcribe_with_parakeet", _boom)
monkeypatch.setattr(tb, "_transcribe_with_whisper", lambda path: _clone())
assert tb.transcribe_media(str(media_factory.six)) == CANNED
assert "falling back to whisper" in capsys.readouterr().out
def test_transcribe_media_parakeet_accepted(monkeypatch, media_factory, capsys):
monkeypatch.setenv("TRANSCRIBE_BACKEND", "parakeet")
monkeypatch.setattr(tb, "_transcribe_with_parakeet", lambda path: _clone())
def _unexpected(path):
raise AssertionError("whisper should not run when parakeet succeeds")
monkeypatch.setattr(tb, "_transcribe_with_whisper", _unexpected)
assert tb.transcribe_media(str(media_factory.six)) == CANNED
assert "parakeet ok" in capsys.readouterr().out
# ---------------------------------------------------------------------------
# main.transcribe_video — wiring
# ---------------------------------------------------------------------------
def test_transcribe_video_uses_module_dispatcher(heavy_stubs, monkeypatch, media_factory):
released = []
monkeypatch.setattr(tb, "ASR_HOST_SLOTS", 0) # no flock, no waiting
monkeypatch.setattr(tb, "transcribe_media", lambda path: _clone())
monkeypatch.setattr(tb, "release_models", lambda: released.append(True))
result = heavy_stubs.transcribe_video(str(media_factory.six))
assert result == CANNED
assert released == [True]
def test_host_asr_slot_zero_is_noop(monkeypatch, tmp_path):
slot = tb.host_asr_slot(slots=0, lock_dir=str(tmp_path))
with slot as entered:
assert entered is slot
assert not list(tmp_path.glob(".asr-gpu-*.lock"))
# ---------------------------------------------------------------------------
# Transcript checkpoint round-trip
# ---------------------------------------------------------------------------
def test_checkpoint_roundtrip(heavy_stubs, tmp_path):
out = tmp_path
heavy_stubs.save_transcript_checkpoint(str(out), CANNED, "/jobs/a.mp4", 12.34)
loaded = heavy_stubs.load_transcript_checkpoint(str(out), "/jobs/a.mp4", 12.34)
assert loaded == CANNED
# A different source name is ignored.
assert heavy_stubs.load_transcript_checkpoint(str(out), "/jobs/b.mp4", 12.34) is None
# A different duration is ignored.
assert heavy_stubs.load_transcript_checkpoint(str(out), "/jobs/a.mp4", 20.0) is None
heavy_stubs.clear_transcript_checkpoint(str(out))
assert not (out / heavy_stubs.TRANSCRIPT_CHECKPOINT).exists()
assert heavy_stubs.load_transcript_checkpoint(str(out), "/jobs/a.mp4", 12.34) is None
def test_checkpoint_same_basename_different_dir_is_accepted(heavy_stubs, tmp_path):
out = tmp_path
heavy_stubs.save_transcript_checkpoint(str(out), CANNED, "/first/a.mp4", 6.0)
# The key is basename+duration, so a re-download to another directory matches.
assert heavy_stubs.load_transcript_checkpoint(str(out), "/second/a.mp4", 6.0) == CANNED
def test_checkpoint_malformed_is_ignored(heavy_stubs, tmp_path):
(tmp_path / heavy_stubs.TRANSCRIPT_CHECKPOINT).write_text("{not json")
assert heavy_stubs.load_transcript_checkpoint(str(tmp_path), "/a.mp4", 6.0) is None
def test_checkpoint_without_segments_is_ignored(heavy_stubs, tmp_path):
payload = {"source": {"name": "a.mp4", "duration": 6.0}, "transcript": {}}
(tmp_path / heavy_stubs.TRANSCRIPT_CHECKPOINT).write_text(json.dumps(payload))
assert heavy_stubs.load_transcript_checkpoint(str(tmp_path), "/a.mp4", 6.0) is None
def test_clear_checkpoint_missing_is_ok(heavy_stubs, tmp_path):
heavy_stubs.clear_transcript_checkpoint(str(tmp_path)) # must not raise

View file

@ -156,7 +156,7 @@ def test_resumed_job_keeps_its_safety_cap(dirs, monkeypatch):
d.mkdir()
(d / app_module._RESUME_FILE).write_text(json.dumps({
"cmd": ["python", "main.py"], "priority": 2, "user_id": None,
"reservation_id": f"res-{name}", "watermark": False, "attempts": 0,
"reservation_id": f"res-{name}", "attempts": 0,
"source_cap_minutes": cap,
}))
monkeypatch.setenv("SOURCE_CAP_MINUTES", "3") # a stale value must not leak in

View file

@ -74,9 +74,6 @@ class TestMainAnnouncesTheDeliveredFile:
"""
main_src = MAIN_PY.read_text(encoding="utf-8")
caption_at = main_src.index("captioned = auto_caption_clip(")
# The free plan's served file is a wm_ copy of the captioned final
# (mark_delivery), so the marker must also come after that step.
served_at = main_src.index("served = captioned or deliver_path")
mark_at = main_src.index("served = mark_delivery(served)")
marker_at = main_src.index('print(f"CLIP_READY {i} {os.path.basename(served)}")')
assert caption_at < served_at < mark_at < marker_at
assert caption_at < served_at < marker_at

View file

@ -33,7 +33,7 @@ def _manifest(out, job_id, **extra):
d = out / job_id
d.mkdir(exist_ok=True)
m = {"cmd": ["python", "main.py"], "priority": 2, "user_id": None,
"reservation_id": f"res-{job_id}", "watermark": False, "attempts": 0}
"reservation_id": f"res-{job_id}", "attempts": 0}
m.update(extra)
(d / app_module._RESUME_FILE).write_text(json.dumps(m))
return d

View file

@ -21,8 +21,7 @@ class TestTheGuardIsWiredIn:
app = pytest.importorskip("clipwright.api.app")
mount = next(r for r in app.app.routes
if getattr(r, "name", None) == "videos")
# app._media_guard wraps the allowlist (and adds the free-plan rule
# that refuses a marked job's clean twins, tests/test_watermark_delivery).
# app._media_guard wraps the allowlist (media_auth.is_servable).
assert mount.app.guard is app._media_guard, \
"/videos is serving the working directory with no allowlist"
assert not app._media_guard("job/.resume.json")

View file

@ -28,7 +28,7 @@ LEGACY_MODULES = frozenset({
"restoring_static", "scene_detection", "screencast_layout",
"security_utils", "split_layout", "subtitles", "thumbnail",
"transcribe_backends", "verify_aesthetic", "verify_custom_hook",
"verify_hooks", "watermarked", "yt_clients",
"verify_hooks", "yt_clients",
})

View file

@ -266,7 +266,7 @@ class TestPerformRecut:
assert os.path.exists(tmp_path / clean)
assert os.path.exists(tmp_path / served)
def test_source_path_reframes_and_watermarks(self, tmp_path):
def test_source_path_reframes(self, tmp_path):
events = []
def fake_renderer(work, out, output_format):
@ -278,10 +278,9 @@ class TestPerformRecut:
served, clean = recut.perform_recut(
input_path="source.mp4", segments=[_seg(5, 15)],
output_dir=str(tmp_path), clean_name="t_clip_1.mp4",
reframe=True, output_format="vertical", watermark=True,
runner=self._touching_runner, renderer=fake_renderer,
watermarker=lambda path: events.append(("watermark",)))
assert events == [("reframe", "vertical"), ("watermark",)]
reframe=True, output_format="vertical",
runner=self._touching_runner, renderer=fake_renderer)
assert events == [("reframe", "vertical")]
assert served == clean
def test_renderer_failure_raises_and_cleans_up(self, tmp_path):

View file

@ -62,7 +62,7 @@ def job(tmp_path, monkeypatch):
app_module.jobs[JOB_ID] = {
"status": "completed", "logs": [],
"result": {"clips": [dict(clip)], "cost_analysis": {}},
"user_id": None, "watermark": False,
"user_id": None,
}
try:
yield {"dir": job_dir, "meta_path": job_dir / "mytitle_metadata.json"}

View file

@ -77,7 +77,6 @@ def job(tmp_path, monkeypatch):
"logs": [],
"result": {"clips": [dict(clip)], "cost_analysis": {}},
"user_id": None,
"watermark": False,
}
try:
yield {"dir": job_dir, "meta_path": job_dir / "mytitle_metadata.json"}
@ -244,9 +243,6 @@ class TestRerenderPaths:
assert call["input_path"].endswith("src.mp4")
assert call["reframe"] is True
assert call["output_format"] == "auto"
# The free-plan mark is applied at delivery (app._deliver), never
# inside the recut, so the served twins stay clean for an upgrade.
assert not call.get("watermark")
# Source-absolute times, not rebased.
assert call["segments"] == [{"start": 45.0, "end": 55.0}]

View file

@ -66,7 +66,6 @@ def job(tmp_path, monkeypatch):
"video_url": "/videos/x/clip_1.mp4",
}]},
"user_id": None,
"watermark": False,
}
try:
yield job_dir

View file

@ -1,138 +0,0 @@
"""The watermark is a served COPY, never the file itself.
Until 30-sep-2026 the mark was burned into the canonical reframe, so every
derivative (hook, captions, recut) inherited it and nothing short of running
the whole job again could remove it.
Now every file the pipeline and the editor write is clean, and the served file
on a marked job is a ``wm_`` twin of the final one (``main.mark_delivery``).
"""
import os
import pytest
from clipwright.media import watermarked
class TestNames:
def test_marked_and_clean_are_inverses(self):
assert watermarked.marked_name("a_clip_1.mp4") == "wm_a_clip_1.mp4"
assert watermarked.marked_name("wm_a_clip_1.mp4") == "wm_a_clip_1.mp4"
assert watermarked.clean_name("wm_subtitled_1_hooked_2_a_clip_1.mp4") == \
"subtitled_1_hooked_2_a_clip_1.mp4"
assert watermarked.clean_name("a_clip_1.mp4") == "a_clip_1.mp4"
assert watermarked.is_marked("wm_x.mp4") and not watermarked.is_marked("x.mp4")
def test_clean_deliverables_are_clips_and_their_derivatives(self):
for name in ("t_clip_1.mp4", "subtitled_1_t_clip_1.mp4", "hooked_1_t_clip_2.mp4",
"recut_1_ab_t_clip_1.mp4", "edited_t_clip_1.mp4",
"translated_es_t_clip_1.mp4"):
assert watermarked.is_clean_deliverable(name), name
# The marked copy itself, the editor's scratch files, and sidecars are
# not clean deliverables: they stay servable on a marked job.
for name in ("wm_t_clip_1.mp4", "temp_preview_0.mp4", "temp_scene_ab_001.jpg",
"subs_0_1.ass", "t_clip_1.layout.json"):
assert not watermarked.is_clean_deliverable(name), name
def test_marker_round_trip(self, tmp_path):
d = str(tmp_path)
assert not watermarked.job_is_marked(d)
watermarked.mark_job(d)
assert watermarked.job_is_marked(d)
class TestMarkDelivery:
"""The pipeline's last step on a marked job: a wm_ copy next to the clean final."""
def test_writes_the_copy_and_leaves_the_final_alone(self, tmp_path):
main = pytest.importorskip("clipwright.pipeline.main")
final = tmp_path / "subtitled_1_t_clip_1.mp4"
final.write_bytes(b"clean")
calls = []
def marker(src, out):
calls.append((os.path.basename(src), os.path.basename(out)))
with open(out, "wb") as f:
f.write(b"marked")
return True
served = main.mark_delivery(str(final), marker=marker)
assert os.path.basename(served) == "wm_subtitled_1_t_clip_1.mp4"
assert calls == [("subtitled_1_t_clip_1.mp4", "wm_subtitled_1_t_clip_1.mp4")]
assert final.read_bytes() == b"clean"
def test_reuses_an_existing_copy(self, tmp_path):
main = pytest.importorskip("clipwright.pipeline.main")
(tmp_path / "t_clip_1.mp4").write_bytes(b"clean")
(tmp_path / "wm_t_clip_1.mp4").write_bytes(b"marked")
served = main.mark_delivery(str(tmp_path / "t_clip_1.mp4"),
marker=lambda *_: pytest.fail("re-encoded"))
assert os.path.basename(served) == "wm_t_clip_1.mp4"
def test_fails_open_under_the_marked_name(self, tmp_path):
"""A failed mark still serves the clip, and still under the wm_ name:
the /videos guard refuses the clean deliverables of a marked job, so a
clean name here would be a clip the user cannot play."""
main = pytest.importorskip("clipwright.pipeline.main")
(tmp_path / "t_clip_1.mp4").write_bytes(b"clean")
served = main.mark_delivery(str(tmp_path / "t_clip_1.mp4"),
marker=lambda *_: False)
assert os.path.basename(served) == "wm_t_clip_1.mp4"
assert (tmp_path / "wm_t_clip_1.mp4").read_bytes() == b"clean"
class TestWalkBacks:
"""The mark is the outermost layer: every editor derivation strips it first."""
def test_strip_captions_walks_through_the_mark(self, tmp_path):
app = pytest.importorskip("clipwright.api.app")
d = str(tmp_path)
for name in ("t_clip_1.mp4", "hooked_2_t_clip_1.mp4",
"subtitled_3_hooked_2_t_clip_1.mp4",
"wm_subtitled_3_hooked_2_t_clip_1.mp4"):
(tmp_path / name).write_bytes(b"x")
assert app._strip_burned_captions(d, "wm_subtitled_3_hooked_2_t_clip_1.mp4") == \
"hooked_2_t_clip_1.mp4"
assert app._strip_burned_hook(d, "hooked_2_t_clip_1.mp4") == "t_clip_1.mp4"
# The mark is a copy of a file that is on disk: it walks back the same.
assert app._strip_burned_hook(d, "wm_hooked_2_t_clip_1.mp4") == "t_clip_1.mp4"
def test_strip_keeps_the_mark_when_the_twin_is_gone(self, tmp_path):
app = pytest.importorskip("clipwright.api.app")
(tmp_path / "wm_t_clip_1.mp4").write_bytes(b"x")
assert app._strip_burned_captions(str(tmp_path), "wm_t_clip_1.mp4") == "wm_t_clip_1.mp4"
def test_canonical_clip_file_prefers_the_marked_copy(self, tmp_path):
app = pytest.importorskip("clipwright.api.app")
import time
(tmp_path / "t_clip_1.mp4").write_bytes(b"x")
(tmp_path / "subtitled_5_t_clip_1.mp4").write_bytes(b"x")
time.sleep(0.02)
(tmp_path / "wm_subtitled_5_t_clip_1.mp4").write_bytes(b"x")
os.utime(tmp_path / "wm_subtitled_5_t_clip_1.mp4", None)
assert app._canonical_clip_file(str(tmp_path), "t", 0) == "wm_subtitled_5_t_clip_1.mp4"
class TestMediaGuard:
"""A marked job's clean twins are not fetchable by stripping wm_ off the URL."""
def test_marked_job_refuses_clean_clips_only(self, tmp_path, monkeypatch):
app = pytest.importorskip("clipwright.api.app")
monkeypatch.setattr(app, "OUTPUT_DIR", str(tmp_path))
(tmp_path / "job1").mkdir()
watermarked.mark_job(str(tmp_path / "job1"))
assert app._media_guard("job1/wm_subtitled_1_t_clip_1.mp4")
assert not app._media_guard("job1/subtitled_1_t_clip_1.mp4")
assert not app._media_guard("job1/t_clip_1.mp4")
# Editor scratch files and sidecars stay servable.
assert app._media_guard("job1/temp_preview_0.mp4")
assert app._media_guard("job1/subs_0_1.ass")
# And a dotfile never is, marker included.
assert not app._media_guard("job1/.marked")
def test_unmarked_job_serves_everything_deliverable(self, tmp_path, monkeypatch):
app = pytest.importorskip("clipwright.api.app")
monkeypatch.setattr(app, "OUTPUT_DIR", str(tmp_path))
(tmp_path / "job2").mkdir()
assert app._media_guard("job2/t_clip_1.mp4")
assert not app._media_guard("job2/t_metadata.json")