Compare commits
16 commits
alpha-0.1.
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 26b05ab56c | |||
| c7f922de32 | |||
| 980dae98e8 | |||
| 47add55c5f | |||
| 71e0ebf7ea | |||
| d6275aab4c | |||
| ab5cdb87a9 | |||
| 9823e8fe69 | |||
| 2dc1ba1eea | |||
| a00fe8544d | |||
| 91a5465f81 | |||
| 0040aa49da | |||
| 1dec0dd1af | |||
| 719946b3cd | |||
| d56455e555 | |||
| 80e59db429 |
286 changed files with 17508 additions and 13502 deletions
|
|
@ -14,11 +14,10 @@ ENV/
|
|||
.eggs/
|
||||
*.egg-info/
|
||||
.pytest_cache/
|
||||
.ruff_cache/
|
||||
|
||||
# Node
|
||||
node_modules/
|
||||
remotion/node_modules/
|
||||
render-service/node_modules/
|
||||
dashboard/node_modules/
|
||||
|
||||
# IDE
|
||||
|
|
@ -27,6 +26,17 @@ dashboard/node_modules/
|
|||
*.swp
|
||||
*.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)
|
||||
*.mp4
|
||||
*.avi
|
||||
|
|
@ -43,7 +53,6 @@ videos/
|
|||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
!.env.cloud.example
|
||||
*.pem
|
||||
*.key
|
||||
|
||||
|
|
@ -55,10 +64,3 @@ docker-compose.yml
|
|||
# Docs
|
||||
README.md
|
||||
*.md
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
|
|||
54
.env.example
54
.env.example
|
|
@ -1,8 +1,7 @@
|
|||
# AWS S3 (optional — for clip backup)
|
||||
AWS_ACCESS_KEY_ID=your_aws_access_key_here
|
||||
AWS_SECRET_ACCESS_KEY=your_aws_secret_key_here
|
||||
AWS_REGION=eu-west-3
|
||||
AWS_S3_BUCKET=your-bucket-name
|
||||
# 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=...
|
||||
|
|
@ -27,6 +26,9 @@ AWS_S3_BUCKET=your-bucket-name
|
|||
# Concurrent GPU transcriptions (parakeet or whisper-on-cuda). Keep 1.
|
||||
# ASR_GPU_CONCURRENCY=1
|
||||
|
||||
# Concurrent pipeline jobs (default 5).
|
||||
# MAX_CONCURRENT_JOBS=5
|
||||
|
||||
# Video encoder for all ffmpeg encodes: x264 (default) | nvenc | auto.
|
||||
# auto probes h264_nvenc once at startup and falls back to x264 if unusable.
|
||||
# FFMPEG_ENCODER=x264
|
||||
|
|
@ -55,13 +57,8 @@ GEMINI_IMAGE_MODEL=gemini-3.1-flash-image
|
|||
# LLM_SCORE_BATCH=3
|
||||
# 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
|
||||
|
|
@ -74,17 +71,6 @@ GEMINI_IMAGE_MODEL=gemini-3.1-flash-image
|
|||
# sidecars, dotfiles) so only media is exposed. Files are swept with the job
|
||||
# (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 (rate_limit.py). "<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)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
|
@ -106,21 +92,9 @@ GEMINI_IMAGE_MODEL=gemini-3.1-flash-image
|
|||
# number to cap uploads and reject larger files with HTTP 413.
|
||||
# MAX_FILE_SIZE_MB=0
|
||||
|
||||
# Which hop may declare the client's address in X-Forwarded-For. The Dockerfile
|
||||
# defaults to the private Docker ranges; narrow it to Traefik's own address on
|
||||
# the container network in production. NEVER "*": that lets any caller forge
|
||||
# the IP the rate limiter and the rights declaration are keyed on.
|
||||
# FORWARDED_ALLOW_IPS=10.0.1.7
|
||||
|
||||
# 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
|
||||
|
||||
# Encrypted PostgreSQL backups (ops/pg_backup.sh — installed and scheduled on
|
||||
# the database host, not by the app).
|
||||
# DATABASE_URL=postgres://user:pass@host:5432/clipwright
|
||||
# BACKUP_AGE_RECIPIENT=age1...
|
||||
# BACKUP_DEST=s3://clipwright-backups/pg
|
||||
# BACKUP_S3_ENDPOINT=https://<accountid>.r2.cloudflarestorage.com
|
||||
# RETENTION_DAYS=30
|
||||
|
||||
# X-Forwarded-For trust. The container launches uvicorn with
|
||||
# `--proxy-headers --forwarded-allow-ips *` (see the Dockerfile CMD), so any
|
||||
# caller that can reach the port may declare its own address and scheme. This
|
||||
# is not configurable via an environment variable: run the API behind a reverse
|
||||
# proxy that overwrites X-Forwarded-For, and never publish the backend port
|
||||
# directly to the internet.
|
||||
|
|
|
|||
95
.github/workflows/ci.yml
vendored
95
.github/workflows/ci.yml
vendored
|
|
@ -5,41 +5,92 @@ on:
|
|||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
env:
|
||||
PYTHONHASHSEED: "0"
|
||||
TZ: UTC
|
||||
PIP_DISABLE_PIP_VERSION_CHECK: "1"
|
||||
|
||||
jobs:
|
||||
backend-tests:
|
||||
# Fast unit suite. No ffmpeg, no ML stack.
|
||||
unit:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
# The Forgejo runner cannot provision Python 3.11 via actions/setup-python
|
||||
# ("Version 3.11 was not found in the local cache"), so every job runs in a
|
||||
# container that already has Python 3.11. It must also ship Node and git:
|
||||
# the runner executes JS actions (actions/checkout) by invoking `node`
|
||||
# inside the job container.
|
||||
container: nikolaik/python-nodejs:python3.11-nodejs20
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.11"
|
||||
# Everything the collected tests import at module level, WITHOUT the
|
||||
# heavy ML stack (torch/ultralytics/mediapipe/faster-whisper) — the
|
||||
# pipeline modules import those lazily behind their feature gates, and
|
||||
# the tests exercise the gated-off paths. numpy+opencv cover the layout
|
||||
# modules, fastapi/boto3/PyJWT/python-multipart cover importing app.py
|
||||
# for the MCP endpoint tests, google-genai covers gemini_worker.
|
||||
# scenedetect (in requirements-test.txt) pulls the full opencv-python,
|
||||
# whose cv2 binary links libGL.so.1 — absent from the base image. The
|
||||
# pipeline modules the unit tests import need it at import time.
|
||||
- name: Install opencv system libs
|
||||
run: apt-get update -qq && apt-get install -y -qq --no-install-recommends libgl1
|
||||
- name: Install test dependencies
|
||||
run: >
|
||||
pip install pytest pillow httpx pydantic sqlalchemy greenlet numpy
|
||||
opencv-python-headless python-dotenv google-genai fastapi boto3
|
||||
PyJWT email-validator python-multipart
|
||||
- name: Run tests
|
||||
run: pytest tests/ -v
|
||||
run: pip install -r requirements-test.txt
|
||||
- name: Run unit tests
|
||||
# Exclude the E2E tree from *collection*: `-m "not e2e"` only filters
|
||||
# execution, but pytest still imports every module to collect it, and
|
||||
# the pipeline E2E modules import the pipeline (tqdm/scenedetect/ML),
|
||||
# which would pull in fixtures the unit suite does not exercise.
|
||||
run: pytest tests/ --ignore=tests/e2e -m "not e2e" -q
|
||||
|
||||
frontend-build:
|
||||
# Backend E2E: API + pipeline. ffmpeg/ffprobe must be installed in-job.
|
||||
# requirements-test.txt already carries pytest-asyncio/asgi-lifespan/
|
||||
# pytest-timeout and the pure-Python scene engine. API and pipeline run as
|
||||
# separate processes so the pipeline tests' fake `clipwright.pipeline.main`
|
||||
# can never leak into the API process. No ML stack: detectors are stubbed,
|
||||
# only ffmpeg is real.
|
||||
backend-e2e:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
container: nikolaik/python-nodejs:python3.11-nodejs20
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install ffmpeg
|
||||
run: apt-get update -qq && apt-get install -y -qq --no-install-recommends ffmpeg && ffmpeg -version | head -1
|
||||
- name: Install test dependencies
|
||||
run: pip install -r requirements-test.txt
|
||||
- name: Run API E2E
|
||||
run: pytest tests/e2e/api -m e2e -q --timeout=120
|
||||
- name: Run pipeline E2E (non-ML)
|
||||
run: pytest tests/e2e/pipeline -m "e2e and not ml" -q --timeout=120
|
||||
|
||||
# Dashboard E2E (Playwright). The container already ships Node 20 + npm + git,
|
||||
# so actions/setup-node and actions/cache are deliberately NOT used (their
|
||||
# Node download / cache endpoints time out against the act runner:
|
||||
# "connect ETIMEDOUT 172.27.0.4:41759"). Playwright is retry-free by config;
|
||||
# install browsers fresh each run.
|
||||
dashboard-e2e:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
container: nikolaik/python-nodejs:python3.11-nodejs20
|
||||
# Turn on the real-backend lane: Playwright's second webServer boots a real
|
||||
# uvicorn (pipeline stub_env) and the `real` project drives it.
|
||||
env:
|
||||
CW_E2E_REAL: "1"
|
||||
defaults:
|
||||
run:
|
||||
working-directory: dashboard
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "20"
|
||||
cache: npm
|
||||
cache-dependency-path: dashboard/package-lock.json
|
||||
# ffmpeg builds the media fixture and renders the real pipeline's clips;
|
||||
# libgl1 satisfies opencv (pulled by scenedetect) at import time.
|
||||
- name: Install ffmpeg + opencv system libs
|
||||
run: apt-get update -qq && apt-get install -y -qq --no-install-recommends ffmpeg libgl1
|
||||
# Backend deps for the uvicorn server the real lane launches (uvicorn is
|
||||
# pinned in requirements-test.txt alongside fastapi/scenedetect/...).
|
||||
- name: Install backend test dependencies
|
||||
run: pip install -r ../requirements-test.txt
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
- name: Install Playwright browsers
|
||||
run: npx playwright install --with-deps chromium
|
||||
- name: Lint
|
||||
run: npm run lint
|
||||
- name: Build
|
||||
run: npm run build
|
||||
- name: Browser E2E
|
||||
run: npm run test:e2e
|
||||
|
|
|
|||
42
.github/workflows/publish-cli.yml
vendored
42
.github/workflows/publish-cli.yml
vendored
|
|
@ -1,42 +0,0 @@
|
|||
name: Publish CLI to PyPI
|
||||
|
||||
# Push a tag cli-vX.Y.Z (matching `version` in cli/pyproject.toml) to publish
|
||||
# the `clipwright` CLI. Uses PyPI Trusted Publishing (OIDC): no API token.
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "cli-v*.*.*"
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
environment: pypi
|
||||
permissions:
|
||||
id-token: write
|
||||
contents: read
|
||||
defaults:
|
||||
run:
|
||||
working-directory: cli
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
- name: Tag matches cli/pyproject.toml version
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
run: |
|
||||
v=$(python -c "import tomllib;print(tomllib.load(open('pyproject.toml','rb'))['project']['version'])")
|
||||
[ "cli-v$v" = "${GITHUB_REF_NAME}" ] || { echo "tag ${GITHUB_REF_NAME} != cli-v$v"; exit 1; }
|
||||
- name: Build
|
||||
run: |
|
||||
pip install build
|
||||
python -m build
|
||||
- name: Smoke test the wheel
|
||||
run: |
|
||||
pip install dist/*.whl
|
||||
clipwright --help
|
||||
- name: Publish
|
||||
uses: pypa/gh-action-pypi-publish@release/v1
|
||||
with:
|
||||
packages-dir: cli/dist/
|
||||
33
.gitignore
vendored
33
.gitignore
vendored
|
|
@ -12,13 +12,18 @@
|
|||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
# Temporary files / runtime dirs
|
||||
temp_*
|
||||
# Runtime dirs
|
||||
uploads/
|
||||
downloads/
|
||||
videos/
|
||||
output/
|
||||
|
||||
# Legacy channel profile source (migrated into clipwright.sqlite3 on first run)
|
||||
channels/
|
||||
|
||||
# Local SQLite runtime state
|
||||
clipwright.sqlite3
|
||||
clipwright.sqlite3-wal
|
||||
clipwright.sqlite3-shm
|
||||
|
||||
# OS / IDE
|
||||
.DS_Store
|
||||
.idea/
|
||||
|
|
@ -33,19 +38,9 @@ output/
|
|||
# Cache dirs
|
||||
.cache/
|
||||
.config/
|
||||
# Multi-agent Skills
|
||||
.agents/
|
||||
.agent/
|
||||
.claude/
|
||||
# skills/ holds third-party installs (symlinks); our own published skill is versioned
|
||||
skills/*
|
||||
!skills/clipwright/
|
||||
skills-lock.json
|
||||
.fontconfig/
|
||||
.pytest_cache/
|
||||
.ruff_cache/
|
||||
|
||||
|
||||
# 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
|
||||
# Agent / tool local state
|
||||
.opencode/
|
||||
|
|
|
|||
|
|
@ -1,3 +0,0 @@
|
|||
[
|
||||
{ "date": "2026-07-17", "scope": "app", "macrostructure": "Marquee Hero (marketing) / Workbench (app) / Long Document (content)", "theme": "lumen", "drop": "night", "enrichment": "filament-chamber apparatus + meter strip (landing only)", "brief": "Clipwright · full app + landing redesign, design.md-managed" }
|
||||
]
|
||||
600
CLAUDE.md
600
CLAUDE.md
|
|
@ -1,600 +0,0 @@
|
|||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## Project Overview
|
||||
|
||||
Clipwright is an AI-powered vertical video editor that transforms long YouTube videos or local uploads into viral-ready short clips (9:16 format) for TikTok, Instagram Reels, and YouTube Shorts. It also includes YouTube Studio (titles, thumbnails, descriptions) and publishes through a self-hosted Postiz instance. Uses Google Gemini 3.1 Flash-Lite (`gemini-3.1-flash-lite`, overridable with `GEMINI_MODEL`) for viral moment detection and title generation.
|
||||
|
||||
## Development Commands
|
||||
|
||||
### Local Development (Docker)
|
||||
```bash
|
||||
docker compose up --build # Build and run full stack
|
||||
```
|
||||
- Backend: http://localhost:8000 (FastAPI/Uvicorn)
|
||||
- Frontend: http://localhost:5175 (Vite proxies API calls to backend)
|
||||
|
||||
### Frontend Only (Dashboard)
|
||||
```bash
|
||||
cd dashboard
|
||||
npm install
|
||||
npm run dev # Dev server with HMR (port 5173)
|
||||
npm run build # Production build
|
||||
npm run lint # ESLint (strict, --max-warnings 0)
|
||||
```
|
||||
|
||||
### Backend Only
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
uvicorn app:app --host 0.0.0.0 --port 8000
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
### Core Processing Pipeline
|
||||
1. **Ingest** - YouTube download (yt-dlp) or local upload
|
||||
2. **Transcription** - faster-whisper with word-level timestamps
|
||||
3. **Scene Detection** - PySceneDetect for segment boundaries
|
||||
4. **AI Analysis** - Gemini identifies 3-15 viral moments (15-60 sec each)
|
||||
5. **FFmpeg Extraction** - Precise clip cutting
|
||||
6. **AI Cropping** - Vertical reframing with subject tracking
|
||||
7. **Effects/Subtitles** - Optional AI-generated FFmpeg filters
|
||||
8. **Hook Overlay** - Text overlays with styled fonts
|
||||
9. **Voice Dubbing** - Optional ElevenLabs AI translation (30+ languages)
|
||||
10. **S3 Backup** - Silent background upload
|
||||
11. **Social Distribution** - Self-hosted Postiz (clip uploaded, then scheduled or posted)
|
||||
|
||||
### Key Files
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `main.py` | Core video processing: transcription, scene detection, clip extraction, vertical reframing |
|
||||
| `app.py` | FastAPI server with async job queue and REST endpoints |
|
||||
| `editor.py` | Gemini AI integration for dynamic video effects (FFmpeg filter generation) |
|
||||
| `hooks.py` | Hook text overlay generation with font rendering |
|
||||
| `s3_uploader.py` | AWS S3 upload with caching |
|
||||
| `subtitles.py` | SRT generation, FFmpeg subtitle burning, and dubbed video transcription |
|
||||
| `translate.py` | ElevenLabs dubbing API for AI voice translation |
|
||||
| `dashboard/src/App.jsx` | Main React component with state management |
|
||||
| `dashboard/src/components/TranslateModal.jsx` | Voice dubbing UI with language selection |
|
||||
| `dashboard/vite-plugin-seo.js` | Build-time SEO surface: injects crawler-visible homepage content, emits static pages, sitemap.xml and llms.txt |
|
||||
| `dashboard/seo/data.js` | Single source of truth for pricing, pipeline and competitor facts used by every generated page |
|
||||
|
||||
### SEO / AI-crawler surface
|
||||
|
||||
The dashboard is a client-rendered SPA with hash routing, so the HTML served for
|
||||
`/` used to contain an empty `<div id="root">`. Googlebot renders JavaScript and
|
||||
saw the real page; GPTBot, ClaudeBot and PerplexityBot do not and measured the
|
||||
homepage as zero characters of text. `vite-plugin-seo.js` fixes that at build time:
|
||||
|
||||
- Injects the content of `seo/landing-fallback.js` into `#root`. React's
|
||||
`createRoot().render()` replaces it on mount, so users get the app and
|
||||
non-executing clients get the copy. **Keep it in sync with `Landing.jsx`.**
|
||||
- Emits the standalone pages (the `/alternatives` cluster, the clip-generator,
|
||||
open-source and use-case pages; the full list is
|
||||
`buildPages()` in `seo/pages.js`) as flat `.html` files.
|
||||
nginx resolves the clean URL through `try_files $uri $uri.html`; serving them as
|
||||
directories instead makes nginx 301 to a trailing slash and every canonical
|
||||
would then point at a redirect.
|
||||
- Generates `sitemap.xml` and `llms.txt` from the same page list, so they cannot
|
||||
drift. Do not add a static `public/sitemap.xml` back.
|
||||
|
||||
When editing pricing anywhere, edit `seo/data.js` too. Clipwright has a single
|
||||
self-hosted edition: free and open source under MIT. Do not reintroduce a hosted
|
||||
or paid tier into the copy.
|
||||
|
||||
### Free tools (/tools) and SEO attribution
|
||||
|
||||
- `free_tools.py` (router always mounted): `GET /api/tools/youtube-transcript`
|
||||
reads the captions a video **already has** on YouTube via yt-dlp (never the
|
||||
GPU, never media). Routes: the `STATIC_PROXY_URLS` only (anonymous, then the
|
||||
cookies), direct when there are none; **never** the per-GB `PROXY_URL`. A
|
||||
static that answers with zero formats and zero captions is a degraded route,
|
||||
not a "no captions" verdict (seen on one of the three statics, 23-sep-2026).
|
||||
`POST /api/tools/youtube-metadata` = one Gemini text call (tags / titles /
|
||||
description) with the managed key. Per-IP windows + global daily cap per tool,
|
||||
24 h cache (also for "no captions"/"unavailable").
|
||||
- Pages: `seo/tools.js` (hub + 3 tools). A tool page carries
|
||||
`tool: {entry, html}`:
|
||||
the form is in the static HTML, the behaviour is a Vite entry in
|
||||
`dashboard/tools/*.js` (`vite.config.js` rollupOptions.input) that
|
||||
`vite-plugin-seo.js` looks up by name in the bundle. The 9:16 converter runs
|
||||
in the browser with mediabunny/WebCodecs (no upload).
|
||||
- Attribution: `seo/render.js` writes the same first-touch `cw_attrib` key the
|
||||
app writes, from the static page the visit started on. Before, every signup
|
||||
was credited to "/" (7,481/7,481 rows, 30 days to 23-sep-2026). Signup,
|
||||
CheckoutStarted and Subscribed carry `landing_path`/`referrer_host`/utm as
|
||||
OpenPanel props (`lib/analytics.js`).
|
||||
- Apex→www: 301 comes from the front app's **stored Coolify custom labels**
|
||||
(`redirectregex.permanent=true`, patched 23-sep-2026). The nginx 301 block
|
||||
below never sees the apex while that Traefik middleware exists.
|
||||
|
||||
### Cómo se elige el layout
|
||||
|
||||
`POST /api/process` acepta `layouts`: una lista (JSON) o cadena separada por
|
||||
comas con `auto`, `split`, `screencast`, `speaker_cut`, `punch_in` y `none`.
|
||||
Cada nombre enciende su variable de entorno para **ese** trabajo
|
||||
(`app.py:layout_env`); `none` apaga el picker aunque prod corra con
|
||||
`AUTO_LAYOUT=1` (recorte simple y nada más). Sin `layouts` manda el env del
|
||||
despliegue, que desde el 25-ago-2026 es `AUTO_LAYOUT=1`. El dashboard lo expone
|
||||
en opciones avanzadas ("vertical layout": auto / split / screencast / none,
|
||||
`MediaInput.jsx`, recordado en `localStorage.cw_layout`).
|
||||
|
||||
`auto` activa `layout_picker.py`: **una** llamada a Gemini por vídeo de origen
|
||||
(no por clip) que elige entre `none` / `screencast` / `split`. Medido sobre el
|
||||
corpus de 48 contra etiquetas revisadas a mano: 94% / 92% / 96% en tres pasadas,
|
||||
con 0-1 falsos positivos sobre los 28 clips que no deben tocarse, y solo 2 clips
|
||||
que cambian de respuesta entre pasadas.
|
||||
|
||||
**Manda 12 fotogramas a 1024px, no el vídeo.** Gemini factura vídeo a ~300
|
||||
tokens por segundo: una hora de fuente son ~1,08M de tokens (no cabe en una
|
||||
ventana de 1M) y una subida de 1-2 GB para recibir una palabra. Doce fotogramas
|
||||
cuestan ~3k tokens **dure lo que dure la fuente**, que es lo que hace viable
|
||||
esto con los podcasts de una hora que entran de verdad. La resolución importa y
|
||||
el número de fotogramas no: a 640px detecta 15 de 20 (una hoja de cálculo es
|
||||
ilegible), a 1024px sube a 17, y pasar a 24 fotogramas lo empeora. A 1024px la
|
||||
diferencia con mandar el vídeo entero cae dentro de la varianza que ya tiene el
|
||||
propio modo vídeo, a 2,2 s por clip en vez de ~15 s.
|
||||
|
||||
Lo que hace que funcione, y que conviene no deshacer: se le pide una **decisión
|
||||
entre opciones cerradas**, no una medida. Los cuatro intentos anteriores (Canny,
|
||||
MSER, cobertura temporal, anchura) le pedían un número y ninguno separó una hoja
|
||||
de cálculo de un marcador de esquina. La varianza que este repo atribuía a
|
||||
Gemini era de las medidas continuas, no del modelo.
|
||||
|
||||
`layout_picker.apply()` sólo **añade**: una elección explícita del usuario nunca
|
||||
se desactiva porque el modelo diga `none`.
|
||||
|
||||
### Hook grounding for on-screen clips (`hook_grounding.py`)
|
||||
|
||||
The hook and title come from the detail pass, which only reads the
|
||||
transcript, so on a clip whose meaning is on the screen (a settings dialog,
|
||||
a spreadsheet) they summarise the video's topic instead of naming what is
|
||||
shown. After the render, if the `<clip>.layout.json` sidecar says at least
|
||||
25% of the clip is `screencast` / `wide` / `inset` (plus `general` when the
|
||||
layout picker called the video a screencast: a face-less scene there is a
|
||||
slide or a dialog, not a group shot), three frames from those
|
||||
stretches at 1024px plus the clip's own words go to Gemini
|
||||
(`GroundedHook`) and `viral_hook_text` / `video_title_for_youtube_short`
|
||||
are rewritten in place before `auto_hook_clip` burns them; the originals
|
||||
stay under `hook_grounding.before`. Gemini-only (frames): with just a local
|
||||
LLM it logs one line and keeps the transcript hook. `HOOK_GROUNDING=0`
|
||||
disables it. The detail prompt itself now carries the rule "about this
|
||||
moment, not the video", which is the cheap half of the same fix.
|
||||
|
||||
### How many clips a job returns (`clip_selection.py`)
|
||||
|
||||
The count is not a setting, it is derived, and every stage of the derivation
|
||||
used to leak. `get_viral_clips` builds ~90s scoring windows over the
|
||||
transcript, scores them in batches, shortlists the best `shortlist_target`
|
||||
(`min(10, duration//90 + 2)`, floor 3) and asks the detail pass for
|
||||
`clip_count_targets(len(shortlist))` clips — a floor that matters because
|
||||
users who got 1-3 clips came back a second day 0.4% of the time against
|
||||
16.1% for 4-9.
|
||||
|
||||
Two things broke that chain, both found on a 9:10 source on 22-sep-2026 that
|
||||
delivered 3 clips in prod:
|
||||
|
||||
- **The scoring pass selected instead of ranking.** Its prompt said "choose up
|
||||
to 3 windows from this batch", so the shortlist ceiling was
|
||||
`3 * n_batches`, not the target: 9 windows batched 8 + 1 gave 3 + 1 = 4
|
||||
against a target of 8, and `clip_count_targets` then asked for 4-8 clips
|
||||
instead of 6-12. Every source under ~30 min was starved this way — this is
|
||||
the mechanism behind "95% of jobs deliver 3 clips or fewer". It also threw
|
||||
away the ranking it was computing, since a batch of five great moments
|
||||
could still only contribute three. The prompt now scores **every** window
|
||||
and the shortlist is the global top N. Batches are near-equal
|
||||
(`score_batches`) for the same reason the cap is gone: a trailing batch of
|
||||
one window returned that window whatever its score, so the tail of the
|
||||
video entered the shortlist by arithmetic.
|
||||
- **The clip floor was only a sentence in the prompt.** Nothing in code
|
||||
checked it, so a detail pass that returned half was shipped as-is. When it
|
||||
comes back under `min_clips`, the shortlist windows that produced nothing
|
||||
get one more call for the difference. An empty answer is accepted: that is
|
||||
material that genuinely holds no more, and padding is worse than a short
|
||||
list.
|
||||
|
||||
Measured on that source, same transcript, three runs: shortlist 4 → 8 and
|
||||
4 clips → 6, at the same cost (~$0.005, 3 calls). `target_clips` on
|
||||
`/api/process` (dashboard: advanced options) still pins both ends via
|
||||
`CLIP_TARGET_MIN`/`MAX` when the user wants an exact number.
|
||||
|
||||
### Silent footage: the vision fallback (`main.get_visual_clips`)
|
||||
|
||||
The moment picker reads the transcript, so a video with nothing said in it
|
||||
would score nothing. `main.py` switches paths by itself instead, and the
|
||||
switch is the part worth knowing because it is not only "no audio track":
|
||||
`transcribe_video` raising `NoAudioError`, **and** `speech_is_sparse()`
|
||||
coming back true, both set `transcript = None` and route to
|
||||
`get_visual_clips`. Sparse means under `MIN_SPEECH_WORDS` (8) in total or
|
||||
under `MIN_SPEECH_WORDS_PER_MIN` (5). Music-only footage and a session
|
||||
recorded with the mic muted transcribe to a handful of stray words, which
|
||||
is worse than silence: without that second test the picker scores those
|
||||
words and cuts around them.
|
||||
|
||||
The vision pass uploads the video, Gemini watches it and returns the same
|
||||
`{"shorts"}` shape (`gemini_worker.VisualResponse`) in the same 15-60s
|
||||
band, so every stage after it is byte-identical: layouts, inset detection,
|
||||
hooks. `CLIP_TARGET_MIN`/`MAX` apply directly here rather than being
|
||||
derived from scoring windows, because there are none. The transcript is
|
||||
stored as `{"language": "none", "segments": []}`, so the clips come out
|
||||
with no subtitles, which is correct and not a bug.
|
||||
|
||||
**This is the one stage that sends Gemini the video instead of frames, and
|
||||
that is deliberate** — 12 frames can say what kind of video this is (which
|
||||
is all the layout picker needs), they cannot say which 40 seconds to cut.
|
||||
The cost is the ceiling: Gemini bills video at ~300 tokens/second, so an
|
||||
hour is ~1.08M tokens, past a 1M window, and **nothing guards the length**.
|
||||
A silent multi-hour source fails at the model rather than politely. If that
|
||||
needs fixing, the answer is a guard or segmenting the source, not porting
|
||||
the frame trick over from the layout picker. Gemini-only either way: a
|
||||
text-only `LLM_BASE_URL` server cannot see footage, and with no
|
||||
`GEMINI_API_KEY` the function logs one line and returns None, which fails
|
||||
the job outright.
|
||||
|
||||
The public `/gta-5-clips` page states these thresholds and this ceiling to
|
||||
users; if the behaviour changes, change `dashboard/seo/pages.js` too.
|
||||
|
||||
### Local LLM for the moment picker (`llm_backend.py`)
|
||||
|
||||
`LLM_BASE_URL` (+ `LLM_MODEL`, `LLM_API_KEY`) routes the two transcript
|
||||
passes of `get_viral_clips` to any OpenAI-compatible `/chat/completions`
|
||||
instead of Gemini; the response is validated with the same pydantic schemas
|
||||
Gemini enforces server-side, so `main.py` sees one shape. `main.score_batch_size`
|
||||
drops to 3 windows per call there (local contexts are 4-8k; a truncated
|
||||
prompt scores garbage silently). Self-host `/api/process` then accepts a
|
||||
request without `X-Gemini-Key` and `/api/config.localLlm` tells the dashboard
|
||||
not to demand one. Frame-based stages (`layout_picker`, `screencast_layout`,
|
||||
`get_visual_clips`) stay on Gemini and degrade as they always did without a
|
||||
key. On a self-hosted instance it is always available.
|
||||
|
||||
### Thumbnail Studio (`thumbnail.py`, `/api/thumbnail/*`)
|
||||
|
||||
Titles come from the transcript plus 10 frames at 1024px, never the whole
|
||||
video (same reasoning as the layout picker: an hour of video is ~1M tokens for
|
||||
a text task). Two calls: a 25-title brainstorm across fixed styles, then a
|
||||
critic that scores, dedupes by angle and returns 10, each paired with a 1-4
|
||||
word `thumbnail_text` that complements the title rather than repeating it.
|
||||
Rules baked in: payoff inside 50 characters (phones cut there), keyword in the
|
||||
first 3 words, same language as the transcript. Text model is
|
||||
`GEMINI_MODEL_THUMBNAIL` (default `gemini-3.7-flash`), deliberately not
|
||||
`GEMINI_MODEL`: flash-lite is fine for a closed-choice layout pick and visibly
|
||||
worse at creative titles. Image model is `GEMINI_IMAGE_MODEL` (default
|
||||
`gemini-3.1-flash-image`).
|
||||
|
||||
Thumbnails are `count` **different concepts**, not one prompt repeated: a text
|
||||
call designs each (hook text, side for the text, palette, scene prompt), then
|
||||
one image call per concept in parallel. By default (`burn_text=true`) the
|
||||
image model is told to leave that side as negative space and PIL sets the text
|
||||
in Anton with a black stroke, so accents and spelling are never wrong; the
|
||||
`AI painted` toggle lets the model render the text itself. Every output is
|
||||
cover-cropped to 1280x720 and saved under YouTube's 2 MB limit.
|
||||
`GET /api/thumbnail/frames/{session}` scores sampled frames by face area and
|
||||
sharpness (MediaPipe + Laplacian), keeps them spread across the runtime, and
|
||||
the dashboard offers them as the person reference so the thumbnail shows the
|
||||
creator instead of a stranger; an uploaded face photo still wins.
|
||||
|
||||
### Video Reframing Modes
|
||||
|
||||
**A source already shot vertical is passed through untouched.**
|
||||
`reframe_v2.source_already_fits()` gates it: every layout below reorganises the
|
||||
frame to buy back width the crop threw away, and on a 9:16 upload there is none
|
||||
to buy. GENERAL was the visible failure — its 0.42 height ratio, which buys
|
||||
presence on a landscape source by overflowing the sides, scaled a 1080x1920
|
||||
source down to a 453px sliver floating over a blurred copy of itself, and the
|
||||
scene classifier routes every face-less shot (a slide, a screen recording) there.
|
||||
So the picker is skipped (one Gemini call saved per upload), the classifier is
|
||||
skipped, and every scene renders TRACK, whose crop is the whole frame.
|
||||
`general_filtergraph` additionally floors the foreground at the height where the
|
||||
source fills the output width, so the editor's explicit GENERAL override on a
|
||||
portrait clip cannot reproduce the shrink either.
|
||||
|
||||
- **TRACK Mode** (single subject): MediaPipe face detection + YOLOv8 fallback with "Heavy Tripod" stabilization
|
||||
- **GENERAL Mode** (groups/landscapes): Blurred background layout preserving full width
|
||||
- **SPLIT Mode** (two-shot conversation, `split_layout.py`): both speakers stacked
|
||||
in half-frames. Off by default (`SPLIT_LAYOUT=1`); v2 engine only, so a
|
||||
fallback to the v1 loop silently renders GENERAL instead. It upgrades scenes
|
||||
the classifier already sent to GENERAL, never TRACK ones, and needs both faces
|
||||
visible **in the same frame** for at least half the sampled frames — that is
|
||||
what separates a real two-shot from a plano/contraplano, where stacking would
|
||||
show the same person twice. `SPLIT_TIGHTNESS` (default 0.8) trades a little
|
||||
upscale for keeping the other speaker out of each half. Captions on a SPLIT
|
||||
stretch sit on the seam between the halves (`{\an5}` per word event in
|
||||
`subtitles.generate_ass`), the one place they cover nobody; the render
|
||||
records which stretches are stacked in a `<clip>.layout.json` sidecar
|
||||
(`layout_ranges.py`) and every metadata writer copies it into the clip's
|
||||
`layout_ranges`, so `/api/subtitle` finds it after a restyle too. The fast
|
||||
rerender (cut without reframe) carries the canonical clip's ranges through
|
||||
the new cut (`layout_ranges.remap`, in `recut.perform_recut`). Only the
|
||||
ASS path can do this; SRT burns keep one alignment for the whole file.
|
||||
- **SCREENCAST / WIDE Modes** (`screencast_layout.py`, `SCREENCAST_LAYOUT=1`):
|
||||
for scenes whose meaning lives outside the centre. Gemini reports each range's
|
||||
**width_fraction**, and that is the gate — coverage was tried before and did
|
||||
not separate a spreadsheet from a corner ticker, while width does (a bug spans
|
||||
~15% and survives any crop, a spreadsheet spans ~100% and cannot). Content
|
||||
narrower than 0.5 moves nothing. Between 0.5 and 0.85 there is room beside the
|
||||
content, so SCREENCAST stacks it over the presenter. Above 0.85 the presenter
|
||||
is composited **on top of** the content and stacking would show it twice, so
|
||||
those scenes get WIDE: the GENERAL layout with side-cropping disabled.
|
||||
- **INSET Mode** (`camera_inset.py`): pantalla a ancho completo arriba, el
|
||||
recuadro de la webcam ampliado abajo. Para el caso de una sola fuente con la
|
||||
cámara compuesta en una esquina (OBS, VOD de stream). Se encadena detrás de
|
||||
la decisión `screencast`, **no** se le pregunta a Gemini: ofrecido como cuarta
|
||||
opción respondió `screencast` en los 5 clips que tienen recuadro, en dos
|
||||
pasadas, y la exactitud global cayó de 92% a 83-85%. El detector geométrico
|
||||
encuentra esos 5 sin falsos positivos. Los tres filtros que hacen falta, cada
|
||||
uno pagado con una iteración: sujeto **pequeño**, **descentrado en
|
||||
horizontal** (una cara de talking head está centrada aunque esté alta), y
|
||||
**quieto entre muestras** (3-11px frente a 316px de una persona real).
|
||||
- **ALTERNATE Mode** (`active_speaker.py`, `SPEAKER_SIGNAL=1` + `SPEAKER_CUT=1`):
|
||||
hard cuts to whoever is talking, rendered through the TRACK path as a
|
||||
trajectory with jumps. `SPEAKER_SIGNAL=1` alone just gates SPLIT on both people
|
||||
actually speaking. Mouth activity **must** be normalised per speaker before
|
||||
comparing (`normalise_activity`): raw frame-difference magnitude scales with
|
||||
local contrast and lighting, and on a real two-shot it handed one speaker
|
||||
90-100% of the scene.
|
||||
- **Punch-in** (`punch_in.py`, `PUNCH_IN=1`): not a layout. A ~12% push on the
|
||||
clip's beats, riding the TRACK path by widening its per-frame crop command
|
||||
from x-only to w/h/x/y. Beats currently come from the audio envelope;
|
||||
`emphasis_times` is a plain list of seconds so the transcript's hook words can
|
||||
replace it without touching the module.
|
||||
|
||||
### Key Classes
|
||||
- `SmoothedCameraman` - Stabilized camera movement with safe zone logic (prevents jitter)
|
||||
- `SpeakerTracker` - Prevents rapid speaker switching, handles temporary occlusions
|
||||
|
||||
### API Endpoints
|
||||
| Method | Route | Purpose |
|
||||
|--------|-------|---------|
|
||||
| POST | `/api/process` | Submit video for processing |
|
||||
| GET | `/api/status/{job_id}` | Poll job status and logs |
|
||||
| POST | `/api/edit` | Apply AI video effects |
|
||||
| POST | `/api/subtitle` | Generate and apply subtitles (auto-transcribes dubbed videos) |
|
||||
| POST | `/api/hook` | Add text hook overlays |
|
||||
| POST | `/api/translate` | AI voice dubbing via ElevenLabs |
|
||||
| GET | `/api/translate/languages` | List supported dubbing languages |
|
||||
| POST | `/api/postiz/post` | Upload a clip to Postiz, then schedule or post it now |
|
||||
| GET | `/api/postiz/integrations` | List the channels connected in Postiz |
|
||||
| GET | `/api/postiz/scheduled` | List scheduled posts in a date window |
|
||||
| DELETE | `/api/postiz/scheduled/{id}` | Delete a scheduled post |
|
||||
| GET | `/api/postiz/analytics` | Channel analytics (`integration` id required) |
|
||||
| GET | `/api/postiz/analytics/posts` | Analytics for one published post (`post_id` required) |
|
||||
|
||||
### Publishing through Postiz
|
||||
|
||||
`postiz.py` is a thin client for a self-hosted [Postiz](https://postiz.com/)
|
||||
instance. The dashboard sends the user's `X-Postiz-Key` / `X-Postiz-Url`
|
||||
headers; the backend falls back to the `POSTIZ_API_KEY` / `POSTIZ_URL` env
|
||||
vars. Because the clip file lives on the app server, the backend reads it and
|
||||
uploads the bytes to Postiz (`POST /upload`, multipart), then references the
|
||||
returned `{id, path}` in `POST /posts`. Provider settings (`tiktok`,
|
||||
`instagram`, `youtube`) are built server-side from the clip title and caption.
|
||||
Auth is the raw key, no `Bearer`.
|
||||
|
||||
### Webhooks
|
||||
|
||||
`POST /api/process` takes `webhook_url` + optional
|
||||
`webhook_secret` (HMAC-SHA256, `X-Clipwright-Signature`). Validated with
|
||||
`security_utils.assert_public_url` at submit AND at delivery (DNS rebinding).
|
||||
Fired once per job from `run_job_wrapper`; survives redeploys via the resume
|
||||
manifest. Each clip carries `video_url` (the local `/videos/...` path).
|
||||
`PUBLIC_API_URL` env sets the absolute-URL base when behind a proxy.
|
||||
|
||||
### Concurrency Model
|
||||
Async job queue with semaphore-based concurrency control. Configure via `MAX_CONCURRENT_JOBS` env var (default: 5). Jobs auto-cleanup after 1 hour.
|
||||
|
||||
The real limit on the GPU box is VRAM, not CPU: each `main.py` job holds
|
||||
Parakeet (onnxruntime CUDA), TransNetV2 (torch, ~2 GB at peak) and an
|
||||
NVENC session, and when the card is full a cut fails as "Generic error in
|
||||
an external library" / exit 187 with 0 bytes, TransNetV2 as CUDA OOM, and
|
||||
the reframe writer as a broken pipe. The retry in `ffmpeg_utils.cut_clip`
|
||||
waits for a **busy** GPU; it cannot help with a **full** one. The API
|
||||
process itself was the biggest tenant (7.7 GB idle on 17-sep-2026): the
|
||||
thumbnail studio and `/api/subtitle` on a dubbed clip transcribe
|
||||
in-process and the ASR singletons then lived in uvicorn for good, so both
|
||||
now call `transcribe_backends.release_models()` when they are done. Size
|
||||
`MAX_CONCURRENT_JOBS` against the free VRAM first, then check the CPU.
|
||||
|
||||
The CPU is the other ceiling (a 20-thread host sat at load ~100 at peak on
|
||||
22 and 25-sep-2026). Two costs were pure waste and are gone, with the
|
||||
delivered clips byte-identical (decoded-frame MD5s + audio, 15 clips of 3
|
||||
real videos, bench of 25-sep-2026):
|
||||
- **onnxruntime threads spinning** during Parakeet: ~160 CPU-s per 9 min of
|
||||
audio while the GPU did the work. `parakeet_session_options()` turns
|
||||
spinning off for the ASR session only; the VAD must keep `load_vad`'s
|
||||
defaults (see the docstring for why).
|
||||
- **A seek per sampled frame** in `analyze_scenes_strategy` and
|
||||
`split_layout`: each seek re-decoded the GOP. `frame_sampler.read_at`
|
||||
reads forward once and returns the same frames.
|
||||
Net: a job's CPU roughly halves (Python side -65-80%).
|
||||
|
||||
Then speed at equal quality (25-sep-2026; SSIM 0.990-0.9998 vs before,
|
||||
checked by eye, audio identical):
|
||||
- **Cut on the card** (`ffmpeg_utils.cut_clip`, NVDEC -> NVENC with
|
||||
`-hwaccel_output_format cuda`) for 8-bit 4:2:0 sources; byte-identical to
|
||||
the CPU cut. Other sources and a failed GPU cut decode on the CPU.
|
||||
- **Silero VAD on one CPU thread** (`vad_load_kwargs`): on CUDA it ran one
|
||||
32 ms chunk per launch and was most of the transcription's wall time.
|
||||
- **Blur at quarter size** (`ffmpeg_utils.blurred_backdrop`).
|
||||
- **hooked_ + subtitled_ from one ffmpeg** (`hooks.add_hook_to_video(also=)`):
|
||||
the editor still needs both files (re-caption walks back to hooked_,
|
||||
hook replace to the canonical), so nothing is skipped, only one decode.
|
||||
- **CLIP_WORKERS=6** by default.
|
||||
Tried and dropped: NVDEC for the analysis decodes and `scale_cuda` (slower in
|
||||
wall, and scale_cuda does not match swscale); yt-dlp chunking/concurrent
|
||||
fragments (YouTube serves DASH over https, no gain beyond network noise).
|
||||
Measured with a side-by-side bench: Gemini decisions recorded once and
|
||||
replayed, old and new code run at the same time, clips compared by
|
||||
decoded-frame MD5 / SSIM.
|
||||
|
||||
Three guards keep the card from filling (22-sep-2026: 30-60% of jobs failing
|
||||
per hour at peak with `MAX_CONCURRENT_JOBS=8`):
|
||||
- **Job processes release the ASR model after transcribing**
|
||||
(`main.transcribe_video` → `release_models()`). Before, a job kept Parakeet's
|
||||
onnxruntime CUDA arena (~4-6 GB) for its whole render; TransNetV2 also
|
||||
`empty_cache()`s after each pass.
|
||||
- **Parakeet runs lean** (`transcribe_backends.parakeet_providers`,
|
||||
`PARAKEET_VAD_BATCH`=4): 4 VAD segments per encoder batch instead of 8, CUDA
|
||||
arena `kSameAsRequested`, no max cuDNN workspace. Peak per transcription
|
||||
6.1 → 4.6 GB with the same words (benchmark 22-sep-2026: 10 real videos,
|
||||
4,850 words, 1 word changed outside a clip that goes to whisper anyway).
|
||||
Batch 2 dropped a sentence and int8 was 11x slower with 11.7% of words
|
||||
different: both rejected.
|
||||
- **Host-wide transcription slots** (`transcribe_backends.host_asr_slot`,
|
||||
`ASR_HOST_SLOTS`, default 2): flock files `output/.asr-gpu-N.lock`, shared by
|
||||
every job process and by both containers of a deploy.
|
||||
- **Queue admission** (`app._wait_for_shared_gpu`): a job starts only when
|
||||
running-here + running-on-the-draining-instance < `MAX_CONCURRENT_JOBS` and
|
||||
`nvidia-smi` reports at least `GPU_MIN_FREE_MB` (4500) free; an idle card
|
||||
always starts, and the wait is bounded by the drain timeout.
|
||||
|
||||
Failures the user should never see (`app.run_job_wrapper`):
|
||||
- **Auto-retry**: a failed job whose error text is transient (CUDA/OOM,
|
||||
NVENC "Generic error in an external library", cublas, Gemini 5xx, "No clips
|
||||
could be rendered") is re-queued once after `AUTO_RETRY_DELAY_SECONDS` (30),
|
||||
keeping its reservation and transcript checkpoint (`AUTO_RETRY_LIMIT`=1).
|
||||
Content failures (no audio, private video, no clips found, policy block)
|
||||
are final as before. Inside a job, `main.py` retries each failed clip once,
|
||||
alone, after a pause, and renders clips best-score first.
|
||||
- **Shutdown is not failure**: when the drain timeout cancels a running job,
|
||||
the child is killed and the manifest + reservation are kept, so the next
|
||||
instance resumes it. A manifest next to a metadata file means "stopped
|
||||
mid-render" and is resumed, not recovered as completed.
|
||||
- `/api/status` returns `queue: {position, ahead, eta_seconds}` while queued,
|
||||
which the dashboard shows as a queue position and ETA.
|
||||
|
||||
### Download proxy routing and accounting (`yt_clients.py`, `metering.py`)
|
||||
|
||||
Downloads go direct → static ISP proxies (flat rate) → DataImpulse (per GB),
|
||||
and the duration probe (`metering.probe_url_minutes`) follows the same
|
||||
order, with one extra free step before any per-GB attempt: the fallback
|
||||
clients through a static (`fallback-static`). **The client list is explicit
|
||||
and shared** (`yt_clients.py`: `default,mweb` + the bgutil PO token
|
||||
provider): with account cookies yt-dlp's own defaults are `tv_downgraded` +
|
||||
`web`, and on a share of videos both come back UNPLAYABLE / SABR-only, which
|
||||
yt-dlp reports as "Video unavailable". That was mistaken for an IP ban for a
|
||||
week (it happened on every static IP too) and fed ~26 downloads a week to
|
||||
the per-GB proxy, which then fetched 360p through the same dead list.
|
||||
Measured in the prod container on 6-sep-2026, same static, same video:
|
||||
cookies + defaults → unavailable; cookies + `default,mweb` → 1080p; no
|
||||
cookies → 1080p. `mweb` needs the PO token, and the token needs the
|
||||
webpage: never put `player_skip: webpage` back. A fallback attempt runs
|
||||
anonymously when an HD attempt already failed with the cookies on that
|
||||
route, and every attempt asks for the 1080p format spec (the old
|
||||
`best[ext=mp4]` fallback spec was itself the 360p progressive file).
|
||||
Two rules keep the per-GB proxy at zero on a normal day: the probe
|
||||
reaches it **only** when a static route failed for a reason another IP can
|
||||
fix (`static_failure_warrants_paid`: bot-check, 403/429, proxy/network
|
||||
errors), never for a private/removed/members-only video, an uploader's
|
||||
country block (the residential pool failed identically in 5 of 6 paid
|
||||
probes, 3-5 sep) or a live stream
|
||||
with no duration (those failed the same on every IP and used to cost ~1.7 MB
|
||||
× 2 extractors each), and **never for a non-YouTube URL** (the download
|
||||
plan already excluded those; Twitch, Kick, Rumble and product pages were
|
||||
reaching it through the probe). The probe also carries `YOUTUBE_COOKIES`,
|
||||
like the download does: an anonymous probe from the static IPs gets "Sign in
|
||||
to confirm you're not a bot" in bursts (4-sep-2026: ~10 probes in one hour,
|
||||
1.8 MB each on the per-GB proxy) because a datacenter IP's anonymous rate
|
||||
limit is low and we make ~400 YouTube hits a day from three of them, while
|
||||
the authenticated download sails through the same IPs. But the **first**
|
||||
attempt on a route carries them and the second drops them, on the probe as
|
||||
on the download: with the cookies attached YouTube answers UNPLAYABLE for
|
||||
every client (`web_embedded`, `tv_downgraded`, `web` **and** `mweb`) on a
|
||||
share of videos, which yt-dlp reports as "Video unavailable" (9-sep-2026,
|
||||
same video on all three statics; anonymous on the same IP → 1080p 137+140).
|
||||
Without that anonymous second attempt the probe read a cookie problem as an
|
||||
IP problem and escalated to the per-GB proxy, which carries the same cookies
|
||||
and fails identically, while the download recovered for free on the same
|
||||
static. `main.py` prints `PROXY_ROUTE=<json>` after
|
||||
every download (winner, paid bytes across all attempts including failed
|
||||
paid ones, each free attempt's error); `app.py` logs `PROXY_ROUTE` at job end
|
||||
and warns when the paid proxy carried bytes. Both the probe and the download pass `noplaylist`: a
|
||||
`watch?v=X&list=...` or mix link is the one video the user was watching,
|
||||
and without it yt-dlp walks the whole list, dies on its first private /
|
||||
age-gated / bot-checked entry (a video nobody pasted), the probe reads
|
||||
that as an IP problem and pays the proxy to walk the same list again, and
|
||||
the user gets a 400 for a valid link (26 of the 37 paid probes between
|
||||
7 and 17-sep-2026). And the probe keeps **every** attempt's error per
|
||||
static route, not the last one: the anonymous retry ends in a bot-check
|
||||
by design, and a "confirm your age" from the cookie attempt is the
|
||||
verdict, so it must not be overwritten into an escalation. A URL that is
|
||||
not one video is refused by path before any request
|
||||
(`yt_clients.youtube_non_video_reason`): `noplaylist` does nothing for
|
||||
those and yt-dlp walks them entry by entry (one search URL held the
|
||||
probe thread for 37 min in the prod container). That check is an
|
||||
**allowlist** of the paths that carry a video id, not a list of the bad
|
||||
ones: while it named the pages it knew, a hashtag page and the legacy
|
||||
`/<vanity>` channel URL went straight through, and one of them walked to
|
||||
page 23 on the static pool and then paid the per-GB proxy to walk it
|
||||
again (20-sep-2026).
|
||||
Since 30-sep-2026 YouTube answers the bot-check to anonymous requests
|
||||
from every one of our non-residential IPs (the 3 statics and the server's
|
||||
own IP alike), **per video**: the same video fails on all of them and a few
|
||||
popular ones pass on all of them, whatever the client (web, mweb, ios,
|
||||
android_vr, tv, web_embedded, with or without a player PO token). Only an
|
||||
authenticated session or a residential IP gets through. So when the probe
|
||||
saw every static bot-checked and the paid proxy answer, the job carries
|
||||
`DOWNLOAD_SKIP_STATICS=1` (`metering.pop_statics_bot_checked`, also in the
|
||||
resume manifest) and `plan_download_attempts` goes straight to the paid
|
||||
attempts instead of repeating four anonymous hits for the same verdict.
|
||||
The proxy watcher also checks the ytcfg `LOGGED_IN` marker when
|
||||
`YOUTUBE_COOKIES` is set and pages on the first probe that says the session
|
||||
is gone. `PAID_PROXY_DAILY_MB` (default
|
||||
500) is the hard ceiling: past it the paid proxy is dropped from the probe
|
||||
and from every new job's env until UTC midnight. The watcher probes the
|
||||
static pool against a real YouTube watch page (playable markers), not
|
||||
google.com — the 28th happened because YouTube refused the static IPs while
|
||||
google kept answering 204. On the dev Mac, do not keep
|
||||
`PROXY_URL` in `.env`: every local `main.py` run then bills DataImpulse.
|
||||
|
||||
### Deploys and running jobs (handover + drain)
|
||||
|
||||
Every push to `main` redeploys the API container. Coolify starts the NEW
|
||||
container before stopping the old one (rolling update) and both share
|
||||
`output/`, so `app.py` coordinates them instead of relying on a fast swap:
|
||||
|
||||
- Each instance writes its id to `output/.instance` at startup. An instance
|
||||
that sees another id there is the old one and **drains**: it finishes the
|
||||
jobs it is running, starts none, and leaves queued manifests on disk.
|
||||
- A running job heartbeats its `.resume.json` every 10 s. The resume scan
|
||||
(startup + every 30 s) re-enqueues only manifests nobody heartbeated for
|
||||
60 s, so no job runs twice and none is lost. Max 2 resume attempts.
|
||||
- SIGTERM (`docker stop`) drains too, up to `DRAIN_TIMEOUT_SECONDS` (840),
|
||||
then hands the signal to uvicorn. The app's Coolify stop grace period is
|
||||
900 s (`application_settings.stop_grace_period`); keep the timeout below it.
|
||||
After the drain hands the signal to uvicorn, `--timeout-graceful-shutdown 15`
|
||||
(Dockerfile) caps the wait for in-flight connections: uvicorn's default is
|
||||
unbounded, and one open range download kept a drained container alive for
|
||||
the full grace period while Traefik still routed half the traffic to its
|
||||
closed port.
|
||||
- `/health/ready` + the Dockerfile `HEALTHCHECK` are what keep Traefik off a
|
||||
dying container: its docker provider only routes to `healthy` containers,
|
||||
so an instance answers 503 from the moment it gets SIGTERM (out of rotation
|
||||
within ~10 s, socket still open) and a booting one gets no traffic until it
|
||||
answers. Only SIGTERM flips it, not the marker drain: at that point the new
|
||||
container is still booting and nobody else would be routable. The Coolify
|
||||
app has its health check enabled on that path so it waits for the new
|
||||
container to be `healthy` before stopping the old one. With that option on,
|
||||
Coolify replaces the Dockerfile HEALTHCHECK with its own curl/wget command
|
||||
AND its own interval/retries (5 s × 3), so the image must ship `curl` or
|
||||
every deploy rolls back as unhealthy, and a stopping container takes 15 s
|
||||
to turn `unhealthy`. That is why the drain keeps serving for
|
||||
`PROXY_DRAIN_SECONDS` (20) after the jobs are done before it hands the
|
||||
signal to uvicorn: closing the socket earlier is 502s until Traefik
|
||||
notices (measured ~60 s per deploy with retries=12 and no grace). And
|
||||
`HARD_EXIT_SECONDS` (30) after that the process is ended outright: uvicorn
|
||||
finishing does not end the interpreter while an executor thread hangs in
|
||||
a network probe, and that kept a drained container alive for the full 900 s.
|
||||
`/health` stays a plain liveness probe for the external watcher.
|
||||
- `/api/status` answers from disk for a job this instance never held, so a
|
||||
poll landing on either container during the handover is fine.
|
||||
- `main.py` leaves `.transcript_checkpoint.json` in the job dir so a job that
|
||||
does get re-run skips the paid transcription (download and Gemini repeat).
|
||||
|
||||
Before pushing, still batch small commits (tests, docs) with the next real
|
||||
change: every deploy is a ~5 min build plus a handover.
|
||||
|
||||
## CI: a green pipeline closes the task, not the push
|
||||
- After every `git push`, wait for the commit's workflow and confirm it is green: `ci-wait` (Victor's Mac) or `gh run watch $(gh run list -c $(git rev-parse HEAD) -L1 --json databaseId -q ".[0].databaseId") --exit-status`.
|
||||
- If it is red: fix, push, check again. Never report the task as done with a red CI.
|
||||
- Before pushing, run locally what the CI runs (lint + tests of this repo).
|
||||
19
Dockerfile
19
Dockerfile
|
|
@ -31,6 +31,11 @@ FROM python:3.11-slim
|
|||
|
||||
WORKDIR /app
|
||||
|
||||
# The FastAPI app lives in the `clipwright` package and job workers are launched
|
||||
# as `python -m clipwright.pipeline.main`, so the repo root must be importable
|
||||
# regardless of the process cwd.
|
||||
ENV PYTHONPATH=/app
|
||||
|
||||
# Install FFmpeg, OpenCV deps, Node.js + npm + git (for yt-dlp JS + bgutil build).
|
||||
# fontconfig + fonts-liberation back the subtitle font choices: without real
|
||||
# fonts libass falls back to DejaVu for every UI option (issue #57).
|
||||
|
|
@ -66,6 +71,18 @@ COPY --from=builder /opt/venv /opt/venv
|
|||
ENV PATH="/opt/venv/bin:$PATH"
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
|
||||
# Runtime caches must not land inside the bind-mounted source tree. Compose
|
||||
# mounts the host repo at /app, and the container's non-root appuser cannot
|
||||
# write there, so matplotlib/fontconfig logged permission errors and dropped a
|
||||
# stray .fontconfig (owned by the container's uid) into the repo. Point HOME
|
||||
# and the disposable caches at writable /tmp; keep the ASR model cache on the
|
||||
# named volume mounted at HF_HOME (see docker-compose.yml) so it survives
|
||||
# container recreates.
|
||||
ENV HOME=/tmp \
|
||||
MPLCONFIGDIR=/tmp/.cache/matplotlib \
|
||||
YOLO_CONFIG_DIR=/tmp/Ultralytics \
|
||||
HF_HOME=/app/.cache/huggingface
|
||||
|
||||
# GPU runtime wiring — harmless no-ops on CPU builds / hosts without the
|
||||
# NVIDIA runtime. LD_LIBRARY_PATH points at the pip-installed CUDA libs
|
||||
# (paths simply don't exist in CPU images); DRIVER_CAPABILITIES asks the
|
||||
|
|
@ -126,4 +143,4 @@ EXPOSE 8000
|
|||
HEALTHCHECK --interval=5s --timeout=3s --start-period=30s --retries=2 \
|
||||
CMD curl -sf http://127.0.0.1:8000/health/ready > /dev/null || exit 1
|
||||
|
||||
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers", "--forwarded-allow-ips", "*", "--timeout-graceful-shutdown", "15"]
|
||||
CMD ["uvicorn", "clipwright.api.app:app", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers", "--forwarded-allow-ips", "*", "--timeout-graceful-shutdown", "15"]
|
||||
|
|
|
|||
323
README.md
323
README.md
|
|
@ -1,139 +1,68 @@
|
|||
# Clipwright
|
||||
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
[](https://opensource.org/)
|
||||
[](http://makeapullrequest.com)
|
||||
[](https://docs.docker.com/compose/)
|
||||
**Self-hosted AI video platform** with 2 tools in one: **Clip Generator** and **YouTube Studio**, publishing through a self-hosted **Postiz** instance.
|
||||
Self-hosted, MIT-licensed video toolkit in one Docker stack:
|
||||
|
||||

|
||||
- **Clip Generator** — turn long videos (podcasts, webinars, streams, interviews) into viral-ready 9:16 shorts with AI moment detection, auto subtitles and smart vertical reframing.
|
||||
- **YouTube Studio** — AI titles, thumbnails and descriptions for YouTube.
|
||||
- **Postiz publishing** — post or schedule the results to TikTok, Instagram Reels and YouTube Shorts through your own self-hosted [Postiz](https://postiz.com/) instance.
|
||||
|
||||
Two people on camera? Clipwright stacks them instead of shrinking the wide shot, puts the captions on the seam where they cover nobody, and switches back to a face-tracked crop when the cut goes to one person. The AI picks the layout per video; nothing to configure.
|
||||

|
||||
|
||||
This is a clean, self-hosted fork of [OpenShorts](https://github.com/mutonby/openshorts), renamed Clipwright. You run it on your own machine with Docker and bring your own Gemini and ElevenLabs keys. There is no hosted service, no billing, and no usage cap. Publishing to TikTok, Instagram Reels and YouTube Shorts goes through your own [Postiz](https://postiz.com/) instance.
|
||||
You run it on your own machine, bring your own API keys, and keep your source video on your infrastructure. No hosted service, no billing, no usage cap.
|
||||
|
||||
> **Fork:** Clipwright is a fork of OpenShorts (<https://github.com/mutonby/openshorts>), MIT-licensed. Upstream copyright is preserved in [LICENSE](LICENSE) and [NOTICE](NOTICE).
|
||||
## Fork
|
||||
|
||||
---
|
||||
|
||||
## 2 Tools in 1 Platform
|
||||
|
||||
### 1. Clip Generator
|
||||
Turn your long-form videos — podcasts, webinars, livestreams, vlogs, interviews — into viral-ready 9:16 shorts for TikTok, Instagram Reels, and YouTube Shorts.
|
||||
|
||||

|
||||
|
||||
### 2. YouTube Studio
|
||||
Free AI YouTube toolkit: thumbnails, titles and descriptions.
|
||||
|
||||

|
||||
|
||||
- AI thumbnail generator with face overlay
|
||||
- 10 viral title suggestions with refinement chat
|
||||
- Auto-generated descriptions with chapter timestamps
|
||||
|
||||
---
|
||||
|
||||
## Key Features
|
||||
|
||||
### Clip Generator
|
||||
- **Viral Moment Detection**: Google Gemini 3.1 Flash-Lite analyzes transcripts and scene boundaries to detect 3-15 high-potential moments
|
||||
- **Runs fully local if you want**: point `LLM_BASE_URL` at Ollama, LM Studio, vLLM or any OpenAI-compatible server and the moment picker runs on your own model, no Google key needed (see [Run without a Google key](#6-run-without-a-google-key-local-llm-optional))
|
||||
- **Smart 9:16 Cropping**: AI reframing per scene — TRACK mode (MediaPipe + YOLOv8 face tracking), GENERAL mode (blurred background), SPLIT mode (two speakers stacked, captions on the seam) and SCREENCAST mode (screen over presenter); the layout is picked per video by Gemini or forced from the dashboard
|
||||
- **Auto Subtitles**: faster-whisper with word-level timestamps, styled and burned into clips
|
||||
- **AI Voice Dubbing**: ElevenLabs integration for 30+ languages
|
||||
- **Hook Text Overlays**: AI-generated attention-grabbing text overlays
|
||||
- **AI Video Effects**: Gemini-generated FFmpeg filters for professional effects
|
||||
|
||||
### YouTube Studio
|
||||
- AI-powered title generation with 10 viral options
|
||||
- Interactive refinement chat for titles
|
||||
- AI thumbnail generation with custom face + background
|
||||
- Auto descriptions with chapter timestamps from the Whisper transcript
|
||||
|
||||
### Postiz Publishing
|
||||
- **One-click posting** to TikTok, Instagram Reels, and YouTube Shorts through your self-hosted Postiz instance
|
||||
- **Schedule uploads** for any date and time — plan your content calendar and let Postiz publish
|
||||
- **You own the credentials**: Postiz runs on your infrastructure and holds the platform tokens, so Clipwright never has them
|
||||
|
||||
### Infrastructure
|
||||
- S3 cloud backup (optional; private bucket for clips)
|
||||
- Async job queue with configurable concurrency
|
||||
|
||||
---
|
||||
|
||||
## Who Is This For?
|
||||
|
||||
- **Content creators** — Turn long videos into shorts automatically, publish to all platforms at once
|
||||
- **Podcasters & educators** — Extract the most engaging moments from episodes and lessons
|
||||
- **Developers** — Self-host, customize the pipeline, integrate via API
|
||||
- **Privacy-conscious teams** — The source video stays on your infrastructure
|
||||
|
||||
---
|
||||
|
||||
## How Much Does It Cost?
|
||||
|
||||
Self-hosting Clipwright is free. You provide the machine and you only pay for the AI APIs you use, and most have generous free tiers:
|
||||
|
||||
| Service | Free Tier | Paid Cost | Used For |
|
||||
|---------|-----------|-----------|----------|
|
||||
| **Google Gemini** | Free trial with generous limits | < $0.01 per 10-min video | Viral moment detection, titles, thumbnails, descriptions |
|
||||
| **Local LLM (Ollama, LM Studio, vLLM...)** | **Free, your hardware** | $0 | Viral moment detection instead of Gemini (`LLM_BASE_URL`) |
|
||||
| **ElevenLabs** | Free tier available | Pay-per-use | Voice dubbing |
|
||||
| **Postiz** | **Open source, self-hosted** | $0 (your hardware) | Publishing to TikTok, Instagram, YouTube |
|
||||
| **AWS S3** | Optional | ~$0.023/GB | Backup for clips |
|
||||
|
||||
**Bottom line:** you can clip and publish videos for practically free with a Gemini free-tier key and a self-hosted Postiz.
|
||||
|
||||
---
|
||||
Clipwright is a fork of [OpenShorts](https://github.com/mutonby/openshorts), renamed and trimmed to a self-hosted tool: the cloud/billing mode, AI Shorts/UGC, MCP/agent layer and Upload-Post publishing were removed, YouTube Studio was fixed, and publishing now goes through Postiz. Upstream copyright is preserved in [LICENSE](LICENSE) and [NOTICE](NOTICE).
|
||||
|
||||
## Requirements
|
||||
|
||||
- **Docker & Docker Compose**
|
||||
- **Google Gemini API Key** ([Free — get it here](https://aistudio.google.com/app/apikey)) — required for all AI features unless `LLM_BASE_URL` is set
|
||||
- **ElevenLabs API Key** ([Free tier](https://elevenlabs.io)) — optional, for voice dubbing
|
||||
- **Self-hosted Postiz** ([Postiz docs](https://docs.postiz.com/)) — optional, for social publishing
|
||||
- **Google Gemini API key** — [free tier](https://aistudio.google.com/app/apikey) — used for moment detection, layouts, titles and thumbnails. Optional if you set `LLM_BASE_URL`.
|
||||
- **A self-hosted Postiz instance** — optional, only for publishing.
|
||||
|
||||
---
|
||||
## Quick start
|
||||
|
||||
## Getting Started
|
||||
|
||||
### 1. Clone
|
||||
```bash
|
||||
git clone https://git.pbento.pt/pedro-bento/clipwright.git
|
||||
cd clipwright
|
||||
```
|
||||
|
||||
### 2. Configure (optional)
|
||||
```bash
|
||||
cp .env.example .env
|
||||
# Edit .env with your AWS keys for S3 backup and your Postiz URL/key
|
||||
```
|
||||
|
||||
### 3. Launch
|
||||
```bash
|
||||
cp .env.example .env # optional: Postiz server-side key
|
||||
docker compose up --build
|
||||
```
|
||||
|
||||
### 4. Open Dashboard
|
||||
Navigate to **`http://localhost:5175`**
|
||||
Open the dashboard at **http://localhost:5175**, go to **Settings**, and paste your keys (Gemini; Postiz is optional). Then:
|
||||
|
||||
1. Go to **Settings** and enter your API keys (Gemini, ElevenLabs) and your Postiz URL + API key
|
||||
2. **Clip Generator**: Upload a long-form video to generate viral shorts
|
||||
3. **YouTube Studio**: Generate thumbnails, titles, and descriptions for YouTube
|
||||
1. **Clip Generator** — upload a long video or paste a URL.
|
||||
2. **YouTube Studio** — generate titles, thumbnails and descriptions.
|
||||
3. Publish a finished clip to your connected Postiz channels.
|
||||
|
||||
### 5. GPU acceleration (optional, NVIDIA)
|
||||
## Configuration
|
||||
|
||||
The default image is CPU-only. With an NVIDIA card (any card with NVENC, e.g. RTX 4060) an 8-minute video clips in about a minute instead of 5 to 8. Nothing is passed through in the VM sense — the container just gets access to the host GPU.
|
||||
Server-side (`.env`):
|
||||
|
||||
| Variable | Purpose |
|
||||
|---|---|
|
||||
| `GEMINI_API_KEY` | Gemini key used server-side (self-host). The dashboard can also send one per request. |
|
||||
| `LLM_BASE_URL` / `LLM_MODEL` / `LLM_API_KEY` | Point the moment picker at any OpenAI-compatible server (Ollama, vLLM, LM Studio…) to run without a Google key. |
|
||||
| `POSTIZ_URL` / `POSTIZ_API_KEY` | Your Postiz instance + API key, used when the dashboard does not send them. |
|
||||
| `MAX_CONCURRENT_JOBS` | Concurrent jobs (default 5). |
|
||||
| `MAX_FILE_SIZE_MB` | Upload cap in MB; `0` (default) is unlimited. |
|
||||
|
||||
Client-side (stored encrypted in your browser): `GEMINI_API_KEY`, `postiz_url`, `postiz_key_v1`.
|
||||
|
||||
### Run without a Google key (optional)
|
||||
|
||||
**Host:** install the NVIDIA driver (`nvidia-smi` must work) and the [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html):
|
||||
```bash
|
||||
sudo nvidia-ctk runtime configure --runtime=docker && sudo systemctl restart docker
|
||||
docker run --rm --gpus all nvidia/cuda:12.4.0-base-ubuntu22.04 nvidia-smi # sanity check
|
||||
# .env
|
||||
LLM_BASE_URL=http://host.docker.internal:11434/v1 # Ollama on the host
|
||||
LLM_MODEL=qwen2.5:14b
|
||||
```
|
||||
On Windows use Docker Desktop with the WSL2 backend and the Windows NVIDIA driver; no driver inside WSL.
|
||||
|
||||
**Compose:** create `docker-compose.override.yml` next to `docker-compose.yml` (picked up automatically). `GPU: "1"` adds cuBLAS/cuDNN and onnxruntime-gpu to the image (~2 GB); `video` is required for NVENC.
|
||||
Works with Ollama, LM Studio, vLLM, llama.cpp, LocalAI and OpenRouter. Use `OLLAMA_CONTEXT_LENGTH=16384` or higher. The moment picker then runs locally; frame-based stages (layout picker, silent videos) still use Gemini if a key is present.
|
||||
|
||||
### GPU acceleration (optional, NVIDIA)
|
||||
|
||||
The default image is CPU-only. With an NVIDIA card an 8-minute video clips in about a minute instead of 5–8. Install the [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html), then create `docker-compose.override.yml`:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
backend:
|
||||
|
|
@ -150,79 +79,16 @@ services:
|
|||
capabilities: [gpu, video]
|
||||
```
|
||||
|
||||
**`.env`:**
|
||||
```
|
||||
WHISPER_MODEL=large-v3-turbo
|
||||
WHISPER_DEVICE=cuda
|
||||
WHISPER_COMPUTE=float16
|
||||
FFMPEG_ENCODER=auto # probes h264_nvenc at startup, falls back to x264
|
||||
TRANSCRIBE_BACKEND=parakeet # optional: ~2x faster than whisper, 25 European languages, auto-falls back to whisper
|
||||
ASR_GPU_CONCURRENCY=1
|
||||
```
|
||||
## Publishing with Postiz
|
||||
|
||||
**Verify:**
|
||||
```bash
|
||||
docker compose up --build -d
|
||||
docker exec clipwright-backend nvidia-smi -L
|
||||
docker exec clipwright-backend ffmpeg -hide_banner -f lavfi -i testsrc=size=256x256:rate=1 -frames:v 1 -c:v h264_nvenc -f null -
|
||||
```
|
||||
The backend log on the first job reports the chosen encoder and transcription device. A CUDA error in whisper (e.g. VRAM exhausted) retries once on CPU automatically. 8 GB of VRAM is enough for `large-v3-turbo` fp16 plus the detection models.
|
||||
1. Run Postiz yourself and connect TikTok, Instagram and/or YouTube inside it.
|
||||
2. Create a public API key in Postiz (**Settings → Developers / Public API**).
|
||||
3. In Clipwright **Settings**, enter your Postiz URL and key, then **Test connection** to list your channels.
|
||||
4. In the publish modal, tick the exact channel each clip should go to. Multiple channels per network are supported (for example two YouTube channels), so you pick the channel itself, not the platform, and schedule it with a **DD/MM/YYYY** date.
|
||||
|
||||
---
|
||||
Clipwright uploads the clip to your Postiz instance and creates the post there; the platform tokens never leave your infrastructure.
|
||||
|
||||
### 6. Run without a Google key (local LLM, optional)
|
||||
|
||||
The only cloud call in the clip pipeline is the moment picker: it sends the
|
||||
transcript (never the video) to Gemini. Point it at any OpenAI-compatible
|
||||
server instead and the whole pipeline stays on your box:
|
||||
|
||||
```bash
|
||||
# .env
|
||||
LLM_BASE_URL=http://host.docker.internal:11434/v1 # Ollama on the host
|
||||
LLM_MODEL=qwen2.5:14b # any chat model that follows instructions
|
||||
# LLM_API_KEY=... # only if your server checks one (vLLM --api-key, OpenRouter)
|
||||
```
|
||||
|
||||
Works with Ollama, LM Studio, vLLM, llama.cpp server, LocalAI and OpenRouter.
|
||||
The dashboard stops asking for a Gemini key when this is set. Two things to
|
||||
know:
|
||||
|
||||
- **Context length.** A scoring call carries three transcript windows
|
||||
(~2-3k tokens) and the detail call up to ten (~5k on a long podcast).
|
||||
Ollama defaults to a 4096-token context and truncates silently, so run it
|
||||
with `OLLAMA_CONTEXT_LENGTH=16384` (or set `num_ctx` in a Modelfile); raise
|
||||
`LLM_SCORE_BATCH` above 3 only if your context allows it. 7-8B models
|
||||
return valid JSON reliably, 3B ones do not.
|
||||
- **What still needs Gemini.** Anything that has to look at frames: the
|
||||
automatic layout picker (`AUTO_LAYOUT`), the on-screen content detector
|
||||
and silent videos (no speech to clip by). Without a Gemini key those fall
|
||||
back to the plain face-tracking crop, and a silent video fails with a
|
||||
message that says so. Add a key alongside `LLM_BASE_URL` and you get both.
|
||||
|
||||
## Technical Pipeline
|
||||
|
||||
### Clip Generator
|
||||
1. **Ingest** — Local video upload (or self-hosted URL ingest via yt-dlp)
|
||||
2. **Transcribe** — faster-whisper with word-level timestamps
|
||||
3. **Detect** — PySceneDetect for scene boundaries
|
||||
4. **Analyze** — Gemini identifies 3-15 viral moments (15-60s each)
|
||||
5. **Extract** — FFmpeg precise clip cutting
|
||||
6. **Reframe** — AI vertical cropping with subject tracking
|
||||
7. **Effects** — Subtitles, hooks, AI video effects
|
||||
8. **Publish** — S3 backup + publishing through Postiz
|
||||
|
||||
### YouTube Studio
|
||||
1. **Titles** — Gemini generates 10 options with an interactive refinement chat
|
||||
2. **Thumbnails** — AI image generation with an optional uploaded face and background
|
||||
3. **Descriptions** — auto-written from the Whisper transcript with chapter timestamps
|
||||
|
||||
---
|
||||
|
||||
## Automate It: REST API and Webhooks
|
||||
|
||||
You don't need the dashboard. The pipeline is callable by scripts and workflows.
|
||||
|
||||
### REST API
|
||||
## API and webhooks
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:8000/api/process \
|
||||
|
|
@ -231,91 +97,30 @@ curl -X POST http://localhost:8000/api/process \
|
|||
"webhook_url": "https://your-server.com/hooks/clipwright"}'
|
||||
```
|
||||
|
||||
Interactive docs at `/docs` (OpenAPI) on any instance.
|
||||
Add `webhook_url` for exactly one callback when the job ends; with `webhook_secret` the body is signed `X-Clipwright-Signature: sha256=…`. Interactive docs are at `/docs`.
|
||||
|
||||
### Completion webhooks
|
||||
## Project structure
|
||||
|
||||
Pass `webhook_url` (and optionally `webhook_secret`) to `POST /api/process` and you get exactly one `POST` when the job reaches a terminal state — no polling loops in your n8n / cron pipelines:
|
||||
|
||||
```json
|
||||
{"event": "job.completed", "job_id": "…",
|
||||
"clips": [{"index": 0, "title": "…", "video_url": "…"}]}
|
||||
```
|
||||
clipwright/ # Python backend package
|
||||
core/ # shared helpers (security, filesystem paths)
|
||||
api/ # FastAPI app, auth, free tools
|
||||
pipeline/ # download → transcribe → clip orchestration, Gemini, quality probe
|
||||
layouts/ # reframing: active speaker, split/screencast, punch-in
|
||||
media/ # FFmpeg helpers, subtitles, hooks, thumbnails, recut
|
||||
integrations/ # Postiz, YouTube, file hosts
|
||||
tools/ # local verification scripts (python -m clipwright.tools.verify_hooks)
|
||||
dashboard/ # React + Vite dashboard (its own build)
|
||||
tests/ # pytest suite (pythonpath = ["."])
|
||||
fonts/ assets/ # shared runtime resources (kept at repo root)
|
||||
```
|
||||
|
||||
With a secret, the body is signed: `X-Clipwright-Signature: sha256=<hmac-sha256(body)>`.
|
||||
The backend runs from the source tree (no install step): `uvicorn clipwright.api.app:app` serves the API and clip jobs run as `python -m clipwright.pipeline.main`.
|
||||
|
||||
### n8n
|
||||
## Tech stack
|
||||
|
||||
An importable workflow (video URL in, clips out, no polling) lives in
|
||||
[`examples/n8n/`](examples/n8n/). Publishing in the workflow goes through your
|
||||
Postiz instance.
|
||||
|
||||
---
|
||||
|
||||
## Tech Stack
|
||||
|
||||
| Layer | Technology |
|
||||
|-------|-----------|
|
||||
| Backend | Python 3.11, FastAPI, google-genai, faster-whisper, ultralytics (YOLOv8), mediapipe, opencv-python, yt-dlp, FFmpeg, httpx |
|
||||
| Frontend | React 18, Vite 4, Tailwind CSS 3.4 |
|
||||
| AI APIs | Google Gemini, ElevenLabs |
|
||||
| Infrastructure | Docker + Docker Compose, AWS S3 (optional) |
|
||||
| Publishing | Self-hosted [Postiz](https://postiz.com/) (TikTok, Instagram, YouTube) |
|
||||
|
||||
---
|
||||
|
||||
## Environment Variables
|
||||
|
||||
**Server-side (.env):**
|
||||
| Variable | Description |
|
||||
|----------|------------|
|
||||
| `AWS_ACCESS_KEY_ID` | AWS access key for S3 (optional) |
|
||||
| `AWS_SECRET_ACCESS_KEY` | AWS secret key (optional) |
|
||||
| `AWS_REGION` | AWS region (default: us-east-1) |
|
||||
| `AWS_S3_BUCKET` | Private bucket for clip backup (optional) |
|
||||
| `MAX_CONCURRENT_JOBS` | Concurrent processing limit (default: 5) |
|
||||
| `MAX_FILE_SIZE_MB` | Upload size cap in MB. `0` (default) is unlimited |
|
||||
| `LLM_BASE_URL` | OpenAI-compatible server for the moment picker (Ollama, vLLM, LM Studio...). Set it and the Gemini key becomes optional |
|
||||
| `LLM_MODEL` | Model name on that server (default `llama3.1:8b`) |
|
||||
| `LLM_API_KEY` | Bearer token for that server, if it checks one |
|
||||
| `LLM_SCORE_BATCH` | Transcript windows per scoring call (default 3 local, 8 Gemini) |
|
||||
| `POSTIZ_URL` | Base URL of your self-hosted Postiz instance |
|
||||
| `POSTIZ_API_KEY` | Postiz API key used server-side when the dashboard does not send one |
|
||||
|
||||
**Client-side (encrypted in localStorage):**
|
||||
| Key | Description |
|
||||
|-----|------------|
|
||||
| `GEMINI_API_KEY` | Google Gemini — required unless `LLM_BASE_URL` is set (then only for layout picking and silent videos) |
|
||||
| `ELEVENLABS_API_KEY` | ElevenLabs — optional, for voice dubbing |
|
||||
| `postiz_url` | Base URL of your self-hosted Postiz instance |
|
||||
| `postiz_key_v1` | Postiz API key, sent to the backend as `X-Postiz-Key` |
|
||||
|
||||
---
|
||||
|
||||
## Security & Performance
|
||||
|
||||
- **Non-Root Execution**: Containers run as dedicated `appuser`
|
||||
- **Concurrency Control**: Semaphore-based job queue (`MAX_CONCURRENT_JOBS`)
|
||||
- **Auto-Cleanup**: Automatic purging of old jobs (1h retention)
|
||||
- **Encrypted Keys**: API keys encrypted client-side, never stored server-side
|
||||
- **Upload Validation**: Image uploads validated for format and minimum size
|
||||
- **Configurable File Limits**: `MAX_FILE_SIZE_MB` (0 = unlimited)
|
||||
|
||||
---
|
||||
|
||||
## Social Publishing Setup (Postiz)
|
||||
|
||||
1. **Deploy Postiz**: run your own instance with Docker (see the [Postiz docs](https://docs.postiz.com/))
|
||||
2. **Connect accounts**: link TikTok, Instagram and/or YouTube inside Postiz
|
||||
3. **Create an API key**: in Postiz settings, generate a public API key
|
||||
4. **Use in Clipwright**: paste the Postiz URL and key in Settings, then use "Test connection" to list the connected channels
|
||||
|
||||
---
|
||||
|
||||
## Contributions
|
||||
|
||||
Contributions are welcome! Whether it's improving the crop and subtitle pipeline or the dashboard — feel free to open a PR.
|
||||
Python 3.11 · FastAPI · google-genai · faster-whisper · ultralytics (YOLOv8) · MediaPipe · FFmpeg · React 18 · Vite · Tailwind · Docker Compose.
|
||||
|
||||
## License
|
||||
|
||||
MIT License — Clipwright is yours to use, modify, and scale.
|
||||
MIT. Forked from [OpenShorts](https://github.com/mutonby/openshorts); upstream copyright preserved in [LICENSE](LICENSE) and [NOTICE](NOTICE).
|
||||
|
|
|
|||
|
|
@ -1,46 +0,0 @@
|
|||
"""Render the Clipwright watermark lockup (white mark + wordmark) to a PNG.
|
||||
|
||||
Pre-rendered at 4x so it downscales cleanly onto any clip size, with a soft
|
||||
dark shadow so it stays legible over bright footage.
|
||||
"""
|
||||
from PIL import Image, ImageDraw, ImageFont, ImageFilter
|
||||
|
||||
S = 4 # supersampling
|
||||
H = 64 * S # lockup height
|
||||
PAD = 6 * S
|
||||
|
||||
font = ImageFont.truetype("/System/Library/Fonts/HelveticaNeue.ttc", int(38 * S), index=1) # Bold
|
||||
text = "Clipwright"
|
||||
|
||||
tmp = Image.new("RGBA", (10, 10))
|
||||
tb = ImageDraw.Draw(tmp).textbbox((0, 0), text, font=font)
|
||||
tw, th = tb[2] - tb[0], tb[3] - tb[1]
|
||||
|
||||
mark = int(40 * S) # square mark
|
||||
gap = int(12 * S)
|
||||
W = mark + gap + tw + PAD * 2
|
||||
|
||||
img = Image.new("RGBA", (W, H), (0, 0, 0, 0))
|
||||
d = ImageDraw.Draw(img)
|
||||
|
||||
# Rounded square outline + play triangle: reads as "clip/play" at small sizes.
|
||||
mx, my = PAD, (H - mark) // 2
|
||||
r = int(mark * 0.28)
|
||||
d.rounded_rectangle([mx, my, mx + mark, my + mark], radius=r,
|
||||
outline=(255, 255, 255, 255), width=int(3.5 * S))
|
||||
t = mark * 0.30
|
||||
cx, cy = mx + mark / 2, my + mark / 2
|
||||
d.polygon([(cx - t * 0.55, cy - t), (cx - t * 0.55, cy + t), (cx + t * 0.85, cy)],
|
||||
fill=(255, 255, 255, 255))
|
||||
|
||||
d.text((mx + mark + gap - tb[0], (H - th) // 2 - tb[1]), text, font=font,
|
||||
fill=(255, 255, 255, 255))
|
||||
|
||||
# Soft shadow behind everything for contrast on light footage.
|
||||
shadow = Image.new("RGBA", (W, H), (0, 0, 0, 0))
|
||||
shadow.paste((0, 0, 0, 170), (0, 0), img.split()[3])
|
||||
shadow = shadow.filter(ImageFilter.GaussianBlur(int(2.5 * S)))
|
||||
out = Image.alpha_composite(shadow, img)
|
||||
|
||||
out.save("watermark.png")
|
||||
print("watermark.png", out.size)
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 65 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 62 MiB |
Binary file not shown.
|
Before Width: | Height: | Size: 2.5 MiB |
|
|
@ -1,58 +0,0 @@
|
|||
# Clipwright CLI
|
||||
|
||||
Clip long videos into vertical 9:16 shorts from the terminal. Zero
|
||||
dependencies; talks to the same self-hosted REST API the dashboard uses.
|
||||
|
||||
```bash
|
||||
pip install clipwright # or: uvx clipwright / pipx run clipwright
|
||||
```
|
||||
|
||||
## Use it against your own instance
|
||||
|
||||
Clipwright is free, open source under MIT and self-hosted with Docker. There is
|
||||
no hosted edition and no paid plan, so there is no account to create. Point the
|
||||
CLI at your instance:
|
||||
|
||||
```bash
|
||||
export CLIPWRIGHT_API_URL=http://localhost:8000
|
||||
|
||||
clipwright process "https://youtube.com/watch?v=..." --wait
|
||||
clipwright clips <job_id>
|
||||
clipwright publish <job_id> 0 --platforms tiktok,youtube
|
||||
clipwright quota
|
||||
```
|
||||
|
||||
Self-hosted instances are open by default and need no API key. You do need a
|
||||
Google Gemini key: put it in the server's environment, or send it per call as an
|
||||
`X-Gemini-Key` header. If you put your own instance behind a key, the CLI sends
|
||||
`CLIPWRIGHT_API_KEY` (`clw_...`) as a bearer token.
|
||||
|
||||
## Publish through Postiz
|
||||
|
||||
Publishing goes through your self-hosted Postiz instance. Pass the base URL and
|
||||
API key with `--postiz-url` / `--postiz-key`, or set `POSTIZ_URL` /
|
||||
`POSTIZ_API_KEY`; the CLI forwards them to the server as `X-Postiz-Url` /
|
||||
`X-Postiz-Key`.
|
||||
|
||||
```bash
|
||||
clipwright publish <job_id> 0 --platforms tiktok,youtube \
|
||||
--postiz-url https://postiz.example.com --postiz-key <key>
|
||||
```
|
||||
|
||||
## Quota
|
||||
|
||||
`clipwright quota` prints the instance config it reads from `GET /api/config`:
|
||||
the job-retention window, whether YouTube-URL ingest is enabled, and the
|
||||
local-LLM setting. A self-hosted instance has no minute quota, so none is
|
||||
reported.
|
||||
|
||||
## Pipelines and webhooks
|
||||
|
||||
Prefer the webhook to `--wait`: pass `--webhook` and `--webhook-secret` and
|
||||
Clipwright POSTs once (HMAC-signed, `X-Clipwright-Signature: sha256=<hex>`) when
|
||||
the job ends, with each clip's title and `video_url`. Set `PUBLIC_API_URL` on
|
||||
the server so those links are absolute; otherwise they are relative to your
|
||||
instance.
|
||||
|
||||
The agent-native version of the same surface is the Clipwright skill in
|
||||
[`skills/clipwright/`](../skills/clipwright/).
|
||||
|
|
@ -1,251 +0,0 @@
|
|||
"""Clipwright CLI: clip long videos into vertical shorts from the terminal.
|
||||
|
||||
Zero dependencies by design so `uvx clipwright` and `pipx run clipwright`
|
||||
start instantly. Talks to the same REST API the dashboard uses; nothing here
|
||||
can drift from what the app actually does.
|
||||
|
||||
Auth and target come from the environment:
|
||||
CLIPWRIGHT_API_KEY clw_... key for a deploy that requires one (optional;
|
||||
a self-hosted instance needs none)
|
||||
CLIPWRIGHT_API_URL defaults to http://localhost:8000 for a self-hosted
|
||||
instance, where no key is needed.
|
||||
|
||||
Publishing goes through Postiz. The base URL and API key come from the
|
||||
--postiz-url / --postiz-key flags, then POSTIZ_URL / POSTIZ_API_KEY.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
DEFAULT_API = "http://localhost:8000"
|
||||
POLL_SECONDS = 10
|
||||
|
||||
|
||||
def _base():
|
||||
return os.environ.get("CLIPWRIGHT_API_URL", DEFAULT_API).rstrip("/")
|
||||
|
||||
|
||||
def _request(method, path, body=None, extra_headers=None):
|
||||
headers = {"Accept": "application/json"}
|
||||
if extra_headers:
|
||||
headers.update(extra_headers)
|
||||
key = os.environ.get("CLIPWRIGHT_API_KEY")
|
||||
if key:
|
||||
headers["Authorization"] = f"Bearer {key}"
|
||||
data = None
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode()
|
||||
headers["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(_base() + path, data=data, headers=headers, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=120) as resp:
|
||||
return resp.status, json.loads(resp.read().decode() or "{}")
|
||||
except urllib.error.HTTPError as e:
|
||||
try:
|
||||
payload = json.loads(e.read().decode() or "{}")
|
||||
except Exception:
|
||||
payload = {"detail": str(e.reason)}
|
||||
return e.code, payload
|
||||
except urllib.error.URLError as e:
|
||||
print(f"error: cannot reach {_base()} ({e.reason})", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
|
||||
|
||||
def _die(status, payload):
|
||||
detail = payload.get("detail", payload) if isinstance(payload, dict) else payload
|
||||
if not isinstance(detail, str):
|
||||
detail = json.dumps(detail)
|
||||
print(f"error ({status}): {detail}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def _absolutize(url):
|
||||
if url and url.startswith("/"):
|
||||
return _base() + url
|
||||
return url
|
||||
|
||||
|
||||
def _print_clips(result):
|
||||
clips = (result or {}).get("clips") or []
|
||||
if not clips:
|
||||
print("no clips in result")
|
||||
return
|
||||
for i, clip in enumerate(clips):
|
||||
title = clip.get("title") or clip.get("video_title_for_youtube_short") or f"clip {i}"
|
||||
print(f"[{i}] {title}")
|
||||
print(f" {_absolutize(clip.get('video_url') or '')}")
|
||||
|
||||
|
||||
def cmd_process(args):
|
||||
body = {"url": args.url, "acknowledged": True}
|
||||
if args.layouts:
|
||||
body["layouts"] = args.layouts
|
||||
if args.format:
|
||||
body["output_format"] = args.format
|
||||
if args.webhook:
|
||||
body["webhook_url"] = args.webhook
|
||||
if args.webhook_secret:
|
||||
body["webhook_secret"] = args.webhook_secret
|
||||
status, payload = _request("POST", "/api/process", body)
|
||||
if status >= 400:
|
||||
_die(status, payload)
|
||||
job_id = payload.get("job_id")
|
||||
if args.json and not args.wait:
|
||||
print(json.dumps(payload))
|
||||
return
|
||||
print(f"job queued: {job_id}")
|
||||
if args.wait:
|
||||
_watch(job_id, as_json=args.json)
|
||||
else:
|
||||
print(f"follow it with: clipwright status {job_id} --watch")
|
||||
|
||||
|
||||
def _watch(job_id, as_json=False):
|
||||
seen_logs = 0
|
||||
while True:
|
||||
status, payload = _request("GET", f"/api/status/{job_id}")
|
||||
if status >= 400:
|
||||
_die(status, payload)
|
||||
logs = payload.get("logs") or []
|
||||
for line in logs[seen_logs:]:
|
||||
print(f" {line}")
|
||||
seen_logs = len(logs)
|
||||
state = payload.get("status")
|
||||
if state == "completed":
|
||||
if as_json:
|
||||
print(json.dumps(payload.get("result") or {}))
|
||||
else:
|
||||
print("completed:")
|
||||
_print_clips(payload.get("result"))
|
||||
return
|
||||
if state == "failed":
|
||||
print("job failed; last log lines above", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
time.sleep(POLL_SECONDS)
|
||||
|
||||
|
||||
def cmd_status(args):
|
||||
if args.watch:
|
||||
_watch(args.job_id, as_json=args.json)
|
||||
return
|
||||
status, payload = _request("GET", f"/api/status/{args.job_id}")
|
||||
if status >= 400:
|
||||
_die(status, payload)
|
||||
if args.json:
|
||||
print(json.dumps(payload))
|
||||
return
|
||||
print(f"status: {payload.get('status')}")
|
||||
logs = payload.get("logs") or []
|
||||
if logs:
|
||||
print(f"last log: {logs[-1]}")
|
||||
|
||||
|
||||
def cmd_clips(args):
|
||||
status, payload = _request("GET", f"/api/status/{args.job_id}")
|
||||
if status >= 400:
|
||||
_die(status, payload)
|
||||
if payload.get("status") != "completed":
|
||||
print(f"job is {payload.get('status')}, no clips yet", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
if args.json:
|
||||
print(json.dumps((payload.get("result") or {}).get("clips") or []))
|
||||
return
|
||||
_print_clips(payload.get("result"))
|
||||
|
||||
|
||||
def cmd_quota(args):
|
||||
# Self-host has no minute quota: the cloud account/quota router is gone.
|
||||
# Report the instance config instead so the command stays useful.
|
||||
status, payload = _request("GET", "/api/config")
|
||||
if status >= 400:
|
||||
_die(status, payload)
|
||||
if args.json:
|
||||
print(json.dumps(payload))
|
||||
return
|
||||
print("self-hosted: no minute quota")
|
||||
print(f"job retention: {payload.get('jobRetentionSeconds')}s")
|
||||
print(f"youtube url: {'enabled' if payload.get('youtubeUrlEnabled') else 'disabled'}")
|
||||
local_llm = payload.get("localLlm")
|
||||
if local_llm:
|
||||
print(f"local llm: {local_llm}")
|
||||
|
||||
|
||||
def cmd_publish(args):
|
||||
body = {
|
||||
"job_id": args.job_id,
|
||||
"clip_index": args.clip_index,
|
||||
"platforms": [p.strip() for p in args.platforms.split(",") if p.strip()],
|
||||
}
|
||||
if args.title:
|
||||
body["title"] = args.title
|
||||
if args.schedule:
|
||||
body["scheduled_date"] = args.schedule
|
||||
if args.timezone:
|
||||
body["timezone"] = args.timezone
|
||||
postiz_key = args.postiz_key or os.environ.get("POSTIZ_API_KEY")
|
||||
if not postiz_key:
|
||||
print("error: no Postiz API key: pass --postiz-key or set POSTIZ_API_KEY",
|
||||
file=sys.stderr)
|
||||
sys.exit(1)
|
||||
postiz_url = (args.postiz_url or os.environ.get("POSTIZ_URL") or "").rstrip("/")
|
||||
headers = {"X-Postiz-Key": postiz_key}
|
||||
if postiz_url:
|
||||
headers["X-Postiz-Url"] = postiz_url
|
||||
status, payload = _request("POST", "/api/postiz/post", body,
|
||||
extra_headers=headers)
|
||||
if status >= 400:
|
||||
_die(status, payload)
|
||||
print(json.dumps(payload) if args.json else f"publishing: {payload}")
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="clipwright",
|
||||
description="Clip long videos into vertical shorts via the Clipwright API.",
|
||||
)
|
||||
parser.add_argument("--json", action="store_true", help="raw JSON output")
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
p = sub.add_parser("process", help="submit a video URL for clipping")
|
||||
p.add_argument("url", help="YouTube or direct video URL")
|
||||
p.add_argument("--layouts", help="comma list: auto,split,screencast,speaker_cut,punch_in")
|
||||
p.add_argument("--format", help="output format, e.g. 1080p")
|
||||
p.add_argument("--webhook", help="webhook URL fired once when the job ends")
|
||||
p.add_argument("--webhook-secret", help="HMAC secret for X-Clipwright-Signature")
|
||||
p.add_argument("--wait", action="store_true", help="stream logs until the job ends")
|
||||
p.set_defaults(func=cmd_process)
|
||||
|
||||
p = sub.add_parser("status", help="job status and last log line")
|
||||
p.add_argument("job_id")
|
||||
p.add_argument("--watch", action="store_true", help="stream logs until the job ends")
|
||||
p.set_defaults(func=cmd_status)
|
||||
|
||||
p = sub.add_parser("clips", help="list finished clips with links")
|
||||
p.add_argument("job_id")
|
||||
p.set_defaults(func=cmd_clips)
|
||||
|
||||
p = sub.add_parser("quota", help="instance config (self-host has no quota)")
|
||||
p.set_defaults(func=cmd_quota)
|
||||
|
||||
p = sub.add_parser("publish", help="post or schedule one clip through Postiz")
|
||||
p.add_argument("job_id")
|
||||
p.add_argument("clip_index", type=int)
|
||||
p.add_argument("--platforms", required=True, help="comma list: tiktok,instagram,youtube")
|
||||
p.add_argument("--title")
|
||||
p.add_argument("--schedule", help="ISO datetime for scheduled posting")
|
||||
p.add_argument("--timezone", help="IANA timezone for --schedule")
|
||||
p.add_argument("--postiz-url", help="Postiz base URL (env POSTIZ_URL)")
|
||||
p.add_argument("--postiz-key", help="Postiz API key (env POSTIZ_API_KEY)")
|
||||
p.set_defaults(func=cmd_publish)
|
||||
|
||||
args = parser.parse_args(argv)
|
||||
args.func(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -1,30 +0,0 @@
|
|||
[build-system]
|
||||
requires = ["setuptools>=68"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "clipwright"
|
||||
version = "0.1.0"
|
||||
description = "CLI for Clipwright: clip long videos into vertical shorts and publish them, from the terminal"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.9"
|
||||
license = { text = "MIT" }
|
||||
authors = [{ name = "Clipwright" }]
|
||||
keywords = ["video", "clips", "shorts", "ai", "tiktok", "youtube-shorts", "cli"]
|
||||
classifiers = [
|
||||
"Environment :: Console",
|
||||
"License :: OSI Approved :: MIT License",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Topic :: Multimedia :: Video",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
Homepage = "https://git.pbento.pt/pedro-bento/clipwright"
|
||||
Source = "https://git.pbento.pt/pedro-bento/clipwright"
|
||||
Documentation = "https://git.pbento.pt/pedro-bento/clipwright/tree/main/cli"
|
||||
|
||||
[project.scripts]
|
||||
clipwright = "clipwright_cli:main"
|
||||
|
||||
[tool.setuptools]
|
||||
py-modules = ["clipwright_cli"]
|
||||
1
clipwright/__init__.py
Normal file
1
clipwright/__init__.py
Normal file
|
|
@ -0,0 +1 @@
|
|||
"""Clipwright backend."""
|
||||
1
clipwright/api/__init__.py
Normal file
1
clipwright/api/__init__.py
Normal file
|
|
@ -0,0 +1 @@
|
|||
"""Clipwright backend."""
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -41,6 +41,8 @@ from urllib.parse import parse_qs, urlparse
|
|||
from fastapi import APIRouter, HTTPException, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from clipwright.media import title_validation
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
|
@ -476,6 +478,7 @@ class MetadataRequest(BaseModel):
|
|||
topic: str
|
||||
keyword: Optional[str] = ""
|
||||
audience: Optional[str] = ""
|
||||
channel: Optional[str] = None
|
||||
|
||||
|
||||
_COMMON_RULES = """
|
||||
|
|
@ -543,8 +546,13 @@ def _clean(s: str) -> str:
|
|||
return re.sub(r"\s*—\s*", ", ", (s or "")).strip()
|
||||
|
||||
|
||||
def shape_result(mode: str, data: dict) -> dict:
|
||||
"""Validate and tidy the model's JSON into what the page renders."""
|
||||
def shape_result(mode: str, data: dict, profile=None) -> dict:
|
||||
"""Validate and tidy the model's JSON into what the page renders.
|
||||
|
||||
For ``titles``, ``profile`` adds the channel's rule checks (PLAN #3) and the
|
||||
result carries a ``violations`` list so the caller can re-ask once. The
|
||||
caller pops ``violations`` before returning it to the client.
|
||||
"""
|
||||
if mode == "titles":
|
||||
items = []
|
||||
for t in (data.get("titles") or [])[:12]:
|
||||
|
|
@ -555,7 +563,11 @@ def shape_result(mode: str, data: dict) -> dict:
|
|||
items.append({"title": title, "angle": _clean(str(t.get("angle", "")))[:40]})
|
||||
if not items:
|
||||
raise ValueError("no titles")
|
||||
return {"titles": items}
|
||||
return {
|
||||
"titles": items,
|
||||
"violations": title_validation.validate_titles(
|
||||
[i["title"] for i in items], profile),
|
||||
}
|
||||
if mode == "description":
|
||||
desc = _clean(str(data.get("description", "")))[:5000]
|
||||
if not desc:
|
||||
|
|
@ -576,6 +588,37 @@ def shape_result(mode: str, data: dict) -> dict:
|
|||
return {"tags": tags, "characters": len(",".join(tags))}
|
||||
|
||||
|
||||
def _profile_for_channel(channel):
|
||||
"""Resolve the optional channel field to a Profile (PLAN #3)."""
|
||||
slug = str(channel or "").strip()
|
||||
if not slug:
|
||||
return None
|
||||
from clipwright.pipeline.profiles import ProfileError, load_profile
|
||||
try:
|
||||
return load_profile(slug)
|
||||
except ProfileError as e:
|
||||
raise HTTPException(status_code=400,
|
||||
detail={"code": "bad_channel", "message": str(e)})
|
||||
|
||||
|
||||
def _retry_titles(prompt, candidate, profile):
|
||||
"""One re-ask with the critique; keeps the first attempt if it fails."""
|
||||
def validate(c):
|
||||
return title_validation.validate_titles([t["title"] for t in c["titles"]], profile)
|
||||
|
||||
def retry_once(violations):
|
||||
try:
|
||||
data = _generate(prompt + "\n\n" + title_validation.critique_block(violations))
|
||||
return shape_result("titles", data, profile)
|
||||
except Exception as e: # a failed re-ask must not lose the first attempt
|
||||
print(f"[free_tools] title retry failed: {e}")
|
||||
return None
|
||||
|
||||
best = title_validation.run_with_validation(lambda: candidate, validate, retry_once)
|
||||
best.pop("violations", None)
|
||||
return best
|
||||
|
||||
|
||||
def _gemini_key():
|
||||
return os.environ.get("GEMINI_API_KEY", "").strip() or None
|
||||
|
||||
|
|
@ -631,12 +674,20 @@ async def youtube_metadata(payload: MetadataRequest, request: Request):
|
|||
raise HTTPException(status_code=503, detail={
|
||||
"code": "not_configured", "message": "This tool needs a Gemini API key on the server."})
|
||||
_enforce("metadata", request)
|
||||
profile = _profile_for_channel(payload.channel)
|
||||
prompt = build_prompt(mode, topic.replace("{", "(").replace("}", ")"), keyword, audience)
|
||||
last = None
|
||||
for _ in range(2):
|
||||
try:
|
||||
data = await asyncio.wait_for(asyncio.to_thread(_generate, prompt), timeout=40)
|
||||
return {"mode": mode, **shape_result(mode, data)}
|
||||
shaped = shape_result(mode, data, profile)
|
||||
# Deterministic title QA (PLAN #3): one re-ask if the titles break
|
||||
# the rules, then keep the better attempt. Never blocks the job.
|
||||
if mode == "titles" and shaped.get("violations"):
|
||||
shaped = await asyncio.wait_for(
|
||||
asyncio.to_thread(_retry_titles, prompt, shaped, profile), timeout=80)
|
||||
shaped.pop("violations", None)
|
||||
return {"mode": mode, **shaped}
|
||||
except asyncio.TimeoutError:
|
||||
last = "timeout"
|
||||
break
|
||||
|
|
@ -11,23 +11,18 @@ This subclass keeps everything ``StaticFiles`` does (Range requests, ETags,
|
|||
HEAD) and adds one step before the filesystem: ``guard`` (the allowlist,
|
||||
``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
|
||||
guard only -- there is no restorer in this fork.
|
||||
|
||||
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.
|
||||
guard only.
|
||||
"""
|
||||
from typing import Awaitable, Callable, Optional
|
||||
from typing import Callable, Optional
|
||||
|
||||
from starlette.exceptions import HTTPException
|
||||
from starlette.staticfiles import StaticFiles
|
||||
|
||||
Restorer = Callable[[str], Awaitable[bool]]
|
||||
Guard = Callable[[str], bool]
|
||||
|
||||
|
||||
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
|
||||
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
|
||||
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
|
||||
the module docstring.
|
||||
anyone who has the job id.
|
||||
"""
|
||||
|
||||
def __init__(self, *args, restorer: Optional[Restorer] = None,
|
||||
guard: Optional[Guard] = None, **kwargs):
|
||||
def __init__(self, *args, guard: Optional[Guard] = None, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.restorer = restorer
|
||||
self.guard = guard
|
||||
|
||||
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.
|
||||
if self.guard is not None and not self.guard(path):
|
||||
raise HTTPException(status_code=404)
|
||||
try:
|
||||
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)
|
||||
return await super().get_response(path, scope)
|
||||
1
clipwright/core/__init__.py
Normal file
1
clipwright/core/__init__.py
Normal file
|
|
@ -0,0 +1 @@
|
|||
"""Clipwright backend."""
|
||||
24
clipwright/core/paths.py
Normal file
24
clipwright/core/paths.py
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
"""Canonical filesystem locations for the Clipwright backend.
|
||||
|
||||
The importable package lives at ``<repo>/clipwright`` while the shared runtime
|
||||
resources (``fonts/``, ``yolov8n.pt``) stay at the repository root.
|
||||
Keeping the constants here means every module resolves them the same way,
|
||||
independently of the current working directory or of how deep a module sits in
|
||||
the package.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
# .../clipwright (kept private: only used below to locate REPO_ROOT)
|
||||
PACKAGE_DIR = Path(__file__).resolve().parent.parent
|
||||
# Repository root (also the Docker WORKDIR /app).
|
||||
REPO_ROOT = PACKAGE_DIR.parent
|
||||
|
||||
FONTS_DIR = REPO_ROOT / "fonts"
|
||||
|
||||
__all__ = [
|
||||
"REPO_ROOT",
|
||||
"FONTS_DIR",
|
||||
]
|
||||
|
|
@ -14,25 +14,6 @@ import socket
|
|||
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):
|
||||
"""Raised when a URL is not safe to fetch server-side."""
|
||||
|
||||
1
clipwright/integrations/__init__.py
Normal file
1
clipwright/integrations/__init__.py
Normal file
|
|
@ -0,0 +1 @@
|
|||
"""Clipwright backend."""
|
||||
154
clipwright/integrations/youtube_data.py
Normal file
154
clipwright/integrations/youtube_data.py
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
"""Minimal YouTube Data API v3 client -- first comment only (PLAN #6).
|
||||
|
||||
The Shorts "Related video" link and comment pinning are Studio-UI only and are
|
||||
**not** exposed by any API, so this module deliberately does one thing: post a
|
||||
top-level comment on a video via ``commentThreads.insert``. Pinning that comment
|
||||
stays manual.
|
||||
|
||||
Auth is a real-channel OAuth refresh token (service accounts do not work for
|
||||
this scope). Credentials come from the environment and the integration is
|
||||
**opt-in**: with any of them missing, :func:`is_configured` is false and no
|
||||
network call is ever made. Callers must check :func:`is_configured` (or handle
|
||||
:class:`YoutubeDataError`) before asking for a comment.
|
||||
|
||||
Quota: ``commentThreads.insert`` costs 50 units of the default 10,000/day
|
||||
project quota (~200 comments/day). That is the whole reason posting is a
|
||||
deliberate, caller-triggered action and never automatic.
|
||||
|
||||
Blocking, like ``postiz.py``: call through ``asyncio.to_thread`` from async
|
||||
handlers. Every function accepts an optional pre-built ``httpx.Client`` so tests
|
||||
can inject a ``httpx.MockTransport`` and no live OAuth is ever needed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
import httpx
|
||||
|
||||
TOKEN_URI = "https://oauth2.googleapis.com/token"
|
||||
COMMENT_THREADS_URL = "https://www.googleapis.com/youtube/v3/commentThreads"
|
||||
# Required by insert (the comment posting endpoint). Read-only analytics use a
|
||||
# different scope; this module never reads.
|
||||
SCOPE = "https://www.googleapis.com/auth/youtube.force-ssl"
|
||||
|
||||
# Environment variable names, kept as constants so the API layer can name them
|
||||
# in its "not configured" message without duplicating strings.
|
||||
CLIENT_ID_ENV = "YOUTUBE_OAUTH_CLIENT_ID"
|
||||
CLIENT_SECRET_ENV = "YOUTUBE_OAUTH_CLIENT_SECRET"
|
||||
REFRESH_TOKEN_ENV = "YOUTUBE_OAUTH_REFRESH_TOKEN"
|
||||
TOKEN_URI_ENV = "YOUTUBE_OAUTH_TOKEN_URI"
|
||||
|
||||
|
||||
class YoutubeDataError(Exception):
|
||||
"""A missing config or non-2xx response from the YouTube Data API.
|
||||
|
||||
Carries the status and body so the FastAPI layer can translate it into the
|
||||
same status/detail it would have surfaced otherwise.
|
||||
"""
|
||||
|
||||
def __init__(self, status_code: int, detail: str):
|
||||
super().__init__(detail)
|
||||
self.status_code = status_code
|
||||
self.detail = detail
|
||||
|
||||
|
||||
def _env(name: str, default: Optional[str] = None) -> Optional[str]:
|
||||
value = os.environ.get(name)
|
||||
if value is None:
|
||||
return default
|
||||
value = value.strip()
|
||||
return value or default
|
||||
|
||||
|
||||
def credentials() -> Dict[str, Optional[str]]:
|
||||
"""The OAuth credentials read from the environment (values may be None)."""
|
||||
return {
|
||||
"client_id": _env(CLIENT_ID_ENV),
|
||||
"client_secret": _env(CLIENT_SECRET_ENV),
|
||||
"refresh_token": _env(REFRESH_TOKEN_ENV),
|
||||
"token_uri": _env(TOKEN_URI_ENV, TOKEN_URI),
|
||||
}
|
||||
|
||||
|
||||
def is_configured() -> bool:
|
||||
"""True when a refresh-token flow can run. False = no-op, never called."""
|
||||
creds = credentials()
|
||||
return all(creds[key] for key in ("client_id", "client_secret", "refresh_token"))
|
||||
|
||||
|
||||
def _access_token(client: httpx.Client, creds: Dict[str, Optional[str]]) -> str:
|
||||
resp = client.post(str(creds["token_uri"]), data={
|
||||
"client_id": creds["client_id"],
|
||||
"client_secret": creds["client_secret"],
|
||||
"refresh_token": creds["refresh_token"],
|
||||
"grant_type": "refresh_token",
|
||||
})
|
||||
if resp.status_code != 200:
|
||||
raise YoutubeDataError(
|
||||
502,
|
||||
f"YouTube OAuth token refresh failed: {(resp.text or '')[:300]}",
|
||||
)
|
||||
try:
|
||||
token = (resp.json() or {}).get("access_token")
|
||||
except ValueError:
|
||||
token = None
|
||||
if not token:
|
||||
raise YoutubeDataError(502, "YouTube OAuth token refresh returned no access_token")
|
||||
return token
|
||||
|
||||
|
||||
def post_first_comment(video_id: str, text: str, timeout: float = 60.0,
|
||||
client: Optional[httpx.Client] = None) -> Dict[str, Any]:
|
||||
"""Post ``text`` as a top-level comment on ``video_id``.
|
||||
|
||||
Returns the API's ``commentThreads.insert`` response (id + snippet).
|
||||
|
||||
Raises :class:`YoutubeDataError` when unconfigured, given bad input, or when
|
||||
YouTube rejects the insert. ``client`` is the test seam; pass an
|
||||
``httpx.Client`` built with a ``MockTransport`` to exercise this offline.
|
||||
"""
|
||||
if not video_id or not str(video_id).strip():
|
||||
raise YoutubeDataError(400, "video_id is required")
|
||||
if not text or not str(text).strip():
|
||||
raise YoutubeDataError(400, "comment text is required")
|
||||
if not is_configured():
|
||||
raise YoutubeDataError(
|
||||
400,
|
||||
"YouTube Data API is not configured; set "
|
||||
f"{CLIENT_ID_ENV}, {CLIENT_SECRET_ENV} and {REFRESH_TOKEN_ENV}",
|
||||
)
|
||||
|
||||
owns_client = client is None
|
||||
client = client or httpx.Client(timeout=timeout)
|
||||
try:
|
||||
token = _access_token(client, credentials())
|
||||
resp = client.post(
|
||||
COMMENT_THREADS_URL,
|
||||
params={"part": "snippet"},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
json={"snippet": {
|
||||
"videoId": str(video_id).strip(),
|
||||
"topLevelComment": {
|
||||
"snippet": {"textOriginal": str(text)},
|
||||
},
|
||||
}},
|
||||
)
|
||||
finally:
|
||||
if owns_client:
|
||||
client.close()
|
||||
|
||||
if resp.status_code not in (200, 201):
|
||||
# 4xx are the caller's (invalid video / scope); 5xx become 502 so the
|
||||
# API layer does not claim the upstream is down with a gateway code
|
||||
# that came from YouTube, not this server.
|
||||
status = resp.status_code if resp.status_code < 500 else 502
|
||||
raise YoutubeDataError(
|
||||
status,
|
||||
f"YouTube commentThreads.insert failed: {(resp.text or '')[:300]}",
|
||||
)
|
||||
try:
|
||||
return resp.json() or {}
|
||||
except ValueError:
|
||||
return {}
|
||||
1
clipwright/layouts/__init__.py
Normal file
1
clipwright/layouts/__init__.py
Normal file
|
|
@ -0,0 +1 @@
|
|||
"""Clipwright backend."""
|
||||
|
|
@ -220,7 +220,7 @@ def speaker_xs(held, centres, crop_w, orig_w, n_frames, fps,
|
|||
|
||||
def verdicts_for_scene(video_path, start_f, end_f, fps, centres):
|
||||
"""Per-window speaker verdicts for one scene, from its two face centres."""
|
||||
import split_layout
|
||||
from clipwright.layouts import split_layout
|
||||
|
||||
start_s = start_f / fps
|
||||
duration_s = (end_f - start_f) / fps
|
||||
|
|
@ -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 += small_h % 2
|
||||
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]
|
||||
|
||||
|
|
@ -20,7 +20,7 @@ them with margin.
|
|||
"""
|
||||
import os
|
||||
|
||||
from ffmpeg_utils import blurred_backdrop
|
||||
from clipwright.media.ffmpeg_utils import blurred_backdrop
|
||||
|
||||
CORNER_MARGIN = 0.20 # a subject this far from an edge (as a fraction of the
|
||||
# frame) still counts as anchored to it
|
||||
|
|
@ -159,8 +159,8 @@ def detect(video_path, samples=10):
|
|||
"""
|
||||
import cv2
|
||||
import numpy as np
|
||||
import main as m
|
||||
import screencast_layout
|
||||
from clipwright.pipeline import main as m
|
||||
from clipwright.layouts import screencast_layout
|
||||
|
||||
cap = cv2.VideoCapture(video_path)
|
||||
if not cap.isOpened():
|
||||
909
clipwright/layouts/code_layout.py
Normal file
909
clipwright/layouts/code_layout.py
Normal file
|
|
@ -0,0 +1,909 @@
|
|||
"""CODE/TERMINAL vertical layout: an IDE or terminal recording in 9:16.
|
||||
|
||||
The case every screen layout here handles badly: a maximized 1440p editor or a
|
||||
terminal window. The existing SCREENCAST layout treats it as "content over a
|
||||
presenter", which on a code recording means the output is the whole 1440p frame
|
||||
shrunk to a 608px strip — 24px of glyph height at best, unreadable on a phone.
|
||||
|
||||
What a code recording actually needs is the opposite trade. The viewer has to
|
||||
read characters, so the *pane* is cropped to one column of code and scaled up to
|
||||
fill the width, with the source's blur as decorative filler above and below, and
|
||||
the bottom ~15% left clear for captions. When the pane is taller than the output
|
||||
band, a crop window has to follow the active line (a `sendcmd` pan) so the line
|
||||
being typed stays on screen.
|
||||
|
||||
Design, following the ``camera_inset`` pattern:
|
||||
|
||||
- module ``ENABLED`` read from ``CODE_LAYOUT`` (off by default);
|
||||
- ``detect_code_pane`` -> geometry (a self-contained edge/row-column detector,
|
||||
like ``split_layout.detect_split_scenes``: no ``content_ranges`` dead wire);
|
||||
- pure geometry helpers (``pane_from_projections``, ``stable_pane``,
|
||||
``fit_window``, ``follow_sendcmd_lines``) so the decisions are unit-testable
|
||||
without OpenCV;
|
||||
- ``code_filtergraph`` -> crop -> scale -> overlay on a blurred backdrop.
|
||||
|
||||
Everything tunable is an env-overridable constant. The thresholds were set from
|
||||
first principles and *must* be calibrated against a real 1440p corpus with
|
||||
``clipwright/tools/verify_code_layout.py`` before the layout is enabled by
|
||||
default.
|
||||
|
||||
Import-time cost is ``numpy`` only; ``cv2`` is imported lazily inside the frame
|
||||
functions so the unit suite (which has no OpenCV) still collects this module.
|
||||
"""
|
||||
import os
|
||||
|
||||
import numpy as np
|
||||
|
||||
from clipwright.media.ffmpeg_utils import blurred_backdrop
|
||||
|
||||
# Off by default: a wrong CODE crop shows a wall of clipped glyphs, which is a
|
||||
# worse failure than leaving a code clip on the TRACK/WIDE default.
|
||||
ENABLED = os.environ.get("CODE_LAYOUT", "0") == "1"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Env-overridable tuning. See clipwright/tools/verify_code_layout.py for the
|
||||
# corpus pass that produces real numbers for these; the defaults are estimates.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# Pan the crop window to keep the active line visible on a tall pane.
|
||||
FOLLOW_ENABLED = os.environ.get("CODE_FOLLOW", "1") == "1"
|
||||
|
||||
# Extra zoom on top of "fit the pane width to the output width". 1.0 keeps the
|
||||
# whole pane width; >1 crops a narrower column and scales it up (bigger glyphs).
|
||||
ZOOM = float(os.environ.get("CODE_ZOOM", "1.0"))
|
||||
|
||||
# Minimum horizontal scale (out_w / pane_w). Below this the pane is being
|
||||
# downscaled so far that the text stops being readable, and the caller should
|
||||
# fall back to SCREENCAST/WIDE. At 1440p maximized, out_w/pane_w == 1080/1440 ==
|
||||
# 0.75 exactly, so a maximized editor sits on the boundary and a maximized
|
||||
# ultrawide falls through.
|
||||
MIN_SCALE = float(os.environ.get("CODE_MIN_SCALE", "0.75"))
|
||||
|
||||
# Face/camera band height, as a fraction of out_h, when a cam_box is supplied.
|
||||
CAMERA_BAND_RATIO = float(os.environ.get("CODE_CAMERA_BAND", "0.18"))
|
||||
|
||||
# Bottom band reserved for captions, as a fraction of out_h.
|
||||
CAPTION_BAND_RATIO = float(os.environ.get("CODE_CAPTION_BAND", "0.15"))
|
||||
|
||||
# Pane gates, as a fraction of the frame. A corner panel is not a code pane.
|
||||
PANE_MIN_WIDTH_FRAC = float(os.environ.get("CODE_PANE_MIN_WIDTH", "0.35"))
|
||||
PANE_MIN_HEIGHT_FRAC = float(os.environ.get("CODE_PANE_MIN_HEIGHT", "0.25"))
|
||||
|
||||
# Edge-density floor inside the pane (fraction of pixels above the Sobel
|
||||
# threshold). Flat wallpapers and photos fall below it.
|
||||
EDGE_DENSITY_FLOOR = float(os.environ.get("CODE_EDGE_DENSITY", "0.02"))
|
||||
|
||||
# Temporal stability: the pane centre must stay within this fraction of the
|
||||
# frame across samples, for at least this fraction of them.
|
||||
STABILITY_TOLERANCE = float(os.environ.get("CODE_STABILITY_TOLERANCE", "0.04"))
|
||||
STABILITY_MIN_FRAC = float(os.environ.get("CODE_STABILITY_FRAC", "0.6"))
|
||||
|
||||
# Detection runs on a copy at most this wide. Sobel/close is O(pixels) and the
|
||||
# pane geometry does not need full resolution.
|
||||
DETECT_MAX_WIDTH = int(os.environ.get("CODE_DETECT_WIDTH", "960"))
|
||||
|
||||
# Wide-short morphological close: joins glyphs into horizontal line runs
|
||||
# without merging adjacent text lines (which a square kernel does).
|
||||
CLOSE_KERNEL = (35, 3)
|
||||
|
||||
# Fraction of the projection max that counts as pane edge mass.
|
||||
PROJ_THRESHOLD_RATIO = float(os.environ.get("CODE_PROJ_THRESHOLD", "0.15"))
|
||||
|
||||
# Below this scaled Sobel magnitude a frame contributes no edge map.
|
||||
SOBEL_FLOOR = float(os.environ.get("CODE_SOBEL_FLOOR", "8.0"))
|
||||
SOBEL_RATIO = 0.15
|
||||
|
||||
# Active-line tracking.
|
||||
ACTIVE_MAX_WIDTH = int(os.environ.get("CODE_ACTIVE_WIDTH", "480"))
|
||||
ACTIVE_BAND_FRAC = 0.20
|
||||
ACTIVE_MIN_CONCENTRATION = float(
|
||||
os.environ.get("CODE_ACTIVE_CONCENTRATION", "0.35"))
|
||||
ACTIVE_MIN_MASS = float(os.environ.get("CODE_ACTIVE_MASS", "1500"))
|
||||
|
||||
# Editor classification: syntax highlighting raises chroma variance above a
|
||||
# plain terminal's.
|
||||
EDITOR_SAT_STD = float(os.environ.get("CODE_EDITOR_SAT_STD", "28"))
|
||||
GUTTER_FRACTION = 0.12
|
||||
|
||||
# IDE chrome masking. A maximized editor's window is the whole 2560px of a 1440p
|
||||
# source, so a whole-window pane scales at 1080/2560 ~= 0.42 and trips
|
||||
# MIN_SCALE. What we want is the TEXT COLUMN: the activity bar and sidebar sit
|
||||
# in the left margin and the minimap in the right, each separated from the code
|
||||
# by a sustained blank border. The detector searches within these margins for
|
||||
# that blank run and cuts there; with no chrome (a bare terminal) there is no
|
||||
# run and the full width is kept. Widths vary by theme and zoom — tune
|
||||
# CODE_CHROME_* and CODE_TEXT_* from tools/verify_code_layout.py.
|
||||
CHROME_LEFT_FRAC = float(os.environ.get("CODE_CHROME_LEFT", "0.22"))
|
||||
CHROME_RIGHT_FRAC = float(os.environ.get("CODE_CHROME_RIGHT", "0.10"))
|
||||
CHROME_BOTTOM_FRAC = float(os.environ.get("CODE_CHROME_BOTTOM", "0.03"))
|
||||
# A "gap" is a sustained run of columns below this share of the text max.
|
||||
GAP_FRAC = float(os.environ.get("CODE_GAP_FRAC", "0.08"))
|
||||
GAP_PX = int(os.environ.get("CODE_GAP_PX", "4"))
|
||||
TEXT_CORE_FRAC = float(os.environ.get("CODE_TEXT_CORE", "0.35"))
|
||||
TEXT_MIN_WIDTH_FRAC = float(os.environ.get("CODE_TEXT_MIN_WIDTH", "0.2"))
|
||||
|
||||
# Per-scene verification: share of frames sampled inside the pane that must
|
||||
# still read as code for the scene to keep CODE (otherwise its other verdict
|
||||
# stands). A cutaway to the facecam fails the texture/palette checks.
|
||||
SCENE_CODE_FRAC = float(os.environ.get("CODE_SCENE_FRAC", "0.5"))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pure geometry (no cv2): projections -> pane, stability, band layout, sendcmd.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _extent(projection, threshold):
|
||||
"""First/last index above ``threshold`` (end exclusive), or None."""
|
||||
idx = np.flatnonzero(np.asarray(projection, dtype=float) > threshold)
|
||||
if idx.size == 0:
|
||||
return None
|
||||
return int(idx[0]), int(idx[-1]) + 1
|
||||
|
||||
|
||||
def pane_from_projections(row_proj, col_proj, frame_w, frame_h,
|
||||
min_width_frac=PANE_MIN_WIDTH_FRAC,
|
||||
min_height_frac=PANE_MIN_HEIGHT_FRAC,
|
||||
threshold_ratio=PROJ_THRESHOLD_RATIO):
|
||||
"""Locate the code pane from 1-D row/column edge projections.
|
||||
|
||||
``row_proj`` is per-row edge mass (length = pane-space height) and
|
||||
``col_proj`` per-column. The pane is the bounding extent of edge mass above
|
||||
a fraction of each projection's own max: text lines are many separated rows
|
||||
of mass, so a "longest contiguous run" would lock onto a single line. The
|
||||
extent is in the same coordinate space as ``frame_w``/``frame_h`` (detection
|
||||
passes the downscaled size; the fractions are scale-invariant).
|
||||
|
||||
Returns ``(x, y, w, h)`` or None when the box is missing or fails either
|
||||
size gate.
|
||||
"""
|
||||
rows = np.asarray(row_proj, dtype=float)
|
||||
cols = np.asarray(col_proj, dtype=float)
|
||||
if rows.size == 0 or cols.size == 0:
|
||||
return None
|
||||
if rows.max() <= 0 or cols.max() <= 0:
|
||||
return None
|
||||
ry = _extent(rows, threshold_ratio * rows.max())
|
||||
cx = _extent(cols, threshold_ratio * cols.max())
|
||||
if ry is None or cx is None:
|
||||
return None
|
||||
y0, y1 = ry
|
||||
x0, x1 = cx
|
||||
w, h = x1 - x0, y1 - y0
|
||||
if w < min_width_frac * frame_w or h < min_height_frac * frame_h:
|
||||
return None
|
||||
return (x0, y0, w, h)
|
||||
|
||||
|
||||
def _smooth(values, window=9):
|
||||
v = np.asarray(values, dtype=float)
|
||||
if window <= 1 or v.size < window:
|
||||
return v
|
||||
kernel = np.ones(window, dtype=float) / window
|
||||
return np.convolve(v, kernel, mode="same")
|
||||
|
||||
|
||||
def _gaps(below, gap_px):
|
||||
"""(start, end) of every sustained True run in a boolean array."""
|
||||
out = []
|
||||
start = None
|
||||
for i, flag in enumerate(below):
|
||||
if flag and start is None:
|
||||
start = i
|
||||
elif not flag and start is not None:
|
||||
if i - start >= gap_px:
|
||||
out.append((start, i))
|
||||
start = None
|
||||
if start is not None and len(below) - start >= gap_px:
|
||||
out.append((start, len(below)))
|
||||
return out
|
||||
|
||||
|
||||
def text_column_extent(col_proj, frame_w, left_skip_frac=CHROME_LEFT_FRAC,
|
||||
right_skip_frac=CHROME_RIGHT_FRAC,
|
||||
core_frac=TEXT_CORE_FRAC,
|
||||
min_width_frac=TEXT_MIN_WIDTH_FRAC,
|
||||
gap_frac=GAP_FRAC, gap_px=GAP_PX, smooth=9):
|
||||
"""(x0, x1) of the editor text column, with IDE chrome cut off.
|
||||
|
||||
``col_proj`` is per-column edge mass. The whole extent of edge mass is
|
||||
first-to-last above ``core_frac`` of the max (text fills nearly every
|
||||
column across many lines, so a longest-run would lock onto one block). The
|
||||
left and right margins are then searched for a sustained blank border — the
|
||||
gap between the sidebar and the code, and between the code and the
|
||||
minimap — and the extent is cut at the innermost one. A bare terminal has
|
||||
no such border and keeps its full width. Returns None when no run clears
|
||||
``min_width_frac``.
|
||||
"""
|
||||
cols = _smooth(col_proj, smooth)
|
||||
if cols.size == 0:
|
||||
return None
|
||||
top = float(cols.max())
|
||||
if top <= 0:
|
||||
return None
|
||||
core = cols > core_frac * top
|
||||
if not core.any():
|
||||
return None
|
||||
first = int(np.argmax(core))
|
||||
last = int(len(core) - np.argmax(core[::-1]))
|
||||
|
||||
thr = gap_frac * top
|
||||
x0 = first
|
||||
window = cols[first:first + int(round(left_skip_frac * frame_w))]
|
||||
gaps = _gaps(window < thr, max(2, gap_px))
|
||||
if gaps:
|
||||
x0 = first + gaps[-1][1]
|
||||
|
||||
x1 = last
|
||||
rstart = max(x0, last - int(round(right_skip_frac * frame_w)))
|
||||
window = cols[rstart:last]
|
||||
gaps = _gaps(window < thr, max(2, gap_px))
|
||||
if gaps:
|
||||
x1 = rstart + gaps[-1][0]
|
||||
|
||||
if x1 - x0 < min_width_frac * frame_w:
|
||||
return None
|
||||
return x0, x1
|
||||
|
||||
|
||||
def clamp_pane_width(pane, max_width, anchor="left"):
|
||||
"""Narrow a pane to at most ``max_width`` columns.
|
||||
|
||||
Used when the text column is still wider than the readable scale allows
|
||||
(1080 / MIN_SCALE ~= 1440 on a 1440p source): code is left-aligned, so
|
||||
keeping the left edge keeps indentation and line starts. Returns an even
|
||||
``(x, y, w, h)`` tuple.
|
||||
"""
|
||||
x, y, w, h = _pane_box(pane)
|
||||
max_width = int(max_width) - (int(max_width) % 2)
|
||||
if max_width < 2:
|
||||
max_width = 2
|
||||
if w <= max_width:
|
||||
return (x, y, w, h)
|
||||
nx = x + (w - max_width) // 2 if anchor == "center" else x
|
||||
nx = max(0, nx - (nx % 2))
|
||||
return (nx, y, max_width, h)
|
||||
|
||||
|
||||
def _stable_members(boxes, frame_w, frame_h, tolerance):
|
||||
arr = np.asarray(boxes, dtype=float)
|
||||
cx = arr[:, 0] + arr[:, 2] / 2.0
|
||||
cy = arr[:, 1] + arr[:, 3] / 2.0
|
||||
mid_x, mid_y = float(np.median(cx)), float(np.median(cy))
|
||||
close = ((np.abs(cx - mid_x) <= tolerance * frame_w)
|
||||
& (np.abs(cy - mid_y) <= tolerance * frame_h))
|
||||
return arr, close
|
||||
|
||||
|
||||
def stable_pane(boxes, frame_w, frame_h, tolerance=STABILITY_TOLERANCE,
|
||||
min_frac=STABILITY_MIN_FRAC):
|
||||
"""Median box over the samples that agree, or None.
|
||||
|
||||
A pane that jumps around the screen is a moving camera or a slideshow, not a
|
||||
fixed editor window; clustering around the median tolerates one stray sample
|
||||
without tolerating real movement.
|
||||
"""
|
||||
if not boxes:
|
||||
return None
|
||||
arr, close = _stable_members(boxes, frame_w, frame_h, tolerance)
|
||||
if int(close.sum()) < max(2, int(round(min_frac * len(boxes)))):
|
||||
return None
|
||||
return tuple(int(round(v)) for v in np.median(arr[close], axis=0))
|
||||
|
||||
|
||||
def stability_fraction(boxes, frame_w, frame_h, tolerance=STABILITY_TOLERANCE):
|
||||
"""Fraction of samples whose centre agrees with the median."""
|
||||
if not boxes:
|
||||
return 0.0
|
||||
_, close = _stable_members(boxes, frame_w, frame_h, tolerance)
|
||||
return float(close.mean()) if close.size else 0.0
|
||||
|
||||
|
||||
def edge_density(mask, box):
|
||||
"""Fraction of set pixels inside ``box`` (mask may be 0/1 or 0/255)."""
|
||||
x, y, w, h = (int(v) for v in box[:4])
|
||||
m = np.asarray(mask)
|
||||
sub = m[max(0, y):y + h, max(0, x):x + w]
|
||||
if sub.size == 0:
|
||||
return 0.0
|
||||
scale = 255.0 if sub.max() > 1 else 1.0
|
||||
return float(sub.mean()) / scale
|
||||
|
||||
|
||||
def code_bands(out_h, caption_ratio=None):
|
||||
"""(content_h, caption_h): even, positive, and summing to ``out_h``."""
|
||||
ratio = CAPTION_BAND_RATIO if caption_ratio is None else caption_ratio
|
||||
caption_h = int(round(out_h * ratio))
|
||||
caption_h -= caption_h % 2
|
||||
caption_h = max(2, min(caption_h, out_h - 2))
|
||||
content_h = out_h - caption_h
|
||||
return content_h, caption_h
|
||||
|
||||
|
||||
def fit_window(pane_h, scale, band_h):
|
||||
"""(crop_h, scaled_h, needs_follow) for a pane of ``pane_h`` at ``scale``.
|
||||
|
||||
``crop_h`` is the source window height, ``scaled_h`` its height after
|
||||
scaling, both even and clamped so ``scaled_h <= band_h``. ``needs_follow``
|
||||
is True when the pane is taller than the band and only a window can fit.
|
||||
"""
|
||||
pane_h = max(2, int(pane_h))
|
||||
if scale <= 0:
|
||||
return None
|
||||
full_scaled = pane_h * scale
|
||||
if full_scaled <= band_h:
|
||||
scaled_h = int(round(full_scaled))
|
||||
scaled_h += scaled_h % 2
|
||||
scaled_h = max(2, min(scaled_h, band_h))
|
||||
crop_h = pane_h - (pane_h % 2)
|
||||
return max(2, crop_h), scaled_h, False
|
||||
crop_h = int(round(band_h / scale))
|
||||
crop_h += crop_h % 2
|
||||
crop_h = max(2, min(crop_h, pane_h - (pane_h % 2)))
|
||||
scaled_h = band_h - (band_h % 2)
|
||||
return crop_h, max(2, scaled_h), True
|
||||
|
||||
|
||||
def follow_sendcmd_lines(follow, pane_y, window_h, pane_h, start=0.0,
|
||||
target="crop@c"):
|
||||
"""sendcmd lines panning a crop window to the active line.
|
||||
|
||||
``follow`` is ``[(timestamp, source_y), ...]`` where ``timestamp`` is in the
|
||||
source's clock; ``start`` is the segment start, subtracted so the emitted
|
||||
timestamps are relative to the segment (the render seeks per scene). Only
|
||||
change-points are emitted: ``y`` is clamped to the pane and deduped.
|
||||
"""
|
||||
lines = []
|
||||
prev = None
|
||||
lo = int(pane_y)
|
||||
hi = max(lo, int(pane_y + pane_h - window_h))
|
||||
for t, y in follow:
|
||||
rel = float(t) - float(start)
|
||||
if rel < 0:
|
||||
continue
|
||||
top = int(round(float(y) - window_h / 2.0))
|
||||
top = max(lo, min(top, hi))
|
||||
top -= top % 2
|
||||
if top == prev:
|
||||
continue
|
||||
lines.append(f"{rel:.4f} {target} y {top};")
|
||||
prev = top
|
||||
return lines
|
||||
|
||||
|
||||
def _pane_box(pane):
|
||||
if isinstance(pane, dict):
|
||||
return (int(pane["x"]), int(pane["y"]), int(pane["w"]), int(pane["h"]))
|
||||
return tuple(int(v) for v in pane[:4])
|
||||
|
||||
|
||||
def code_filtergraph(pane, out_w, out_h, follow=None, cam_box=None,
|
||||
min_scale=MIN_SCALE, caption_ratio=None, zoom=None):
|
||||
"""Crop the code pane, scale it to ``out_w``, overlay on a blurred backdrop.
|
||||
|
||||
``pane`` is an ``(x, y, w, h)`` tuple or a ``detect_code_pane`` dict in
|
||||
SOURCE coordinates. ``follow`` is a segment-relative
|
||||
``[(t, source_y), ...]`` series from ``active_line_series``; it produces a
|
||||
``sendcmd`` pan when the pane is taller than the content band. ``cam_box``
|
||||
optionally overlays a face in the caption band.
|
||||
|
||||
Returns the filtergraph string ending in ``[v]``, or None when
|
||||
``out_w / pane_w < min_scale`` so the caller can fall back to
|
||||
SCREENCAST/WIDE.
|
||||
"""
|
||||
x, y, w, h = _pane_box(pane)
|
||||
x = max(0, x - (x % 2))
|
||||
y = max(0, y - (y % 2))
|
||||
w = max(2, w - (w % 2))
|
||||
h = max(2, h - (h % 2))
|
||||
|
||||
fit = out_w / float(w)
|
||||
if fit < min_scale:
|
||||
return None
|
||||
|
||||
z = ZOOM if zoom is None else zoom
|
||||
scale = fit * max(0.1, float(z))
|
||||
if scale <= 0:
|
||||
return None
|
||||
|
||||
content_h, caption_h = code_bands(out_h, caption_ratio)
|
||||
|
||||
# Horizontal crop window: at zoom 1 this is the whole pane width.
|
||||
crop_w = int(round(out_w / scale))
|
||||
crop_w += crop_w % 2
|
||||
crop_w = max(2, min(crop_w, w))
|
||||
crop_x = x + (w - crop_w) // 2
|
||||
crop_x = max(0, crop_x - (crop_x % 2))
|
||||
|
||||
fitted = fit_window(h, scale, content_h)
|
||||
if fitted is None:
|
||||
return None
|
||||
crop_h, scaled_h, needs_follow = fitted
|
||||
y_off = max(0, (content_h - scaled_h) // 2)
|
||||
|
||||
window_top = None
|
||||
if needs_follow:
|
||||
window_top = y + (h - crop_h) // 2
|
||||
if follow:
|
||||
window_top = int(round(float(follow[0][1]) - crop_h / 2.0))
|
||||
window_top = max(y, min(window_top, y + h - crop_h))
|
||||
window_top -= window_top % 2
|
||||
|
||||
if needs_follow and follow:
|
||||
lines = follow_sendcmd_lines(follow, y, crop_h, h, start=0.0)
|
||||
else:
|
||||
lines = []
|
||||
|
||||
if lines:
|
||||
# Each line is already ';'-terminated; concatenating avoids the empty
|
||||
# command a second separator would produce.
|
||||
commands = "".join(lines)
|
||||
fg = (f"sendcmd=c='{commands}',"
|
||||
f"crop@c=w={crop_w}:h={crop_h}:x={crop_x}:y={window_top},"
|
||||
f"scale={out_w}:{scaled_h}[code]")
|
||||
else:
|
||||
static_y = (window_top if window_top is not None
|
||||
else y + (h - crop_h) // 2)
|
||||
static_y = max(y, min(static_y, y + h - crop_h))
|
||||
static_y -= static_y % 2
|
||||
fg = (f"crop=w={crop_w}:h={crop_h}:x={crop_x}:y={static_y},"
|
||||
f"scale={out_w}:{scaled_h}[code]")
|
||||
|
||||
parts = []
|
||||
if cam_box is not None:
|
||||
cx, cy, cw, ch = _pane_box(cam_box)
|
||||
cx = max(0, cx - (cx % 2))
|
||||
cy = max(0, cy - (cy % 2))
|
||||
cw = max(2, cw - (cw % 2))
|
||||
ch = max(2, ch - (ch % 2))
|
||||
cam_h = int(round(out_h * CAMERA_BAND_RATIO))
|
||||
cam_h -= cam_h % 2
|
||||
cam_h = max(2, min(cam_h, caption_h))
|
||||
parts.append("[0:v]split=3[bga][fga][cama];")
|
||||
parts.append(f"[bga]{blurred_backdrop(out_w, out_h, 12)}[bg];")
|
||||
parts.append(f"[fga]{fg};")
|
||||
parts.append(f"[cama]crop=w={cw}:h={ch}:x={cx}:y={cy},"
|
||||
f"scale={out_w}:{cam_h}[cam];")
|
||||
parts.append(f"[bg][code]overlay=x=0:y={y_off}[withcode];")
|
||||
parts.append(f"[withcode][cam]overlay=x=0:y={out_h - caption_h},"
|
||||
f"setsar=1[v]")
|
||||
else:
|
||||
parts.append("[0:v]split=2[bga][fga];")
|
||||
parts.append(f"[bga]{blurred_backdrop(out_w, out_h, 12)}[bg];")
|
||||
parts.append(f"[fga]{fg};")
|
||||
parts.append(f"[bg][code]overlay=x=0:y={y_off},setsar=1[v]")
|
||||
return "".join(parts)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# OpenCV detection (lazy import).
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _downscale(frame, max_width):
|
||||
import cv2
|
||||
h, w = frame.shape[:2]
|
||||
if w <= max_width:
|
||||
return frame
|
||||
factor = max_width / float(w)
|
||||
return cv2.resize(frame, (max_width, max(2, int(round(h * factor)))),
|
||||
interpolation=cv2.INTER_AREA)
|
||||
|
||||
|
||||
def _edge_maps(frame, max_width=DETECT_MAX_WIDTH):
|
||||
"""Sobel edge mask + wide-short close + row/column projections.
|
||||
|
||||
Returns a dict with the mask, closed mask, projections and the working
|
||||
dimensions, or None when the frame has no gradient (black/frozen).
|
||||
"""
|
||||
import cv2
|
||||
small = _downscale(frame, max_width)
|
||||
gray = cv2.cvtColor(small, cv2.COLOR_BGR2GRAY)
|
||||
gx = cv2.Sobel(gray, cv2.CV_32F, 1, 0, ksize=3)
|
||||
gy = cv2.Sobel(gray, cv2.CV_32F, 0, 1, ksize=3)
|
||||
mag = cv2.magnitude(gx, gy)
|
||||
top = float(mag.max())
|
||||
if top <= 1e-6:
|
||||
return None
|
||||
threshold = max(SOBEL_FLOOR, SOBEL_RATIO * top)
|
||||
mask = (mag > threshold).astype(np.uint8) * 255
|
||||
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, CLOSE_KERNEL)
|
||||
closed = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
|
||||
return {
|
||||
"mask": mask,
|
||||
"closed": closed,
|
||||
"row_proj": closed.sum(axis=1).astype(np.float64),
|
||||
"col_proj": closed.sum(axis=0).astype(np.float64),
|
||||
# The close joins glyphs into line runs, which is what the row
|
||||
# projection needs — but it also bridges the blank IDE chrome borders,
|
||||
# so the column projection for TEXT-COLUMN masking comes from the RAW
|
||||
# mask, where the border survives.
|
||||
"col_proj_raw": mask.sum(axis=0).astype(np.float64),
|
||||
"w": small.shape[1],
|
||||
"h": small.shape[0],
|
||||
}
|
||||
|
||||
|
||||
def _classify_pane(frame, box):
|
||||
"""Editor vs terminal. Defaults to editor when the signal is weak.
|
||||
|
||||
An editor shows a left gutter of stable digit rows (line numbers) and
|
||||
syntax highlighting raises the crop's saturation variance. A terminal has
|
||||
neither: text starts at the left margin and is mostly one foreground colour.
|
||||
"""
|
||||
import cv2
|
||||
x, y, w, h = (int(v) for v in box)
|
||||
crop = frame[max(0, y):y + h, max(0, x):x + w]
|
||||
if crop.size == 0:
|
||||
return "editor"
|
||||
hsv = cv2.cvtColor(crop, cv2.COLOR_BGR2HSV)
|
||||
sat_std = float(hsv[:, :, 1].std())
|
||||
|
||||
gutter_w = max(4, int(w * GUTTER_FRACTION))
|
||||
gutter = crop[:, :gutter_w]
|
||||
gg = cv2.cvtColor(gutter, cv2.COLOR_BGR2GRAY)
|
||||
gx = np.abs(cv2.Sobel(gg, cv2.CV_32F, 1, 0, ksize=3))
|
||||
per_col = gx.sum(axis=0)
|
||||
total = float(per_col.sum()) + 1e-6
|
||||
gutter_peak = float(per_col.max() / total) if per_col.size else 0.0
|
||||
|
||||
if sat_std >= EDITOR_SAT_STD and gutter_peak > 0.08:
|
||||
return "editor"
|
||||
if sat_std < EDITOR_SAT_STD and gutter_peak <= 0.08:
|
||||
return "terminal"
|
||||
return "editor"
|
||||
|
||||
|
||||
def detect_code_pane(video_path, samples=12):
|
||||
"""Median code pane across sampled frames, or None.
|
||||
|
||||
Pipeline per sample: downscale to <= DETECT_MAX_WIDTH, Sobel magnitude mask,
|
||||
wide-short morphological close (joins glyphs into line runs), row/column
|
||||
projection -> bounding pane. Gates: pane width/height fractions, in-pane
|
||||
edge-density floor, and temporal stability of the pane centre.
|
||||
|
||||
Returns ``{"x", "y", "w", "h", "mode", "confidence", "frame_w",
|
||||
"frame_h"}`` in source coordinates, or None meaning "use another layout".
|
||||
"""
|
||||
if not ENABLED:
|
||||
return None
|
||||
try:
|
||||
import cv2
|
||||
except ImportError:
|
||||
return None
|
||||
|
||||
cap = cv2.VideoCapture(video_path)
|
||||
if not cap.isOpened():
|
||||
return None
|
||||
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
||||
frame_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
||||
frame_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
||||
if total <= 0 or frame_w <= 0 or frame_h <= 0:
|
||||
cap.release()
|
||||
return None
|
||||
|
||||
n = max(2, int(samples))
|
||||
boxes = []
|
||||
densities = []
|
||||
votes = {"editor": 0, "terminal": 0}
|
||||
try:
|
||||
for i in range(n):
|
||||
cap.set(cv2.CAP_PROP_POS_FRAMES, int(i * total / n))
|
||||
ok, frame = cap.read()
|
||||
if not ok:
|
||||
continue
|
||||
maps = _edge_maps(frame)
|
||||
if maps is None:
|
||||
continue
|
||||
det_box = pane_from_projections(
|
||||
maps["row_proj"], maps["col_proj"], maps["w"], maps["h"])
|
||||
if det_box is None:
|
||||
continue
|
||||
# The plain projection returns the whole window; cut it down to the
|
||||
# text column so a maximized 1440p editor does not scale at 0.42.
|
||||
# Raw projection: the morphological close would bridge the chrome
|
||||
# borders this is looking for.
|
||||
text_cols = text_column_extent(maps["col_proj_raw"], maps["w"])
|
||||
if text_cols is not None:
|
||||
x0, x1 = text_cols
|
||||
else:
|
||||
x0, x1 = det_box[0], det_box[0] + det_box[2]
|
||||
y0 = det_box[1]
|
||||
y1 = det_box[1] + det_box[3]
|
||||
# Shave the status bar / window border off the bottom.
|
||||
y1 -= int(round(CHROME_BOTTOM_FRAC * (y1 - y0)))
|
||||
w, h = x1 - x0, y1 - y0
|
||||
if (w < PANE_MIN_WIDTH_FRAC * maps["w"]
|
||||
or h < PANE_MIN_HEIGHT_FRAC * maps["h"]):
|
||||
continue
|
||||
det_box = (x0, y0, w, h)
|
||||
density = edge_density(maps["closed"], det_box)
|
||||
if density < EDGE_DENSITY_FLOOR:
|
||||
continue
|
||||
sx = frame_w / float(maps["w"])
|
||||
sy = frame_h / float(maps["h"])
|
||||
box = (int(round(det_box[0] * sx)), int(round(det_box[1] * sy)),
|
||||
int(round(det_box[2] * sx)), int(round(det_box[3] * sy)))
|
||||
boxes.append(box)
|
||||
densities.append(density)
|
||||
votes[_classify_pane(frame, box)] += 1
|
||||
finally:
|
||||
cap.release()
|
||||
|
||||
if len(boxes) < 2:
|
||||
return None
|
||||
stable = stable_pane(boxes, frame_w, frame_h)
|
||||
if stable is None:
|
||||
return None
|
||||
x, y, w, h = stable
|
||||
if w < PANE_MIN_WIDTH_FRAC * frame_w or h < PANE_MIN_HEIGHT_FRAC * frame_h:
|
||||
return None
|
||||
|
||||
mode = "editor" if votes["editor"] >= votes["terminal"] else "terminal"
|
||||
stable_frac = stability_fraction(boxes, frame_w, frame_h)
|
||||
density = float(np.mean(densities)) if densities else 0.0
|
||||
confidence = max(0.0, min(1.0, 0.6 * stable_frac
|
||||
+ 0.4 * min(1.0, density / (4 * EDGE_DENSITY_FLOOR))))
|
||||
return {"x": x, "y": y, "w": w, "h": h, "mode": mode,
|
||||
"confidence": confidence, "frame_w": frame_w, "frame_h": frame_h}
|
||||
|
||||
|
||||
def _active_point(row_mass, total, band_frac=ACTIVE_BAND_FRAC,
|
||||
min_concentration=ACTIVE_MIN_CONCENTRATION):
|
||||
"""(normalised centroid, concentration, mass) of the top-mass row band.
|
||||
|
||||
The centroid is the mass-weighted centre of the busiest ``band_frac`` of
|
||||
rows, normalised to 0..1 over the region. ``concentration`` is that band's
|
||||
share of all changed pixels: a caret or highlighted line is concentrated, a
|
||||
whole-screen redraw is not.
|
||||
"""
|
||||
n = len(row_mass)
|
||||
if n == 0 or total <= 0:
|
||||
return None
|
||||
k = max(1, int(round(n * band_frac)))
|
||||
order = np.argsort(row_mass)[-k:]
|
||||
band_mass = float(row_mass[order].sum())
|
||||
if band_mass <= 0:
|
||||
return None
|
||||
concentration = band_mass / float(total)
|
||||
if concentration < min_concentration:
|
||||
return None
|
||||
idx = order.astype(float)
|
||||
cy = float((idx * row_mass[order]).sum() / band_mass)
|
||||
return (cy / (n - 1) if n > 1 else 0.0), concentration, band_mass
|
||||
|
||||
|
||||
def _median_smooth(values, window=3):
|
||||
values = np.asarray(values, dtype=float)
|
||||
if window <= 1 or len(values) < window:
|
||||
return values
|
||||
half = window // 2
|
||||
out = values.copy()
|
||||
for i in range(len(values)):
|
||||
lo = max(0, i - half)
|
||||
hi = min(len(values), i + half + 1)
|
||||
out[i] = np.median(values[lo:hi])
|
||||
return out
|
||||
|
||||
|
||||
def active_line_series(video_path, pane, start, end, sample_fps=2.0):
|
||||
"""Track the active line (caret/current-line highlight) over a range.
|
||||
|
||||
Low-res decode at ``sample_fps``; ``absdiff`` between consecutive samples
|
||||
masked to the pane; per-row changed mass; the top-mass band's centroid is
|
||||
kept only when it concentrates >= ``ACTIVE_MIN_CONCENTRATION`` of the change
|
||||
and the band mass clears the floor. The y series is median-smoothed.
|
||||
|
||||
Returns ``[(timestamp, source_y), ...]`` in the source's absolute clock (the
|
||||
caller subtracts the segment start when building sendcmd lines), or None
|
||||
when fewer than three reliable points are found.
|
||||
"""
|
||||
if not ENABLED or not FOLLOW_ENABLED:
|
||||
return None
|
||||
try:
|
||||
import cv2
|
||||
except ImportError:
|
||||
return None
|
||||
if end <= start:
|
||||
return None
|
||||
|
||||
cap = cv2.VideoCapture(video_path)
|
||||
if not cap.isOpened():
|
||||
return None
|
||||
frame_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
||||
frame_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
||||
if frame_w <= 0 or frame_h <= 0:
|
||||
cap.release()
|
||||
return None
|
||||
x, y, w, h = _pane_box(pane)
|
||||
if w <= 0 or h <= 0:
|
||||
cap.release()
|
||||
return None
|
||||
|
||||
step = 1.0 / max(0.1, float(sample_fps))
|
||||
points = []
|
||||
prev_region = None
|
||||
try:
|
||||
t = float(start)
|
||||
while t <= end + 1e-6:
|
||||
cap.set(cv2.CAP_PROP_POS_MSEC, t * 1000.0)
|
||||
ok, frame = cap.read()
|
||||
if not ok:
|
||||
break
|
||||
small = _downscale(frame, ACTIVE_MAX_WIDTH)
|
||||
sw, sh = small.shape[1], small.shape[0]
|
||||
rx = int(round(x * sw / float(frame_w)))
|
||||
ry = int(round(y * sh / float(frame_h)))
|
||||
rw = max(2, int(round(w * sw / float(frame_w))))
|
||||
rh = max(2, int(round(h * sh / float(frame_h))))
|
||||
rx = max(0, min(rx, sw - 2))
|
||||
ry = max(0, min(ry, sh - 2))
|
||||
rw = max(2, min(rw, sw - rx))
|
||||
rh = max(2, min(rh, sh - ry))
|
||||
region = small[ry:ry + rh, rx:rx + rw]
|
||||
if prev_region is not None and prev_region.shape == region.shape:
|
||||
diff = cv2.absdiff(region, prev_region)
|
||||
gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
|
||||
row_mass = gray.sum(axis=1).astype(np.float64)
|
||||
total = float(row_mass.sum())
|
||||
if total >= ACTIVE_MIN_MASS:
|
||||
point = _active_point(row_mass, total)
|
||||
if point is not None:
|
||||
points.append((t, y + point[0] * h))
|
||||
prev_region = region
|
||||
t += step
|
||||
finally:
|
||||
cap.release()
|
||||
|
||||
if len(points) < 3:
|
||||
return None
|
||||
ys = _median_smooth([p[1] for p in points], 3)
|
||||
return [(float(ts), float(yy)) for (ts, _), yy in zip(points, ys)]
|
||||
|
||||
|
||||
def _regular_rows(row_proj, min_period=6, max_period=60, min_peak=0.25):
|
||||
"""True when the row projection has a periodic peak (monospace line pitch).
|
||||
|
||||
Autocorrelation of the mean-subtracted projection; a peak in the plausible
|
||||
line-height band means evenly spaced text lines rather than prose or a UI.
|
||||
"""
|
||||
v = np.asarray(row_proj, dtype=float)
|
||||
if v.size < min_period + 2:
|
||||
return False
|
||||
v = v - v.mean()
|
||||
denom = float((v * v).sum())
|
||||
if denom <= 0:
|
||||
return False
|
||||
ac = np.correlate(v, v, mode="full")[len(v) - 1:]
|
||||
ac = ac / denom
|
||||
hi = min(max_period, len(ac) - 1)
|
||||
if hi <= min_period:
|
||||
return False
|
||||
return float(ac[min_period:hi + 1].max()) >= min_peak
|
||||
|
||||
|
||||
def _texture_ok(maps):
|
||||
"""Edge-density floor + monospace row regularity on an edge-map dict."""
|
||||
density = edge_density(maps["closed"], (0, 0, maps["w"], maps["h"]))
|
||||
if density < EDGE_DENSITY_FLOOR:
|
||||
return False
|
||||
return _regular_rows(maps["row_proj"])
|
||||
|
||||
|
||||
def _palette_ok(crop):
|
||||
"""Editor/terminal palette: dark background or mostly monochrome."""
|
||||
hsv = _hsv(crop)
|
||||
sat_std = float(hsv[:, :, 1].std())
|
||||
dark = float((hsv[:, :, 2] < 102).mean())
|
||||
return bool(dark >= 0.35 or sat_std <= 45.0)
|
||||
|
||||
|
||||
def frame_shows_code(frame, pane):
|
||||
"""True when the pane region of THIS frame still reads as code.
|
||||
|
||||
Text density (edge-density floor + monospace row regularity) plus the
|
||||
editor/terminal palette. A facecam cutaway puts skin/room inside the pane
|
||||
rectangle, which fails both the row pitch and the dark/monochrome palette.
|
||||
"""
|
||||
try:
|
||||
import cv2 # noqa: F401
|
||||
except ImportError:
|
||||
return False
|
||||
x, y, w, h = _pane_box(pane)
|
||||
frame_h, frame_w = frame.shape[:2]
|
||||
x0 = max(0, min(x, frame_w - 2))
|
||||
y0 = max(0, min(y, frame_h - 2))
|
||||
x1 = max(x0 + 2, min(x + w, frame_w))
|
||||
y1 = max(y0 + 2, min(y + h, frame_h))
|
||||
crop = frame[y0:y1, x0:x1]
|
||||
if crop.size == 0:
|
||||
return False
|
||||
maps = _edge_maps(crop)
|
||||
if maps is None:
|
||||
return False
|
||||
return _texture_ok(maps) and _palette_ok(crop)
|
||||
|
||||
|
||||
def scene_shows_code(video_path, pane, start, end, samples=3):
|
||||
"""Sample a scene's frames inside the pane; True on a majority that read
|
||||
as code. A cutaway to the camera fails and keeps the scene's other verdict.
|
||||
"""
|
||||
if end <= start:
|
||||
return False
|
||||
try:
|
||||
import cv2
|
||||
except ImportError:
|
||||
return False
|
||||
cap = cv2.VideoCapture(video_path)
|
||||
if not cap.isOpened():
|
||||
return False
|
||||
frames = []
|
||||
try:
|
||||
n = max(1, int(samples))
|
||||
for i in range(n):
|
||||
t = start + (end - start) * (i + 0.5) / n
|
||||
cap.set(cv2.CAP_PROP_POS_MSEC, t * 1000.0)
|
||||
ok, frame = cap.read()
|
||||
if ok:
|
||||
frames.append(frame)
|
||||
finally:
|
||||
cap.release()
|
||||
if len(frames) < 2:
|
||||
return False
|
||||
good = sum(1 for f in frames if frame_shows_code(f, pane))
|
||||
return good >= max(2, int(round(SCENE_CODE_FRAC * len(frames))))
|
||||
|
||||
|
||||
def looks_like_code(frames):
|
||||
"""Conservative fallback for deployments with no Gemini key.
|
||||
|
||||
``frames`` is a list of BGR arrays. True only when all three hold across the
|
||||
samples: a static pane (centres agree), monospace row regularity, and an
|
||||
editor/terminal palette (dark or mostly monochrome). This is deliberately
|
||||
strict — a false positive demotes a real talking-head clip — and callers
|
||||
MUST NOT invoke it over an explicit operator layout.
|
||||
"""
|
||||
if not frames or len(frames) < 2:
|
||||
return False
|
||||
planes = []
|
||||
row_projs = []
|
||||
sat_stds = []
|
||||
dark_fracs = []
|
||||
for frame in frames:
|
||||
maps = _edge_maps(frame)
|
||||
if maps is None:
|
||||
continue
|
||||
box = pane_from_projections(
|
||||
maps["row_proj"], maps["col_proj"], maps["w"], maps["h"])
|
||||
if box is None:
|
||||
continue
|
||||
if edge_density(maps["closed"], box) < EDGE_DENSITY_FLOOR:
|
||||
continue
|
||||
x, y, w, h = box
|
||||
crop = frame[y:y + h, x:x + w]
|
||||
if crop.size == 0:
|
||||
continue
|
||||
hsv = _hsv(crop)
|
||||
planes.append((x, y, w, h, maps["w"], maps["h"]))
|
||||
row_projs.append(maps["row_proj"])
|
||||
sat_stds.append(float(hsv[:, :, 1].std()))
|
||||
dark_fracs.append(float((hsv[:, :, 2] < 102).mean()))
|
||||
|
||||
if len(planes) < max(2, int(round(0.6 * len(frames)))):
|
||||
return False
|
||||
|
||||
centres_x = np.array([(p[0] + p[2] / 2.0) / p[4] for p in planes])
|
||||
centres_y = np.array([(p[1] + p[3] / 2.0) / p[5] for p in planes])
|
||||
if centres_x.std() > 0.05 or centres_y.std() > 0.05:
|
||||
return False
|
||||
|
||||
median_proj = np.median(np.array(row_projs, dtype=float), axis=0)
|
||||
if not _regular_rows(median_proj):
|
||||
return False
|
||||
|
||||
sat_std = float(np.median(sat_stds))
|
||||
dark = float(np.median(dark_fracs))
|
||||
return bool(dark >= 0.35 or sat_std <= 45.0)
|
||||
|
||||
|
||||
def _hsv(crop):
|
||||
import cv2
|
||||
return cv2.cvtColor(crop, cv2.COLOR_BGR2HSV)
|
||||
|
|
@ -64,6 +64,7 @@ SAMPLE_WIDTH = int(os.environ.get("LAYOUT_SAMPLE_WIDTH", "1024"))
|
|||
DECISION_FLAGS = {
|
||||
"none": [],
|
||||
"screencast": ["screencast_layout"],
|
||||
"code": ["code_layout"],
|
||||
"split": ["split_layout", "active_speaker"],
|
||||
}
|
||||
|
||||
|
|
@ -82,12 +83,14 @@ def apply(decision):
|
|||
stacking regardless of what the model thinks, and a model that says "none"
|
||||
must not quietly undo that.
|
||||
"""
|
||||
import active_speaker
|
||||
import screencast_layout
|
||||
import split_layout
|
||||
from clipwright.layouts import active_speaker
|
||||
from clipwright.layouts import code_layout
|
||||
from clipwright.layouts import screencast_layout
|
||||
from clipwright.layouts import split_layout
|
||||
|
||||
modules = {"split_layout": split_layout,
|
||||
"screencast_layout": screencast_layout,
|
||||
"code_layout": code_layout,
|
||||
"active_speaker": active_speaker}
|
||||
|
||||
touched = []
|
||||
|
|
@ -191,7 +194,7 @@ def pick(video_path, video_duration):
|
|||
# raises, and an unimportable SDK is just one more reason to fall back.
|
||||
from google import genai
|
||||
from google.genai import types as genai_types
|
||||
import gemini_worker
|
||||
from clipwright.pipeline import gemini_worker
|
||||
|
||||
frames = sample_frames(video_path)
|
||||
if not frames:
|
||||
|
|
@ -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.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
|
||||
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"]
|
||||
|
||||
|
||||
def in_split(t, splits):
|
||||
return any(s <= t < e for s, e in splits or [])
|
||||
|
||||
|
||||
def remap(ranges, segments):
|
||||
"""Carry ranges across a cut-and-concat. ``segments`` are the kept
|
||||
stretches of the SOURCE file in order ({"start", "end"}); the output is
|
||||
|
|
@ -14,11 +14,14 @@ It rides the TRACK path, widening the existing per-frame crop command from
|
|||
x-only to w/h/x/y, so it composes with the camera trajectory instead of fighting
|
||||
it. Off by default (``PUNCH_IN=1``).
|
||||
|
||||
Beat times come from the audio envelope. The transcript would be a better
|
||||
source (punch on the hook word, not on the loudest syllable), and render() has
|
||||
no transcript today — ``emphasis_times`` is a plain list of seconds, so wiring
|
||||
main.py's word timings in later needs no change here.
|
||||
Beat times come from the audio envelope, aligned to the clip-relative word
|
||||
onsets the transcript provides (``emphasis_times(word_times=...)``). The
|
||||
envelope finds the emphasis; the word onset says exactly when it started, so
|
||||
each peak snaps to the nearest word instead of sitting on the loudest
|
||||
syllable. A clip with no envelope beats falls back to the word onsets alone,
|
||||
and without ``word_times`` the beat derivation is exactly what it always was.
|
||||
"""
|
||||
import bisect
|
||||
import os
|
||||
|
||||
import numpy as np
|
||||
|
|
@ -59,6 +62,11 @@ BEAT_WINDOW = 0.2
|
|||
MIN_GAP_SECONDS = 18.0
|
||||
BEAT_PROMINENCE = 0.60
|
||||
|
||||
# How far an envelope peak may move to land on a word onset. The envelope frame
|
||||
# is coarse (BEAT_WINDOW); the word's start is exact, so the tolerance is a bit
|
||||
# wider than the frame rather than equal to it.
|
||||
WORD_SNAP_SECONDS = 0.5
|
||||
|
||||
|
||||
def _ease(t):
|
||||
"""Smoothstep on [0, 1]. Linear ramps look mechanical at this duration."""
|
||||
|
|
@ -155,32 +163,72 @@ def sendcmd_lines(boxes, fps, target="crop@c"):
|
|||
return lines
|
||||
|
||||
|
||||
def emphasis_times(video_path, duration, window=BEAT_WINDOW,
|
||||
min_gap=MIN_GAP_SECONDS, prominence=BEAT_PROMINENCE):
|
||||
"""Seconds where the audio leaps above its own baseline.
|
||||
def _snap_to_word(t, words, snap):
|
||||
"""``t`` moved to the closest onset in the sorted ``words``, if within
|
||||
``snap``. Without a word in range the envelope beat is left where it is."""
|
||||
i = bisect.bisect_left(words, t)
|
||||
best, best_d = t, snap
|
||||
for j in (i - 1, i):
|
||||
if 0 <= j < len(words):
|
||||
d = abs(words[j] - t)
|
||||
if d <= best_d:
|
||||
best, best_d = words[j], d
|
||||
return best
|
||||
|
||||
A stand-in for the hook words until the transcript is wired through. Returns
|
||||
[] for silent or unreadable audio, which simply means no punches.
|
||||
|
||||
def merge_beats(audio_beats, word_times, min_gap=MIN_GAP_SECONDS,
|
||||
snap=WORD_SNAP_SECONDS):
|
||||
"""Punch beats: envelope emphasis, snapped onto the words that carry it.
|
||||
|
||||
The envelope finds where the energy jumped; a word onset is the precise
|
||||
instant to push. Each envelope beat is snapped to the nearest word onset
|
||||
within ``snap`` seconds, which is what turns "the loudest syllable" into
|
||||
"the word that was loud". With no envelope beats at all — silent or flat
|
||||
audio — the word onsets themselves become the beats. The result is thinned
|
||||
to ``min_gap`` so two pushes never overlap. Pure: no audio, no I/O, which
|
||||
is what makes the beat timing testable without a clip.
|
||||
"""
|
||||
import active_speaker
|
||||
words = sorted(word_times or [])
|
||||
if audio_beats:
|
||||
candidates = [_snap_to_word(b, words, snap) if words else b
|
||||
for b in audio_beats]
|
||||
else:
|
||||
candidates = list(words)
|
||||
|
||||
envelope = active_speaker.audio_envelope(video_path, 0.0, duration,
|
||||
window_s=window)
|
||||
if not envelope:
|
||||
return []
|
||||
|
||||
values = np.asarray(envelope, dtype=float)
|
||||
baseline = float(np.median(values))
|
||||
peak = float(values.max())
|
||||
if peak - baseline <= 1e-6:
|
||||
return []
|
||||
|
||||
threshold = baseline + (peak - baseline) * prominence
|
||||
times = []
|
||||
last = -1e9
|
||||
for i, v in enumerate(values):
|
||||
t = i * window
|
||||
if v >= threshold and t - last >= min_gap:
|
||||
for t in sorted(candidates):
|
||||
if t - last >= min_gap:
|
||||
times.append(round(t, 3))
|
||||
last = t
|
||||
return times
|
||||
|
||||
|
||||
def emphasis_times(video_path, duration, window=BEAT_WINDOW,
|
||||
min_gap=MIN_GAP_SECONDS, prominence=BEAT_PROMINENCE,
|
||||
word_times=None):
|
||||
"""Seconds where the clip should punch in.
|
||||
|
||||
Audio envelope peaks, merged with ``word_times`` — optional clip-relative
|
||||
word onsets in seconds (clip start = 0), as produced from the transcript.
|
||||
Returns [] for silent, word-less input, which simply means no punches.
|
||||
"""
|
||||
from clipwright.layouts import active_speaker
|
||||
|
||||
envelope = active_speaker.audio_envelope(video_path, 0.0, duration,
|
||||
window_s=window)
|
||||
audio_beats = []
|
||||
if envelope:
|
||||
values = np.asarray(envelope, dtype=float)
|
||||
baseline = float(np.median(values))
|
||||
peak = float(values.max())
|
||||
if peak - baseline > 1e-6:
|
||||
threshold = baseline + (peak - baseline) * prominence
|
||||
last = -1e9
|
||||
for i, v in enumerate(values):
|
||||
t = i * window
|
||||
if v >= threshold and t - last >= min_gap:
|
||||
audio_beats.append(t)
|
||||
last = t
|
||||
|
||||
return merge_beats(audio_beats, word_times, min_gap=min_gap)
|
||||
|
|
@ -21,13 +21,14 @@ import os
|
|||
import subprocess
|
||||
import tempfile
|
||||
|
||||
import active_speaker
|
||||
import camera_inset
|
||||
import punch_in
|
||||
import screencast_layout
|
||||
import layout_ranges
|
||||
import split_layout
|
||||
from ffmpeg_utils import (video_encode_args, blurred_backdrop, escape_filter_value,
|
||||
from clipwright.layouts import active_speaker
|
||||
from clipwright.layouts import camera_inset
|
||||
from clipwright.layouts import code_layout
|
||||
from clipwright.layouts import punch_in
|
||||
from clipwright.layouts import screencast_layout
|
||||
from clipwright.layouts import layout_ranges
|
||||
from clipwright.layouts import split_layout
|
||||
from clipwright.media.ffmpeg_utils import (video_encode_args, blurred_backdrop, escape_filter_value,
|
||||
QUALITY_FAST, METADATA_SCRUB)
|
||||
|
||||
ANALYSIS_MAX_WIDTH = 640
|
||||
|
|
@ -255,7 +256,7 @@ def _analyze_trajectory(input_video, scenes_boundaries, scene_strategies,
|
|||
"""Replays v1's per-frame decision loop on a downscaled ffmpeg-decoded
|
||||
stream. Returns xs: crop x per frame (None on GENERAL frames)."""
|
||||
import numpy as np
|
||||
import main as m
|
||||
from clipwright.pipeline import main as m
|
||||
|
||||
small_w = min(ANALYSIS_MAX_WIDTH, orig_w)
|
||||
if small_w % 2:
|
||||
|
|
@ -341,12 +342,15 @@ def _run(cmd):
|
|||
|
||||
|
||||
def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
|
||||
force_strategy=None, crop_overrides=None, watermark=False):
|
||||
force_strategy=None, crop_overrides=None, word_times=None):
|
||||
"""Full v2 reframe of one clip. Raises on failure (caller falls back).
|
||||
|
||||
``content_ranges`` comes from screencast_layout.detect_content_ranges() on
|
||||
the SOURCE video, already translated into this clip's timeline. None or []
|
||||
means the layout never triggers, which is the default.
|
||||
the SOURCE video, already translated into this clip's timeline. When it is
|
||||
None, the render computes it itself on ``input_video`` if the screencast
|
||||
module is on (see below); this used to be a dead wire no production caller
|
||||
filled, so the picker's "screencast" option did nothing. Pass [] to force
|
||||
the upgrade off, or a list to supply pre-computed ranges.
|
||||
|
||||
``force_strategy`` ('WIDE' / 'TRACK' / any layout the render loop knows)
|
||||
applies that layout to EVERY scene, skipping the classifier and the layout
|
||||
|
|
@ -358,11 +362,12 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
|
|||
the ones the tracker got right. Applied AFTER force_strategy: a per-scene
|
||||
hand position always beats the whole-clip choice for the scenes it names.
|
||||
|
||||
``watermark`` overlays the free-plan mark (main.watermark_filter) in every
|
||||
segment's own encode, instead of main.apply_watermark re-encoding the
|
||||
finished clip once more.
|
||||
``word_times`` are clip-relative word onsets in seconds (clip start = 0)
|
||||
from the transcript, optional. They steer the punch-in beats toward spoken
|
||||
emphasis; None leaves the audio envelope as the only beat source.
|
||||
"""
|
||||
import main as m
|
||||
from clipwright.pipeline import main as m
|
||||
auto_content_ranges = content_ranges is None
|
||||
content_ranges = content_ranges or []
|
||||
|
||||
print(" 🚀 Reframe engine v2 (ffmpeg-native render)")
|
||||
|
|
@ -438,6 +443,57 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
|
|||
if alternates:
|
||||
print(f" 🎬 Speaker-cut layout on {len(alternates)} scene(s)")
|
||||
|
||||
# The SCREENCAST/WIDE/INSET upgrades gate on content_ranges, which no
|
||||
# production caller ever passed: screencast_layout.detect_content_ranges
|
||||
# was called by tests only, so the picker's "screencast" option silently did
|
||||
# nothing (dead wire found in review). Compute them here, once per render,
|
||||
# when the module is on and nothing overrides the layout. CODE does NOT use
|
||||
# this external-ranges path — it self-detects below.
|
||||
if (auto_content_ranges and screencast_layout.ENABLED
|
||||
and not force_strategy and not passthrough):
|
||||
duration = scene_boundaries[-1][1] / fps if scene_boundaries else 0.0
|
||||
try:
|
||||
content_ranges = screencast_layout.detect_content_ranges(
|
||||
input_video, duration)
|
||||
except Exception as e:
|
||||
print(f" ⚠️ On-screen content check failed ({e}).")
|
||||
content_ranges = []
|
||||
|
||||
# CODE is geometric and self-contained, like split_layout: the pane box is
|
||||
# found once for the whole video (screen recordings are usually one long
|
||||
# scene) and then each scene is verified by sampling frames inside that box.
|
||||
# A scene that cuts to the facecam fails the text check and keeps TRACK.
|
||||
# Inserted before SCREENCAST so a code editor with a webcam wins, and the
|
||||
# screencast loop below skips scenes already claimed here.
|
||||
codes = {}
|
||||
code_pane = None
|
||||
if code_layout.ENABLED and not passthrough and not force_strategy:
|
||||
try:
|
||||
code_pane = code_layout.detect_code_pane(input_video)
|
||||
except Exception as e:
|
||||
print(f" ⚠️ Code-pane check failed ({e}) — using other layouts.")
|
||||
code_pane = None
|
||||
if code_pane:
|
||||
max_w = max(2, int(out_w / code_layout.MIN_SCALE))
|
||||
pane_box = code_layout.clamp_pane_width(code_pane, max_w)
|
||||
scale = out_w / float(pane_box[2])
|
||||
print(f" 💻 Code pane {code_pane['w']}x{code_pane['h']} "
|
||||
f"@ {code_pane['x']},{code_pane['y']} "
|
||||
f"mode={code_pane['mode']} conf={code_pane['confidence']:.2f}"
|
||||
f" -> crop {pane_box[2]}px (scale {scale:.2f})")
|
||||
code_pane = dict(code_pane, x=pane_box[0], y=pane_box[1],
|
||||
w=pane_box[2], h=pane_box[3])
|
||||
for scene_idx, (start_f, end_f) in enumerate(scene_boundaries):
|
||||
if strategies[scene_idx] not in ("TRACK", "GENERAL"):
|
||||
continue
|
||||
if code_layout.scene_shows_code(
|
||||
input_video, code_pane, start_f / fps, end_f / fps):
|
||||
strategies[scene_idx] = "CODE"
|
||||
codes[start_f] = code_pane
|
||||
splits.pop(start_f, None)
|
||||
if codes:
|
||||
print(f" 💻 CODE layout on {len(codes)} scene(s)")
|
||||
|
||||
# SCREENCAST wins over SPLIT on the rare scene that qualifies for both: two
|
||||
# faces beside a chart still means the chart is what the shot is about, and
|
||||
# stacking the two speakers would crop it away entirely.
|
||||
|
|
@ -461,6 +517,9 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
|
|||
if content_ranges:
|
||||
for scene_idx, (plan, centre) in screencast_layout.detect_screencast_scenes(
|
||||
input_video, scenes, strategies, content_ranges).items():
|
||||
# CODE was detected geometrically and wins over the screen layouts.
|
||||
if strategies[scene_idx] == 'CODE':
|
||||
continue
|
||||
# An inset beats both screen plans: it is the only one that can show
|
||||
# the screen whole AND the person at a readable size.
|
||||
if inset:
|
||||
|
|
@ -496,7 +555,8 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
|
|||
# Beats are found once per clip; each scene takes the ones inside it.
|
||||
beats = []
|
||||
if punch_in.ENABLED:
|
||||
beats = punch_in.emphasis_times(input_video, len(xs) / fps)
|
||||
beats = punch_in.emphasis_times(input_video, len(xs) / fps,
|
||||
word_times=word_times)
|
||||
if beats:
|
||||
print(f" 🔍 Punch-in on {len(beats)} beat(s)")
|
||||
|
||||
|
|
@ -525,10 +585,6 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
|
|||
ranges = scene_frame_ranges(scene_boundaries, strategies, len(xs))
|
||||
if not ranges:
|
||||
raise RuntimeError("no usable scene ranges")
|
||||
logo = m.watermark_logo_path() if watermark else None
|
||||
if logo and not os.path.exists(logo):
|
||||
print(f" ⚠️ Watermark asset missing ({logo}); clip kept unmarked.")
|
||||
logo = None
|
||||
|
||||
workdir = tempfile.mkdtemp(prefix="reframe_v2_")
|
||||
segments = []
|
||||
|
|
@ -552,6 +608,22 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
|
|||
left, right = splits[start_f]
|
||||
graph = split_layout.split_filtergraph(
|
||||
orig_w, orig_h, out_w, out_h, left, right)
|
||||
elif strategy == 'CODE' and start_f in codes:
|
||||
pane = codes[start_f]
|
||||
follow = None
|
||||
if code_layout.FOLLOW_ENABLED:
|
||||
try:
|
||||
series = code_layout.active_line_series(
|
||||
input_video, pane, ss, ss + dur)
|
||||
if series:
|
||||
follow = [(t - ss, y) for t, y in series]
|
||||
except Exception:
|
||||
follow = None
|
||||
graph = code_layout.code_filtergraph(
|
||||
pane, out_w, out_h, follow=follow)
|
||||
if graph is None:
|
||||
graph = general_filtergraph(out_w, out_h,
|
||||
orig_w=orig_w, orig_h=orig_h)
|
||||
elif strategy == 'GENERAL':
|
||||
graph = general_filtergraph(out_w, out_h,
|
||||
orig_w=orig_w, orig_h=orig_h)
|
||||
|
|
@ -584,10 +656,6 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None,
|
|||
)
|
||||
|
||||
inputs, out_label = ["-i", input_video], "[v]"
|
||||
if logo:
|
||||
inputs += ["-i", logo]
|
||||
graph += ";" + m.watermark_filter(out_w, out_h, video="[v]", out="[vw]")
|
||||
out_label = "[vw]"
|
||||
_run([
|
||||
"ffmpeg", "-y", "-loglevel", "error",
|
||||
"-ss", f"{ss:.4f}", "-t", f"{dur:.4f}", *inputs,
|
||||
|
|
@ -123,7 +123,7 @@ def detect_faces_full_res(frame):
|
|||
screencast candidates only.
|
||||
"""
|
||||
import cv2
|
||||
import main as m
|
||||
from clipwright.pipeline import main as m
|
||||
|
||||
h, w, _ = frame.shape
|
||||
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
||||
|
|
@ -178,7 +178,7 @@ def detect_content_ranges(video_path, video_duration):
|
|||
|
||||
from google import genai
|
||||
from google.genai import types as genai_types
|
||||
import gemini_worker
|
||||
from clipwright.pipeline import gemini_worker
|
||||
|
||||
model_name = os.environ.get("GEMINI_MODEL") or 'gemini-3.1-flash-lite'
|
||||
print("🔎 Checking for full-width on-screen content…")
|
||||
|
|
@ -268,7 +268,7 @@ def detect_screencast_scenes(video_path, scenes, strategies, ranges, samples=6):
|
|||
# Below the gate on purpose: main pulls torch/mediapipe, and the disabled
|
||||
# path (the default, and what CI exercises) must not pay that import.
|
||||
import cv2
|
||||
import main as m
|
||||
from clipwright.pipeline import main as m
|
||||
|
||||
cap = cv2.VideoCapture(video_path)
|
||||
if not cap.isOpened():
|
||||
|
|
@ -18,7 +18,7 @@ import os
|
|||
|
||||
import numpy as np
|
||||
|
||||
import frame_sampler
|
||||
from clipwright.media import frame_sampler
|
||||
|
||||
ENABLED = os.environ.get("SPLIT_LAYOUT", "0") == "1"
|
||||
|
||||
|
|
@ -221,7 +221,7 @@ def detect_split_scenes(video_path, scenes, strategies, samples=None):
|
|||
touching the single-speaker material that is most of the corpus.
|
||||
"""
|
||||
import cv2
|
||||
import main as m
|
||||
from clipwright.pipeline import main as m
|
||||
|
||||
if not ENABLED:
|
||||
return {}
|
||||
1
clipwright/media/__init__.py
Normal file
1
clipwright/media/__init__.py
Normal file
|
|
@ -0,0 +1 @@
|
|||
"""Clipwright backend."""
|
||||
|
|
@ -8,9 +8,9 @@ from google import genai
|
|||
from google.genai import types
|
||||
from pydantic import BaseModel
|
||||
|
||||
import gemini_worker
|
||||
from edit_builder import build_filter_string
|
||||
from ffmpeg_utils import video_encode_args, QUALITY, METADATA_SCRUB
|
||||
from clipwright.pipeline import gemini_worker
|
||||
from clipwright.media.edit_builder import build_filter_string
|
||||
from clipwright.media.ffmpeg_utils import video_encode_args, QUALITY, METADATA_SCRUB
|
||||
|
||||
|
||||
class EditDecision(BaseModel):
|
||||
|
|
@ -65,25 +65,6 @@ class VideoEditor:
|
|||
raise TimeoutError("Gemini file processing timed out after 120s.")
|
||||
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):
|
||||
"""Asks Gemini for an edit decision list, then builds the FFmpeg filter
|
||||
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"
|
||||
|
||||
|
||||
# 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():
|
||||
"""AAC encode args for a delivered clip, with loudness normalisation."""
|
||||
args = ["-c:a", "aac"]
|
||||
|
|
@ -1,12 +1,12 @@
|
|||
import os
|
||||
import re
|
||||
import textwrap
|
||||
import subprocess
|
||||
import urllib.request
|
||||
import uuid
|
||||
from PIL import Image, ImageDraw, ImageFont, ImageFilter
|
||||
|
||||
from ffmpeg_utils import video_encode_args, QUALITY, METADATA_SCRUB
|
||||
from clipwright.media.ffmpeg_utils import video_encode_args, QUALITY, METADATA_SCRUB
|
||||
from clipwright.core.paths import FONTS_DIR
|
||||
|
||||
|
||||
def _truncate_bytes(text, max_bytes):
|
||||
|
|
@ -21,7 +21,7 @@ def _truncate_bytes(text, max_bytes):
|
|||
return encoded[:max_bytes].decode("utf-8", "ignore")
|
||||
|
||||
FONT_URL = "https://github.com/googlefonts/noto-fonts/raw/main/hinted/ttf/NotoSerif/NotoSerif-Bold.ttf"
|
||||
FONT_DIR = "fonts"
|
||||
FONT_DIR = str(FONTS_DIR)
|
||||
FONT_PATH = os.path.join(FONT_DIR, "NotoSerif-Bold.ttf")
|
||||
# Bundled (SIL OFL, see fonts/Montserrat-OFL.txt): the "pill" look's sans.
|
||||
PILL_FONT_PATH = os.path.join(FONT_DIR, "Montserrat-ExtraBold.ttf")
|
||||
|
|
@ -272,7 +272,6 @@ def create_hook_image(text, target_width, output_image_path="hook_overlay.png",
|
|||
line_spacing = 20 # Increased spacing
|
||||
cornerradius = 20
|
||||
shadow_offset = (5, 5)
|
||||
shadow_blur = 10
|
||||
|
||||
# Font Size Calculation (approx 5% of width - tuned to match Noto Serif Bold metrics in browser)
|
||||
pills = bool(look.get("pills"))
|
||||
|
|
@ -4,7 +4,7 @@ turned into a rendered clip.
|
|||
|
||||
The pure helpers here are standard-library only (plus ffmpeg_utils, which is
|
||||
also light) so the module imports in the thin CI environment; everything heavy
|
||||
(reframing, watermark, auto-captions live in main.py) is imported lazily and
|
||||
(reframing, auto-captions live in main.py) is imported lazily and
|
||||
only on the paths that need it.
|
||||
|
||||
Two render paths:
|
||||
|
|
@ -17,14 +17,13 @@ Two render paths:
|
|||
with the same engine the pipeline used.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from ffmpeg_utils import (METADATA_SCRUB, QUALITY_FAST, audio_encode_args,
|
||||
from clipwright.media.ffmpeg_utils import (METADATA_SCRUB, QUALITY_FAST, audio_encode_args,
|
||||
video_encode_args)
|
||||
|
||||
# EDL limits. Deliberately generous — the editor is for humans fixing cuts,
|
||||
|
|
@ -109,7 +108,7 @@ def rebase_segments(segments, range_start, range_end=None):
|
|||
def snap_segments(segments, transcript, source_duration):
|
||||
"""Snap each segment's bounds onto word boundaries (ground truth beats
|
||||
millisecond arithmetic — same rationale as the pipeline's snapping)."""
|
||||
from clip_selection import snap_clip_to_words
|
||||
from clipwright.pipeline.clip_selection import snap_clip_to_words
|
||||
|
||||
words = transcript_words(transcript)
|
||||
if not words:
|
||||
|
|
@ -244,8 +243,8 @@ def run_cut_concat(input_path, segments, out_path, workdir, runner=None):
|
|||
return out_path
|
||||
|
||||
|
||||
# Same ceiling as apply_watermark's: a hung ffmpeg must not pin the executor
|
||||
# thread (and the caller's quota reservation) until a server restart.
|
||||
# A hung ffmpeg must not pin the executor thread (and the caller's quota
|
||||
# reservation) until a server restart.
|
||||
FFMPEG_TIMEOUT_SECONDS = 1800
|
||||
|
||||
|
||||
|
|
@ -263,18 +262,16 @@ def _run_ffmpeg(command):
|
|||
|
||||
|
||||
def perform_recut(*, input_path, segments, output_dir, clean_name,
|
||||
reframe=False, output_format="auto", watermark=False,
|
||||
reframe=False, output_format="auto",
|
||||
captions_transcript=None, force_strategy=None,
|
||||
crop_overrides=None, runner=None, renderer=None,
|
||||
watermarker=None, captioner=None):
|
||||
captioner=None):
|
||||
"""Render a recut clip. Returns (served_filename, clean_filename).
|
||||
|
||||
- ``input_path``/``segments``: the file to cut from and the times ON THAT
|
||||
FILE (the caller rebases for the fast path).
|
||||
- ``reframe``: run the reframe engine on the joined cut (source path only —
|
||||
the canonical file is already framed).
|
||||
- ``watermark``: re-apply the free-plan watermark (source path only — the
|
||||
canonical file already carries it).
|
||||
- ``captions_transcript``: a clip-relative transcript (see
|
||||
``virtual_transcript``); when given and non-empty, captions are burned
|
||||
LAST onto a ``subtitled_<ts>_`` derivative, preserving the invariant
|
||||
|
|
@ -284,9 +281,9 @@ def perform_recut(*, input_path, segments, output_dir, clean_name,
|
|||
the same reason as ``reframe``: the canonical file is already cropped, so
|
||||
its framing can no longer be changed.
|
||||
|
||||
The renderer/watermarker/captioner hooks default to main.py's
|
||||
implementations, imported lazily so this module stays importable without
|
||||
the ML stack; tests inject fakes.
|
||||
The renderer/captioner hooks default to main.py's implementations, imported
|
||||
lazily so this module stays importable without the ML stack; tests inject
|
||||
fakes.
|
||||
"""
|
||||
# The uuid token keeps two same-second saves of one clip from writing (and
|
||||
# then serving) the same filename; the timestamp keeps "newest derived
|
||||
|
|
@ -316,14 +313,11 @@ def perform_recut(*, input_path, segments, output_dir, clean_name,
|
|||
# No reframe means no fresh layout sidecar; the captions would fall
|
||||
# back to the bottom on a stacked clip. Carry the input's layout
|
||||
# ranges through the cut instead (empty when the input has none).
|
||||
import layout_ranges
|
||||
from clipwright.layouts import layout_ranges
|
||||
layout_ranges.write(out_path, [
|
||||
(r["start"], r["end"], r["layout"])
|
||||
for r in layout_ranges.remap(layout_ranges.read(input_path), segments)])
|
||||
|
||||
if watermark:
|
||||
(watermarker or _main_attr("apply_watermark"))(out_path)
|
||||
|
||||
served_name = out_name
|
||||
if captions_transcript and captions_transcript.get("segments"):
|
||||
caption = captioner or _main_attr("auto_caption_clip")
|
||||
|
|
@ -338,5 +332,5 @@ def perform_recut(*, input_path, segments, output_dir, clean_name,
|
|||
|
||||
|
||||
def _main_attr(name):
|
||||
import main # heavy — resolved only when a real render/caption runs
|
||||
from clipwright.pipeline import main # heavy — resolved only when a real render/caption runs
|
||||
return getattr(main, name)
|
||||
|
|
@ -106,7 +106,9 @@ def _detect_transnetv2(video_path):
|
|||
threshold = float(os.environ.get("TRANSNETV2_THRESHOLD", "0.5"))
|
||||
|
||||
with _TN2_LOCK, torch.no_grad():
|
||||
tensor = torch.from_numpy(np.ascontiguousarray(frames)).to(model.device)
|
||||
# frombuffer() yields a read-only array; copy so torch stops warning and
|
||||
# writing to the tensor is well-defined.
|
||||
tensor = torch.from_numpy(np.array(frames, copy=True)).to(model.device)
|
||||
single_frame_pred, _ = model.predict_frames(tensor, quiet=True)
|
||||
single_frame_pred = single_frame_pred.cpu()
|
||||
del tensor
|
||||
|
|
@ -3,8 +3,9 @@ import re
|
|||
import subprocess
|
||||
import sys
|
||||
|
||||
from ffmpeg_utils import (video_encode_args, escape_filter_value, QUALITY,
|
||||
from clipwright.media.ffmpeg_utils import (video_encode_args, escape_filter_value, QUALITY,
|
||||
METADATA_SCRUB)
|
||||
from clipwright.core.paths import FONTS_DIR
|
||||
|
||||
|
||||
_STDIO_CONFIGURED = False
|
||||
|
|
@ -113,41 +114,6 @@ def _normalize_subtitle_word(value):
|
|||
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 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):
|
||||
"""
|
||||
Flatten transcript words for a clip range and group them into short blocks
|
||||
|
|
@ -629,7 +595,7 @@ def subtitles_filter(srt_path, alignment=2, fontsize=16,
|
|||
|
||||
# Let libass see the fonts bundled with the app (e.g. Anton for Impact)
|
||||
# even when the system fontconfig has no cache for them.
|
||||
fonts_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fonts")
|
||||
fonts_dir = str(FONTS_DIR)
|
||||
safe_fonts_dir = _escape_ffmpeg_filter_value(fonts_dir)
|
||||
|
||||
# The first option is named explicitly (filename=) rather than positional:
|
||||
|
|
@ -9,6 +9,9 @@ from google import genai
|
|||
from google.genai import types
|
||||
from google.genai import errors as genai_errors
|
||||
from PIL import Image, ImageDraw, ImageFont, ImageFilter
|
||||
from clipwright.core.paths import FONTS_DIR
|
||||
from clipwright.media import title_validation
|
||||
from clipwright.pipeline import profile_prompts
|
||||
|
||||
# Text/analysis model (titles, concepts, description). Deliberately NOT tied to
|
||||
# GEMINI_MODEL: the pipeline runs flash-lite for a closed-choice layout pick,
|
||||
|
|
@ -30,9 +33,17 @@ TITLE_MAX_CHARS = 65
|
|||
|
||||
THUMB_W, THUMB_H = 1280, 720
|
||||
THUMB_MAX_BYTES = 2 * 1024 * 1024 # YouTube's upload limit
|
||||
THUMB_FONT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fonts", "Anton-Regular.ttf")
|
||||
THUMB_FONT = str(FONTS_DIR / "Anton-Regular.ttf")
|
||||
TEXT_POSITIONS = ("left", "right", "top", "bottom")
|
||||
|
||||
# Mobile viewers (the majority of the audience) watch with YouTube's
|
||||
# timestamp/badge overlays in the bottom-right; keep the headline clear of that
|
||||
# corner and off the right edge.
|
||||
THUMB_SAFE_BOTTOM = 0.20 # bottom fraction reserved for YouTube's UI
|
||||
THUMB_SAFE_RIGHT = 0.05 # margin off the right edge
|
||||
THUMB_SAFE_LEFT = 0.04 # margin off the left edge
|
||||
THUMB_SAFE_TOP = 0.04 # margin off the top edge
|
||||
|
||||
|
||||
def _parse_json(text):
|
||||
"""Gemini JSON, tolerant of code fences and prose around the object."""
|
||||
|
|
@ -49,7 +60,7 @@ def _parse_json(text):
|
|||
def _frame_parts(video_path, n=TITLE_FRAMES, width=TITLE_FRAME_WIDTH):
|
||||
"""Evenly spaced frames as Gemini image parts (empty list on any failure)."""
|
||||
try:
|
||||
from layout_picker import sample_frames
|
||||
from clipwright.layouts.layout_picker import sample_frames
|
||||
return [types.Part.from_bytes(data=b, mime_type="image/jpeg")
|
||||
for b in sample_frames(video_path, n=n, width=width)]
|
||||
except Exception as e:
|
||||
|
|
@ -61,16 +72,19 @@ def _frame_parts(video_path, n=TITLE_FRAMES, width=TITLE_FRAME_WIDTH):
|
|||
# Titles
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def analyze_video_for_titles(api_key, video_path, transcript=None):
|
||||
def analyze_video_for_titles(api_key, video_path, transcript=None, profile=None):
|
||||
"""
|
||||
Suggests YouTube titles from the transcript plus a handful of frames.
|
||||
Two calls: a wide brainstorm, then a critic that scores and picks a
|
||||
diverse top 10 and pairs each title with a 1-4 word thumbnail hook.
|
||||
|
||||
``profile`` (optional channel Profile, PLAN #1) adds the channel's title and
|
||||
hook rules to both calls; ``None`` leaves the prompts unchanged.
|
||||
Returns: { "titles", "thumbnail_texts", "transcript_summary", "language",
|
||||
"segments", "video_duration", "recommended" }
|
||||
"""
|
||||
if transcript is None:
|
||||
from main import transcribe_video
|
||||
from clipwright.pipeline.main import transcribe_video
|
||||
print("🎬 [Thumbnail] Transcribing video...")
|
||||
transcript = transcribe_video(video_path)
|
||||
else:
|
||||
|
|
@ -83,6 +97,11 @@ def analyze_video_for_titles(api_key, video_path, transcript=None):
|
|||
video_duration = segments[-1]["end"] if segments else 0
|
||||
# Enough transcript for a title; a 3-hour podcast does not need all of it.
|
||||
transcript_text = transcript.get("text", "")[:60000]
|
||||
# Empty for profile=None, so the f-strings below render exactly as before.
|
||||
channel_rules = profile_prompts.clip_rules_block(profile)
|
||||
if channel_rules:
|
||||
print(f"📦 [Thumbnail] Applying channel profile "
|
||||
f"{getattr(profile, 'slug', '')} to title prompts.")
|
||||
|
||||
brainstorm_prompt = f"""You are a YouTube packaging expert (titles + thumbnails) for a channel that wants maximum CTR without lying.
|
||||
|
||||
|
|
@ -108,7 +127,7 @@ TITLE RULES:
|
|||
- Put the main keyword / subject in the first 3 words.
|
||||
- Be specific to THIS video: names, numbers, tools, places from the transcript. Nothing generic.
|
||||
- No ALL CAPS words, at most one exclamation mark, no emojis.
|
||||
|
||||
{channel_rules}
|
||||
OUTPUT JSON:
|
||||
{{
|
||||
"transcript_summary": "...",
|
||||
|
|
@ -153,7 +172,7 @@ Then return the 10 best, ordered best first, with NO two titles using the same a
|
|||
For each of the 10, write the THUMBNAIL TEXT: 1-4 words, ALL CAPS, in {language}, that COMPLEMENTS the title instead of repeating it (the title says what, the thumbnail says the emotion, the number or the twist). Examples of the relationship: title "How I got 10k subscribers in 30 days" -> thumbnail "0 TO 10K"; title "Por qué dejé mi trabajo en Google" -> thumbnail "ME FUI".
|
||||
|
||||
Pick the top 2 and explain in one sentence each why they will win the click.
|
||||
|
||||
{channel_rules}
|
||||
OUTPUT JSON:
|
||||
{{
|
||||
"titles": ["...", ... 10 items],
|
||||
|
|
@ -165,21 +184,50 @@ OUTPUT JSON:
|
|||
}}"""
|
||||
|
||||
print("🧐 [Thumbnail] Scoring titles...")
|
||||
response = client.models.generate_content(
|
||||
model=TEXT_MODEL,
|
||||
contents=[critic_prompt],
|
||||
config=types.GenerateContentConfig(response_mime_type="application/json"),
|
||||
)
|
||||
try:
|
||||
picked = _parse_json(response.text)
|
||||
titles = [t for t in picked.get("titles", []) if isinstance(t, str) and t.strip()]
|
||||
if not titles:
|
||||
raise ValueError("no titles")
|
||||
except (json.JSONDecodeError, AttributeError, ValueError):
|
||||
print(f"⚠️ [Thumbnail] Critic failed, falling back to the brainstorm: {getattr(response, 'text', '')[:300]}")
|
||||
titles = candidates[:10]
|
||||
picked = {"thumbnail_texts": [], "recommended": []}
|
||||
|
||||
def _critic(violations=None):
|
||||
"""One critic call. ``violations`` appends the re-ask critique."""
|
||||
prompt = critic_prompt
|
||||
if violations:
|
||||
prompt = critic_prompt + "\n\n" + title_validation.critique_block(violations)
|
||||
response = client.models.generate_content(
|
||||
model=TEXT_MODEL,
|
||||
contents=[prompt],
|
||||
config=types.GenerateContentConfig(response_mime_type="application/json"),
|
||||
)
|
||||
try:
|
||||
picked_local = _parse_json(response.text)
|
||||
titles_local = [t for t in picked_local.get("titles", [])
|
||||
if isinstance(t, str) and t.strip()]
|
||||
if not titles_local:
|
||||
raise ValueError("no titles")
|
||||
except (json.JSONDecodeError, AttributeError, ValueError):
|
||||
print(f"⚠️ [Thumbnail] Critic failed: {getattr(response, 'text', '')[:300]}")
|
||||
return None
|
||||
texts_local = [str(t) for t in picked_local.get("thumbnail_texts", [])][:len(titles_local)]
|
||||
texts_local += [""] * (len(titles_local) - len(texts_local))
|
||||
return {
|
||||
"titles": titles_local,
|
||||
"thumbnail_texts": texts_local,
|
||||
"recommended": [r for r in picked_local.get("recommended", [])
|
||||
if isinstance(r, dict) and isinstance(r.get("index"), int)
|
||||
and 0 <= r["index"] < len(titles_local)],
|
||||
}
|
||||
|
||||
def _validate(candidate):
|
||||
if not candidate:
|
||||
return []
|
||||
return title_validation.validate_titles(candidate["titles"], profile)
|
||||
|
||||
# Deterministic QA (PLAN #3): one re-ask if the critic's titles break the
|
||||
# channel rules, then keep the best attempt. Never blocks the response.
|
||||
picked = title_validation.run_with_validation(
|
||||
_critic, _validate, lambda violations: _critic(violations))
|
||||
if picked is None:
|
||||
print("⚠️ [Thumbnail] Critic failed, falling back to the brainstorm candidates.")
|
||||
picked = {"titles": candidates[:10], "thumbnail_texts": [], "recommended": []}
|
||||
|
||||
titles = picked["titles"]
|
||||
thumbnail_texts = [str(t) for t in picked.get("thumbnail_texts", [])][:len(titles)]
|
||||
thumbnail_texts += [""] * (len(titles) - len(thumbnail_texts))
|
||||
return {
|
||||
|
|
@ -189,9 +237,7 @@ OUTPUT JSON:
|
|||
"language": language,
|
||||
"segments": segments,
|
||||
"video_duration": video_duration,
|
||||
"recommended": [r for r in picked.get("recommended", [])
|
||||
if isinstance(r, dict) and isinstance(r.get("index"), int)
|
||||
and 0 <= r["index"] < len(titles)],
|
||||
"recommended": picked.get("recommended", []),
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -265,7 +311,7 @@ def extract_face_frames(video_path, session_id, n=5, samples=40):
|
|||
thumbnails dir. Returns [{"url", "path", "time", "face": [x, y, w, h]}].
|
||||
"""
|
||||
import cv2
|
||||
from main import detect_face_candidates
|
||||
from clipwright.pipeline.main import detect_face_candidates
|
||||
|
||||
out_dir = os.path.join("output", "thumbnails", session_id, "frames")
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
|
|
@ -369,11 +415,15 @@ def _crop_face_reference(frame_path, face_box, out_path):
|
|||
# ---------------------------------------------------------------------------
|
||||
|
||||
def plan_thumbnail_concepts(client, title, count, video_context="", extra_prompt="",
|
||||
thumbnail_text_hint="", has_person=False, language="en"):
|
||||
thumbnail_text_hint="", has_person=False, language="en",
|
||||
profile=None):
|
||||
"""
|
||||
One text call that designs `count` DIFFERENT thumbnails before any pixel is
|
||||
drawn. Asking the image model to invent the concept and render it in one
|
||||
go gives N variations of one idea; splitting it gives N ideas.
|
||||
|
||||
``profile`` (optional channel Profile, PLAN #1) adds the channel's palette,
|
||||
role order and presenter expectation; ``None`` leaves the prompt unchanged.
|
||||
"""
|
||||
person_line = ("A real photo of the presenter is provided and MUST be the focal point, "
|
||||
"with a clear, natural expression that reads at small size (no caricature)."
|
||||
|
|
@ -384,6 +434,8 @@ def plan_thumbnail_concepts(client, title, count, video_context="", extra_prompt
|
|||
hint_line = (f'\nSUGGESTED THUMBNAIL TEXT (use it for the first concept unless it is poor): "{thumbnail_text_hint}"'
|
||||
if thumbnail_text_hint else "")
|
||||
extra_line = f"\nMANDATORY USER INSTRUCTIONS (override everything else):\n{extra_prompt}\n" if extra_prompt else ""
|
||||
# Empty for profile=None, so the f-string below renders exactly as before.
|
||||
channel_rules = profile_prompts.thumbnail_block(profile)
|
||||
prompt = f"""You are a YouTube thumbnail art director. Design {count} DIFFERENT thumbnail concepts for this video.
|
||||
|
||||
VIDEO TITLE: "{title}"
|
||||
|
|
@ -393,17 +445,18 @@ VIDEO CONTEXT: {video_context or "(none)"}
|
|||
The thumbnail must show WHAT the video is about, not only how the presenter feels: name the concrete subject (the product, the tool, the result, the numbers) and build the picture around it. A face alone with two words is the lazy default; use it at most once, and only combined with a strong prop or scene.
|
||||
|
||||
Each concept must use a different device, e.g.: the presenter + a prop that IS the topic (a phone showing vertical clips, a laptop with the app, a counter/badge with the number); before/after or "long video -> short clips" split; product/UI hero shot with the presenter small; a giant number or stat as the hero with the subject behind; "X vs Y" comparison; a red circle/arrow on a detail; a dramatic reveal with depth (foreground object, blurred background). Layered, cinematic, premium: real props, depth of field, rim light, particles, glow on the key object. Never flat, never a plain wall behind the person. No two concepts may share the same text or the same layout.
|
||||
|
||||
{channel_rules}
|
||||
Per concept give:
|
||||
- "text": 1-4 words, ALL CAPS, in {language}. Complements the title (the title says what, the text says the emotion, the number or the twist). Never repeat the title. No emoji.
|
||||
- "text_position": one of "left", "right", "top", "bottom" (where the text block sits; the subject goes on the opposite side).
|
||||
- "text_color": "white" or "yellow" (yellow for money/energy, white otherwise).
|
||||
- "role": exactly one of "emotion", "technical", "curiosity" — the job this concept does for the click. Cover ALL THREE roles across the set (at least one of each): "emotion" is a human face or feeling, "technical" is the product, tool, code, diagram or concrete result, "curiosity" is a question, a reveal or a hidden detail.
|
||||
- "scene": a precise image-generation prompt in English, 2-4 sentences: subject, expression/pose, background, lighting, colours, camera. Say that the text_position side is clean negative space (simple, dark or plain) so a headline can sit there. It must NOT ask for any text, letters, captions or logos in the image.
|
||||
- The image model REFUSES prompts that name or depict real people, companies or brands. Never write a real name (person, company, product, logo) in "scene". Refer to the presenter only as "the person in the provided photo" when a photo is provided, otherwise as a generic, unnamed person or use objects and symbols.
|
||||
- "why": one short sentence on why this earns the click.
|
||||
|
||||
OUTPUT JSON:
|
||||
{{"concepts": [{{"text": "...", "text_position": "left", "text_color": "yellow", "scene": "...", "why": "..."}}, ...]}}"""
|
||||
{{"concepts": [{{"text": "...", "text_position": "left", "text_color": "yellow", "role": "emotion", "scene": "...", "why": "..."}}, ...]}}"""
|
||||
|
||||
response = client.models.generate_content(
|
||||
model=TEXT_MODEL,
|
||||
|
|
@ -415,32 +468,96 @@ OUTPUT JSON:
|
|||
except (json.JSONDecodeError, AttributeError):
|
||||
print(f"⚠️ [Thumbnail] Concept JSON unreadable, using a generic concept: {getattr(response, 'text', '')[:200]}")
|
||||
concepts = []
|
||||
return normalise_concepts(concepts, count, title, thumbnail_text_hint)
|
||||
role_order = list(profile.thumbnail.role_order) if profile else None
|
||||
return normalise_concepts(concepts, count, title, thumbnail_text_hint,
|
||||
role_order=role_order)
|
||||
|
||||
|
||||
def normalise_concepts(concepts, count, title, thumbnail_text_hint=""):
|
||||
"""Clamp model output to what the renderer accepts and pad to `count`."""
|
||||
# #4: every concept declares the job it does for the click, and the set must
|
||||
# cover emotion + technical. Kept here (not in the prompt alone) because a
|
||||
# prompt is not a contract.
|
||||
CONCEPT_ROLES = ("emotion", "technical", "curiosity")
|
||||
|
||||
_ROLE_SCENES = {
|
||||
"emotion": (
|
||||
"A dramatic, high-contrast YouTube thumbnail centred on a person's face and "
|
||||
"expression (surprise, focus or relief), warm rim light, blurred background, "
|
||||
"the {pos} side clean dark negative space."),
|
||||
"technical": (
|
||||
"A clean product/UI hero shot for a video titled '{title}': the tool, code, "
|
||||
"diagram or result sharp and large, cool cinematic light, the {pos} side "
|
||||
"clean dark negative space."),
|
||||
"curiosity": (
|
||||
"A cinematic reveal for a video titled '{title}': a key detail partly hidden "
|
||||
"or circled, depth of field, dramatic light, the {pos} side clean dark "
|
||||
"negative space."),
|
||||
}
|
||||
|
||||
|
||||
def _role_scene(role, title, position):
|
||||
template = _ROLE_SCENES.get(role, _ROLE_SCENES["curiosity"])
|
||||
return template.format(title=title, pos=position)
|
||||
|
||||
|
||||
def _fallback_concept(title, hint, role, position="left"):
|
||||
return {
|
||||
"text": (hint or "").upper()[:40],
|
||||
"text_position": position,
|
||||
"text_color": "white",
|
||||
"role": role,
|
||||
"scene": _role_scene(role, title, position),
|
||||
"why": f"fallback ({role})",
|
||||
}
|
||||
|
||||
|
||||
def normalise_concepts(concepts, count, title, thumbnail_text_hint="", role_order=None):
|
||||
"""Clamp model output to what the renderer accepts and pad to `count`.
|
||||
|
||||
Also enforces the #4 role mix: every concept carries a role and the set is
|
||||
guaranteed at least one "emotion" and one "technical" concept. A missing
|
||||
role is filled by converting the last available concept to a role-appropriate
|
||||
scene, so no concept is dropped.
|
||||
"""
|
||||
cleaned = []
|
||||
for c in concepts:
|
||||
if not isinstance(c, dict) or not c.get("scene"):
|
||||
continue
|
||||
role = c.get("role") if c.get("role") in CONCEPT_ROLES else None
|
||||
cleaned.append({
|
||||
"text": str(c.get("text") or thumbnail_text_hint or "").strip().upper()[:40],
|
||||
"text_position": c.get("text_position") if c.get("text_position") in TEXT_POSITIONS else "left",
|
||||
"text_color": "yellow" if c.get("text_color") == "yellow" else "white",
|
||||
"role": role,
|
||||
"scene": str(c["scene"]),
|
||||
"why": str(c.get("why", "")),
|
||||
})
|
||||
|
||||
order = [r for r in (role_order or []) if r in CONCEPT_ROLES] or list(CONCEPT_ROLES)
|
||||
while len(cleaned) < count:
|
||||
cleaned.append({
|
||||
"text": thumbnail_text_hint.upper()[:40],
|
||||
"text_position": "left",
|
||||
"text_color": "white",
|
||||
"scene": (f"A bold, high-contrast YouTube thumbnail scene for a video titled '{title}'. "
|
||||
"Dramatic lighting, vibrant colours, the left third is clean dark negative space."),
|
||||
"why": "fallback",
|
||||
})
|
||||
return cleaned[:count]
|
||||
role = order[len(cleaned) % len(order)]
|
||||
cleaned.append(_fallback_concept(title, thumbnail_text_hint, role))
|
||||
cleaned = cleaned[:count]
|
||||
|
||||
if count < 2:
|
||||
return cleaned
|
||||
|
||||
present = {c["role"] for c in cleaned}
|
||||
used: set[int] = set()
|
||||
for role in ("emotion", "technical"):
|
||||
if role in present:
|
||||
continue
|
||||
target = next((c for c in reversed(cleaned)
|
||||
if c["role"] is None and id(c) not in used), None)
|
||||
if target is None:
|
||||
target = next((c for c in reversed(cleaned) if id(c) not in used), None)
|
||||
if target is None:
|
||||
break
|
||||
used.add(id(target))
|
||||
target["role"] = role
|
||||
target["scene"] = _role_scene(role, title, target["text_position"])
|
||||
target["why"] = target["why"] or f"{role} concept"
|
||||
present.add(role)
|
||||
return cleaned
|
||||
|
||||
|
||||
def _wrap_lines(draw, text, font, max_width):
|
||||
|
|
@ -501,8 +618,46 @@ def burn_thumbnail_text(img, text, position="left", color="white"):
|
|||
else:
|
||||
x0, y0 = int(W * 0.04), H - total_h - int(H * 0.06) - top_pad
|
||||
|
||||
# Bottom-right safe area (#4): the headline must not sit under YouTube's
|
||||
# timestamp/badge corner nor run off the right edge. Whatever the requested
|
||||
# position, the rendered block is clamped inside the safe box.
|
||||
bottom_limit = int(H * (1.0 - THUMB_SAFE_BOTTOM))
|
||||
right_limit = int(W * (1.0 - THUMB_SAFE_RIGHT))
|
||||
left_limit = int(W * THUMB_SAFE_LEFT)
|
||||
top_limit = int(H * THUMB_SAFE_TOP)
|
||||
|
||||
center_x = W // 2
|
||||
ink_w = widest + stroke
|
||||
ink_h = total_h + stroke
|
||||
if horizontal:
|
||||
block_left, block_right = x0, x0 + ink_w
|
||||
else:
|
||||
block_left, block_right = center_x - ink_w // 2, center_x + ink_w // 2
|
||||
if block_right > right_limit:
|
||||
shift = block_right - right_limit
|
||||
if horizontal:
|
||||
x0 -= shift
|
||||
else:
|
||||
center_x -= shift
|
||||
if block_left < left_limit:
|
||||
shift = left_limit - block_left
|
||||
if horizontal:
|
||||
x0 += shift
|
||||
else:
|
||||
center_x += shift
|
||||
|
||||
visual_top = y0 + top_pad
|
||||
if visual_top < top_limit:
|
||||
y0 += top_limit - visual_top
|
||||
visual_top = top_limit
|
||||
if visual_top + ink_h > bottom_limit:
|
||||
y0 = bottom_limit - ink_h - top_pad
|
||||
y0 = max(y0, -top_pad) # keep the ink on the canvas
|
||||
|
||||
def line_x(line):
|
||||
return x0 if horizontal else (W - draw.textlength(line, font=font)) // 2
|
||||
if horizontal:
|
||||
return x0
|
||||
return center_x - int(draw.textlength(line, font=font)) // 2
|
||||
|
||||
shadow = Image.new("RGBA", img.size, (0, 0, 0, 0))
|
||||
sdraw = ImageDraw.Draw(shadow)
|
||||
|
|
@ -521,8 +676,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
|
||||
# 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
|
||||
# presenter. Videos get the mp4 `comment` tag (ffmpeg_utils.mark_ai_generated);
|
||||
# a JPEG's equivalent is XMP, and the interoperable vocabulary is IPTC's
|
||||
# presenter. Videos get an mp4 `comment` tag; a JPEG's equivalent is XMP, and
|
||||
# the interoperable vocabulary is IPTC's
|
||||
# DigitalSourceType, whose `trainedAlgorithmicMedia` value is what Google,
|
||||
# LinkedIn, TikTok and Adobe already read. Written alongside the EXIF Software
|
||||
# tag because the two survive different pipelines: a re-encode usually keeps
|
||||
|
|
@ -611,7 +766,7 @@ def _generate_one(client, concept, reference_images, out_path, burn_text):
|
|||
if burn_text:
|
||||
pos = concept['text_position']
|
||||
share = "45% of the width" if pos in ("left", "right") else "40% of the height"
|
||||
text_rule = ("Do NOT render any text, letters, numbers, captions, logos or watermarks anywhere "
|
||||
text_rule = ("Do NOT render any text, letters, numbers, captions, logos or branding marks anywhere "
|
||||
f"in the image. The {pos} {share} of the frame must be clean, simple negative space "
|
||||
"(plain, dark or softly blurred, no objects, no detail): a headline will be placed "
|
||||
"there afterwards. Put the subject and every object in the remaining part.")
|
||||
|
|
@ -625,7 +780,7 @@ def _generate_one(client, concept, reference_images, out_path, burn_text):
|
|||
|
||||
{text_rule}
|
||||
|
||||
Style: high contrast, saturated colours, crisp subject separation, cinematic lighting, sharp focus on the subject, readable at 168x94 pixels. No clutter, no small details, no borders, no watermark."""
|
||||
Style: high contrast, saturated colours, crisp subject separation, cinematic lighting, sharp focus on the subject, readable at 168x94 pixels. No clutter, no small details, no borders, no branding mark."""
|
||||
if reference_images:
|
||||
prompt += ("\nIDENTITY: the person in the provided photo must appear as EXACTLY the same real person: "
|
||||
"identical face shape, skin, eyes, glasses, facial hair, hairstyle and hair length, age and "
|
||||
|
|
@ -662,11 +817,13 @@ Style: high contrast, saturated colours, crisp subject separation, cinematic lig
|
|||
|
||||
def generate_thumbnail(api_key, title, session_id, face_image_path=None, bg_image_path=None,
|
||||
extra_prompt="", count=3, video_context="", burn_text=True,
|
||||
thumbnail_text_hint="", language="en", frame_reference=None):
|
||||
thumbnail_text_hint="", language="en", frame_reference=None,
|
||||
profile=None):
|
||||
"""
|
||||
Generates `count` thumbnails, each from its own concept, in parallel.
|
||||
frame_reference: {"path", "face"} from extract_face_frames, used as the
|
||||
person reference when the user picked a frame instead of uploading a photo.
|
||||
profile: optional channel Profile (PLAN #1), forwarded to the concept call.
|
||||
Returns [{"url", "text", "why"}] (only the ones that rendered).
|
||||
"""
|
||||
client = genai.Client(api_key=api_key)
|
||||
|
|
@ -687,7 +844,8 @@ def generate_thumbnail(api_key, title, session_id, face_image_path=None, bg_imag
|
|||
|
||||
concepts = plan_thumbnail_concepts(
|
||||
client, title, count, video_context=video_context, extra_prompt=extra_prompt,
|
||||
thumbnail_text_hint=thumbnail_text_hint, has_person=bool(reference_images), language=language)
|
||||
thumbnail_text_hint=thumbnail_text_hint, has_person=bool(reference_images),
|
||||
language=language, profile=profile)
|
||||
for i, c in enumerate(concepts):
|
||||
print(f"🎨 [Thumbnail] Concept {i + 1}: \"{c['text']}\" ({c['text_position']}) - {c['why']}")
|
||||
|
||||
|
|
@ -719,7 +877,8 @@ def generate_thumbnail(api_key, title, session_id, face_image_path=None, bg_imag
|
|||
fallback = True
|
||||
print(f"✅ [Thumbnail] Saved: {out_path}")
|
||||
return {"url": f"/thumbnails/{session_id}/{os.path.basename(out_path)}",
|
||||
"text": concept["text"], "why": concept["why"], "fallback": fallback}
|
||||
"text": concept["text"], "why": concept["why"],
|
||||
"role": concept.get("role"), "fallback": fallback}
|
||||
except Exception as e:
|
||||
print(f"❌ [Thumbnail] Generation {i + 1} failed: {e}")
|
||||
return {"error": str(e)}
|
||||
|
|
@ -738,9 +897,12 @@ def generate_thumbnail(api_key, title, session_id, face_image_path=None, bg_imag
|
|||
# Description
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def generate_youtube_description(api_key, title, transcript_segments, language, video_duration):
|
||||
def generate_youtube_description(api_key, title, transcript_segments, language, video_duration,
|
||||
profile=None):
|
||||
"""
|
||||
Uses Gemini to generate a YouTube description with chapter markers from transcript segments.
|
||||
``profile`` (optional channel Profile, PLAN #1) adds the channel's description
|
||||
structure, links and tone; ``None`` leaves the prompt unchanged.
|
||||
Returns: { "description": "full description text with chapters" }
|
||||
"""
|
||||
client = genai.Client(api_key=api_key)
|
||||
|
|
@ -761,6 +923,9 @@ def generate_youtube_description(api_key, title, transcript_segments, language,
|
|||
dur_secs = int(video_duration % 60)
|
||||
duration_str = f"{dur_mins}:{dur_secs:02d}"
|
||||
|
||||
# Empty for profile=None, so the f-string below renders exactly as before.
|
||||
channel_rules = profile_prompts.description_block(profile)
|
||||
|
||||
prompt = f"""You are a YouTube SEO expert. Generate a complete YouTube video description for the following video.
|
||||
|
||||
VIDEO TITLE: "{title}"
|
||||
|
|
@ -782,7 +947,7 @@ REQUIREMENTS:
|
|||
- Place chapters in their own section with a blank line before and after
|
||||
5. Add 5-10 relevant hashtags at the end
|
||||
6. Keep the total description under 5000 characters
|
||||
|
||||
{channel_rules}
|
||||
OUTPUT: Return ONLY the description text (no JSON wrapper, no markdown code blocks). The description should be ready to paste directly into YouTube."""
|
||||
|
||||
print("🤖 [Thumbnail] Generating YouTube description with chapters...")
|
||||
170
clipwright/media/title_validation.py
Normal file
170
clipwright/media/title_validation.py
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
"""Deterministic YouTube title QA (PLAN #3 + #4, merged).
|
||||
|
||||
No LLM call lives here: the rules are the active channel profile's
|
||||
``title_rules`` plus a few universal structural checks, so validation is cheap
|
||||
enough to run on every generated title and cannot itself hallucinate.
|
||||
|
||||
Two entry points:
|
||||
* :func:`validate_title` / :func:`validate_titles` return the list of human-
|
||||
readable violations for one title, or for a set (structural rules).
|
||||
* :func:`run_with_validation` wraps generation: try, and on violations re-ask
|
||||
exactly once with the critique; if the retry does not improve, keep the first
|
||||
attempt. It NEVER raises on a validation failure and never blocks the job.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections import Counter
|
||||
|
||||
from clipwright.pipeline.profiles import Profile
|
||||
|
||||
# Task-descriptive openers that describe what the video *does* rather than what
|
||||
# the viewer gets. The profile's ``banned_openers`` add the channel's own.
|
||||
_TASK_OPENERS = (
|
||||
"in this video", "in today's video", "this video", "explaining", "discussing",
|
||||
"talking about", "a look at", "let's", "watch me", "i'm going to",
|
||||
"im going to", "here's how i", "step by step",
|
||||
)
|
||||
_TASK_OPENER_RE = re.compile(
|
||||
r"^(?:" + "|".join(re.escape(o) for o in _TASK_OPENERS) + r")\b", re.I)
|
||||
|
||||
# Words that carry no topic, so a title starting with one has not front-loaded
|
||||
# its keyword. This is the deterministic proxy for ``keyword_position="start"``
|
||||
# (the profile carries no keyword to locate precisely).
|
||||
_STOPWORDS = frozenset({
|
||||
"the", "a", "an", "this", "that", "these", "those", "my", "your", "our",
|
||||
"their", "his", "her", "its", "it", "i", "we", "you", "they", "he", "she",
|
||||
"is", "are", "was", "were", "be", "been", "being", "as", "if", "when",
|
||||
"while", "so", "just", "in", "on", "at", "of", "for", "to", "with", "from",
|
||||
"by", "and", "but", "or",
|
||||
})
|
||||
|
||||
# Broad cue sets for required_signal. Deliberately generous: a false negative
|
||||
# would force a retry, and a false positive only lets a weaker title through.
|
||||
_CONSEQUENCE_RE = re.compile(
|
||||
r"\b(why|because|so that|cost|costs|costing|ruin|ruined|ruins|broke|broken|"
|
||||
r"breaks|lost|lose|loses|win|won|wins|crashed|crash|crashes|fail|failed|"
|
||||
r"fails|failure|change|changed|changes|makes|made|turns|turned|becomes|became|"
|
||||
r"stops|stopped|kills|killed|destroy|destroyed|saved|saves|before|after|"
|
||||
r"mistake|mistakes|warning|warns|secretly|almost|never again|no longer|"
|
||||
r"instead)\b", re.I)
|
||||
_CURIOSITY_RE = re.compile(
|
||||
r"\?|\b(why|how|what|secret|truth|real reason|reason|hidden|nobody|everyone|"
|
||||
r"no one|shouldn'?t|should not|impossible|actually|forgot|forgotten|never|"
|
||||
r"finally|revealed|reveal|mystery|unknown|here'?s|looks like|seems)\b", re.I)
|
||||
|
||||
|
||||
def _first_word(title: str) -> str:
|
||||
match = re.match(r"\s*([A-Za-zÀ-ÿ0-9']+)", title or "")
|
||||
return match.group(1).lower() if match else ""
|
||||
|
||||
|
||||
def validate_title(title: str, profile: Profile | None) -> list[str]:
|
||||
"""Every reason this one title breaks the profile's title rules.
|
||||
|
||||
Structural checks (task-descriptive openers) run with or without a profile;
|
||||
the profile-specific checks are skipped when ``profile`` is None.
|
||||
"""
|
||||
title = (title or "").strip()
|
||||
if not title:
|
||||
return ["title is empty"]
|
||||
|
||||
problems: list[str] = []
|
||||
rules = getattr(profile, "title_rules", None)
|
||||
if rules is not None:
|
||||
if len(title) > rules.max_chars:
|
||||
problems.append(f"{len(title)} chars exceeds the {rules.max_chars}-char maximum")
|
||||
elif len(title) > rules.mobile_chars:
|
||||
problems.append(
|
||||
f"{len(title)} chars exceeds the {rules.mobile_chars}-char mobile limit")
|
||||
lowered = title.lower()
|
||||
for pattern in rules.banned_patterns:
|
||||
if pattern.lower() in lowered:
|
||||
problems.append(f'uses the banned phrase "{pattern}"')
|
||||
for opener in rules.banned_openers:
|
||||
if lowered.startswith(opener.lower()):
|
||||
problems.append(f'opens with the banned opener "{opener}"')
|
||||
break
|
||||
first = _first_word(title)
|
||||
if rules.keyword_position == "start" and first in _STOPWORDS:
|
||||
problems.append(f'starts with the filler word "{first}" instead of the keyword')
|
||||
if rules.number_policy == "avoid" and re.search(r"\d", title):
|
||||
problems.append("uses a number where the channel avoids them")
|
||||
elif rules.number_policy == "require" and not re.search(r"\d", title):
|
||||
problems.append("has no number, which this channel requires")
|
||||
signal = rules.required_signal
|
||||
consequence = bool(_CONSEQUENCE_RE.search(title))
|
||||
curiosity = bool(_CURIOSITY_RE.search(title))
|
||||
if signal == "consequence" and not consequence:
|
||||
problems.append("carries no consequence or stake")
|
||||
elif signal == "curiosity" and not curiosity:
|
||||
problems.append("opens no curiosity gap the video pays off")
|
||||
elif signal == "either" and not (consequence or curiosity):
|
||||
problems.append("carries no consequence or curiosity signal")
|
||||
|
||||
if _TASK_OPENER_RE.match(title):
|
||||
problems.append("opens with a task-descriptive phrase")
|
||||
return problems
|
||||
|
||||
|
||||
def validate_titles(titles, profile: Profile | None) -> list[str]:
|
||||
"""Per-title violations plus the structural rules that span a title set."""
|
||||
clean = [t for t in (titles or []) if isinstance(t, str) and t.strip()]
|
||||
problems: list[str] = []
|
||||
for i, title in enumerate(clean):
|
||||
for problem in validate_title(title, profile):
|
||||
problems.append(f"title {i + 1}: {problem}")
|
||||
|
||||
if not clean:
|
||||
problems.append("no titles")
|
||||
|
||||
firsts = Counter(_first_word(t) for t in clean)
|
||||
for word, count in firsts.items():
|
||||
if word and count > 3:
|
||||
problems.append(f'{count} titles start with the same word "{word}" (max 3)')
|
||||
colons = sum(1 for t in clean if ":" in t)
|
||||
if colons > 2:
|
||||
problems.append(f"{colons} titles use a colon pattern (max 2)")
|
||||
return problems
|
||||
|
||||
|
||||
def critique_block(violations) -> str:
|
||||
"""An instruction block that hands the model the exact violations to fix."""
|
||||
lines = ["VALIDATION FAILED — the previous titles broke these rules:"]
|
||||
lines += [f"- {v}" for v in violations]
|
||||
lines.append("Rewrite the titles so every rule passes; keep every other instruction.")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def run_with_validation(generate, validate, retry_once):
|
||||
"""Try ``generate``; on violations re-ask exactly once and keep the best.
|
||||
|
||||
``generate()`` -> candidate
|
||||
``validate(candidate)`` -> list of violations
|
||||
``retry_once(violations)`` -> a new candidate, or None if it could not run
|
||||
|
||||
Returns the candidate with the fewest violations (the first one on a tie or
|
||||
a failed retry). Never raises because of a validation failure.
|
||||
"""
|
||||
candidate = generate()
|
||||
violations = list(validate(candidate) or [])
|
||||
if not violations:
|
||||
return candidate
|
||||
|
||||
try:
|
||||
retry = retry_once(violations)
|
||||
except Exception as e: # a broken retry must not lose the first attempt
|
||||
print(f"⚠️ [titles] validation retry failed ({e}); keeping the first attempt.")
|
||||
return candidate
|
||||
if retry is None:
|
||||
return candidate
|
||||
|
||||
retry_violations = list(validate(retry) or [])
|
||||
if len(retry_violations) < len(violations):
|
||||
print(f"✅ [titles] retry reduced violations "
|
||||
f"{len(violations)} -> {len(retry_violations)}.")
|
||||
return retry
|
||||
print(f"⚠️ [titles] retry did not improve "
|
||||
f"({len(violations)} -> {len(retry_violations)}); keeping the first attempt.")
|
||||
return candidate
|
||||
1
clipwright/pipeline/__init__.py
Normal file
1
clipwright/pipeline/__init__.py
Normal file
|
|
@ -0,0 +1 @@
|
|||
"""Clipwright backend."""
|
||||
207
clipwright/pipeline/bridge.py
Normal file
207
clipwright/pipeline/bridge.py
Normal file
|
|
@ -0,0 +1,207 @@
|
|||
"""Shorts -> long-form bridge copy (PLAN #6).
|
||||
|
||||
Pure, network-free helpers that turn the active channel profile (+ its
|
||||
``published_video_history``) into the copy a Short needs to funnel viewers to a
|
||||
long-form video:
|
||||
|
||||
* ``description_bridge`` -- a block appended to the Short's YouTube description;
|
||||
* ``first_comment`` -- the top-level comment to post (and pin).
|
||||
|
||||
Two "related video" features are Studio-UI only and are **not** exposed by any
|
||||
API: the Shorts "Related video" link and comment pinning. Those therefore stay
|
||||
manual, and ``checklist`` spells out the exact Studio steps including the
|
||||
target long-form URL.
|
||||
|
||||
The explicit target wins over the profile history. Callers pass it from the CLI
|
||||
(``--longform-url``) or the API (``related_video_url``); nothing here performs
|
||||
I/O.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Mapping, Optional
|
||||
|
||||
from clipwright.pipeline import profile_prompts
|
||||
from clipwright.pipeline.profiles import Profile
|
||||
|
||||
# Fallback label when the target URL is provided but the profile says nothing.
|
||||
DEFAULT_TARGET_LABEL = "Full video"
|
||||
|
||||
# Keys a published_video_history entry may carry to identify the video. The
|
||||
# first match wins; ``id``/``video_id`` build a watch URL.
|
||||
_URL_KEYS = ("url", "video_url", "watch_url", "link")
|
||||
_ID_KEYS = ("id", "video_id", "youtube_id")
|
||||
_DATE_KEYS = ("published_at", "published", "date", "uploaded_at")
|
||||
|
||||
|
||||
def _entry_url(entry: Mapping) -> Optional[str]:
|
||||
"""The watch URL for one ``published_video_history`` entry, or None."""
|
||||
if not isinstance(entry, Mapping):
|
||||
return None
|
||||
for key in _URL_KEYS:
|
||||
value = entry.get(key)
|
||||
if isinstance(value, str) and value.strip():
|
||||
return value.strip()
|
||||
for key in _ID_KEYS:
|
||||
value = entry.get(key)
|
||||
if isinstance(value, str) and value.strip():
|
||||
return f"https://www.youtube.com/watch?v={value.strip()}"
|
||||
return None
|
||||
|
||||
|
||||
def _entry_sort_key(entry: Mapping) -> str:
|
||||
for key in _DATE_KEYS:
|
||||
value = entry.get(key)
|
||||
if isinstance(value, str) and value.strip():
|
||||
return value.strip()
|
||||
return ""
|
||||
|
||||
|
||||
def target_video(profile: Optional[Profile],
|
||||
related_video_url: Optional[str] = None) -> Optional[str]:
|
||||
"""The long-form target: the explicit URL, else the newest history entry.
|
||||
|
||||
An explicit ``related_video_url`` always wins. Otherwise the profile's
|
||||
``published_video_history`` is searched for an entry that names a video
|
||||
(``url``/``video_url``/... or an ``id``); the newest by a best-effort date
|
||||
field is chosen, falling back to the last entry listed.
|
||||
"""
|
||||
if isinstance(related_video_url, str) and related_video_url.strip():
|
||||
return related_video_url.strip()
|
||||
history = list(getattr(profile, "published_video_history", None) or [])
|
||||
candidates = [(k, e) for e in history if (k := _entry_url(e))]
|
||||
if not candidates:
|
||||
return None
|
||||
candidates.sort(key=lambda pair: _entry_sort_key(pair[1]))
|
||||
return candidates[-1][0]
|
||||
|
||||
|
||||
def _target_label(profile: Optional[Profile]) -> str:
|
||||
"""A human label for the target, derived from the profile's description."""
|
||||
template = getattr(profile, "description_template", "") if profile else ""
|
||||
# Templates look like "{hook}\n\nFull video: {link}\n\n#tags" -- lift the
|
||||
# words before "{link}" when they name the long-form video.
|
||||
if "{link}" in template:
|
||||
prefix = template.split("{link}")[0].strip().splitlines()[-1].strip()
|
||||
prefix = prefix.rstrip(":").strip()
|
||||
if prefix and "{hook}" not in prefix:
|
||||
return prefix
|
||||
return DEFAULT_TARGET_LABEL
|
||||
|
||||
|
||||
def _clip_hook(clip: Optional[Mapping]) -> str:
|
||||
"""The clip's hook text if the pipeline produced one, else its title."""
|
||||
if not isinstance(clip, Mapping):
|
||||
return ""
|
||||
for key in ("viral_hook_text", "hook_text", "video_title_for_youtube_short"):
|
||||
value = clip.get(key)
|
||||
if isinstance(value, str) and value.strip():
|
||||
return value.strip()
|
||||
return ""
|
||||
|
||||
|
||||
def _render_description_template(template: str, target: Optional[str],
|
||||
clip: Optional[Mapping]) -> str:
|
||||
"""Fill the profile's ``{hook}``/``{link}`` slots without str.format.
|
||||
|
||||
``str.format`` would explode on any other brace in the template (or
|
||||
hashtags that are fine today); a literal replace can only touch the two
|
||||
documented placeholders.
|
||||
"""
|
||||
rendered = template.replace("{hook}", _clip_hook(clip))
|
||||
rendered = rendered.replace("{link}", target or "")
|
||||
return "\n".join(line.rstrip() for line in rendered.splitlines()).strip()
|
||||
|
||||
|
||||
def description_bridge(profile: Optional[Profile],
|
||||
related_video_url: Optional[str] = None,
|
||||
clip: Optional[Mapping] = None) -> str:
|
||||
"""The description block: a target CTA plus the profile's description copy.
|
||||
|
||||
The target URL appears first (and in the rendered template when the profile
|
||||
has one). Without a target the channel links/description still render, so a
|
||||
bridge is produced even before a long-form URL is chosen.
|
||||
"""
|
||||
target = target_video(profile, related_video_url)
|
||||
parts: list[str] = []
|
||||
if target:
|
||||
parts.append(f"▶ {_target_label(profile)}: {target}")
|
||||
|
||||
template = (getattr(profile, "description_template", "") if profile else "") or ""
|
||||
rendered = _render_description_template(template, target, clip) if template else ""
|
||||
if rendered:
|
||||
parts.append(rendered)
|
||||
else:
|
||||
# No template: fall back to the profile's plain description block.
|
||||
block = profile_prompts.description_block(profile) if profile else ""
|
||||
if block:
|
||||
parts.append(block.rstrip())
|
||||
|
||||
# The profile's links belong in the bridge even when the template's {link}
|
||||
# slot was empty (no target yet) or the template does not mention them.
|
||||
links = [link for link in (getattr(profile, "links", None) or [])
|
||||
if isinstance(link, str) and link.strip()]
|
||||
if links and not any(link in "\n".join(parts) for link in links):
|
||||
parts.append("More from this channel: " + " | ".join(links))
|
||||
|
||||
return "\n\n".join(p for p in parts if p).strip()
|
||||
|
||||
|
||||
def first_comment(profile: Optional[Profile],
|
||||
related_video_url: Optional[str] = None,
|
||||
clip: Optional[Mapping] = None) -> str:
|
||||
"""The top-level comment text. Always carries the long-form reference.
|
||||
|
||||
With no target it points at the channel's links (or the description) rather
|
||||
than inventing a URL; it is never empty.
|
||||
"""
|
||||
target = target_video(profile, related_video_url)
|
||||
hook = _clip_hook(clip)
|
||||
if target:
|
||||
text = f"▶ {_target_label(profile)}: {target}"
|
||||
if hook:
|
||||
text += f"\n\n{_target_label(profile)} covers this: {hook}"
|
||||
return text
|
||||
links = list(getattr(profile, "links", None) or [])
|
||||
if links:
|
||||
return f"Watch the long-form videos here: {links[0]}"
|
||||
return "The full long-form video is linked in the description."
|
||||
|
||||
|
||||
def checklist(profile: Optional[Profile],
|
||||
related_video_url: Optional[str] = None) -> list[str]:
|
||||
"""The manual Studio steps for this Short (both are Studio-UI only).
|
||||
|
||||
The Shorts "Related video" link and comment pinning have no public API, so
|
||||
they are copy-paste steps, not something the server can do.
|
||||
"""
|
||||
target = target_video(profile, related_video_url)
|
||||
target_text = target or "<paste the long-form video URL>"
|
||||
return [
|
||||
"Open YouTube Studio -> Content -> this Short -> Edit.",
|
||||
f"Details -> Related video: set it to {target_text} "
|
||||
"(the Shorts related-video link is Studio-UI only; no API can set it).",
|
||||
"Post the generated first comment "
|
||||
"(or call this clip's bridge/comment endpoint if the YouTube Data API "
|
||||
"is configured).",
|
||||
"Pin the first comment: hover it -> the three-dot menu -> Pin. "
|
||||
"Pinning stays manual (no API).",
|
||||
]
|
||||
|
||||
|
||||
def build_bridge(profile: Optional[Profile],
|
||||
clip: Optional[Mapping] = None,
|
||||
related_video_url: Optional[str] = None) -> dict[str, Any]:
|
||||
"""All bridge fields for one clip, ready to merge into clip metadata.
|
||||
|
||||
``related_video_url`` is the explicit target (CLI ``--longform-url`` / API
|
||||
``related_video_url``); when omitted the profile history is used.
|
||||
"""
|
||||
target = target_video(profile, related_video_url)
|
||||
return {
|
||||
"related_video_url": target,
|
||||
"description_bridge": description_bridge(profile, target, clip),
|
||||
"first_comment": first_comment(profile, target, clip),
|
||||
"checklist": checklist(profile, target),
|
||||
"manual_pin_required": True,
|
||||
}
|
||||
|
|
@ -5,6 +5,8 @@ Standard-library only so both main.py and gemini_worker.py can import it and
|
|||
the logic stays unit-testable without the heavy video dependencies.
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
# USD per 1M tokens (input, output incl. thinking), from ai.google.dev pricing.
|
||||
MODEL_PRICES = {
|
||||
"gemini-3.5-flash": (1.50, 9.00),
|
||||
|
|
@ -188,18 +190,6 @@ def clip_duration_bounds():
|
|||
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,
|
||||
window_seconds=90, overlap_seconds=30):
|
||||
"""
|
||||
|
|
@ -360,3 +350,185 @@ def snap_clip_to_words(start, end, words, video_duration,
|
|||
if new_end <= new_start or new_end - new_start < min_duration:
|
||||
return original
|
||||
return (round(new_start, 3), round(new_end, 3))
|
||||
|
||||
|
||||
# --- Hook-first boundaries (#2a) -------------------------------------------
|
||||
# The first seconds decide the swipe. A model-proposed clip routinely opens on
|
||||
# wind-up ("so today we're going to...") and buries the question, the number or
|
||||
# the stakes 3-8s in. Word timestamps are ground truth, so the start can be
|
||||
# moved onto the first strong spoken hook deterministically — no LLM, no key.
|
||||
#
|
||||
# These are the signal vocabularies the scan combines. A token matching ANY set
|
||||
# is a hook; the EARLIEST such token inside the allowed trim window wins. They
|
||||
# are deliberately conservative: a miss leaves the clip untouched, a false
|
||||
# positive only advances the start a bounded amount (see the env caps).
|
||||
_HOOK_INTERROGATIVES = frozenset({
|
||||
"what", "why", "how", "when", "where", "who", "whom", "whose", "which",
|
||||
"is", "are", "was", "were", "do", "does", "did", "can", "could", "would",
|
||||
"should", "will", "shall",
|
||||
})
|
||||
_HOOK_IMPERATIVES = frozenset({
|
||||
"look", "watch", "imagine", "think", "stop", "try", "check", "see",
|
||||
"listen", "remember", "forget", "consider", "notice", "suppose", "picture",
|
||||
"keep", "take", "put", "go", "come", "use", "make", "let", "dont", "show",
|
||||
"tell", "explain", "build", "create", "write", "read", "open", "close",
|
||||
"click", "press", "type", "install", "run", "fix", "never", "always",
|
||||
})
|
||||
_HOOK_NUMBERS = frozenset({
|
||||
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
|
||||
"nine", "ten", "eleven", "twelve", "hundred", "thousand", "million",
|
||||
"billion", "half", "quarter", "twice", "once", "double", "triple",
|
||||
"dozen", "percent", "first", "second", "third",
|
||||
})
|
||||
_HOOK_CONTRAST = frozenset({
|
||||
"but", "until", "actually", "instead", "except", "however", "though",
|
||||
"although", "whereas", "yet", "still", "suddenly", "wait", "unless",
|
||||
"otherwise", "despite", "nevertheless", "contrary", "opposite", "reverse",
|
||||
})
|
||||
_HOOK_STAKES = frozenset({
|
||||
"never", "always", "first", "worst", "bug", "bugs", "crash", "crashes",
|
||||
"crashed", "crashing", "broke", "broken", "break", "wrong", "lost", "lose",
|
||||
"losing", "fail", "failed", "fails", "failure", "dies", "death", "dead",
|
||||
"kill", "killed", "destroy", "destroyed", "ruin", "ruined", "disaster",
|
||||
"mistake", "error", "errors", "segfault", "danger", "dangerous", "scared",
|
||||
"terrified", "panic", "emergency", "critical", "fatal", "illegal",
|
||||
"corrupt", "corrupted", "hacked", "stolen", "missing", "gone", "worse",
|
||||
})
|
||||
# Pure hesitation / connective words that are never hooks. The scan simply
|
||||
# walks past them, so they end up in the trimmed wind-up; they must not count.
|
||||
_HOOK_FILLER = frozenset({
|
||||
"uh", "um", "erm", "ah", "eh", "hmm", "mmm", "so", "well", "okay", "ok",
|
||||
"yeah", "yep", "right", "and", "then", "like", "basically", "just",
|
||||
"you", "know", "i", "mean", "we", "the", "a", "an", "it", "that", "this",
|
||||
})
|
||||
|
||||
# Conservative defaults: HOOK_FIRST is on, but a start only ever moves a few
|
||||
# seconds and never more than a quarter of the clip.
|
||||
_HOOK_FIRST_DEFAULT_MAX_TRIM = 4.0
|
||||
_HOOK_FIRST_DEFAULT_MAX_FRACTION = 0.25
|
||||
# A trim smaller than this is noise; leaving the clip alone is kinder than a
|
||||
# sub-frame jitter that only complicates the render.
|
||||
_MIN_HOOK_TRIM = 0.2
|
||||
|
||||
|
||||
def _env_float(name, default):
|
||||
"""Read a float env var, falling back to ``default`` on garbage/absence."""
|
||||
import os
|
||||
|
||||
raw = os.environ.get(name)
|
||||
if raw is None or str(raw).strip() == "":
|
||||
return default
|
||||
try:
|
||||
return float(raw)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def hook_first_enabled():
|
||||
"""Whether to move clip starts onto the first spoken hook.
|
||||
|
||||
``HOOK_FIRST`` defaults ON (conservatively capped); set it to ``0`` /
|
||||
``false`` / ``no`` / ``off`` to disable the pass for A/B runs.
|
||||
"""
|
||||
import os
|
||||
|
||||
raw = os.environ.get("HOOK_FIRST")
|
||||
if raw is None:
|
||||
return True
|
||||
return str(raw).strip().lower() not in ("", "0", "false", "no", "off")
|
||||
|
||||
|
||||
def _hook_token(raw):
|
||||
"""Normalise a Whisper word to a bare lowercase token.
|
||||
|
||||
Words are inconsistent about a leading space (" word" vs "word") and carry
|
||||
trailing punctuation ("crash!"), so both are stripped before matching.
|
||||
"""
|
||||
token = str(raw or "").strip().lower()
|
||||
token = re.sub(r"^[^0-9a-z]+", "", token)
|
||||
token = re.sub(r"[^0-9a-z]+$", "", token)
|
||||
return token
|
||||
|
||||
|
||||
def _is_hook_token(token):
|
||||
"""True when a normalised token carries one of the hook signals."""
|
||||
if not token or token in _HOOK_FILLER:
|
||||
return False
|
||||
if any(ch.isdigit() for ch in token):
|
||||
return True
|
||||
return (token in _HOOK_INTERROGATIVES
|
||||
or token in _HOOK_IMPERATIVES
|
||||
or token in _HOOK_NUMBERS
|
||||
or token in _HOOK_CONTRAST
|
||||
or token in _HOOK_STAKES)
|
||||
|
||||
|
||||
def find_hook_start(words, clip_start, clip_end, min_duration=15.0,
|
||||
max_trim=None, max_fraction=None):
|
||||
"""The strongest deterministic start for a clip, or ``None``.
|
||||
|
||||
Scans the opening of ``[clip_start, clip_end]`` for the EARLIEST word that
|
||||
matches a hook signal (question, imperative, number/quantity, contrast or
|
||||
stakes — see the vocabularies above). Leading hesitation, silence and
|
||||
filler do not match, so they fall into the trimmed wind-up. Returns the
|
||||
hook word's start when it is a legal trim, else ``None`` (no change — a
|
||||
clip without a clear hook is left exactly where snapping put it).
|
||||
|
||||
``words`` is the whole-video ``[{'w','s','e'}, ...]`` list (same shape
|
||||
``snap_clip_to_words`` takes). The trim is bounded three ways so the pass
|
||||
can never wreck a clip:
|
||||
|
||||
* ``max_trim`` seconds (env ``HOOK_FIRST_MAX_TRIM``, default 4.0)
|
||||
* ``max_fraction`` of the clip's duration (env ``HOOK_FIRST_MAX_FRACTION``,
|
||||
default 0.25)
|
||||
* the remaining clip must still be at least ``min_duration`` seconds.
|
||||
"""
|
||||
try:
|
||||
clip_start = float(clip_start)
|
||||
clip_end = float(clip_end)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
duration = clip_end - clip_start
|
||||
if duration <= 0:
|
||||
return None
|
||||
|
||||
if max_trim is None:
|
||||
max_trim = _env_float("HOOK_FIRST_MAX_TRIM",
|
||||
_HOOK_FIRST_DEFAULT_MAX_TRIM)
|
||||
if max_fraction is None:
|
||||
max_fraction = _env_float("HOOK_FIRST_MAX_FRACTION",
|
||||
_HOOK_FIRST_DEFAULT_MAX_FRACTION)
|
||||
try:
|
||||
max_trim = max(0.0, float(max_trim))
|
||||
max_fraction = max(0.0, float(max_fraction))
|
||||
min_duration = float(min_duration)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
cap = min(max_trim, max_fraction * duration)
|
||||
if cap < _MIN_HOOK_TRIM:
|
||||
return None
|
||||
latest = clip_start + cap
|
||||
|
||||
hook_start = None
|
||||
for word in words or []:
|
||||
try:
|
||||
word_start = float(word.get("s", 0))
|
||||
except (AttributeError, TypeError, ValueError):
|
||||
continue
|
||||
if word_start < clip_start or word_start > latest:
|
||||
continue
|
||||
if word_start >= clip_end:
|
||||
continue
|
||||
if _is_hook_token(_hook_token(word.get("w"))):
|
||||
if hook_start is None or word_start < hook_start:
|
||||
hook_start = word_start
|
||||
|
||||
if hook_start is None:
|
||||
return None
|
||||
trim = hook_start - clip_start
|
||||
if trim < _MIN_HOOK_TRIM:
|
||||
return None
|
||||
if clip_end - hook_start < min_duration:
|
||||
return None
|
||||
return round(hook_start, 3)
|
||||
|
|
@ -1,4 +1,3 @@
|
|||
import argparse
|
||||
import json
|
||||
import mimetypes
|
||||
import os
|
||||
|
|
@ -6,12 +5,10 @@ import sys
|
|||
from typing import List, Optional
|
||||
|
||||
from dotenv import load_dotenv
|
||||
from google import genai
|
||||
from google.genai import types as genai_types
|
||||
from pydantic import BaseModel
|
||||
|
||||
from clip_selection import (clip_count_targets, clip_duration_bounds,
|
||||
lookup_model_prices)
|
||||
from clipwright.pipeline.clip_selection import lookup_model_prices
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
|
@ -160,6 +157,13 @@ Pick ONE layout:
|
|||
in both runs, while overall accuracy fell from 92% to 83-85%. camera_inset.py
|
||||
finds the same five geometrically with no false positives, so that question is
|
||||
answered downstream instead of being asked here.)
|
||||
- "code": a screen recording of code — an IDE or a terminal — where the viewer
|
||||
must read the source itself (a programming tutorial, a live debug, a shell
|
||||
session). ONLY when monospaced text fills the screen and reading it is the
|
||||
point; a slide or a spreadsheet is "screencast", not this. This option is
|
||||
UNVALIDATED: it was added for a CODE layout that is off by default
|
||||
(CODE_LAYOUT) and must be shadow-run on a corpus before it is relied on. When
|
||||
unsure, answer "none" or "screencast".
|
||||
- "split": stack two people. ONLY when two people are visible IN THE SAME SHOT
|
||||
at the same time in most frames, talking to each other. Frames that alternate
|
||||
between one-person close-ups are NOT this, however many people appear.
|
||||
|
|
@ -225,17 +229,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:
|
||||
stream = sys.stdout
|
||||
text = str(message)
|
||||
|
|
@ -337,7 +330,7 @@ COPY RULES — ALL text fields (descriptions, title, hook) MUST be written in TR
|
|||
- `why`: one sentence, max 20 words, naming what makes THIS moment worth a
|
||||
clip — the specific hook, claim, number or payoff, not the topic.
|
||||
|
||||
TRANSCRIPT_LANGUAGE: {language}
|
||||
{profile_rules}TRANSCRIPT_LANGUAGE: {language}
|
||||
VIDEO_DURATION_SECONDS: {video_duration}
|
||||
CANDIDATE_WINDOWS_JSON:
|
||||
{windows_json}
|
||||
|
|
@ -567,69 +560,4 @@ def _config_for_strategy(strategy: str, mode: str, model_name: str) -> genai_typ
|
|||
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())
|
||||
|
|
@ -24,7 +24,7 @@ import json
|
|||
import os
|
||||
from typing import Optional
|
||||
|
||||
SCREEN_LAYOUTS = {"screencast", "wide", "inset"}
|
||||
SCREEN_LAYOUTS = {"screencast", "code", "wide", "inset"}
|
||||
FRAMES = int(os.environ.get("HOOK_GROUNDING_FRAMES", "3"))
|
||||
WIDTH = int(os.environ.get("HOOK_GROUNDING_WIDTH", "1024"))
|
||||
# Ignore a blip: the screen stretches must cover this share of the clip.
|
||||
|
|
@ -42,7 +42,7 @@ def screen_video() -> bool:
|
|||
(verified on a product update video: every GENERAL scene was a stats
|
||||
card), even when the width gate did not upgrade it to SCREENCAST."""
|
||||
try:
|
||||
import screencast_layout
|
||||
from clipwright.layouts import screencast_layout
|
||||
return bool(getattr(screencast_layout, "ENABLED", False))
|
||||
except Exception:
|
||||
return False
|
||||
|
|
@ -50,7 +50,7 @@ def screen_video() -> bool:
|
|||
|
||||
def screen_ranges(ranges, on_screen_video=None):
|
||||
"""(start, end) pairs, clip seconds, of the stretches rendered on-screen."""
|
||||
import layout_ranges
|
||||
from clipwright.layouts import layout_ranges
|
||||
layouts = set(SCREEN_LAYOUTS)
|
||||
if screen_video() if on_screen_video is None else on_screen_video:
|
||||
layouts.add("general")
|
||||
|
|
@ -125,7 +125,7 @@ def _ask_gemini(frames, prompt, api_key):
|
|||
"""One vision call; returns the parsed dict. Split out so tests can stub it."""
|
||||
from google import genai
|
||||
from google.genai import types as genai_types
|
||||
import gemini_worker
|
||||
from clipwright.pipeline import gemini_worker
|
||||
|
||||
client = genai.Client(api_key=api_key)
|
||||
model_name = os.environ.get("GEMINI_MODEL") or "gemini-3.1-flash-lite"
|
||||
|
|
@ -151,7 +151,7 @@ def reground(clip_path, clip, transcript, start, end) -> Optional[dict]:
|
|||
"keeping the transcript hook.")
|
||||
return None
|
||||
try:
|
||||
import gemini_worker
|
||||
from clipwright.pipeline import gemini_worker
|
||||
|
||||
times = sample_times(clip.get("layout_ranges"), float(end) - float(start))
|
||||
frames = frames_at(clip_path, times)
|
||||
|
|
@ -23,7 +23,6 @@ so ``main.py`` sees one shape regardless of provider.
|
|||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from typing import Optional, Tuple, Type
|
||||
|
||||
|
|
@ -108,7 +107,7 @@ def generate_json(prompt: str, schema: Type[BaseModel], model: Optional[str] = N
|
|||
provider. Raises on HTTP errors, empty bodies and schema violations; the
|
||||
retry policy lives in the caller, same as for Gemini.
|
||||
"""
|
||||
import gemini_worker # local import: keeps this module free of the google SDK
|
||||
from clipwright.pipeline import gemini_worker # local import: keeps this module free of the google SDK
|
||||
|
||||
url = f"{base_url()}/chat/completions"
|
||||
model = model or model_name()
|
||||
|
|
@ -9,10 +9,7 @@ import threading
|
|||
import unicodedata
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from scenedetect import open_video, SceneManager
|
||||
from scenedetect.detectors import ContentDetector
|
||||
from ultralytics import YOLO
|
||||
import torch
|
||||
import os
|
||||
import math
|
||||
import numpy as np
|
||||
|
|
@ -23,16 +20,21 @@ import mediapipe as mp
|
|||
from google import genai
|
||||
from google.genai import types as genai_types
|
||||
|
||||
import frame_sampler
|
||||
import gemini_worker
|
||||
import hook_grounding
|
||||
import layout_picker
|
||||
import llm_backend
|
||||
from clip_selection import (build_transcript_windows, clip_count_targets,
|
||||
from clipwright.media import frame_sampler
|
||||
from clipwright.media.subtitles import merge_continuation_words
|
||||
from clipwright.pipeline import bridge
|
||||
from clipwright.pipeline import gemini_worker
|
||||
from clipwright.pipeline import hook_grounding
|
||||
from clipwright.pipeline.profiles import ProfileError, load_profile
|
||||
from clipwright.pipeline import profile_prompts
|
||||
from clipwright.layouts import layout_picker
|
||||
from clipwright.pipeline import llm_backend
|
||||
from clipwright.pipeline.clip_selection import (build_transcript_windows, clip_count_targets,
|
||||
clip_duration_bounds, dedupe_overlapping,
|
||||
find_hook_start, hook_first_enabled,
|
||||
score_batches, shortlist_target,
|
||||
snap_clip_to_words, trim_to_best)
|
||||
from ffmpeg_utils import (video_encode_args, audio_encode_args, cut_clip, QUALITY,
|
||||
from clipwright.media.ffmpeg_utils import (video_encode_args, cut_clip,
|
||||
QUALITY_FAST, METADATA_SCRUB)
|
||||
from dotenv import load_dotenv
|
||||
import json
|
||||
|
|
@ -46,44 +48,10 @@ load_dotenv()
|
|||
# --- Constants ---
|
||||
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! 🚫'>"
|
||||
}}
|
||||
]
|
||||
}}
|
||||
"""
|
||||
# Active per-channel profile (PLAN #1 v0). Populated from --channel / the
|
||||
# CHANNEL_PROFILE env var in __main__; None when the job runs channel-less.
|
||||
# Nothing reads it for generation yet -- later items (#3/#4/#6) will.
|
||||
ACTIVE_PROFILE = None
|
||||
|
||||
# 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
|
||||
|
|
@ -633,7 +601,7 @@ def analyze_scenes_strategy(video_path, scenes):
|
|||
return strategies
|
||||
|
||||
def detect_scenes(video_path):
|
||||
import scene_detection
|
||||
from clipwright.media import scene_detection
|
||||
return scene_detection.detect_scenes(video_path)
|
||||
|
||||
def get_video_resolution(video_path):
|
||||
|
|
@ -836,14 +804,14 @@ def download_youtube_video(url, output_dir=".", on_audio=None):
|
|||
"""
|
||||
# SSRF guard: block non-http(s) schemes and private/loopback/metadata hosts
|
||||
# before handing the URL to yt-dlp.
|
||||
from security_utils import assert_public_url
|
||||
from clipwright.core.security_utils import assert_public_url
|
||||
assert_public_url(url)
|
||||
# Throwaway hosts agents fall back to (tmpfiles.org) hand out short-lived
|
||||
# signed links; refresh through the host's page so yt-dlp gets the file.
|
||||
import file_hosts
|
||||
from clipwright.integrations import file_hosts
|
||||
url = file_hosts.resolve(url)
|
||||
# Reject non-video YouTube links before the download starts.
|
||||
from yt_clients import NotASingleVideo, youtube_non_video_reason
|
||||
from clipwright.integrations.yt_clients import NotASingleVideo, youtube_non_video_reason
|
||||
reason = youtube_non_video_reason(url)
|
||||
if reason:
|
||||
raise NotASingleVideo(f"This link is {reason}.")
|
||||
|
|
@ -899,7 +867,7 @@ def download_youtube_video(url, output_dir=".", on_audio=None):
|
|||
# explicit `default,mweb` because the authed defaults alone return
|
||||
# "Video unavailable" on a share of videos, from every IP, and that was
|
||||
# what fed the per-GB proxy (6-sep-2026, verified in the prod container).
|
||||
from yt_clients import hd_extractor_args, fallback_extractor_args
|
||||
from clipwright.integrations.yt_clients import hd_extractor_args, fallback_extractor_args
|
||||
hd_args = hd_extractor_args(_bgutil_http, _bgutil_script)
|
||||
fallback_args = fallback_extractor_args(_bgutil_http, _bgutil_script)
|
||||
|
||||
|
|
@ -1210,7 +1178,7 @@ def auto_caption_clip(clip_path, transcript, clip_start, clip_end, split_ranges=
|
|||
if not transcript or not transcript.get('segments'):
|
||||
return None # silent video: nothing to caption
|
||||
try:
|
||||
import subtitles as _subs
|
||||
from clipwright.media import subtitles as _subs
|
||||
style = _subs.AUTO_CAPTION_STYLE
|
||||
output_dir = os.path.dirname(clip_path)
|
||||
stem = os.path.basename(clip_path)
|
||||
|
|
@ -1242,7 +1210,7 @@ def auto_caption_clip(clip_path, transcript, clip_start, clip_end, split_ranges=
|
|||
out_path = os.path.join(output_dir, f"subtitled_{generation_id}_{stem}")
|
||||
|
||||
if split_ranges is None:
|
||||
import layout_ranges as _layouts
|
||||
from clipwright.layouts import layout_ranges as _layouts
|
||||
split_ranges = _layouts.split_ranges(_layouts.read(clip_path))
|
||||
if not _subs.generate_ass(
|
||||
transcript, clip_start, clip_end, ass_path,
|
||||
|
|
@ -1302,7 +1270,7 @@ def auto_hook_clip(clip_path, clip, captions=None):
|
|||
except ValueError:
|
||||
seconds = 5.0
|
||||
try:
|
||||
from hooks import add_hook_to_video, HOOK_STYLES
|
||||
from clipwright.media.hooks import add_hook_to_video, HOOK_STYLES
|
||||
if style not in HOOK_STYLES:
|
||||
style = "pill"
|
||||
output_dir = os.path.dirname(clip_path)
|
||||
|
|
@ -1342,154 +1310,66 @@ def auto_hook_clip(clip_path, clip, captions=None):
|
|||
|
||||
|
||||
def render_clip(input_video, final_output_video, output_format="auto",
|
||||
force_strategy=None, crop_overrides=None, watermark=False):
|
||||
force_strategy=None, crop_overrides=None, word_times=None):
|
||||
"""Route a cut clip through the right renderer for the chosen output format.
|
||||
vertical/auto -> 9:16 reframe, square -> 1:1 reframe, horizontal -> keep.
|
||||
``force_strategy`` (e.g. 'WIDE'/'TRACK') pins every scene's layout — the
|
||||
clip editor's whole-clip framing override. ``crop_overrides`` positions
|
||||
individual scenes by hand (the per-scene reframing editor) and wins over
|
||||
``force_strategy`` for the scenes it names.
|
||||
``watermark`` burns the free-plan mark into the result: inside the reframe
|
||||
encode on the v2 path, as a separate pass (apply_watermark) otherwise."""
|
||||
``force_strategy`` for the scenes it names. ``word_times`` are optional
|
||||
clip-relative word onsets (seconds, clip start = 0) that steer punch-ins."""
|
||||
if output_format == "horizontal":
|
||||
ok = finalize_clip_passthrough(input_video, final_output_video)
|
||||
if ok and watermark:
|
||||
apply_watermark(final_output_video)
|
||||
return ok
|
||||
return finalize_clip_passthrough(input_video, final_output_video)
|
||||
aspect = 1.0 if output_format == "square" else ASPECT_RATIO
|
||||
return process_video_to_vertical(input_video, final_output_video, aspect_ratio=aspect,
|
||||
force_strategy=force_strategy,
|
||||
crop_overrides=crop_overrides,
|
||||
watermark=watermark)
|
||||
word_times=word_times)
|
||||
|
||||
|
||||
# Watermark geometry, as fractions of the clip width/height.
|
||||
#
|
||||
# Vertical placement is the whole point: the top and bottom strips of a 9:16
|
||||
# clip are either black bars or blurred filler (GENERAL layout), so a mark up
|
||||
# there is cropped away without touching a single pixel of real footage. At 40%
|
||||
# of the height it sits inside the content band — a 16:9 source letterboxed
|
||||
# into 9:16 spans roughly 34%-66% — so removing the mark means cutting into the
|
||||
# picture. Left-aligned, like OpusClip's.
|
||||
WATERMARK_WIDTH_RATIO = 0.30
|
||||
WATERMARK_MARGIN_RATIO = 0.05
|
||||
WATERMARK_Y_RATIO = 0.40
|
||||
WATERMARK_OPACITY = 0.85
|
||||
def clip_word_onsets(transcript, clip_start, clip_end):
|
||||
"""Clip-relative onset seconds for the words spoken inside a clip.
|
||||
|
||||
|
||||
def watermark_logo_path():
|
||||
return os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
||||
"assets", "watermark.png")
|
||||
|
||||
|
||||
def watermark_filter(vw, vh, video="[0:v]", logo="[1:v]", out=""):
|
||||
"""filter_complex chain overlaying the logo input on a vw x vh video."""
|
||||
wm_w = max(80, int(vw * WATERMARK_WIDTH_RATIO))
|
||||
x = int(vw * WATERMARK_MARGIN_RATIO)
|
||||
y = int(vh * WATERMARK_Y_RATIO)
|
||||
return (
|
||||
f"{logo}scale={wm_w}:-1,format=rgba,"
|
||||
f"colorchannelmixer=aa={WATERMARK_OPACITY}[wm];"
|
||||
f"{video}[wm]overlay=x={x}:y={y}{out}"
|
||||
)
|
||||
|
||||
|
||||
def apply_watermark(video_path, output_path=None):
|
||||
"""Burn the Clipwright watermark into a finished clip (free plan).
|
||||
|
||||
One re-encode pass over the final file so every output format (TRACK,
|
||||
GENERAL, horizontal passthrough) gets the mark. In place by default; with
|
||||
``output_path`` the source stays untouched and the marked copy is written
|
||||
there, which is how the pipeline keeps the clean file next to the served
|
||||
one (see ``mark_delivery``).
|
||||
The punch-in path wants "when a word started" on the cut clip's timeline
|
||||
(0 = ``clip_start``). A word that straddles a boundary still contributes:
|
||||
one already underway when the clip opens lands at 0, one crossing the end
|
||||
lands at the clip's duration. Returns [] when the transcript has no word
|
||||
timings, which leaves the audio envelope as the only beat source.
|
||||
"""
|
||||
logo_path = watermark_logo_path()
|
||||
if not os.path.exists(logo_path):
|
||||
print(f" ⚠️ Watermark asset missing ({logo_path}); clip kept unmarked.")
|
||||
return False
|
||||
|
||||
# Scale the lockup from the clip's real width: overlay can't read the other
|
||||
# input's size, and computing it here avoids the deprecated scale2ref.
|
||||
try:
|
||||
probe = subprocess.check_output(
|
||||
["ffprobe", "-v", "error", "-select_streams", "v:0",
|
||||
"-show_entries", "stream=width,height", "-of", "csv=p=0:s=x", video_path],
|
||||
stderr=subprocess.STDOUT, timeout=60,
|
||||
).decode().strip().split("x")
|
||||
vw, vh = int(probe[0]), int(probe[1])
|
||||
except Exception as e:
|
||||
print(f" ⚠️ Could not probe clip for watermark ({e}); clip kept unmarked.")
|
||||
return False
|
||||
|
||||
filt = watermark_filter(vw, vh)
|
||||
tmp_path = (output_path or video_path) + ".wm.mp4"
|
||||
cmd = ["ffmpeg", "-y", "-i", video_path, "-i", logo_path,
|
||||
"-filter_complex", filt,
|
||||
*video_encode_args(QUALITY), "-c:a", "copy", *METADATA_SCRUB,
|
||||
"-movflags", "+faststart", tmp_path]
|
||||
result = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
|
||||
timeout=1800)
|
||||
if result.returncode == 0 and os.path.exists(tmp_path):
|
||||
os.replace(tmp_path, output_path or video_path)
|
||||
return True
|
||||
err = (result.stderr or b"").decode(errors="ignore")[-300:]
|
||||
print(f" ⚠️ Watermark pass failed (clip kept unmarked): {err}")
|
||||
if os.path.exists(tmp_path):
|
||||
os.remove(tmp_path)
|
||||
return False
|
||||
|
||||
|
||||
def mark_delivery(final_path, marker=None):
|
||||
"""The free-plan copy of a finished clip to serve: ``wm_<final>`` next to it.
|
||||
|
||||
The clean ``final_path`` is left as it is. That is the whole point: an
|
||||
upgrade re-points the clip at the clean twin instead of re-running the
|
||||
job (``watermarked`` module). An existing copy is reused, so re-choosing
|
||||
a file the user already had (captions off, hook off) costs no encode.
|
||||
|
||||
Returns the marked path, or ``final_path`` itself when the copy could not
|
||||
be made: the mark must never cost the user the clip (same fail-open rule
|
||||
apply_watermark has always had).
|
||||
"""
|
||||
import watermarked
|
||||
out_path = os.path.join(os.path.dirname(final_path),
|
||||
watermarked.marked_name(final_path))
|
||||
if os.path.exists(out_path) and os.path.getsize(out_path) > 0:
|
||||
return out_path
|
||||
ok = (marker or apply_watermark)(final_path, out_path)
|
||||
if ok and os.path.exists(out_path):
|
||||
return out_path
|
||||
# Still the wm_ name: the /videos guard refuses the clean deliverables of
|
||||
# a free job, so serving the clean name here would be a clip the user
|
||||
# cannot play. The copy simply carries no mark.
|
||||
print(f" ⚠️ Serving {os.path.basename(final_path)} unmarked (copy).")
|
||||
try:
|
||||
shutil.copyfile(final_path, out_path)
|
||||
return out_path
|
||||
except OSError:
|
||||
return final_path
|
||||
if not transcript or clip_end <= clip_start:
|
||||
return []
|
||||
span = clip_end - clip_start
|
||||
onsets = []
|
||||
for seg in transcript.get("segments", []) or []:
|
||||
for word in seg.get("words") or []:
|
||||
if word.get("end", 0) <= clip_start or word.get("start", 0) >= clip_end:
|
||||
continue
|
||||
onset = word.get("start", 0) - clip_start
|
||||
onsets.append(round(min(max(onset, 0.0), span), 3))
|
||||
return sorted(onsets)
|
||||
|
||||
|
||||
def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPECT_RATIO,
|
||||
force_strategy=None, crop_overrides=None, watermark=False):
|
||||
force_strategy=None, crop_overrides=None, word_times=None):
|
||||
"""
|
||||
Core logic to reframe a horizontal video to a target aspect ratio using
|
||||
scene detection and Active Speaker Tracking (MediaPipe).
|
||||
aspect_ratio: width/height of the output (9/16 vertical, 1.0 square).
|
||||
force_strategy / crop_overrides pin layouts and scene crops by hand (v2
|
||||
engine only — the v1 loop below has no layout concept beyond its own
|
||||
classifier).
|
||||
classifier). word_times feeds clip-relative word onsets to the punch-in
|
||||
beats (v2 only; the v1 loop has no punch-ins).
|
||||
"""
|
||||
# v2 engine: analyze downscaled, render natively in ffmpeg. Any failure
|
||||
# falls back to the v1 frame loop below so a v2 edge case can't kill jobs.
|
||||
if os.environ.get("REFRAME_ENGINE", "v2").strip().lower() != "v1":
|
||||
try:
|
||||
import reframe_v2
|
||||
from clipwright.layouts import reframe_v2
|
||||
t0 = time.time()
|
||||
result = reframe_v2.render(input_video, final_output_video, aspect_ratio,
|
||||
force_strategy=force_strategy,
|
||||
crop_overrides=crop_overrides,
|
||||
watermark=watermark)
|
||||
word_times=word_times)
|
||||
print(f" ⏱️ Reframe v2 total: {time.time() - t0:.1f}s")
|
||||
return result
|
||||
except Exception as e:
|
||||
|
|
@ -1536,7 +1416,7 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE
|
|||
# Same delivery floor as the v2 engine — a fallback render is still the clip
|
||||
# the user posts, so it must not ship sub-HD. The frame loop below already
|
||||
# resizes every cropped frame to these dims, so nothing else changes.
|
||||
from reframe_v2 import delivery_size
|
||||
from clipwright.layouts.reframe_v2 import delivery_size
|
||||
OUTPUT_WIDTH, OUTPUT_HEIGHT = delivery_size(original_width, original_height,
|
||||
aspect_ratio)
|
||||
|
||||
|
|
@ -1684,8 +1564,6 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE
|
|||
if os.path.exists(leftover):
|
||||
os.remove(leftover)
|
||||
|
||||
if watermark:
|
||||
apply_watermark(final_output_video)
|
||||
return True
|
||||
|
||||
# --- Transcript checkpoint (survive a redeploy without paying twice) ---------
|
||||
|
|
@ -1751,6 +1629,93 @@ def clear_transcript_checkpoint(output_dir):
|
|||
print(f"⚠️ Could not remove transcript checkpoint: {e}")
|
||||
|
||||
|
||||
# The only handoff manifest schema this build understands (cadence PLAN #8).
|
||||
HANDOFF_SCHEMA = "clipwright.handoff/1"
|
||||
# The master's measured duration may differ from the manifest's edited timeline
|
||||
# by this fraction before we refuse to align the edited-timeline transcript.
|
||||
HANDOFF_DURATION_TOLERANCE = 0.01
|
||||
|
||||
|
||||
class HandoffError(Exception):
|
||||
"""A cadence handoff manifest is missing, invalid or does not match the master."""
|
||||
|
||||
|
||||
def load_handoff_transcript(manifest_path, input_video, duration):
|
||||
"""Load the cadence-edited transcript a handoff manifest points at.
|
||||
|
||||
Cadence emits word tokens with a leading space and compound fragments
|
||||
without one (cadence PLAN #8, design rule #1), so every segment's words are
|
||||
run through ``merge_continuation_words`` on load. Missing ``words`` lists
|
||||
are left alone.
|
||||
|
||||
The manifest's ``edited.master`` is null in v1: the video passed via ``-i``
|
||||
/ ``-u`` *is* the master, so its measured ``duration`` must match
|
||||
``edited.duration`` within +/-1% or the edited-timeline alignment is not
|
||||
trustworthy. ``sources[].path`` is never opened: those are emitter-local
|
||||
paths (never honor a remote manifest's file references).
|
||||
|
||||
Raises ``HandoffError`` on any problem; the caller decides whether to refuse
|
||||
the job.
|
||||
"""
|
||||
manifest_path = os.path.abspath(manifest_path)
|
||||
try:
|
||||
with open(manifest_path, encoding="utf-8") as f:
|
||||
manifest = json.load(f)
|
||||
except FileNotFoundError:
|
||||
raise HandoffError(f"handoff manifest not found: {manifest_path}")
|
||||
except json.JSONDecodeError as e:
|
||||
raise HandoffError(f"malformed handoff manifest {manifest_path}: {e}")
|
||||
except OSError as e:
|
||||
raise HandoffError(f"could not read handoff manifest {manifest_path}: {e}")
|
||||
if not isinstance(manifest, dict):
|
||||
raise HandoffError(f"handoff manifest {manifest_path} must be a JSON object")
|
||||
|
||||
schema = manifest.get("schema")
|
||||
if schema and schema != HANDOFF_SCHEMA:
|
||||
raise HandoffError(
|
||||
f"unsupported handoff schema {schema!r} (expected {HANDOFF_SCHEMA!r})")
|
||||
|
||||
# Duration gate: -i/-u is the edited master, so it has to match the manifest.
|
||||
edited = manifest.get("edited") or {}
|
||||
edited_duration = edited.get("duration") if isinstance(edited, dict) else None
|
||||
if edited_duration is not None:
|
||||
try:
|
||||
edited_duration = float(edited_duration)
|
||||
except (TypeError, ValueError):
|
||||
raise HandoffError(
|
||||
f"edited.duration must be a number, got {edited_duration!r}")
|
||||
if duration and abs(float(duration) - edited_duration) > \
|
||||
HANDOFF_DURATION_TOLERANCE * edited_duration:
|
||||
raise HandoffError(
|
||||
f"input duration {float(duration):.2f}s for "
|
||||
f"{os.path.basename(str(input_video))} differs from the handoff's "
|
||||
f"edited timeline {edited_duration:.2f}s by more than 1% — refusing "
|
||||
f"the handoff. Pass --transcript explicitly if you need to force it.")
|
||||
|
||||
# transcript.path is resolved relative to the MANIFEST's directory.
|
||||
transcript_ref = manifest.get("transcript")
|
||||
if not isinstance(transcript_ref, dict) or not transcript_ref.get("path"):
|
||||
raise HandoffError("handoff manifest has no transcript.path")
|
||||
transcript_path = os.path.normpath(os.path.join(
|
||||
os.path.dirname(manifest_path), str(transcript_ref["path"])))
|
||||
try:
|
||||
with open(transcript_path, encoding="utf-8") as f:
|
||||
transcript = json.load(f)
|
||||
except FileNotFoundError:
|
||||
raise HandoffError(f"handoff transcript not found: {transcript_path}")
|
||||
except json.JSONDecodeError as e:
|
||||
raise HandoffError(f"malformed handoff transcript {transcript_path}: {e}")
|
||||
except OSError as e:
|
||||
raise HandoffError(f"could not read handoff transcript {transcript_path}: {e}")
|
||||
if not isinstance(transcript, dict) or not transcript.get("segments"):
|
||||
raise HandoffError(f"handoff transcript {transcript_path} has no segments")
|
||||
|
||||
for segment in transcript["segments"]:
|
||||
if isinstance(segment, dict) and isinstance(segment.get("words"), list):
|
||||
segment["words"] = merge_continuation_words(segment["words"])
|
||||
return transcript
|
||||
|
||||
|
||||
CLIP_RETRY_PAUSE_SECONDS = float(os.environ.get("CLIP_RETRY_PAUSE_SECONDS", "10"))
|
||||
|
||||
|
||||
|
|
@ -1765,6 +1730,57 @@ def clip_render_order(shorts):
|
|||
return sorted(range(len(shorts)), key=lambda i: (-score(i), i))
|
||||
|
||||
|
||||
# --- Retention provenance (PLAN #10, "instrument now") ---------------------
|
||||
# Every clip carries one versioned provenance object so a future retention /
|
||||
# analytics loop becomes a data pull instead of a re-architecture. It records
|
||||
# only what the pipeline already produced: the active profile, the model's
|
||||
# predicted score, how the start boundary was chosen (#2a hook-first vs the
|
||||
# plain word snap), whether a long-form bridge target was attached (#6), and
|
||||
# the publish target. Additive: no existing metadata field changes shape. The
|
||||
# loop itself is deliberately NOT built here.
|
||||
PROVENANCE_SCHEMA_VERSION = 1
|
||||
|
||||
|
||||
def build_provenance(clip, profile=None):
|
||||
"""The versioned provenance record for one clip (PLAN #10).
|
||||
|
||||
Reads the ``hook_first`` block #2a writes when it moves a clip start, the
|
||||
merged #6 bridge fields, the model's ``predicted_score`` and the active
|
||||
profile. Anything the pipeline does not have at clip time (e.g. a
|
||||
title-validator version or a chosen thumbnail role) is omitted rather than
|
||||
guessed. Pure and side-effect free so it can be unit tested without a
|
||||
render.
|
||||
"""
|
||||
clip = clip if isinstance(clip, dict) else {}
|
||||
hook_first = clip.get("hook_first")
|
||||
hook_first = hook_first if isinstance(hook_first, dict) else None
|
||||
applied = hook_first is not None
|
||||
related = (clip.get("related_video_url") or "")
|
||||
related = related.strip() if isinstance(related, str) else ""
|
||||
return {
|
||||
"schema_version": PROVENANCE_SCHEMA_VERSION,
|
||||
"profile": getattr(profile, "slug", None) or None,
|
||||
"predicted_score": clip.get("predicted_score"),
|
||||
"hook": {
|
||||
"applied": applied,
|
||||
# Which pass set the final start: the deterministic hook-first trim
|
||||
# (#2a), or the plain word-boundary snap it ran on top of.
|
||||
"source": "hook_first" if applied else "snap",
|
||||
"start": hook_first.get("start") if applied else None,
|
||||
"trim": hook_first.get("trim") if applied else None,
|
||||
"proposed": hook_first.get("proposed") if applied else None,
|
||||
},
|
||||
"bridge": {
|
||||
"present": bool(related),
|
||||
"related_video_url": related or None,
|
||||
},
|
||||
"publish": {
|
||||
"postiz_integration_id": getattr(
|
||||
profile, "default_postiz_integration_id", None),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _free_gpu_cache():
|
||||
try:
|
||||
import torch
|
||||
|
|
@ -1776,7 +1792,7 @@ def _free_gpu_cache():
|
|||
|
||||
def transcribe_video(video_path):
|
||||
print("🎙️ Transcribing video...")
|
||||
from transcribe_backends import transcribe_media, release_models, host_asr_slot
|
||||
from clipwright.pipeline.transcribe_backends import transcribe_media, release_models, host_asr_slot
|
||||
|
||||
# At most ASR_HOST_SLOTS jobs transcribe on the GPU at once, host-wide.
|
||||
# Inside the slot, the model's VRAM is handed back before the long render
|
||||
|
|
@ -1923,6 +1939,11 @@ def get_viral_clips(transcript_result, video_duration):
|
|||
model_name = os.environ.get("GEMINI_MODEL") or 'gemini-3.1-flash-lite'
|
||||
print(f"\U0001f916 Model: {model_name} | language: {language}")
|
||||
|
||||
# PLAN #1: the active channel profile tunes the copy fields (Short title,
|
||||
# viral hook). ACTIVE_PROFILE is set once at CLI startup; None here renders
|
||||
# an empty block, leaving the prompt byte-identical to a profile-less run.
|
||||
profile_rules = profile_prompts.clip_rules_block(ACTIVE_PROFILE)
|
||||
|
||||
# Full word list — ground truth for snapping cut points.
|
||||
words = []
|
||||
for segment in transcript_result['segments']:
|
||||
|
|
@ -1987,6 +2008,7 @@ def get_viral_clips(transcript_result, video_duration):
|
|||
video_duration=video_duration, language=language,
|
||||
min_clips=lo, max_clips=hi,
|
||||
min_secs=min_secs, max_secs=max_secs,
|
||||
profile_rules=profile_rules,
|
||||
windows_json=json.dumps(_payload(ws), ensure_ascii=False))
|
||||
return build
|
||||
|
||||
|
|
@ -2033,6 +2055,30 @@ def get_viral_clips(transcript_result, video_duration):
|
|||
ns, ne = snap_clip_to_words(s.get("start", 0), s.get("end", 0), words, video_duration,
|
||||
min_duration=min_secs, max_duration=max_secs)
|
||||
s["start"], s["end"] = ns, ne
|
||||
|
||||
# Hook-first boundaries (#2a): move each snapped start onto the first
|
||||
# strong spoken hook, trimming wind-up so the clip opens on the hook.
|
||||
# Deterministic and word-based (no LLM); a clip with no clear hook is
|
||||
# left exactly where the snap put it. The pass is env-capped and on by
|
||||
# default (HOOK_FIRST); see clip_selection.find_hook_start.
|
||||
if hook_first_enabled():
|
||||
moved = 0
|
||||
for s in shorts:
|
||||
old_start = float(s.get("start", 0) or 0)
|
||||
new_start = find_hook_start(words, old_start, s.get("end", 0),
|
||||
min_duration=min_secs)
|
||||
if new_start is None or new_start >= old_start:
|
||||
continue
|
||||
trim = round(old_start - new_start, 3)
|
||||
print(f" Hook-first clip {s.get('source_window_id') or '?'}: "
|
||||
f"start {old_start:.2f} -> {new_start:.2f} (trim {trim:.2f}s)")
|
||||
s["start"] = new_start
|
||||
s["hook_first"] = {"start": new_start, "trim": trim,
|
||||
"proposed": old_start}
|
||||
moved += 1
|
||||
if moved:
|
||||
print(f" Hook-first trimmed {moved} of {len(shorts)} clip start(s).")
|
||||
|
||||
deduped = dedupe_overlapping(shorts)
|
||||
if len(deduped) < len(shorts):
|
||||
print(f" Dropped {len(shorts) - len(deduped)} clip(s) overlapping a "
|
||||
|
|
@ -2190,10 +2236,46 @@ if __name__ == '__main__':
|
|||
help="Output aspect: vertical/auto (9:16), horizontal (keep 16:9), square (1:1).")
|
||||
parser.add_argument('--transcript', type=str,
|
||||
help="Path to a precomputed transcript JSON (transcribe_media shape); skips transcription.")
|
||||
parser.add_argument('--handoff', type=str, default=None,
|
||||
help="Path to a cadence handoff manifest JSON. Loads the "
|
||||
"edited-timeline transcript it points at (relative to "
|
||||
"the manifest), validates the master duration and "
|
||||
"skips transcription.")
|
||||
parser.add_argument('--channel', type=str, default=None,
|
||||
help="Channel profile slug (channels/<slug>.json); "
|
||||
"overrides the CHANNEL_PROFILE env var.")
|
||||
parser.add_argument('--longform-url', type=str, default=None,
|
||||
help="Target long-form video URL for the Shorts->long-form "
|
||||
"bridge copy/checklist (PLAN #6). Optional: without it "
|
||||
"the active profile's published_video_history is used.")
|
||||
|
||||
args = parser.parse_args()
|
||||
output_format = args.format
|
||||
|
||||
# Per-channel profile (PLAN #1 v0): resolve and validate before any work so
|
||||
# a bad profile fails at startup, and hang it off a module global that later
|
||||
# items (#3/#4/#6) will read. The API passes CHANNEL_PROFILE; --channel wins
|
||||
# for local CLI runs. Generation behaviour is deliberately untouched.
|
||||
_channel_slug = args.channel or os.environ.get("CHANNEL_PROFILE") or None
|
||||
if _channel_slug:
|
||||
try:
|
||||
ACTIVE_PROFILE = load_profile(_channel_slug)
|
||||
print(f"📦 Channel profile: {_channel_slug} "
|
||||
f"(tone={ACTIVE_PROFILE.tone or 'unset'})")
|
||||
except ProfileError as e:
|
||||
if args.channel:
|
||||
# An explicit --channel that does not load is a config error.
|
||||
print(f"❌ Channel profile {args.channel!r}: {e}")
|
||||
sys.exit(1)
|
||||
# Env-derived only: warn and keep the run identical to channel-less.
|
||||
print(f"⚠️ Ignoring CHANNEL_PROFILE={_channel_slug!r}: {e}")
|
||||
|
||||
# Shorts -> long-form bridge target (PLAN #6). Explicit --longform-url wins;
|
||||
# otherwise the per-clip generator falls back to the profile history.
|
||||
longform_url = (args.longform_url or os.environ.get("LONGFORM_URL") or "").strip() or None
|
||||
if longform_url:
|
||||
print(f"🔗 Bridge target (long-form): {longform_url}")
|
||||
|
||||
script_start_time = time.time()
|
||||
|
||||
def _ensure_dir(path: str) -> str:
|
||||
|
|
@ -2251,7 +2333,7 @@ if __name__ == '__main__':
|
|||
threading.Thread(target=_early_work, args=(audio_path, audio_duration),
|
||||
daemon=True).start()
|
||||
|
||||
use_early = (not args.skip_analysis and not args.transcript
|
||||
use_early = (not args.skip_analysis and not args.transcript and not args.handoff
|
||||
and os.environ.get("EARLY_AUDIO", "1").strip() != "0"
|
||||
and not os.environ.get("MAX_SOURCE_MINUTES", "").strip()
|
||||
and not os.path.exists(os.path.join(output_dir, TRANSCRIPT_CHECKPOINT)))
|
||||
|
|
@ -2308,7 +2390,7 @@ if __name__ == '__main__':
|
|||
_w = int(_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
||||
_h = int(_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
||||
_cap.release()
|
||||
from reframe_v2 import source_already_fits # imports main back
|
||||
from clipwright.layouts.reframe_v2 import source_already_fits # imports main back
|
||||
# A source already shot vertical has no width to reorganise, and
|
||||
# the render passes it through whatever the model says. Asking
|
||||
# anyway costs a Gemini call per upload to be ignored.
|
||||
|
|
@ -2340,12 +2422,25 @@ if __name__ == '__main__':
|
|||
|
||||
# 3. Transcribe — unless the video has no audio, in which case fall back
|
||||
# to Gemini vision (picks clips from the imagery instead of the speech).
|
||||
from transcribe_backends import NoAudioError
|
||||
from clipwright.pipeline.transcribe_backends import NoAudioError
|
||||
transcript = None
|
||||
# Cadence handoff (PLAN #8): the edited-timeline transcript, already
|
||||
# aligned to the master, so there is nothing to transcribe. It wins over
|
||||
# --transcript. A handoff that fails validation is refused (not silently
|
||||
# re-transcribed): the whole point is alignment to the edited timeline,
|
||||
# and guessing would cut clips on the wrong one.
|
||||
if args.handoff:
|
||||
try:
|
||||
transcript = load_handoff_transcript(args.handoff, input_video, duration)
|
||||
print(f"⏩ Using cadence handoff transcript "
|
||||
f"({len(transcript['segments'])} segments) — skipping transcription.")
|
||||
except HandoffError as e:
|
||||
print(f"❌ Handoff refused: {e}")
|
||||
sys.exit(1)
|
||||
# Module handover (issue #68): another module already transcribed this
|
||||
# exact source with the same backend, so reuse its output. Any problem
|
||||
# with the file falls back to transcribing normally rather than failing.
|
||||
if args.transcript:
|
||||
elif args.transcript:
|
||||
try:
|
||||
with open(args.transcript, 'r') as f:
|
||||
transcript = json.load(f)
|
||||
|
|
@ -2408,6 +2503,19 @@ if __name__ == '__main__':
|
|||
else:
|
||||
print(f"🔥 Found {len(clips_data['shorts'])} clips!")
|
||||
|
||||
# Shorts -> long-form bridge copy (PLAN #6): per clip, derive the
|
||||
# description block, first-comment text, target URL and the manual
|
||||
# Studio checklist from the active profile. The explicit
|
||||
# --longform-url wins over the profile's published_video_history.
|
||||
# The related-video link and comment pinning are Studio-UI only
|
||||
# (no API), hence the checklist rather than a server-side action.
|
||||
for _clip in clips_data['shorts']:
|
||||
_clip.update(bridge.build_bridge(
|
||||
ACTIVE_PROFILE, clip=_clip, related_video_url=longform_url))
|
||||
# Retention provenance (PLAN #10): one versioned record per
|
||||
# clip, written with the metadata below. Additive only.
|
||||
_clip['provenance'] = build_provenance(_clip, ACTIVE_PROFILE)
|
||||
|
||||
# Save metadata. Silent videos have no transcript → no subtitles,
|
||||
# which is correct (there's no speech to caption).
|
||||
clips_data['transcript'] = transcript or {"language": "none", "segments": []}
|
||||
|
|
@ -2440,20 +2548,21 @@ if __name__ == '__main__':
|
|||
cut_clip(input_video, clip_temp_path, start, end, i + 1)
|
||||
|
||||
# Layer order: the canonical reframe stays CLEAN, the hook
|
||||
# is a derived hooked_ file, captions go last on top of
|
||||
# whichever is current, and on the free plan the served
|
||||
# file is a wm_ copy of that final (mark_delivery). The
|
||||
# mark used to ride the reframe encode, which made it
|
||||
# permanent: paying could not remove it from clips already
|
||||
# made. Each worker writes only its own clip dict, so the
|
||||
# re-dump after the pool is race-free.
|
||||
success = render_clip(clip_temp_path, clip_final_path, output_format)
|
||||
# is a derived hooked_ file, and captions go last on top of
|
||||
# whichever is current. Each worker writes only its own clip
|
||||
# dict, so the re-dump after the pool is race-free.
|
||||
# Spoken emphasis drives punch-in timing when the source
|
||||
# transcript carries word timestamps; [] falls back to the
|
||||
# audio envelope inside the renderer.
|
||||
word_times = clip_word_onsets(transcript, start, end)
|
||||
success = render_clip(clip_temp_path, clip_final_path, output_format,
|
||||
word_times=word_times)
|
||||
if success:
|
||||
print(f" 🎞️ Clip {i+1} framed")
|
||||
deliver_path = clip_final_path
|
||||
# Which stretches were stacked (SPLIT): captions go on the
|
||||
# seam there, and /api/subtitle needs it again later.
|
||||
import layout_ranges as _layouts
|
||||
from clipwright.layouts import layout_ranges as _layouts
|
||||
clip['layout_ranges'] = _layouts.read(clip_final_path)
|
||||
# The hook was written from the transcript alone. When the
|
||||
# render put this clip's meaning on the screen, rewrite hook
|
||||
|
|
@ -2479,16 +2588,14 @@ if __name__ == '__main__':
|
|||
deliver_path, transcript, start, end,
|
||||
split_ranges=split_ranges)
|
||||
served = captioned or deliver_path
|
||||
if os.environ.get("WATERMARK") == "1":
|
||||
served = mark_delivery(served)
|
||||
print(f" ✅ Clip {i+1} ready: {clip_final_path}")
|
||||
# Hand the API the file to actually serve for this clip.
|
||||
# Without it the status poller guesses the clean reframe
|
||||
# name, so a job in flight showed every clip stripped of
|
||||
# its hook and captions until the WHOLE job finished and
|
||||
# the result got rebuilt through _canonical_clip_file.
|
||||
# Printed only after the full chain (reframe, watermark,
|
||||
# hook, captions) so the file is complete when it is
|
||||
# Printed only after the full chain (reframe, hook,
|
||||
# captions) so the file is complete when it is
|
||||
# announced, never one that ffmpeg is still writing.
|
||||
print(f"CLIP_READY {i} {os.path.basename(served)}")
|
||||
return success
|
||||
|
|
@ -2502,11 +2609,6 @@ if __name__ == '__main__':
|
|||
clip_workers = max(int(os.environ.get("CLIP_WORKERS", "6")), 1)
|
||||
shorts = clips_data['shorts']
|
||||
failed = []
|
||||
if os.environ.get("WATERMARK") == "1":
|
||||
# Tells the /videos guard that the clean twins in this
|
||||
# directory are not for serving (watermarked.MARKER_FILE).
|
||||
import watermarked
|
||||
watermarked.mark_job(output_dir)
|
||||
with ThreadPoolExecutor(max_workers=min(clip_workers, len(shorts))) as pool:
|
||||
# Best clip first: the pool starts work in submission order, so
|
||||
# the user's first delivered clip is the strongest one instead
|
||||
125
clipwright/pipeline/profile_prompts.py
Normal file
125
clipwright/pipeline/profile_prompts.py
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
"""Profile -> prompt fragments (PLAN #1, full).
|
||||
|
||||
The single mapping between a channel :class:`~clipwright.pipeline.profiles.Profile`
|
||||
and the text the generators read. Both generation paths use it and nothing else:
|
||||
|
||||
* the clipping path (``gemini_worker.DETAIL_PROMPT_TEMPLATE``, via ``main.py``)
|
||||
* the Studio path (``media/thumbnail.py``: titles, concepts, description)
|
||||
|
||||
Every helper is pure and accepts ``profile=None``; a ``None`` profile returns the
|
||||
empty string, so a caller that was never given a channel renders exactly the
|
||||
prompt it did before profiles existed. A non-empty block ends with a single ``\\n``
|
||||
so it can be dropped onto its own line in an f-string without shifting anything
|
||||
(an empty string leaves the line blank, byte-for-byte as today).
|
||||
|
||||
Keep the blocks short: they are constraints on an already-long prompt, not a
|
||||
second prompt.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from clipwright.pipeline.profiles import Profile
|
||||
|
||||
# Full sentences, keyed by the enums ``profiles.py`` validates. Kept here so a
|
||||
# new enum value fails loudly (missing from the map) instead of silently
|
||||
# dropping the constraint.
|
||||
_KEYWORD_POSITION_TEXT = {
|
||||
"start": "Put the main keyword or subject in the first 3 words",
|
||||
"middle": "Put the main keyword or subject near the middle",
|
||||
"end": "Put the main keyword or subject at the end",
|
||||
"any": "Place the main keyword or subject wherever it reads best",
|
||||
}
|
||||
_NUMBER_POLICY_TEXT = {
|
||||
"allow": "Numbers are allowed when they earn attention",
|
||||
"avoid": "Avoid numbers unless a number is the point",
|
||||
"require": "Every title must contain a concrete number",
|
||||
}
|
||||
_REQUIRED_SIGNAL_TEXT = {
|
||||
"consequence": "Every title must carry a concrete consequence or stake",
|
||||
"curiosity": "Every title must open a curiosity gap the video pays off",
|
||||
"either": "Every title must carry a consequence or a curiosity gap",
|
||||
"none": "",
|
||||
}
|
||||
|
||||
|
||||
def _quoted(items):
|
||||
return "; ".join(f'"{item}"' for item in items)
|
||||
|
||||
|
||||
def title_rules_block(profile: Profile | None) -> str:
|
||||
"""Title constraints: length, banned content, keyword/number/signal policy, tone."""
|
||||
if profile is None:
|
||||
return ""
|
||||
rules = profile.title_rules
|
||||
lines = ["CHANNEL TITLE RULES:"]
|
||||
if profile.tone:
|
||||
lines.append(f"- Tone: {profile.tone}.")
|
||||
lines.append(
|
||||
f"- Hard maximum {rules.max_chars} characters; the payoff must land inside "
|
||||
f"the first {rules.mobile_chars} (phones truncate there).")
|
||||
position = _KEYWORD_POSITION_TEXT.get(rules.keyword_position)
|
||||
if position:
|
||||
lines.append(f"- {position}.")
|
||||
signal = _REQUIRED_SIGNAL_TEXT.get(rules.required_signal)
|
||||
if signal:
|
||||
lines.append(f"- {signal}.")
|
||||
number = _NUMBER_POLICY_TEXT.get(rules.number_policy)
|
||||
if number:
|
||||
lines.append(f"- {number}.")
|
||||
if rules.banned_patterns:
|
||||
lines.append(f"- Never use the phrases: {_quoted(rules.banned_patterns)}.")
|
||||
if rules.banned_openers:
|
||||
lines.append(f"- Never open a title with: {_quoted(rules.banned_openers)}.")
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def hook_block(profile: Profile | None) -> str:
|
||||
"""Hook style and the patterns the channel already knows work."""
|
||||
if profile is None:
|
||||
return ""
|
||||
lines = []
|
||||
if profile.hook_style:
|
||||
lines.append(f"- Hook style: {profile.hook_style}.")
|
||||
if profile.hook_patterns:
|
||||
lines.append(f"- Patterns that work for this channel: {_quoted(profile.hook_patterns)}.")
|
||||
if not lines:
|
||||
return ""
|
||||
return "CHANNEL HOOK RULES:\n" + "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def description_block(profile: Profile | None) -> str:
|
||||
"""Description structure, the channel's links and its tone."""
|
||||
if profile is None:
|
||||
return ""
|
||||
lines = []
|
||||
if profile.description_template:
|
||||
template = profile.description_template.replace("\n", "\\n")
|
||||
lines.append(f'- Follow this structure for the blurb: "{template}".')
|
||||
if profile.links:
|
||||
lines.append(f"- Include these links: {', '.join(profile.links)}.")
|
||||
if profile.tone:
|
||||
lines.append(f"- Tone: {profile.tone}.")
|
||||
if not lines:
|
||||
return ""
|
||||
return "CHANNEL DESCRIPTION RULES:\n" + "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def thumbnail_block(profile: Profile | None) -> str:
|
||||
"""Thumbnail roles, palette and whether a presenter photo is expected."""
|
||||
if profile is None:
|
||||
return ""
|
||||
thumb = profile.thumbnail
|
||||
lines = []
|
||||
if thumb.role_order:
|
||||
lines.append(f"- Concept roles, in priority order: {', '.join(thumb.role_order)}.")
|
||||
if thumb.palette:
|
||||
lines.append(f"- Palette: {', '.join(thumb.palette)}.")
|
||||
presenter = ("available and encouraged" if thumb.presenter_photo
|
||||
else "not expected; prefer objects, scenes or symbols")
|
||||
lines.append(f"- Presenter photo is {presenter}.")
|
||||
return "CHANNEL THUMBNAIL RULES:\n" + "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def clip_rules_block(profile: Profile | None) -> str:
|
||||
"""The clipping path's block: hook guidance then title constraints."""
|
||||
return hook_block(profile) + title_rules_block(profile)
|
||||
434
clipwright/pipeline/profiles.py
Normal file
434
clipwright/pipeline/profiles.py
Normal file
|
|
@ -0,0 +1,434 @@
|
|||
"""Per-channel profiles (PLAN #1, v0).
|
||||
|
||||
A profile is the machine-readable root for one channel's packaging rules: the
|
||||
title constraints, hook patterns, description template and thumbnail roles that
|
||||
later items (#3, #4, #6, #10) read. This v0 defines the schema, the validating
|
||||
loader and the ``CHANNEL_PROFILE`` plumbing only -- nothing here changes how
|
||||
titles, hooks or descriptions are generated yet.
|
||||
|
||||
The runtime source of truth is the SQLite store in
|
||||
``clipwright.storage.channel_profiles`` (``<repo>/clipwright.sqlite3``). A one-time
|
||||
migration imports the legacy ``<repo>/channels/<slug>.json`` files on first
|
||||
bootstrap; ``channels_dir`` remains a test/embedding seam that reads straight
|
||||
from a directory. Every field is optional and falls back to a sensible default,
|
||||
so a minimal ``{"language": "en"}`` profile loads. Unknown keys are ignored so a
|
||||
newer profile can ship ahead of the code; known keys with the wrong type or an
|
||||
out-of-domain enum are refused with a message that names the exact path.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from collections.abc import Mapping, Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from clipwright.core.paths import REPO_ROOT
|
||||
|
||||
# ``<repo>/channels`` (also ``/app/channels`` in the Docker image).
|
||||
CHANNELS_DIR = REPO_ROOT / "channels"
|
||||
# Fallback selector used when ``load_profile`` is called without a slug.
|
||||
ENV_VAR = "CHANNEL_PROFILE"
|
||||
|
||||
# A slug becomes a filename under CHANNELS_DIR, so it may not contain separators
|
||||
# or traversal segments.
|
||||
_SLUG_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]*$")
|
||||
|
||||
KEYWORD_POSITIONS = frozenset({"start", "middle", "end", "any"})
|
||||
NUMBER_POLICIES = frozenset({"allow", "avoid", "require"})
|
||||
REQUIRED_SIGNALS = frozenset({"consequence", "curiosity", "either", "none"})
|
||||
|
||||
|
||||
class ProfileError(ValueError):
|
||||
"""A channel profile is missing, unreadable or does not match the schema."""
|
||||
|
||||
|
||||
# --- typed coercion --------------------------------------------------------
|
||||
|
||||
def _require_mapping(value: Any, where: str) -> Mapping:
|
||||
if not isinstance(value, Mapping):
|
||||
raise ProfileError(f"{where} must be a JSON object, got {type(value).__name__}")
|
||||
return value
|
||||
|
||||
|
||||
def _as_str(value: Any, where: str, default: str) -> str:
|
||||
if value is None:
|
||||
return default
|
||||
if not isinstance(value, str):
|
||||
raise ProfileError(f"{where} must be a string, got {type(value).__name__}")
|
||||
return value
|
||||
|
||||
|
||||
def _as_optional_str(value: Any, where: str) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
if not isinstance(value, str):
|
||||
raise ProfileError(f"{where} must be a string or null, got {type(value).__name__}")
|
||||
return value
|
||||
|
||||
|
||||
def _as_int(value: Any, where: str, default: int) -> int:
|
||||
if value is None:
|
||||
return default
|
||||
# bool is an int subclass in Python; a JSON true is not a valid count.
|
||||
if isinstance(value, bool) or not isinstance(value, int):
|
||||
raise ProfileError(f"{where} must be an integer, got {type(value).__name__}")
|
||||
return value
|
||||
|
||||
|
||||
def _as_bool(value: Any, where: str, default: bool) -> bool:
|
||||
if value is None:
|
||||
return default
|
||||
if not isinstance(value, bool):
|
||||
raise ProfileError(f"{where} must be a boolean, got {type(value).__name__}")
|
||||
return value
|
||||
|
||||
|
||||
def _as_str_list(value: Any, where: str, default: Sequence[str]) -> list[str]:
|
||||
if value is None:
|
||||
return list(default)
|
||||
if isinstance(value, str) or not isinstance(value, Sequence):
|
||||
raise ProfileError(
|
||||
f"{where} must be a JSON array of strings, got {type(value).__name__}"
|
||||
)
|
||||
out: list[str] = []
|
||||
for i, item in enumerate(value):
|
||||
if not isinstance(item, str):
|
||||
raise ProfileError(f"{where}[{i}] must be a string, got {type(item).__name__}")
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
|
||||
def _as_dict_list(value: Any, where: str, default: Sequence[Mapping]) -> list[dict]:
|
||||
if value is None:
|
||||
return [dict(d) for d in default]
|
||||
if isinstance(value, str) or not isinstance(value, Sequence):
|
||||
raise ProfileError(
|
||||
f"{where} must be a JSON array of objects, got {type(value).__name__}"
|
||||
)
|
||||
out: list[dict] = []
|
||||
for i, item in enumerate(value):
|
||||
if not isinstance(item, Mapping):
|
||||
raise ProfileError(
|
||||
f"{where}[{i}] must be a JSON object, got {type(item).__name__}"
|
||||
)
|
||||
out.append(dict(item))
|
||||
return out
|
||||
|
||||
|
||||
def _as_enum(value: Any, where: str, allowed: frozenset, default: str) -> str:
|
||||
if value is None:
|
||||
return default
|
||||
if value not in allowed:
|
||||
options = ", ".join(sorted(allowed))
|
||||
raise ProfileError(f"{where} must be one of {{{options}}}, got {value!r}")
|
||||
return value
|
||||
|
||||
|
||||
# --- schema ----------------------------------------------------------------
|
||||
|
||||
@dataclass
|
||||
class TitleRules:
|
||||
"""Deterministic title constraints (consumed by the #3 validator)."""
|
||||
|
||||
max_chars: int = 70
|
||||
mobile_chars: int = 40
|
||||
banned_patterns: list[str] = field(default_factory=list)
|
||||
keyword_position: str = "start"
|
||||
number_policy: str = "allow"
|
||||
required_signal: str = "either"
|
||||
banned_openers: list[str] = field(default_factory=list)
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Mapping, where: str = "title_rules") -> "TitleRules":
|
||||
data = _require_mapping(data, where)
|
||||
return cls(
|
||||
max_chars=_as_int(data.get("max_chars"), f"{where}.max_chars", 70),
|
||||
mobile_chars=_as_int(data.get("mobile_chars"), f"{where}.mobile_chars", 40),
|
||||
banned_patterns=_as_str_list(
|
||||
data.get("banned_patterns"), f"{where}.banned_patterns", ()
|
||||
),
|
||||
keyword_position=_as_enum(
|
||||
data.get("keyword_position"), f"{where}.keyword_position",
|
||||
KEYWORD_POSITIONS, "start",
|
||||
),
|
||||
number_policy=_as_enum(
|
||||
data.get("number_policy"), f"{where}.number_policy",
|
||||
NUMBER_POLICIES, "allow",
|
||||
),
|
||||
required_signal=_as_enum(
|
||||
data.get("required_signal"), f"{where}.required_signal",
|
||||
REQUIRED_SIGNALS, "either",
|
||||
),
|
||||
banned_openers=_as_str_list(
|
||||
data.get("banned_openers"), f"{where}.banned_openers", ()
|
||||
),
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
"""Serialise to the exact shape :meth:`from_dict` accepts."""
|
||||
return {
|
||||
"max_chars": self.max_chars,
|
||||
"mobile_chars": self.mobile_chars,
|
||||
"banned_patterns": list(self.banned_patterns),
|
||||
"keyword_position": self.keyword_position,
|
||||
"number_policy": self.number_policy,
|
||||
"required_signal": self.required_signal,
|
||||
"banned_openers": list(self.banned_openers),
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class ThumbnailRules:
|
||||
"""Thumbnail concept roles and look (consumed by #4)."""
|
||||
|
||||
role_order: list[str] = field(
|
||||
default_factory=lambda: ["curiosity", "emotion", "technical"]
|
||||
)
|
||||
palette: list[str] = field(default_factory=list)
|
||||
presenter_photo: bool = False
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Mapping, where: str = "thumbnail") -> "ThumbnailRules":
|
||||
data = _require_mapping(data, where)
|
||||
return cls(
|
||||
role_order=_as_str_list(
|
||||
data.get("role_order"), f"{where}.role_order",
|
||||
["curiosity", "emotion", "technical"],
|
||||
),
|
||||
palette=_as_str_list(data.get("palette"), f"{where}.palette", ()),
|
||||
presenter_photo=_as_bool(
|
||||
data.get("presenter_photo"), f"{where}.presenter_photo", False
|
||||
),
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
"""Serialise to the exact shape :meth:`from_dict` accepts."""
|
||||
return {
|
||||
"role_order": list(self.role_order),
|
||||
"palette": list(self.palette),
|
||||
"presenter_photo": self.presenter_photo,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Profile:
|
||||
"""One channel's packaging rules."""
|
||||
|
||||
slug: str
|
||||
# Human-readable display name for selectors; falls back to ``slug`` when unset.
|
||||
name: str = ""
|
||||
language: str = "en"
|
||||
tone: str = ""
|
||||
title_rules: TitleRules = field(default_factory=TitleRules)
|
||||
hook_patterns: list[str] = field(default_factory=list)
|
||||
hook_style: str = ""
|
||||
description_template: str = ""
|
||||
links: list[str] = field(default_factory=list)
|
||||
thumbnail: ThumbnailRules = field(default_factory=ThumbnailRules)
|
||||
default_postiz_integration_id: str | None = None
|
||||
published_video_history: list[dict] = field(default_factory=list)
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Mapping, slug: str) -> "Profile":
|
||||
data = _require_mapping(data, f"profile {slug!r}")
|
||||
raw_title = data.get("title_rules")
|
||||
raw_thumb = data.get("thumbnail")
|
||||
return cls(
|
||||
slug=slug,
|
||||
name=_as_str(data.get("name"), "name", ""),
|
||||
language=_as_str(data.get("language"), "language", "en"),
|
||||
tone=_as_str(data.get("tone"), "tone", ""),
|
||||
title_rules=TitleRules.from_dict({} if raw_title is None else raw_title),
|
||||
hook_patterns=_as_str_list(data.get("hook_patterns"), "hook_patterns", ()),
|
||||
hook_style=_as_str(data.get("hook_style"), "hook_style", ""),
|
||||
description_template=_as_str(
|
||||
data.get("description_template"), "description_template", ""
|
||||
),
|
||||
links=_as_str_list(data.get("links"), "links", ()),
|
||||
thumbnail=ThumbnailRules.from_dict({} if raw_thumb is None else raw_thumb),
|
||||
default_postiz_integration_id=_as_optional_str(
|
||||
data.get("default_postiz_integration_id"),
|
||||
"default_postiz_integration_id",
|
||||
),
|
||||
published_video_history=_as_dict_list(
|
||||
data.get("published_video_history"), "published_video_history", ()
|
||||
),
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
"""Serialise every field except ``slug``.
|
||||
|
||||
The result matches :meth:`from_dict`'s expected shapes exactly, so
|
||||
``Profile.from_dict(p.to_dict(), p.slug)`` round-trips.
|
||||
"""
|
||||
return {
|
||||
"name": self.name,
|
||||
"language": self.language,
|
||||
"tone": self.tone,
|
||||
"title_rules": self.title_rules.to_dict(),
|
||||
"hook_patterns": list(self.hook_patterns),
|
||||
"hook_style": self.hook_style,
|
||||
"description_template": self.description_template,
|
||||
"links": list(self.links),
|
||||
"thumbnail": self.thumbnail.to_dict(),
|
||||
"default_postiz_integration_id": self.default_postiz_integration_id,
|
||||
"published_video_history": [dict(item) for item in self.published_video_history],
|
||||
}
|
||||
|
||||
|
||||
def _load_profile_file(slug: str, directory: Path) -> Profile:
|
||||
"""Read and validate ``<directory>/<slug>.json`` (file-backed seam)."""
|
||||
path = directory / f"{slug}.json"
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8")
|
||||
except FileNotFoundError:
|
||||
raise ProfileError(f"channel profile not found: {path}")
|
||||
except OSError as e:
|
||||
raise ProfileError(f"could not read channel profile {path}: {e}")
|
||||
|
||||
try:
|
||||
data = json.loads(text)
|
||||
except json.JSONDecodeError as e:
|
||||
raise ProfileError(f"malformed JSON in {path}: {e}")
|
||||
|
||||
return Profile.from_dict(data, slug)
|
||||
|
||||
|
||||
def _list_profiles_dir(directory: Path) -> list[dict]:
|
||||
"""Best-effort ``[{"slug", "name"}]`` scan of a ``channels/`` directory."""
|
||||
if not directory.is_dir():
|
||||
return []
|
||||
|
||||
out: list[dict] = []
|
||||
for path in sorted(directory.glob("*.json")):
|
||||
slug = path.stem
|
||||
if not _SLUG_RE.match(slug):
|
||||
continue
|
||||
try:
|
||||
profile = _load_profile_file(slug, directory)
|
||||
except ProfileError:
|
||||
continue
|
||||
out.append({"slug": slug, "name": profile.name or slug})
|
||||
return out
|
||||
|
||||
|
||||
def load_profile(slug: str | None = None, channels_dir: str | os.PathLike | None = None) -> Profile:
|
||||
"""Load and validate a channel profile.
|
||||
|
||||
``slug`` wins; when it is omitted the ``CHANNEL_PROFILE`` env var is used.
|
||||
With ``channels_dir`` the legacy ``<dir>/<slug>.json`` file is read; without
|
||||
it the SQLite store is the source of truth.
|
||||
"""
|
||||
resolved = slug or os.environ.get(ENV_VAR) or None
|
||||
if not resolved:
|
||||
raise ProfileError(f"no channel profile selected; pass a slug or set {ENV_VAR}")
|
||||
if not _SLUG_RE.match(resolved):
|
||||
raise ProfileError(
|
||||
f"invalid channel slug {resolved!r}; expected letters, digits, '-' or '_'"
|
||||
)
|
||||
|
||||
if channels_dir is not None:
|
||||
return _load_profile_file(resolved, Path(channels_dir))
|
||||
|
||||
from clipwright.storage import channel_profiles as store
|
||||
|
||||
raw = store.get_raw(resolved)
|
||||
if raw is None:
|
||||
raise ProfileError(f"channel profile not found: {resolved}")
|
||||
return Profile.from_dict(raw, resolved)
|
||||
|
||||
|
||||
def list_profiles(channels_dir: str | os.PathLike | None = None) -> list[dict]:
|
||||
"""List the loadable channel profiles as ``[{"slug", "name"}]``.
|
||||
|
||||
With ``channels_dir`` this scans that directory; otherwise it reads the
|
||||
SQLite store. Best-effort by design: a malformed legacy file is skipped
|
||||
rather than breaking a selector, and ``name`` falls back to ``slug`` when a
|
||||
profile omits its display name.
|
||||
"""
|
||||
if channels_dir is not None:
|
||||
return _list_profiles_dir(Path(channels_dir))
|
||||
|
||||
from clipwright.storage import channel_profiles as store
|
||||
|
||||
return store.list_summaries()
|
||||
|
||||
|
||||
def save_profile(slug: str, data: Mapping) -> Profile:
|
||||
"""Validate ``data`` and upsert it into the store under ``slug``."""
|
||||
if not isinstance(slug, str) or not _SLUG_RE.match(slug):
|
||||
raise ProfileError(
|
||||
f"invalid channel slug {slug!r}; expected letters, digits, '-' or '_'"
|
||||
)
|
||||
profile = Profile.from_dict(data, slug)
|
||||
|
||||
from clipwright.storage import channel_profiles as store
|
||||
|
||||
store.upsert(slug, profile.name or slug, profile.to_dict())
|
||||
return profile
|
||||
|
||||
|
||||
def delete_profile(slug: str) -> bool:
|
||||
"""Delete a stored profile; ``True`` when it existed."""
|
||||
from clipwright.storage import channel_profiles as store
|
||||
|
||||
return store.delete(slug)
|
||||
|
||||
|
||||
def profile_payload(slug: str) -> dict:
|
||||
"""The API shape for one profile: ``{"slug", **profile.to_dict()}``."""
|
||||
from clipwright.storage import channel_profiles as store
|
||||
|
||||
raw = store.get_raw(slug)
|
||||
if raw is None:
|
||||
raise ProfileError(f"channel profile not found: {slug}")
|
||||
return {"slug": slug, **Profile.from_dict(raw, slug).to_dict()}
|
||||
|
||||
|
||||
def export_payload() -> dict:
|
||||
"""A portable export document: ``{"version": 1, "profiles": [...]}``."""
|
||||
from clipwright.storage import channel_profiles as store
|
||||
|
||||
profiles_out: list[dict] = []
|
||||
for raw in store.list_raw():
|
||||
slug = raw["slug"]
|
||||
profiles_out.append({"slug": slug, **Profile.from_dict(raw, slug).to_dict()})
|
||||
return {"version": 1, "profiles": profiles_out}
|
||||
|
||||
|
||||
def import_payload(payload: Any) -> dict:
|
||||
"""Import profiles from an export document, a bare list or a single dict.
|
||||
|
||||
Bad items are reported in ``failed`` instead of aborting the batch; a
|
||||
payload that is neither a JSON object nor array raises :class:`ProfileError`.
|
||||
"""
|
||||
if isinstance(payload, dict):
|
||||
raw_items = payload.get("profiles")
|
||||
items = raw_items if isinstance(raw_items, list) else [payload]
|
||||
elif isinstance(payload, list):
|
||||
items = payload
|
||||
else:
|
||||
raise ProfileError("channel profile import must be a JSON object or array")
|
||||
|
||||
imported = 0
|
||||
failed: list[dict] = []
|
||||
for item in items:
|
||||
if not isinstance(item, Mapping):
|
||||
failed.append({"slug": "", "error": "profile entry must be a JSON object"})
|
||||
continue
|
||||
slug = item.get("slug")
|
||||
if not isinstance(slug, str) or not slug:
|
||||
failed.append({"slug": "", "error": "profile entry is missing a slug"})
|
||||
continue
|
||||
data = {key: value for key, value in item.items() if key != "slug"}
|
||||
try:
|
||||
save_profile(slug, data)
|
||||
except ProfileError as e:
|
||||
failed.append({"slug": slug, "error": str(e)})
|
||||
continue
|
||||
imported += 1
|
||||
return {"imported": imported, "failed": failed}
|
||||
|
|
@ -16,15 +16,16 @@ import sys
|
|||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
from clipwright.core.paths import REPO_ROOT
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
def _find_cookies_path():
|
||||
# Mirrors main.py's cookie discovery.
|
||||
script_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
for candidate in [
|
||||
os.path.join(script_dir, 'www.youtube.com_cookies.txt'),
|
||||
os.path.join(script_dir, 'cookies.txt'),
|
||||
str(REPO_ROOT / 'www.youtube.com_cookies.txt'),
|
||||
str(REPO_ROOT / 'cookies.txt'),
|
||||
'/app/cookies.txt',
|
||||
]:
|
||||
if os.path.exists(candidate):
|
||||
|
|
@ -44,8 +45,8 @@ def main() -> int:
|
|||
# result is the fail-open "unknown", so the caller carries on and the
|
||||
# real probe / download refuse the URL with their own message.
|
||||
try:
|
||||
from security_utils import assert_public_url
|
||||
from yt_clients import youtube_non_video_reason
|
||||
from clipwright.core.security_utils import assert_public_url
|
||||
from clipwright.integrations.yt_clients import youtube_non_video_reason
|
||||
assert_public_url(args.url)
|
||||
if youtube_non_video_reason(args.url):
|
||||
raise ValueError("not a single video")
|
||||
|
|
@ -32,7 +32,7 @@ import tempfile
|
|||
import threading
|
||||
import time
|
||||
|
||||
from subtitles import (
|
||||
from clipwright.media.subtitles import (
|
||||
get_whisper_config,
|
||||
WHISPER_TRANSCRIBE_PARAMS,
|
||||
merge_continuation_words,
|
||||
|
|
@ -368,7 +368,7 @@ def release_models():
|
|||
del whisper, parakeet
|
||||
# TransNetV2 is the other torch tenant an in-process pipeline leaves
|
||||
# behind (scene_detection keeps it as a module singleton too).
|
||||
tn2 = sys.modules.get("scene_detection")
|
||||
tn2 = sys.modules.get("clipwright.media.scene_detection")
|
||||
if tn2 is not None:
|
||||
tn2._tn2_model = None
|
||||
import gc
|
||||
6
clipwright/storage/__init__.py
Normal file
6
clipwright/storage/__init__.py
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
"""Local persistence helpers for the Clipwright backend.
|
||||
|
||||
Right now this package holds the SQLite-backed channel profile store; future
|
||||
runtime state can follow the same shape (stdlib ``sqlite3``, one file at the
|
||||
repo root, lazily created schema).
|
||||
"""
|
||||
176
clipwright/storage/channel_profiles.py
Normal file
176
clipwright/storage/channel_profiles.py
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
"""SQLite-backed channel profile store.
|
||||
|
||||
This is the runtime source of truth for channel profiles. It replaces the
|
||||
committed ``channels/<slug>.json`` files: on the very first bootstrap (the
|
||||
``seeded`` key is absent from ``meta``) any profile files that the file loader
|
||||
still accepts are imported once, then the guard is set so later runs never
|
||||
re-read the directory. Set ``CLIPWRIGHT_DB`` to move the database; otherwise it
|
||||
lives at ``<repo>/clipwright.sqlite3``.
|
||||
|
||||
Threading: FastAPI sync endpoints run in a threadpool, so every public
|
||||
operation is serialized by a module-level re-entrant lock. The pipeline runs in
|
||||
a separate process and relies on SQLite's own locking (WAL + busy timeout).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import threading
|
||||
from collections.abc import Mapping
|
||||
from pathlib import Path
|
||||
|
||||
from clipwright.core.paths import REPO_ROOT
|
||||
|
||||
_LOCK = threading.RLock()
|
||||
|
||||
_SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS channel_profiles (
|
||||
slug TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL DEFAULT '',
|
||||
data TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS meta (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
"""
|
||||
|
||||
|
||||
def db_path() -> Path:
|
||||
"""Location of the profile database (``CLIPWRIGHT_DB`` overrides)."""
|
||||
override = os.environ.get("CLIPWRIGHT_DB")
|
||||
if override:
|
||||
return Path(override)
|
||||
return REPO_ROOT / "clipwright.sqlite3"
|
||||
|
||||
|
||||
def _connect() -> sqlite3.Connection:
|
||||
path = db_path()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
conn = sqlite3.connect(path, timeout=15)
|
||||
conn.row_factory = sqlite3.Row
|
||||
conn.execute("PRAGMA journal_mode=WAL")
|
||||
conn.execute("PRAGMA busy_timeout=15000")
|
||||
return conn
|
||||
|
||||
|
||||
def _bootstrap(conn: sqlite3.Connection) -> None:
|
||||
"""Create the schema if missing and run the one-time file import."""
|
||||
conn.executescript(_SCHEMA)
|
||||
_seed_if_needed(conn)
|
||||
|
||||
|
||||
def _seed_if_needed(conn: sqlite3.Connection) -> None:
|
||||
seeded = conn.execute("SELECT value FROM meta WHERE key = 'seeded'").fetchone()
|
||||
if seeded is not None:
|
||||
return
|
||||
|
||||
# Lazy import: profiles imports this module from inside its own functions,
|
||||
# so a top-level import here would be circular.
|
||||
from clipwright.pipeline import profiles
|
||||
|
||||
directory = profiles.CHANNELS_DIR
|
||||
if directory.is_dir():
|
||||
for path in sorted(directory.glob("*.json")):
|
||||
slug = path.stem
|
||||
try:
|
||||
profile = profiles.load_profile(slug, channels_dir=directory)
|
||||
except profiles.ProfileError:
|
||||
continue
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO channel_profiles (slug, name, data) "
|
||||
"VALUES (?, ?, ?)",
|
||||
(slug, profile.name or slug, json.dumps(profile.to_dict(), ensure_ascii=False)),
|
||||
)
|
||||
conn.execute("INSERT OR REPLACE INTO meta (key, value) VALUES ('seeded', '1')")
|
||||
|
||||
|
||||
def _row_to_dict(row: sqlite3.Row) -> dict:
|
||||
data = json.loads(row["data"])
|
||||
data["slug"] = row["slug"]
|
||||
return data
|
||||
|
||||
|
||||
def get_raw(slug: str) -> dict | None:
|
||||
"""Return the stored profile dict (with ``slug`` injected) or ``None``."""
|
||||
with _LOCK:
|
||||
conn = _connect()
|
||||
try:
|
||||
_bootstrap(conn)
|
||||
conn.commit()
|
||||
row = conn.execute(
|
||||
"SELECT slug, data FROM channel_profiles WHERE slug = ?", (slug,)
|
||||
).fetchone()
|
||||
return _row_to_dict(row) if row is not None else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def list_raw() -> list[dict]:
|
||||
"""Every stored profile as a parsed dict with ``slug`` injected."""
|
||||
with _LOCK:
|
||||
conn = _connect()
|
||||
try:
|
||||
_bootstrap(conn)
|
||||
conn.commit()
|
||||
rows = conn.execute(
|
||||
"SELECT slug, data FROM channel_profiles ORDER BY slug"
|
||||
).fetchall()
|
||||
return [_row_to_dict(row) for row in rows]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def list_summaries() -> list[dict]:
|
||||
"""``[{"slug", "name"}]`` for every profile, sorted by slug."""
|
||||
with _LOCK:
|
||||
conn = _connect()
|
||||
try:
|
||||
_bootstrap(conn)
|
||||
conn.commit()
|
||||
rows = conn.execute(
|
||||
"SELECT slug, name FROM channel_profiles ORDER BY slug"
|
||||
).fetchall()
|
||||
return [{"slug": row["slug"], "name": row["name"] or row["slug"]} for row in rows]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def upsert(slug: str, name: str, data: Mapping) -> None:
|
||||
"""Insert or replace a profile row (``updated_at`` is bumped on replace)."""
|
||||
payload = json.dumps(dict(data), ensure_ascii=False)
|
||||
with _LOCK:
|
||||
conn = _connect()
|
||||
try:
|
||||
_bootstrap(conn)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO channel_profiles (slug, name, data)
|
||||
VALUES (?, ?, ?)
|
||||
ON CONFLICT(slug) DO UPDATE SET
|
||||
name = excluded.name,
|
||||
data = excluded.data,
|
||||
updated_at = datetime('now')
|
||||
""",
|
||||
(slug, name, payload),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def delete(slug: str) -> bool:
|
||||
"""Delete a profile; ``True`` when a row was removed."""
|
||||
with _LOCK:
|
||||
conn = _connect()
|
||||
try:
|
||||
_bootstrap(conn)
|
||||
cursor = conn.execute("DELETE FROM channel_profiles WHERE slug = ?", (slug,))
|
||||
conn.commit()
|
||||
return cursor.rowcount > 0
|
||||
finally:
|
||||
conn.close()
|
||||
1
clipwright/tools/__init__.py
Normal file
1
clipwright/tools/__init__.py
Normal file
|
|
@ -0,0 +1 @@
|
|||
"""Clipwright backend."""
|
||||
|
|
@ -1,8 +1,7 @@
|
|||
import os
|
||||
import shutil
|
||||
# Check if PIL is installed, if not we can't run this locally but it will run in docker
|
||||
try:
|
||||
from hooks import create_hook_image
|
||||
from clipwright.media.hooks import create_hook_image
|
||||
except ImportError:
|
||||
print("⚠️ PIL not found locally. Please run this inside the Docker container.")
|
||||
# Mocking for local check if needed or just exit
|
||||
169
clipwright/tools/verify_code_layout.py
Normal file
169
clipwright/tools/verify_code_layout.py
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
"""Calibration tool for the CODE/TERMINAL layout.
|
||||
|
||||
Usage (from the repo root):
|
||||
|
||||
python -m clipwright.tools.verify_code_layout path/to/recording.mp4 \
|
||||
--start 12.0 --duration 8 --out-dir output/code_layout
|
||||
|
||||
It forces the layout on (ignoring ``CODE_LAYOUT``), detects the pane, prints
|
||||
pane / confidence / mode, writes:
|
||||
|
||||
- ``debug_bands.png`` — a schematic of the 9:16 output with the code band and
|
||||
the caption reserve marked;
|
||||
- ``still.png`` — a real render through ``code_filtergraph`` at ``--start``.
|
||||
|
||||
Exit codes: 0 on a detected pane and a rendered still; 1 when nothing detects
|
||||
(so a corpus sweep can flag misses); 2 when cv2 is unavailable.
|
||||
|
||||
The detection thresholds in ``code_layout`` are estimates from first
|
||||
principles. Run this across a set of real 1440p IDE and terminal recordings and
|
||||
tune ``CODE_*`` from what actually lands here.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
DEFAULT_OUT = "output/code_layout"
|
||||
|
||||
|
||||
def _parse_args(argv):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("video", help="path to the source recording")
|
||||
parser.add_argument("--start", type=float, default=0.0,
|
||||
help="segment start in seconds")
|
||||
parser.add_argument("--duration", type=float, default=6.0,
|
||||
help="seconds of active-line tracking to sample")
|
||||
parser.add_argument("--samples", type=int, default=12,
|
||||
help="frames sampled for pane detection")
|
||||
parser.add_argument("--out-w", type=int, default=1080)
|
||||
parser.add_argument("--out-h", type=int, default=1920)
|
||||
parser.add_argument("--out-dir", default=DEFAULT_OUT)
|
||||
parser.add_argument("--no-follow", action="store_true",
|
||||
help="skip active-line tracking (static window)")
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def _draw_bands(path, pane, out_w, out_h, graph):
|
||||
"""Schematic of the output: backdrop, code band, caption reserve."""
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
canvas = np.full((out_h, out_w, 3), 32, dtype=np.uint8)
|
||||
content_h, caption_h = _bands(out_h)
|
||||
scale = out_w / float(pane["w"])
|
||||
scaled_h = min(content_h, int(round(pane["h"] * scale)))
|
||||
y_off = max(0, (content_h - scaled_h) // 2)
|
||||
|
||||
cv2.rectangle(canvas, (0, y_off), (out_w - 1, y_off + scaled_h),
|
||||
(40, 160, 40), thickness=-1)
|
||||
cv2.rectangle(canvas, (0, out_h - caption_h), (out_w - 1, out_h - 1),
|
||||
(160, 90, 40), thickness=-1)
|
||||
cv2.putText(canvas, f"pane {pane['w']}x{pane['h']} @ {pane['x']},{pane['y']}",
|
||||
(16, 40), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2)
|
||||
cv2.putText(canvas, f"code band h={scaled_h}",
|
||||
(16, y_off + max(30, scaled_h // 2)),
|
||||
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 255, 255), 2)
|
||||
cv2.putText(canvas, "caption reserve",
|
||||
(16, out_h - caption_h + max(30, caption_h // 2)),
|
||||
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2)
|
||||
if "sendcmd" in graph:
|
||||
cv2.putText(canvas, "sendcmd follow ON",
|
||||
(16, out_h - 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7,
|
||||
(80, 220, 255), 2)
|
||||
cv2.imwrite(path, canvas)
|
||||
|
||||
|
||||
def _bands(out_h):
|
||||
from clipwright.layouts import code_layout
|
||||
return code_layout.code_bands(out_h)
|
||||
|
||||
|
||||
def _render_still(video, start, graph, out_path):
|
||||
cmd = [
|
||||
"ffmpeg", "-y", "-loglevel", "error",
|
||||
"-ss", f"{start:.4f}", "-i", video,
|
||||
"-frames:v", "1",
|
||||
"-filter_complex", graph, "-map", "[v]",
|
||||
out_path,
|
||||
]
|
||||
proc = subprocess.run(cmd, capture_output=True, text=True)
|
||||
if proc.returncode != 0:
|
||||
print(f"❌ ffmpeg failed:\n{proc.stderr}")
|
||||
return False
|
||||
return os.path.exists(out_path) and os.path.getsize(out_path) > 0
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
args = _parse_args(argv if argv is not None else sys.argv[1:])
|
||||
try:
|
||||
import cv2 # noqa: F401 (presence check only)
|
||||
except ImportError:
|
||||
print("❌ OpenCV (cv2) is required to run this tool.")
|
||||
return 2
|
||||
|
||||
from clipwright.layouts import code_layout
|
||||
code_layout.ENABLED = True
|
||||
code_layout.FOLLOW_ENABLED = True
|
||||
|
||||
if not os.path.exists(args.video):
|
||||
print(f"❌ No such video: {args.video}")
|
||||
return 1
|
||||
|
||||
os.makedirs(args.out_dir, exist_ok=True)
|
||||
|
||||
pane = code_layout.detect_code_pane(args.video, samples=args.samples)
|
||||
if pane is None:
|
||||
print("❌ No code pane detected — nothing to render. "
|
||||
"Tune CODE_PANE_MIN_* / CODE_EDGE_DENSITY / CODE_STABILITY_*.")
|
||||
return 1
|
||||
|
||||
print(f"✅ Pane: x={pane['x']} y={pane['y']} w={pane['w']} h={pane['h']} "
|
||||
f"({pane['w']}x{pane['h']})")
|
||||
print(f" mode={pane['mode']} confidence={pane['confidence']:.2f} "
|
||||
f"frame={pane['frame_w']}x{pane['frame_h']}")
|
||||
|
||||
# Mirror reframe_v2: if the text column is still wider than the readable
|
||||
# scale allows, crop it to out_w / MIN_SCALE rather than falling back.
|
||||
max_w = max(2, int(args.out_w / code_layout.MIN_SCALE))
|
||||
clamped = code_layout.clamp_pane_width(pane, max_w)
|
||||
if clamped[2] != pane["w"]:
|
||||
print(f" clamped text column {pane['w']} -> {clamped[2]}px "
|
||||
f"(CODE_MIN_SCALE={code_layout.MIN_SCALE})")
|
||||
pane = dict(pane, x=clamped[0], y=clamped[1], w=clamped[2], h=clamped[3])
|
||||
print(f" scale: {args.out_w / float(pane['w']):.2f}")
|
||||
|
||||
follow = None
|
||||
if not args.no_follow:
|
||||
series = code_layout.active_line_series(
|
||||
args.video, pane, args.start, args.start + args.duration)
|
||||
if series:
|
||||
# code_filtergraph expects timestamps relative to the segment start.
|
||||
follow = [(t - args.start, y) for t, y in series]
|
||||
print(f" follow: {len(follow)} points over "
|
||||
f"{follow[0][0]:.1f}-{follow[-1][0]:.1f}s")
|
||||
else:
|
||||
print(" follow: no reliable active-line series (static window)")
|
||||
|
||||
graph = code_layout.code_filtergraph(pane, args.out_w, args.out_h,
|
||||
follow=follow)
|
||||
if graph is None:
|
||||
scale = args.out_w / float(max(1, pane["w"]))
|
||||
print(f"❌ Scale {scale:.2f} < CODE_MIN_SCALE "
|
||||
f"({code_layout.MIN_SCALE}) — this clip falls back to "
|
||||
f"SCREENCAST/WIDE.")
|
||||
return 1
|
||||
|
||||
debug_path = os.path.join(args.out_dir, "debug_bands.png")
|
||||
still_path = os.path.join(args.out_dir, "still.png")
|
||||
_draw_bands(debug_path, pane, args.out_w, args.out_h, graph)
|
||||
if not _render_still(args.video, args.start, graph, still_path):
|
||||
return 1
|
||||
|
||||
print(f"🖼️ wrote {debug_path}")
|
||||
print(f"🖼️ wrote {still_path}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import os
|
||||
try:
|
||||
from hooks import create_hook_image
|
||||
from clipwright.media.hooks import create_hook_image
|
||||
except ImportError:
|
||||
print("⚠️ PIL not found locally. Run inside Docker.")
|
||||
exit(1)
|
||||
|
|
@ -1,6 +1,5 @@
|
|||
import os
|
||||
import shutil
|
||||
from hooks import create_hook_image
|
||||
from clipwright.media.hooks import create_hook_image
|
||||
|
||||
def verify():
|
||||
print("🧪 Verifying Hook Image Generation...")
|
||||
|
|
@ -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:
|
||||
|
||||
- [@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
|
||||
- [@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
|
||||
|
||||
## 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.
|
||||
- `npm install` — install dependencies
|
||||
- `npm run dev` — dev server with HMR
|
||||
- `npm run build` — production build to `dist/`
|
||||
- `npm run preview` — serve the built output
|
||||
- `npm run lint` — ESLint
|
||||
|
|
|
|||
2
dashboard/e2e/.gitignore
vendored
Normal file
2
dashboard/e2e/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
.artifacts/
|
||||
.test-results/
|
||||
398
dashboard/e2e/fixtures/api-mocks.js
Normal file
398
dashboard/e2e/fixtures/api-mocks.js
Normal file
|
|
@ -0,0 +1,398 @@
|
|||
// 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' });
|
||||
}
|
||||
|
||||
if (method === 'GET' && /^\/api\/jobs\/[^/]+\/clip\/\d+\/download$/.test(path)) {
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/zip',
|
||||
headers: { 'content-disposition': 'attachment; filename="Test Clip.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
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
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
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');
|
||||
94
dashboard/e2e/playwright.config.js
Normal file
94
dashboard/e2e/playwright.config.js
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
// 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.
|
||||
//
|
||||
// The `real` project and its backend webServer only exist when CW_E2E_REAL is
|
||||
// set (CI sets it). A bare `npm run test:e2e` therefore stays mock-only and
|
||||
// needs no Python deps.
|
||||
/* global process */
|
||||
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)), '..');
|
||||
const repoRoot = path.resolve(dashboardDir, '..');
|
||||
|
||||
const realBackend = !!process.env.CW_E2E_REAL;
|
||||
|
||||
const webServers = [
|
||||
{
|
||||
command: 'npm run build && npx vite preview --port 4173 --strictPort --host 127.0.0.1',
|
||||
cwd: dashboardDir,
|
||||
url: 'http://127.0.0.1:4173',
|
||||
reuseExistingServer: !process.env.CI,
|
||||
timeout: 120_000,
|
||||
stdout: 'ignore',
|
||||
stderr: 'pipe',
|
||||
},
|
||||
];
|
||||
|
||||
if (realBackend) {
|
||||
// Real `uvicorn clipwright.api.app:app` with the pipeline's stub_env on
|
||||
// PYTHONPATH: sitecustomize stubs the ML/network edges so the real CLI runs
|
||||
// with real ffmpeg, no model downloads and no outbound requests. The env
|
||||
// values mirror tests/e2e/pipeline's deterministic, no-ML configuration.
|
||||
webServers.push({
|
||||
command: 'python -m uvicorn clipwright.api.app:app --host 127.0.0.1 --port 8000 --log-level warning',
|
||||
cwd: repoRoot,
|
||||
url: 'http://127.0.0.1:8000/health',
|
||||
reuseExistingServer: !process.env.CI,
|
||||
timeout: 120_000,
|
||||
stdout: 'ignore',
|
||||
stderr: 'pipe',
|
||||
env: {
|
||||
PYTHONPATH: ['tests/e2e/pipeline/stub_env', '.'].join(path.delimiter),
|
||||
GEMINI_API_KEY: 'test',
|
||||
MIN_SOURCE_SECONDS: '0',
|
||||
QUALITY_GATE_MIN_HEIGHT: '0',
|
||||
AUTO_LAYOUT: '0',
|
||||
SCENE_ENGINE: 'pyscenedetect',
|
||||
ASR_HOST_SLOTS: '0',
|
||||
FFMPEG_ENCODER: 'x264',
|
||||
TZ: 'UTC',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export default defineConfig({
|
||||
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'] },
|
||||
},
|
||||
// The real lane runs the full pipeline, which needs more than the 30s
|
||||
// default. Gated so a mock-only run never tries to boot Python.
|
||||
...(realBackend ? [{
|
||||
name: 'real',
|
||||
testMatch: /real-backend\.spec\.js/,
|
||||
timeout: 120_000,
|
||||
use: { ...devices['Desktop Chrome'] },
|
||||
}] : []),
|
||||
],
|
||||
webServer: webServers,
|
||||
});
|
||||
35
dashboard/e2e/specs/clip-editor.spec.js
Normal file
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
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
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
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
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();
|
||||
});
|
||||
});
|
||||
33
dashboard/e2e/specs/real-backend.spec.js
Normal file
33
dashboard/e2e/specs/real-backend.spec.js
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
import { test, expect } from '@playwright/test';
|
||||
import { seedApp } from '../fixtures/app.js';
|
||||
import { SIXTY_MP4 } from '../fixtures/media.js';
|
||||
|
||||
// Real-backend lane.
|
||||
//
|
||||
// Drives the built app against a real `uvicorn clipwright.api.app:app` whose
|
||||
// pipeline runs the real CLI through tests/e2e/pipeline/stub_env (fake ML/ASR/
|
||||
// Gemini, real ffmpeg). No route mocks: the preview server proxies /api,
|
||||
// /videos and /thumbnails to the backend (vite.config.js preview.proxy), so
|
||||
// every request in this spec is served by Python. The spec is only collected
|
||||
// when CW_E2E_REAL is set; the `mock` lane ignores it.
|
||||
test.describe('real backend', () => {
|
||||
test('generates a clip against a real uvicorn + stub_env server', async ({ page }) => {
|
||||
// Seed the BYOK Gemini key (and consent) exactly like the mock specs.
|
||||
// No installApiMocks: this lane talks to the real server.
|
||||
await seedApp(page, { geminiKey: 'e2e-gemini-key' });
|
||||
await page.goto('/#app');
|
||||
|
||||
await expect(page.getByRole('heading', { name: /create viral shorts/i })).toBeVisible();
|
||||
|
||||
// Upload the ffmpeg-built fixture, attest rights, submit.
|
||||
await page.setInputFiles('input[type="file"][accept="video/*"]', SIXTY_MP4);
|
||||
await page.locator('form input[type="checkbox"]').first().check();
|
||||
await page.getByRole('button', { name: /generate clips/i }).click();
|
||||
|
||||
// The app polls /api/status every 2s; the real pipeline (real ffmpeg,
|
||||
// stubbed ML) finishes in well under a minute. Bounded auto-wait, no
|
||||
// sleeps: the clip count badge only renders once results carry clips.
|
||||
await expect(page.getByText(/\d+ Clips/)).toBeVisible({ timeout: 60_000 });
|
||||
await expect(page.getByText('Clip 1', { exact: true })).toBeVisible({ timeout: 60_000 });
|
||||
});
|
||||
});
|
||||
35
dashboard/e2e/specs/reframe-editor.spec.js
Normal file
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);
|
||||
});
|
||||
});
|
||||
53
dashboard/e2e/specs/results-actions.spec.js
Normal file
53
dashboard/e2e/specs/results-actions.spec.js
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
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('downloads a single clip as a titled 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}/clip/0/download`),
|
||||
);
|
||||
const downloadPromise = page.waitForEvent('download');
|
||||
await page.getByRole('button', { name: 'download', exact: true }).first().click();
|
||||
|
||||
await requestPromise;
|
||||
const download = await downloadPromise;
|
||||
expect(download.suggestedFilename()).toBe('Test Clip.zip');
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
53
dashboard/e2e/specs/schedule-autofill.spec.js
Normal file
53
dashboard/e2e/specs/schedule-autofill.spec.js
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
// Global schedule start date (results header) auto-fills each clip's post modal
|
||||
// date/time from that clip's VIRALITY RANK (rank 1 = most viral = top card).
|
||||
//
|
||||
// The mocked session clips are:
|
||||
// clip index 0 "First viral clip" score 91 -> rank 1
|
||||
// clip index 1 "Second viral clip" score 77 -> rank 2
|
||||
// Per the agreed cadence (odd rank on the picked date, even rank the next day,
|
||||
// shared time cycles 18:00 -> 21:00 -> 13:00):
|
||||
// rank 1 -> start date @ 18:00
|
||||
// rank 2 -> start date + 1 day @ 18:00
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { openApp, completedSession } from '../fixtures/app.js';
|
||||
|
||||
const START = '2030-01-02';
|
||||
const seed = {
|
||||
session: completedSession(),
|
||||
postizUrl: 'http://postiz.e2e.local',
|
||||
postizKey: 'postiz-e2e-key',
|
||||
};
|
||||
|
||||
test.describe('global schedule auto-fill', () => {
|
||||
test('prefills each clip post time from its virality rank', async ({ page }) => {
|
||||
await openApp(page, { seed });
|
||||
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
|
||||
|
||||
// Pick the global start date in the results header.
|
||||
await page.getByTestId('schedule-start-date').fill(START);
|
||||
|
||||
// Rank 1 (top card): start date @ 18:00, scheduling auto-enabled so the
|
||||
// prefilled time is visible.
|
||||
await page.getByRole('button', { name: 'post', exact: true }).nth(0).click();
|
||||
let dialog = page.getByRole('dialog');
|
||||
await expect(dialog.getByLabel('date', { exact: true })).toHaveValue(START);
|
||||
await expect(dialog.getByLabel('time (HH:MM)', { exact: true })).toHaveValue('18:00');
|
||||
await expect(dialog.getByRole('checkbox', { name: /schedule post/i })).toBeChecked();
|
||||
await dialog.getByRole('button', { name: 'close' }).click();
|
||||
|
||||
// Rank 2: next day, same first time slot.
|
||||
await page.getByRole('button', { name: 'post', exact: true }).nth(1).click();
|
||||
dialog = page.getByRole('dialog');
|
||||
await expect(dialog.getByLabel('date', { exact: true })).toHaveValue('2030-01-03');
|
||||
await expect(dialog.getByLabel('time (HH:MM)', { exact: true })).toHaveValue('18:00');
|
||||
});
|
||||
|
||||
test('with no start date the schedule stays off', async ({ page }) => {
|
||||
await openApp(page, { seed });
|
||||
await expect(page.getByRole('heading', { name: 'First viral clip' })).toBeVisible();
|
||||
|
||||
await page.getByRole('button', { name: 'post', exact: true }).nth(0).click();
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(dialog.getByRole('checkbox', { name: /schedule post/i })).not.toBeChecked();
|
||||
});
|
||||
});
|
||||
23
dashboard/e2e/specs/session-restore.spec.js
Normal file
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
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
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
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();
|
||||
});
|
||||
});
|
||||
|
|
@ -102,7 +102,6 @@
|
|||
"AI viral moment detection with Google Gemini 3.1 Flash-Lite",
|
||||
"Smart 9:16 vertical cropping with MediaPipe face tracking and YOLOv8 fallback",
|
||||
"Automatic subtitle generation with word-level timestamps",
|
||||
"AI voice dubbing in 30+ languages via ElevenLabs",
|
||||
"Local video file upload and YouTube link ingest",
|
||||
"Hook text overlays with styled fonts",
|
||||
"AI-generated video effects via FFmpeg",
|
||||
|
|
@ -162,15 +161,15 @@
|
|||
"name": "Is there a free alternative to Opus Clip?",
|
||||
"acceptedAnswer": {
|
||||
"@type": "Answer",
|
||||
"text": "Yes. Clipwright self-hosted is a free and open source alternative to Opus Clip, MIT licensed, with no watermark and no usage cap, running on your own machine via Docker. As of July 2026 Opus Clip costs $15 per month for the Starter plan with 150 minutes, and $29 per month for Pro with 300 minutes, on top of a watermarked free tier of 60 minutes. Opus Clip bills one credit per minute of source video imported rather than per clip exported. Clipwright offers comparable AI moment detection using Google Gemini, face-tracked vertical cropping and automatic subtitles, and adds AI voice dubbing into 30+ languages, which Opus Clip does not have. Opus Clip ships a larger caption-style library and needs no setup."
|
||||
"text": "Yes. Clipwright self-hosted is a free and open source alternative to Opus Clip, MIT licensed, with no watermark and no usage cap, running on your own machine via Docker. As of July 2026 Opus Clip costs $15 per month for the Starter plan with 150 minutes, and $29 per month for Pro with 300 minutes, on top of a watermarked free tier of 60 minutes. Opus Clip bills one credit per minute of source video imported rather than per clip exported. Clipwright offers comparable AI moment detection using Google Gemini, face-tracked vertical cropping and automatic subtitles. Opus Clip ships a larger caption-style library and needs no setup."
|
||||
}
|
||||
},
|
||||
{
|
||||
"@type": "Question",
|
||||
"name": "Can Clipwright add subtitles and translate videos?",
|
||||
"name": "Can Clipwright add subtitles to videos?",
|
||||
"acceptedAnswer": {
|
||||
"@type": "Answer",
|
||||
"text": "Yes. Subtitles are generated with faster-whisper at word-level timestamps and burned into the video with FFmpeg. For translation, ElevenLabs AI dubbing translates the audio into more than 30 languages while preserving the original speaker's voice characteristics, and the dubbed audio is then automatically re-transcribed so the burned-in subtitles are in the target language rather than the original."
|
||||
"text": "Yes. Subtitles are generated with faster-whisper at word-level timestamps and burned into the video with FFmpeg, all locally on your own machine."
|
||||
}
|
||||
},
|
||||
{
|
||||
|
|
|
|||
|
|
@ -41,10 +41,10 @@ server {
|
|||
# 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
|
||||
# through the hash (#/pricing, #/auth/callback), which never reaches the
|
||||
# server, so there is no deep link that needs the fallback — and answering
|
||||
# 200 with identical markup for every made-up path made the whole site look
|
||||
# like one page duplicated infinitely to a crawler.
|
||||
# through the hash, which never reaches the server, so there is no deep link
|
||||
# that needs the fallback — and answering 200 with identical markup for
|
||||
# every made-up path made the whole site look like one page duplicated
|
||||
# infinitely to a crawler.
|
||||
location / {
|
||||
try_files $uri $uri.html $uri/ =404;
|
||||
add_header Cache-Control "no-store, must-revalidate" always;
|
||||
|
|
|
|||
130
dashboard/package-lock.json
generated
130
dashboard/package-lock.json
generated
|
|
@ -9,18 +9,17 @@
|
|||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"@remotion/media": "^4.0.447",
|
||||
"@remotion/media-utils": "^4.0.447",
|
||||
"@remotion/player": "^4.0.447",
|
||||
"@remotion/web-renderer": "^4.0.447",
|
||||
"lucide-react": "^0.344.0",
|
||||
"mediabunny": "^1.39.2",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"remotion": "^4.0.447",
|
||||
"zod": "^4.3.6"
|
||||
"remotion": "^4.0.447"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.5",
|
||||
"@playwright/test": "^1.63.0",
|
||||
"@types/react": "^18.2.64",
|
||||
"@types/react-dom": "^18.2.21",
|
||||
"@vitejs/plugin-react": "^4.2.1",
|
||||
|
|
@ -988,6 +987,22 @@
|
|||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/@playwright/test": {
|
||||
"version": "1.63.0",
|
||||
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.63.0.tgz",
|
||||
"integrity": "sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright": "1.63.0"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/@remotion/licensing": {
|
||||
"version": "4.0.447",
|
||||
"resolved": "https://registry.npmjs.org/@remotion/licensing/-/licensing-4.0.447.tgz",
|
||||
|
|
@ -1008,20 +1023,6 @@
|
|||
"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": {
|
||||
"version": "4.0.447",
|
||||
"resolved": "https://registry.npmjs.org/@remotion/player/-/player-4.0.447.tgz",
|
||||
|
|
@ -1468,12 +1469,16 @@
|
|||
"dev": true
|
||||
},
|
||||
"node_modules/baseline-browser-mapping": {
|
||||
"version": "2.9.11",
|
||||
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.9.11.tgz",
|
||||
"integrity": "sha512-Sg0xJUNDU1sJNGdfGWhVHX0kkZ+HWcvmVymJbj6NSgZZmW/8S9Y2HQ5euytnIgakgxN6papOAWiwDo1ctFDcoQ==",
|
||||
"version": "2.11.27",
|
||||
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.27.tgz",
|
||||
"integrity": "sha512-ElY12DaROGuan+lMmZ8Cvo/ZUbXPe7Enc/9VU/b1T3Kp4dwytRcNdR8DoSJN5SNJT/CuvcCA0DHDVmMOCePdRQ==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"baseline-browser-mapping": "dist/cli.js"
|
||||
"baseline-browser-mapping": "dist/cli.cjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/binary-extensions": {
|
||||
|
|
@ -1613,9 +1618,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/caniuse-lite": {
|
||||
"version": "1.0.30001761",
|
||||
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001761.tgz",
|
||||
"integrity": "sha512-JF9ptu1vP2coz98+5051jZ4PwQgd2ni8A+gYSN7EA7dPKIMf0pDlSUxhdmVOaV3/fYK5uWBkgSXJaRLr4+3A6g==",
|
||||
"version": "1.0.30001814",
|
||||
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001814.tgz",
|
||||
"integrity": "sha512-/Uaf1lAzr59XcMpW0o96WoEfr+VXK2OX4U9AgFoiSHsVJ4HppnIFUjtYzsyDH2+tgANaQb2/oxYGwCPapN1FpA==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
|
|
@ -1630,7 +1635,8 @@
|
|||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ai"
|
||||
}
|
||||
]
|
||||
],
|
||||
"license": "CC-BY-4.0"
|
||||
},
|
||||
"node_modules/chalk": {
|
||||
"version": "4.1.2",
|
||||
|
|
@ -3911,6 +3917,35 @@
|
|||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright": {
|
||||
"version": "1.63.0",
|
||||
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz",
|
||||
"integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright-core": "1.63.0"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright-core": {
|
||||
"version": "1.63.0",
|
||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",
|
||||
"integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"playwright-core": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/possible-typed-array-names": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",
|
||||
|
|
@ -5801,6 +5836,15 @@
|
|||
"fastq": "^1.6.0"
|
||||
}
|
||||
},
|
||||
"@playwright/test": {
|
||||
"version": "1.63.0",
|
||||
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.63.0.tgz",
|
||||
"integrity": "sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"playwright": "1.63.0"
|
||||
}
|
||||
},
|
||||
"@remotion/licensing": {
|
||||
"version": "4.0.447",
|
||||
"resolved": "https://registry.npmjs.org/@remotion/licensing/-/licensing-4.0.447.tgz",
|
||||
|
|
@ -5816,15 +5860,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": {
|
||||
"version": "4.0.447",
|
||||
"resolved": "https://registry.npmjs.org/@remotion/player/-/player-4.0.447.tgz",
|
||||
|
|
@ -6144,9 +6179,9 @@
|
|||
"dev": true
|
||||
},
|
||||
"baseline-browser-mapping": {
|
||||
"version": "2.9.11",
|
||||
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.9.11.tgz",
|
||||
"integrity": "sha512-Sg0xJUNDU1sJNGdfGWhVHX0kkZ+HWcvmVymJbj6NSgZZmW/8S9Y2HQ5euytnIgakgxN6papOAWiwDo1ctFDcoQ==",
|
||||
"version": "2.11.27",
|
||||
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.27.tgz",
|
||||
"integrity": "sha512-ElY12DaROGuan+lMmZ8Cvo/ZUbXPe7Enc/9VU/b1T3Kp4dwytRcNdR8DoSJN5SNJT/CuvcCA0DHDVmMOCePdRQ==",
|
||||
"dev": true
|
||||
},
|
||||
"binary-extensions": {
|
||||
|
|
@ -6232,9 +6267,9 @@
|
|||
"dev": true
|
||||
},
|
||||
"caniuse-lite": {
|
||||
"version": "1.0.30001761",
|
||||
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001761.tgz",
|
||||
"integrity": "sha512-JF9ptu1vP2coz98+5051jZ4PwQgd2ni8A+gYSN7EA7dPKIMf0pDlSUxhdmVOaV3/fYK5uWBkgSXJaRLr4+3A6g==",
|
||||
"version": "1.0.30001814",
|
||||
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001814.tgz",
|
||||
"integrity": "sha512-/Uaf1lAzr59XcMpW0o96WoEfr+VXK2OX4U9AgFoiSHsVJ4HppnIFUjtYzsyDH2+tgANaQb2/oxYGwCPapN1FpA==",
|
||||
"dev": true
|
||||
},
|
||||
"chalk": {
|
||||
|
|
@ -7767,6 +7802,21 @@
|
|||
"integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==",
|
||||
"dev": true
|
||||
},
|
||||
"playwright": {
|
||||
"version": "1.63.0",
|
||||
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz",
|
||||
"integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"playwright-core": "1.63.0"
|
||||
}
|
||||
},
|
||||
"playwright-core": {
|
||||
"version": "1.63.0",
|
||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",
|
||||
"integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",
|
||||
"dev": true
|
||||
},
|
||||
"possible-typed-array-names": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",
|
||||
|
|
|
|||
|
|
@ -7,22 +7,22 @@
|
|||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"lint": "eslint . --report-unused-disable-directives --max-warnings 0",
|
||||
"preview": "vite preview"
|
||||
"preview": "vite preview",
|
||||
"test:e2e": "playwright test --config e2e/playwright.config.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@remotion/media": "^4.0.447",
|
||||
"@remotion/media-utils": "^4.0.447",
|
||||
"@remotion/player": "^4.0.447",
|
||||
"@remotion/web-renderer": "^4.0.447",
|
||||
"lucide-react": "^0.344.0",
|
||||
"mediabunny": "^1.39.2",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"remotion": "^4.0.447",
|
||||
"zod": "^4.3.6"
|
||||
"remotion": "^4.0.447"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.5",
|
||||
"@playwright/test": "^1.63.0",
|
||||
"@types/react": "^18.2.64",
|
||||
"@types/react-dom": "^18.2.21",
|
||||
"@vitejs/plugin-react": "^4.2.1",
|
||||
|
|
|
|||
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
Before Width: | Height: | Size: 171 KiB |
Binary file not shown.
|
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: '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',
|
||||
},
|
||||
]
|
||||
|
|
|
|||
|
|
@ -90,7 +90,7 @@ export const LANDING_FALLBACK = `<div id="seo-content" style="background:oklch(1
|
|||
<section style="${S.section};padding-top:4rem"><div style="${S.wrap}">
|
||||
<p style="${S.eyebrow}">AI clip generator · self-hosted & open source</p>
|
||||
<h1 style="${S.h1}">the free open source ai clip generator, built to clip what people actually watch.</h1>
|
||||
<p style="${S.p};max-width:44rem;font-size:1.05rem">Turn long videos into viral 9:16 shorts, self-hosted with Docker and free under MIT. Publish to TikTok, Instagram Reels and YouTube Shorts through your own self-hosted <a href="https://postiz.com/" rel="noopener" style="${S.a}">Postiz</a> instance, or wire the REST API into your own pipeline with the <a href="/n8n-youtube-shorts-automation" style="${S.a}">n8n workflow</a>. Just want it free? Start with the <a href="/free-ai-clip-generator" style="${S.a}">free AI clip generator</a>.</p>
|
||||
<p style="${S.p};max-width:44rem;font-size:1.05rem">Turn long videos into viral 9:16 shorts, self-hosted with Docker and free under MIT. Publish to TikTok, Instagram Reels and YouTube Shorts through your own self-hosted <a href="https://postiz.com/" rel="noopener" style="${S.a}">Postiz</a> instance, or wire the REST API into your own pipeline. Just want it free? Start with the <a href="/free-ai-clip-generator" style="${S.a}">free AI clip generator</a>.</p>
|
||||
<p style="${S.muted};max-width:44rem"><strong style="color:oklch(75% 0.11 150)">No account, no card, no watermark.</strong> Run it yourself: <a style="${S.a}" href="https://git.pbento.pt/pedro-bento/clipwright" rel="noopener">self-host free on GitHub</a> and bring your own Gemini key.</p>
|
||||
</div></section>
|
||||
|
||||
|
|
@ -146,8 +146,7 @@ export const LANDING_FALLBACK = `<div id="seo-content" style="background:oklch(1
|
|||
<a style="${S.a}" href="/opus-pro">Opus Pro</a> ·
|
||||
<a style="${S.a}" href="/vizard-ai-video-to-text">Vizard AI video to text</a> ·
|
||||
<a style="${S.a}" href="/submagic-reviews">Submagic review</a> ·
|
||||
<a style="${S.a}" href="/automate-shorts-api">Automate shorts via API</a> ·
|
||||
<a style="${S.a}" href="/n8n-youtube-shorts-automation">n8n template</a>
|
||||
<a style="${S.a}" href="/automate-shorts-api">Automate shorts via API</a>
|
||||
</p>
|
||||
</div></section>
|
||||
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue