chore: drop watermark feature, CLI, docs, design.md; consolidate requirements (#6)
- 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. Reviewed-on: #6 Co-authored-by: pedro-bento <mail@pbento.pt> Co-committed-by: pedro-bento <mail@pbento.pt>
This commit is contained in:
parent
0040aa49da
commit
91a5465f81
46 changed files with 283 additions and 1378 deletions
42
.github/workflows/ci.yml
vendored
42
.github/workflows/ci.yml
vendored
|
|
@ -11,7 +11,7 @@ env:
|
||||||
PIP_DISABLE_PIP_VERSION_CHECK: "1"
|
PIP_DISABLE_PIP_VERSION_CHECK: "1"
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
# Fast unit suite. No ffmpeg, no ML stack, no pytest-timeout requirement.
|
# Fast unit suite. No ffmpeg, no ML stack.
|
||||||
unit:
|
unit:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
timeout-minutes: 15
|
timeout-minutes: 15
|
||||||
|
|
@ -23,20 +23,26 @@ jobs:
|
||||||
container: nikolaik/python-nodejs:python3.11-nodejs20
|
container: nikolaik/python-nodejs:python3.11-nodejs20
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
# 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
|
- name: Install test dependencies
|
||||||
run: pip install -r requirements-test.txt
|
run: pip install -r requirements-test.txt
|
||||||
- name: Run unit tests
|
- name: Run unit tests
|
||||||
# Exclude the E2E tree from *collection*: `-m "not e2e"` only filters
|
# Exclude the E2E tree from *collection*: `-m "not e2e"` only filters
|
||||||
# execution, but pytest still imports every module to collect it, and the
|
# execution, but pytest still imports every module to collect it, and
|
||||||
# pipeline E2E modules import the pipeline (tqdm/scenedetect/ML) which is
|
# the pipeline E2E modules import the pipeline (tqdm/scenedetect/ML),
|
||||||
# intentionally absent from the unit environment.
|
# which would pull in fixtures the unit suite does not exercise.
|
||||||
run: pytest tests/ --ignore=tests/e2e -m "not e2e" -q
|
run: pytest tests/ --ignore=tests/e2e -m "not e2e" -q
|
||||||
|
|
||||||
# Backend E2E: API + pipeline. ffmpeg/ffprobe must be installed in-job; the
|
# Backend E2E: API + pipeline. ffmpeg/ffprobe must be installed in-job.
|
||||||
# E2E requirements add pytest-asyncio/asgi-lifespan/pytest-timeout and the
|
# requirements-test.txt already carries pytest-asyncio/asgi-lifespan/
|
||||||
# pure-Python scene engine. API and pipeline run as separate processes so the
|
# pytest-timeout and the pure-Python scene engine. API and pipeline run as
|
||||||
# pipeline tests' fake `clipwright.pipeline.main` can never leak into the API
|
# separate processes so the pipeline tests' fake `clipwright.pipeline.main`
|
||||||
# process. No ML stack: detectors are stubbed, only ffmpeg is real.
|
# can never leak into the API process. No ML stack: detectors are stubbed,
|
||||||
|
# only ffmpeg is real.
|
||||||
backend-e2e:
|
backend-e2e:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
timeout-minutes: 30
|
timeout-minutes: 30
|
||||||
|
|
@ -45,8 +51,8 @@ jobs:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- name: Install ffmpeg
|
- name: Install ffmpeg
|
||||||
run: apt-get update -qq && apt-get install -y -qq --no-install-recommends ffmpeg && ffmpeg -version | head -1
|
run: apt-get update -qq && apt-get install -y -qq --no-install-recommends ffmpeg && ffmpeg -version | head -1
|
||||||
- name: Install E2E dependencies
|
- name: Install test dependencies
|
||||||
run: pip install -r requirements-e2e.txt
|
run: pip install -r requirements-test.txt
|
||||||
- name: Run API E2E
|
- name: Run API E2E
|
||||||
run: pytest tests/e2e/api -m e2e -q --timeout=120
|
run: pytest tests/e2e/api -m e2e -q --timeout=120
|
||||||
- name: Run pipeline E2E (non-ML)
|
- name: Run pipeline E2E (non-ML)
|
||||||
|
|
@ -61,13 +67,23 @@ jobs:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
timeout-minutes: 30
|
timeout-minutes: 30
|
||||||
container: nikolaik/python-nodejs:python3.11-nodejs20
|
container: nikolaik/python-nodejs:python3.11-nodejs20
|
||||||
|
# Turn on the real-backend lane: Playwright's second webServer boots a real
|
||||||
|
# uvicorn (pipeline stub_env) and the `real` project drives it.
|
||||||
|
env:
|
||||||
|
CW_E2E_REAL: "1"
|
||||||
defaults:
|
defaults:
|
||||||
run:
|
run:
|
||||||
working-directory: dashboard
|
working-directory: dashboard
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- name: Install ffmpeg (E2E media fixture)
|
# ffmpeg builds the media fixture and renders the real pipeline's clips;
|
||||||
run: apt-get update -qq && apt-get install -y -qq --no-install-recommends ffmpeg
|
# libgl1 satisfies opencv (pulled by scenedetect) at import time.
|
||||||
|
- name: Install ffmpeg + opencv system libs
|
||||||
|
run: apt-get update -qq && apt-get install -y -qq --no-install-recommends ffmpeg libgl1
|
||||||
|
# Backend deps for the uvicorn server the real lane launches (uvicorn is
|
||||||
|
# pinned in requirements-test.txt alongside fastapi/scenedetect/...).
|
||||||
|
- name: Install backend test dependencies
|
||||||
|
run: pip install -r ../requirements-test.txt
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: npm ci
|
run: npm ci
|
||||||
- name: Install Playwright browsers
|
- name: Install Playwright browsers
|
||||||
|
|
|
||||||
42
.github/workflows/publish-cli.yml
vendored
42
.github/workflows/publish-cli.yml
vendored
|
|
@ -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/
|
|
||||||
|
|
@ -111,7 +111,6 @@ clipwright/ # Python backend package
|
||||||
integrations/ # Postiz, YouTube, file hosts
|
integrations/ # Postiz, YouTube, file hosts
|
||||||
tools/ # local verification scripts (python -m clipwright.tools.verify_hooks)
|
tools/ # local verification scripts (python -m clipwright.tools.verify_hooks)
|
||||||
dashboard/ # React + Vite dashboard (its own build)
|
dashboard/ # React + Vite dashboard (its own build)
|
||||||
cli/ # published `clipwright` HTTP client (own pyproject)
|
|
||||||
tests/ # pytest suite (pythonpath = ["."])
|
tests/ # pytest suite (pythonpath = ["."])
|
||||||
fonts/ assets/ # shared runtime resources (kept at repo root)
|
fonts/ assets/ # shared runtime resources (kept at repo root)
|
||||||
```
|
```
|
||||||
|
|
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 65 KiB |
|
|
@ -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.
|
|
||||||
|
|
@ -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()
|
|
||||||
|
|
@ -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"]
|
|
||||||
|
|
@ -28,7 +28,6 @@ from pydantic import BaseModel
|
||||||
import httpx
|
import httpx
|
||||||
from clipwright.media import recut
|
from clipwright.media import recut
|
||||||
from clipwright.layouts import layout_ranges
|
from clipwright.layouts import layout_ranges
|
||||||
from clipwright.media import watermarked
|
|
||||||
from clipwright.api import media_auth
|
from clipwright.api import media_auth
|
||||||
from clipwright.integrations import postiz
|
from clipwright.integrations import postiz
|
||||||
from clipwright.core.paths import REPO_ROOT
|
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
|
# captioned hooks; the bare recut_/hooked_/hook_ patterns cover
|
||||||
# derivations that shipped uncaptioned (hook_ is the legacy manual-
|
# derivations that shipped uncaptioned (hook_ is the legacy manual-
|
||||||
# hook prefix, kept so old jobs still resolve).
|
# 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}"))
|
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"recut_*_{clean}"))
|
||||||
+ glob.glob(os.path.join(output_dir, f"hooked_*_{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"hook_{clean}")))
|
||||||
+ glob.glob(os.path.join(output_dir, f"wm_*{clean}")))
|
|
||||||
except Exception:
|
except Exception:
|
||||||
derived = []
|
derived = []
|
||||||
if not 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.
|
Trust the disk, not the promise.
|
||||||
"""
|
"""
|
||||||
# main.py announces the file it actually finished for each clip
|
# main.py announces the file it actually finished for each clip
|
||||||
# (CLIP_READY, printed after the whole reframe/watermark/hook/caption
|
# (CLIP_READY, printed after the whole reframe/hook/caption chain).
|
||||||
# chain). Prefer it over rebuilding the name: the marker is what the file
|
# Prefer it over rebuilding the name: the marker is what the file
|
||||||
# IS, _canonical_clip_file is a guess from the naming convention.
|
# IS, _canonical_clip_file is a guess from the naming convention.
|
||||||
ready_files = (jobs.get(job_id) or {}).get('ready_files') or {}
|
ready_files = (jobs.get(job_id) or {}).get('ready_files') or {}
|
||||||
kept = []
|
kept = []
|
||||||
|
|
@ -391,21 +387,6 @@ def _clips_actually_rendered(job_id, output_dir, base_name, clips):
|
||||||
return kept, len(clips) - len(kept)
|
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):
|
def _strip_burned_captions(output_dir, filename):
|
||||||
"""Walk ``subtitled_<ts>_`` prefixes back to the file without burned captions.
|
"""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
|
underlying file is gone, e.g. a library restore that only kept the current
|
||||||
version).
|
version).
|
||||||
"""
|
"""
|
||||||
filename = _strip_watermark_copy(output_dir, filename)
|
|
||||||
while True:
|
while True:
|
||||||
m = re.match(r'^subtitled_\d+_(.+)$', filename)
|
m = re.match(r'^subtitled_\d+_(.+)$', filename)
|
||||||
if not m or not os.path.exists(os.path.join(output_dir, m.group(1))):
|
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:
|
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
|
the name is returned unchanged when there is nothing to strip or the
|
||||||
underlying file is gone."""
|
underlying file is gone."""
|
||||||
filename = _strip_watermark_copy(output_dir, filename)
|
|
||||||
while True:
|
while True:
|
||||||
m = re.match(r'^(?:hooked_\d+_|hook_)(.+)$', filename)
|
m = re.match(r'^(?:hooked_\d+_|hook_)(.+)$', filename)
|
||||||
if not m or not os.path.exists(os.path.join(output_dir, m.group(1))):
|
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):
|
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
|
return filename
|
||||||
|
|
||||||
|
|
||||||
def _media_guard(path: str) -> bool:
|
def _media_guard(path: str) -> bool:
|
||||||
"""``/videos`` allowlist: deliverable types only (media_auth)."""
|
"""``/videos`` allowlist: deliverable types only (media_auth)."""
|
||||||
if not media_auth.is_servable(path):
|
return 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))
|
|
||||||
|
|
||||||
|
|
||||||
def _reapply_captions(job_id, clip_index, video_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,
|
"canonical_range": canonical_range,
|
||||||
"duration": total,
|
"duration": total,
|
||||||
"current_file": current_file,
|
"current_file": current_file,
|
||||||
"has_captions": bool(re.match(r'^subtitled_\d+_',
|
"has_captions": bool(re.match(r'^subtitled_\d+_', current_file)),
|
||||||
watermarked.clean_name(current_file))),
|
|
||||||
"words": words_out,
|
"words": words_out,
|
||||||
"source": {
|
"source": {
|
||||||
"available": bool(source_path),
|
"available": bool(source_path),
|
||||||
|
|
@ -3794,8 +3767,8 @@ async def remove_subtitles(req: RemoveSubtitlesRequest, request: Request):
|
||||||
raise HTTPException(status_code=404,
|
raise HTTPException(status_code=404,
|
||||||
detail="The original clip is no longer available.")
|
detail="The original clip is no longer available.")
|
||||||
|
|
||||||
# Free plan: the un-captioned file is served through its wm_ copy, which
|
# The un-captioned file is served as-is; captions were stripped above so
|
||||||
# is reused when the clip shipped that way (no encode).
|
# a later restyle does not stack a second caption layer.
|
||||||
filename = await _deliver(request, req.job_id, filename)
|
filename = await _deliver(request, req.job_id, filename)
|
||||||
new_url = f"/videos/{req.job_id}/{filename}"
|
new_url = f"/videos/{req.job_id}/{filename}"
|
||||||
if req.clip_index < len(job.get('result', {}).get('clips', [])):
|
if req.clip_index < len(job.get('result', {}).get('clips', [])):
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
"""Canonical filesystem locations for the Clipwright backend.
|
"""Canonical filesystem locations for the Clipwright backend.
|
||||||
|
|
||||||
The importable package lives at ``<repo>/clipwright`` while the shared runtime
|
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,
|
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
|
independently of the current working directory or of how deep a module sits in
|
||||||
the package.
|
the package.
|
||||||
|
|
@ -17,10 +17,8 @@ PACKAGE_DIR = Path(__file__).resolve().parent.parent
|
||||||
REPO_ROOT = PACKAGE_DIR.parent
|
REPO_ROOT = PACKAGE_DIR.parent
|
||||||
|
|
||||||
FONTS_DIR = REPO_ROOT / "fonts"
|
FONTS_DIR = REPO_ROOT / "fonts"
|
||||||
ASSETS_DIR = REPO_ROOT / "assets"
|
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
"REPO_ROOT",
|
"REPO_ROOT",
|
||||||
"FONTS_DIR",
|
"FONTS_DIR",
|
||||||
"ASSETS_DIR",
|
|
||||||
]
|
]
|
||||||
|
|
|
||||||
|
|
@ -341,7 +341,7 @@ def _run(cmd):
|
||||||
|
|
||||||
|
|
||||||
def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
|
def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
|
||||||
force_strategy=None, crop_overrides=None, watermark=False):
|
force_strategy=None, crop_overrides=None):
|
||||||
"""Full v2 reframe of one clip. Raises on failure (caller falls back).
|
"""Full v2 reframe of one clip. Raises on failure (caller falls back).
|
||||||
|
|
||||||
``content_ranges`` comes from screencast_layout.detect_content_ranges() on
|
``content_ranges`` comes from screencast_layout.detect_content_ranges() on
|
||||||
|
|
@ -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
|
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
|
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.
|
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
|
from clipwright.pipeline import main as m
|
||||||
content_ranges = content_ranges or []
|
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))
|
ranges = scene_frame_ranges(scene_boundaries, strategies, len(xs))
|
||||||
if not ranges:
|
if not ranges:
|
||||||
raise RuntimeError("no usable scene ranges")
|
raise RuntimeError("no usable scene ranges")
|
||||||
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_")
|
workdir = tempfile.mkdtemp(prefix="reframe_v2_")
|
||||||
segments = []
|
segments = []
|
||||||
|
|
@ -584,10 +576,6 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
|
||||||
)
|
)
|
||||||
|
|
||||||
inputs, out_label = ["-i", input_video], "[v]"
|
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([
|
_run([
|
||||||
"ffmpeg", "-y", "-loglevel", "error",
|
"ffmpeg", "-y", "-loglevel", "error",
|
||||||
"-ss", f"{ss:.4f}", "-t", f"{dur:.4f}", *inputs,
|
"-ss", f"{ss:.4f}", "-t", f"{dur:.4f}", *inputs,
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ turned into a rendered clip.
|
||||||
|
|
||||||
The pure helpers here are standard-library only (plus ffmpeg_utils, which is
|
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
|
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.
|
only on the paths that need it.
|
||||||
|
|
||||||
Two render paths:
|
Two render paths:
|
||||||
|
|
@ -243,8 +243,8 @@ def run_cut_concat(input_path, segments, out_path, workdir, runner=None):
|
||||||
return out_path
|
return out_path
|
||||||
|
|
||||||
|
|
||||||
# Same ceiling as apply_watermark's: a hung ffmpeg must not pin the executor
|
# A hung ffmpeg must not pin the executor thread (and the caller's quota
|
||||||
# thread (and the caller's quota reservation) until a server restart.
|
# reservation) until a server restart.
|
||||||
FFMPEG_TIMEOUT_SECONDS = 1800
|
FFMPEG_TIMEOUT_SECONDS = 1800
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -262,18 +262,16 @@ def _run_ffmpeg(command):
|
||||||
|
|
||||||
|
|
||||||
def perform_recut(*, input_path, segments, output_dir, clean_name,
|
def perform_recut(*, input_path, segments, output_dir, clean_name,
|
||||||
reframe=False, output_format="auto", watermark=False,
|
reframe=False, output_format="auto",
|
||||||
captions_transcript=None, force_strategy=None,
|
captions_transcript=None, force_strategy=None,
|
||||||
crop_overrides=None, runner=None, renderer=None,
|
crop_overrides=None, runner=None, renderer=None,
|
||||||
watermarker=None, captioner=None):
|
captioner=None):
|
||||||
"""Render a recut clip. Returns (served_filename, clean_filename).
|
"""Render a recut clip. Returns (served_filename, clean_filename).
|
||||||
|
|
||||||
- ``input_path``/``segments``: the file to cut from and the times ON THAT
|
- ``input_path``/``segments``: the file to cut from and the times ON THAT
|
||||||
FILE (the caller rebases for the fast path).
|
FILE (the caller rebases for the fast path).
|
||||||
- ``reframe``: run the reframe engine on the joined cut (source path only —
|
- ``reframe``: run the reframe engine on the joined cut (source path only —
|
||||||
the canonical file is already framed).
|
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
|
- ``captions_transcript``: a clip-relative transcript (see
|
||||||
``virtual_transcript``); when given and non-empty, captions are burned
|
``virtual_transcript``); when given and non-empty, captions are burned
|
||||||
LAST onto a ``subtitled_<ts>_`` derivative, preserving the invariant
|
LAST onto a ``subtitled_<ts>_`` derivative, preserving the invariant
|
||||||
|
|
@ -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
|
the same reason as ``reframe``: the canonical file is already cropped, so
|
||||||
its framing can no longer be changed.
|
its framing can no longer be changed.
|
||||||
|
|
||||||
The renderer/watermarker/captioner hooks default to main.py's
|
The renderer/captioner hooks default to main.py's implementations, imported
|
||||||
implementations, imported lazily so this module stays importable without
|
lazily so this module stays importable without the ML stack; tests inject
|
||||||
the ML stack; tests inject fakes.
|
fakes.
|
||||||
"""
|
"""
|
||||||
# The uuid token keeps two same-second saves of one clip from writing (and
|
# The uuid token keeps two same-second saves of one clip from writing (and
|
||||||
# then serving) the same filename; the timestamp keeps "newest derived
|
# 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"])
|
(r["start"], r["end"], r["layout"])
|
||||||
for r in layout_ranges.remap(layout_ranges.read(input_path), segments)])
|
for r in layout_ranges.remap(layout_ranges.read(input_path), segments)])
|
||||||
|
|
||||||
if watermark:
|
|
||||||
(watermarker or _main_attr("apply_watermark"))(out_path)
|
|
||||||
|
|
||||||
served_name = out_name
|
served_name = out_name
|
||||||
if captions_transcript and captions_transcript.get("segments"):
|
if captions_transcript and captions_transcript.get("segments"):
|
||||||
caption = captioner or _main_attr("auto_caption_clip")
|
caption = captioner or _main_attr("auto_caption_clip")
|
||||||
|
|
|
||||||
|
|
@ -612,7 +612,7 @@ def _generate_one(client, concept, reference_images, out_path, burn_text):
|
||||||
if burn_text:
|
if burn_text:
|
||||||
pos = concept['text_position']
|
pos = concept['text_position']
|
||||||
share = "45% of the width" if pos in ("left", "right") else "40% of the height"
|
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 "
|
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 "
|
"(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.")
|
"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}
|
{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:
|
if reference_images:
|
||||||
prompt += ("\nIDENTITY: the person in the provided photo must appear as EXACTLY the same real person: "
|
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 "
|
"identical face shape, skin, eyes, glasses, facial hair, hairstyle and hair length, age and "
|
||||||
|
|
|
||||||
|
|
@ -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
|
|
||||||
|
|
@ -25,12 +25,11 @@ from clipwright.pipeline import gemini_worker
|
||||||
from clipwright.pipeline import hook_grounding
|
from clipwright.pipeline import hook_grounding
|
||||||
from clipwright.layouts import layout_picker
|
from clipwright.layouts import layout_picker
|
||||||
from clipwright.pipeline import llm_backend
|
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,
|
from clipwright.pipeline.clip_selection import (build_transcript_windows, clip_count_targets,
|
||||||
clip_duration_bounds, dedupe_overlapping,
|
clip_duration_bounds, dedupe_overlapping,
|
||||||
score_batches, shortlist_target,
|
score_batches, shortlist_target,
|
||||||
snap_clip_to_words, trim_to_best)
|
snap_clip_to_words, trim_to_best)
|
||||||
from 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)
|
QUALITY_FAST, METADATA_SCRUB)
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
import json
|
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",
|
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.
|
"""Route a cut clip through the right renderer for the chosen output format.
|
||||||
vertical/auto -> 9:16 reframe, square -> 1:1 reframe, horizontal -> keep.
|
vertical/auto -> 9:16 reframe, square -> 1:1 reframe, horizontal -> keep.
|
||||||
``force_strategy`` (e.g. 'WIDE'/'TRACK') pins every scene's layout — the
|
``force_strategy`` (e.g. 'WIDE'/'TRACK') pins every scene's layout — the
|
||||||
clip editor's whole-clip framing override. ``crop_overrides`` positions
|
clip editor's whole-clip framing override. ``crop_overrides`` positions
|
||||||
individual scenes by hand (the per-scene reframing editor) and wins over
|
individual scenes by hand (the per-scene reframing editor) and wins over
|
||||||
``force_strategy`` for the scenes it names.
|
``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."""
|
|
||||||
if output_format == "horizontal":
|
if output_format == "horizontal":
|
||||||
ok = finalize_clip_passthrough(input_video, final_output_video)
|
return finalize_clip_passthrough(input_video, final_output_video)
|
||||||
if ok and watermark:
|
|
||||||
apply_watermark(final_output_video)
|
|
||||||
return ok
|
|
||||||
aspect = 1.0 if output_format == "square" else ASPECT_RATIO
|
aspect = 1.0 if output_format == "square" else ASPECT_RATIO
|
||||||
return process_video_to_vertical(input_video, final_output_video, aspect_ratio=aspect,
|
return process_video_to_vertical(input_video, final_output_video, aspect_ratio=aspect,
|
||||||
force_strategy=force_strategy,
|
force_strategy=force_strategy,
|
||||||
crop_overrides=crop_overrides,
|
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
|
|
||||||
|
|
||||||
|
|
||||||
def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPECT_RATIO,
|
def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPECT_RATIO,
|
||||||
force_strategy=None, crop_overrides=None, watermark=False):
|
force_strategy=None, crop_overrides=None):
|
||||||
"""
|
"""
|
||||||
Core logic to reframe a horizontal video to a target aspect ratio using
|
Core logic to reframe a horizontal video to a target aspect ratio using
|
||||||
scene detection and Active Speaker Tracking (MediaPipe).
|
scene detection and Active Speaker Tracking (MediaPipe).
|
||||||
|
|
@ -1446,8 +1333,7 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE
|
||||||
t0 = time.time()
|
t0 = time.time()
|
||||||
result = reframe_v2.render(input_video, final_output_video, aspect_ratio,
|
result = reframe_v2.render(input_video, final_output_video, aspect_ratio,
|
||||||
force_strategy=force_strategy,
|
force_strategy=force_strategy,
|
||||||
crop_overrides=crop_overrides,
|
crop_overrides=crop_overrides)
|
||||||
watermark=watermark)
|
|
||||||
print(f" ⏱️ Reframe v2 total: {time.time() - t0:.1f}s")
|
print(f" ⏱️ Reframe v2 total: {time.time() - t0:.1f}s")
|
||||||
return result
|
return result
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|
@ -1642,8 +1528,6 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE
|
||||||
if os.path.exists(leftover):
|
if os.path.exists(leftover):
|
||||||
os.remove(leftover)
|
os.remove(leftover)
|
||||||
|
|
||||||
if watermark:
|
|
||||||
apply_watermark(final_output_video)
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
# --- Transcript checkpoint (survive a redeploy without paying twice) ---------
|
# --- 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)
|
cut_clip(input_video, clip_temp_path, start, end, i + 1)
|
||||||
|
|
||||||
# Layer order: the canonical reframe stays CLEAN, the hook
|
# Layer order: the canonical reframe stays CLEAN, the hook
|
||||||
# is a derived hooked_ file, captions go last on top of
|
# is a derived hooked_ file, and captions go last on top of
|
||||||
# whichever is current, and on the free plan the served
|
# whichever is current. Each worker writes only its own clip
|
||||||
# file is a wm_ copy of that final (mark_delivery). The
|
# dict, so the re-dump after the pool is race-free.
|
||||||
# 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.
|
|
||||||
success = render_clip(clip_temp_path, clip_final_path, output_format)
|
success = render_clip(clip_temp_path, clip_final_path, output_format)
|
||||||
if success:
|
if success:
|
||||||
print(f" 🎞️ Clip {i+1} framed")
|
print(f" 🎞️ Clip {i+1} framed")
|
||||||
|
|
@ -2437,16 +2317,14 @@ if __name__ == '__main__':
|
||||||
deliver_path, transcript, start, end,
|
deliver_path, transcript, start, end,
|
||||||
split_ranges=split_ranges)
|
split_ranges=split_ranges)
|
||||||
served = captioned or deliver_path
|
served = captioned or deliver_path
|
||||||
if os.environ.get("WATERMARK") == "1":
|
|
||||||
served = mark_delivery(served)
|
|
||||||
print(f" ✅ Clip {i+1} ready: {clip_final_path}")
|
print(f" ✅ Clip {i+1} ready: {clip_final_path}")
|
||||||
# Hand the API the file to actually serve for this clip.
|
# Hand the API the file to actually serve for this clip.
|
||||||
# Without it the status poller guesses the clean reframe
|
# Without it the status poller guesses the clean reframe
|
||||||
# name, so a job in flight showed every clip stripped of
|
# name, so a job in flight showed every clip stripped of
|
||||||
# its hook and captions until the WHOLE job finished and
|
# its hook and captions until the WHOLE job finished and
|
||||||
# the result got rebuilt through _canonical_clip_file.
|
# the result got rebuilt through _canonical_clip_file.
|
||||||
# Printed only after the full chain (reframe, watermark,
|
# Printed only after the full chain (reframe, hook,
|
||||||
# hook, captions) so the file is complete when it is
|
# captions) so the file is complete when it is
|
||||||
# announced, never one that ffmpeg is still writing.
|
# announced, never one that ffmpeg is still writing.
|
||||||
print(f"CLIP_READY {i} {os.path.basename(served)}")
|
print(f"CLIP_READY {i} {os.path.basename(served)}")
|
||||||
return success
|
return success
|
||||||
|
|
@ -2460,11 +2338,6 @@ if __name__ == '__main__':
|
||||||
clip_workers = max(int(os.environ.get("CLIP_WORKERS", "6")), 1)
|
clip_workers = max(int(os.environ.get("CLIP_WORKERS", "6")), 1)
|
||||||
shorts = clips_data['shorts']
|
shorts = clips_data['shorts']
|
||||||
failed = []
|
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:
|
with ThreadPoolExecutor(max_workers=min(clip_workers, len(shorts))) as pool:
|
||||||
# Best clip first: the pool starts work in submission order, so
|
# Best clip first: the pool starts work in submission order, so
|
||||||
# the user's first delivered clip is the strongest one instead
|
# the user's first delivered clip is the strongest one instead
|
||||||
|
|
|
||||||
|
|
@ -3,12 +3,58 @@
|
||||||
// worker. This is the lane that must stay green in CI.
|
// worker. This is the lane that must stay green in CI.
|
||||||
// - `real`: drives the real backend (uvicorn + stub pipeline). Kept separate
|
// - `real`: drives the real backend (uvicorn + stub pipeline). Kept separate
|
||||||
// so the mocked lane never depends on Python.
|
// so the mocked lane never depends on Python.
|
||||||
|
//
|
||||||
|
// The `real` project and its backend webServer only exist when CW_E2E_REAL is
|
||||||
|
// set (CI sets it). A bare `npm run test:e2e` therefore stays mock-only and
|
||||||
|
// needs no Python deps.
|
||||||
/* global process */
|
/* global process */
|
||||||
import { defineConfig, devices } from '@playwright/test';
|
import { defineConfig, devices } from '@playwright/test';
|
||||||
import { fileURLToPath } from 'node:url';
|
import { fileURLToPath } from 'node:url';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
|
|
||||||
const dashboardDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
const dashboardDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
const repoRoot = path.resolve(dashboardDir, '..');
|
||||||
|
|
||||||
|
const realBackend = !!process.env.CW_E2E_REAL;
|
||||||
|
|
||||||
|
const webServers = [
|
||||||
|
{
|
||||||
|
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',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
if (realBackend) {
|
||||||
|
// Real `uvicorn clipwright.api.app:app` with the pipeline's stub_env on
|
||||||
|
// PYTHONPATH: sitecustomize stubs the ML/network edges so the real CLI runs
|
||||||
|
// with real ffmpeg, no model downloads and no outbound requests. The env
|
||||||
|
// values mirror tests/e2e/pipeline's deterministic, no-ML configuration.
|
||||||
|
webServers.push({
|
||||||
|
command: 'python -m uvicorn clipwright.api.app:app --host 127.0.0.1 --port 8000 --log-level warning',
|
||||||
|
cwd: repoRoot,
|
||||||
|
url: 'http://127.0.0.1:8000/health',
|
||||||
|
reuseExistingServer: !process.env.CI,
|
||||||
|
timeout: 120_000,
|
||||||
|
stdout: 'ignore',
|
||||||
|
stderr: 'pipe',
|
||||||
|
env: {
|
||||||
|
PYTHONPATH: ['tests/e2e/pipeline/stub_env', '.'].join(path.delimiter),
|
||||||
|
GEMINI_API_KEY: 'test',
|
||||||
|
MIN_SOURCE_SECONDS: '0',
|
||||||
|
QUALITY_GATE_MIN_HEIGHT: '0',
|
||||||
|
AUTO_LAYOUT: '0',
|
||||||
|
SCENE_ENGINE: 'pyscenedetect',
|
||||||
|
ASR_HOST_SLOTS: '0',
|
||||||
|
FFMPEG_ENCODER: 'x264',
|
||||||
|
TZ: 'UTC',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
testDir: './specs',
|
testDir: './specs',
|
||||||
|
|
@ -35,19 +81,14 @@ export default defineConfig({
|
||||||
testIgnore: /real-backend\.spec\.js/,
|
testIgnore: /real-backend\.spec\.js/,
|
||||||
use: { ...devices['Desktop Chrome'] },
|
use: { ...devices['Desktop Chrome'] },
|
||||||
},
|
},
|
||||||
{
|
// The real lane runs the full pipeline, which needs more than the 30s
|
||||||
|
// default. Gated so a mock-only run never tries to boot Python.
|
||||||
|
...(realBackend ? [{
|
||||||
name: 'real',
|
name: 'real',
|
||||||
testMatch: /real-backend\.spec\.js/,
|
testMatch: /real-backend\.spec\.js/,
|
||||||
|
timeout: 120_000,
|
||||||
use: { ...devices['Desktop Chrome'] },
|
use: { ...devices['Desktop Chrome'] },
|
||||||
},
|
}] : []),
|
||||||
],
|
],
|
||||||
webServer: {
|
webServer: webServers,
|
||||||
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',
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,33 @@
|
||||||
import { test, expect } from '@playwright/test';
|
import { test, expect } from '@playwright/test';
|
||||||
|
import { seedApp } from '../fixtures/app.js';
|
||||||
|
import { SIXTY_MP4 } from '../fixtures/media.js';
|
||||||
|
|
||||||
// Real-backend lane.
|
// Real-backend lane.
|
||||||
//
|
//
|
||||||
// The plan calls for driving a real `uvicorn clipwright.api.app:app` with the
|
// Drives the built app against a real `uvicorn clipwright.api.app:app` whose
|
||||||
// pipeline's stub_env (tests/e2e/pipeline/stub_env) so the browser talks to the
|
// pipeline runs the real CLI through tests/e2e/pipeline/stub_env (fake ML/ASR/
|
||||||
// actual API instead of route mocks. That pipeline/stub environment is owned by
|
// Gemini, real ffmpeg). No route mocks: the preview server proxies /api,
|
||||||
// the backend E2E lanes, and the dashboard CI job provisions Node + Chromium
|
// /videos and /thumbnails to the backend (vite.config.js preview.proxy), so
|
||||||
// only (no Python deps, no ffmpeg), so this stays fixme until the backend lane
|
// every request in this spec is served by Python. The spec is only collected
|
||||||
// exposes a server the dashboard job can launch. The same routes are covered
|
// when CW_E2E_REAL is set; the `mock` lane ignores it.
|
||||||
// end-to-end over HTTP by tests/e2e/api.
|
|
||||||
test.describe('real backend', () => {
|
test.describe('real backend', () => {
|
||||||
test.fixme('generates clips against a real uvicorn + stub_env server', async ({ page }) => {
|
test('generates a clip against a real uvicorn + stub_env server', async ({ page }) => {
|
||||||
await page.goto('/');
|
// Seed the BYOK Gemini key (and consent) exactly like the mock specs.
|
||||||
await expect(page).toHaveTitle(/Clipwright/);
|
// No installApiMocks: this lane talks to the real server.
|
||||||
|
await seedApp(page, { geminiKey: 'e2e-gemini-key' });
|
||||||
|
await page.goto('/#app');
|
||||||
|
|
||||||
|
await expect(page.getByRole('heading', { name: /create viral shorts/i })).toBeVisible();
|
||||||
|
|
||||||
|
// Upload the ffmpeg-built fixture, attest rights, submit.
|
||||||
|
await page.setInputFiles('input[type="file"][accept="video/*"]', SIXTY_MP4);
|
||||||
|
await page.locator('form input[type="checkbox"]').first().check();
|
||||||
|
await page.getByRole('button', { name: /generate clips/i }).click();
|
||||||
|
|
||||||
|
// The app polls /api/status every 2s; the real pipeline (real ffmpeg,
|
||||||
|
// stubbed ML) finishes in well under a minute. Bounded auto-wait, no
|
||||||
|
// sleeps: the clip count badge only renders once results carry clips.
|
||||||
|
await expect(page.getByText(/\d+ Clips/)).toBeVisible({ timeout: 60_000 });
|
||||||
|
await expect(page.getByText('Clip 1', { exact: true })).toBeVisible({ timeout: 60_000 });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -623,9 +623,7 @@ switched off.</p>
|
||||||
<h2>4. Who receives data (processors) and where</h2>
|
<h2>4. Who receives data (processors) and where</h2>
|
||||||
<p>Depending on how you configure it, the software can send data to these
|
<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
|
third-party providers. The machine-readable list, with the transfer safeguard
|
||||||
for each, is kept in the public repository at
|
for each, is kept in the public repository, and changes are recorded there.</p>
|
||||||
<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>
|
|
||||||
<ul>
|
<ul>
|
||||||
<li><strong>Google (Gemini API)</strong> — AI analysis to select moments,
|
<li><strong>Google (Gemini API)</strong> — AI analysis to select moments,
|
||||||
layouts, titles and thumbnails. It receives your video's transcript and
|
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
|
<p>The retention constants are configurable in the environment; the defaults
|
||||||
above are what the code enforces.</p>
|
above are what the code enforces.</p>
|
||||||
<p>The full, per-item version of this table, written against the actual code
|
<p>The full, per-item version of this table, written against the actual code
|
||||||
that enforces it, is in the public repository at
|
that enforces it, is kept in the public repository.</p>
|
||||||
<a href="https://git.pbento.pt/pedro-bento/clipwright/blob/main/docs/compliance/retencion.md">docs/compliance/retencion.md</a>.</p>
|
|
||||||
|
|
||||||
<h2>6. Your rights</h2>
|
<h2>6. Your rights</h2>
|
||||||
<p>You can ask us for access, rectification, erasure, restriction, portability
|
<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>
|
<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
|
<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
|
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
|
transferencia de cada uno, se mantiene en el repositorio público, donde
|
||||||
<a href="https://git.pbento.pt/pedro-bento/clipwright/blob/main/docs/compliance/subprocessors.md">docs/compliance/subprocessors.md</a>,
|
también se registran los cambios.</p>
|
||||||
donde también se registran los cambios.</p>
|
|
||||||
<ul>
|
<ul>
|
||||||
<li><strong>Google (API Gemini)</strong> — análisis con IA para seleccionar
|
<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
|
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
|
<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>
|
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
|
<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
|
realmente la aplica, está en el repositorio público.</p>
|
||||||
<a href="https://git.pbento.pt/pedro-bento/clipwright/blob/main/docs/compliance/retencion.md">docs/compliance/retencion.md</a>.</p>
|
|
||||||
|
|
||||||
<h2>6. Tus derechos</h2>
|
<h2>6. Tus derechos</h2>
|
||||||
<p>Puedes pedirnos acceso, rectificación, supresión, limitación y portabilidad
|
<p>Puedes pedirnos acceso, rectificación, supresión, limitación y portabilidad
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { X } from 'lucide-react';
|
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.
|
* Plain dark overlay (no backdrop-blur), hairline paper2 panel.
|
||||||
*
|
*
|
||||||
* Props:
|
* Props:
|
||||||
|
|
|
||||||
|
|
@ -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
|
* grid of toggle buttons (position/size/animation pickers, platform
|
||||||
* selectors, mode switches).
|
* selectors, mode switches).
|
||||||
*
|
*
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { Check } from 'lucide-react';
|
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.
|
* ordinals, hairline connectors, brass current step.
|
||||||
*
|
*
|
||||||
* Props:
|
* Props:
|
||||||
|
|
|
||||||
|
|
@ -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
|
/* 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. */
|
with the rest of the faces in public/fonts.css: no request to Google. */
|
||||||
@import './tokens.css';
|
@import './tokens.css';
|
||||||
|
|
|
||||||
|
|
@ -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)
|
* macrostructure: Marquee Hero (marketing) / Workbench (app) / Long Document (content)
|
||||||
* nav: N9 edge-aligned · footer: Ft5 statement · enrichment: filament apparatus (landing only)
|
* nav: N9 edge-aligned · footer: Ft5 statement · enrichment: filament apparatus (landing only)
|
||||||
* pre-emit critique: P5 H4 E4 S5 R5 V4
|
* pre-emit critique: P5 H4 E4 S5 R5 V4
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,14 @@ import seo from './vite-plugin-seo'
|
||||||
// the host against a backend reachable at localhost (no CORS, same-origin).
|
// the host against a backend reachable at localhost (no CORS, same-origin).
|
||||||
const backend = process.env.VITE_PROXY_TARGET || 'http://backend:8000'
|
const backend = process.env.VITE_PROXY_TARGET || 'http://backend:8000'
|
||||||
|
|
||||||
|
// Backend target for the *preview* server (the built app). The Playwright
|
||||||
|
// real-backend lane serves `vite preview` and needs same-origin /api, /videos
|
||||||
|
// and /thumbnails to reach a locally-launched uvicorn instead of the compose
|
||||||
|
// service. Defaults to the loopback backend the config's second webServer
|
||||||
|
// starts; CW_BACKEND_URL overrides it for other setups. Proxying keeps the
|
||||||
|
// built bundle origin-relative (no absolute VITE_API_URL baked in).
|
||||||
|
const previewBackend = process.env.CW_BACKEND_URL || 'http://127.0.0.1:8000'
|
||||||
|
|
||||||
// https://vitejs.dev/config/
|
// https://vitejs.dev/config/
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
// seo() runs on build only. It injects the crawler-visible homepage content
|
// seo() runs on build only. It injects the crawler-visible homepage content
|
||||||
|
|
@ -36,5 +44,14 @@ export default defineConfig({
|
||||||
'/videos': { target: backend, changeOrigin: true },
|
'/videos': { target: backend, changeOrigin: true },
|
||||||
'/thumbnails': { target: backend, changeOrigin: true },
|
'/thumbnails': { target: backend, changeOrigin: true },
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
// Mirror of server.proxy for `vite preview`, so the production bundle talks
|
||||||
|
// to the real backend same-origin (the browser E2E real-backend lane).
|
||||||
|
preview: {
|
||||||
|
proxy: {
|
||||||
|
'/api': { target: previewBackend, changeOrigin: true },
|
||||||
|
'/videos': { target: previewBackend, changeOrigin: true },
|
||||||
|
'/thumbnails': { target: previewBackend, changeOrigin: true },
|
||||||
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
|
||||||
168
design.md
168
design.md
|
|
@ -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.
|
|
||||||
|
|
@ -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`.
|
|
||||||
|
|
@ -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. |
|
|
||||||
|
|
@ -1,9 +1,7 @@
|
||||||
# The backend is not packaged or published: it runs from a bind-mounted source
|
# 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
|
# tree (docker-compose.yml) and `requirements.txt` is the single runtime
|
||||||
# dependency source for the Docker image. This file therefore carries tool
|
# dependency source for the Docker image. This file therefore carries tool
|
||||||
# configuration only — no [build-system] and no [project] table — which also
|
# configuration only — no [build-system] and no [project] table.
|
||||||
# avoids colliding with the published `clipwright` CLI distribution under
|
|
||||||
# `cli/`.
|
|
||||||
|
|
||||||
[tool.pytest.ini_options]
|
[tool.pytest.ini_options]
|
||||||
minversion = "7.0"
|
minversion = "7.0"
|
||||||
|
|
@ -17,7 +15,7 @@ pythonpath = ["."]
|
||||||
markers = [
|
markers = [
|
||||||
"e2e: end-to-end tests, run separately from the fast unit suite",
|
"e2e: end-to-end tests, run separately from the fast unit suite",
|
||||||
"pipeline: end-to-end tests that exercise the pipeline stages",
|
"pipeline: end-to-end tests that exercise the pipeline stages",
|
||||||
"ml: tests that need the heavy ML stack (see requirements-ml-e2e.txt)",
|
"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
|
# 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
|
# auto mode does not change the behaviour of the unit suite. pytest-timeout is
|
||||||
|
|
@ -30,7 +28,6 @@ line-length = 100
|
||||||
target-version = "py311"
|
target-version = "py311"
|
||||||
extend-exclude = [
|
extend-exclude = [
|
||||||
"dashboard",
|
"dashboard",
|
||||||
"cli",
|
|
||||||
"output",
|
"output",
|
||||||
"uploads",
|
"uploads",
|
||||||
]
|
]
|
||||||
|
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
-r requirements-test.txt
|
|
||||||
# Thin E2E environment: the unit-test stack plus the async HTTP client, the
|
|
||||||
# ASGI lifespan helper and the ffmpeg-driven media/scene helpers. No heavy ML
|
|
||||||
# here — the `ml`-marked pipeline tests add requirements-ml-e2e.txt on top.
|
|
||||||
|
|
||||||
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,6 +0,0 @@
|
||||||
# Heavy ML stack for the `ml`-marked pipeline E2E tests. Mirrors the runtime
|
|
||||||
# image's requirements.txt (torch / ultralytics / mediapipe / faster-whisper)
|
|
||||||
# on top of the thin E2E environment. Non-ML pipeline tests run against the
|
|
||||||
# stub_env fakes and never need this file.
|
|
||||||
-r requirements-e2e.txt
|
|
||||||
-r requirements.txt
|
|
||||||
|
|
@ -1,7 +1,10 @@
|
||||||
# Thin test environment: everything the collected tests import at module level,
|
# Thin test environment for BOTH the unit and E2E suites: everything the
|
||||||
# WITHOUT the heavy ML stack (torch/ultralytics/mediapipe/faster-whisper). The
|
# collected tests import at module level, WITHOUT the heavy ML stack
|
||||||
# pipeline modules import those lazily behind their feature gates, and the tests
|
# (torch/ultralytics/mediapipe/faster-whisper). The pipeline modules import
|
||||||
# exercise the gated-off paths.
|
# 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
|
pytest
|
||||||
pillow
|
pillow
|
||||||
httpx
|
httpx
|
||||||
|
|
@ -11,4 +14,11 @@ opencv-python-headless
|
||||||
python-dotenv
|
python-dotenv
|
||||||
google-genai
|
google-genai
|
||||||
fastapi
|
fastapi
|
||||||
|
uvicorn==0.46.0
|
||||||
python-multipart
|
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
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,88 @@
|
||||||
|
|
||||||
The repo-root ``clipwright/`` package is made importable by
|
The repo-root ``clipwright/`` package is made importable by
|
||||||
``[tool.pytest.ini_options] pythonpath = ["."]`` in the root ``pyproject.toml``,
|
``[tool.pytest.ini_options] pythonpath = ["."]`` in the root ``pyproject.toml``,
|
||||||
so no manual ``sys.path`` manipulation is needed here. This module is kept for
|
so no manual ``sys.path`` manipulation is needed here.
|
||||||
future shared fixtures.
|
|
||||||
|
The unit test environment deliberately omits the heavy ML stack
|
||||||
|
(torch/ultralytics/mediapipe/faster-whisper) so CI stays fast.
|
||||||
|
``clipwright.pipeline.main`` imports ``ultralytics`` and ``mediapipe`` at module
|
||||||
|
level, which made every test that does ``pytest.importorskip("...main")`` skip.
|
||||||
|
To keep that coverage without pulling gigabytes into CI, we install minimal
|
||||||
|
stand-ins *only when the real packages are absent* (the production image and a
|
||||||
|
developer machine with the real deps installed are unaffected).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
import types
|
||||||
|
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
|
||||||
|
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 _FakeDetection:
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def process(self, *args, **kwargs):
|
||||||
|
return SimpleNamespace(detections=None)
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _is_importable(name: str) -> bool:
|
||||||
|
try:
|
||||||
|
__import__(name)
|
||||||
|
return True
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _install_heavy_stubs() -> None:
|
||||||
|
if not _is_importable("ultralytics"):
|
||||||
|
ultralytics = types.ModuleType("ultralytics")
|
||||||
|
ultralytics.YOLO = _FakeYOLO
|
||||||
|
sys.modules["ultralytics"] = ultralytics
|
||||||
|
|
||||||
|
if not _is_importable("mediapipe"):
|
||||||
|
mediapipe = types.ModuleType("mediapipe")
|
||||||
|
solutions = types.ModuleType("mediapipe.solutions")
|
||||||
|
|
||||||
|
def _solution(name: str) -> types.ModuleType:
|
||||||
|
mod = types.ModuleType(f"mediapipe.solutions.{name}")
|
||||||
|
mod.FaceDetection = _FakeDetection
|
||||||
|
mod.Detection = _FakeDetection
|
||||||
|
sys.modules[f"mediapipe.solutions.{name}"] = mod
|
||||||
|
return mod
|
||||||
|
|
||||||
|
for name in (
|
||||||
|
"face_detection",
|
||||||
|
"face_mesh",
|
||||||
|
"pose",
|
||||||
|
"hands",
|
||||||
|
"holistic",
|
||||||
|
"selfie_segmentation",
|
||||||
|
):
|
||||||
|
setattr(solutions, name, _solution(name))
|
||||||
|
|
||||||
|
mediapipe.solutions = solutions
|
||||||
|
sys.modules["mediapipe"] = mediapipe
|
||||||
|
sys.modules["mediapipe.solutions"] = solutions
|
||||||
|
|
||||||
|
|
||||||
|
_install_heavy_stubs()
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ real ffmpeg, but the child interpreter is started with ``stub_env`` on
|
||||||
``PYTHONPATH``. ``stub_env/sitecustomize.py`` swaps the ML and network edges
|
``PYTHONPATH``. ``stub_env/sitecustomize.py`` swaps the ML and network edges
|
||||||
(ultralytics/mediapipe, ASR, Gemini) for deterministic fakes, so no model is
|
(ultralytics/mediapipe, ASR, Gemini) for deterministic fakes, so no model is
|
||||||
downloaded and no request leaves the process. Mark ML-backed variants with
|
downloaded and no request leaves the process. Mark ML-backed variants with
|
||||||
``pytest.mark.ml``; those run against ``requirements-ml-e2e.txt`` instead.
|
``pytest.mark.ml``; those need the heavy ML stack from ``requirements.txt``.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,7 @@ deterministic fakes. The real CLI then runs the real pipeline with real ffmpeg
|
||||||
and zero network / zero ML.
|
and zero network / zero ML.
|
||||||
|
|
||||||
Kept intentionally dependency-free (stdlib only) so it imports cleanly in the
|
Kept intentionally dependency-free (stdlib only) so it imports cleanly in the
|
||||||
thin ``requirements-e2e.txt`` environment.
|
thin ``requirements-test.txt`` environment.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
|
|
||||||
|
|
@ -27,7 +27,7 @@ def _cli_env(pipeline_env, **overrides):
|
||||||
"ASR_HOST_SLOTS": "0",
|
"ASR_HOST_SLOTS": "0",
|
||||||
"CLIP_WORKERS": "2",
|
"CLIP_WORKERS": "2",
|
||||||
})
|
})
|
||||||
for var in ("AUTO_HOOK", "WATERMARK", "MAX_SOURCE_MINUTES",
|
for var in ("AUTO_HOOK", "MAX_SOURCE_MINUTES",
|
||||||
"SOURCE_CAP_MINUTES", "DOWNLOAD_SKIP_STATICS"):
|
"SOURCE_CAP_MINUTES", "DOWNLOAD_SKIP_STATICS"):
|
||||||
pipeline_env.pop(var, None)
|
pipeline_env.pop(var, None)
|
||||||
pipeline_env.update(overrides)
|
pipeline_env.update(overrides)
|
||||||
|
|
|
||||||
|
|
@ -120,7 +120,7 @@ class TestRecut:
|
||||||
assert served.startswith("recut_") and served.endswith("_clip_1.mp4")
|
assert served.startswith("recut_") and served.endswith("_clip_1.mp4")
|
||||||
assert _probe_dims(tmp_path / served) == (320, 180)
|
assert _probe_dims(tmp_path / served) == (320, 180)
|
||||||
|
|
||||||
def test_source_path_wires_renderer_and_watermarker(self, tmp_path):
|
def test_source_path_wires_the_renderer(self, tmp_path):
|
||||||
events = []
|
events = []
|
||||||
|
|
||||||
def fake_runner(cmd):
|
def fake_runner(cmd):
|
||||||
|
|
@ -136,10 +136,9 @@ class TestRecut:
|
||||||
served, clean = recut.perform_recut(
|
served, clean = recut.perform_recut(
|
||||||
input_path="source.mp4", segments=[{"start": 5, "end": 15}],
|
input_path="source.mp4", segments=[{"start": 5, "end": 15}],
|
||||||
output_dir=str(tmp_path), clean_name="clip_1.mp4",
|
output_dir=str(tmp_path), clean_name="clip_1.mp4",
|
||||||
reframe=True, output_format="vertical", watermark=True,
|
reframe=True, output_format="vertical",
|
||||||
runner=fake_runner, renderer=fake_renderer,
|
runner=fake_runner, renderer=fake_renderer)
|
||||||
watermarker=lambda path: events.append(("watermark",)))
|
assert events == [("reframe", "vertical")]
|
||||||
assert events == [("reframe", "vertical"), ("watermark",)]
|
|
||||||
assert served == clean
|
assert served == clean
|
||||||
|
|
||||||
def test_captioner_is_invoked_last_and_wins_the_served_name(self, tmp_path):
|
def test_captioner_is_invoked_last_and_wins_the_served_name(self, tmp_path):
|
||||||
|
|
|
||||||
|
|
@ -1,143 +0,0 @@
|
||||||
"""L5 Pipeline media — WATERMARK stage.
|
|
||||||
|
|
||||||
The pure naming helpers, a real ``apply_watermark`` burn against the bundled
|
|
||||||
``assets/watermark.png``, and ``main.mark_delivery``'s contract: the served
|
|
||||||
``wm_`` copy is written while the clean twin is left byte-for-byte untouched,
|
|
||||||
an existing copy is reused, and a failed mark still fails open under the ``wm_``
|
|
||||||
name.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import os
|
|
||||||
import shutil
|
|
||||||
import subprocess
|
|
||||||
import sys
|
|
||||||
import types
|
|
||||||
from types import SimpleNamespace
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from clipwright.media import watermarked
|
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
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 / "t_clip_1.mp4"
|
|
||||||
shutil.copyfile(media_factory.six, dest)
|
|
||||||
return dest
|
|
||||||
|
|
||||||
|
|
||||||
class TestWatermarkedNames:
|
|
||||||
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_a_clip_1.mp4") == \
|
|
||||||
"subtitled_1_a_clip_1.mp4"
|
|
||||||
assert watermarked.is_marked("wm_x.mp4") and not watermarked.is_marked("x.mp4")
|
|
||||||
|
|
||||||
def test_clean_deliverables_exclude_scratch_and_sidecars(self):
|
|
||||||
assert watermarked.is_clean_deliverable("t_clip_1.mp4")
|
|
||||||
assert watermarked.is_clean_deliverable("hooked_1_t_clip_2.mp4")
|
|
||||||
for name in ("wm_t_clip_1.mp4", "temp_preview_0.mp4", "t_clip_1.layout.json"):
|
|
||||||
assert not watermarked.is_clean_deliverable(name)
|
|
||||||
|
|
||||||
def test_job_marker_round_trip(self, tmp_path):
|
|
||||||
assert not watermarked.job_is_marked(str(tmp_path))
|
|
||||||
watermarked.mark_job(str(tmp_path))
|
|
||||||
assert watermarked.job_is_marked(str(tmp_path))
|
|
||||||
|
|
||||||
|
|
||||||
class TestApplyWatermark:
|
|
||||||
def test_bundled_asset_is_present(self):
|
|
||||||
assert os.path.exists(main.watermark_logo_path())
|
|
||||||
|
|
||||||
def test_real_burn_writes_a_marked_copy_at_source_dimensions(self, clip, tmp_path):
|
|
||||||
out = tmp_path / "marked.mp4"
|
|
||||||
assert main.apply_watermark(str(clip), str(out)) is True
|
|
||||||
assert out.exists() and out.stat().st_size > 0
|
|
||||||
assert _probe_dims(out) == (320, 180)
|
|
||||||
# In-place source untouched when output_path is given.
|
|
||||||
assert _probe_dims(clip) == (320, 180)
|
|
||||||
|
|
||||||
def test_missing_asset_fails_open(self, clip, tmp_path, monkeypatch):
|
|
||||||
monkeypatch.setattr(main, "watermark_logo_path", lambda: "/nope/watermark.png")
|
|
||||||
assert main.apply_watermark(str(clip), str(tmp_path / "x.mp4")) is False
|
|
||||||
|
|
||||||
|
|
||||||
class TestMarkDelivery:
|
|
||||||
def test_writes_the_copy_and_leaves_the_clean_twin_untouched(self, clip, tmp_path):
|
|
||||||
before = clip.read_bytes()
|
|
||||||
served = main.mark_delivery(str(clip))
|
|
||||||
assert os.path.basename(served) == "wm_t_clip_1.mp4"
|
|
||||||
assert os.path.exists(served) and os.path.getsize(served) > 0
|
|
||||||
# The clean deliverable is byte-for-byte what it was.
|
|
||||||
assert clip.read_bytes() == before
|
|
||||||
|
|
||||||
def test_reuses_an_existing_copy(self, clip, tmp_path):
|
|
||||||
existing = tmp_path / "wm_t_clip_1.mp4"
|
|
||||||
existing.write_bytes(b"already-marked")
|
|
||||||
served = main.mark_delivery(str(clip), marker=lambda *_: pytest.fail("re-encoded"))
|
|
||||||
assert served == str(existing)
|
|
||||||
assert existing.read_bytes() == b"already-marked"
|
|
||||||
|
|
||||||
def test_failed_mark_fails_open_under_the_wm_name(self, clip, tmp_path):
|
|
||||||
served = main.mark_delivery(str(clip), marker=lambda *_: False)
|
|
||||||
assert os.path.basename(served) == "wm_t_clip_1.mp4"
|
|
||||||
assert os.path.exists(served)
|
|
||||||
assert clip.read_bytes() == (tmp_path / "wm_t_clip_1.mp4").read_bytes()
|
|
||||||
|
|
@ -156,7 +156,7 @@ def test_resumed_job_keeps_its_safety_cap(dirs, monkeypatch):
|
||||||
d.mkdir()
|
d.mkdir()
|
||||||
(d / app_module._RESUME_FILE).write_text(json.dumps({
|
(d / app_module._RESUME_FILE).write_text(json.dumps({
|
||||||
"cmd": ["python", "main.py"], "priority": 2, "user_id": None,
|
"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,
|
"source_cap_minutes": cap,
|
||||||
}))
|
}))
|
||||||
monkeypatch.setenv("SOURCE_CAP_MINUTES", "3") # a stale value must not leak in
|
monkeypatch.setenv("SOURCE_CAP_MINUTES", "3") # a stale value must not leak in
|
||||||
|
|
|
||||||
|
|
@ -74,9 +74,6 @@ class TestMainAnnouncesTheDeliveredFile:
|
||||||
"""
|
"""
|
||||||
main_src = MAIN_PY.read_text(encoding="utf-8")
|
main_src = MAIN_PY.read_text(encoding="utf-8")
|
||||||
caption_at = main_src.index("captioned = auto_caption_clip(")
|
caption_at = main_src.index("captioned = auto_caption_clip(")
|
||||||
# The free plan's served file is a wm_ copy of the captioned final
|
|
||||||
# (mark_delivery), so the marker must also come after that step.
|
|
||||||
served_at = main_src.index("served = captioned or deliver_path")
|
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)}")')
|
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
|
||||||
|
|
|
||||||
|
|
@ -33,7 +33,7 @@ def _manifest(out, job_id, **extra):
|
||||||
d = out / job_id
|
d = out / job_id
|
||||||
d.mkdir(exist_ok=True)
|
d.mkdir(exist_ok=True)
|
||||||
m = {"cmd": ["python", "main.py"], "priority": 2, "user_id": None,
|
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)
|
m.update(extra)
|
||||||
(d / app_module._RESUME_FILE).write_text(json.dumps(m))
|
(d / app_module._RESUME_FILE).write_text(json.dumps(m))
|
||||||
return d
|
return d
|
||||||
|
|
|
||||||
|
|
@ -21,8 +21,7 @@ class TestTheGuardIsWiredIn:
|
||||||
app = pytest.importorskip("clipwright.api.app")
|
app = pytest.importorskip("clipwright.api.app")
|
||||||
mount = next(r for r in app.app.routes
|
mount = next(r for r in app.app.routes
|
||||||
if getattr(r, "name", None) == "videos")
|
if getattr(r, "name", None) == "videos")
|
||||||
# app._media_guard wraps the allowlist (and adds the free-plan rule
|
# app._media_guard wraps the allowlist (media_auth.is_servable).
|
||||||
# that refuses a marked job's clean twins, tests/test_watermark_delivery).
|
|
||||||
assert mount.app.guard is app._media_guard, \
|
assert mount.app.guard is app._media_guard, \
|
||||||
"/videos is serving the working directory with no allowlist"
|
"/videos is serving the working directory with no allowlist"
|
||||||
assert not app._media_guard("job/.resume.json")
|
assert not app._media_guard("job/.resume.json")
|
||||||
|
|
|
||||||
|
|
@ -28,7 +28,7 @@ LEGACY_MODULES = frozenset({
|
||||||
"restoring_static", "scene_detection", "screencast_layout",
|
"restoring_static", "scene_detection", "screencast_layout",
|
||||||
"security_utils", "split_layout", "subtitles", "thumbnail",
|
"security_utils", "split_layout", "subtitles", "thumbnail",
|
||||||
"transcribe_backends", "verify_aesthetic", "verify_custom_hook",
|
"transcribe_backends", "verify_aesthetic", "verify_custom_hook",
|
||||||
"verify_hooks", "watermarked", "yt_clients",
|
"verify_hooks", "yt_clients",
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -266,7 +266,7 @@ class TestPerformRecut:
|
||||||
assert os.path.exists(tmp_path / clean)
|
assert os.path.exists(tmp_path / clean)
|
||||||
assert os.path.exists(tmp_path / served)
|
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 = []
|
events = []
|
||||||
|
|
||||||
def fake_renderer(work, out, output_format):
|
def fake_renderer(work, out, output_format):
|
||||||
|
|
@ -278,10 +278,9 @@ class TestPerformRecut:
|
||||||
served, clean = recut.perform_recut(
|
served, clean = recut.perform_recut(
|
||||||
input_path="source.mp4", segments=[_seg(5, 15)],
|
input_path="source.mp4", segments=[_seg(5, 15)],
|
||||||
output_dir=str(tmp_path), clean_name="t_clip_1.mp4",
|
output_dir=str(tmp_path), clean_name="t_clip_1.mp4",
|
||||||
reframe=True, output_format="vertical", watermark=True,
|
reframe=True, output_format="vertical",
|
||||||
runner=self._touching_runner, renderer=fake_renderer,
|
runner=self._touching_runner, renderer=fake_renderer)
|
||||||
watermarker=lambda path: events.append(("watermark",)))
|
assert events == [("reframe", "vertical")]
|
||||||
assert events == [("reframe", "vertical"), ("watermark",)]
|
|
||||||
assert served == clean
|
assert served == clean
|
||||||
|
|
||||||
def test_renderer_failure_raises_and_cleans_up(self, tmp_path):
|
def test_renderer_failure_raises_and_cleans_up(self, tmp_path):
|
||||||
|
|
|
||||||
|
|
@ -62,7 +62,7 @@ def job(tmp_path, monkeypatch):
|
||||||
app_module.jobs[JOB_ID] = {
|
app_module.jobs[JOB_ID] = {
|
||||||
"status": "completed", "logs": [],
|
"status": "completed", "logs": [],
|
||||||
"result": {"clips": [dict(clip)], "cost_analysis": {}},
|
"result": {"clips": [dict(clip)], "cost_analysis": {}},
|
||||||
"user_id": None, "watermark": False,
|
"user_id": None,
|
||||||
}
|
}
|
||||||
try:
|
try:
|
||||||
yield {"dir": job_dir, "meta_path": job_dir / "mytitle_metadata.json"}
|
yield {"dir": job_dir, "meta_path": job_dir / "mytitle_metadata.json"}
|
||||||
|
|
|
||||||
|
|
@ -77,7 +77,6 @@ def job(tmp_path, monkeypatch):
|
||||||
"logs": [],
|
"logs": [],
|
||||||
"result": {"clips": [dict(clip)], "cost_analysis": {}},
|
"result": {"clips": [dict(clip)], "cost_analysis": {}},
|
||||||
"user_id": None,
|
"user_id": None,
|
||||||
"watermark": False,
|
|
||||||
}
|
}
|
||||||
try:
|
try:
|
||||||
yield {"dir": job_dir, "meta_path": job_dir / "mytitle_metadata.json"}
|
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["input_path"].endswith("src.mp4")
|
||||||
assert call["reframe"] is True
|
assert call["reframe"] is True
|
||||||
assert call["output_format"] == "auto"
|
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.
|
# Source-absolute times, not rebased.
|
||||||
assert call["segments"] == [{"start": 45.0, "end": 55.0}]
|
assert call["segments"] == [{"start": 45.0, "end": 55.0}]
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -66,7 +66,6 @@ def job(tmp_path, monkeypatch):
|
||||||
"video_url": "/videos/x/clip_1.mp4",
|
"video_url": "/videos/x/clip_1.mp4",
|
||||||
}]},
|
}]},
|
||||||
"user_id": None,
|
"user_id": None,
|
||||||
"watermark": False,
|
|
||||||
}
|
}
|
||||||
try:
|
try:
|
||||||
yield job_dir
|
yield job_dir
|
||||||
|
|
|
||||||
|
|
@ -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")
|
|
||||||
Loading…
Reference in a new issue