Compare commits
3 commits
1551371626
...
026f3ff271
| Author | SHA1 | Date | |
|---|---|---|---|
| 026f3ff271 | |||
| 7f4cdbc318 | |||
| 59e0db8c24 |
|
|
@ -14,11 +14,10 @@ ENV/
|
||||||
.eggs/
|
.eggs/
|
||||||
*.egg-info/
|
*.egg-info/
|
||||||
.pytest_cache/
|
.pytest_cache/
|
||||||
|
.ruff_cache/
|
||||||
|
|
||||||
# Node
|
# Node
|
||||||
node_modules/
|
node_modules/
|
||||||
remotion/node_modules/
|
|
||||||
render-service/node_modules/
|
|
||||||
dashboard/node_modules/
|
dashboard/node_modules/
|
||||||
|
|
||||||
# IDE
|
# IDE
|
||||||
|
|
@ -27,6 +26,17 @@ dashboard/node_modules/
|
||||||
*.swp
|
*.swp
|
||||||
*.swo
|
*.swo
|
||||||
|
|
||||||
|
# Agent / tool local state
|
||||||
|
.opencode/
|
||||||
|
|
||||||
|
# Local caches
|
||||||
|
.cache/
|
||||||
|
.config/
|
||||||
|
|
||||||
|
# Not needed in the runtime image
|
||||||
|
tests/
|
||||||
|
screenshots/
|
||||||
|
|
||||||
# Video files (will be mounted via volume)
|
# Video files (will be mounted via volume)
|
||||||
*.mp4
|
*.mp4
|
||||||
*.avi
|
*.avi
|
||||||
|
|
@ -43,7 +53,6 @@ videos/
|
||||||
.env
|
.env
|
||||||
.env.*
|
.env.*
|
||||||
!.env.example
|
!.env.example
|
||||||
!.env.cloud.example
|
|
||||||
*.pem
|
*.pem
|
||||||
*.key
|
*.key
|
||||||
|
|
||||||
|
|
@ -55,10 +64,3 @@ docker-compose.yml
|
||||||
# Docs
|
# Docs
|
||||||
README.md
|
README.md
|
||||||
*.md
|
*.md
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
45
.env.example
|
|
@ -1,3 +1,8 @@
|
||||||
|
# Google Gemini API key used server-side (moment detection, layouts, titles and
|
||||||
|
# thumbnails). The dashboard can also send a key per request, and the key is
|
||||||
|
# optional entirely when LLM_BASE_URL points at an OpenAI-compatible server.
|
||||||
|
# GEMINI_API_KEY=your_gemini_api_key
|
||||||
|
|
||||||
# YouTube cookies (optional — paste Netscape-format cookies to bypass bot detection)
|
# YouTube cookies (optional — paste Netscape-format cookies to bypass bot detection)
|
||||||
# YOUTUBE_COOKIES=...
|
# YOUTUBE_COOKIES=...
|
||||||
|
|
||||||
|
|
@ -21,6 +26,9 @@
|
||||||
# Concurrent GPU transcriptions (parakeet or whisper-on-cuda). Keep 1.
|
# Concurrent GPU transcriptions (parakeet or whisper-on-cuda). Keep 1.
|
||||||
# ASR_GPU_CONCURRENCY=1
|
# ASR_GPU_CONCURRENCY=1
|
||||||
|
|
||||||
|
# Concurrent pipeline jobs (default 5).
|
||||||
|
# MAX_CONCURRENT_JOBS=5
|
||||||
|
|
||||||
# Video encoder for all ffmpeg encodes: x264 (default) | nvenc | auto.
|
# Video encoder for all ffmpeg encodes: x264 (default) | nvenc | auto.
|
||||||
# auto probes h264_nvenc once at startup and falls back to x264 if unusable.
|
# auto probes h264_nvenc once at startup and falls back to x264 if unusable.
|
||||||
# FFMPEG_ENCODER=x264
|
# FFMPEG_ENCODER=x264
|
||||||
|
|
@ -49,13 +57,8 @@ GEMINI_IMAGE_MODEL=gemini-3.1-flash-image
|
||||||
# LLM_SCORE_BATCH=3
|
# LLM_SCORE_BATCH=3
|
||||||
# LLM_TIMEOUT=600
|
# LLM_TIMEOUT=600
|
||||||
|
|
||||||
# Hard daily ceiling for the per-GB paid proxy (UTC day, MB). Above it,
|
|
||||||
# DataImpulse is removed from every chain until midnight and the jobs that
|
|
||||||
# needed it fail with a clear error. 0 disables the cap. Default 500.
|
|
||||||
# PAID_PROXY_DAILY_MB=500
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Privacy, retention and access control (GDPR remediation, 4-sep-2026)
|
# Privacy and access control (GDPR remediation, 4-sep-2026)
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
# Absolute base URL of the API as the internet reaches it, used for the
|
# Absolute base URL of the API as the internet reaches it, used for the
|
||||||
|
|
@ -68,17 +71,6 @@ GEMINI_IMAGE_MODEL=gemini-3.1-flash-image
|
||||||
# sidecars, dotfiles) so only media is exposed. Files are swept with the job
|
# sidecars, dotfiles) so only media is exposed. Files are swept with the job
|
||||||
# (JOB_RETENTION_SECONDS).
|
# (JOB_RETENTION_SECONDS).
|
||||||
|
|
||||||
# Retention for thumbnails. Thumbnails and the frames sampled to make them are
|
|
||||||
# close-ups of a real person; the clock runs from the last download.
|
|
||||||
# THUMBNAIL_RETENTION_SECONDS=86400
|
|
||||||
|
|
||||||
# Per-IP rate limiting. "<max requests>/<window seconds>".
|
|
||||||
# Defaults: auth 30/600, process 60/3600. Set RATE_LIMIT_ENABLED=0
|
|
||||||
# to turn the whole thing off (self-host behind your own firewall).
|
|
||||||
# RATE_LIMIT_ENABLED=1
|
|
||||||
# RATE_LIMIT_AUTH=30/600
|
|
||||||
# RATE_LIMIT_PROCESS=60/3600
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Publishing (self-hosted Postiz)
|
# Publishing (self-hosted Postiz)
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
@ -100,16 +92,9 @@ GEMINI_IMAGE_MODEL=gemini-3.1-flash-image
|
||||||
# number to cap uploads and reject larger files with HTTP 413.
|
# number to cap uploads and reject larger files with HTTP 413.
|
||||||
# MAX_FILE_SIZE_MB=0
|
# MAX_FILE_SIZE_MB=0
|
||||||
|
|
||||||
# Which hop may declare the client's address in X-Forwarded-For. The Dockerfile
|
# X-Forwarded-For trust. The container launches uvicorn with
|
||||||
# defaults to the private Docker ranges; narrow it to Traefik's own address on
|
# `--proxy-headers --forwarded-allow-ips *` (see the Dockerfile CMD), so any
|
||||||
# the container network in production. NEVER "*": that lets any caller forge
|
# caller that can reach the port may declare its own address and scheme. This
|
||||||
# the IP the rate limiter and the rights declaration are keyed on.
|
# is not configurable via an environment variable: run the API behind a reverse
|
||||||
# FORWARDED_ALLOW_IPS=10.0.1.7
|
# proxy that overwrites X-Forwarded-For, and never publish the backend port
|
||||||
|
# directly to the internet.
|
||||||
# Strict-Transport-Security value sent on https responses from the API. Empty
|
|
||||||
# disables it. Do not add "preload" without understanding that it is one-way.
|
|
||||||
# HSTS_HEADER=max-age=31536000; includeSubDomains
|
|
||||||
|
|
||||||
# Optional PostgreSQL database (only needed if you run the app against one).
|
|
||||||
# DATABASE_URL=postgres://user:pass@host:5432/clipwright
|
|
||||||
|
|
||||||
|
|
|
||||||
65
.github/workflows/ci.yml
vendored
|
|
@ -5,39 +5,72 @@ on:
|
||||||
branches: [main]
|
branches: [main]
|
||||||
pull_request:
|
pull_request:
|
||||||
|
|
||||||
|
env:
|
||||||
|
PYTHONHASHSEED: "0"
|
||||||
|
TZ: UTC
|
||||||
|
PIP_DISABLE_PIP_VERSION_CHECK: "1"
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
backend-tests:
|
# Fast unit suite. No ffmpeg, no ML stack, no pytest-timeout requirement.
|
||||||
|
unit:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 15
|
||||||
# The Forgejo runner cannot provision Python 3.11 via actions/setup-python
|
# The Forgejo runner cannot provision Python 3.11 via actions/setup-python
|
||||||
# ("Version 3.11 was not found in the local cache"), so the job runs inside
|
# ("Version 3.11 was not found in the local cache"), so every job runs in a
|
||||||
# a container that already has Python 3.11. It must also ship Node and git:
|
# container that already has Python 3.11. It must also ship Node and git:
|
||||||
# the runner executes JS actions (actions/checkout) by invoking `node`
|
# the runner executes JS actions (actions/checkout) by invoking `node`
|
||||||
# inside the job container, so a python-only image fails at checkout.
|
# inside the job container.
|
||||||
container: nikolaik/python-nodejs:python3.11-nodejs20
|
container: nikolaik/python-nodejs:python3.11-nodejs20
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
# Shared thin test environment (see requirements-test.txt): everything the
|
|
||||||
# collected tests import at module level, WITHOUT the heavy ML stack
|
|
||||||
# (torch/ultralytics/mediapipe/faster-whisper), which the pipeline modules
|
|
||||||
# import lazily behind their feature gates.
|
|
||||||
- name: Install test dependencies
|
- name: Install test dependencies
|
||||||
run: pip install -r requirements-test.txt
|
run: pip install -r requirements-test.txt
|
||||||
- name: Run tests
|
- name: Run unit tests
|
||||||
run: pytest tests/ -v
|
run: pytest tests/ -m "not e2e" -q
|
||||||
|
|
||||||
frontend-build:
|
# Backend E2E: API + pipeline. ffmpeg/ffprobe must be installed in-job; the
|
||||||
|
# E2E requirements add pytest-asyncio/asgi-lifespan/pytest-timeout and the
|
||||||
|
# pure-Python scene engine. API and pipeline run as separate processes so the
|
||||||
|
# pipeline tests' fake `clipwright.pipeline.main` can never leak into the API
|
||||||
|
# process. No ML stack: detectors are stubbed, only ffmpeg is real.
|
||||||
|
backend-e2e:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 30
|
||||||
|
container: nikolaik/python-nodejs:python3.11-nodejs20
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Install ffmpeg
|
||||||
|
run: apt-get update -qq && apt-get install -y -qq --no-install-recommends ffmpeg && ffmpeg -version | head -1
|
||||||
|
- name: Install E2E dependencies
|
||||||
|
run: pip install -r requirements-e2e.txt
|
||||||
|
- name: Run API E2E
|
||||||
|
run: pytest tests/e2e/api -m e2e -q --timeout=120
|
||||||
|
- name: Run pipeline E2E (non-ML)
|
||||||
|
run: pytest tests/e2e/pipeline -m "e2e and not ml" -q --timeout=120
|
||||||
|
|
||||||
|
# Dashboard E2E (Playwright). The container already ships Node 20 + npm + git,
|
||||||
|
# so actions/setup-node and actions/cache are deliberately NOT used (their
|
||||||
|
# Node download / cache endpoints time out against the act runner:
|
||||||
|
# "connect ETIMEDOUT 172.27.0.4:41759"). Playwright is retry-free by config;
|
||||||
|
# install browsers fresh each run.
|
||||||
|
dashboard-e2e:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 30
|
||||||
|
container: nikolaik/python-nodejs:python3.11-nodejs20
|
||||||
defaults:
|
defaults:
|
||||||
run:
|
run:
|
||||||
working-directory: dashboard
|
working-directory: dashboard
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: actions/setup-node@v4
|
- name: Install ffmpeg (E2E media fixture)
|
||||||
with:
|
run: apt-get update -qq && apt-get install -y -qq --no-install-recommends ffmpeg
|
||||||
node-version: "20"
|
|
||||||
cache: npm
|
|
||||||
cache-dependency-path: dashboard/package-lock.json
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: npm ci
|
run: npm ci
|
||||||
|
- name: Install Playwright browsers
|
||||||
|
run: npx playwright install --with-deps chromium
|
||||||
|
- name: Lint
|
||||||
|
run: npm run lint
|
||||||
- name: Build
|
- name: Build
|
||||||
run: npm run build
|
run: npm run build
|
||||||
|
- name: Browser E2E
|
||||||
|
run: npm run test:e2e
|
||||||
|
|
|
||||||
22
.gitignore
vendored
|
|
@ -12,11 +12,8 @@
|
||||||
__pycache__/
|
__pycache__/
|
||||||
*.pyc
|
*.pyc
|
||||||
|
|
||||||
# Temporary files / runtime dirs
|
# Runtime dirs
|
||||||
temp_*
|
|
||||||
uploads/
|
uploads/
|
||||||
downloads/
|
|
||||||
videos/
|
|
||||||
output/
|
output/
|
||||||
|
|
||||||
# OS / IDE
|
# OS / IDE
|
||||||
|
|
@ -34,20 +31,7 @@ output/
|
||||||
.cache/
|
.cache/
|
||||||
.config/
|
.config/
|
||||||
.pytest_cache/
|
.pytest_cache/
|
||||||
|
.ruff_cache/
|
||||||
|
|
||||||
# Multi-agent Skills
|
# Agent / tool local state
|
||||||
.agents/
|
|
||||||
.agent/
|
|
||||||
.claude/
|
|
||||||
|
|
||||||
# Design-tool / agent-local state
|
|
||||||
.hallmark/
|
|
||||||
.opencode/
|
.opencode/
|
||||||
|
|
||||||
|
|
||||||
# Cloud env example kept local only (avoid leaking infra hints)
|
|
||||||
.env.cloud.example
|
|
||||||
.worktrees
|
|
||||||
|
|
||||||
# Instrucciones locales con datos de infra (repo público)
|
|
||||||
CLAUDE.local.md
|
|
||||||
|
|
|
||||||
|
|
@ -106,13 +106,11 @@ clipwright/ # Python backend package
|
||||||
core/ # shared helpers (security, filesystem paths)
|
core/ # shared helpers (security, filesystem paths)
|
||||||
api/ # FastAPI app, auth, free tools
|
api/ # FastAPI app, auth, free tools
|
||||||
pipeline/ # download → transcribe → clip orchestration, Gemini, quality probe
|
pipeline/ # download → transcribe → clip orchestration, Gemini, quality probe
|
||||||
layouts/ # reframing: active speaker, split/screencast/panel, punch-in
|
layouts/ # reframing: active speaker, split/screencast, punch-in
|
||||||
media/ # FFmpeg helpers, subtitles, hooks, thumbnails, recut
|
media/ # FFmpeg helpers, subtitles, hooks, thumbnails, recut
|
||||||
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)
|
||||||
remotion/ # Remotion compositions used by the renderer
|
|
||||||
render-service/ # Node render microservice (its own Dockerfile)
|
|
||||||
cli/ # published `clipwright` HTTP client (own pyproject)
|
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)
|
||||||
|
|
|
||||||
|
|
@ -1472,9 +1472,11 @@ async def lifespan(app: FastAPI):
|
||||||
_install_drain_signal_handler()
|
_install_drain_signal_handler()
|
||||||
asyncio.create_task(_handover_watch())
|
asyncio.create_task(_handover_watch())
|
||||||
asyncio.create_task(_resume_scan())
|
asyncio.create_task(_resume_scan())
|
||||||
# Start worker and cleanup
|
# Start worker and cleanup. The assignments are load-bearing: asyncio holds
|
||||||
worker_task = asyncio.create_task(process_queue())
|
# no strong reference to a task, so dropping these lets the worker and the
|
||||||
cleanup_task = asyncio.create_task(cleanup_jobs())
|
# cleanup loop be garbage-collected mid-run.
|
||||||
|
_worker_task = asyncio.create_task(process_queue())
|
||||||
|
_cleanup_task = asyncio.create_task(cleanup_jobs())
|
||||||
yield
|
yield
|
||||||
# Cleanup (optional: cancel worker)
|
# Cleanup (optional: cancel worker)
|
||||||
|
|
||||||
|
|
@ -1625,7 +1627,6 @@ async def run_job(job_id, job_data):
|
||||||
t_log.start()
|
t_log.start()
|
||||||
|
|
||||||
# Async wait for process with incremental updates
|
# Async wait for process with incremental updates
|
||||||
start_wait = time.time()
|
|
||||||
last_heartbeat = time.time()
|
last_heartbeat = time.time()
|
||||||
while process.poll() is None:
|
while process.poll() is None:
|
||||||
try:
|
try:
|
||||||
|
|
@ -1679,7 +1680,7 @@ async def run_job(job_id, job_data):
|
||||||
|
|
||||||
if ready_clips:
|
if ready_clips:
|
||||||
jobs[job_id]['result'] = {'clips': ready_clips, 'cost_analysis': cost_analysis}
|
jobs[job_id]['result'] = {'clips': ready_clips, 'cost_analysis': cost_analysis}
|
||||||
except Exception as e:
|
except Exception:
|
||||||
# Ignore read errors during processing
|
# Ignore read errors during processing
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
@ -3388,10 +3389,6 @@ async def _reframe_locked(req: ReframeRequest, request: Request, job, overrides)
|
||||||
framing = (clip.get('recipe') or {}).get('framing') or 'auto'
|
framing = (clip.get('recipe') or {}).get('framing') or 'auto'
|
||||||
force_strategy = _FRAMING_STRATEGIES.get(framing)
|
force_strategy = _FRAMING_STRATEGIES.get(framing)
|
||||||
|
|
||||||
# A reframe re-renders the full cut from source — same work as a source-path
|
|
||||||
# rerender.
|
|
||||||
total = recut.total_duration(segments)
|
|
||||||
|
|
||||||
# Every default clip ships with burned captions; re-rendering without them
|
# Every default clip ships with burned captions; re-rendering without them
|
||||||
# would silently hand back a caption-less file.
|
# would silently hand back a caption-less file.
|
||||||
v_transcript = (recut.virtual_transcript(data.get('transcript') or {}, segments)
|
v_transcript = (recut.virtual_transcript(data.get('transcript') or {}, segments)
|
||||||
|
|
@ -3455,35 +3452,6 @@ async def _reframe_locked(req: ReframeRequest, request: Request, job, overrides)
|
||||||
raise HTTPException(status_code=500, detail=str(e))
|
raise HTTPException(status_code=500, detail=str(e))
|
||||||
|
|
||||||
|
|
||||||
# --- Remotion Render Proxy ---
|
|
||||||
RENDER_SERVICE_URL = os.getenv("RENDER_SERVICE_URL", "http://renderer:3100")
|
|
||||||
@app.post("/api/render")
|
|
||||||
async def proxy_render(request: Request):
|
|
||||||
"""Proxy render requests to the Node.js Remotion render service."""
|
|
||||||
import httpx
|
|
||||||
body = await request.json()
|
|
||||||
try:
|
|
||||||
async with httpx.AsyncClient(timeout=30.0) as client:
|
|
||||||
resp = await client.post(f"{RENDER_SERVICE_URL}/render", json=body)
|
|
||||||
return resp.json()
|
|
||||||
except Exception as e:
|
|
||||||
raise HTTPException(status_code=502, detail=f"Render service unavailable: {e}")
|
|
||||||
|
|
||||||
@app.get("/api/render/{render_id}")
|
|
||||||
async def proxy_render_status(render_id: str, request: Request):
|
|
||||||
"""Proxy render status polling to the Node.js Remotion render service."""
|
|
||||||
import httpx
|
|
||||||
# The id goes into the upstream path: ids are uuids, nothing else passes.
|
|
||||||
if not re.fullmatch(r"[A-Za-z0-9-]{1,64}", render_id or ""):
|
|
||||||
raise HTTPException(status_code=404, detail="Not found")
|
|
||||||
try:
|
|
||||||
async with httpx.AsyncClient(timeout=10.0) as client:
|
|
||||||
resp = await client.get(f"{RENDER_SERVICE_URL}/render/{render_id}")
|
|
||||||
return resp.json()
|
|
||||||
except Exception as e:
|
|
||||||
raise HTTPException(status_code=502, detail=f"Render service unavailable: {e}")
|
|
||||||
|
|
||||||
|
|
||||||
class EffectsGenerateRequest(BaseModel):
|
class EffectsGenerateRequest(BaseModel):
|
||||||
job_id: str
|
job_id: str
|
||||||
clip_index: int
|
clip_index: int
|
||||||
|
|
|
||||||
|
|
@ -11,23 +11,18 @@ This subclass keeps everything ``StaticFiles`` does (Range requests, ETags,
|
||||||
HEAD) and adds one step before the filesystem: ``guard`` (the allowlist,
|
HEAD) and adds one step before the filesystem: ``guard`` (the allowlist,
|
||||||
``media_auth.is_servable``, wrapped by ``app._media_guard``) refuses a path, and
|
``media_auth.is_servable``, wrapped by ``app._media_guard``) refuses a path, and
|
||||||
a refused path looks exactly like a missing one. ``app.py`` mounts it with the
|
a refused path looks exactly like a missing one. ``app.py`` mounts it with the
|
||||||
guard only -- there is no restorer in this fork.
|
guard only.
|
||||||
|
|
||||||
The optional ``restorer`` hook predates the self-host fork: it let a miss ask a
|
|
||||||
job's durable copy (R2) to come back before answering 404. Nothing wires one up
|
|
||||||
any more; the parameter is kept because callers and tests may still pass one.
|
|
||||||
"""
|
"""
|
||||||
from typing import Awaitable, Callable, Optional
|
from typing import Callable, Optional
|
||||||
|
|
||||||
from starlette.exceptions import HTTPException
|
from starlette.exceptions import HTTPException
|
||||||
from starlette.staticfiles import StaticFiles
|
from starlette.staticfiles import StaticFiles
|
||||||
|
|
||||||
Restorer = Callable[[str], Awaitable[bool]]
|
|
||||||
Guard = Callable[[str], bool]
|
Guard = Callable[[str], bool]
|
||||||
|
|
||||||
|
|
||||||
class RestoringStaticFiles(StaticFiles):
|
class RestoringStaticFiles(StaticFiles):
|
||||||
"""StaticFiles that refuses non-deliverables, with an optional restore hook.
|
"""StaticFiles that refuses non-deliverables.
|
||||||
|
|
||||||
``guard`` is the allowlist (``media_auth.is_servable``). Without it this
|
``guard`` is the allowlist (``media_auth.is_servable``). Without it this
|
||||||
mount hands out the whole working directory to anyone holding the job id:
|
mount hands out the whole working directory to anyone holding the job id:
|
||||||
|
|
@ -38,14 +33,11 @@ class RestoringStaticFiles(StaticFiles):
|
||||||
|
|
||||||
This is only the path half of media_auth: the clips themselves, and the
|
This is only the path half of media_auth: the clips themselves, and the
|
||||||
untouched source video sitting in the same directory, are still public to
|
untouched source video sitting in the same directory, are still public to
|
||||||
anyone who has the job id. ``restorer`` is not wired up in this fork; see
|
anyone who has the job id.
|
||||||
the module docstring.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, *args, restorer: Optional[Restorer] = None,
|
def __init__(self, *args, guard: Optional[Guard] = None, **kwargs):
|
||||||
guard: Optional[Guard] = None, **kwargs):
|
|
||||||
super().__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
self.restorer = restorer
|
|
||||||
self.guard = guard
|
self.guard = guard
|
||||||
|
|
||||||
async def get_response(self, path: str, scope):
|
async def get_response(self, path: str, scope):
|
||||||
|
|
@ -53,23 +45,4 @@ class RestoringStaticFiles(StaticFiles):
|
||||||
# missing one, or the 404-vs-403 difference confirms the file is there.
|
# missing one, or the 404-vs-403 difference confirms the file is there.
|
||||||
if self.guard is not None and not self.guard(path):
|
if self.guard is not None and not self.guard(path):
|
||||||
raise HTTPException(status_code=404)
|
raise HTTPException(status_code=404)
|
||||||
try:
|
return await super().get_response(path, scope)
|
||||||
return await super().get_response(path, scope)
|
|
||||||
except HTTPException as exc:
|
|
||||||
if exc.status_code != 404 or self.restorer is None:
|
|
||||||
raise
|
|
||||||
job_id = path.split("/", 1)[0] if "/" in path else ""
|
|
||||||
if not job_id:
|
|
||||||
raise
|
|
||||||
try:
|
|
||||||
restored = await self.restorer(job_id)
|
|
||||||
except Exception:
|
|
||||||
restored = False
|
|
||||||
if not restored:
|
|
||||||
raise
|
|
||||||
# The guard may read the job directory (a free job's clean twins
|
|
||||||
# are refused by a marker file that only exists once the files
|
|
||||||
# are back), so the verdict before the restore is not final.
|
|
||||||
if self.guard is not None and not self.guard(path):
|
|
||||||
raise HTTPException(status_code=404)
|
|
||||||
return await super().get_response(path, scope)
|
|
||||||
|
|
|
||||||
|
|
@ -11,21 +11,16 @@ from __future__ import annotations
|
||||||
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
# .../clipwright
|
# .../clipwright (kept private: only used below to locate REPO_ROOT)
|
||||||
PACKAGE_DIR = Path(__file__).resolve().parent.parent
|
PACKAGE_DIR = Path(__file__).resolve().parent.parent
|
||||||
# Repository root (also the Docker WORKDIR /app).
|
# Repository root (also the Docker WORKDIR /app).
|
||||||
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"
|
ASSETS_DIR = REPO_ROOT / "assets"
|
||||||
UPLOADS_DIR = REPO_ROOT / "uploads"
|
|
||||||
OUTPUT_DIR = REPO_ROOT / "output"
|
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
"PACKAGE_DIR",
|
|
||||||
"REPO_ROOT",
|
"REPO_ROOT",
|
||||||
"FONTS_DIR",
|
"FONTS_DIR",
|
||||||
"ASSETS_DIR",
|
"ASSETS_DIR",
|
||||||
"UPLOADS_DIR",
|
|
||||||
"OUTPUT_DIR",
|
|
||||||
]
|
]
|
||||||
|
|
|
||||||
|
|
@ -14,25 +14,6 @@ import socket
|
||||||
from urllib.parse import urlparse
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
|
||||||
def truncate_ip(ip: str) -> str:
|
|
||||||
"""Drop the host part of an address so it identifies a network, not a device.
|
|
||||||
|
|
||||||
Used for the rights declaration kept with a project (art. 5.1.c: the record
|
|
||||||
has to show the confirmation was made from somewhere at some time, which a
|
|
||||||
/24 answers as well as a full address, and it does not hand anyone a
|
|
||||||
per-device identifier that survives for years). IPv4 keeps three octets,
|
|
||||||
IPv6 keeps the /48 the RIRs actually assign. Anything unparseable becomes
|
|
||||||
"unknown" rather than being stored verbatim.
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
addr = ipaddress.ip_address((ip or "").strip())
|
|
||||||
except ValueError:
|
|
||||||
return "unknown"
|
|
||||||
if addr.version == 4:
|
|
||||||
return str(ipaddress.ip_network(f"{addr}/24", strict=False).network_address)
|
|
||||||
return str(ipaddress.ip_network(f"{addr}/48", strict=False).network_address)
|
|
||||||
|
|
||||||
|
|
||||||
class UnsafeURLError(ValueError):
|
class UnsafeURLError(ValueError):
|
||||||
"""Raised when a URL is not safe to fetch server-side."""
|
"""Raised when a URL is not safe to fetch server-side."""
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -251,7 +251,6 @@ def decode_activity(video_path, start_s, duration_s, boxes, fps,
|
||||||
small_h = max(int(orig_h * small_w / orig_w), 2)
|
small_h = max(int(orig_h * small_w / orig_w), 2)
|
||||||
small_h += small_h % 2
|
small_h += small_h % 2
|
||||||
scale = orig_w / float(small_w)
|
scale = orig_w / float(small_w)
|
||||||
frame_bytes = small_w * small_h * 3
|
|
||||||
|
|
||||||
regions = [mouth_region(b, small_w, small_h, scale) for b in boxes]
|
regions = [mouth_region(b, small_w, small_h, scale) for b in boxes]
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -15,7 +15,6 @@ Whoever updates a clip's metadata copies them into ``layout_ranges`` so
|
||||||
/api/subtitle can find them after the sidecar is gone.
|
/api/subtitle can find them after the sidecar is gone.
|
||||||
"""
|
"""
|
||||||
import json
|
import json
|
||||||
import os
|
|
||||||
|
|
||||||
SIDECAR_SUFFIX = ".layout.json"
|
SIDECAR_SUFFIX = ".layout.json"
|
||||||
|
|
||||||
|
|
@ -71,10 +70,6 @@ def split_ranges(ranges):
|
||||||
return [(r["start"], r["end"]) for r in normalise(ranges) if r["layout"] == "split"]
|
return [(r["start"], r["end"]) for r in normalise(ranges) if r["layout"] == "split"]
|
||||||
|
|
||||||
|
|
||||||
def in_split(t, splits):
|
|
||||||
return any(s <= t < e for s, e in splits or [])
|
|
||||||
|
|
||||||
|
|
||||||
def remap(ranges, segments):
|
def remap(ranges, segments):
|
||||||
"""Carry ranges across a cut-and-concat. ``segments`` are the kept
|
"""Carry ranges across a cut-and-concat. ``segments`` are the kept
|
||||||
stretches of the SOURCE file in order ({"start", "end"}); the output is
|
stretches of the SOURCE file in order ({"start", "end"}); the output is
|
||||||
|
|
|
||||||
|
|
@ -1,274 +0,0 @@
|
||||||
"""PANEL layout: three or four people from one wide shot, tiled into 9:16.
|
|
||||||
|
|
||||||
The generalisation of split_layout past two people. A round table, a debate set
|
|
||||||
or a podcast with guests is a single wide shot where TRACK picks one person and
|
|
||||||
GENERAL shrinks everyone to a strip. OpusClip ships "Three" and "Four" layouts
|
|
||||||
for exactly this and we had nothing.
|
|
||||||
|
|
||||||
Geometry, for a 1080x1920 output:
|
|
||||||
|
|
||||||
3 people three stacked bands, 1080x640 each
|
|
||||||
4 people a 2x2 grid, 540x960 each
|
|
||||||
|
|
||||||
Three stacked rather than 2+1, because an odd tile reads as a mistake; four as a
|
|
||||||
grid rather than four bands, because a 1080x480 band is a letterbox slot nobody
|
|
||||||
fits in. Both keep every tile the same size: a bigger tile silently claims the
|
|
||||||
person in it is the important one, and the layout has no way to know that.
|
|
||||||
|
|
||||||
Off by default (``PANEL_LAYOUT=1``). Shares split_layout's rules, because the
|
|
||||||
failure modes are the same ones: faces must COEXIST in the frame (otherwise it
|
|
||||||
is a multi-camera cut and tiling would show one person several times), be far
|
|
||||||
enough apart, and be big enough not to be an audience.
|
|
||||||
"""
|
|
||||||
import os
|
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
|
|
||||||
from clipwright.layouts import split_layout
|
|
||||||
|
|
||||||
ENABLED = os.environ.get("PANEL_LAYOUT", "0") == "1"
|
|
||||||
|
|
||||||
# How many people this layout will lay out. Five-plus is a crowd: at 1080 wide
|
|
||||||
# each tile drops under 400px tall and nobody is legible, so those scenes are
|
|
||||||
# better served by GENERAL keeping the room intact.
|
|
||||||
MIN_PEOPLE = 3
|
|
||||||
MAX_PEOPLE = 4
|
|
||||||
|
|
||||||
# Same bar as SPLIT: the tiles must be showing different people at the same
|
|
||||||
# moment, not the same person across cuts.
|
|
||||||
MIN_COEXISTENCE = split_layout.MIN_COEXISTENCE
|
|
||||||
MIN_FACE_WIDTH = split_layout.MIN_FACE_WIDTH
|
|
||||||
MIN_SCENE_SECONDS = split_layout.MIN_SCENE_SECONDS
|
|
||||||
|
|
||||||
# Minimum gap between neighbouring faces, as a fraction of frame width. Lower
|
|
||||||
# than SPLIT's 0.20 because four people in one shot genuinely sit closer
|
|
||||||
# together; below this they overlap and the tiles repeat shoulders.
|
|
||||||
MIN_SEPARATION = 0.12
|
|
||||||
|
|
||||||
PANEL_TIGHTNESS = float(os.environ.get("PANEL_TIGHTNESS", "0.85"))
|
|
||||||
|
|
||||||
|
|
||||||
def tile_grid(count, out_w, out_h):
|
|
||||||
"""(columns, rows, tile_w, tile_h). Always a 2x2 grid, for 3 people or 4.
|
|
||||||
|
|
||||||
Three horizontal bands was the obvious shape and it does not work. A
|
|
||||||
1080x640 band is LANDSCAPE, so filling it from a 1080-tall source needs a
|
|
||||||
1551px-wide crop; on a 1920 frame holding three people that reaches both
|
|
||||||
neighbours, and the rendered bands each showed two faces. Clamping the crop
|
|
||||||
to the space a person owns then made it 328x194, upscaled 3.3x into a
|
|
||||||
blurry close-up of a nose.
|
|
||||||
|
|
||||||
A 2x2 grid has PORTRAIT tiles (540x960), which ask for a tall narrow crop
|
|
||||||
— the shape a person actually occupies. Three people use three cells and
|
|
||||||
the fourth holds the wide shot, which doubles as context for who is in the
|
|
||||||
room.
|
|
||||||
"""
|
|
||||||
cols, rows = 2, 2
|
|
||||||
tile_w = out_w // cols
|
|
||||||
tile_h = out_h // rows
|
|
||||||
return cols, rows, tile_w - (tile_w % 2), tile_h - (tile_h % 2)
|
|
||||||
|
|
||||||
|
|
||||||
def usable_faces(candidates, frame_w):
|
|
||||||
"""Faces big enough to be participants, deduped, left to right.
|
|
||||||
|
|
||||||
Deduping because this layout decides by headcount and nothing upstream
|
|
||||||
guarantees one box per head.
|
|
||||||
"""
|
|
||||||
big = [c for c in split_layout.dedupe_faces(candidates)
|
|
||||||
if c['box'][2] >= MIN_FACE_WIDTH * frame_w]
|
|
||||||
big.sort(key=lambda c: c['box'][0])
|
|
||||||
return big
|
|
||||||
|
|
||||||
|
|
||||||
def well_separated(faces, frame_w, min_gap=MIN_SEPARATION):
|
|
||||||
"""True when every pair of faces is far enough apart to be distinct people.
|
|
||||||
|
|
||||||
Distance between centres, not horizontal gap. Participants are not always
|
|
||||||
in a row: a shot measured on a real recording had two people stacked one
|
|
||||||
above the other on the same side of the frame, 18px apart horizontally and
|
|
||||||
545px vertically. Judging by horizontal gap alone called them the same
|
|
||||||
person and threw the scene away.
|
|
||||||
"""
|
|
||||||
threshold = min_gap * frame_w
|
|
||||||
for i, a in enumerate(faces):
|
|
||||||
ax = a['box'][0] + a['box'][2] / 2.0
|
|
||||||
ay = a['box'][1] + a['box'][3] / 2.0
|
|
||||||
for b in faces[i + 1:]:
|
|
||||||
bx = b['box'][0] + b['box'][2] / 2.0
|
|
||||||
by = b['box'][1] + b['box'][3] / 2.0
|
|
||||||
if ((ax - bx) ** 2 + (ay - by) ** 2) ** 0.5 < threshold:
|
|
||||||
return False
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
def analyze_scene(frames, frame_w):
|
|
||||||
"""Median centres for a stable panel of 3-4 people, or None.
|
|
||||||
|
|
||||||
``frames`` is a list of per-frame candidate lists, as
|
|
||||||
``main.detect_face_candidates`` returns them.
|
|
||||||
"""
|
|
||||||
if not frames:
|
|
||||||
return None
|
|
||||||
|
|
||||||
per_count = {}
|
|
||||||
for candidates in frames:
|
|
||||||
faces = usable_faces(candidates, frame_w)
|
|
||||||
if not (MIN_PEOPLE <= len(faces) <= MAX_PEOPLE):
|
|
||||||
continue
|
|
||||||
if not well_separated(faces, frame_w):
|
|
||||||
continue
|
|
||||||
per_count.setdefault(len(faces), []).append(
|
|
||||||
[split_layout._centre(c['box']) for c in faces])
|
|
||||||
|
|
||||||
if not per_count:
|
|
||||||
return None
|
|
||||||
|
|
||||||
# Take the headcount that held for longest; a frame where one head turned
|
|
||||||
# away should not decide the layout.
|
|
||||||
count = max(per_count, key=lambda k: len(per_count[k]))
|
|
||||||
seen = per_count[count]
|
|
||||||
if len(seen) < MIN_COEXISTENCE * len(frames):
|
|
||||||
return None
|
|
||||||
|
|
||||||
arr = np.array(seen, dtype=float) # (samples, people, 4)
|
|
||||||
return [tuple(float(v) for v in person) for person in np.median(arr, axis=0)]
|
|
||||||
|
|
||||||
|
|
||||||
def panel_geometry(orig_w, orig_h, tile_w, tile_h, centre, tightness=None,
|
|
||||||
neighbour_gap=None):
|
|
||||||
"""Crop (w, h, x, y) framing one person for one tile.
|
|
||||||
|
|
||||||
``neighbour_gap`` is the distance to the closest other participant. It is
|
|
||||||
the binding constraint and not an optional refinement: a three-band layout
|
|
||||||
has 1080x640 tiles, which are LANDSCAPE, so filling one from a 1080-tall
|
|
||||||
source asks for a 1551px-wide crop. On a 1920px frame holding three people
|
|
||||||
that swallows the neighbours, and the rendered bands showed two faces each.
|
|
||||||
Clamping the crop to the space a person actually owns fixes the framing at
|
|
||||||
the cost of upscaling, which is the right trade: a band showing the wrong
|
|
||||||
person is broken, a soft one is merely worse.
|
|
||||||
"""
|
|
||||||
tightness = PANEL_TIGHTNESS if tightness is None else tightness
|
|
||||||
aspect = tile_w / float(tile_h)
|
|
||||||
|
|
||||||
crop_h = int(round(orig_h * max(0.3, min(tightness, 1.0))))
|
|
||||||
crop_w = int(round(crop_h * aspect))
|
|
||||||
if crop_w > orig_w:
|
|
||||||
crop_w = orig_w
|
|
||||||
crop_h = int(round(crop_w / aspect))
|
|
||||||
|
|
||||||
if neighbour_gap:
|
|
||||||
# 0.9 leaves a sliver of margin: cropping exactly to the midpoint puts
|
|
||||||
# the neighbour's shoulder on the edge of the tile.
|
|
||||||
allowed = max(int(neighbour_gap * 0.9), 2)
|
|
||||||
if crop_w > allowed:
|
|
||||||
crop_w = allowed
|
|
||||||
crop_h = int(round(crop_w / aspect))
|
|
||||||
crop_w -= crop_w % 2
|
|
||||||
crop_h -= crop_h % 2
|
|
||||||
|
|
||||||
cx, cy = centre[0], centre[1]
|
|
||||||
x = max(0, min(int(round(cx - crop_w / 2.0)), orig_w - crop_w))
|
|
||||||
y = max(0, min(int(round(cy - crop_h * 0.42)), orig_h - crop_h))
|
|
||||||
return crop_w, crop_h, x - (x % 2), y - (y % 2)
|
|
||||||
|
|
||||||
|
|
||||||
def neighbour_gaps(centres):
|
|
||||||
"""Horizontal distance from each person to their closest neighbour."""
|
|
||||||
xs = [c[0] for c in centres]
|
|
||||||
gaps = []
|
|
||||||
for i, x in enumerate(xs):
|
|
||||||
others = [abs(x - o) for j, o in enumerate(xs) if j != i]
|
|
||||||
gaps.append(min(others) if others else None)
|
|
||||||
return gaps
|
|
||||||
|
|
||||||
|
|
||||||
def panel_filtergraph(orig_w, orig_h, out_w, out_h, centres):
|
|
||||||
"""Tile 3 or 4 people into the vertical frame, left-to-right, top-to-bottom."""
|
|
||||||
count = len(centres)
|
|
||||||
cols, rows, tile_w, tile_h = tile_grid(count, out_w, out_h)
|
|
||||||
|
|
||||||
gaps = neighbour_gaps(centres)
|
|
||||||
streams = count if count == 4 else count + 1 # trio needs the wide shot
|
|
||||||
|
|
||||||
parts = [f"[0:v]split={streams}"
|
|
||||||
+ "".join(f"[s{i}]" for i in range(streams)) + ";"]
|
|
||||||
for i, centre in enumerate(centres):
|
|
||||||
cw, ch, cx, cy = panel_geometry(orig_w, orig_h, tile_w, tile_h, centre,
|
|
||||||
neighbour_gap=gaps[i])
|
|
||||||
parts.append(f"[s{i}]crop=w={cw}:h={ch}:x={cx}:y={cy},"
|
|
||||||
f"scale={tile_w}:{tile_h}[t{i}];")
|
|
||||||
|
|
||||||
if count == 3:
|
|
||||||
# Fourth cell: the room, letterboxed inside the tile so nothing is cut.
|
|
||||||
parts.append(f"[s3]scale={tile_w}:-2,"
|
|
||||||
f"pad={tile_w}:{tile_h}:0:({tile_h}-ih)/2:black[t3];")
|
|
||||||
|
|
||||||
parts.append("[t0][t1]hstack=inputs=2[top];"
|
|
||||||
"[t2][t3]hstack=inputs=2[bot];"
|
|
||||||
"[top][bot]vstack=inputs=2,")
|
|
||||||
parts.append(f"pad={out_w}:{out_h}:0:0,setsar=1[v]")
|
|
||||||
return "".join(parts)
|
|
||||||
|
|
||||||
|
|
||||||
def detect_panel_scenes(video_path, scenes, strategies, samples=None):
|
|
||||||
"""Scenes to render as PANEL: ``{scene_index: [centres]}``.
|
|
||||||
|
|
||||||
Only scenes the classifier already sent to GENERAL are considered, for the
|
|
||||||
same reason SPLIT does it: GENERAL already means "more than one face", and
|
|
||||||
single-speaker material is most of the corpus and must not be touched.
|
|
||||||
"""
|
|
||||||
if not ENABLED:
|
|
||||||
return {}
|
|
||||||
# Below the gate on purpose: main pulls torch/mediapipe, and the disabled
|
|
||||||
# path (the default, and what CI exercises) must not pay that import.
|
|
||||||
import cv2
|
|
||||||
from clipwright.pipeline import main as m
|
|
||||||
|
|
||||||
cap = cv2.VideoCapture(video_path)
|
|
||||||
if not cap.isOpened():
|
|
||||||
return {}
|
|
||||||
|
|
||||||
fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
|
|
||||||
frame_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
|
||||||
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) or 0
|
|
||||||
found = {}
|
|
||||||
|
|
||||||
try:
|
|
||||||
for i, (start, end) in enumerate(scenes):
|
|
||||||
if i < len(strategies) and strategies[i] != 'GENERAL':
|
|
||||||
continue
|
|
||||||
s_f, e_f = start.get_frames(), end.get_frames()
|
|
||||||
duration = (e_f - s_f) / fps
|
|
||||||
if duration < MIN_SCENE_SECONDS:
|
|
||||||
continue
|
|
||||||
|
|
||||||
n = samples or int(min(max(duration / split_layout.SECONDS_PER_SAMPLE,
|
|
||||||
split_layout.MIN_SAMPLES),
|
|
||||||
split_layout.MAX_SAMPLES))
|
|
||||||
last_f = e_f - 1
|
|
||||||
if total_frames:
|
|
||||||
last_f = min(last_f, total_frames - 1)
|
|
||||||
if last_f < s_f:
|
|
||||||
continue
|
|
||||||
|
|
||||||
sampled = []
|
|
||||||
for f_idx in np.linspace(s_f, last_f, n):
|
|
||||||
cap.set(cv2.CAP_PROP_POS_FRAMES, int(round(f_idx)))
|
|
||||||
ok, frame = cap.read()
|
|
||||||
if not ok:
|
|
||||||
continue
|
|
||||||
if frame.mean() < 16:
|
|
||||||
continue
|
|
||||||
sampled.append(m.detect_face_candidates(frame))
|
|
||||||
|
|
||||||
if len(sampled) < max(4, n // 2):
|
|
||||||
continue
|
|
||||||
|
|
||||||
centres = analyze_scene(sampled, frame_w)
|
|
||||||
if centres:
|
|
||||||
found[i] = centres
|
|
||||||
finally:
|
|
||||||
cap.release()
|
|
||||||
|
|
||||||
return found
|
|
||||||
|
|
@ -65,25 +65,6 @@ class VideoEditor:
|
||||||
raise TimeoutError("Gemini file processing timed out after 120s.")
|
raise TimeoutError("Gemini file processing timed out after 120s.")
|
||||||
time.sleep(2)
|
time.sleep(2)
|
||||||
|
|
||||||
def delete_uploaded(self, video_file_obj):
|
|
||||||
"""Remove an uploaded clip from the Gemini Files API.
|
|
||||||
|
|
||||||
The upload is a full copy of the user's video on Google's servers, kept
|
|
||||||
there for 48 h if nobody deletes it. The effects passes need it for one
|
|
||||||
request; every caller must drop it in a ``finally`` right after, so the
|
|
||||||
privacy policy's "we do not leave your footage with the model provider"
|
|
||||||
describes the code. Best-effort: an editing job must not fail because
|
|
||||||
the cleanup call did.
|
|
||||||
"""
|
|
||||||
name = getattr(video_file_obj, "name", None)
|
|
||||||
if not name:
|
|
||||||
return
|
|
||||||
try:
|
|
||||||
self.client.files.delete(name=name)
|
|
||||||
except Exception as e:
|
|
||||||
print(f"⚠️ Could not delete {name} from Gemini Files ({e}) — "
|
|
||||||
f"it expires there in 48 h.")
|
|
||||||
|
|
||||||
def get_ffmpeg_filter(self, video_file_obj, duration, fps=30, width=None, height=None, transcript=None, has_captions=False):
|
def get_ffmpeg_filter(self, video_file_obj, duration, fps=30, width=None, height=None, transcript=None, has_captions=False):
|
||||||
"""Asks Gemini for an edit decision list, then builds the FFmpeg filter
|
"""Asks Gemini for an edit decision list, then builds the FFmpeg filter
|
||||||
deterministically (edit_builder) so syntax and zoom limits are always safe."""
|
deterministically (edit_builder) so syntax and zoom limits are always safe."""
|
||||||
|
|
|
||||||
|
|
@ -85,55 +85,6 @@ METADATA_SCRUB = ["-map_metadata", "-1", "-map_chapters", "-1",
|
||||||
LOUDNORM_FILTER = "loudnorm=I=-14:TP=-2.0:LRA=11"
|
LOUDNORM_FILTER = "loudnorm=I=-14:TP=-2.0:LRA=11"
|
||||||
|
|
||||||
|
|
||||||
# AI Act art. 50(2): a provider whose system generates synthetic audio or video
|
|
||||||
# has to mark the output in a machine-readable way. The regulation asks for the
|
|
||||||
# marking, not for a particular standard, and the cheap one that survives every
|
|
||||||
# player and every upload is a container tag: `ffprobe -show_format` reads it
|
|
||||||
# back, and TikTok/Reels/YouTube ignore it. Stamped by a stream copy, so it is
|
|
||||||
# a remux (no quality loss, ~0.2 s) and never a re-encode.
|
|
||||||
#
|
|
||||||
# Deliberately narrow: it goes on outputs where a machine actually synthesised
|
|
||||||
# voice or a person (dubbing, AI actors), not on an ordinary clip, whose audio
|
|
||||||
# and pixels are the user's own footage. Marking everything would make the tag
|
|
||||||
# mean nothing.
|
|
||||||
AI_DISCLOSURE = "AI-generated content produced with Clipwright (git.pbento.pt/pedro-bento/clipwright)"
|
|
||||||
|
|
||||||
|
|
||||||
def mark_ai_generated(path, detail=""):
|
|
||||||
"""Stamp AI Act art. 50(2) machine-readable tags on a finished file.
|
|
||||||
|
|
||||||
Returns True when the file now carries the tags. Never raises: a missing
|
|
||||||
tag must not lose the user the video they just paid minutes for.
|
|
||||||
"""
|
|
||||||
note = f"{AI_DISCLOSURE}: {detail}" if detail else AI_DISCLOSURE
|
|
||||||
tmp = f"{path}.aitag.mp4"
|
|
||||||
# `comment` and not a custom `ai_generated` key: mp4 only carries the
|
|
||||||
# standard iTunes-style tags, and ffmpeg drops anything else without
|
|
||||||
# warning (verified with ffprobe -show_entries format_tags).
|
|
||||||
# -map 0 because ffmpeg's default picks one stream per type: a dubbed file
|
|
||||||
# that ever ships two audio tracks would come back with one.
|
|
||||||
cmd = ["ffmpeg", "-y", "-i", path, "-map", "0", "-c", "copy",
|
|
||||||
"-metadata", f"comment={note}",
|
|
||||||
"-movflags", "+faststart", tmp]
|
|
||||||
try:
|
|
||||||
r = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
|
|
||||||
if r.returncode != 0 or not os.path.exists(tmp) or os.path.getsize(tmp) == 0:
|
|
||||||
print(f"[ai-tag] skipped for {os.path.basename(path)}: {r.stderr[-300:]}")
|
|
||||||
if os.path.exists(tmp):
|
|
||||||
os.remove(tmp)
|
|
||||||
return False
|
|
||||||
os.replace(tmp, path)
|
|
||||||
return True
|
|
||||||
except Exception as e:
|
|
||||||
print(f"[ai-tag] skipped for {os.path.basename(path)}: {e}")
|
|
||||||
if os.path.exists(tmp):
|
|
||||||
try:
|
|
||||||
os.remove(tmp)
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def audio_encode_args():
|
def audio_encode_args():
|
||||||
"""AAC encode args for a delivered clip, with loudness normalisation."""
|
"""AAC encode args for a delivered clip, with loudness normalisation."""
|
||||||
args = ["-c:a", "aac"]
|
args = ["-c:a", "aac"]
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,5 @@
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import textwrap
|
|
||||||
import subprocess
|
import subprocess
|
||||||
import urllib.request
|
import urllib.request
|
||||||
import uuid
|
import uuid
|
||||||
|
|
@ -273,7 +272,6 @@ def create_hook_image(text, target_width, output_image_path="hook_overlay.png",
|
||||||
line_spacing = 20 # Increased spacing
|
line_spacing = 20 # Increased spacing
|
||||||
cornerradius = 20
|
cornerradius = 20
|
||||||
shadow_offset = (5, 5)
|
shadow_offset = (5, 5)
|
||||||
shadow_blur = 10
|
|
||||||
|
|
||||||
# Font Size Calculation (approx 5% of width - tuned to match Noto Serif Bold metrics in browser)
|
# Font Size Calculation (approx 5% of width - tuned to match Noto Serif Bold metrics in browser)
|
||||||
pills = bool(look.get("pills"))
|
pills = bool(look.get("pills"))
|
||||||
|
|
|
||||||
|
|
@ -17,7 +17,6 @@ Two render paths:
|
||||||
with the same engine the pipeline used.
|
with the same engine the pipeline used.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
|
||||||
import os
|
import os
|
||||||
import shutil
|
import shutil
|
||||||
import subprocess
|
import subprocess
|
||||||
|
|
|
||||||
|
|
@ -114,41 +114,6 @@ def _normalize_subtitle_word(value):
|
||||||
return " ".join(str(value or "").split())
|
return " ".join(str(value or "").split())
|
||||||
|
|
||||||
|
|
||||||
def transcribe_audio(video_path):
|
|
||||||
"""
|
|
||||||
Transcribe audio from a video file via the configured ASR backend.
|
|
||||||
Returns transcript in the same format as main.py for compatibility.
|
|
||||||
"""
|
|
||||||
# Lazy import: transcribe_backends imports helpers from this module.
|
|
||||||
from clipwright.pipeline.transcribe_backends import transcribe_media
|
|
||||||
|
|
||||||
_log(f"🎙️ Transcribing audio from: {video_path}")
|
|
||||||
transcript = transcribe_media(video_path)
|
|
||||||
_log(f"✅ Transcription complete. Language: {transcript['language']}")
|
|
||||||
return transcript
|
|
||||||
|
|
||||||
|
|
||||||
def generate_srt_from_video(video_path, output_path, max_chars=20, max_duration=2.0,
|
|
||||||
style="classic", **style_opts):
|
|
||||||
"""
|
|
||||||
Transcribe a video and generate a subtitle file directly (SRT, or karaoke
|
|
||||||
ASS when style="karaoke"). Used for dubbed videos without a transcript.
|
|
||||||
"""
|
|
||||||
transcript = transcribe_audio(video_path)
|
|
||||||
|
|
||||||
# Get video duration to use as clip_end
|
|
||||||
import cv2
|
|
||||||
cap = cv2.VideoCapture(video_path)
|
|
||||||
fps = cap.get(cv2.CAP_PROP_FPS)
|
|
||||||
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
|
||||||
duration = frame_count / fps if fps else 0
|
|
||||||
cap.release()
|
|
||||||
|
|
||||||
if style == "karaoke":
|
|
||||||
return generate_ass(transcript, 0, duration, output_path, max_chars, max_duration, **style_opts)
|
|
||||||
return generate_srt(transcript, 0, duration, output_path, max_chars, max_duration)
|
|
||||||
|
|
||||||
|
|
||||||
def _collect_word_blocks(transcript, clip_start, clip_end, max_chars=20, max_duration=2.0):
|
def _collect_word_blocks(transcript, clip_start, clip_end, max_chars=20, max_duration=2.0):
|
||||||
"""
|
"""
|
||||||
Flatten transcript words for a clip range and group them into short blocks
|
Flatten transcript words for a clip range and group them into short blocks
|
||||||
|
|
|
||||||
|
|
@ -522,8 +522,8 @@ def burn_thumbnail_text(img, text, position="left", color="white"):
|
||||||
# AI Act art. 50(2): a synthetic image has to be marked in a machine-readable
|
# AI Act art. 50(2): a synthetic image has to be marked in a machine-readable
|
||||||
# way, and these thumbnails are exactly the case the article is about — an
|
# way, and these thumbnails are exactly the case the article is about — an
|
||||||
# image model painting a scene, often around a reference photo of the real
|
# image model painting a scene, often around a reference photo of the real
|
||||||
# presenter. Videos get the mp4 `comment` tag (ffmpeg_utils.mark_ai_generated);
|
# presenter. Videos get an mp4 `comment` tag; a JPEG's equivalent is XMP, and
|
||||||
# a JPEG's equivalent is XMP, and the interoperable vocabulary is IPTC's
|
# the interoperable vocabulary is IPTC's
|
||||||
# DigitalSourceType, whose `trainedAlgorithmicMedia` value is what Google,
|
# DigitalSourceType, whose `trainedAlgorithmicMedia` value is what Google,
|
||||||
# LinkedIn, TikTok and Adobe already read. Written alongside the EXIF Software
|
# LinkedIn, TikTok and Adobe already read. Written alongside the EXIF Software
|
||||||
# tag because the two survive different pipelines: a re-encode usually keeps
|
# tag because the two survive different pipelines: a re-encode usually keeps
|
||||||
|
|
|
||||||
|
|
@ -77,10 +77,3 @@ def mark_job(job_dir: str) -> None:
|
||||||
f.write("1")
|
f.write("1")
|
||||||
except OSError:
|
except OSError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
def unmark_job(job_dir: str) -> None:
|
|
||||||
try:
|
|
||||||
os.remove(os.path.join(job_dir, MARKER_FILE))
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
|
|
|
||||||
|
|
@ -188,18 +188,6 @@ def clip_duration_bounds():
|
||||||
return round(lo, 3), round(hi, 3)
|
return round(lo, 3), round(hi, 3)
|
||||||
|
|
||||||
|
|
||||||
def compact_words(words, precision=2):
|
|
||||||
"""Round word timestamps for prompts — full float precision wastes tokens."""
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
"w": w.get("w", ""),
|
|
||||||
"s": round(float(w.get("s", 0)), precision),
|
|
||||||
"e": round(float(w.get("e", 0)), precision),
|
|
||||||
}
|
|
||||||
for w in words
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
def build_transcript_windows(transcript_result, video_duration,
|
def build_transcript_windows(transcript_result, video_duration,
|
||||||
window_seconds=90, overlap_seconds=30):
|
window_seconds=90, overlap_seconds=30):
|
||||||
"""
|
"""
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,3 @@
|
||||||
import argparse
|
|
||||||
import json
|
import json
|
||||||
import mimetypes
|
import mimetypes
|
||||||
import os
|
import os
|
||||||
|
|
@ -6,12 +5,10 @@ import sys
|
||||||
from typing import List, Optional
|
from typing import List, Optional
|
||||||
|
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
from google import genai
|
|
||||||
from google.genai import types as genai_types
|
from google.genai import types as genai_types
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
from clipwright.pipeline.clip_selection import (clip_count_targets, clip_duration_bounds,
|
from clipwright.pipeline.clip_selection import lookup_model_prices
|
||||||
lookup_model_prices)
|
|
||||||
|
|
||||||
load_dotenv()
|
load_dotenv()
|
||||||
|
|
||||||
|
|
@ -225,17 +222,6 @@ For "what", name the content in three words or fewer (e.g. "stock chart",
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
def _configure_stdio() -> None:
|
|
||||||
for stream_name in ("stdout", "stderr"):
|
|
||||||
stream = getattr(sys, stream_name, None)
|
|
||||||
if not stream or not hasattr(stream, "reconfigure"):
|
|
||||||
continue
|
|
||||||
try:
|
|
||||||
stream.reconfigure(encoding="utf-8", errors="replace")
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
def _log(message: str) -> None:
|
def _log(message: str) -> None:
|
||||||
stream = sys.stdout
|
stream = sys.stdout
|
||||||
text = str(message)
|
text = str(message)
|
||||||
|
|
@ -567,69 +553,4 @@ def _config_for_strategy(strategy: str, mode: str, model_name: str) -> genai_typ
|
||||||
return genai_types.GenerateContentConfig(**kwargs)
|
return genai_types.GenerateContentConfig(**kwargs)
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
|
||||||
_configure_stdio()
|
|
||||||
|
|
||||||
parser = argparse.ArgumentParser(description="Run a single Gemini request for clip scoring/detailing.")
|
|
||||||
parser.add_argument("--mode", choices=["score", "detail"], required=True)
|
|
||||||
parser.add_argument("--input", dest="input_path", required=True)
|
|
||||||
parser.add_argument("--output", dest="output_path", required=True)
|
|
||||||
parser.add_argument("--strategy", default="structured-schema")
|
|
||||||
parser.add_argument("--model", default="gemini-2.5-flash")
|
|
||||||
args = parser.parse_args()
|
|
||||||
|
|
||||||
api_key = os.getenv("GEMINI_API_KEY")
|
|
||||||
if not api_key:
|
|
||||||
raise SystemExit("Missing GEMINI_API_KEY.")
|
|
||||||
|
|
||||||
with open(args.input_path, "r", encoding="utf-8") as f:
|
|
||||||
payload = json.load(f)
|
|
||||||
|
|
||||||
model_name = args.model
|
|
||||||
client = genai.Client(api_key=api_key)
|
|
||||||
config = _config_for_strategy(args.strategy, args.mode, model_name)
|
|
||||||
language = str(payload.get("language") or "unknown")
|
|
||||||
|
|
||||||
template = SCORE_PROMPT_TEMPLATE if args.mode == "score" else DETAIL_PROMPT_TEMPLATE
|
|
||||||
fmt = {
|
|
||||||
"video_duration": payload["video_duration"],
|
|
||||||
"language": language,
|
|
||||||
"windows_json": json.dumps(payload["windows"], ensure_ascii=False),
|
|
||||||
}
|
|
||||||
if args.mode != "score":
|
|
||||||
# Score mode receives every window, not a shortlist, so a count target
|
|
||||||
# derived from it would be meaningless — and the score template has no
|
|
||||||
# placeholder for one: it ranks whatever it is given.
|
|
||||||
fmt["min_clips"], fmt["max_clips"] = clip_count_targets(len(payload.get("windows") or []))
|
|
||||||
fmt["min_secs"], fmt["max_secs"] = clip_duration_bounds()
|
|
||||||
prompt = template.format(**fmt)
|
|
||||||
|
|
||||||
_log(f"🤖 Gemini worker request: mode={args.mode} strategy={args.strategy} model={model_name} items={len(payload.get('windows', []))}")
|
|
||||||
response = client.models.generate_content(
|
|
||||||
model=model_name,
|
|
||||||
contents=prompt,
|
|
||||||
config=config,
|
|
||||||
)
|
|
||||||
|
|
||||||
raw_text = _get_response_text(response)
|
|
||||||
# With response_schema the SDK returns an already-validated object; fall
|
|
||||||
# back to the text-repair path only when that is unavailable.
|
|
||||||
parsed_obj = getattr(response, "parsed", None)
|
|
||||||
if parsed_obj is not None:
|
|
||||||
parsed = parsed_obj.model_dump() if hasattr(parsed_obj, "model_dump") else parsed_obj
|
|
||||||
else:
|
|
||||||
parsed = _parse_json_response_text(raw_text)
|
|
||||||
result = {
|
|
||||||
"mode": args.mode,
|
|
||||||
"payload": parsed,
|
|
||||||
"cost_analysis": _calculate_cost_analysis(response, model_name),
|
|
||||||
"raw_text": raw_text,
|
|
||||||
}
|
|
||||||
with open(args.output_path, "w", encoding="utf-8") as f:
|
|
||||||
json.dump(result, f, indent=2, ensure_ascii=False)
|
|
||||||
_log(f"✅ Gemini worker success: mode={args.mode}")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
raise SystemExit(main())
|
|
||||||
|
|
|
||||||
|
|
@ -23,7 +23,6 @@ so ``main.py`` sees one shape regardless of provider.
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
|
||||||
import os
|
import os
|
||||||
from typing import Optional, Tuple, Type
|
from typing import Optional, Tuple, Type
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -9,10 +9,7 @@ import threading
|
||||||
import unicodedata
|
import unicodedata
|
||||||
import uuid
|
import uuid
|
||||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||||
from scenedetect import open_video, SceneManager
|
|
||||||
from scenedetect.detectors import ContentDetector
|
|
||||||
from ultralytics import YOLO
|
from ultralytics import YOLO
|
||||||
import torch
|
|
||||||
import os
|
import os
|
||||||
import math
|
import math
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
@ -33,7 +30,7 @@ from clipwright.pipeline.clip_selection import (build_transcript_windows, clip_c
|
||||||
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, audio_encode_args, cut_clip, QUALITY,
|
from clipwright.media.ffmpeg_utils import (video_encode_args, cut_clip, QUALITY,
|
||||||
QUALITY_FAST, METADATA_SCRUB)
|
QUALITY_FAST, METADATA_SCRUB)
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
import json
|
import json
|
||||||
|
|
@ -47,45 +44,6 @@ load_dotenv()
|
||||||
# --- Constants ---
|
# --- Constants ---
|
||||||
ASPECT_RATIO = 9 / 16
|
ASPECT_RATIO = 9 / 16
|
||||||
|
|
||||||
GEMINI_PROMPT_TEMPLATE = """
|
|
||||||
You are a senior short-form video editor. Read the ENTIRE transcript and word-level timestamps to choose the 3–15 MOST VIRAL moments for TikTok/IG Reels/YouTube Shorts. Each clip must be between 15 and 60 seconds long.
|
|
||||||
|
|
||||||
⚠️ FFMPEG TIME CONTRACT — STRICT REQUIREMENTS:
|
|
||||||
- Return timestamps in ABSOLUTE SECONDS from the start of the video (usable in: ffmpeg -ss <start> -to <end> -i <input> ...).
|
|
||||||
- Only NUMBERS with decimal point, up to 3 decimals (examples: 0, 1.250, 17.350).
|
|
||||||
- Ensure 0 ≤ start < end ≤ VIDEO_DURATION_SECONDS.
|
|
||||||
- Each clip between 15 and 60 s (inclusive).
|
|
||||||
- Prefer starting 0.2–0.4 s BEFORE the hook and ending 0.2–0.4 s AFTER the payoff.
|
|
||||||
- Use silence moments for natural cuts; never cut in the middle of a word or phrase.
|
|
||||||
- STRICTLY FORBIDDEN to use time formats other than absolute seconds.
|
|
||||||
|
|
||||||
VIDEO_DURATION_SECONDS: {video_duration}
|
|
||||||
|
|
||||||
TRANSCRIPT_TEXT (raw):
|
|
||||||
{transcript_text}
|
|
||||||
|
|
||||||
WORDS_JSON (array of {{w, s, e}} where s/e are seconds):
|
|
||||||
{words_json}
|
|
||||||
|
|
||||||
STRICT EXCLUSIONS:
|
|
||||||
- No generic intros/outros or purely sponsorship segments unless they contain the hook.
|
|
||||||
- No clips < 15 s or > 60 s.
|
|
||||||
|
|
||||||
OUTPUT — RETURN ONLY VALID JSON (no markdown, no comments). Order clips by predicted performance (best to worst). In the descriptions, ALWAYS include a CTA like "Follow me and comment X and I'll send you the workflow" (especially if discussing an n8n workflow):
|
|
||||||
{{
|
|
||||||
"shorts": [
|
|
||||||
{{
|
|
||||||
"start": <number in seconds, e.g., 12.340>,
|
|
||||||
"end": <number in seconds, e.g., 37.900>,
|
|
||||||
"video_description_for_tiktok": "<description for TikTok oriented to get views>",
|
|
||||||
"video_description_for_instagram": "<description for Instagram oriented to get views>",
|
|
||||||
"video_title_for_youtube_short": "<title for YouTube Short oriented to get views 100 chars max>",
|
|
||||||
"viral_hook_text": "<SHORT punchy text overlay (max 10 words) with 1-2 fitting emojis. MUST BE IN THE SAME LANGUAGE AS THE VIDEO TRANSCRIPT. Examples: 'POV: You realized... 😳', 'Did you know? 🤯', 'Stop doing this! 🚫'>"
|
|
||||||
}}
|
|
||||||
]
|
|
||||||
}}
|
|
||||||
"""
|
|
||||||
|
|
||||||
# Load the YOLO model once (Keep for backup or scene analysis if needed)
|
# Load the YOLO model once (Keep for backup or scene analysis if needed)
|
||||||
# YOLO_MODEL_PATH lets deployments point at a pre-downloaded weights file so a
|
# YOLO_MODEL_PATH lets deployments point at a pre-downloaded weights file so a
|
||||||
# volume mounted over the workdir doesn't trigger a re-download at startup.
|
# volume mounted over the workdir doesn't trigger a re-download at startup.
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,4 @@
|
||||||
import os
|
import os
|
||||||
import shutil
|
|
||||||
# Check if PIL is installed, if not we can't run this locally but it will run in docker
|
# Check if PIL is installed, if not we can't run this locally but it will run in docker
|
||||||
try:
|
try:
|
||||||
from clipwright.media.hooks import create_hook_image
|
from clipwright.media.hooks import create_hook_image
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,4 @@
|
||||||
import os
|
import os
|
||||||
import shutil
|
|
||||||
from clipwright.media.hooks import create_hook_image
|
from clipwright.media.hooks import create_hook_image
|
||||||
|
|
||||||
def verify():
|
def verify():
|
||||||
|
|
|
||||||
|
|
@ -1,16 +1,9 @@
|
||||||
# React + Vite
|
# Clipwright dashboard
|
||||||
|
|
||||||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
Vite + React front end for Clipwright.
|
||||||
|
|
||||||
Currently, two official plugins are available:
|
- `npm install` — install dependencies
|
||||||
|
- `npm run dev` — dev server with HMR
|
||||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
|
- `npm run build` — production build to `dist/`
|
||||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
- `npm run preview` — serve the built output
|
||||||
|
- `npm run lint` — ESLint
|
||||||
## React Compiler
|
|
||||||
|
|
||||||
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
|
||||||
|
|
||||||
## Expanding the ESLint configuration
|
|
||||||
|
|
||||||
If you are developing a production application, we recommend using TypeScript with type-aware lint rules enabled. Check out the [TS template](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts) for information on how to integrate TypeScript and [`typescript-eslint`](https://typescript-eslint.io) in your project.
|
|
||||||
|
|
|
||||||
2
dashboard/e2e/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
||||||
|
.artifacts/
|
||||||
|
.test-results/
|
||||||
389
dashboard/e2e/fixtures/api-mocks.js
Normal file
|
|
@ -0,0 +1,389 @@
|
||||||
|
// State-machine route interception for the dashboard's backend.
|
||||||
|
//
|
||||||
|
// Every spec runs against the built dashboard with **zero unmocked network**:
|
||||||
|
// this fixture installs a catch-all that aborts anything off-origin, then the
|
||||||
|
// specific /api, /videos and /thumbnails handlers that answer with deterministic
|
||||||
|
// fixtures. The only "state" is a counter per endpoint, which is enough to model
|
||||||
|
// queued -> processing -> completed without a single timer or sleep in a spec —
|
||||||
|
// the app's own 2s poll drives it, and Playwright's auto-wait absorbs the gap.
|
||||||
|
|
||||||
|
export const BASE_ORIGIN = 'http://127.0.0.1:4173';
|
||||||
|
|
||||||
|
export const JOB_ID = '11111111-1111-4111-8111-111111111111';
|
||||||
|
|
||||||
|
// 1x1 transparent PNG, decoded by the browser at route.fulfill time.
|
||||||
|
const TINY_PNG =
|
||||||
|
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M8AAAMBAQDJ/pLvAAAAAElFTkSuQmCC';
|
||||||
|
|
||||||
|
export function defaultClips() {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
video_url: `/videos/${JOB_ID}/clip_1.mp4`,
|
||||||
|
video_title_for_youtube_short: 'First viral clip',
|
||||||
|
video_description_for_tiktok: 'TikTok caption one #viral #shorts',
|
||||||
|
video_description_for_instagram: 'Instagram caption one #reels',
|
||||||
|
start: 0,
|
||||||
|
end: 30,
|
||||||
|
predicted_score: 91,
|
||||||
|
why: 'Opens on a strong claim the rest of the clip pays off.',
|
||||||
|
auto_hook: { text: 'Watch this' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
video_url: `/videos/${JOB_ID}/clip_2.mp4`,
|
||||||
|
video_title_for_youtube_short: 'Second viral clip',
|
||||||
|
video_description_for_tiktok: 'TikTok caption two #viral',
|
||||||
|
video_description_for_instagram: 'Instagram caption two #reels',
|
||||||
|
start: 40,
|
||||||
|
end: 70,
|
||||||
|
predicted_score: 77,
|
||||||
|
why: 'A clean story beat with a natural ending.',
|
||||||
|
auto_hook: null,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function defaultResults() {
|
||||||
|
return {
|
||||||
|
clips: defaultClips(),
|
||||||
|
cost_analysis: { input_tokens: 1200, output_tokens: 400, total_cost: 0.00123 },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function defaultEdl() {
|
||||||
|
return {
|
||||||
|
job_id: JOB_ID,
|
||||||
|
clip_index: 0,
|
||||||
|
title: 'First viral clip',
|
||||||
|
segments: [{ start: 0, end: 30 }],
|
||||||
|
framing: 'auto',
|
||||||
|
canonical_range: { start: 0, end: 30 },
|
||||||
|
duration: 30,
|
||||||
|
current_file: 'clip_1.mp4',
|
||||||
|
has_captions: false,
|
||||||
|
words: [
|
||||||
|
{ w: 'Hello', s: 0, e: 0.6 },
|
||||||
|
{ w: 'world', s: 0.6, e: 1.2 },
|
||||||
|
{ w: 'this', s: 1.2, e: 1.6 },
|
||||||
|
{ w: 'is', s: 1.6, e: 1.9 },
|
||||||
|
{ w: 'a', s: 1.9, e: 2.1 },
|
||||||
|
{ w: 'clip', s: 2.1, e: 2.7 },
|
||||||
|
],
|
||||||
|
source: { available: true, url: `/api/source/${JOB_ID}`, duration: 120, duration_estimated: false },
|
||||||
|
limits: { max_segments: 12, min_segment_seconds: 0.5, max_total_seconds: 180 },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function defaultScenes() {
|
||||||
|
return {
|
||||||
|
job_id: JOB_ID,
|
||||||
|
clip_index: 0,
|
||||||
|
crop_width_fraction: 0.5,
|
||||||
|
preview_url: `/videos/${JOB_ID}/scenes_preview.mp4`,
|
||||||
|
saved_overrides: {},
|
||||||
|
scenes: [
|
||||||
|
{
|
||||||
|
index: 0,
|
||||||
|
start: 0,
|
||||||
|
end: 15,
|
||||||
|
suggested_center: 0.5,
|
||||||
|
suggested_center_y: 0.5,
|
||||||
|
thumbnail_url: `/thumbnails/${JOB_ID}/scene_0.png`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
index: 1,
|
||||||
|
start: 15,
|
||||||
|
end: 30,
|
||||||
|
suggested_center: 0.4,
|
||||||
|
suggested_center_y: 0.5,
|
||||||
|
thumbnail_url: `/thumbnails/${JOB_ID}/scene_1.png`,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function defaultIntegrations() {
|
||||||
|
return [
|
||||||
|
{ id: 'int-yt', identifier: 'youtube', name: 'My YouTube', disabled: false },
|
||||||
|
{ id: 'int-tt', identifier: 'tiktok', name: 'My TikTok', disabled: false },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function json(route, data, status = 200) {
|
||||||
|
return route.fulfill({
|
||||||
|
status,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function video(route) {
|
||||||
|
return route.fulfill({ status: 200, contentType: 'video/mp4', body: '' });
|
||||||
|
}
|
||||||
|
|
||||||
|
function png(route) {
|
||||||
|
return route.fulfill({ status: 200, contentType: 'image/png', body: atob(TINY_PNG) });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Install all network handlers on `page`. Returns a mutable `state` object so a
|
||||||
|
* spec can assert on call counts (e.g. the quality gate resend).
|
||||||
|
*/
|
||||||
|
export async function installApiMocks(page, options = {}) {
|
||||||
|
const opts = {
|
||||||
|
config: {
|
||||||
|
youtubeUrlEnabled: true,
|
||||||
|
billingEnabled: false,
|
||||||
|
jobRetentionSeconds: 86400,
|
||||||
|
localLlm: null,
|
||||||
|
},
|
||||||
|
clips: defaultClips(),
|
||||||
|
// 'queued' | 'needs_confirmation', consumed in order.
|
||||||
|
processSequence: ['queued'],
|
||||||
|
// 'processing' | 'completed' | 'failed', consumed in order; the last
|
||||||
|
// entry repeats once exhausted.
|
||||||
|
statusSequence: ['processing', 'completed'],
|
||||||
|
transcript: { captions: [], durationSec: 30, language: 'en' },
|
||||||
|
edl: defaultEdl(),
|
||||||
|
scenes: defaultScenes(),
|
||||||
|
integrations: defaultIntegrations(),
|
||||||
|
thumbnail: {
|
||||||
|
analyze: {
|
||||||
|
session_id: 'session-e2e',
|
||||||
|
titles: ['Mock title one', 'Mock title two'],
|
||||||
|
thumbnail_texts: ['Big win', 'How to'],
|
||||||
|
context: '',
|
||||||
|
language: 'en',
|
||||||
|
recommended: [{ index: 0, reason: 'clearest promise' }],
|
||||||
|
},
|
||||||
|
generate: {
|
||||||
|
thumbnails: [
|
||||||
|
{ url: '/thumbnails/e2e/thumb_1.png', text: 'Big win', why: 'bright and readable' },
|
||||||
|
{ url: '/thumbnails/e2e/thumb_2.png', text: 'How to', why: 'strong contrast' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
describe: { description: 'A generated description with 00:00 chapters.' },
|
||||||
|
},
|
||||||
|
tools: {
|
||||||
|
transcript: {
|
||||||
|
title: 'Mock Video',
|
||||||
|
channel: 'Mock Channel',
|
||||||
|
duration: 125,
|
||||||
|
kind: 'auto',
|
||||||
|
language: 'en',
|
||||||
|
video_id: 'dQw4w9WgXcQ',
|
||||||
|
cached: false,
|
||||||
|
languages: [{ code: 'en', kind: 'auto', name: 'English', request: 'en' }],
|
||||||
|
segments: [
|
||||||
|
{ start: 0, dur: 2, text: 'Hello world' },
|
||||||
|
{ start: 2, dur: 2, text: 'Second line' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
...options,
|
||||||
|
};
|
||||||
|
|
||||||
|
const state = {
|
||||||
|
processCalls: 0,
|
||||||
|
statusCalls: 0,
|
||||||
|
rerenderCalls: 0,
|
||||||
|
reframeCalls: 0,
|
||||||
|
subtitleCalls: 0,
|
||||||
|
hookCalls: 0,
|
||||||
|
postCalls: 0,
|
||||||
|
thumbnailPublishCalls: 0,
|
||||||
|
thumbnailPublishStatusCalls: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Catch-all: allow same-origin and in-page schemes, abort everything else.
|
||||||
|
// Registered first so the specific handlers below (registered later) win.
|
||||||
|
await page.route('**/*', (route) => {
|
||||||
|
const url = new URL(route.request().url());
|
||||||
|
if (url.origin === BASE_ORIGIN || url.protocol === 'data:' || url.protocol === 'blob:') {
|
||||||
|
return route.continue();
|
||||||
|
}
|
||||||
|
return route.abort();
|
||||||
|
});
|
||||||
|
|
||||||
|
await page.route('**/api/**', async (route) => {
|
||||||
|
const req = route.request();
|
||||||
|
const method = req.method();
|
||||||
|
const path = new URL(req.url()).pathname;
|
||||||
|
|
||||||
|
if (method === 'GET' && path === '/api/config') return json(route, opts.config);
|
||||||
|
|
||||||
|
if (method === 'POST' && path === '/api/process') {
|
||||||
|
const phase = opts.processSequence[Math.min(state.processCalls, opts.processSequence.length - 1)];
|
||||||
|
state.processCalls += 1;
|
||||||
|
if (phase === 'needs_confirmation') {
|
||||||
|
return json(route, {
|
||||||
|
needs_confirmation: true,
|
||||||
|
quality_check: { max_height: 360, min_height: 720, cookies_invalid: false },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return json(route, { job_id: JOB_ID, status: 'queued', partial: null });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (method === 'GET' && path.startsWith('/api/status/')) {
|
||||||
|
const phase = opts.statusSequence[Math.min(state.statusCalls, opts.statusSequence.length - 1)];
|
||||||
|
state.statusCalls += 1;
|
||||||
|
if (phase === 'failed') {
|
||||||
|
return json(route, {
|
||||||
|
status: 'failed',
|
||||||
|
logs: ['boom'],
|
||||||
|
log_times: [Date.now() / 1000],
|
||||||
|
result: null,
|
||||||
|
queue: null,
|
||||||
|
partial: null,
|
||||||
|
error: 'The video is too short to clip.',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const result = phase === 'completed'
|
||||||
|
? { clips: opts.clips, cost_analysis: defaultResults().cost_analysis }
|
||||||
|
: { clips: opts.clips.slice(0, 1), cost_analysis: null };
|
||||||
|
return json(route, {
|
||||||
|
status: phase,
|
||||||
|
logs: phase === 'completed' ? ['Done.'] : ['Rendering clip 1...'],
|
||||||
|
log_times: [Date.now() / 1000],
|
||||||
|
result,
|
||||||
|
queue: null,
|
||||||
|
partial: null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (method === 'GET' && path.startsWith('/api/source-url/')) {
|
||||||
|
return json(route, { url: `/videos/${JOB_ID}/source.mp4` });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (method === 'GET' && path.startsWith('/api/source/')) return video(route);
|
||||||
|
|
||||||
|
if (method === 'GET' && /^\/api\/jobs\/[^/]+\/download-all$/.test(path)) {
|
||||||
|
return route.fulfill({ status: 200, contentType: 'application/zip', body: 'PK-e2e-zip' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const clipMatch = path.match(/^\/api\/clip\/([^/]+)\/(\d+)\/(transcript|edl|scenes)$/);
|
||||||
|
if (method === 'GET' && clipMatch) {
|
||||||
|
const kind = clipMatch[3];
|
||||||
|
if (kind === 'transcript') return json(route, opts.transcript);
|
||||||
|
if (kind === 'edl') return json(route, opts.edl);
|
||||||
|
return json(route, opts.scenes);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (method === 'POST' && path === '/api/clip/rerender') {
|
||||||
|
state.rerenderCalls += 1;
|
||||||
|
const body = req.postDataJSON();
|
||||||
|
const segments = body?.segments || [{ start: 0, end: 30 }];
|
||||||
|
return json(route, {
|
||||||
|
new_video_url: `/videos/${JOB_ID}/recut_e2e_clip_1.mp4`,
|
||||||
|
recipe: { v: 1, segments, canonical_range: { start: 0, end: 30 } },
|
||||||
|
framing: body?.framing || 'auto',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (method === 'POST' && path === '/api/clip/reframe') {
|
||||||
|
state.reframeCalls += 1;
|
||||||
|
return json(route, {
|
||||||
|
new_video_url: `/videos/${JOB_ID}/recut_e2e_reframe_clip_1.mp4`,
|
||||||
|
recipe: { v: 1, segments: [{ start: 0, end: 30 }], canonical_range: { start: 0, end: 30 } },
|
||||||
|
framing: 'auto',
|
||||||
|
framed_scenes: [0],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (method === 'POST' && path === '/api/subtitle/remove') {
|
||||||
|
state.subtitleCalls += 1;
|
||||||
|
return json(route, { success: true, new_video_url: `/videos/${JOB_ID}/clean_clip_1.mp4` });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (method === 'POST' && path === '/api/subtitle') {
|
||||||
|
state.subtitleCalls += 1;
|
||||||
|
return json(route, { new_video_url: `/videos/${JOB_ID}/subtitled_e2e_clip_1.mp4` });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (method === 'POST' && path === '/api/hook') {
|
||||||
|
state.hookCalls += 1;
|
||||||
|
const body = req.postDataJSON();
|
||||||
|
return json(route, {
|
||||||
|
new_video_url: `/videos/${JOB_ID}/hooked_e2e_clip_1.mp4`,
|
||||||
|
burned_hook: body?.remove ? null : { text: body?.text || 'Hook' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (method === 'POST' && path === '/api/effects/generate') {
|
||||||
|
return json(route, { effects: { segments: [{ start: 0, end: 2, zoom: 1.2 }] } });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (method === 'POST' && path === '/api/edit') {
|
||||||
|
return json(route, { new_video_url: `/videos/${JOB_ID}/edited_e2e_clip_1.mp4` });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (method === 'GET' && path === '/api/postiz/integrations') {
|
||||||
|
return json(route, { integrations: opts.integrations });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (method === 'POST' && path === '/api/postiz/post') {
|
||||||
|
state.postCalls += 1;
|
||||||
|
return json(route, {
|
||||||
|
success: true,
|
||||||
|
results: {},
|
||||||
|
posted: [{ id: 'int-yt', name: 'My YouTube', identifier: 'youtube' }],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (method === 'GET' && path === '/api/postiz/scheduled') {
|
||||||
|
return json(route, { scheduled_posts: [] });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (method === 'POST' && path === '/api/thumbnail/upload') {
|
||||||
|
return json(route, { session_id: 'session-e2e' });
|
||||||
|
}
|
||||||
|
if (method === 'POST' && path === '/api/thumbnail/analyze') {
|
||||||
|
return json(route, opts.thumbnail.analyze);
|
||||||
|
}
|
||||||
|
if (method === 'POST' && path === '/api/thumbnail/titles') {
|
||||||
|
return json(route, {
|
||||||
|
session_id: 'session-e2e',
|
||||||
|
titles: opts.thumbnail.analyze.titles,
|
||||||
|
thumbnail_texts: opts.thumbnail.analyze.thumbnail_texts,
|
||||||
|
recommended: [],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (method === 'POST' && path === '/api/thumbnail/generate') {
|
||||||
|
return json(route, opts.thumbnail.generate);
|
||||||
|
}
|
||||||
|
if (method === 'GET' && path.startsWith('/api/thumbnail/frames/')) {
|
||||||
|
return json(route, { frames: [] });
|
||||||
|
}
|
||||||
|
if (method === 'POST' && path === '/api/thumbnail/describe') {
|
||||||
|
return json(route, opts.thumbnail.describe);
|
||||||
|
}
|
||||||
|
if (method === 'POST' && path === '/api/thumbnail/publish') {
|
||||||
|
state.thumbnailPublishCalls += 1;
|
||||||
|
return json(route, { publish_id: 'pub-e2e', status: 'uploading' });
|
||||||
|
}
|
||||||
|
if (method === 'GET' && path.startsWith('/api/thumbnail/publish/status/')) {
|
||||||
|
state.thumbnailPublishStatusCalls += 1;
|
||||||
|
return json(route, { status: 'done', result: { id: 'post-e2e' }, error: null });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (method === 'GET' && path === '/api/tools/youtube-transcript') {
|
||||||
|
return json(route, opts.tools.transcript);
|
||||||
|
}
|
||||||
|
if (method === 'POST' && path === '/api/tools/youtube-metadata') {
|
||||||
|
const body = req.postDataJSON() || {};
|
||||||
|
if (body.mode === 'titles') {
|
||||||
|
return json(route, { mode: 'titles', titles: [{ title: 'Mock title', angle: 'how-to' }] });
|
||||||
|
}
|
||||||
|
if (body.mode === 'description') {
|
||||||
|
return json(route, { mode: 'description', description: 'Mock description for the video.' });
|
||||||
|
}
|
||||||
|
return json(route, { mode: 'tags', tags: ['mock', 'tags', 'example'], characters: 17 });
|
||||||
|
}
|
||||||
|
|
||||||
|
return json(route, { detail: `no e2e mock for ${method} ${path}` }, 404);
|
||||||
|
});
|
||||||
|
|
||||||
|
await page.route('**/videos/**', (route) => video(route));
|
||||||
|
await page.route('**/thumbnails/**', (route) => png(route));
|
||||||
|
|
||||||
|
return state;
|
||||||
|
}
|
||||||
63
dashboard/e2e/fixtures/app.js
Normal file
|
|
@ -0,0 +1,63 @@
|
||||||
|
// App-level helpers shared by the specs: localStorage seeding (Gemini key,
|
||||||
|
// Postiz config, a restored session), the in-browser render seam, and a single
|
||||||
|
// `openApp` that installs mocks, seeds storage and navigates.
|
||||||
|
import { installApiMocks, JOB_ID, defaultClips, defaultResults } from './api-mocks.js';
|
||||||
|
|
||||||
|
// Mirrors SECRET_KEY in src/App.jsx (no VITE_ENCRYPTION_KEY is set by the build).
|
||||||
|
const SECRET_KEY = 'Clipwright-Static-Salt-Change-Me';
|
||||||
|
|
||||||
|
export function encryptSecret(text) {
|
||||||
|
let xor = '';
|
||||||
|
for (let i = 0; i < text.length; i += 1) {
|
||||||
|
xor += String.fromCharCode(text.charCodeAt(i) ^ SECRET_KEY.charCodeAt(i % SECRET_KEY.length));
|
||||||
|
}
|
||||||
|
return `ENC:${btoa(xor)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function seedApp(page, { geminiKey = 'e2e-gemini-key', postizUrl, postizKey, session } = {}) {
|
||||||
|
await page.addInitScript((payload) => {
|
||||||
|
try {
|
||||||
|
// A stored consent decision keeps the cookie banner out of the way
|
||||||
|
// (the banner is otherwise shown to EEA timezones, which the CI
|
||||||
|
// runner's TZ would make nondeterministic).
|
||||||
|
window.localStorage.setItem('clipwright_consent', JSON.stringify({
|
||||||
|
v: 1, ts: new Date().toISOString(), necessary: true, analytics: true, marketing: false,
|
||||||
|
}));
|
||||||
|
if (payload.geminiKey) window.localStorage.setItem('gemini_key', payload.geminiKey);
|
||||||
|
if (payload.postizUrl) window.localStorage.setItem('postiz_url', payload.postizUrl);
|
||||||
|
if (payload.encryptedPostizKey) window.localStorage.setItem('postiz_key_v1', payload.encryptedPostizKey);
|
||||||
|
if (payload.session) window.localStorage.setItem('clipwright_session', JSON.stringify(payload.session));
|
||||||
|
} catch (_) { /* storage unavailable */ }
|
||||||
|
}, {
|
||||||
|
geminiKey,
|
||||||
|
postizUrl,
|
||||||
|
encryptedPostizKey: postizKey ? encryptSecret(postizKey) : null,
|
||||||
|
session,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Replace the WebCodecs/Remotion render with a deterministic blob URL so the
|
||||||
|
// specs never depend on hardware encoders. See src/lib/renderInBrowser.js.
|
||||||
|
await page.addInitScript(() => {
|
||||||
|
window.__CW_E2E_RENDER__ = () => 'blob:http://127.0.0.1:4173/e2e-render';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function completedSession({ jobId = JOB_ID, clips = defaultClips() } = {}) {
|
||||||
|
return {
|
||||||
|
jobId,
|
||||||
|
status: 'complete',
|
||||||
|
results: { clips, cost_analysis: defaultResults().cost_analysis },
|
||||||
|
processingMedia: null,
|
||||||
|
activeTab: 'dashboard',
|
||||||
|
timestamp: Date.now(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function openApp(page, { hash = '#app', seed, mocks } = {}) {
|
||||||
|
const state = await installApiMocks(page, mocks);
|
||||||
|
await seedApp(page, seed);
|
||||||
|
await page.goto(`/${hash}`);
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
export { installApiMocks, JOB_ID, defaultClips, defaultResults };
|
||||||
26
dashboard/e2e/fixtures/global-setup.js
Normal file
|
|
@ -0,0 +1,26 @@
|
||||||
|
// Builds the tiny media the specs upload. ffmpeg is required by the plan; when
|
||||||
|
// it is absent (a bare `npm test` on a machine without it) we still write a
|
||||||
|
// non-empty placeholder so the upload path is exercised rather than skipped.
|
||||||
|
import { execFileSync } from 'node:child_process';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import { ARTIFACTS_DIR, SIXTY_MP4 } from './media.js';
|
||||||
|
|
||||||
|
export default function globalSetup() {
|
||||||
|
fs.mkdirSync(ARTIFACTS_DIR, { recursive: true });
|
||||||
|
try {
|
||||||
|
execFileSync('ffmpeg', [
|
||||||
|
'-y',
|
||||||
|
'-f', 'lavfi', '-i', 'testsrc=size=160x90:rate=30:duration=60',
|
||||||
|
'-f', 'lavfi', '-i', 'sine=frequency=440:duration=60',
|
||||||
|
'-c:v', 'libx264', '-pix_fmt', 'yuv420p',
|
||||||
|
'-c:a', 'aac', '-shortest',
|
||||||
|
SIXTY_MP4,
|
||||||
|
], { stdio: 'ignore' });
|
||||||
|
console.log(`[e2e] built ${SIXTY_MP4}`);
|
||||||
|
} catch (err) {
|
||||||
|
if (!fs.existsSync(SIXTY_MP4)) {
|
||||||
|
fs.writeFileSync(SIXTY_MP4, 'clipwright-e2e-placeholder');
|
||||||
|
}
|
||||||
|
console.warn(`[e2e] ffmpeg unavailable, wrote a placeholder media file: ${err.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
15
dashboard/e2e/fixtures/media.js
Normal file
|
|
@ -0,0 +1,15 @@
|
||||||
|
// Media used by the browser E2E specs.
|
||||||
|
//
|
||||||
|
// Nothing binary is committed: global-setup builds a tiny mp4 with ffmpeg into
|
||||||
|
// e2e/.artifacts (git-ignored) and the specs read the path from here. The file
|
||||||
|
// only has to be a real, non-empty video container — the dashboard's upload
|
||||||
|
// path reads its duration from the browser and falls back gracefully when the
|
||||||
|
// browser cannot decode the codec, so an undecodable build still exercises the
|
||||||
|
// flow.
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import path from 'node:path';
|
||||||
|
|
||||||
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
|
||||||
|
export const ARTIFACTS_DIR = path.join(here, '..', '.artifacts');
|
||||||
|
export const SIXTY_MP4 = path.join(ARTIFACTS_DIR, 'sixty.mp4');
|
||||||
53
dashboard/e2e/playwright.config.js
Normal file
|
|
@ -0,0 +1,53 @@
|
||||||
|
// Browser E2E config. Two projects:
|
||||||
|
// - `mock` (default): every network edge is intercepted, no retries, one
|
||||||
|
// worker. This is the lane that must stay green in CI.
|
||||||
|
// - `real`: drives the real backend (uvicorn + stub pipeline). Kept separate
|
||||||
|
// so the mocked lane never depends on Python.
|
||||||
|
/* global process */
|
||||||
|
import { defineConfig, devices } from '@playwright/test';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import path from 'node:path';
|
||||||
|
|
||||||
|
const dashboardDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
testDir: './specs',
|
||||||
|
// No retries anywhere: a flaky test is a bug, not a coin flip.
|
||||||
|
retries: 0,
|
||||||
|
// One worker keeps the shared preview server and the deterministic fixtures
|
||||||
|
// predictable.
|
||||||
|
workers: 1,
|
||||||
|
fullyParallel: false,
|
||||||
|
timeout: 30_000,
|
||||||
|
expect: { timeout: 5_000 },
|
||||||
|
reporter: [['list']],
|
||||||
|
outputDir: './.test-results',
|
||||||
|
globalSetup: './fixtures/global-setup.js',
|
||||||
|
use: {
|
||||||
|
baseURL: 'http://127.0.0.1:4173',
|
||||||
|
trace: 'retain-on-failure',
|
||||||
|
screenshot: 'only-on-failure',
|
||||||
|
video: 'retain-on-failure',
|
||||||
|
},
|
||||||
|
projects: [
|
||||||
|
{
|
||||||
|
name: 'mock',
|
||||||
|
testIgnore: /real-backend\.spec\.js/,
|
||||||
|
use: { ...devices['Desktop Chrome'] },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'real',
|
||||||
|
testMatch: /real-backend\.spec\.js/,
|
||||||
|
use: { ...devices['Desktop Chrome'] },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
webServer: {
|
||||||
|
command: 'npm run build && npx vite preview --port 4173 --strictPort --host 127.0.0.1',
|
||||||
|
cwd: dashboardDir,
|
||||||
|
url: 'http://127.0.0.1:4173',
|
||||||
|
reuseExistingServer: !process.env.CI,
|
||||||
|
timeout: 120_000,
|
||||||
|
stdout: 'ignore',
|
||||||
|
stderr: 'pipe',
|
||||||
|
},
|
||||||
|
});
|
||||||
35
dashboard/e2e/specs/clip-editor.spec.js
Normal file
|
|
@ -0,0 +1,35 @@
|
||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import { openApp, completedSession, JOB_ID } from '../fixtures/app.js';
|
||||||
|
|
||||||
|
test.describe('clip editor', () => {
|
||||||
|
test('edits the recipe and re-renders through /api/clip/rerender', async ({ page }) => {
|
||||||
|
await openApp(page, { seed: { session: completedSession() } });
|
||||||
|
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
|
||||||
|
|
||||||
|
await page.getByRole('button', { name: 'edit clip' }).first().click();
|
||||||
|
await expect(page.getByRole('heading', { name: 'edit clip' })).toBeVisible();
|
||||||
|
// The EDL loaded (the loading state is gone) and its segment is listed.
|
||||||
|
await expect(page.getByRole('button', { name: /add segment/i })).toBeVisible();
|
||||||
|
await expect(page.getByLabel('segment 1 start')).toHaveValue('0');
|
||||||
|
|
||||||
|
// Add a second segment so the recipe is dirty and renderable.
|
||||||
|
await page.getByRole('button', { name: /add segment/i }).click();
|
||||||
|
await expect(page.getByLabel('segment 2 start')).toBeVisible();
|
||||||
|
|
||||||
|
const requestPromise = page.waitForRequest(
|
||||||
|
(r) => r.method() === 'POST' && r.url().includes('/api/clip/rerender'),
|
||||||
|
);
|
||||||
|
await page.getByRole('button', { name: /re-render/i }).click();
|
||||||
|
const request = await requestPromise;
|
||||||
|
|
||||||
|
const body = request.postDataJSON();
|
||||||
|
expect(body.job_id).toBe(JOB_ID);
|
||||||
|
expect(body.clip_index).toBe(0);
|
||||||
|
expect(body.segments).toHaveLength(2);
|
||||||
|
expect(body.framing).toBe('auto');
|
||||||
|
expect(body.reapply_captions).toBe(true);
|
||||||
|
|
||||||
|
// The new preview URL is adopted; the editor stays open.
|
||||||
|
await expect(page.getByRole('heading', { name: 'edit clip' })).toBeVisible();
|
||||||
|
});
|
||||||
|
});
|
||||||
45
dashboard/e2e/specs/free-tools.spec.js
Normal file
|
|
@ -0,0 +1,45 @@
|
||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import { installApiMocks } from '../fixtures/app.js';
|
||||||
|
|
||||||
|
// The free tools are static, no-React pages emitted by vite-plugin-seo. They
|
||||||
|
// talk to the same /api origin, so the same route mocks apply.
|
||||||
|
|
||||||
|
test.describe('free tools', () => {
|
||||||
|
test('youtube transcript generator renders captions', async ({ page }) => {
|
||||||
|
await installApiMocks(page);
|
||||||
|
await page.goto('/youtube-transcript-generator.html');
|
||||||
|
|
||||||
|
const requestPromise = page.waitForRequest(
|
||||||
|
(r) => r.url().includes('/api/tools/youtube-transcript'),
|
||||||
|
);
|
||||||
|
await page.fill('#yt-url', 'https://www.youtube.com/watch?v=dQw4w9WgXcQ');
|
||||||
|
await page.click('#yt-form button[type="submit"]');
|
||||||
|
const request = await requestPromise;
|
||||||
|
expect(new URL(request.url()).searchParams.get('url'))
|
||||||
|
.toBe('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
|
||||||
|
|
||||||
|
await expect(page.locator('#yt-title')).toHaveText('Mock Video');
|
||||||
|
await expect(page.locator('#yt-result')).toBeVisible();
|
||||||
|
await expect(page.locator('#yt-text')).toContainText('Hello world');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('youtube tag generator returns tags', async ({ page }) => {
|
||||||
|
await installApiMocks(page);
|
||||||
|
await page.goto('/youtube-tag-generator.html');
|
||||||
|
|
||||||
|
await page.fill('#md-topic', 'A detailed topic sentence about sourdough bread for beginners.');
|
||||||
|
await page.click('#md-go');
|
||||||
|
|
||||||
|
await expect(page.locator('#md-out')).toBeVisible();
|
||||||
|
await expect(page.locator('#md-out')).toContainText('mock');
|
||||||
|
await expect(page.locator('#md-out')).toContainText('tags');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('video aspect ratio converter loads its client-side tool', async ({ page }) => {
|
||||||
|
await installApiMocks(page);
|
||||||
|
await page.goto('/video-aspect-ratio-converter.html');
|
||||||
|
|
||||||
|
await expect(page.locator('#vc-file')).toBeAttached();
|
||||||
|
await expect(page.locator('#vc-drop')).toBeVisible();
|
||||||
|
});
|
||||||
|
});
|
||||||
52
dashboard/e2e/specs/generate-flow.spec.js
Normal file
|
|
@ -0,0 +1,52 @@
|
||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import { openApp } from '../fixtures/app.js';
|
||||||
|
import { SIXTY_MP4 } from '../fixtures/media.js';
|
||||||
|
|
||||||
|
test.describe('generate flow', () => {
|
||||||
|
test('uploads a file, posts it to /api/process and renders the clips', async ({ page }) => {
|
||||||
|
await openApp(page, { mocks: { statusSequence: ['processing', 'completed'] } });
|
||||||
|
|
||||||
|
await page.setInputFiles('input[type="file"][accept="video/*"]', SIXTY_MP4);
|
||||||
|
await page.locator('form input[type="checkbox"]').first().check();
|
||||||
|
|
||||||
|
const requestPromise = page.waitForRequest(
|
||||||
|
(r) => r.method() === 'POST' && r.url().includes('/api/process'),
|
||||||
|
);
|
||||||
|
await page.getByRole('button', { name: /generate clips/i }).click();
|
||||||
|
const request = await requestPromise;
|
||||||
|
|
||||||
|
expect(request.headers()['x-gemini-key']).toBe('e2e-gemini-key');
|
||||||
|
expect(request.headers()['content-type']).toContain('multipart/form-data');
|
||||||
|
// The multipart body carries the chosen file and the attestation.
|
||||||
|
const body = request.postDataBuffer().toString('latin1');
|
||||||
|
expect(body).toContain('sixty.mp4');
|
||||||
|
expect(body).toContain('acknowledged');
|
||||||
|
|
||||||
|
// Polling is driven by the app's own 2s interval; auto-wait absorbs it.
|
||||||
|
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
|
||||||
|
await expect(page.getByRole('heading', { name: 'Second viral clip' })).toBeVisible();
|
||||||
|
await expect(page.getByText('2 Clips')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('submits a YouTube URL as JSON with the Gemini header', async ({ page }) => {
|
||||||
|
await openApp(page);
|
||||||
|
|
||||||
|
await page.getByRole('button', { name: /video url/i }).click();
|
||||||
|
await page.getByPlaceholder(/paste a video link/i).fill('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
|
||||||
|
await page.locator('form input[type="checkbox"]').first().check();
|
||||||
|
|
||||||
|
const requestPromise = page.waitForRequest(
|
||||||
|
(r) => r.method() === 'POST' && r.url().includes('/api/process'),
|
||||||
|
);
|
||||||
|
await page.getByRole('button', { name: /generate clips/i }).click();
|
||||||
|
const request = await requestPromise;
|
||||||
|
|
||||||
|
expect(request.postDataJSON()).toMatchObject({
|
||||||
|
url: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
|
||||||
|
acknowledged: true,
|
||||||
|
force_low_quality: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
|
||||||
|
});
|
||||||
|
});
|
||||||
37
dashboard/e2e/specs/postiz-publish.spec.js
Normal file
|
|
@ -0,0 +1,37 @@
|
||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import { openApp, completedSession, JOB_ID } from '../fixtures/app.js';
|
||||||
|
|
||||||
|
test.describe('postiz publish', () => {
|
||||||
|
test('publishes a clip to the connected channels through /api/postiz/post', async ({ page }) => {
|
||||||
|
await openApp(page, {
|
||||||
|
seed: {
|
||||||
|
session: completedSession(),
|
||||||
|
postizUrl: 'http://postiz.e2e.local',
|
||||||
|
postizKey: 'postiz-e2e-key',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
|
||||||
|
|
||||||
|
await page.getByRole('button', { name: 'post', exact: true }).first().click();
|
||||||
|
const dialog = page.getByRole('dialog');
|
||||||
|
await expect(dialog.getByText('PUBLISH', { exact: true })).toBeVisible();
|
||||||
|
|
||||||
|
// Connected channels load from the mocked integrations endpoint.
|
||||||
|
await expect(dialog.getByText('My YouTube')).toBeVisible();
|
||||||
|
|
||||||
|
const requestPromise = page.waitForRequest(
|
||||||
|
(r) => r.method() === 'POST' && r.url().includes('/api/postiz/post'),
|
||||||
|
);
|
||||||
|
await dialog.getByRole('button', { name: /publish now/i }).click();
|
||||||
|
const request = await requestPromise;
|
||||||
|
|
||||||
|
const body = request.postDataJSON();
|
||||||
|
expect(body.job_id).toBe(JOB_ID);
|
||||||
|
expect(body.clip_index).toBe(0);
|
||||||
|
expect(body.integration_ids).toContain('int-yt');
|
||||||
|
expect(body.title).toBe('First viral clip');
|
||||||
|
expect(request.headers()['x-postiz-url']).toBe('http://postiz.e2e.local');
|
||||||
|
|
||||||
|
await expect(page.getByText(/Posted to My YouTube/)).toBeVisible();
|
||||||
|
});
|
||||||
|
});
|
||||||
38
dashboard/e2e/specs/quality-gate.spec.js
Normal file
|
|
@ -0,0 +1,38 @@
|
||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import { openApp } from '../fixtures/app.js';
|
||||||
|
|
||||||
|
test.describe('quality gate', () => {
|
||||||
|
test('asks before processing a low-resolution source and resends with force_low_quality', async ({ page }) => {
|
||||||
|
await openApp(page, { mocks: { processSequence: ['needs_confirmation', 'queued'] } });
|
||||||
|
|
||||||
|
await page.getByRole('button', { name: /video url/i }).click();
|
||||||
|
await page.getByPlaceholder(/paste a video link/i).fill('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
|
||||||
|
await page.locator('form input[type="checkbox"]').first().check();
|
||||||
|
|
||||||
|
const firstPromise = page.waitForRequest(
|
||||||
|
(r) => r.method() === 'POST' && r.url().includes('/api/process'),
|
||||||
|
);
|
||||||
|
await page.getByRole('button', { name: /generate clips/i }).click();
|
||||||
|
const first = await firstPromise;
|
||||||
|
expect(first.postDataJSON()).toMatchObject({ force_low_quality: false });
|
||||||
|
|
||||||
|
// The gate opens instead of starting the job.
|
||||||
|
const dialog = page.getByRole('dialog');
|
||||||
|
await expect(dialog.getByText(/low source quality/i)).toBeVisible();
|
||||||
|
await expect(dialog.getByText(/360p/)).toBeVisible();
|
||||||
|
|
||||||
|
const secondPromise = page.waitForRequest(
|
||||||
|
(r) => r.method() === 'POST'
|
||||||
|
&& r.url().includes('/api/process')
|
||||||
|
&& JSON.parse(r.postData()).force_low_quality === true,
|
||||||
|
);
|
||||||
|
await page.getByRole('button', { name: /process anyway/i }).click();
|
||||||
|
const second = await secondPromise;
|
||||||
|
expect(second.postDataJSON()).toMatchObject({
|
||||||
|
url: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
|
||||||
|
force_low_quality: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
|
||||||
|
});
|
||||||
|
});
|
||||||
17
dashboard/e2e/specs/real-backend.spec.js
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
|
||||||
|
// Real-backend lane.
|
||||||
|
//
|
||||||
|
// The plan calls for driving a real `uvicorn clipwright.api.app:app` with the
|
||||||
|
// pipeline's stub_env (tests/e2e/pipeline/stub_env) so the browser talks to the
|
||||||
|
// actual API instead of route mocks. That pipeline/stub environment is owned by
|
||||||
|
// the backend E2E lanes, and the dashboard CI job provisions Node + Chromium
|
||||||
|
// only (no Python deps, no ffmpeg), so this stays fixme until the backend lane
|
||||||
|
// exposes a server the dashboard job can launch. The same routes are covered
|
||||||
|
// end-to-end over HTTP by tests/e2e/api.
|
||||||
|
test.describe('real backend', () => {
|
||||||
|
test.fixme('generates clips against a real uvicorn + stub_env server', async ({ page }) => {
|
||||||
|
await page.goto('/');
|
||||||
|
await expect(page).toHaveTitle(/Clipwright/);
|
||||||
|
});
|
||||||
|
});
|
||||||
35
dashboard/e2e/specs/reframe-editor.spec.js
Normal file
|
|
@ -0,0 +1,35 @@
|
||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import { openApp, completedSession, JOB_ID } from '../fixtures/app.js';
|
||||||
|
|
||||||
|
test.describe('reframe editor', () => {
|
||||||
|
test('splits a scene and applies reframing through /api/clip/reframe', async ({ page }) => {
|
||||||
|
await openApp(page, { seed: { session: completedSession() } });
|
||||||
|
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
|
||||||
|
|
||||||
|
await page.getByRole('button', { name: 'reframing' }).first().click();
|
||||||
|
await expect(page.getByRole('heading', { name: 'reframing' })).toBeVisible();
|
||||||
|
|
||||||
|
// Scenes came back from the mocked /scenes endpoint.
|
||||||
|
await expect(page.getByText(/scene 1 ·/)).toBeVisible();
|
||||||
|
await expect(page.getByText(/nothing adjusted yet/i)).toBeVisible();
|
||||||
|
|
||||||
|
await page.getByTitle('stack two regions instead of one window').first().click();
|
||||||
|
await expect(page.getByText(/1 scene reframed by hand/i)).toBeVisible();
|
||||||
|
|
||||||
|
const requestPromise = page.waitForRequest(
|
||||||
|
(r) => r.method() === 'POST' && r.url().includes('/api/clip/reframe'),
|
||||||
|
);
|
||||||
|
await page.getByRole('button', { name: /apply reframing/i }).click();
|
||||||
|
const request = await requestPromise;
|
||||||
|
|
||||||
|
const body = request.postDataJSON();
|
||||||
|
expect(body.job_id).toBe(JOB_ID);
|
||||||
|
expect(body.clip_index).toBe(0);
|
||||||
|
expect(body.crop_overrides['0']).toBeTruthy();
|
||||||
|
expect(body.crop_overrides['0'].top).toBeTruthy();
|
||||||
|
expect(body.crop_overrides['0'].bottom).toBeTruthy();
|
||||||
|
|
||||||
|
// A successful save closes the editor.
|
||||||
|
await expect(page.getByRole('heading', { name: 'reframing' })).toHaveCount(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
38
dashboard/e2e/specs/results-actions.spec.js
Normal file
|
|
@ -0,0 +1,38 @@
|
||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import { openApp, completedSession, JOB_ID } from '../fixtures/app.js';
|
||||||
|
|
||||||
|
test.describe('results actions', () => {
|
||||||
|
test('downloads all clips as a zip', async ({ page }) => {
|
||||||
|
await openApp(page, { seed: { session: completedSession() } });
|
||||||
|
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
|
||||||
|
|
||||||
|
const requestPromise = page.waitForRequest(
|
||||||
|
(r) => r.method() === 'GET' && r.url().includes(`/api/jobs/${JOB_ID}/download-all`),
|
||||||
|
);
|
||||||
|
const downloadPromise = page.waitForEvent('download');
|
||||||
|
await page.getByRole('button', { name: /download all/i }).click();
|
||||||
|
|
||||||
|
await requestPromise;
|
||||||
|
const download = await downloadPromise;
|
||||||
|
expect(download.suggestedFilename()).toContain('clipwright_clips_');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('opens the generated descriptions', async ({ page }) => {
|
||||||
|
await openApp(page, { seed: { session: completedSession() } });
|
||||||
|
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
|
||||||
|
|
||||||
|
await page.getByRole('button', { name: /view descriptions/i }).first().click();
|
||||||
|
const dialog = page.getByRole('dialog');
|
||||||
|
await expect(dialog.getByText('GENERATED COPY')).toBeVisible();
|
||||||
|
await expect(dialog.getByText('TikTok caption one #viral #shorts')).toBeVisible();
|
||||||
|
await expect(dialog.getByText('First viral clip')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('removes a generated clip and resets the workspace', async ({ page }) => {
|
||||||
|
await openApp(page, { seed: { session: completedSession() } });
|
||||||
|
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
|
||||||
|
|
||||||
|
await page.getByRole('button', { name: /new project/i }).click();
|
||||||
|
await expect(page.getByRole('heading', { name: /create viral shorts/i })).toBeVisible();
|
||||||
|
});
|
||||||
|
});
|
||||||
23
dashboard/e2e/specs/session-restore.spec.js
Normal file
|
|
@ -0,0 +1,23 @@
|
||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import { openApp, completedSession } from '../fixtures/app.js';
|
||||||
|
|
||||||
|
test.describe('session restore', () => {
|
||||||
|
test('restores a completed job from localStorage and shows its clips', async ({ page }) => {
|
||||||
|
await openApp(page, { seed: { session: completedSession() } });
|
||||||
|
|
||||||
|
await expect(page.getByText('Session recovered')).toBeVisible();
|
||||||
|
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
|
||||||
|
await expect(page.getByRole('heading', { name: 'Second viral clip' })).toBeVisible();
|
||||||
|
await expect(page.getByText('2 Clips')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('discards a session older than the retention window', async ({ page }) => {
|
||||||
|
const stale = completedSession();
|
||||||
|
stale.timestamp = Date.now() - 25 * 60 * 60 * 1000; // 25h > 24h
|
||||||
|
await openApp(page, { seed: { session: stale } });
|
||||||
|
|
||||||
|
await expect(page.getByRole('heading', { name: /create viral shorts/i })).toBeVisible();
|
||||||
|
await expect(page.getByText('Session recovered')).toHaveCount(0);
|
||||||
|
await expect(page.getByRole('heading', { name: 'First viral clip' })).toHaveCount(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
28
dashboard/e2e/specs/smoke.spec.js
Normal file
|
|
@ -0,0 +1,28 @@
|
||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import { openApp } from '../fixtures/app.js';
|
||||||
|
|
||||||
|
test.describe('smoke', () => {
|
||||||
|
test('boots the app, renders the generator and reaches Settings', async ({ page }) => {
|
||||||
|
const pageErrors = [];
|
||||||
|
page.on('pageerror', (err) => pageErrors.push(err.message));
|
||||||
|
|
||||||
|
await openApp(page, { hash: '#app' });
|
||||||
|
|
||||||
|
await expect(page.getByRole('heading', { name: /create viral shorts/i })).toBeVisible();
|
||||||
|
// The Gemini key is seeded, so the "keys missing" banners must not show.
|
||||||
|
await expect(page.getByText(/Required API keys missing/i)).toHaveCount(0);
|
||||||
|
await expect(page.getByText(/Gemini API Key Missing/i)).toHaveCount(0);
|
||||||
|
|
||||||
|
// Settings is a full view reachable from the rail.
|
||||||
|
await page.getByRole('button', { name: /settings/i }).first().click();
|
||||||
|
await expect(page.getByRole('heading', { name: 'Settings' })).toBeVisible();
|
||||||
|
await expect(page.getByText(/Publishing \(Postiz\)/i)).toBeVisible();
|
||||||
|
|
||||||
|
expect(pageErrors).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('asks for the Gemini key when none is stored', async ({ page }) => {
|
||||||
|
await openApp(page, { seed: { geminiKey: '' } });
|
||||||
|
await expect(page.getByText(/Required API keys missing/i)).toBeVisible();
|
||||||
|
});
|
||||||
|
});
|
||||||
46
dashboard/e2e/specs/subtitle-modal.spec.js
Normal file
|
|
@ -0,0 +1,46 @@
|
||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import { openApp, completedSession, JOB_ID } from '../fixtures/app.js';
|
||||||
|
|
||||||
|
test.describe('subtitle modal', () => {
|
||||||
|
test('applies a caption style to one clip and posts the style to /api/subtitle', async ({ page }) => {
|
||||||
|
await openApp(page, { seed: { session: completedSession() } });
|
||||||
|
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
|
||||||
|
|
||||||
|
await page.getByRole('button', { name: 'subtitles' }).first().click();
|
||||||
|
const dialog = page.getByRole('dialog');
|
||||||
|
await expect(dialog.getByText('EDITOR · SUBTITLES')).toBeVisible();
|
||||||
|
|
||||||
|
const requestPromise = page.waitForRequest(
|
||||||
|
(r) => r.method() === 'POST' && r.url().includes('/api/subtitle'),
|
||||||
|
);
|
||||||
|
await dialog.getByRole('button', { name: /apply to this clip/i }).click();
|
||||||
|
const request = await requestPromise;
|
||||||
|
|
||||||
|
expect(request.postDataJSON()).toMatchObject({
|
||||||
|
job_id: JOB_ID,
|
||||||
|
clip_index: 0,
|
||||||
|
style: 'karaoke',
|
||||||
|
input_filename: 'clip_1.mp4',
|
||||||
|
});
|
||||||
|
|
||||||
|
// Success closes the editor.
|
||||||
|
await expect(page.getByText('EDITOR · SUBTITLES')).toHaveCount(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('applies one style to every clip', async ({ page }) => {
|
||||||
|
await openApp(page, { seed: { session: completedSession() }, mocks: { statusSequence: ['completed'] } });
|
||||||
|
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
|
||||||
|
|
||||||
|
const bodies = [];
|
||||||
|
page.on('request', (r) => {
|
||||||
|
if (r.method() === 'POST' && r.url().includes('/api/subtitle')) bodies.push(r.postDataJSON());
|
||||||
|
});
|
||||||
|
|
||||||
|
await page.getByRole('button', { name: 'subtitles' }).first().click();
|
||||||
|
const dialog = page.getByRole('dialog');
|
||||||
|
await dialog.getByRole('button', { name: /apply this style to all 2 clips/i }).click();
|
||||||
|
|
||||||
|
await expect.poll(() => bodies.length).toBe(2);
|
||||||
|
expect(bodies.map((b) => b.clip_index).sort()).toEqual([0, 1]);
|
||||||
|
});
|
||||||
|
});
|
||||||
43
dashboard/e2e/specs/thumbnail-studio.spec.js
Normal file
|
|
@ -0,0 +1,43 @@
|
||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import { openApp } from '../fixtures/app.js';
|
||||||
|
|
||||||
|
test.describe('thumbnail studio', () => {
|
||||||
|
test('manual title -> generate -> describe -> publish to YouTube', async ({ page }) => {
|
||||||
|
await openApp(page, {
|
||||||
|
hash: '#app?tab=thumbnails',
|
||||||
|
seed: { postizUrl: 'http://postiz.e2e.local', postizKey: 'postiz-e2e-key' },
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(page.getByRole('heading', { name: /youtube studio/i })).toBeVisible();
|
||||||
|
|
||||||
|
// Mode B: write a title by hand.
|
||||||
|
await page.getByPlaceholder(/Enter your YouTube title/i).fill('My manual e2e title');
|
||||||
|
await page.getByRole('button', { name: /use this title/i }).click();
|
||||||
|
await page.getByRole('button', { name: /continue to thumbnails/i }).click();
|
||||||
|
|
||||||
|
// Step 2: generate thumbnails.
|
||||||
|
const generatePromise = page.waitForRequest(
|
||||||
|
(r) => r.method() === 'POST' && r.url().includes('/api/thumbnail/generate'),
|
||||||
|
);
|
||||||
|
await page.getByRole('button', { name: /generate thumbnails/i }).click();
|
||||||
|
await generatePromise;
|
||||||
|
await expect(page.getByAltText('Thumbnail 1')).toBeVisible();
|
||||||
|
|
||||||
|
await page.getByAltText('Thumbnail 1').click({ force: true });
|
||||||
|
await page.getByRole('button', { name: /next: description/i }).click();
|
||||||
|
|
||||||
|
// Step 3: write a description and continue.
|
||||||
|
await page.locator('textarea').first().fill('A hand written e2e description.');
|
||||||
|
await page.getByRole('button', { name: /next: publish/i }).click();
|
||||||
|
|
||||||
|
// Step 4: publish (Postiz is configured).
|
||||||
|
const publishPromise = page.waitForRequest(
|
||||||
|
(r) => r.method() === 'POST' && r.url().includes('/api/thumbnail/publish'),
|
||||||
|
);
|
||||||
|
await page.getByRole('button', { name: /publish to youtube/i }).click();
|
||||||
|
const publish = await publishPromise;
|
||||||
|
expect(publish.postDataBuffer().toString('latin1')).toContain('My manual e2e title');
|
||||||
|
|
||||||
|
await expect(page.getByText(/published successfully/i)).toBeVisible();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -41,10 +41,10 @@ server {
|
||||||
# trailing-slash URL, so every canonical would point at a redirect.
|
# trailing-slash URL, so every canonical would point at a redirect.
|
||||||
#
|
#
|
||||||
# Unknown paths get a real 404, not the SPA shell. The app routes entirely
|
# Unknown paths get a real 404, not the SPA shell. The app routes entirely
|
||||||
# through the hash (#/pricing, #/auth/callback), which never reaches the
|
# through the hash, which never reaches the server, so there is no deep link
|
||||||
# server, so there is no deep link that needs the fallback — and answering
|
# that needs the fallback — and answering 200 with identical markup for
|
||||||
# 200 with identical markup for every made-up path made the whole site look
|
# every made-up path made the whole site look like one page duplicated
|
||||||
# like one page duplicated infinitely to a crawler.
|
# infinitely to a crawler.
|
||||||
location / {
|
location / {
|
||||||
try_files $uri $uri.html $uri/ =404;
|
try_files $uri $uri.html $uri/ =404;
|
||||||
add_header Cache-Control "no-store, must-revalidate" always;
|
add_header Cache-Control "no-store, must-revalidate" always;
|
||||||
|
|
|
||||||
97
dashboard/package-lock.json
generated
|
|
@ -9,18 +9,17 @@
|
||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@remotion/media": "^4.0.447",
|
"@remotion/media": "^4.0.447",
|
||||||
"@remotion/media-utils": "^4.0.447",
|
|
||||||
"@remotion/player": "^4.0.447",
|
"@remotion/player": "^4.0.447",
|
||||||
"@remotion/web-renderer": "^4.0.447",
|
"@remotion/web-renderer": "^4.0.447",
|
||||||
"lucide-react": "^0.344.0",
|
"lucide-react": "^0.344.0",
|
||||||
"mediabunny": "^1.39.2",
|
"mediabunny": "^1.39.2",
|
||||||
"react": "^18.2.0",
|
"react": "^18.2.0",
|
||||||
"react-dom": "^18.2.0",
|
"react-dom": "^18.2.0",
|
||||||
"remotion": "^4.0.447",
|
"remotion": "^4.0.447"
|
||||||
"zod": "^4.3.6"
|
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.39.5",
|
"@eslint/js": "^9.39.5",
|
||||||
|
"@playwright/test": "^1.63.0",
|
||||||
"@types/react": "^18.2.64",
|
"@types/react": "^18.2.64",
|
||||||
"@types/react-dom": "^18.2.21",
|
"@types/react-dom": "^18.2.21",
|
||||||
"@vitejs/plugin-react": "^4.2.1",
|
"@vitejs/plugin-react": "^4.2.1",
|
||||||
|
|
@ -988,6 +987,22 @@
|
||||||
"node": ">= 8"
|
"node": ">= 8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@playwright/test": {
|
||||||
|
"version": "1.63.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.63.0.tgz",
|
||||||
|
"integrity": "sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"playwright": "1.63.0"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"playwright": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@remotion/licensing": {
|
"node_modules/@remotion/licensing": {
|
||||||
"version": "4.0.447",
|
"version": "4.0.447",
|
||||||
"resolved": "https://registry.npmjs.org/@remotion/licensing/-/licensing-4.0.447.tgz",
|
"resolved": "https://registry.npmjs.org/@remotion/licensing/-/licensing-4.0.447.tgz",
|
||||||
|
|
@ -1008,20 +1023,6 @@
|
||||||
"react-dom": ">=16.8.0"
|
"react-dom": ">=16.8.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@remotion/media-utils": {
|
|
||||||
"version": "4.0.447",
|
|
||||||
"resolved": "https://registry.npmjs.org/@remotion/media-utils/-/media-utils-4.0.447.tgz",
|
|
||||||
"integrity": "sha512-PltvSZsY+By8DlsZeAN63D1cMsgXewCqEq39nJrO0VZVc5nnWyd+nvMZz9yhGsoMo2Z5xNkfZhPkl+Gs25wn0Q==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"mediabunny": "1.39.2",
|
|
||||||
"remotion": "4.0.447"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"react": ">=16.8.0",
|
|
||||||
"react-dom": ">=16.8.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@remotion/player": {
|
"node_modules/@remotion/player": {
|
||||||
"version": "4.0.447",
|
"version": "4.0.447",
|
||||||
"resolved": "https://registry.npmjs.org/@remotion/player/-/player-4.0.447.tgz",
|
"resolved": "https://registry.npmjs.org/@remotion/player/-/player-4.0.447.tgz",
|
||||||
|
|
@ -3911,6 +3912,35 @@
|
||||||
"node": ">= 6"
|
"node": ">= 6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/playwright": {
|
||||||
|
"version": "1.63.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz",
|
||||||
|
"integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"playwright-core": "1.63.0"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"playwright": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/playwright-core": {
|
||||||
|
"version": "1.63.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",
|
||||||
|
"integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"bin": {
|
||||||
|
"playwright-core": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/possible-typed-array-names": {
|
"node_modules/possible-typed-array-names": {
|
||||||
"version": "1.1.0",
|
"version": "1.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",
|
||||||
|
|
@ -5801,6 +5831,15 @@
|
||||||
"fastq": "^1.6.0"
|
"fastq": "^1.6.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"@playwright/test": {
|
||||||
|
"version": "1.63.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.63.0.tgz",
|
||||||
|
"integrity": "sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ==",
|
||||||
|
"dev": true,
|
||||||
|
"requires": {
|
||||||
|
"playwright": "1.63.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"@remotion/licensing": {
|
"@remotion/licensing": {
|
||||||
"version": "4.0.447",
|
"version": "4.0.447",
|
||||||
"resolved": "https://registry.npmjs.org/@remotion/licensing/-/licensing-4.0.447.tgz",
|
"resolved": "https://registry.npmjs.org/@remotion/licensing/-/licensing-4.0.447.tgz",
|
||||||
|
|
@ -5816,15 +5855,6 @@
|
||||||
"zod": "4.3.6"
|
"zod": "4.3.6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"@remotion/media-utils": {
|
|
||||||
"version": "4.0.447",
|
|
||||||
"resolved": "https://registry.npmjs.org/@remotion/media-utils/-/media-utils-4.0.447.tgz",
|
|
||||||
"integrity": "sha512-PltvSZsY+By8DlsZeAN63D1cMsgXewCqEq39nJrO0VZVc5nnWyd+nvMZz9yhGsoMo2Z5xNkfZhPkl+Gs25wn0Q==",
|
|
||||||
"requires": {
|
|
||||||
"mediabunny": "1.39.2",
|
|
||||||
"remotion": "4.0.447"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"@remotion/player": {
|
"@remotion/player": {
|
||||||
"version": "4.0.447",
|
"version": "4.0.447",
|
||||||
"resolved": "https://registry.npmjs.org/@remotion/player/-/player-4.0.447.tgz",
|
"resolved": "https://registry.npmjs.org/@remotion/player/-/player-4.0.447.tgz",
|
||||||
|
|
@ -7767,6 +7797,21 @@
|
||||||
"integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==",
|
"integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==",
|
||||||
"dev": true
|
"dev": true
|
||||||
},
|
},
|
||||||
|
"playwright": {
|
||||||
|
"version": "1.63.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz",
|
||||||
|
"integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==",
|
||||||
|
"dev": true,
|
||||||
|
"requires": {
|
||||||
|
"playwright-core": "1.63.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"playwright-core": {
|
||||||
|
"version": "1.63.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",
|
||||||
|
"integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",
|
||||||
|
"dev": true
|
||||||
|
},
|
||||||
"possible-typed-array-names": {
|
"possible-typed-array-names": {
|
||||||
"version": "1.1.0",
|
"version": "1.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",
|
||||||
|
|
|
||||||
|
|
@ -7,22 +7,22 @@
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "vite build",
|
"build": "vite build",
|
||||||
"lint": "eslint . --report-unused-disable-directives --max-warnings 0",
|
"lint": "eslint . --report-unused-disable-directives --max-warnings 0",
|
||||||
"preview": "vite preview"
|
"preview": "vite preview",
|
||||||
|
"test:e2e": "playwright test --config e2e/playwright.config.js"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@remotion/media": "^4.0.447",
|
"@remotion/media": "^4.0.447",
|
||||||
"@remotion/media-utils": "^4.0.447",
|
|
||||||
"@remotion/player": "^4.0.447",
|
"@remotion/player": "^4.0.447",
|
||||||
"@remotion/web-renderer": "^4.0.447",
|
"@remotion/web-renderer": "^4.0.447",
|
||||||
"lucide-react": "^0.344.0",
|
"lucide-react": "^0.344.0",
|
||||||
"mediabunny": "^1.39.2",
|
"mediabunny": "^1.39.2",
|
||||||
"react": "^18.2.0",
|
"react": "^18.2.0",
|
||||||
"react-dom": "^18.2.0",
|
"react-dom": "^18.2.0",
|
||||||
"remotion": "^4.0.447",
|
"remotion": "^4.0.447"
|
||||||
"zod": "^4.3.6"
|
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.39.5",
|
"@eslint/js": "^9.39.5",
|
||||||
|
"@playwright/test": "^1.63.0",
|
||||||
"@types/react": "^18.2.64",
|
"@types/react": "^18.2.64",
|
||||||
"@types/react-dom": "^18.2.21",
|
"@types/react-dom": "^18.2.21",
|
||||||
"@vitejs/plugin-react": "^4.2.1",
|
"@vitejs/plugin-react": "^4.2.1",
|
||||||
|
|
|
||||||
|
Before Width: | Height: | Size: 25 KiB |
|
|
@ -1 +0,0 @@
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
|
||||||
|
Before Width: | Height: | Size: 1.5 KiB |
|
|
@ -210,17 +210,3 @@ export const COMPARISON_ROWS = [
|
||||||
{ feature: 'Free AI YouTube thumbnail & title studio', os: 'Yes', vendor: 'No' },
|
{ feature: 'Free AI YouTube thumbnail & title studio', os: 'Yes', vendor: 'No' },
|
||||||
{ feature: 'Usage cap', os: 'None', vendor: 'Metered on every tier' },
|
{ feature: 'Usage cap', os: 'None', vendor: 'Metered on every tier' },
|
||||||
]
|
]
|
||||||
|
|
||||||
/* Third-party figures used across the pages. Every one is attributed inline,
|
|
||||||
* because sourced statistics are among the few things that reliably survive
|
|
||||||
* into a generated answer. */
|
|
||||||
export const CITED_STATS = [
|
|
||||||
{
|
|
||||||
claim: 'Short-form video delivers the highest ROI of any content format.',
|
|
||||||
source: 'HubSpot, State of Marketing 2025',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
claim: '91% of businesses use video as a marketing tool.',
|
|
||||||
source: 'Wyzowl, Video Marketing Statistics 2025',
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
|
||||||
|
|
@ -1,42 +0,0 @@
|
||||||
#root {
|
|
||||||
max-width: 1280px;
|
|
||||||
margin: 0 auto;
|
|
||||||
padding: 2rem;
|
|
||||||
text-align: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
.logo {
|
|
||||||
height: 6em;
|
|
||||||
padding: 1.5em;
|
|
||||||
will-change: filter;
|
|
||||||
transition: filter 300ms;
|
|
||||||
}
|
|
||||||
.logo:hover {
|
|
||||||
filter: drop-shadow(0 0 2em #646cffaa);
|
|
||||||
}
|
|
||||||
.logo.react:hover {
|
|
||||||
filter: drop-shadow(0 0 2em #61dafbaa);
|
|
||||||
}
|
|
||||||
|
|
||||||
@keyframes logo-spin {
|
|
||||||
from {
|
|
||||||
transform: rotate(0deg);
|
|
||||||
}
|
|
||||||
to {
|
|
||||||
transform: rotate(360deg);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (prefers-reduced-motion: no-preference) {
|
|
||||||
a:nth-of-type(2) .logo {
|
|
||||||
animation: logo-spin infinite 20s linear;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.card {
|
|
||||||
padding: 2em;
|
|
||||||
}
|
|
||||||
|
|
||||||
.read-the-docs {
|
|
||||||
color: #888;
|
|
||||||
}
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
|
||||||
|
Before Width: | Height: | Size: 4 KiB |
|
|
@ -8,12 +8,10 @@
|
||||||
// "Accept all" are the same component with the same size, weight, colour
|
// "Accept all" are the same component with the same size, weight, colour
|
||||||
// and position; there is no pre-ticked box and no dark pattern.
|
// and position; there is no pre-ticked box and no dark pattern.
|
||||||
//
|
//
|
||||||
// It renders nothing once a decision exists — the footer link
|
// It renders nothing once a decision exists.
|
||||||
// (openConsentManager) is how anyone changes their mind.
|
import { useState } from 'react';
|
||||||
import { useEffect, useState } from 'react';
|
|
||||||
import {
|
import {
|
||||||
getConsent, hasDecided, acceptAll, rejectAll, setConsent,
|
getConsent, hasDecided, acceptAll, rejectAll, setConsent,
|
||||||
onConsentOpenRequest,
|
|
||||||
} from '../lib/consent';
|
} from '../lib/consent';
|
||||||
|
|
||||||
const CATEGORY_COPY = [
|
const CATEGORY_COPY = [
|
||||||
|
|
@ -41,12 +39,6 @@ export default function CookieBanner() {
|
||||||
const [details, setDetails] = useState(false);
|
const [details, setDetails] = useState(false);
|
||||||
const [draft, setDraft] = useState(() => getConsent());
|
const [draft, setDraft] = useState(() => getConsent());
|
||||||
|
|
||||||
useEffect(() => onConsentOpenRequest(() => {
|
|
||||||
setDraft(getConsent());
|
|
||||||
setDetails(true);
|
|
||||||
setOpen(true);
|
|
||||||
}), []);
|
|
||||||
|
|
||||||
if (!open) return null;
|
if (!open) return null;
|
||||||
|
|
||||||
const close = () => { setOpen(false); setDetails(false); };
|
const close = () => { setOpen(false); setDetails(false); };
|
||||||
|
|
|
||||||
|
|
@ -23,8 +23,6 @@
|
||||||
const STORAGE_KEY = 'clipwright_consent';
|
const STORAGE_KEY = 'clipwright_consent';
|
||||||
const VERSION = 1;
|
const VERSION = 1;
|
||||||
|
|
||||||
export const CATEGORIES = ['necessary', 'analytics', 'marketing'];
|
|
||||||
|
|
||||||
const DENY_ALL = { necessary: true, analytics: false, marketing: false };
|
const DENY_ALL = { necessary: true, analytics: false, marketing: false };
|
||||||
const GRANT_ALL = { necessary: true, analytics: true, marketing: true };
|
const GRANT_ALL = { necessary: true, analytics: true, marketing: true };
|
||||||
|
|
||||||
|
|
@ -62,9 +60,6 @@ export function refineGeo() {
|
||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
const listeners = new Set();
|
|
||||||
|
|
||||||
const read = () => {
|
const read = () => {
|
||||||
try {
|
try {
|
||||||
const raw = localStorage.getItem(STORAGE_KEY);
|
const raw = localStorage.getItem(STORAGE_KEY);
|
||||||
|
|
@ -77,9 +72,6 @@ const read = () => {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/** The stored decision, or null when the visitor has never been asked. */
|
|
||||||
export const getConsentRecord = () => read();
|
|
||||||
|
|
||||||
/** Effective permissions. Nothing but `necessary` before a decision exists. */
|
/** Effective permissions. Nothing but `necessary` before a decision exists. */
|
||||||
export const getConsent = () => {
|
export const getConsent = () => {
|
||||||
const stored = read();
|
const stored = read();
|
||||||
|
|
@ -97,11 +89,6 @@ export const hasDecided = () => read() !== null || !isEEAVisitor();
|
||||||
|
|
||||||
export const allows = (category) => !!getConsent()[category];
|
export const allows = (category) => !!getConsent()[category];
|
||||||
|
|
||||||
export function onConsentChange(fn) {
|
|
||||||
listeners.add(fn);
|
|
||||||
return () => listeners.delete(fn);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Persist a decision and act on it immediately.
|
* Persist a decision and act on it immediately.
|
||||||
*
|
*
|
||||||
|
|
@ -123,8 +110,6 @@ export function setConsent(choice) {
|
||||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
|
localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
|
||||||
} catch (_) { /* private mode: the decision holds for this page at least */ }
|
} catch (_) { /* private mode: the decision holds for this page at least */ }
|
||||||
|
|
||||||
listeners.forEach((fn) => { try { fn(getConsent()); } catch (_) { /* ignore */ } });
|
|
||||||
|
|
||||||
applyConsent();
|
applyConsent();
|
||||||
return getConsent();
|
return getConsent();
|
||||||
}
|
}
|
||||||
|
|
@ -143,14 +128,3 @@ export function applyConsent() {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reopening the banner from anywhere (the footer link) without threading props
|
|
||||||
// through the whole tree.
|
|
||||||
const OPEN_EVENT = 'clipwright:consent-open';
|
|
||||||
export const openConsentManager = () => {
|
|
||||||
try { window.dispatchEvent(new CustomEvent(OPEN_EVENT)); } catch (_) { /* ignore */ }
|
|
||||||
};
|
|
||||||
export const onConsentOpenRequest = (fn) => {
|
|
||||||
window.addEventListener(OPEN_EVENT, fn);
|
|
||||||
return () => window.removeEventListener(OPEN_EVENT, fn);
|
|
||||||
};
|
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,7 @@ export async function renderInBrowser({
|
||||||
onProgress,
|
onProgress,
|
||||||
signal,
|
signal,
|
||||||
}) {
|
}) {
|
||||||
|
if (window.__CW_E2E_RENDER__) return window.__CW_E2E_RENDER__();
|
||||||
const fps = 30;
|
const fps = 30;
|
||||||
const durationInFrames = Math.max(1, Math.round(durationInSeconds * fps));
|
const durationInFrames = Math.max(1, Math.round(durationInSeconds * fps));
|
||||||
|
|
||||||
|
|
@ -60,15 +61,3 @@ export async function renderInBrowser({
|
||||||
const blob = await getBlob();
|
const blob = await getBlob();
|
||||||
return URL.createObjectURL(blob);
|
return URL.createObjectURL(blob);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Triggers a download of a blob URL as an MP4 file.
|
|
||||||
*/
|
|
||||||
export function downloadBlobUrl(blobUrl, filename = 'output.mp4') {
|
|
||||||
const link = document.createElement('a');
|
|
||||||
link.href = blobUrl;
|
|
||||||
link.download = filename;
|
|
||||||
document.body.appendChild(link);
|
|
||||||
link.click();
|
|
||||||
document.body.removeChild(link);
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,3 @@
|
||||||
import { z } from "zod";
|
|
||||||
|
|
||||||
// --- Word-level caption ---
|
// --- Word-level caption ---
|
||||||
export interface CaptionWord {
|
export interface CaptionWord {
|
||||||
text: string;
|
text: string;
|
||||||
|
|
@ -94,66 +92,3 @@ export interface ShortVideoProps {
|
||||||
hook: HookConfig | null;
|
hook: HookConfig | null;
|
||||||
effects: EffectsConfig | null;
|
effects: EffectsConfig | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Zod schemas for validation (used by render service) ---
|
|
||||||
export const captionWordSchema = z.object({
|
|
||||||
text: z.string(),
|
|
||||||
startMs: z.number(),
|
|
||||||
endMs: z.number(),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const subtitleStyleSchema = z.object({
|
|
||||||
fontFamily: z.string(),
|
|
||||||
fontSize: z.number(),
|
|
||||||
fontColor: z.string(),
|
|
||||||
highlightColor: z.string(),
|
|
||||||
borderColor: z.string(),
|
|
||||||
borderWidth: z.number(),
|
|
||||||
bgColor: z.string(),
|
|
||||||
bgOpacity: z.number().min(0).max(1),
|
|
||||||
animation: z.enum(["none", "word-highlight", "pop", "karaoke"]),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const subtitleConfigSchema = z.object({
|
|
||||||
captions: z.array(captionWordSchema),
|
|
||||||
position: z.enum(["top", "middle", "bottom"]),
|
|
||||||
style: subtitleStyleSchema,
|
|
||||||
});
|
|
||||||
|
|
||||||
export const hookConfigSchema = z.object({
|
|
||||||
text: z.string(),
|
|
||||||
position: z.enum(["top", "center", "bottom"]),
|
|
||||||
size: z.enum(["S", "M", "L"]),
|
|
||||||
style: z
|
|
||||||
.enum(["pill", "classic", "dark", "yellow", "red", "outline", "outline_yellow"])
|
|
||||||
.default("pill"),
|
|
||||||
font: z.enum(["montserrat", "anton", "serif"]).optional(),
|
|
||||||
entranceAnimation: z.enum(["spring", "fade", "slide-up", "none"]),
|
|
||||||
displayDurationSec: z.number().positive(),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const effectSegmentSchema = z.object({
|
|
||||||
startSec: z.number().min(0),
|
|
||||||
endSec: z.number().positive(),
|
|
||||||
zoom: z.number().min(0.5).max(3),
|
|
||||||
zoomCenterX: z.number().min(0).max(1),
|
|
||||||
zoomCenterY: z.number().min(0).max(1),
|
|
||||||
brightness: z.number().min(0).max(3),
|
|
||||||
contrast: z.number().min(0).max(3),
|
|
||||||
saturate: z.number().min(0).max(3),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const effectsConfigSchema = z.object({
|
|
||||||
segments: z.array(effectSegmentSchema),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const shortVideoPropsSchema = z.object({
|
|
||||||
videoUrl: z.string(),
|
|
||||||
durationInFrames: z.number().int().positive(),
|
|
||||||
fps: z.number().positive(),
|
|
||||||
width: z.number().int().positive(),
|
|
||||||
height: z.number().int().positive(),
|
|
||||||
subtitles: subtitleConfigSchema.nullable(),
|
|
||||||
hook: hookConfigSchema.nullable(),
|
|
||||||
effects: effectsConfigSchema.nullable(),
|
|
||||||
});
|
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,6 @@ import seo from './vite-plugin-seo'
|
||||||
// name; set VITE_PROXY_TARGET=http://localhost:8000 to run the dev server on
|
// name; set VITE_PROXY_TARGET=http://localhost:8000 to run the dev server on
|
||||||
// the host against a backend reachable at localhost (no CORS, same-origin).
|
// 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'
|
||||||
const renderer = process.env.VITE_RENDER_TARGET || 'http://renderer:3100'
|
|
||||||
|
|
||||||
// https://vitejs.dev/config/
|
// https://vitejs.dev/config/
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
|
|
@ -36,7 +35,6 @@ export default defineConfig({
|
||||||
'/api': { target: backend, changeOrigin: true },
|
'/api': { target: backend, changeOrigin: true },
|
||||||
'/videos': { target: backend, changeOrigin: true },
|
'/videos': { target: backend, changeOrigin: true },
|
||||||
'/thumbnails': { target: backend, changeOrigin: true },
|
'/thumbnails': { target: backend, changeOrigin: true },
|
||||||
'/render': { target: renderer, changeOrigin: true },
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -1,19 +0,0 @@
|
||||||
# Local-only override: remap host ports to avoid clashes with other running
|
|
||||||
# projects (e.g. another backend on :8000). Not for production.
|
|
||||||
# `!override` REPLACES the base ports list instead of appending to it.
|
|
||||||
services:
|
|
||||||
backend:
|
|
||||||
ports: !override
|
|
||||||
- "8001:8000"
|
|
||||||
environment:
|
|
||||||
# Point auth/magic-link/CORS at the local frontend instead of git.pbento.pt/pedro-bento/clipwright.
|
|
||||||
- FRONTEND_URL=http://localhost:5176
|
|
||||||
- ALLOWED_ORIGINS=http://localhost:5176,http://localhost:5175,http://localhost:8001
|
|
||||||
frontend:
|
|
||||||
ports: !override
|
|
||||||
- "5176:5173"
|
|
||||||
environment:
|
|
||||||
# Call the backend directly (not via the Vite proxy) so Google OAuth builds
|
|
||||||
# a redirect_uri of http://localhost:8001/... which matches the registered
|
|
||||||
# client. Cross-origin API calls are allowed by ALLOWED_ORIGINS above.
|
|
||||||
- VITE_API_URL=http://localhost:8001
|
|
||||||
|
|
@ -29,20 +29,3 @@ services:
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
depends_on:
|
depends_on:
|
||||||
- backend
|
- backend
|
||||||
|
|
||||||
renderer:
|
|
||||||
build:
|
|
||||||
context: .
|
|
||||||
dockerfile: render-service/Dockerfile
|
|
||||||
container_name: clipwright-renderer
|
|
||||||
ports:
|
|
||||||
- "3100:3100"
|
|
||||||
volumes:
|
|
||||||
- ./output:/output
|
|
||||||
environment:
|
|
||||||
- REMOTION_BUNDLE_PATH=/app/remotion
|
|
||||||
- OUTPUT_DIR=/output
|
|
||||||
- PORT=3100
|
|
||||||
restart: unless-stopped
|
|
||||||
depends_on:
|
|
||||||
- backend
|
|
||||||
|
|
|
||||||
|
|
@ -23,7 +23,7 @@ las constantes de entorno.
|
||||||
| Descarga de origen conservada de un trabajo por URL | Igual que el trabajo, o antes si se configura | `app._sweep_retained_sources`, `SOURCE_RETENTION_SECONDS` |
|
| 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` |
|
| 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` |
|
| Ficheros en `uploads/` | **1 h** (misma vuelta del barrido) | `app.cleanup_jobs` |
|
||||||
| **Miniaturas generadas y fotogramas muestreados** (`output/thumbnails/<sesión>`) — recortes de la cara del presentador | **24 h desde la última descarga**; servir un fichero reinicia el reloj | `app._sweep_thumbnail_sessions`, `THUMBNAIL_RETENTION_SECONDS` |
|
| **Miniaturas generadas y fotogramas muestreados** (`output/thumbnails/<sesión>`) — recortes de la cara del presentador | Sin caducidad automática: permanecen hasta que borres la sesión o el volumen de salida | Sin barrido dedicado: `app.cleanup_jobs` omite `output/thumbnails` |
|
||||||
| Tope de disco: se purgan los trabajos más antiguos por encima del límite | Inmediato al superarlo | `app._enforce_output_size_cap`, `OUTPUT_MAX_GB` |
|
| 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
|
La retención de fotos de actor se retiró con la función de vídeo UGC
|
||||||
|
|
|
||||||
|
|
@ -11,14 +11,25 @@ testpaths = ["tests"]
|
||||||
# Makes the repo-root `clipwright/` package importable without a sys.path hack
|
# Makes the repo-root `clipwright/` package importable without a sys.path hack
|
||||||
# in tests/conftest.py.
|
# in tests/conftest.py.
|
||||||
pythonpath = ["."]
|
pythonpath = ["."]
|
||||||
|
# E2E taxonomy. The fast unit suite (`tests/test_*.py`) is selected with
|
||||||
|
# `-m "not e2e"`; the E2E lanes live under `tests/e2e/` and mark themselves.
|
||||||
|
# `ml` gates the heavy ML stack (torch/ultralytics/mediapipe/faster-whisper).
|
||||||
|
markers = [
|
||||||
|
"e2e: end-to-end tests, run separately from the fast unit suite",
|
||||||
|
"pipeline: end-to-end tests that exercise the pipeline stages",
|
||||||
|
"ml: tests that need the heavy ML stack (see requirements-ml-e2e.txt)",
|
||||||
|
]
|
||||||
|
# Safe: `grep -rn "async def test_" tests/` found no existing async tests, so
|
||||||
|
# auto mode does not change the behaviour of the unit suite. pytest-timeout is
|
||||||
|
# passed on the CI command line (`--timeout=120`) instead of an ini key so the
|
||||||
|
# thin unit environment (which may lack pytest-timeout) still collects.
|
||||||
|
asyncio_mode = "auto"
|
||||||
|
|
||||||
[tool.ruff]
|
[tool.ruff]
|
||||||
line-length = 100
|
line-length = 100
|
||||||
target-version = "py311"
|
target-version = "py311"
|
||||||
extend-exclude = [
|
extend-exclude = [
|
||||||
"dashboard",
|
"dashboard",
|
||||||
"render-service",
|
|
||||||
"remotion",
|
|
||||||
"cli",
|
"cli",
|
||||||
"output",
|
"output",
|
||||||
"uploads",
|
"uploads",
|
||||||
|
|
|
||||||
2
remotion/.gitignore
vendored
|
|
@ -1,2 +0,0 @@
|
||||||
node_modules/
|
|
||||||
dist/
|
|
||||||
|
|
@ -1,27 +0,0 @@
|
||||||
{
|
|
||||||
"name": "clipwright-remotion",
|
|
||||||
"version": "1.0.0",
|
|
||||||
"private": true,
|
|
||||||
"type": "module",
|
|
||||||
"scripts": {
|
|
||||||
"studio": "remotion studio",
|
|
||||||
"render": "remotion render",
|
|
||||||
"build": "tsc --noEmit"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"@remotion/cli": "^4.0.0",
|
|
||||||
"@remotion/google-fonts": "^4.0.0",
|
|
||||||
"@remotion/layout-utils": "^4.0.0",
|
|
||||||
"@remotion/media": "^4.0.447",
|
|
||||||
"@remotion/player": "^4.0.0",
|
|
||||||
"react": "^18.2.0",
|
|
||||||
"react-dom": "^18.2.0",
|
|
||||||
"remotion": "^4.0.0",
|
|
||||||
"zod": "^4.3.6"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@types/react": "^18.2.64",
|
|
||||||
"@types/react-dom": "^18.2.21",
|
|
||||||
"typescript": "^5.4.0"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,96 +0,0 @@
|
||||||
import React from "react";
|
|
||||||
import { Composition } from "remotion";
|
|
||||||
import { ShortVideo } from "./compositions/ShortVideo";
|
|
||||||
import type { ShortVideoProps } from "./lib/types";
|
|
||||||
import { shortVideoPropsSchema } from "./lib/types";
|
|
||||||
|
|
||||||
const DEFAULT_PROPS: ShortVideoProps = {
|
|
||||||
videoUrl: "",
|
|
||||||
durationInFrames: 900, // 30s at 30fps
|
|
||||||
fps: 30,
|
|
||||||
width: 1080,
|
|
||||||
height: 1920,
|
|
||||||
subtitles: {
|
|
||||||
captions: [
|
|
||||||
{ text: "This", startMs: 0, endMs: 400 },
|
|
||||||
{ text: "is", startMs: 400, endMs: 600 },
|
|
||||||
{ text: "a", startMs: 600, endMs: 750 },
|
|
||||||
{ text: "demo", startMs: 750, endMs: 1200 },
|
|
||||||
{ text: "of", startMs: 1200, endMs: 1400 },
|
|
||||||
{ text: "animated", startMs: 1400, endMs: 2000 },
|
|
||||||
{ text: "subtitles", startMs: 2000, endMs: 2800 },
|
|
||||||
{ text: "in", startMs: 2800, endMs: 3000 },
|
|
||||||
{ text: "Remotion", startMs: 3000, endMs: 3800 },
|
|
||||||
{ text: "with", startMs: 4000, endMs: 4300 },
|
|
||||||
{ text: "word", startMs: 4300, endMs: 4700 },
|
|
||||||
{ text: "level", startMs: 4700, endMs: 5100 },
|
|
||||||
{ text: "highlighting", startMs: 5100, endMs: 6000 },
|
|
||||||
],
|
|
||||||
position: "bottom",
|
|
||||||
style: {
|
|
||||||
fontFamily: "Arial",
|
|
||||||
fontSize: 52,
|
|
||||||
fontColor: "#FFFFFF",
|
|
||||||
highlightColor: "#FFDD00",
|
|
||||||
borderColor: "#000000",
|
|
||||||
borderWidth: 3,
|
|
||||||
bgColor: "#000000",
|
|
||||||
bgOpacity: 0,
|
|
||||||
animation: "pop",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
hook: {
|
|
||||||
text: "POV: You just discovered Clipwright",
|
|
||||||
position: "top",
|
|
||||||
size: "M",
|
|
||||||
entranceAnimation: "spring",
|
|
||||||
displayDurationSec: 5,
|
|
||||||
},
|
|
||||||
effects: {
|
|
||||||
segments: [
|
|
||||||
{
|
|
||||||
startSec: 2,
|
|
||||||
endSec: 5,
|
|
||||||
zoom: 1.2,
|
|
||||||
zoomCenterX: 0.5,
|
|
||||||
zoomCenterY: 0.35,
|
|
||||||
brightness: 1.05,
|
|
||||||
contrast: 1.1,
|
|
||||||
saturate: 1.15,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
startSec: 8,
|
|
||||||
endSec: 12,
|
|
||||||
zoom: 1.15,
|
|
||||||
zoomCenterX: 0.5,
|
|
||||||
zoomCenterY: 0.4,
|
|
||||||
brightness: 1,
|
|
||||||
contrast: 1,
|
|
||||||
saturate: 1,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
export const RemotionRoot: React.FC = () => {
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<Composition
|
|
||||||
id="ShortVideo"
|
|
||||||
schema={shortVideoPropsSchema}
|
|
||||||
component={ShortVideo}
|
|
||||||
durationInFrames={DEFAULT_PROPS.durationInFrames}
|
|
||||||
fps={DEFAULT_PROPS.fps}
|
|
||||||
width={DEFAULT_PROPS.width}
|
|
||||||
height={DEFAULT_PROPS.height}
|
|
||||||
defaultProps={DEFAULT_PROPS}
|
|
||||||
calculateMetadata={({ props }) => ({
|
|
||||||
durationInFrames: props.durationInFrames,
|
|
||||||
fps: props.fps,
|
|
||||||
width: props.width,
|
|
||||||
height: props.height,
|
|
||||||
})}
|
|
||||||
/>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
@ -1,172 +0,0 @@
|
||||||
import React from "react";
|
|
||||||
import {
|
|
||||||
AbsoluteFill,
|
|
||||||
Sequence,
|
|
||||||
useCurrentFrame,
|
|
||||||
useVideoConfig,
|
|
||||||
spring,
|
|
||||||
interpolate,
|
|
||||||
} from "remotion";
|
|
||||||
import type { HookConfig } from "../lib/types";
|
|
||||||
import { notoSerifFontFace, NOTO_SERIF_FONT_FAMILY } from "../lib/fonts";
|
|
||||||
|
|
||||||
interface HookOverlayProps {
|
|
||||||
config: HookConfig;
|
|
||||||
}
|
|
||||||
|
|
||||||
const SIZE_SCALE: Record<string, number> = {
|
|
||||||
S: 0.8,
|
|
||||||
M: 1.0,
|
|
||||||
L: 1.3,
|
|
||||||
};
|
|
||||||
|
|
||||||
const POSITION_STYLE: Record<string, React.CSSProperties> = {
|
|
||||||
top: { top: "18%", bottom: "auto" },
|
|
||||||
center: { top: "50%", bottom: "auto", transform: "translateY(-50%)" },
|
|
||||||
bottom: { top: "68%", bottom: "auto" },
|
|
||||||
};
|
|
||||||
|
|
||||||
// Must mirror clipwright/media/hooks.py HOOK_STYLES so preview == burned output.
|
|
||||||
interface HookLook {
|
|
||||||
box: string | null;
|
|
||||||
text: string;
|
|
||||||
outlinePx: number;
|
|
||||||
outlineColor: string;
|
|
||||||
shadow: boolean;
|
|
||||||
}
|
|
||||||
const HOOK_LOOKS: Record<string, HookLook> = {
|
|
||||||
classic: { box: "rgba(255,255,255,0.94)", text: "#000000", outlinePx: 0, outlineColor: "#000", shadow: true },
|
|
||||||
dark: { box: "rgba(18,18,20,0.92)", text: "#FFFFFF", outlinePx: 0, outlineColor: "#000", shadow: true },
|
|
||||||
yellow: { box: "rgba(255,214,0,0.96)", text: "#000000", outlinePx: 0, outlineColor: "#000", shadow: true },
|
|
||||||
red: { box: "rgba(220,38,38,0.96)", text: "#FFFFFF", outlinePx: 0, outlineColor: "#000", shadow: true },
|
|
||||||
outline: { box: null, text: "#FFFFFF", outlinePx: 8, outlineColor: "#000000", shadow: false },
|
|
||||||
outline_yellow: { box: null, text: "#FFD600", outlinePx: 8, outlineColor: "#000000", shadow: false },
|
|
||||||
};
|
|
||||||
|
|
||||||
const textStroke = (px: number, color: string): string => {
|
|
||||||
if (!px) return "none";
|
|
||||||
const o: string[] = [];
|
|
||||||
for (let dx = -px; dx <= px; dx++)
|
|
||||||
for (let dy = -px; dy <= px; dy++)
|
|
||||||
if (dx || dy) o.push(`${dx}px ${dy}px 0 ${color}`);
|
|
||||||
return o.join(", ");
|
|
||||||
};
|
|
||||||
|
|
||||||
export const HookOverlay: React.FC<HookOverlayProps> = ({ config }) => {
|
|
||||||
const { fps } = useVideoConfig();
|
|
||||||
const displayFrames = Math.round(config.displayDurationSec * fps);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<AbsoluteFill>
|
|
||||||
<style>{notoSerifFontFace}</style>
|
|
||||||
<Sequence from={0} durationInFrames={displayFrames} layout="none">
|
|
||||||
<HookBox config={config} displayFrames={displayFrames} />
|
|
||||||
</Sequence>
|
|
||||||
</AbsoluteFill>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
interface HookBoxProps {
|
|
||||||
config: HookConfig;
|
|
||||||
displayFrames: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
const HookBox: React.FC<HookBoxProps> = ({ config, displayFrames }) => {
|
|
||||||
const frame = useCurrentFrame();
|
|
||||||
const { fps } = useVideoConfig();
|
|
||||||
const scale = SIZE_SCALE[config.size] ?? 1.0;
|
|
||||||
|
|
||||||
// Entrance animation
|
|
||||||
let animOpacity = 1;
|
|
||||||
let animScale = 1;
|
|
||||||
let animTranslateY = 0;
|
|
||||||
|
|
||||||
switch (config.entranceAnimation) {
|
|
||||||
case "spring": {
|
|
||||||
const prog = spring({
|
|
||||||
frame,
|
|
||||||
fps,
|
|
||||||
config: { mass: 0.8, stiffness: 200, damping: 15 },
|
|
||||||
durationInFrames: 20,
|
|
||||||
});
|
|
||||||
animScale = interpolate(prog, [0, 1], [0.7, 1]);
|
|
||||||
animOpacity = interpolate(prog, [0, 1], [0, 1]);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case "fade": {
|
|
||||||
animOpacity = interpolate(frame, [0, 15], [0, 1], {
|
|
||||||
extrapolateRight: "clamp",
|
|
||||||
});
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case "slide-up": {
|
|
||||||
const prog = spring({
|
|
||||||
frame,
|
|
||||||
fps,
|
|
||||||
config: { mass: 1, stiffness: 150, damping: 18 },
|
|
||||||
durationInFrames: 20,
|
|
||||||
});
|
|
||||||
animTranslateY = interpolate(prog, [0, 1], [60, 0]);
|
|
||||||
animOpacity = interpolate(prog, [0, 1], [0, 1]);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Exit fade (last 15 frames)
|
|
||||||
const fadeOutStart = displayFrames - 15;
|
|
||||||
if (frame > fadeOutStart) {
|
|
||||||
animOpacity *= interpolate(frame, [fadeOutStart, displayFrames], [1, 0], {
|
|
||||||
extrapolateLeft: "clamp",
|
|
||||||
extrapolateRight: "clamp",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const positionStyle = POSITION_STYLE[config.position] ?? POSITION_STYLE.top;
|
|
||||||
const look = HOOK_LOOKS[config.style ?? "classic"] ?? HOOK_LOOKS.classic;
|
|
||||||
|
|
||||||
// Base font size: 5% of 1080 width (matches clipwright/media/hooks.py logic)
|
|
||||||
const baseFontSize = 1080 * 0.05;
|
|
||||||
const fontSize = Math.round(baseFontSize * scale);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
position: "absolute",
|
|
||||||
left: 0,
|
|
||||||
right: 0,
|
|
||||||
display: "flex",
|
|
||||||
justifyContent: "center",
|
|
||||||
...positionStyle,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
opacity: animOpacity,
|
|
||||||
transform: `scale(${animScale}) translateY(${animTranslateY}px)`,
|
|
||||||
maxWidth: "90%",
|
|
||||||
backgroundColor: look.box ?? "transparent",
|
|
||||||
borderRadius: 20,
|
|
||||||
padding: look.box ? `${25 * scale}px ${30 * scale}px` : `${8 * scale}px ${12 * scale}px`,
|
|
||||||
boxShadow: look.shadow ? "5px 5px 15px rgba(0, 0, 0, 0.25)" : "none",
|
|
||||||
textAlign: "center",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
style={{
|
|
||||||
fontFamily: `'${NOTO_SERIF_FONT_FAMILY}', 'Noto Serif', Georgia, serif`,
|
|
||||||
fontSize,
|
|
||||||
fontWeight: 700,
|
|
||||||
color: look.text,
|
|
||||||
lineHeight: 1.4,
|
|
||||||
wordBreak: "break-word",
|
|
||||||
textShadow: textStroke(look.outlinePx, look.outlineColor),
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{config.text}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
@ -1,33 +0,0 @@
|
||||||
import React from "react";
|
|
||||||
import { AbsoluteFill } from "remotion";
|
|
||||||
import { Video } from "@remotion/media";
|
|
||||||
import type { ShortVideoProps } from "../lib/types";
|
|
||||||
import { Subtitles } from "./Subtitles";
|
|
||||||
import { HookOverlay } from "./HookOverlay";
|
|
||||||
import { VideoEffects } from "./VideoEffects";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Main composition that layers all post-processing on top of the base video.
|
|
||||||
* Uses @remotion/media Video for browser-side rendering compatibility.
|
|
||||||
*/
|
|
||||||
export const ShortVideo: React.FC<Record<string, unknown>> = (rawProps) => {
|
|
||||||
const { videoUrl, subtitles, hook, effects } =
|
|
||||||
rawProps as unknown as ShortVideoProps;
|
|
||||||
return (
|
|
||||||
<AbsoluteFill style={{ backgroundColor: "#000" }}>
|
|
||||||
{/* Layer 1: Base video with optional zoom/color effects */}
|
|
||||||
<VideoEffects config={effects}>
|
|
||||||
<Video
|
|
||||||
src={videoUrl}
|
|
||||||
style={{ width: "100%", height: "100%", objectFit: "cover" }}
|
|
||||||
/>
|
|
||||||
</VideoEffects>
|
|
||||||
|
|
||||||
{/* Layer 2: Animated subtitles */}
|
|
||||||
{subtitles && <Subtitles config={subtitles} />}
|
|
||||||
|
|
||||||
{/* Layer 3: Hook text overlay */}
|
|
||||||
{hook && <HookOverlay config={hook} />}
|
|
||||||
</AbsoluteFill>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
@ -1,227 +0,0 @@
|
||||||
import React from "react";
|
|
||||||
import {
|
|
||||||
AbsoluteFill,
|
|
||||||
Sequence,
|
|
||||||
useCurrentFrame,
|
|
||||||
useVideoConfig,
|
|
||||||
spring,
|
|
||||||
interpolate,
|
|
||||||
} from "remotion";
|
|
||||||
import type { SubtitleConfig } from "../lib/types";
|
|
||||||
import { groupCaptionsIntoBlocks, getActiveWordIndex } from "../lib/captions";
|
|
||||||
import { getFontStack } from "../lib/fonts";
|
|
||||||
|
|
||||||
interface SubtitlesProps {
|
|
||||||
config: SubtitleConfig;
|
|
||||||
}
|
|
||||||
|
|
||||||
const POSITION_MAP: Record<string, React.CSSProperties> = {
|
|
||||||
top: { top: "12%", bottom: "auto" },
|
|
||||||
middle: { top: "45%", bottom: "auto" },
|
|
||||||
bottom: { bottom: "10%", top: "auto" },
|
|
||||||
};
|
|
||||||
|
|
||||||
export const Subtitles: React.FC<SubtitlesProps> = ({ config }) => {
|
|
||||||
const { fps } = useVideoConfig();
|
|
||||||
const blocks = groupCaptionsIntoBlocks(config.captions);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<AbsoluteFill>
|
|
||||||
{blocks.map((block, i) => {
|
|
||||||
const startFrame = Math.round((block.startMs / 1000) * fps);
|
|
||||||
const durationFrames = Math.max(
|
|
||||||
1,
|
|
||||||
Math.round(((block.endMs - block.startMs) / 1000) * fps)
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Sequence
|
|
||||||
key={i}
|
|
||||||
from={startFrame}
|
|
||||||
durationInFrames={durationFrames}
|
|
||||||
layout="none"
|
|
||||||
>
|
|
||||||
<SubtitleBlock
|
|
||||||
block={block}
|
|
||||||
config={config}
|
|
||||||
blockStartMs={block.startMs}
|
|
||||||
/>
|
|
||||||
</Sequence>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</AbsoluteFill>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
interface SubtitleBlockProps {
|
|
||||||
block: ReturnType<typeof groupCaptionsIntoBlocks>[number];
|
|
||||||
config: SubtitleConfig;
|
|
||||||
blockStartMs: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
const SubtitleBlock: React.FC<SubtitleBlockProps> = ({
|
|
||||||
block,
|
|
||||||
config,
|
|
||||||
blockStartMs,
|
|
||||||
}) => {
|
|
||||||
const frame = useCurrentFrame();
|
|
||||||
const { fps } = useVideoConfig();
|
|
||||||
const { style, position } = config;
|
|
||||||
|
|
||||||
// Current time relative to composition start (sequence-relative frame)
|
|
||||||
const currentTimeMs = blockStartMs + (frame / fps) * 1000;
|
|
||||||
const activeIndex = getActiveWordIndex(block.words, currentTimeMs);
|
|
||||||
|
|
||||||
const positionStyle = POSITION_MAP[position] ?? POSITION_MAP.bottom;
|
|
||||||
const fontStack = getFontStack(style.fontFamily);
|
|
||||||
|
|
||||||
// Background box style
|
|
||||||
const hasBg = style.bgOpacity > 0;
|
|
||||||
const bgStyle: React.CSSProperties = hasBg
|
|
||||||
? {
|
|
||||||
backgroundColor: `${style.bgColor}${Math.round(style.bgOpacity * 255)
|
|
||||||
.toString(16)
|
|
||||||
.padStart(2, "0")}`,
|
|
||||||
borderRadius: 8,
|
|
||||||
padding: "8px 16px",
|
|
||||||
}
|
|
||||||
: {};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
position: "absolute",
|
|
||||||
left: 0,
|
|
||||||
right: 0,
|
|
||||||
display: "flex",
|
|
||||||
justifyContent: "center",
|
|
||||||
...positionStyle,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
display: "flex",
|
|
||||||
flexWrap: "wrap",
|
|
||||||
justifyContent: "center",
|
|
||||||
gap: "6px 8px",
|
|
||||||
maxWidth: "85%",
|
|
||||||
...bgStyle,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{block.words.map((word, i) => (
|
|
||||||
<WordSpan
|
|
||||||
key={i}
|
|
||||||
word={word.text}
|
|
||||||
isActive={i === activeIndex}
|
|
||||||
style={style}
|
|
||||||
fontStack={fontStack}
|
|
||||||
animation={style.animation}
|
|
||||||
frame={frame}
|
|
||||||
fps={fps}
|
|
||||||
wordStartMs={word.startMs}
|
|
||||||
blockStartMs={blockStartMs}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
interface WordSpanProps {
|
|
||||||
word: string;
|
|
||||||
isActive: boolean;
|
|
||||||
style: SubtitleConfig["style"];
|
|
||||||
fontStack: string;
|
|
||||||
animation: SubtitleConfig["style"]["animation"];
|
|
||||||
frame: number;
|
|
||||||
fps: number;
|
|
||||||
wordStartMs: number;
|
|
||||||
blockStartMs: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
const WordSpan: React.FC<WordSpanProps> = ({
|
|
||||||
word,
|
|
||||||
isActive,
|
|
||||||
style,
|
|
||||||
fontStack,
|
|
||||||
animation,
|
|
||||||
frame,
|
|
||||||
fps,
|
|
||||||
wordStartMs,
|
|
||||||
blockStartMs,
|
|
||||||
}) => {
|
|
||||||
const wordStartFrame = Math.round(
|
|
||||||
((wordStartMs - blockStartMs) / 1000) * fps
|
|
||||||
);
|
|
||||||
|
|
||||||
let transform = "";
|
|
||||||
let color = style.fontColor;
|
|
||||||
let extraStyle: React.CSSProperties = {};
|
|
||||||
|
|
||||||
if (isActive) {
|
|
||||||
color = style.highlightColor;
|
|
||||||
|
|
||||||
switch (animation) {
|
|
||||||
case "pop": {
|
|
||||||
const scale = spring({
|
|
||||||
frame: frame - wordStartFrame,
|
|
||||||
fps,
|
|
||||||
config: { mass: 0.5, stiffness: 300, damping: 12 },
|
|
||||||
durationInFrames: 10,
|
|
||||||
});
|
|
||||||
const scaleValue = interpolate(scale, [0, 1], [1, 1.25]);
|
|
||||||
transform = `scale(${scaleValue})`;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case "karaoke": {
|
|
||||||
extraStyle = {
|
|
||||||
backgroundColor: style.highlightColor,
|
|
||||||
color: style.bgColor || "#000000",
|
|
||||||
borderRadius: 4,
|
|
||||||
padding: "2px 6px",
|
|
||||||
};
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case "word-highlight": {
|
|
||||||
extraStyle = {
|
|
||||||
textShadow: `0 0 12px ${style.highlightColor}, 0 0 24px ${style.highlightColor}40`,
|
|
||||||
};
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Text stroke via textShadow (CSS paint-order not reliable in Remotion)
|
|
||||||
const strokeShadow =
|
|
||||||
style.borderWidth > 0
|
|
||||||
? [
|
|
||||||
`${style.borderWidth}px 0 0 ${style.borderColor}`,
|
|
||||||
`-${style.borderWidth}px 0 0 ${style.borderColor}`,
|
|
||||||
`0 ${style.borderWidth}px 0 ${style.borderColor}`,
|
|
||||||
`0 -${style.borderWidth}px 0 ${style.borderColor}`,
|
|
||||||
].join(", ")
|
|
||||||
: "none";
|
|
||||||
|
|
||||||
return (
|
|
||||||
<span
|
|
||||||
style={{
|
|
||||||
fontFamily: fontStack,
|
|
||||||
fontSize: style.fontSize,
|
|
||||||
fontWeight: 700,
|
|
||||||
color: animation === "karaoke" && isActive ? undefined : color,
|
|
||||||
textShadow:
|
|
||||||
animation !== "karaoke"
|
|
||||||
? [strokeShadow, extraStyle.textShadow].filter(Boolean).join(", ")
|
|
||||||
: strokeShadow,
|
|
||||||
transform,
|
|
||||||
display: "inline-block",
|
|
||||||
transition: "none",
|
|
||||||
...extraStyle,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{word}
|
|
||||||
</span>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
@ -1,209 +0,0 @@
|
||||||
import React from "react";
|
|
||||||
import { useCurrentFrame, useVideoConfig, interpolate } from "remotion";
|
|
||||||
import type { EffectsConfig, EffectSegment } from "../lib/types";
|
|
||||||
|
|
||||||
interface VideoEffectsProps {
|
|
||||||
config: EffectsConfig | null;
|
|
||||||
children: React.ReactNode;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Wraps children (typically <OffthreadVideo>) with dynamic CSS transforms and filters.
|
|
||||||
* Interpolates smoothly between effect segments.
|
|
||||||
*/
|
|
||||||
export const VideoEffects: React.FC<VideoEffectsProps> = ({
|
|
||||||
config,
|
|
||||||
children,
|
|
||||||
}) => {
|
|
||||||
const frame = useCurrentFrame();
|
|
||||||
const { fps } = useVideoConfig();
|
|
||||||
|
|
||||||
if (!config || config.segments.length === 0) {
|
|
||||||
return <>{children}</>;
|
|
||||||
}
|
|
||||||
|
|
||||||
const currentTimeSec = frame / fps;
|
|
||||||
const { zoom, centerX, centerY, brightness, contrast, saturate } =
|
|
||||||
getInterpolatedValues(config.segments, currentTimeSec, frame, fps);
|
|
||||||
|
|
||||||
const filterParts: string[] = [];
|
|
||||||
if (brightness !== 1) filterParts.push(`brightness(${brightness})`);
|
|
||||||
if (contrast !== 1) filterParts.push(`contrast(${contrast})`);
|
|
||||||
if (saturate !== 1) filterParts.push(`saturate(${saturate})`);
|
|
||||||
const filterStr = filterParts.length > 0 ? filterParts.join(" ") : "none";
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
width: "100%",
|
|
||||||
height: "100%",
|
|
||||||
overflow: "hidden",
|
|
||||||
position: "relative",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
width: "100%",
|
|
||||||
height: "100%",
|
|
||||||
transform: `scale(${zoom})`,
|
|
||||||
transformOrigin: `${centerX * 100}% ${centerY * 100}%`,
|
|
||||||
filter: filterStr,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
interface InterpolatedValues {
|
|
||||||
zoom: number;
|
|
||||||
centerX: number;
|
|
||||||
centerY: number;
|
|
||||||
brightness: number;
|
|
||||||
contrast: number;
|
|
||||||
saturate: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
function getInterpolatedValues(
|
|
||||||
segments: EffectSegment[],
|
|
||||||
timeSec: number,
|
|
||||||
frame: number,
|
|
||||||
fps: number
|
|
||||||
): InterpolatedValues {
|
|
||||||
// Default values (no effect)
|
|
||||||
const defaults: InterpolatedValues = {
|
|
||||||
zoom: 1,
|
|
||||||
centerX: 0.5,
|
|
||||||
centerY: 0.5,
|
|
||||||
brightness: 1,
|
|
||||||
contrast: 1,
|
|
||||||
saturate: 1,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Find active segment
|
|
||||||
const active = segments.find(
|
|
||||||
(s) => timeSec >= s.startSec && timeSec < s.endSec
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!active) {
|
|
||||||
// Check if we're transitioning between segments (smooth fade)
|
|
||||||
const prev = segments.filter((s) => s.endSec <= timeSec).pop();
|
|
||||||
const next = segments.find((s) => s.startSec > timeSec);
|
|
||||||
|
|
||||||
if (prev && next) {
|
|
||||||
const gap = next.startSec - prev.endSec;
|
|
||||||
if (gap < 1.0) {
|
|
||||||
// Short gap: interpolate between prev and next
|
|
||||||
const progress = (timeSec - prev.endSec) / gap;
|
|
||||||
return lerpSegments(prev, next, progress);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Transition out from previous segment
|
|
||||||
if (prev) {
|
|
||||||
const fadeOutDuration = 0.3; // seconds
|
|
||||||
const elapsed = timeSec - prev.endSec;
|
|
||||||
if (elapsed < fadeOutDuration) {
|
|
||||||
const progress = elapsed / fadeOutDuration;
|
|
||||||
return lerpToDefaults(prev, progress, defaults);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Transition into next segment
|
|
||||||
if (next) {
|
|
||||||
const fadeInDuration = 0.3;
|
|
||||||
const remaining = next.startSec - timeSec;
|
|
||||||
if (remaining < fadeInDuration) {
|
|
||||||
const progress = 1 - remaining / fadeInDuration;
|
|
||||||
return lerpFromDefaults(next, progress, defaults);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return defaults;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Inside active segment: smooth entrance/exit at edges
|
|
||||||
const segDuration = active.endSec - active.startSec;
|
|
||||||
const transitionSec = Math.min(0.3, segDuration * 0.15);
|
|
||||||
|
|
||||||
const startFrame = Math.round(active.startSec * fps);
|
|
||||||
const endFrame = Math.round(active.endSec * fps);
|
|
||||||
const transitionFrames = Math.round(transitionSec * fps);
|
|
||||||
|
|
||||||
// Entrance ease
|
|
||||||
const entranceFactor = interpolate(
|
|
||||||
frame,
|
|
||||||
[startFrame, startFrame + transitionFrames],
|
|
||||||
[0, 1],
|
|
||||||
{ extrapolateLeft: "clamp", extrapolateRight: "clamp" }
|
|
||||||
);
|
|
||||||
|
|
||||||
// Exit ease
|
|
||||||
const exitFactor = interpolate(
|
|
||||||
frame,
|
|
||||||
[endFrame - transitionFrames, endFrame],
|
|
||||||
[1, 0],
|
|
||||||
{ extrapolateLeft: "clamp", extrapolateRight: "clamp" }
|
|
||||||
);
|
|
||||||
|
|
||||||
const factor = Math.min(entranceFactor, exitFactor);
|
|
||||||
|
|
||||||
return {
|
|
||||||
zoom: lerp(1, active.zoom, factor),
|
|
||||||
centerX: lerp(0.5, active.zoomCenterX, factor),
|
|
||||||
centerY: lerp(0.5, active.zoomCenterY, factor),
|
|
||||||
brightness: lerp(1, active.brightness, factor),
|
|
||||||
contrast: lerp(1, active.contrast, factor),
|
|
||||||
saturate: lerp(1, active.saturate, factor),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function lerp(a: number, b: number, t: number): number {
|
|
||||||
return a + (b - a) * t;
|
|
||||||
}
|
|
||||||
|
|
||||||
function lerpSegments(
|
|
||||||
a: EffectSegment,
|
|
||||||
b: EffectSegment,
|
|
||||||
t: number
|
|
||||||
): InterpolatedValues {
|
|
||||||
return {
|
|
||||||
zoom: lerp(a.zoom, b.zoom, t),
|
|
||||||
centerX: lerp(a.zoomCenterX, b.zoomCenterX, t),
|
|
||||||
centerY: lerp(a.zoomCenterY, b.zoomCenterY, t),
|
|
||||||
brightness: lerp(a.brightness, b.brightness, t),
|
|
||||||
contrast: lerp(a.contrast, b.contrast, t),
|
|
||||||
saturate: lerp(a.saturate, b.saturate, t),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function lerpToDefaults(
|
|
||||||
seg: EffectSegment,
|
|
||||||
t: number,
|
|
||||||
defaults: InterpolatedValues
|
|
||||||
): InterpolatedValues {
|
|
||||||
return {
|
|
||||||
zoom: lerp(seg.zoom, defaults.zoom, t),
|
|
||||||
centerX: lerp(seg.zoomCenterX, defaults.centerX, t),
|
|
||||||
centerY: lerp(seg.zoomCenterY, defaults.centerY, t),
|
|
||||||
brightness: lerp(seg.brightness, defaults.brightness, t),
|
|
||||||
contrast: lerp(seg.contrast, defaults.contrast, t),
|
|
||||||
saturate: lerp(seg.saturate, defaults.saturate, t),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function lerpFromDefaults(
|
|
||||||
seg: EffectSegment,
|
|
||||||
t: number,
|
|
||||||
defaults: InterpolatedValues
|
|
||||||
): InterpolatedValues {
|
|
||||||
return {
|
|
||||||
zoom: lerp(defaults.zoom, seg.zoom, t),
|
|
||||||
centerX: lerp(defaults.centerX, seg.zoomCenterX, t),
|
|
||||||
centerY: lerp(defaults.centerY, seg.zoomCenterY, t),
|
|
||||||
brightness: lerp(defaults.brightness, seg.brightness, t),
|
|
||||||
contrast: lerp(defaults.contrast, seg.contrast, t),
|
|
||||||
saturate: lerp(defaults.saturate, seg.saturate, t),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
@ -1,4 +0,0 @@
|
||||||
import { registerRoot } from "remotion";
|
|
||||||
import { RemotionRoot } from "./Root";
|
|
||||||
|
|
||||||
registerRoot(RemotionRoot);
|
|
||||||
|
|
@ -1,83 +0,0 @@
|
||||||
import type { CaptionWord } from "./types";
|
|
||||||
|
|
||||||
export interface CaptionBlock {
|
|
||||||
words: CaptionWord[];
|
|
||||||
startMs: number;
|
|
||||||
endMs: number;
|
|
||||||
text: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Groups word-level captions into display blocks.
|
|
||||||
* Same logic as Clipwright' generate_srt: max chars per block, max duration per block.
|
|
||||||
*/
|
|
||||||
export function groupCaptionsIntoBlocks(
|
|
||||||
captions: CaptionWord[],
|
|
||||||
maxChars = 20,
|
|
||||||
maxDurationMs = 2000
|
|
||||||
): CaptionBlock[] {
|
|
||||||
const blocks: CaptionBlock[] = [];
|
|
||||||
let currentWords: CaptionWord[] = [];
|
|
||||||
let blockStartMs = 0;
|
|
||||||
|
|
||||||
for (const word of captions) {
|
|
||||||
if (currentWords.length === 0) {
|
|
||||||
currentWords.push(word);
|
|
||||||
blockStartMs = word.startMs;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const currentTextLen = currentWords.reduce(
|
|
||||||
(sum, w) => sum + w.text.length + 1,
|
|
||||||
0
|
|
||||||
);
|
|
||||||
const duration = word.endMs - blockStartMs;
|
|
||||||
|
|
||||||
if (
|
|
||||||
currentTextLen + word.text.length > maxChars ||
|
|
||||||
duration > maxDurationMs
|
|
||||||
) {
|
|
||||||
// Finalize current block
|
|
||||||
const lastWord = currentWords[currentWords.length - 1];
|
|
||||||
blocks.push({
|
|
||||||
words: [...currentWords],
|
|
||||||
startMs: blockStartMs,
|
|
||||||
endMs: lastWord.endMs,
|
|
||||||
text: currentWords.map((w) => w.text).join(" "),
|
|
||||||
});
|
|
||||||
|
|
||||||
currentWords = [word];
|
|
||||||
blockStartMs = word.startMs;
|
|
||||||
} else {
|
|
||||||
currentWords.push(word);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Final block
|
|
||||||
if (currentWords.length > 0) {
|
|
||||||
const lastWord = currentWords[currentWords.length - 1];
|
|
||||||
blocks.push({
|
|
||||||
words: [...currentWords],
|
|
||||||
startMs: blockStartMs,
|
|
||||||
endMs: lastWord.endMs,
|
|
||||||
text: currentWords.map((w) => w.text).join(" "),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return blocks;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Find the active word at a given time in milliseconds.
|
|
||||||
*/
|
|
||||||
export function getActiveWordIndex(
|
|
||||||
words: CaptionWord[],
|
|
||||||
timeMs: number
|
|
||||||
): number {
|
|
||||||
for (let i = 0; i < words.length; i++) {
|
|
||||||
if (timeMs >= words[i].startMs && timeMs < words[i].endMs) {
|
|
||||||
return i;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
@ -1,33 +0,0 @@
|
||||||
import { staticFile } from "remotion";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* CSS @font-face declaration for NotoSerif-Bold (bundled locally).
|
|
||||||
* Use in components via: <style>{notoSerifFontFace}</style>
|
|
||||||
*/
|
|
||||||
export const NOTO_SERIF_FONT_FAMILY = "NotoSerif-Bold";
|
|
||||||
|
|
||||||
export const notoSerifFontFace = `
|
|
||||||
@font-face {
|
|
||||||
font-family: '${NOTO_SERIF_FONT_FAMILY}';
|
|
||||||
src: url('${staticFile("fonts/NotoSerif-Bold.ttf")}') format('truetype');
|
|
||||||
font-weight: 700;
|
|
||||||
font-style: normal;
|
|
||||||
}
|
|
||||||
`;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Map of subtitle font families to their CSS-safe names.
|
|
||||||
* These match the options available in SubtitleModal.jsx.
|
|
||||||
*/
|
|
||||||
export const SUBTITLE_FONTS: Record<string, string> = {
|
|
||||||
Verdana: "Verdana, Geneva, sans-serif",
|
|
||||||
Arial: "Arial, Helvetica, sans-serif",
|
|
||||||
Impact: "Impact, Haettenschweiler, sans-serif",
|
|
||||||
Helvetica: "Helvetica, Arial, sans-serif",
|
|
||||||
Georgia: "Georgia, 'Times New Roman', serif",
|
|
||||||
"Courier New": "'Courier New', Courier, monospace",
|
|
||||||
};
|
|
||||||
|
|
||||||
export function getFontStack(fontFamily: string): string {
|
|
||||||
return SUBTITLE_FONTS[fontFamily] ?? fontFamily;
|
|
||||||
}
|
|
||||||
|
|
@ -1,139 +0,0 @@
|
||||||
import { z } from "zod";
|
|
||||||
|
|
||||||
// --- Word-level caption ---
|
|
||||||
export interface CaptionWord {
|
|
||||||
text: string;
|
|
||||||
startMs: number;
|
|
||||||
endMs: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Subtitle config ---
|
|
||||||
export type SubtitleAnimation = "none" | "word-highlight" | "pop" | "karaoke";
|
|
||||||
export type SubtitlePosition = "top" | "middle" | "bottom";
|
|
||||||
|
|
||||||
export interface SubtitleStyle {
|
|
||||||
fontFamily: string;
|
|
||||||
fontSize: number;
|
|
||||||
fontColor: string;
|
|
||||||
highlightColor: string;
|
|
||||||
borderColor: string;
|
|
||||||
borderWidth: number;
|
|
||||||
bgColor: string;
|
|
||||||
bgOpacity: number;
|
|
||||||
animation: SubtitleAnimation;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface SubtitleConfig {
|
|
||||||
captions: CaptionWord[];
|
|
||||||
position: SubtitlePosition;
|
|
||||||
style: SubtitleStyle;
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Hook config ---
|
|
||||||
export type HookPosition = "top" | "center" | "bottom";
|
|
||||||
export type HookSize = "S" | "M" | "L";
|
|
||||||
export type HookEntrance = "spring" | "fade" | "slide-up" | "none";
|
|
||||||
|
|
||||||
export type HookStyle =
|
|
||||||
| "classic"
|
|
||||||
| "dark"
|
|
||||||
| "yellow"
|
|
||||||
| "red"
|
|
||||||
| "outline"
|
|
||||||
| "outline_yellow";
|
|
||||||
|
|
||||||
export interface HookConfig {
|
|
||||||
text: string;
|
|
||||||
position: HookPosition;
|
|
||||||
size: HookSize;
|
|
||||||
entranceAnimation: HookEntrance;
|
|
||||||
displayDurationSec: number;
|
|
||||||
style?: HookStyle;
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Effects config ---
|
|
||||||
export interface EffectSegment {
|
|
||||||
startSec: number;
|
|
||||||
endSec: number;
|
|
||||||
zoom: number;
|
|
||||||
zoomCenterX: number;
|
|
||||||
zoomCenterY: number;
|
|
||||||
brightness: number;
|
|
||||||
contrast: number;
|
|
||||||
saturate: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface EffectsConfig {
|
|
||||||
segments: EffectSegment[];
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Main composition props ---
|
|
||||||
export interface ShortVideoProps {
|
|
||||||
videoUrl: string;
|
|
||||||
durationInFrames: number;
|
|
||||||
fps: number;
|
|
||||||
width: number;
|
|
||||||
height: number;
|
|
||||||
subtitles: SubtitleConfig | null;
|
|
||||||
hook: HookConfig | null;
|
|
||||||
effects: EffectsConfig | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Zod schemas for validation (used by render service) ---
|
|
||||||
export const captionWordSchema = z.object({
|
|
||||||
text: z.string(),
|
|
||||||
startMs: z.number(),
|
|
||||||
endMs: z.number(),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const subtitleStyleSchema = z.object({
|
|
||||||
fontFamily: z.string(),
|
|
||||||
fontSize: z.number(),
|
|
||||||
fontColor: z.string(),
|
|
||||||
highlightColor: z.string(),
|
|
||||||
borderColor: z.string(),
|
|
||||||
borderWidth: z.number(),
|
|
||||||
bgColor: z.string(),
|
|
||||||
bgOpacity: z.number().min(0).max(1),
|
|
||||||
animation: z.enum(["none", "word-highlight", "pop", "karaoke"]),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const subtitleConfigSchema = z.object({
|
|
||||||
captions: z.array(captionWordSchema),
|
|
||||||
position: z.enum(["top", "middle", "bottom"]),
|
|
||||||
style: subtitleStyleSchema,
|
|
||||||
});
|
|
||||||
|
|
||||||
export const hookConfigSchema = z.object({
|
|
||||||
text: z.string(),
|
|
||||||
position: z.enum(["top", "center", "bottom"]),
|
|
||||||
size: z.enum(["S", "M", "L"]),
|
|
||||||
entranceAnimation: z.enum(["spring", "fade", "slide-up", "none"]),
|
|
||||||
displayDurationSec: z.number().positive(),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const effectSegmentSchema = z.object({
|
|
||||||
startSec: z.number().min(0),
|
|
||||||
endSec: z.number().positive(),
|
|
||||||
zoom: z.number().min(0.5).max(3),
|
|
||||||
zoomCenterX: z.number().min(0).max(1),
|
|
||||||
zoomCenterY: z.number().min(0).max(1),
|
|
||||||
brightness: z.number().min(0).max(3),
|
|
||||||
contrast: z.number().min(0).max(3),
|
|
||||||
saturate: z.number().min(0).max(3),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const effectsConfigSchema = z.object({
|
|
||||||
segments: z.array(effectSegmentSchema),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const shortVideoPropsSchema = z.object({
|
|
||||||
videoUrl: z.string(),
|
|
||||||
durationInFrames: z.number().int().positive(),
|
|
||||||
fps: z.number().positive(),
|
|
||||||
width: z.number().int().positive(),
|
|
||||||
height: z.number().int().positive(),
|
|
||||||
subtitles: subtitleConfigSchema.nullable(),
|
|
||||||
hook: hookConfigSchema.nullable(),
|
|
||||||
effects: effectsConfigSchema.nullable(),
|
|
||||||
});
|
|
||||||
|
|
@ -1,16 +0,0 @@
|
||||||
{
|
|
||||||
"compilerOptions": {
|
|
||||||
"target": "ES2022",
|
|
||||||
"module": "ES2022",
|
|
||||||
"moduleResolution": "bundler",
|
|
||||||
"jsx": "react-jsx",
|
|
||||||
"strict": true,
|
|
||||||
"esModuleInterop": true,
|
|
||||||
"skipLibCheck": true,
|
|
||||||
"forceConsistentCasingInFileNames": true,
|
|
||||||
"outDir": "./dist",
|
|
||||||
"rootDir": "./src",
|
|
||||||
"declaration": true
|
|
||||||
},
|
|
||||||
"include": ["src/**/*"]
|
|
||||||
}
|
|
||||||
2
render-service/.gitignore
vendored
|
|
@ -1,2 +0,0 @@
|
||||||
node_modules/
|
|
||||||
dist/
|
|
||||||
|
|
@ -1,34 +0,0 @@
|
||||||
FROM node:18-bookworm-slim
|
|
||||||
|
|
||||||
# Install Chromium and FFmpeg for Remotion rendering
|
|
||||||
RUN apt-get update && \
|
|
||||||
apt-get install -y --no-install-recommends chromium ffmpeg && \
|
|
||||||
rm -rf /var/lib/apt/lists/*
|
|
||||||
|
|
||||||
ENV PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium
|
|
||||||
ENV REMOTION_BUNDLE_PATH=/app/remotion
|
|
||||||
ENV OUTPUT_DIR=/output
|
|
||||||
|
|
||||||
WORKDIR /app
|
|
||||||
|
|
||||||
# Copy render service source
|
|
||||||
COPY render-service/package.json ./
|
|
||||||
RUN npm install
|
|
||||||
|
|
||||||
COPY render-service/tsconfig.json ./
|
|
||||||
COPY render-service/src/ ./src/
|
|
||||||
|
|
||||||
# Copy remotion source for bundling
|
|
||||||
COPY remotion/package.json /app/remotion/package.json
|
|
||||||
COPY remotion/tsconfig.json /app/remotion/tsconfig.json
|
|
||||||
COPY remotion/src/ /app/remotion/src/
|
|
||||||
COPY remotion/public/ /app/remotion/public/
|
|
||||||
|
|
||||||
# Install remotion deps
|
|
||||||
RUN cd /app/remotion && npm install
|
|
||||||
|
|
||||||
# Build TypeScript
|
|
||||||
RUN npm run build
|
|
||||||
|
|
||||||
EXPOSE 3100
|
|
||||||
CMD ["node", "dist/server.js"]
|
|
||||||
4097
render-service/package-lock.json
generated
|
|
@ -1,26 +0,0 @@
|
||||||
{
|
|
||||||
"name": "clipwright-render-service",
|
|
||||||
"version": "1.0.0",
|
|
||||||
"private": true,
|
|
||||||
"type": "module",
|
|
||||||
"scripts": {
|
|
||||||
"dev": "tsx watch src/server.ts",
|
|
||||||
"test": "node --import tsx --test src/composition-metadata.test.ts",
|
|
||||||
"build": "tsc",
|
|
||||||
"start": "node dist/server.js"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"@remotion/bundler": "^4.0.0",
|
|
||||||
"@remotion/renderer": "^4.0.0",
|
|
||||||
"express": "^4.21.0",
|
|
||||||
"remotion": "^4.0.0",
|
|
||||||
"uuid": "^10.0.0",
|
|
||||||
"zod": "^4.3.6"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@types/express": "^5.0.0",
|
|
||||||
"@types/uuid": "^10.0.0",
|
|
||||||
"tsx": "^4.19.0",
|
|
||||||
"typescript": "^5.4.0"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,43 +0,0 @@
|
||||||
import path from "node:path";
|
|
||||||
import { bundle } from "@remotion/bundler";
|
|
||||||
|
|
||||||
let bundleLocation: string | null = null;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Bundles the Remotion project on startup and caches the result.
|
|
||||||
* Uses REMOTION_BUNDLE_PATH env var to locate the remotion source
|
|
||||||
* (default: "../remotion" relative to this service's root).
|
|
||||||
*/
|
|
||||||
export async function initBundle(): Promise<void> {
|
|
||||||
const remotionRoot = process.env.REMOTION_BUNDLE_PATH
|
|
||||||
? path.resolve(process.env.REMOTION_BUNDLE_PATH)
|
|
||||||
: path.resolve(import.meta.dirname, "../../remotion");
|
|
||||||
|
|
||||||
const entryPoint = path.join(remotionRoot, "src", "index.ts");
|
|
||||||
|
|
||||||
console.log(`[bundle] Bundling Remotion project from: ${entryPoint}`);
|
|
||||||
|
|
||||||
bundleLocation = await bundle({
|
|
||||||
entryPoint,
|
|
||||||
onProgress: (progress: number) => {
|
|
||||||
if (progress % 10 === 0) {
|
|
||||||
console.log(`[bundle] Progress: ${progress}%`);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log(`[bundle] Bundle created at: ${bundleLocation}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the cached bundle location.
|
|
||||||
* Throws if initBundle() has not been called yet.
|
|
||||||
*/
|
|
||||||
export function getBundleLocation(): string {
|
|
||||||
if (!bundleLocation) {
|
|
||||||
throw new Error(
|
|
||||||
"Bundle not initialized. Call initBundle() before getBundleLocation()."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return bundleLocation;
|
|
||||||
}
|
|
||||||
|
|
@ -1,62 +0,0 @@
|
||||||
import { before, test } from "node:test";
|
|
||||||
import assert from "node:assert/strict";
|
|
||||||
import { selectComposition } from "@remotion/renderer";
|
|
||||||
import { initBundle, getBundleLocation } from "./bundle.js";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Contract test for the render pipeline's composition metadata.
|
|
||||||
*
|
|
||||||
* render-worker.ts passes durationInFrames/fps/width/height via inputProps and
|
|
||||||
* renders whatever selectComposition() reports. Without calculateMetadata on
|
|
||||||
* the ShortVideo Composition, Remotion ignores those inputProps and always
|
|
||||||
* reports the static DEFAULT_PROPS metadata (900 frames / 30fps / 1080x1920),
|
|
||||||
* so every clip renders at 30s regardless of its real length.
|
|
||||||
*/
|
|
||||||
|
|
||||||
const BUNDLE_TIMEOUT_MS = 5 * 60 * 1000;
|
|
||||||
|
|
||||||
before(async () => {
|
|
||||||
await initBundle();
|
|
||||||
}, { timeout: BUNDLE_TIMEOUT_MS });
|
|
||||||
|
|
||||||
test(
|
|
||||||
"selectComposition honors per-render duration/fps/dimensions from inputProps",
|
|
||||||
{ timeout: BUNDLE_TIMEOUT_MS },
|
|
||||||
async () => {
|
|
||||||
const composition = await selectComposition({
|
|
||||||
serveUrl: getBundleLocation(),
|
|
||||||
id: "ShortVideo",
|
|
||||||
inputProps: {
|
|
||||||
videoUrl: "",
|
|
||||||
durationInFrames: 300,
|
|
||||||
fps: 25,
|
|
||||||
width: 720,
|
|
||||||
height: 1280,
|
|
||||||
},
|
|
||||||
logLevel: "error",
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(composition.durationInFrames, 300);
|
|
||||||
assert.equal(composition.fps, 25);
|
|
||||||
assert.equal(composition.width, 720);
|
|
||||||
assert.equal(composition.height, 1280);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
test(
|
|
||||||
"selectComposition falls back to DEFAULT_PROPS metadata when inputProps omit it",
|
|
||||||
{ timeout: BUNDLE_TIMEOUT_MS },
|
|
||||||
async () => {
|
|
||||||
const composition = await selectComposition({
|
|
||||||
serveUrl: getBundleLocation(),
|
|
||||||
id: "ShortVideo",
|
|
||||||
inputProps: { videoUrl: "" },
|
|
||||||
logLevel: "error",
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(composition.durationInFrames, 900);
|
|
||||||
assert.equal(composition.fps, 30);
|
|
||||||
assert.equal(composition.width, 1080);
|
|
||||||
assert.equal(composition.height, 1920);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
@ -1,96 +0,0 @@
|
||||||
import fs from "node:fs";
|
|
||||||
import path from "node:path";
|
|
||||||
import { selectComposition, renderMedia } from "@remotion/renderer";
|
|
||||||
import { getBundleLocation } from "./bundle.js";
|
|
||||||
import { renderJobs } from "./server.js";
|
|
||||||
|
|
||||||
export interface RenderParams {
|
|
||||||
renderId: string;
|
|
||||||
jobId: string;
|
|
||||||
clipIndex: number;
|
|
||||||
props: {
|
|
||||||
videoUrl: string;
|
|
||||||
durationInFrames: number;
|
|
||||||
fps: number;
|
|
||||||
width: number;
|
|
||||||
height: number;
|
|
||||||
subtitles: unknown;
|
|
||||||
hook: unknown;
|
|
||||||
effects: unknown;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Executes a Remotion render in the background.
|
|
||||||
* Updates the in-memory render job map with progress and final status.
|
|
||||||
*/
|
|
||||||
export async function executeRender(params: RenderParams): Promise<void> {
|
|
||||||
const { renderId, jobId, clipIndex, props } = params;
|
|
||||||
const job = renderJobs.get(renderId);
|
|
||||||
|
|
||||||
if (!job) {
|
|
||||||
console.error(`[render-worker] Job ${renderId} not found in map`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
job.status = "rendering";
|
|
||||||
job.progress = 0;
|
|
||||||
|
|
||||||
console.log(
|
|
||||||
`[render-worker] Starting render ${renderId} (job=${jobId}, clip=${clipIndex})`
|
|
||||||
);
|
|
||||||
|
|
||||||
const bundleLocation = getBundleLocation();
|
|
||||||
|
|
||||||
// Select the composition with the provided input props
|
|
||||||
const composition = await selectComposition({
|
|
||||||
serveUrl: bundleLocation,
|
|
||||||
id: "ShortVideo",
|
|
||||||
inputProps: props,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Determine output directory and file path
|
|
||||||
const outputDir = process.env.OUTPUT_DIR
|
|
||||||
? path.resolve(process.env.OUTPUT_DIR)
|
|
||||||
: path.resolve(import.meta.dirname, "../../output");
|
|
||||||
|
|
||||||
const jobOutputDir = path.join(outputDir, jobId);
|
|
||||||
fs.mkdirSync(jobOutputDir, { recursive: true });
|
|
||||||
|
|
||||||
const timestamp = Date.now();
|
|
||||||
const outputFileName = `remotion_${clipIndex}_${timestamp}.mp4`;
|
|
||||||
const outputLocation = path.join(jobOutputDir, outputFileName);
|
|
||||||
|
|
||||||
console.log(`[render-worker] Output: ${outputLocation}`);
|
|
||||||
|
|
||||||
// Render the video
|
|
||||||
await renderMedia({
|
|
||||||
composition,
|
|
||||||
serveUrl: bundleLocation,
|
|
||||||
codec: "h264",
|
|
||||||
crf: 22,
|
|
||||||
outputLocation,
|
|
||||||
onProgress: ({ progress }) => {
|
|
||||||
const percent = Math.round(progress * 100);
|
|
||||||
job.progress = percent;
|
|
||||||
|
|
||||||
if (percent % 10 === 0) {
|
|
||||||
console.log(`[render-worker] ${renderId} progress: ${percent}%`);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
// Success
|
|
||||||
job.status = "done";
|
|
||||||
job.progress = 100;
|
|
||||||
job.outputUrl = outputLocation;
|
|
||||||
|
|
||||||
console.log(`[render-worker] Render ${renderId} completed: ${outputLocation}`);
|
|
||||||
} catch (err) {
|
|
||||||
job.status = "error";
|
|
||||||
job.error = err instanceof Error ? err.message : String(err);
|
|
||||||
|
|
||||||
console.error(`[render-worker] Render ${renderId} failed:`, err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,166 +0,0 @@
|
||||||
import express from "express";
|
|
||||||
import { v4 as uuidv4 } from "uuid";
|
|
||||||
import { z } from "zod";
|
|
||||||
import { initBundle } from "./bundle.js";
|
|
||||||
import { executeRender } from "./render-worker.js";
|
|
||||||
|
|
||||||
// --- Render status types ---
|
|
||||||
|
|
||||||
export type RenderStatus = "queued" | "rendering" | "done" | "error";
|
|
||||||
|
|
||||||
export interface RenderJob {
|
|
||||||
renderId: string;
|
|
||||||
jobId: string;
|
|
||||||
clipIndex: number;
|
|
||||||
status: RenderStatus;
|
|
||||||
progress: number;
|
|
||||||
outputUrl?: string;
|
|
||||||
error?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// In-memory render job map
|
|
||||||
export const renderJobs = new Map<string, RenderJob>();
|
|
||||||
|
|
||||||
// --- Request validation schema ---
|
|
||||||
|
|
||||||
const renderRequestSchema = z.object({
|
|
||||||
jobId: z.string().min(1),
|
|
||||||
clipIndex: z.number().int().min(0),
|
|
||||||
props: z.object({
|
|
||||||
videoUrl: z.string(),
|
|
||||||
durationInFrames: z.number().int().positive(),
|
|
||||||
fps: z.number().positive(),
|
|
||||||
width: z.number().int().positive(),
|
|
||||||
height: z.number().int().positive(),
|
|
||||||
subtitles: z.any().nullable().optional(),
|
|
||||||
hook: z.any().nullable().optional(),
|
|
||||||
effects: z.any().nullable().optional(),
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
// --- Express app ---
|
|
||||||
|
|
||||||
const app = express();
|
|
||||||
app.use(express.json({ limit: "10mb" }));
|
|
||||||
|
|
||||||
const PORT = parseInt(process.env.PORT || "3100", 10);
|
|
||||||
const OUTPUT_DIR = process.env.OUTPUT_DIR || "/output";
|
|
||||||
|
|
||||||
// Serve video files from the shared output volume so Remotion can access them via HTTP
|
|
||||||
app.use("/output", express.static(OUTPUT_DIR));
|
|
||||||
|
|
||||||
// Health check
|
|
||||||
app.get("/health", (_req, res) => {
|
|
||||||
res.json({ ok: true });
|
|
||||||
});
|
|
||||||
|
|
||||||
// Submit a render job
|
|
||||||
app.post("/render", (req, res) => {
|
|
||||||
const parsed = renderRequestSchema.safeParse(req.body);
|
|
||||||
|
|
||||||
if (!parsed.success) {
|
|
||||||
res.status(400).json({
|
|
||||||
error: "Invalid request body",
|
|
||||||
details: parsed.error.issues,
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const { jobId, clipIndex, props } = parsed.data;
|
|
||||||
const renderId = uuidv4();
|
|
||||||
|
|
||||||
const job: RenderJob = {
|
|
||||||
renderId,
|
|
||||||
jobId,
|
|
||||||
clipIndex,
|
|
||||||
status: "queued",
|
|
||||||
progress: 0,
|
|
||||||
};
|
|
||||||
|
|
||||||
renderJobs.set(renderId, job);
|
|
||||||
|
|
||||||
console.log(
|
|
||||||
`[render] Queued render ${renderId} for job=${jobId} clip=${clipIndex}`
|
|
||||||
);
|
|
||||||
|
|
||||||
// Resolve video URL: convert frontend/backend URLs to renderer's own static server
|
|
||||||
// The renderer serves /output/* from the shared Docker volume
|
|
||||||
let resolvedVideoUrl = props.videoUrl;
|
|
||||||
const videoPathMatch = props.videoUrl.match(/\/videos\/([^/]+)\/(.+)$/);
|
|
||||||
if (videoPathMatch) {
|
|
||||||
resolvedVideoUrl = `http://localhost:${PORT}/output/${videoPathMatch[1]}/${videoPathMatch[2]}`;
|
|
||||||
console.log(`[render] Resolved video URL: ${props.videoUrl} -> ${resolvedVideoUrl}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fire and forget - render runs in background
|
|
||||||
executeRender({
|
|
||||||
renderId,
|
|
||||||
jobId,
|
|
||||||
clipIndex,
|
|
||||||
props: {
|
|
||||||
videoUrl: resolvedVideoUrl,
|
|
||||||
durationInFrames: props.durationInFrames,
|
|
||||||
fps: props.fps,
|
|
||||||
width: props.width,
|
|
||||||
height: props.height,
|
|
||||||
subtitles: props.subtitles ?? null,
|
|
||||||
hook: props.hook ?? null,
|
|
||||||
effects: props.effects ?? null,
|
|
||||||
},
|
|
||||||
}).catch((err) => {
|
|
||||||
console.error(`[render] Unhandled error for ${renderId}:`, err);
|
|
||||||
const existingJob = renderJobs.get(renderId);
|
|
||||||
if (existingJob) {
|
|
||||||
existingJob.status = "error";
|
|
||||||
existingJob.error =
|
|
||||||
err instanceof Error ? err.message : "Unknown error";
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
res.status(202).json({ renderId, status: "queued" });
|
|
||||||
});
|
|
||||||
|
|
||||||
// Get render status
|
|
||||||
app.get("/render/:renderId", (req, res) => {
|
|
||||||
const { renderId } = req.params;
|
|
||||||
const job = renderJobs.get(renderId);
|
|
||||||
|
|
||||||
if (!job) {
|
|
||||||
res.status(404).json({ error: "Render not found" });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const response: Record<string, unknown> = {
|
|
||||||
renderId: job.renderId,
|
|
||||||
status: job.status,
|
|
||||||
};
|
|
||||||
|
|
||||||
if (job.progress !== undefined) {
|
|
||||||
response.progress = job.progress;
|
|
||||||
}
|
|
||||||
if (job.outputUrl) {
|
|
||||||
response.outputUrl = job.outputUrl;
|
|
||||||
}
|
|
||||||
if (job.error) {
|
|
||||||
response.error = job.error;
|
|
||||||
}
|
|
||||||
|
|
||||||
res.json(response);
|
|
||||||
});
|
|
||||||
|
|
||||||
// --- Start server ---
|
|
||||||
|
|
||||||
async function main() {
|
|
||||||
console.log("[render-service] Initializing Remotion bundle...");
|
|
||||||
await initBundle();
|
|
||||||
console.log("[render-service] Bundle ready.");
|
|
||||||
|
|
||||||
app.listen(PORT, () => {
|
|
||||||
console.log(`[render-service] Listening on port ${PORT}`);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
main().catch((err) => {
|
|
||||||
console.error("[render-service] Fatal error during startup:", err);
|
|
||||||
process.exit(1);
|
|
||||||
});
|
|
||||||
|
|
@ -1,17 +0,0 @@
|
||||||
{
|
|
||||||
"compilerOptions": {
|
|
||||||
"target": "ES2022",
|
|
||||||
"module": "ESNext",
|
|
||||||
"moduleResolution": "bundler",
|
|
||||||
"strict": true,
|
|
||||||
"esModuleInterop": true,
|
|
||||||
"skipLibCheck": true,
|
|
||||||
"forceConsistentCasingInFileNames": true,
|
|
||||||
"outDir": "dist",
|
|
||||||
"rootDir": "src",
|
|
||||||
"declaration": true,
|
|
||||||
"resolveJsonModule": true
|
|
||||||
},
|
|
||||||
"include": ["src"],
|
|
||||||
"exclude": ["node_modules", "dist"]
|
|
||||||
}
|
|
||||||
11
requirements-e2e.txt
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
-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
|
||||||
6
requirements-ml-e2e.txt
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
# 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
|
||||||
|
Before Width: | Height: | Size: 390 KiB |
|
Before Width: | Height: | Size: 257 KiB |
|
Before Width: | Height: | Size: 2.8 MiB |
|
Before Width: | Height: | Size: 328 KiB |
1
tests/e2e/__init__.py
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
"""End-to-end tests (API, pipeline, browser). See tests/e2e/conftest.py."""
|
||||||
1
tests/e2e/api/__init__.py
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
"""API-level end-to-end tests (one module per route family)."""
|
||||||
152
tests/e2e/api/conftest.py
Normal file
|
|
@ -0,0 +1,152 @@
|
||||||
|
"""API E2E fixtures: an in-process ASGI client, a fake pipeline subprocess, and
|
||||||
|
an event-based queue helper.
|
||||||
|
|
||||||
|
``httpx.ASGITransport`` is used on purpose: ``starlette.testclient.TestClient``
|
||||||
|
runs the app's lifespan (which starts the queue worker, the resume scanner and
|
||||||
|
the drain signal handler) on its own event loop, which leaks tasks and fights
|
||||||
|
the test's loop. The client below never runs lifespan; the startup-recovery
|
||||||
|
test is the one place that opts into ``LifespanManager`` explicitly.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import contextlib
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
|
class FakePopen:
|
||||||
|
"""Stand-in for ``subprocess.Popen`` on the real worker path.
|
||||||
|
|
||||||
|
Parses the ``-o``/``--output`` directory out of ``cmd``, writes a canonical
|
||||||
|
``<base>_clip_1.mp4`` plus a metadata JSON there, and exposes the surface
|
||||||
|
``run_job`` needs (``stdout``, ``poll()``, ``returncode``, ``kill()``).
|
||||||
|
The canonical filename keeps ``_clips_actually_rendered`` deterministic
|
||||||
|
even though ``enqueue_output`` runs on a thread and may not have consumed
|
||||||
|
the ``CLIP_READY`` line yet.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Per-test knobs.
|
||||||
|
base_name = "clipwright"
|
||||||
|
clips = 1
|
||||||
|
returncode = 0
|
||||||
|
lines = None
|
||||||
|
|
||||||
|
instances = []
|
||||||
|
|
||||||
|
def __init__(self, cmd, stdout=None, stderr=None, env=None, cwd=None, **kwargs):
|
||||||
|
self.cmd = list(cmd)
|
||||||
|
self.returncode = type(self).returncode
|
||||||
|
self.killed = False
|
||||||
|
type(self).instances.append(self)
|
||||||
|
|
||||||
|
output_dir = self._output_dir(self.cmd)
|
||||||
|
if output_dir:
|
||||||
|
self._write_outputs(output_dir)
|
||||||
|
|
||||||
|
self.stdout = io.BytesIO(self._stdout_bytes())
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _output_dir(cmd):
|
||||||
|
for flag in ("-o", "--output"):
|
||||||
|
if flag in cmd:
|
||||||
|
idx = cmd.index(flag)
|
||||||
|
if idx + 1 < len(cmd):
|
||||||
|
return cmd[idx + 1]
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _stdout_bytes(self):
|
||||||
|
lines = self.lines
|
||||||
|
if lines is None:
|
||||||
|
lines = [f"CLIP_READY 0 {self.base_name}_clip_1.mp4", "done"]
|
||||||
|
return ("\n".join(lines) + "\n").encode("utf-8")
|
||||||
|
|
||||||
|
def _write_outputs(self, output_dir):
|
||||||
|
import os
|
||||||
|
|
||||||
|
os.makedirs(output_dir, exist_ok=True)
|
||||||
|
shorts = []
|
||||||
|
for i in range(self.clips):
|
||||||
|
shorts.append({
|
||||||
|
"start": float(i * 10),
|
||||||
|
"end": float(i * 10 + 8),
|
||||||
|
"predicted_score": 80 - i,
|
||||||
|
"video_title_for_youtube_short": f"Fake clip {i + 1}",
|
||||||
|
"viral_hook_text": f"Hook {i + 1}",
|
||||||
|
"video_description_for_tiktok": "Fake #test",
|
||||||
|
"video_description_for_instagram": "Fake #test",
|
||||||
|
})
|
||||||
|
with open(os.path.join(output_dir, f"{self.base_name}_clip_{i + 1}.mp4"), "wb") as fh:
|
||||||
|
fh.write(b"\x00" * 2048)
|
||||||
|
with open(os.path.join(output_dir, f"{self.base_name}_metadata.json"), "w") as fh:
|
||||||
|
json.dump({"shorts": shorts, "cost_analysis": {"total_cost": 0.0}}, fh)
|
||||||
|
|
||||||
|
def poll(self):
|
||||||
|
return self.returncode
|
||||||
|
|
||||||
|
def kill(self):
|
||||||
|
self.killed = True
|
||||||
|
|
||||||
|
def wait(self, timeout=None):
|
||||||
|
return self.returncode
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def fake_popen(monkeypatch):
|
||||||
|
"""Install ``FakePopen`` as ``app.subprocess.Popen`` for one test.
|
||||||
|
|
||||||
|
``app.subprocess`` is the shared ``subprocess`` module, so this also covers
|
||||||
|
any other module that resolves ``subprocess.Popen`` at call time.
|
||||||
|
"""
|
||||||
|
import clipwright.api.app as app
|
||||||
|
|
||||||
|
FakePopen.instances = []
|
||||||
|
monkeypatch.setattr(app.subprocess, "Popen", FakePopen)
|
||||||
|
return FakePopen
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
async def client(app_state):
|
||||||
|
"""In-process HTTP client bound to the app under test (no lifespan)."""
|
||||||
|
from httpx import ASGITransport, AsyncClient
|
||||||
|
|
||||||
|
app = app_state.app
|
||||||
|
transport = ASGITransport(app=app.app)
|
||||||
|
async with AsyncClient(transport=transport, base_url="http://testserver") as c:
|
||||||
|
yield c
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def job_done(monkeypatch):
|
||||||
|
"""Return ``await job_done(job_id)``: run the queue until that job ends.
|
||||||
|
|
||||||
|
Wraps ``app.run_job_wrapper`` (resolved by global name at call time) so the
|
||||||
|
wrapper can set an ``asyncio.Event`` once the original returns, then runs
|
||||||
|
``app.process_queue()`` as a task and waits on the event with a bound. No
|
||||||
|
sleeps. The worker is cancelled in ``finally``.
|
||||||
|
"""
|
||||||
|
|
||||||
|
async def _wait(job_id, timeout=10.0):
|
||||||
|
import clipwright.api.app as app
|
||||||
|
|
||||||
|
done = asyncio.Event()
|
||||||
|
original = app.run_job_wrapper
|
||||||
|
|
||||||
|
async def wrapper(jid):
|
||||||
|
try:
|
||||||
|
await original(jid)
|
||||||
|
finally:
|
||||||
|
if jid == job_id:
|
||||||
|
done.set()
|
||||||
|
|
||||||
|
monkeypatch.setattr(app, "run_job_wrapper", wrapper)
|
||||||
|
worker = asyncio.create_task(app.process_queue())
|
||||||
|
try:
|
||||||
|
await asyncio.wait_for(done.wait(), timeout)
|
||||||
|
finally:
|
||||||
|
worker.cancel()
|
||||||
|
with contextlib.suppress(asyncio.CancelledError):
|
||||||
|
await worker
|
||||||
|
|
||||||
|
return _wait
|
||||||
46
tests/e2e/api/test_download_all.py
Normal file
|
|
@ -0,0 +1,46 @@
|
||||||
|
"""L1 API core: the per-job "download all clips" ZIP bundle."""
|
||||||
|
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import zipfile
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.e2e
|
||||||
|
|
||||||
|
|
||||||
|
async def test_download_all_returns_a_zip_of_every_clip(client, app_state, seeded_job):
|
||||||
|
job_id = seeded_job(job_id="job-zip", base="bundle", clips=2)
|
||||||
|
|
||||||
|
resp = await client.get(f"/api/jobs/{job_id}/download-all")
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert resp.headers["content-type"] == "application/zip"
|
||||||
|
|
||||||
|
with zipfile.ZipFile(io.BytesIO(resp.content)) as zf:
|
||||||
|
names = sorted(zf.namelist())
|
||||||
|
assert names == [
|
||||||
|
"clip_01_bundle_clip_1.mp4",
|
||||||
|
"clip_02_bundle_clip_2.mp4",
|
||||||
|
]
|
||||||
|
for name in names:
|
||||||
|
assert zf.read(name)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_download_all_without_metadata_is_404(client):
|
||||||
|
resp = await client.get("/api/jobs/nobody-home/download-all")
|
||||||
|
assert resp.status_code == 404
|
||||||
|
assert resp.json()["detail"] == "Job not found"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_download_all_without_clip_files_is_404(client, app_state):
|
||||||
|
job_id = "job-empty"
|
||||||
|
job_dir = app_state.out / job_id
|
||||||
|
job_dir.mkdir()
|
||||||
|
# Metadata promises a clip; the file itself was never rendered.
|
||||||
|
(job_dir / "empty_metadata.json").write_text(json.dumps({
|
||||||
|
"shorts": [{"start": 0.0, "end": 5.0, "video_title_for_youtube_short": "x"}],
|
||||||
|
}))
|
||||||
|
|
||||||
|
resp = await client.get(f"/api/jobs/{job_id}/download-all")
|
||||||
|
assert resp.status_code == 404
|
||||||
|
assert resp.json()["detail"] == "No clip files found for this job"
|
||||||
263
tests/e2e/api/test_edit_effects.py
Normal file
|
|
@ -0,0 +1,263 @@
|
||||||
|
"""L2 API editing E2E: ``POST /api/edit`` and ``POST /api/effects/generate``.
|
||||||
|
|
||||||
|
Both routes resolve their heavy ``VideoEditor`` by module-global name at call
|
||||||
|
time, so the editor (Gemini upload + ffmpeg filter build/apply) is stubbed at
|
||||||
|
``app.VideoEditor``. The clip on disk is a REAL ffmpeg video because the edit
|
||||||
|
route probes it with OpenCV and the effects route probes it with ffprobe.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.e2e
|
||||||
|
|
||||||
|
app_module = pytest.importorskip("clipwright.api.app")
|
||||||
|
|
||||||
|
|
||||||
|
class StubVideoEditor:
|
||||||
|
"""Records calls; writes the edited output; can fail at any stage."""
|
||||||
|
|
||||||
|
filter_data = {"filter_string": "hue=s=0", "edits": [{"type": "bw_moment"}]}
|
||||||
|
effects_config = {
|
||||||
|
"segments": [{
|
||||||
|
"startSec": 0, "endSec": 6, "zoom": 1.1,
|
||||||
|
"zoomCenterX": 0.5, "zoomCenterY": 0.5,
|
||||||
|
"brightness": 1.0, "contrast": 1.0, "saturate": 1.0,
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
error_stage = None
|
||||||
|
instances = []
|
||||||
|
|
||||||
|
def __init__(self, api_key=None):
|
||||||
|
self.api_key = api_key
|
||||||
|
self.uploaded = []
|
||||||
|
type(self).instances.append(self)
|
||||||
|
|
||||||
|
def upload_video(self, path):
|
||||||
|
if self.error_stage == "upload":
|
||||||
|
raise RuntimeError("upload exploded")
|
||||||
|
self.uploaded.append(path)
|
||||||
|
return {"name": "files/fake"}
|
||||||
|
|
||||||
|
def get_ffmpeg_filter(self, vid, duration, **kwargs):
|
||||||
|
if self.error_stage == "filter":
|
||||||
|
raise RuntimeError("filter exploded")
|
||||||
|
self.filter_kwargs = kwargs
|
||||||
|
return self.filter_data
|
||||||
|
|
||||||
|
def get_effects_config(self, vid, duration, **kwargs):
|
||||||
|
if self.error_stage == "effects":
|
||||||
|
raise RuntimeError("effects exploded")
|
||||||
|
self.effects_kwargs = kwargs
|
||||||
|
return self.effects_config
|
||||||
|
|
||||||
|
def apply_edits(self, input_path, output_path, filter_data):
|
||||||
|
if self.error_stage == "apply":
|
||||||
|
raise RuntimeError("apply exploded")
|
||||||
|
with open(output_path, "wb") as fh:
|
||||||
|
fh.write(b"edited-bytes")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def stub_editor(monkeypatch):
|
||||||
|
StubVideoEditor.instances = []
|
||||||
|
StubVideoEditor.error_stage = None
|
||||||
|
StubVideoEditor.filter_data = {
|
||||||
|
"filter_string": "hue=s=0", "edits": [{"type": "bw_moment"}]}
|
||||||
|
StubVideoEditor.effects_config = {
|
||||||
|
"segments": [{
|
||||||
|
"startSec": 0, "endSec": 6, "zoom": 1.1,
|
||||||
|
"zoomCenterX": 0.5, "zoomCenterY": 0.5,
|
||||||
|
"brightness": 1.0, "contrast": 1.0, "saturate": 1.0,
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
monkeypatch.setattr(app_module, "VideoEditor", StubVideoEditor)
|
||||||
|
return StubVideoEditor
|
||||||
|
|
||||||
|
|
||||||
|
def _make_job(app_state, media_factory, job_id="job-edit", base="edit",
|
||||||
|
output_format="auto"):
|
||||||
|
"""A completed job whose canonical clip is a real, probeable video."""
|
||||||
|
job_dir = app_state.out / job_id
|
||||||
|
job_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copy(media_factory.six, job_dir / f"{base}_clip_1.mp4")
|
||||||
|
clip = {
|
||||||
|
"start": 0.0,
|
||||||
|
"end": 6.0,
|
||||||
|
"video_title_for_youtube_short": "Edit clip",
|
||||||
|
"viral_hook_text": "Hook",
|
||||||
|
"video_url": f"/videos/{job_id}/{base}_clip_1.mp4",
|
||||||
|
}
|
||||||
|
(job_dir / f"{base}_metadata.json").write_text(json.dumps({
|
||||||
|
"shorts": [clip],
|
||||||
|
"transcript": {
|
||||||
|
"language": "en",
|
||||||
|
"segments": [{"start": 0.0, "end": 6.0, "text": "hi there",
|
||||||
|
"words": [{"word": "hi", "start": 1.0, "end": 1.4}]}],
|
||||||
|
},
|
||||||
|
"output_format": output_format,
|
||||||
|
"cost_analysis": {"total_cost": 0.0},
|
||||||
|
}))
|
||||||
|
app_module.jobs[job_id] = {
|
||||||
|
"status": "completed",
|
||||||
|
"logs": [],
|
||||||
|
"result": {"clips": [dict(clip)], "cost_analysis": {}},
|
||||||
|
"user_id": None,
|
||||||
|
}
|
||||||
|
return {"job_id": job_id, "base": base, "dir": job_dir, "clip": clip}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def editor_job(app_state, media_factory):
|
||||||
|
return _make_job(app_state, media_factory)
|
||||||
|
|
||||||
|
|
||||||
|
# --- POST /api/edit ---------------------------------------------------------
|
||||||
|
|
||||||
|
class TestEdit:
|
||||||
|
async def test_success_writes_file_and_persists(self, client, app_state,
|
||||||
|
stub_editor, editor_job):
|
||||||
|
job_id, base = editor_job["job_id"], editor_job["base"]
|
||||||
|
resp = await client.post("/api/edit", json={
|
||||||
|
"job_id": job_id, "clip_index": 0, "api_key": "test-key"})
|
||||||
|
assert resp.status_code == 200, resp.text
|
||||||
|
data = resp.json()
|
||||||
|
assert data["success"] is True
|
||||||
|
assert data["edit_plan"] == stub_editor.filter_data
|
||||||
|
assert data["new_video_url"] == (
|
||||||
|
f"/videos/{job_id}/edited_{base}_clip_1.mp4")
|
||||||
|
|
||||||
|
# The edited file exists on disk...
|
||||||
|
assert (editor_job["dir"] / f"edited_{base}_clip_1.mp4").is_file()
|
||||||
|
# ...and the new current version is persisted to metadata + memory.
|
||||||
|
meta = json.loads((editor_job["dir"] / f"{base}_metadata.json").read_text())
|
||||||
|
assert meta["shorts"][0]["video_url"] == data["new_video_url"]
|
||||||
|
mem = app_module.jobs[job_id]["result"]["clips"][0]
|
||||||
|
assert mem["video_url"] == data["new_video_url"]
|
||||||
|
# The temp ASCII copy the editor used was cleaned up.
|
||||||
|
assert not (editor_job["dir"] / f"temp_input_{job_id}.mp4").exists()
|
||||||
|
|
||||||
|
async def test_404_unknown_job(self, client, stub_editor):
|
||||||
|
resp = await client.post("/api/edit", json={
|
||||||
|
"job_id": "nope", "clip_index": 0, "api_key": "k"})
|
||||||
|
assert resp.status_code == 404
|
||||||
|
|
||||||
|
async def test_missing_file_is_wrapped_as_500(self, client, stub_editor,
|
||||||
|
editor_job):
|
||||||
|
# The route raises its 404 INSIDE the try that ends in a catch-all
|
||||||
|
# `except Exception -> 500`, so a missing input file surfaces as 500
|
||||||
|
# (documented deviation from the 404 the spec expected).
|
||||||
|
resp = await client.post("/api/edit", json={
|
||||||
|
"job_id": editor_job["job_id"], "clip_index": 0, "api_key": "k",
|
||||||
|
"input_filename": "does-not-exist.mp4"})
|
||||||
|
assert resp.status_code == 500
|
||||||
|
|
||||||
|
async def test_400_no_result(self, client, stub_editor):
|
||||||
|
app_module.jobs["job-noresult"] = {
|
||||||
|
"status": "completed", "result": {}, "user_id": None}
|
||||||
|
resp = await client.post("/api/edit", json={
|
||||||
|
"job_id": "job-noresult", "clip_index": 0, "api_key": "k"})
|
||||||
|
assert resp.status_code == 400
|
||||||
|
|
||||||
|
async def test_400_missing_key(self, client, monkeypatch, stub_editor,
|
||||||
|
editor_job):
|
||||||
|
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
|
||||||
|
resp = await client.post("/api/edit", json={
|
||||||
|
"job_id": editor_job["job_id"], "clip_index": 0})
|
||||||
|
assert resp.status_code == 400
|
||||||
|
assert "Gemini" in resp.json()["detail"]
|
||||||
|
|
||||||
|
async def test_500_editor_error(self, client, stub_editor, editor_job):
|
||||||
|
stub_editor.error_stage = "filter"
|
||||||
|
resp = await client.post("/api/edit", json={
|
||||||
|
"job_id": editor_job["job_id"], "clip_index": 0, "api_key": "k"})
|
||||||
|
assert resp.status_code == 500
|
||||||
|
|
||||||
|
async def test_input_filename_is_basenamed(self, client, app_state,
|
||||||
|
stub_editor, editor_job):
|
||||||
|
# The target exists ONLY inside the job dir; the traversal path one
|
||||||
|
# level up does not. Success proves the name was basenamed.
|
||||||
|
(editor_job["dir"] / "secret.mp4").write_bytes(b"inside")
|
||||||
|
assert not (app_state.out / "secret.mp4").exists()
|
||||||
|
resp = await client.post("/api/edit", json={
|
||||||
|
"job_id": editor_job["job_id"], "clip_index": 0, "api_key": "k",
|
||||||
|
"input_filename": "../secret.mp4"})
|
||||||
|
assert resp.status_code == 200, resp.text
|
||||||
|
assert resp.json()["new_video_url"].endswith("/edited_secret.mp4")
|
||||||
|
assert (editor_job["dir"] / "edited_secret.mp4").is_file()
|
||||||
|
|
||||||
|
|
||||||
|
# --- POST /api/effects/generate --------------------------------------------
|
||||||
|
|
||||||
|
class TestEffects:
|
||||||
|
async def test_success_returns_config(self, client, stub_editor,
|
||||||
|
editor_job):
|
||||||
|
resp = await client.post(
|
||||||
|
"/api/effects/generate",
|
||||||
|
headers={"X-Gemini-Key": "test-key"},
|
||||||
|
json={"job_id": editor_job["job_id"], "clip_index": 0})
|
||||||
|
assert resp.status_code == 200, resp.text
|
||||||
|
assert resp.json() == {"effects": stub_editor.effects_config}
|
||||||
|
# The real clip was probed and the transcript from metadata was loaded.
|
||||||
|
assert stub_editor.instances[-1].effects_kwargs["width"] == 320
|
||||||
|
assert stub_editor.instances[-1].effects_kwargs["height"] == 180
|
||||||
|
assert stub_editor.instances[-1].effects_kwargs["transcript"] is not None
|
||||||
|
|
||||||
|
async def test_404_unknown_job(self, client, stub_editor):
|
||||||
|
resp = await client.post(
|
||||||
|
"/api/effects/generate", headers={"X-Gemini-Key": "k"},
|
||||||
|
json={"job_id": "nope", "clip_index": 0})
|
||||||
|
assert resp.status_code == 404
|
||||||
|
|
||||||
|
async def test_404_missing_file(self, client, stub_editor, editor_job):
|
||||||
|
resp = await client.post(
|
||||||
|
"/api/effects/generate", headers={"X-Gemini-Key": "k"},
|
||||||
|
json={"job_id": editor_job["job_id"], "clip_index": 0,
|
||||||
|
"input_filename": "nope.mp4"})
|
||||||
|
assert resp.status_code == 404
|
||||||
|
|
||||||
|
async def test_400_no_result(self, client, stub_editor):
|
||||||
|
app_module.jobs["job-noresult-2"] = {
|
||||||
|
"status": "completed", "result": {}, "user_id": None}
|
||||||
|
resp = await client.post(
|
||||||
|
"/api/effects/generate", headers={"X-Gemini-Key": "k"},
|
||||||
|
json={"job_id": "job-noresult-2", "clip_index": 0})
|
||||||
|
assert resp.status_code == 400
|
||||||
|
|
||||||
|
async def test_400_missing_key(self, client, monkeypatch, stub_editor,
|
||||||
|
editor_job):
|
||||||
|
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
|
||||||
|
resp = await client.post(
|
||||||
|
"/api/effects/generate",
|
||||||
|
json={"job_id": editor_job["job_id"], "clip_index": 0})
|
||||||
|
assert resp.status_code == 400
|
||||||
|
|
||||||
|
async def test_500_editor_error(self, client, stub_editor, editor_job):
|
||||||
|
stub_editor.error_stage = "effects"
|
||||||
|
resp = await client.post(
|
||||||
|
"/api/effects/generate", headers={"X-Gemini-Key": "k"},
|
||||||
|
json={"job_id": editor_job["job_id"], "clip_index": 0})
|
||||||
|
assert resp.status_code == 500
|
||||||
|
|
||||||
|
async def test_500_none_config(self, client, stub_editor, editor_job):
|
||||||
|
stub_editor.effects_config = None
|
||||||
|
resp = await client.post(
|
||||||
|
"/api/effects/generate", headers={"X-Gemini-Key": "k"},
|
||||||
|
json={"job_id": editor_job["job_id"], "clip_index": 0})
|
||||||
|
assert resp.status_code == 500
|
||||||
|
|
||||||
|
async def test_input_filename_is_basenamed(self, client, app_state,
|
||||||
|
media_factory, stub_editor,
|
||||||
|
editor_job):
|
||||||
|
# Real video only inside the job dir; the traversal target one level
|
||||||
|
# up is absent, so success proves the name was basenamed.
|
||||||
|
shutil.copy(media_factory.six, editor_job["dir"] / "secret.mp4")
|
||||||
|
assert not (app_state.out / "secret.mp4").exists()
|
||||||
|
resp = await client.post(
|
||||||
|
"/api/effects/generate", headers={"X-Gemini-Key": "k"},
|
||||||
|
json={"job_id": editor_job["job_id"], "clip_index": 0,
|
||||||
|
"input_filename": "../secret.mp4"})
|
||||||
|
assert resp.status_code == 200, resp.text
|
||||||
82
tests/e2e/api/test_foundation_smoke.py
Normal file
|
|
@ -0,0 +1,82 @@
|
||||||
|
"""Phase-0 foundation smoke test.
|
||||||
|
|
||||||
|
Proves the shared E2E scaffolding works before the per-route lanes are built:
|
||||||
|
|
||||||
|
1. ``/health`` answers through the in-process ASGI client.
|
||||||
|
2. ``app_state`` gives each test a private ``jobs`` dict (isolation).
|
||||||
|
3. A disk-seeded completed job is recoverable the same way a restart recovers.
|
||||||
|
4. The session ``media_factory`` produces ffprobe-able fixture videos.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.e2e
|
||||||
|
|
||||||
|
|
||||||
|
async def test_health_ok(client):
|
||||||
|
resp = await client.get("/health")
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert resp.json() == {"status": "ok"}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_app_state_isolation_a(app_state):
|
||||||
|
# Fresh per test: nothing seeded this dict.
|
||||||
|
assert app_state.app.jobs == {}
|
||||||
|
app_state.app.jobs["isolation-a"] = {"status": "sentinel"}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_app_state_isolation_b(app_state):
|
||||||
|
# If the previous test's write leaked, this dict would not be empty.
|
||||||
|
assert app_state.app.jobs == {}
|
||||||
|
app_state.app.jobs["isolation-b"] = {"status": "sentinel"}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_disk_seeded_job_is_recoverable(app_state, seeded_job, client):
|
||||||
|
job_id = seeded_job(job_id="job-smoke", base="smoke", clips=1)
|
||||||
|
|
||||||
|
job = app_state.app.jobs[job_id]
|
||||||
|
assert job["status"] == "completed"
|
||||||
|
assert job["output_dir"] == str(app_state.out / job_id)
|
||||||
|
|
||||||
|
clips = job["result"]["clips"]
|
||||||
|
assert len(clips) == 1
|
||||||
|
assert clips[0]["video_url"].endswith("/smoke_clip_1.mp4")
|
||||||
|
|
||||||
|
clip_path = app_state.out / job_id / "smoke_clip_1.mp4"
|
||||||
|
assert clip_path.is_file() and clip_path.stat().st_size > 0
|
||||||
|
|
||||||
|
# The recovered clip is actually servable: this proves the /videos mount was
|
||||||
|
# repointed at the per-test output tree (it captures its directory at
|
||||||
|
# import time, so the app_state rebind has to move it explicitly).
|
||||||
|
resp = await client.get(clips[0]["video_url"])
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert resp.content
|
||||||
|
|
||||||
|
|
||||||
|
def _probe(path):
|
||||||
|
out = subprocess.run(
|
||||||
|
["ffprobe", "-v", "error", "-show_entries",
|
||||||
|
"format=duration:stream=codec_type", "-of", "json", str(path)],
|
||||||
|
capture_output=True, text=True, check=True,
|
||||||
|
)
|
||||||
|
return json.loads(out.stdout)
|
||||||
|
|
||||||
|
|
||||||
|
def test_media_factory_files_are_probeable(media_factory):
|
||||||
|
sixty = _probe(media_factory.sixty)
|
||||||
|
assert float(sixty["format"]["duration"]) == pytest.approx(60.0, abs=1.0)
|
||||||
|
assert {"video", "audio"} <= {s["codec_type"] for s in sixty["streams"]}
|
||||||
|
|
||||||
|
six = _probe(media_factory.six)
|
||||||
|
assert float(six["format"]["duration"]) == pytest.approx(6.0, abs=1.0)
|
||||||
|
assert {"video", "audio"} <= {s["codec_type"] for s in six["streams"]}
|
||||||
|
|
||||||
|
silent = _probe(media_factory.silent)
|
||||||
|
assert {s["codec_type"] for s in silent["streams"]} == {"video"}
|
||||||
|
|
||||||
|
cuts = _probe(media_factory.cuts)
|
||||||
|
assert float(cuts["format"]["duration"]) == pytest.approx(6.0, abs=1.0)
|
||||||
|
assert {"video"} <= {s["codec_type"] for s in cuts["streams"]}
|
||||||
65
tests/e2e/api/test_health_config.py
Normal file
|
|
@ -0,0 +1,65 @@
|
||||||
|
"""L1 API core: liveness/readiness probes and the dashboard bootstrap config.
|
||||||
|
|
||||||
|
Drives the real app through ``httpx.ASGITransport`` (no lifespan), so the
|
||||||
|
``_stopping`` flag is flipped by hand the same way SIGTERM does at runtime.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.e2e
|
||||||
|
|
||||||
|
|
||||||
|
async def test_health_is_ok(client):
|
||||||
|
resp = await client.get("/health")
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert resp.json() == {"status": "ok"}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_health_ready_when_running(client, app_state):
|
||||||
|
app_state.app._stopping = False
|
||||||
|
resp = await client.get("/health/ready")
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert resp.json() == {"status": "ready"}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_health_ready_is_503_while_stopping(client, app_state, monkeypatch):
|
||||||
|
monkeypatch.setattr(app_state.app, "_stopping", True)
|
||||||
|
resp = await client.get("/health/ready")
|
||||||
|
assert resp.status_code == 503
|
||||||
|
assert resp.json() == {"status": "stopping"}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_config_youtube_enabled(client, app_state, monkeypatch):
|
||||||
|
monkeypatch.setattr(app_state.app, "DISABLE_YOUTUBE_URL", False)
|
||||||
|
monkeypatch.delenv("LLM_BASE_URL", raising=False)
|
||||||
|
monkeypatch.delenv("LLM_PROVIDER", raising=False)
|
||||||
|
|
||||||
|
resp = await client.get("/api/config")
|
||||||
|
assert resp.status_code == 200
|
||||||
|
body = resp.json()
|
||||||
|
assert body["youtubeUrlEnabled"] is True
|
||||||
|
assert body["billingEnabled"] is False
|
||||||
|
assert body["jobRetentionSeconds"] == app_state.app.JOB_RETENTION_SECONDS
|
||||||
|
# No OpenAI-compatible server configured -> the dashboard is told nothing.
|
||||||
|
assert body["localLlm"] is None
|
||||||
|
|
||||||
|
|
||||||
|
async def test_config_youtube_disabled(client, app_state, monkeypatch):
|
||||||
|
monkeypatch.setattr(app_state.app, "DISABLE_YOUTUBE_URL", True)
|
||||||
|
resp = await client.get("/api/config")
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert resp.json()["youtubeUrlEnabled"] is False
|
||||||
|
|
||||||
|
|
||||||
|
async def test_config_describes_local_llm(client, app_state, monkeypatch):
|
||||||
|
monkeypatch.setenv("LLM_PROVIDER", "openai")
|
||||||
|
monkeypatch.setenv("LLM_BASE_URL", "http://127.0.0.1:11434")
|
||||||
|
monkeypatch.delenv("LLM_MODEL", raising=False)
|
||||||
|
|
||||||
|
resp = await client.get("/api/config")
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert resp.json()["localLlm"] == {
|
||||||
|
"provider": "openai",
|
||||||
|
"model": "llama3.1:8b",
|
||||||
|
"baseUrl": "http://127.0.0.1:11434",
|
||||||
|
}
|
||||||
150
tests/e2e/api/test_hook.py
Normal file
|
|
@ -0,0 +1,150 @@
|
||||||
|
"""L2 API editing E2E: POST /api/hook (add / update / remove).
|
||||||
|
|
||||||
|
The overlay is a REAL ffmpeg pass using the repo's bundled fonts (the fonts/
|
||||||
|
directory is present in the test checkout, so no network fetch happens). The
|
||||||
|
clip is a real fixture video with audio.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.e2e
|
||||||
|
|
||||||
|
app_module = pytest.importorskip("clipwright.api.app")
|
||||||
|
|
||||||
|
|
||||||
|
def _probe(path):
|
||||||
|
out = subprocess.run(
|
||||||
|
["ffprobe", "-v", "error", "-show_entries",
|
||||||
|
"stream=codec_type:format=duration", "-of", "json", str(path)],
|
||||||
|
capture_output=True, text=True, check=True)
|
||||||
|
return json.loads(out.stdout)
|
||||||
|
|
||||||
|
|
||||||
|
def _make_job(app_state, media_factory, job_id="job-hook", base="hk"):
|
||||||
|
job_dir = app_state.out / job_id
|
||||||
|
job_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copy(media_factory.six, job_dir / f"{base}_clip_1.mp4")
|
||||||
|
clip = {
|
||||||
|
"start": 0.0,
|
||||||
|
"end": 6.0,
|
||||||
|
"video_title_for_youtube_short": "Hook clip",
|
||||||
|
"video_url": f"/videos/{job_id}/{base}_clip_1.mp4",
|
||||||
|
}
|
||||||
|
(job_dir / f"{base}_metadata.json").write_text(json.dumps({
|
||||||
|
"shorts": [clip], "output_format": "auto", "cost_analysis": {}}))
|
||||||
|
app_module.jobs[job_id] = {
|
||||||
|
"status": "completed",
|
||||||
|
"logs": [],
|
||||||
|
"result": {"clips": [dict(clip)], "cost_analysis": {}},
|
||||||
|
"user_id": None,
|
||||||
|
}
|
||||||
|
return {"job_id": job_id, "base": base, "dir": job_dir,
|
||||||
|
"meta": job_dir / f"{base}_metadata.json"}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def hook_job(app_state, media_factory):
|
||||||
|
return _make_job(app_state, media_factory)
|
||||||
|
|
||||||
|
|
||||||
|
def _hooked_files(job):
|
||||||
|
return sorted(job["dir"].glob("hooked_*_hk_clip_1.mp4"))
|
||||||
|
|
||||||
|
|
||||||
|
# --- POST /api/hook ---------------------------------------------------------
|
||||||
|
|
||||||
|
class TestHook:
|
||||||
|
async def test_add_burns_hook(self, client, hook_job):
|
||||||
|
resp = await client.post("/api/hook", json={
|
||||||
|
"job_id": hook_job["job_id"], "clip_index": 0,
|
||||||
|
"text": "HELLO WORLD", "style": "pill", "position": "top",
|
||||||
|
"size": "M", "font": "anton"})
|
||||||
|
assert resp.status_code == 200, resp.text
|
||||||
|
data = resp.json()
|
||||||
|
assert data["success"] is True
|
||||||
|
assert data["burned_hook"]["text"] == "HELLO WORLD"
|
||||||
|
assert data["burned_hook"]["style"] == "pill"
|
||||||
|
assert data["new_video_url"].startswith(
|
||||||
|
f"/videos/{hook_job['job_id']}/hooked_")
|
||||||
|
assert data["new_video_url"].endswith("_hk_clip_1.mp4")
|
||||||
|
|
||||||
|
out = _hooked_files(hook_job)
|
||||||
|
assert len(out) == 1
|
||||||
|
assert out[0].stat().st_size > 0
|
||||||
|
assert "video" in {s["codec_type"] for s in _probe(out[0])["streams"]}
|
||||||
|
|
||||||
|
meta = json.loads(hook_job["meta"].read_text())
|
||||||
|
assert meta["shorts"][0]["auto_hook"]["text"] == "HELLO WORLD"
|
||||||
|
assert meta["shorts"][0]["video_url"] == data["new_video_url"]
|
||||||
|
mem = app_module.jobs[hook_job["job_id"]]["result"]["clips"][0]
|
||||||
|
assert mem["auto_hook"]["text"] == "HELLO WORLD"
|
||||||
|
|
||||||
|
async def test_update_replaces_without_stacking(self, client, hook_job):
|
||||||
|
first = await client.post("/api/hook", json={
|
||||||
|
"job_id": hook_job["job_id"], "clip_index": 0,
|
||||||
|
"text": "FIRST", "style": "pill"})
|
||||||
|
assert first.status_code == 200, first.text
|
||||||
|
|
||||||
|
second = await client.post("/api/hook", json={
|
||||||
|
"job_id": hook_job["job_id"], "clip_index": 0,
|
||||||
|
"text": "SECOND", "style": "dark"})
|
||||||
|
assert second.status_code == 200, second.text
|
||||||
|
name = second.json()["new_video_url"].split("/")[-1]
|
||||||
|
# Exactly one hooked_ prefix: the old burn was walked back, not stacked.
|
||||||
|
assert name.count("hooked_") == 1
|
||||||
|
assert name.endswith("_hk_clip_1.mp4")
|
||||||
|
|
||||||
|
meta = json.loads(hook_job["meta"].read_text())
|
||||||
|
assert meta["shorts"][0]["auto_hook"]["text"] == "SECOND"
|
||||||
|
assert meta["shorts"][0]["auto_hook"]["style"] == "dark"
|
||||||
|
|
||||||
|
async def test_remove_strips_hook(self, client, hook_job):
|
||||||
|
add = await client.post("/api/hook", json={
|
||||||
|
"job_id": hook_job["job_id"], "clip_index": 0,
|
||||||
|
"text": "REMOVE ME", "style": "pill"})
|
||||||
|
assert add.status_code == 200
|
||||||
|
|
||||||
|
resp = await client.post("/api/hook", json={
|
||||||
|
"job_id": hook_job["job_id"], "clip_index": 0, "remove": True})
|
||||||
|
assert resp.status_code == 200, resp.text
|
||||||
|
data = resp.json()
|
||||||
|
assert data["burned_hook"] is None
|
||||||
|
assert data["new_video_url"] == (
|
||||||
|
f"/videos/{hook_job['job_id']}/hk_clip_1.mp4")
|
||||||
|
meta = json.loads(hook_job["meta"].read_text())
|
||||||
|
assert "auto_hook" not in meta["shorts"][0]
|
||||||
|
mem = app_module.jobs[hook_job["job_id"]]["result"]["clips"][0]
|
||||||
|
assert "auto_hook" not in mem
|
||||||
|
|
||||||
|
async def test_empty_text_400(self, client, hook_job):
|
||||||
|
resp = await client.post("/api/hook", json={
|
||||||
|
"job_id": hook_job["job_id"], "clip_index": 0, "text": " "})
|
||||||
|
assert resp.status_code == 400
|
||||||
|
assert "Hook text" in resp.json()["detail"]
|
||||||
|
|
||||||
|
async def test_404_unknown_job(self, client):
|
||||||
|
resp = await client.post("/api/hook", json={
|
||||||
|
"job_id": "nope", "clip_index": 0, "text": "x"})
|
||||||
|
assert resp.status_code == 404
|
||||||
|
|
||||||
|
async def test_404_missing_metadata(self, client, hook_job):
|
||||||
|
os.remove(hook_job["meta"])
|
||||||
|
resp = await client.post("/api/hook", json={
|
||||||
|
"job_id": hook_job["job_id"], "clip_index": 0, "text": "x"})
|
||||||
|
assert resp.status_code == 404
|
||||||
|
|
||||||
|
async def test_404_clip_out_of_range(self, client, hook_job):
|
||||||
|
resp = await client.post("/api/hook", json={
|
||||||
|
"job_id": hook_job["job_id"], "clip_index": 5, "text": "x"})
|
||||||
|
assert resp.status_code == 404
|
||||||
|
|
||||||
|
async def test_404_missing_file(self, client, hook_job):
|
||||||
|
resp = await client.post("/api/hook", json={
|
||||||
|
"job_id": hook_job["job_id"], "clip_index": 0, "text": "x",
|
||||||
|
"input_filename": "gone.mp4"})
|
||||||
|
assert resp.status_code == 404
|
||||||
423
tests/e2e/api/test_postiz_routes.py
Normal file
|
|
@ -0,0 +1,423 @@
|
||||||
|
"""L3 E2E: the Postiz integration routes.
|
||||||
|
|
||||||
|
Everything outbound is stubbed at the ``clipwright.integrations.postiz`` seam
|
||||||
|
(``app.py`` calls the module functions through ``asyncio.to_thread``), so the
|
||||||
|
tests exercise the real route logic: credential resolution, channel selection
|
||||||
|
by id vs the legacy ``platforms`` fallback, the per-provider ``settings``
|
||||||
|
mapping, the schedule window and the error translation.
|
||||||
|
|
||||||
|
The unit suite (``tests/test_postiz.py``) already pins the helper functions;
|
||||||
|
these are the ASGI-level contracts through the shared ``client`` fixture.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import functools
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.e2e
|
||||||
|
|
||||||
|
POSTIZ_HEADERS = {"X-Postiz-Url": "https://postiz.example", "X-Postiz-Key": "k"}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def postiz_stub(monkeypatch):
|
||||||
|
"""Capture every Postiz call and return scripted responses.
|
||||||
|
|
||||||
|
Mutate ``stub.integrations`` / ``stub.*_result`` / ``stub.errors`` per test.
|
||||||
|
"""
|
||||||
|
from clipwright.integrations import postiz as postiz_mod
|
||||||
|
|
||||||
|
class Stub:
|
||||||
|
def __init__(self):
|
||||||
|
self.calls = {}
|
||||||
|
self.integrations = [
|
||||||
|
{"id": "yt-1", "name": "Main", "identifier": "youtube", "disabled": False},
|
||||||
|
{"id": "yt-2", "name": "Second", "identifier": "youtube", "disabled": False},
|
||||||
|
{"id": "ig-1", "name": "IG", "identifier": "instagram-standalone",
|
||||||
|
"disabled": False},
|
||||||
|
{"id": "tt-1", "name": "TT", "identifier": "tiktok-business",
|
||||||
|
"disabled": False},
|
||||||
|
]
|
||||||
|
self.upload_result = {"id": "media-1", "path": "media/path"}
|
||||||
|
self.create_result = [{"postId": "p1", "integration": "yt-1"}]
|
||||||
|
self.posts_result = [
|
||||||
|
{"id": "sched-1", "date": "2030-01-01T00:00:00.000Z",
|
||||||
|
"integration": {"id": "yt-1"}},
|
||||||
|
]
|
||||||
|
self.delete_result = None
|
||||||
|
self.analytics_result = {"views": 5, "likes": 1}
|
||||||
|
self.analytics_post_result = {"likes": 3}
|
||||||
|
self.errors = {}
|
||||||
|
|
||||||
|
def _record(self, name, *args, **kwargs):
|
||||||
|
self.calls.setdefault(name, []).append((args, kwargs))
|
||||||
|
if name in self.errors:
|
||||||
|
raise self.errors[name]
|
||||||
|
return {
|
||||||
|
"list_integrations": self.integrations,
|
||||||
|
"upload_media": self.upload_result,
|
||||||
|
"create_post": self.create_result,
|
||||||
|
"list_posts": self.posts_result,
|
||||||
|
"delete_post": self.delete_result,
|
||||||
|
"analytics": self.analytics_result,
|
||||||
|
"analytics_post": self.analytics_post_result,
|
||||||
|
}[name]
|
||||||
|
|
||||||
|
stub = Stub()
|
||||||
|
for name in ("list_integrations", "upload_media", "create_post",
|
||||||
|
"list_posts", "delete_post", "analytics", "analytics_post"):
|
||||||
|
monkeypatch.setattr(postiz_mod, name, functools.partial(stub._record, name))
|
||||||
|
return stub
|
||||||
|
|
||||||
|
|
||||||
|
def _payload(stub):
|
||||||
|
"""The payload handed to ``create_post`` (base, key, payload)."""
|
||||||
|
return stub.calls["create_post"][0][0][2]
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# POST /api/postiz/post
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
async def test_post_success_by_integration_id(client, seeded_job, postiz_stub):
|
||||||
|
job_id = seeded_job(job_id="job-post", base="pw", clips=1)
|
||||||
|
resp = await client.post(
|
||||||
|
"/api/postiz/post",
|
||||||
|
headers=POSTIZ_HEADERS,
|
||||||
|
json={"job_id": job_id, "clip_index": 0,
|
||||||
|
"integration_ids": ["ig-1", "tt-1"],
|
||||||
|
"title": "My Title", "description": "Watch this #fun #clips"},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 200, resp.text
|
||||||
|
body = resp.json()
|
||||||
|
assert body["success"] is True
|
||||||
|
assert body["results"] == postiz_stub.create_result
|
||||||
|
assert [p["platform"] for p in body["posted"]] == ["instagram", "tiktok"]
|
||||||
|
assert [p["name"] for p in body["posted"]] == ["IG", "TT"]
|
||||||
|
|
||||||
|
payload = _payload(postiz_stub)
|
||||||
|
assert payload["type"] == "now"
|
||||||
|
assert payload["shortLink"] is False
|
||||||
|
posts = payload["posts"]
|
||||||
|
assert [p["integration"]["id"] for p in posts] == ["ig-1", "tt-1"]
|
||||||
|
# __type echoes the real identifier, not the mapped platform.
|
||||||
|
assert [p["settings"]["__type"] for p in posts] == \
|
||||||
|
["instagram-standalone", "tiktok-business"]
|
||||||
|
assert posts[0]["settings"] == {"__type": "instagram-standalone", "post_type": "post"}
|
||||||
|
assert posts[1]["settings"]["content_posting_method"] == "DIRECT_POST"
|
||||||
|
assert posts[0]["value"][0]["content"] == "Watch this #fun #clips"
|
||||||
|
assert posts[0]["value"][0]["image"][0] == {"id": "media-1", "path": "media/path"}
|
||||||
|
# The local clip was re-uploaded to Postiz first.
|
||||||
|
assert postiz_stub.calls["upload_media"][0][0][2].endswith("pw_clip_1.mp4")
|
||||||
|
|
||||||
|
|
||||||
|
async def test_post_legacy_platforms_use_the_identifier_map(client, seeded_job, postiz_stub):
|
||||||
|
job_id = seeded_job(job_id="job-legacy", base="pw")
|
||||||
|
resp = await client.post(
|
||||||
|
"/api/postiz/post",
|
||||||
|
headers=POSTIZ_HEADERS,
|
||||||
|
json={"job_id": job_id, "clip_index": 0,
|
||||||
|
"platforms": ["instagram", "tiktok"]},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 200, resp.text
|
||||||
|
posts = _payload(postiz_stub)["posts"]
|
||||||
|
assert [p["integration"]["id"] for p in posts] == ["ig-1", "tt-1"]
|
||||||
|
assert [p["settings"]["__type"] for p in posts] == \
|
||||||
|
["instagram-standalone", "tiktok-business"]
|
||||||
|
assert [e["platform"] for e in resp.json()["posted"]] == ["instagram", "tiktok"]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_post_future_schedule_sets_schedule_type(client, seeded_job, postiz_stub):
|
||||||
|
job_id = seeded_job(job_id="job-sched", base="pw")
|
||||||
|
future = datetime.now(timezone.utc) + timedelta(days=2)
|
||||||
|
resp = await client.post(
|
||||||
|
"/api/postiz/post",
|
||||||
|
headers=POSTIZ_HEADERS,
|
||||||
|
json={"job_id": job_id, "clip_index": 0, "integration_ids": ["yt-1"],
|
||||||
|
"scheduled_date": future.isoformat()},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 200, resp.text
|
||||||
|
payload = _payload(postiz_stub)
|
||||||
|
assert payload["type"] == "schedule"
|
||||||
|
assert payload["date"] == future.astimezone(timezone.utc).strftime(
|
||||||
|
"%Y-%m-%dT%H:%M:%S.000Z")
|
||||||
|
|
||||||
|
|
||||||
|
async def test_post_schedule_accepts_an_iso_offset(client, seeded_job, postiz_stub):
|
||||||
|
job_id = seeded_job(job_id="job-tz", base="pw")
|
||||||
|
resp = await client.post(
|
||||||
|
"/api/postiz/post",
|
||||||
|
headers=POSTIZ_HEADERS,
|
||||||
|
json={"job_id": job_id, "clip_index": 0, "integration_ids": ["yt-1"],
|
||||||
|
"scheduled_date": "2030-06-01T12:00:00+02:00"},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 200, resp.text
|
||||||
|
# The offset is normalised to UTC.
|
||||||
|
assert _payload(postiz_stub)["date"] == "2030-06-01T10:00:00.000Z"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_post_past_schedule_is_400_before_upload(client, seeded_job, postiz_stub):
|
||||||
|
job_id = seeded_job(job_id="job-past", base="pw")
|
||||||
|
past = (datetime.now(timezone.utc) - timedelta(hours=1)).isoformat()
|
||||||
|
resp = await client.post(
|
||||||
|
"/api/postiz/post",
|
||||||
|
headers=POSTIZ_HEADERS,
|
||||||
|
json={"job_id": job_id, "clip_index": 0, "integration_ids": ["yt-1"],
|
||||||
|
"scheduled_date": past},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 400
|
||||||
|
assert "past" in resp.json()["detail"].lower()
|
||||||
|
assert "upload_media" not in postiz_stub.calls
|
||||||
|
assert "create_post" not in postiz_stub.calls
|
||||||
|
|
||||||
|
|
||||||
|
async def test_post_unparseable_schedule_is_400(client, seeded_job, postiz_stub):
|
||||||
|
job_id = seeded_job(job_id="job-bad-date", base="pw")
|
||||||
|
resp = await client.post(
|
||||||
|
"/api/postiz/post",
|
||||||
|
headers=POSTIZ_HEADERS,
|
||||||
|
json={"job_id": job_id, "clip_index": 0, "integration_ids": ["yt-1"],
|
||||||
|
"scheduled_date": "tomorrow"},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
async def test_post_unknown_integration_id_is_400(client, seeded_job, postiz_stub):
|
||||||
|
job_id = seeded_job(job_id="job-unknown", base="pw")
|
||||||
|
resp = await client.post(
|
||||||
|
"/api/postiz/post",
|
||||||
|
headers=POSTIZ_HEADERS,
|
||||||
|
json={"job_id": job_id, "clip_index": 0, "integration_ids": ["nope"]},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 400
|
||||||
|
assert "nope" in resp.json()["detail"]
|
||||||
|
assert "upload_media" not in postiz_stub.calls
|
||||||
|
|
||||||
|
|
||||||
|
async def test_post_disabled_integration_id_is_400(client, seeded_job, postiz_stub):
|
||||||
|
job_id = seeded_job(job_id="job-disabled", base="pw")
|
||||||
|
postiz_stub.integrations = [
|
||||||
|
{"id": "ig-1", "name": "IG", "identifier": "instagram-standalone",
|
||||||
|
"disabled": True},
|
||||||
|
]
|
||||||
|
resp = await client.post(
|
||||||
|
"/api/postiz/post",
|
||||||
|
headers=POSTIZ_HEADERS,
|
||||||
|
json={"job_id": job_id, "clip_index": 0, "integration_ids": ["ig-1"]},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 400
|
||||||
|
assert "Disabled" in resp.json()["detail"]
|
||||||
|
assert "upload_media" not in postiz_stub.calls
|
||||||
|
|
||||||
|
|
||||||
|
async def test_post_not_connected_platform_is_400(client, seeded_job, postiz_stub):
|
||||||
|
job_id = seeded_job(job_id="job-notconn", base="pw")
|
||||||
|
postiz_stub.integrations = [
|
||||||
|
{"id": "yt-1", "name": "Main", "identifier": "youtube", "disabled": False},
|
||||||
|
]
|
||||||
|
resp = await client.post(
|
||||||
|
"/api/postiz/post",
|
||||||
|
headers=POSTIZ_HEADERS,
|
||||||
|
json={"job_id": job_id, "clip_index": 0, "platforms": ["instagram"]},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 400
|
||||||
|
assert "Not connected" in resp.json()["detail"]
|
||||||
|
assert "upload_media" not in postiz_stub.calls
|
||||||
|
|
||||||
|
|
||||||
|
async def test_post_missing_credentials_is_400(client, seeded_job, postiz_stub,
|
||||||
|
monkeypatch):
|
||||||
|
monkeypatch.delenv("POSTIZ_URL", raising=False)
|
||||||
|
monkeypatch.delenv("POSTIZ_API_KEY", raising=False)
|
||||||
|
job_id = seeded_job(job_id="job-creds", base="pw")
|
||||||
|
body = {"job_id": job_id, "clip_index": 0, "platforms": ["youtube"]}
|
||||||
|
|
||||||
|
r = await client.post("/api/postiz/post", headers={"X-Postiz-Key": "k"}, json=body)
|
||||||
|
assert r.status_code == 400 and "URL" in r.json()["detail"]
|
||||||
|
|
||||||
|
r = await client.post("/api/postiz/post",
|
||||||
|
headers={"X-Postiz-Url": "https://p.example"}, json=body)
|
||||||
|
assert r.status_code == 400 and "key" in r.json()["detail"].lower()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_post_no_channels_is_400(client, seeded_job, postiz_stub):
|
||||||
|
job_id = seeded_job(job_id="job-nochan", base="pw")
|
||||||
|
resp = await client.post(
|
||||||
|
"/api/postiz/post",
|
||||||
|
headers=POSTIZ_HEADERS,
|
||||||
|
json={"job_id": job_id, "clip_index": 0},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 400
|
||||||
|
assert "No channels" in resp.json()["detail"]
|
||||||
|
assert "upload_media" not in postiz_stub.calls
|
||||||
|
|
||||||
|
|
||||||
|
async def test_post_unknown_job_is_404(client, postiz_stub):
|
||||||
|
resp = await client.post(
|
||||||
|
"/api/postiz/post",
|
||||||
|
headers=POSTIZ_HEADERS,
|
||||||
|
json={"job_id": "nobody-home", "clip_index": 0, "integration_ids": ["yt-1"]},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 404
|
||||||
|
assert resp.json()["detail"] == "Job not found"
|
||||||
|
assert postiz_stub.calls == {}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_post_missing_clip_file_is_404(client, app_state, postiz_stub):
|
||||||
|
app_state.app.jobs["job-nofile"] = {
|
||||||
|
"result": {"clips": [{"video_url": "/videos/job-nofile/missing.mp4"}]},
|
||||||
|
}
|
||||||
|
resp = await client.post(
|
||||||
|
"/api/postiz/post",
|
||||||
|
headers=POSTIZ_HEADERS,
|
||||||
|
json={"job_id": "job-nofile", "clip_index": 0, "integration_ids": ["yt-1"]},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 404
|
||||||
|
assert "not found" in resp.json()["detail"].lower()
|
||||||
|
assert "upload_media" not in postiz_stub.calls
|
||||||
|
|
||||||
|
|
||||||
|
async def test_post_clip_index_out_of_range_is_400(client, seeded_job, postiz_stub):
|
||||||
|
job_id = seeded_job(job_id="job-index", base="pw")
|
||||||
|
resp = await client.post(
|
||||||
|
"/api/postiz/post",
|
||||||
|
headers=POSTIZ_HEADERS,
|
||||||
|
json={"job_id": job_id, "clip_index": 9, "integration_ids": ["yt-1"]},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 400
|
||||||
|
assert "range" in resp.json()["detail"].lower()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_post_upload_failure_is_502(client, seeded_job, postiz_stub):
|
||||||
|
job_id = seeded_job(job_id="job-upfail", base="pw")
|
||||||
|
postiz_stub.upload_result = {}
|
||||||
|
resp = await client.post(
|
||||||
|
"/api/postiz/post",
|
||||||
|
headers=POSTIZ_HEADERS,
|
||||||
|
json={"job_id": job_id, "clip_index": 0, "integration_ids": ["yt-1"]},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 502
|
||||||
|
assert "upload failed" in resp.json()["detail"].lower()
|
||||||
|
assert "create_post" not in postiz_stub.calls
|
||||||
|
|
||||||
|
|
||||||
|
async def test_post_postiz_error_is_translated(client, seeded_job, postiz_stub):
|
||||||
|
from clipwright.integrations import postiz
|
||||||
|
|
||||||
|
job_id = seeded_job(job_id="job-err", base="pw")
|
||||||
|
postiz_stub.errors["create_post"] = postiz.PostizError(
|
||||||
|
429, "Postiz API Error: slow down")
|
||||||
|
resp = await client.post(
|
||||||
|
"/api/postiz/post",
|
||||||
|
headers=POSTIZ_HEADERS,
|
||||||
|
json={"job_id": job_id, "clip_index": 0, "integration_ids": ["yt-1"]},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 429
|
||||||
|
assert resp.json()["detail"] == "Postiz API Error: slow down"
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# Other Postiz routes
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
async def test_integrations_route_normalises_disabled(client, postiz_stub):
|
||||||
|
postiz_stub.integrations = [
|
||||||
|
{"id": "a", "identifier": "youtube", "disabled": 1},
|
||||||
|
{"id": "b", "identifier": "youtube", "disabled": 0},
|
||||||
|
{"id": "c", "identifier": "youtube"},
|
||||||
|
]
|
||||||
|
resp = await client.get("/api/postiz/integrations", headers=POSTIZ_HEADERS)
|
||||||
|
assert resp.status_code == 200
|
||||||
|
integrations = resp.json()["integrations"]
|
||||||
|
assert [i["disabled"] for i in integrations] == [True, False, False]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_integrations_route_translates_postiz_error(client, postiz_stub):
|
||||||
|
from clipwright.integrations import postiz
|
||||||
|
|
||||||
|
postiz_stub.errors["list_integrations"] = postiz.PostizError(
|
||||||
|
401, "Postiz API Error: bad key")
|
||||||
|
resp = await client.get("/api/postiz/integrations", headers=POSTIZ_HEADERS)
|
||||||
|
assert resp.status_code == 401
|
||||||
|
assert "bad key" in resp.json()["detail"]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_scheduled_route_backfills_and_widens_window(client, postiz_stub):
|
||||||
|
resp = await client.get("/api/postiz/scheduled", headers=POSTIZ_HEADERS,
|
||||||
|
params={"days": 30})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
posts = resp.json()["scheduled_posts"]
|
||||||
|
# Postiz calls it ``date``; the consumer reads ``scheduled_date``.
|
||||||
|
assert posts[0]["scheduled_date"] == "2030-01-01T00:00:00.000Z"
|
||||||
|
assert posts[0]["date"] == "2030-01-01T00:00:00.000Z"
|
||||||
|
|
||||||
|
args = postiz_stub.calls["list_posts"][0][0]
|
||||||
|
start = datetime.fromisoformat(args[2].replace("Z", "+00:00"))
|
||||||
|
end = datetime.fromisoformat(args[3].replace("Z", "+00:00"))
|
||||||
|
# The default window is widened to at least POSTIZ_SCHEDULED_MIN_DAYS (90).
|
||||||
|
assert (end - start) >= timedelta(days=89)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_scheduled_route_forwards_explicit_dates(client, postiz_stub):
|
||||||
|
resp = await client.get(
|
||||||
|
"/api/postiz/scheduled", headers=POSTIZ_HEADERS,
|
||||||
|
params={"start_date": "2030-01-01T00:00:00.000Z",
|
||||||
|
"end_date": "2030-02-01T00:00:00.000Z"})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
args = postiz_stub.calls["list_posts"][0][0]
|
||||||
|
assert args[2] == "2030-01-01T00:00:00.000Z"
|
||||||
|
assert args[3] == "2030-02-01T00:00:00.000Z"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_scheduled_route_translates_postiz_error(client, postiz_stub):
|
||||||
|
from clipwright.integrations import postiz
|
||||||
|
|
||||||
|
postiz_stub.errors["list_posts"] = postiz.PostizError(500, "Postiz API Error: boom")
|
||||||
|
resp = await client.get("/api/postiz/scheduled", headers=POSTIZ_HEADERS)
|
||||||
|
assert resp.status_code == 500
|
||||||
|
assert "boom" in resp.json()["detail"]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_cancel_scheduled_deletes_and_reports(client, postiz_stub):
|
||||||
|
resp = await client.delete("/api/postiz/scheduled/sched-9",
|
||||||
|
headers=POSTIZ_HEADERS)
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert resp.json() == {"success": True, "id": "sched-9"}
|
||||||
|
assert postiz_stub.calls["delete_post"][0][0][2] == "sched-9"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_analytics_route_forwards_channel_and_days(client, postiz_stub):
|
||||||
|
resp = await client.get("/api/postiz/analytics", headers=POSTIZ_HEADERS,
|
||||||
|
params={"integration": "yt-1", "days": 7})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert resp.json() == postiz_stub.analytics_result
|
||||||
|
args = postiz_stub.calls["analytics"][0][0]
|
||||||
|
assert args[2] == "yt-1" and args[3] == 7
|
||||||
|
|
||||||
|
|
||||||
|
async def test_analytics_posts_route_forwards_post_id(client, postiz_stub):
|
||||||
|
resp = await client.get("/api/postiz/analytics/posts", headers=POSTIZ_HEADERS,
|
||||||
|
params={"post_id": "post-9", "days": 3})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert resp.json() == postiz_stub.analytics_post_result
|
||||||
|
args = postiz_stub.calls["analytics_post"][0][0]
|
||||||
|
assert args[2] == "post-9" and args[3] == 3
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# The identifier -> platform map that drives settings.__type
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
def test_settings_echo_the_real_identifier(app_state):
|
||||||
|
app = app_state.app
|
||||||
|
assert app._identifier_platform("instagram-standalone") == "instagram"
|
||||||
|
assert app._identifier_platform("tiktok-business") == "tiktok"
|
||||||
|
assert app._identifier_platform("youtube") == "youtube"
|
||||||
|
|
||||||
|
ig = app._postiz_settings("instagram-standalone", "T", "caption", [])
|
||||||
|
assert ig == {"__type": "instagram-standalone", "post_type": "post"}
|
||||||
|
tt = app._postiz_settings("tiktok-business", "T", "caption", [])
|
||||||
|
assert tt["__type"] == "tiktok-business"
|
||||||
|
assert tt["content_posting_method"] == "DIRECT_POST"
|
||||||