Compare commits
No commits in common. "main" and "alpha-0.1.0" have entirely different histories.
main
...
alpha-0.1.
|
|
@ -14,10 +14,11 @@ ENV/
|
||||||
.eggs/
|
.eggs/
|
||||||
*.egg-info/
|
*.egg-info/
|
||||||
.pytest_cache/
|
.pytest_cache/
|
||||||
.ruff_cache/
|
|
||||||
|
|
||||||
# Node
|
# Node
|
||||||
node_modules/
|
node_modules/
|
||||||
|
remotion/node_modules/
|
||||||
|
render-service/node_modules/
|
||||||
dashboard/node_modules/
|
dashboard/node_modules/
|
||||||
|
|
||||||
# IDE
|
# IDE
|
||||||
|
|
@ -26,17 +27,6 @@ dashboard/node_modules/
|
||||||
*.swp
|
*.swp
|
||||||
*.swo
|
*.swo
|
||||||
|
|
||||||
# Agent / tool local state
|
|
||||||
.opencode/
|
|
||||||
|
|
||||||
# Local caches
|
|
||||||
.cache/
|
|
||||||
.config/
|
|
||||||
|
|
||||||
# Not needed in the runtime image
|
|
||||||
tests/
|
|
||||||
screenshots/
|
|
||||||
|
|
||||||
# Video files (will be mounted via volume)
|
# Video files (will be mounted via volume)
|
||||||
*.mp4
|
*.mp4
|
||||||
*.avi
|
*.avi
|
||||||
|
|
@ -53,6 +43,7 @@ videos/
|
||||||
.env
|
.env
|
||||||
.env.*
|
.env.*
|
||||||
!.env.example
|
!.env.example
|
||||||
|
!.env.cloud.example
|
||||||
*.pem
|
*.pem
|
||||||
*.key
|
*.key
|
||||||
|
|
||||||
|
|
@ -64,3 +55,10 @@ docker-compose.yml
|
||||||
# Docs
|
# Docs
|
||||||
README.md
|
README.md
|
||||||
*.md
|
*.md
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
54
.env.example
|
|
@ -1,7 +1,8 @@
|
||||||
# Google Gemini API key used server-side (moment detection, layouts, titles and
|
# AWS S3 (optional — for clip backup)
|
||||||
# thumbnails). The dashboard can also send a key per request, and the key is
|
AWS_ACCESS_KEY_ID=your_aws_access_key_here
|
||||||
# optional entirely when LLM_BASE_URL points at an OpenAI-compatible server.
|
AWS_SECRET_ACCESS_KEY=your_aws_secret_key_here
|
||||||
# GEMINI_API_KEY=your_gemini_api_key
|
AWS_REGION=eu-west-3
|
||||||
|
AWS_S3_BUCKET=your-bucket-name
|
||||||
|
|
||||||
# YouTube cookies (optional — paste Netscape-format cookies to bypass bot detection)
|
# YouTube cookies (optional — paste Netscape-format cookies to bypass bot detection)
|
||||||
# YOUTUBE_COOKIES=...
|
# YOUTUBE_COOKIES=...
|
||||||
|
|
@ -26,9 +27,6 @@
|
||||||
# Concurrent GPU transcriptions (parakeet or whisper-on-cuda). Keep 1.
|
# Concurrent GPU transcriptions (parakeet or whisper-on-cuda). Keep 1.
|
||||||
# ASR_GPU_CONCURRENCY=1
|
# ASR_GPU_CONCURRENCY=1
|
||||||
|
|
||||||
# Concurrent pipeline jobs (default 5).
|
|
||||||
# MAX_CONCURRENT_JOBS=5
|
|
||||||
|
|
||||||
# Video encoder for all ffmpeg encodes: x264 (default) | nvenc | auto.
|
# Video encoder for all ffmpeg encodes: x264 (default) | nvenc | auto.
|
||||||
# auto probes h264_nvenc once at startup and falls back to x264 if unusable.
|
# auto probes h264_nvenc once at startup and falls back to x264 if unusable.
|
||||||
# FFMPEG_ENCODER=x264
|
# FFMPEG_ENCODER=x264
|
||||||
|
|
@ -57,8 +55,13 @@ GEMINI_IMAGE_MODEL=gemini-3.1-flash-image
|
||||||
# LLM_SCORE_BATCH=3
|
# LLM_SCORE_BATCH=3
|
||||||
# LLM_TIMEOUT=600
|
# LLM_TIMEOUT=600
|
||||||
|
|
||||||
|
# Hard daily ceiling for the per-GB paid proxy (UTC day, MB). Above it,
|
||||||
|
# DataImpulse is removed from every chain until midnight and the jobs that
|
||||||
|
# needed it fail with a clear error. 0 disables the cap. Default 500.
|
||||||
|
# PAID_PROXY_DAILY_MB=500
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Privacy and access control (GDPR remediation, 4-sep-2026)
|
# Privacy, retention and access control (GDPR remediation, 4-sep-2026)
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
# Absolute base URL of the API as the internet reaches it, used for the
|
# Absolute base URL of the API as the internet reaches it, used for the
|
||||||
|
|
@ -71,6 +74,17 @@ GEMINI_IMAGE_MODEL=gemini-3.1-flash-image
|
||||||
# sidecars, dotfiles) so only media is exposed. Files are swept with the job
|
# sidecars, dotfiles) so only media is exposed. Files are swept with the job
|
||||||
# (JOB_RETENTION_SECONDS).
|
# (JOB_RETENTION_SECONDS).
|
||||||
|
|
||||||
|
# Retention for thumbnails. Thumbnails and the frames sampled to make them are
|
||||||
|
# close-ups of a real person; the clock runs from the last download.
|
||||||
|
# THUMBNAIL_RETENTION_SECONDS=86400
|
||||||
|
|
||||||
|
# Per-IP rate limiting (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)
|
# Publishing (self-hosted Postiz)
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
@ -92,9 +106,21 @@ GEMINI_IMAGE_MODEL=gemini-3.1-flash-image
|
||||||
# number to cap uploads and reject larger files with HTTP 413.
|
# number to cap uploads and reject larger files with HTTP 413.
|
||||||
# MAX_FILE_SIZE_MB=0
|
# MAX_FILE_SIZE_MB=0
|
||||||
|
|
||||||
# X-Forwarded-For trust. The container launches uvicorn with
|
# Which hop may declare the client's address in X-Forwarded-For. The Dockerfile
|
||||||
# `--proxy-headers --forwarded-allow-ips *` (see the Dockerfile CMD), so any
|
# defaults to the private Docker ranges; narrow it to Traefik's own address on
|
||||||
# caller that can reach the port may declare its own address and scheme. This
|
# the container network in production. NEVER "*": that lets any caller forge
|
||||||
# is not configurable via an environment variable: run the API behind a reverse
|
# the IP the rate limiter and the rights declaration are keyed on.
|
||||||
# proxy that overwrites X-Forwarded-For, and never publish the backend port
|
# FORWARDED_ALLOW_IPS=10.0.1.7
|
||||||
# directly to the internet.
|
|
||||||
|
# Strict-Transport-Security value sent on https responses from the API. Empty
|
||||||
|
# disables it. Do not add "preload" without understanding that it is one-way.
|
||||||
|
# HSTS_HEADER=max-age=31536000; includeSubDomains
|
||||||
|
|
||||||
|
# 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
|
||||||
|
|
||||||
|
|
|
||||||
95
.github/workflows/ci.yml
vendored
|
|
@ -5,92 +5,41 @@ on:
|
||||||
branches: [main]
|
branches: [main]
|
||||||
pull_request:
|
pull_request:
|
||||||
|
|
||||||
env:
|
|
||||||
PYTHONHASHSEED: "0"
|
|
||||||
TZ: UTC
|
|
||||||
PIP_DISABLE_PIP_VERSION_CHECK: "1"
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
# Fast unit suite. No ffmpeg, no ML stack.
|
backend-tests:
|
||||||
unit:
|
|
||||||
runs-on: ubuntu-latest
|
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:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
# scenedetect (in requirements-test.txt) pulls the full opencv-python,
|
- uses: actions/setup-python@v5
|
||||||
# whose cv2 binary links libGL.so.1 — absent from the base image. The
|
with:
|
||||||
# pipeline modules the unit tests import need it at import time.
|
python-version: "3.11"
|
||||||
- name: Install opencv system libs
|
# Everything the collected tests import at module level, WITHOUT the
|
||||||
run: apt-get update -qq && apt-get install -y -qq --no-install-recommends libgl1
|
# 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.
|
||||||
- name: Install test dependencies
|
- name: Install test dependencies
|
||||||
run: pip install -r requirements-test.txt
|
run: >
|
||||||
- name: Run unit tests
|
pip install pytest pillow httpx pydantic sqlalchemy greenlet numpy
|
||||||
# Exclude the E2E tree from *collection*: `-m "not e2e"` only filters
|
opencv-python-headless python-dotenv google-genai fastapi boto3
|
||||||
# execution, but pytest still imports every module to collect it, and
|
PyJWT email-validator python-multipart
|
||||||
# the pipeline E2E modules import the pipeline (tqdm/scenedetect/ML),
|
- name: Run tests
|
||||||
# which would pull in fixtures the unit suite does not exercise.
|
run: pytest tests/ -v
|
||||||
run: pytest tests/ --ignore=tests/e2e -m "not e2e" -q
|
|
||||||
|
|
||||||
# Backend E2E: API + pipeline. ffmpeg/ffprobe must be installed in-job.
|
frontend-build:
|
||||||
# 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
|
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:
|
defaults:
|
||||||
run:
|
run:
|
||||||
working-directory: dashboard
|
working-directory: dashboard
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
# ffmpeg builds the media fixture and renders the real pipeline's clips;
|
- uses: actions/setup-node@v4
|
||||||
# libgl1 satisfies opencv (pulled by scenedetect) at import time.
|
with:
|
||||||
- name: Install ffmpeg + opencv system libs
|
node-version: "20"
|
||||||
run: apt-get update -qq && apt-get install -y -qq --no-install-recommends ffmpeg libgl1
|
cache: npm
|
||||||
# Backend deps for the uvicorn server the real lane launches (uvicorn is
|
cache-dependency-path: dashboard/package-lock.json
|
||||||
# pinned in requirements-test.txt alongside fastapi/scenedetect/...).
|
|
||||||
- name: Install backend test dependencies
|
|
||||||
run: pip install -r ../requirements-test.txt
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: npm ci
|
run: npm ci
|
||||||
- name: Install Playwright browsers
|
|
||||||
run: npx playwright install --with-deps chromium
|
|
||||||
- name: Lint
|
|
||||||
run: npm run lint
|
|
||||||
- name: Build
|
- name: Build
|
||||||
run: npm run build
|
run: npm run build
|
||||||
- name: Browser E2E
|
|
||||||
run: npm run test:e2e
|
|
||||||
|
|
|
||||||
42
.github/workflows/publish-cli.yml
vendored
Normal file
|
|
@ -0,0 +1,42 @@
|
||||||
|
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
|
|
@ -12,18 +12,13 @@
|
||||||
__pycache__/
|
__pycache__/
|
||||||
*.pyc
|
*.pyc
|
||||||
|
|
||||||
# Runtime dirs
|
# Temporary files / runtime dirs
|
||||||
|
temp_*
|
||||||
uploads/
|
uploads/
|
||||||
|
downloads/
|
||||||
|
videos/
|
||||||
output/
|
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
|
# OS / IDE
|
||||||
.DS_Store
|
.DS_Store
|
||||||
.idea/
|
.idea/
|
||||||
|
|
@ -38,9 +33,19 @@ clipwright.sqlite3-shm
|
||||||
# Cache dirs
|
# Cache dirs
|
||||||
.cache/
|
.cache/
|
||||||
.config/
|
.config/
|
||||||
.fontconfig/
|
# Multi-agent Skills
|
||||||
.pytest_cache/
|
.agents/
|
||||||
.ruff_cache/
|
.agent/
|
||||||
|
.claude/
|
||||||
|
# skills/ holds third-party installs (symlinks); our own published skill is versioned
|
||||||
|
skills/*
|
||||||
|
!skills/clipwright/
|
||||||
|
skills-lock.json
|
||||||
|
|
||||||
# Agent / tool local state
|
|
||||||
.opencode/
|
# Cloud env example kept local only (avoid leaking infra hints)
|
||||||
|
.env.cloud.example
|
||||||
|
.worktrees
|
||||||
|
|
||||||
|
# Instrucciones locales con datos de infra (repo público)
|
||||||
|
CLAUDE.local.md
|
||||||
|
|
|
||||||
3
.hallmark/log.json
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
[
|
||||||
|
{ "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
Normal file
|
|
@ -0,0 +1,600 @@
|
||||||
|
# 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
|
|
@ -31,11 +31,6 @@ FROM python:3.11-slim
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
# The FastAPI app lives in the `clipwright` package and job workers are launched
|
|
||||||
# as `python -m clipwright.pipeline.main`, so the repo root must be importable
|
|
||||||
# regardless of the process cwd.
|
|
||||||
ENV PYTHONPATH=/app
|
|
||||||
|
|
||||||
# Install FFmpeg, OpenCV deps, Node.js + npm + git (for yt-dlp JS + bgutil build).
|
# Install FFmpeg, OpenCV deps, Node.js + npm + git (for yt-dlp JS + bgutil build).
|
||||||
# fontconfig + fonts-liberation back the subtitle font choices: without real
|
# fontconfig + fonts-liberation back the subtitle font choices: without real
|
||||||
# fonts libass falls back to DejaVu for every UI option (issue #57).
|
# fonts libass falls back to DejaVu for every UI option (issue #57).
|
||||||
|
|
@ -71,18 +66,6 @@ COPY --from=builder /opt/venv /opt/venv
|
||||||
ENV PATH="/opt/venv/bin:$PATH"
|
ENV PATH="/opt/venv/bin:$PATH"
|
||||||
ENV PYTHONUNBUFFERED=1
|
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
|
# GPU runtime wiring — harmless no-ops on CPU builds / hosts without the
|
||||||
# NVIDIA runtime. LD_LIBRARY_PATH points at the pip-installed CUDA libs
|
# NVIDIA runtime. LD_LIBRARY_PATH points at the pip-installed CUDA libs
|
||||||
# (paths simply don't exist in CPU images); DRIVER_CAPABILITIES asks the
|
# (paths simply don't exist in CPU images); DRIVER_CAPABILITIES asks the
|
||||||
|
|
@ -143,4 +126,4 @@ EXPOSE 8000
|
||||||
HEALTHCHECK --interval=5s --timeout=3s --start-period=30s --retries=2 \
|
HEALTHCHECK --interval=5s --timeout=3s --start-period=30s --retries=2 \
|
||||||
CMD curl -sf http://127.0.0.1:8000/health/ready > /dev/null || exit 1
|
CMD curl -sf http://127.0.0.1:8000/health/ready > /dev/null || exit 1
|
||||||
|
|
||||||
CMD ["uvicorn", "clipwright.api.app:app", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers", "--forwarded-allow-ips", "*", "--timeout-graceful-shutdown", "15"]
|
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers", "--forwarded-allow-ips", "*", "--timeout-graceful-shutdown", "15"]
|
||||||
|
|
|
||||||
323
README.md
|
|
@ -1,68 +1,139 @@
|
||||||
# Clipwright
|
# Clipwright
|
||||||
|
|
||||||
Self-hosted, MIT-licensed video toolkit in one Docker stack:
|
[](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.
|
||||||
|
|
||||||
- **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.
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
## Fork
|
> **Fork:** Clipwright is a fork of OpenShorts (<https://github.com/mutonby/openshorts>), MIT-licensed. Upstream copyright is preserved in [LICENSE](LICENSE) and [NOTICE](NOTICE).
|
||||||
|
|
||||||
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).
|
---
|
||||||
|
|
||||||
|
## 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.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
- **Docker & Docker Compose**
|
- **Docker & Docker Compose**
|
||||||
- **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`.
|
- **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
|
||||||
- **A self-hosted Postiz instance** — optional, only for publishing.
|
- **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
|
||||||
|
|
||||||
## Quick start
|
---
|
||||||
|
|
||||||
|
## Getting Started
|
||||||
|
|
||||||
|
### 1. Clone
|
||||||
```bash
|
```bash
|
||||||
git clone https://git.pbento.pt/pedro-bento/clipwright.git
|
git clone https://git.pbento.pt/pedro-bento/clipwright.git
|
||||||
cd clipwright
|
cd clipwright
|
||||||
cp .env.example .env # optional: Postiz server-side key
|
```
|
||||||
|
|
||||||
|
### 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
|
||||||
docker compose up --build
|
docker compose up --build
|
||||||
```
|
```
|
||||||
|
|
||||||
Open the dashboard at **http://localhost:5175**, go to **Settings**, and paste your keys (Gemini; Postiz is optional). Then:
|
### 4. Open Dashboard
|
||||||
|
Navigate to **`http://localhost:5175`**
|
||||||
|
|
||||||
1. **Clip Generator** — upload a long video or paste a URL.
|
1. Go to **Settings** and enter your API keys (Gemini, ElevenLabs) and your Postiz URL + API key
|
||||||
2. **YouTube Studio** — generate titles, thumbnails and descriptions.
|
2. **Clip Generator**: Upload a long-form video to generate viral shorts
|
||||||
3. Publish a finished clip to your connected Postiz channels.
|
3. **YouTube Studio**: Generate thumbnails, titles, and descriptions for YouTube
|
||||||
|
|
||||||
## Configuration
|
### 5. GPU acceleration (optional, NVIDIA)
|
||||||
|
|
||||||
Server-side (`.env`):
|
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.
|
||||||
|
|
||||||
| 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
|
```bash
|
||||||
# .env
|
sudo nvidia-ctk runtime configure --runtime=docker && sudo systemctl restart docker
|
||||||
LLM_BASE_URL=http://host.docker.internal:11434/v1 # Ollama on the host
|
docker run --rm --gpus all nvidia/cuda:12.4.0-base-ubuntu22.04 nvidia-smi # sanity check
|
||||||
LLM_MODEL=qwen2.5:14b
|
|
||||||
```
|
```
|
||||||
|
On Windows use Docker Desktop with the WSL2 backend and the Windows NVIDIA driver; no driver inside WSL.
|
||||||
|
|
||||||
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.
|
**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.
|
||||||
|
|
||||||
### 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
|
```yaml
|
||||||
services:
|
services:
|
||||||
backend:
|
backend:
|
||||||
|
|
@ -79,16 +150,79 @@ services:
|
||||||
capabilities: [gpu, video]
|
capabilities: [gpu, video]
|
||||||
```
|
```
|
||||||
|
|
||||||
## Publishing with Postiz
|
**`.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
|
||||||
|
```
|
||||||
|
|
||||||
1. Run Postiz yourself and connect TikTok, Instagram and/or YouTube inside it.
|
**Verify:**
|
||||||
2. Create a public API key in Postiz (**Settings → Developers / Public API**).
|
```bash
|
||||||
3. In Clipwright **Settings**, enter your Postiz URL and key, then **Test connection** to list your channels.
|
docker compose up --build -d
|
||||||
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.
|
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.
|
||||||
|
|
||||||
Clipwright uploads the clip to your Postiz instance and creates the post there; the platform tokens never leave your infrastructure.
|
---
|
||||||
|
|
||||||
## API and webhooks
|
### 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
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
curl -X POST http://localhost:8000/api/process \
|
curl -X POST http://localhost:8000/api/process \
|
||||||
|
|
@ -97,30 +231,91 @@ curl -X POST http://localhost:8000/api/process \
|
||||||
"webhook_url": "https://your-server.com/hooks/clipwright"}'
|
"webhook_url": "https://your-server.com/hooks/clipwright"}'
|
||||||
```
|
```
|
||||||
|
|
||||||
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`.
|
Interactive docs at `/docs` (OpenAPI) on any instance.
|
||||||
|
|
||||||
## Project structure
|
### Completion webhooks
|
||||||
|
|
||||||
```
|
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:
|
||||||
clipwright/ # Python backend package
|
|
||||||
core/ # shared helpers (security, filesystem paths)
|
```json
|
||||||
api/ # FastAPI app, auth, free tools
|
{"event": "job.completed", "job_id": "…",
|
||||||
pipeline/ # download → transcribe → clip orchestration, Gemini, quality probe
|
"clips": [{"index": 0, "title": "…", "video_url": "…"}]}
|
||||||
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)
|
|
||||||
```
|
```
|
||||||
|
|
||||||
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`.
|
With a secret, the body is signed: `X-Clipwright-Signature: sha256=<hmac-sha256(body)>`.
|
||||||
|
|
||||||
## Tech stack
|
### n8n
|
||||||
|
|
||||||
Python 3.11 · FastAPI · google-genai · faster-whisper · ultralytics (YOLOv8) · MediaPipe · FFmpeg · React 18 · Vite · Tailwind · Docker Compose.
|
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.
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
MIT. Forked from [OpenShorts](https://github.com/mutonby/openshorts); upstream copyright preserved in [LICENSE](LICENSE) and [NOTICE](NOTICE).
|
MIT License — Clipwright is yours to use, modify, and scale.
|
||||||
|
|
|
||||||
|
|
@ -220,7 +220,7 @@ def speaker_xs(held, centres, crop_w, orig_w, n_frames, fps,
|
||||||
|
|
||||||
def verdicts_for_scene(video_path, start_f, end_f, fps, centres):
|
def verdicts_for_scene(video_path, start_f, end_f, fps, centres):
|
||||||
"""Per-window speaker verdicts for one scene, from its two face centres."""
|
"""Per-window speaker verdicts for one scene, from its two face centres."""
|
||||||
from clipwright.layouts import split_layout
|
import split_layout
|
||||||
|
|
||||||
start_s = start_f / fps
|
start_s = start_f / fps
|
||||||
duration_s = (end_f - start_f) / fps
|
duration_s = (end_f - start_f) / fps
|
||||||
|
|
@ -251,6 +251,7 @@ def decode_activity(video_path, start_s, duration_s, boxes, fps,
|
||||||
small_h = max(int(orig_h * small_w / orig_w), 2)
|
small_h = max(int(orig_h * small_w / orig_w), 2)
|
||||||
small_h += small_h % 2
|
small_h += small_h % 2
|
||||||
scale = orig_w / float(small_w)
|
scale = orig_w / float(small_w)
|
||||||
|
frame_bytes = small_w * small_h * 3
|
||||||
|
|
||||||
regions = [mouth_region(b, small_w, small_h, scale) for b in boxes]
|
regions = [mouth_region(b, small_w, small_h, scale) for b in boxes]
|
||||||
|
|
||||||
46
assets/make_watermark.py
Normal file
|
|
@ -0,0 +1,46 @@
|
||||||
|
"""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)
|
||||||
BIN
assets/watermark.png
Normal file
|
After Width: | Height: | Size: 65 KiB |
|
|
@ -20,7 +20,7 @@ them with margin.
|
||||||
"""
|
"""
|
||||||
import os
|
import os
|
||||||
|
|
||||||
from clipwright.media.ffmpeg_utils import blurred_backdrop
|
from ffmpeg_utils import blurred_backdrop
|
||||||
|
|
||||||
CORNER_MARGIN = 0.20 # a subject this far from an edge (as a fraction of the
|
CORNER_MARGIN = 0.20 # a subject this far from an edge (as a fraction of the
|
||||||
# frame) still counts as anchored to it
|
# frame) still counts as anchored to it
|
||||||
|
|
@ -159,8 +159,8 @@ def detect(video_path, samples=10):
|
||||||
"""
|
"""
|
||||||
import cv2
|
import cv2
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from clipwright.pipeline import main as m
|
import main as m
|
||||||
from clipwright.layouts import screencast_layout
|
import screencast_layout
|
||||||
|
|
||||||
cap = cv2.VideoCapture(video_path)
|
cap = cv2.VideoCapture(video_path)
|
||||||
if not cap.isOpened():
|
if not cap.isOpened():
|
||||||
BIN
churchil_queen_vertical.gif
Normal file
|
After Width: | Height: | Size: 62 MiB |
BIN
churchil_queen_vertical_short.gif
Normal file
|
After Width: | Height: | Size: 2.5 MiB |
58
cli/README.md
Normal file
|
|
@ -0,0 +1,58 @@
|
||||||
|
# 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/).
|
||||||
251
cli/clipwright_cli.py
Normal file
|
|
@ -0,0 +1,251 @@
|
||||||
|
"""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()
|
||||||
30
cli/pyproject.toml
Normal file
|
|
@ -0,0 +1,30 @@
|
||||||
|
[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"]
|
||||||
|
|
@ -5,8 +5,6 @@ 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.
|
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.
|
# USD per 1M tokens (input, output incl. thinking), from ai.google.dev pricing.
|
||||||
MODEL_PRICES = {
|
MODEL_PRICES = {
|
||||||
"gemini-3.5-flash": (1.50, 9.00),
|
"gemini-3.5-flash": (1.50, 9.00),
|
||||||
|
|
@ -190,6 +188,18 @@ def clip_duration_bounds():
|
||||||
return round(lo, 3), round(hi, 3)
|
return round(lo, 3), round(hi, 3)
|
||||||
|
|
||||||
|
|
||||||
|
def compact_words(words, precision=2):
|
||||||
|
"""Round word timestamps for prompts — full float precision wastes tokens."""
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"w": w.get("w", ""),
|
||||||
|
"s": round(float(w.get("s", 0)), precision),
|
||||||
|
"e": round(float(w.get("e", 0)), precision),
|
||||||
|
}
|
||||||
|
for w in words
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
def build_transcript_windows(transcript_result, video_duration,
|
def build_transcript_windows(transcript_result, video_duration,
|
||||||
window_seconds=90, overlap_seconds=30):
|
window_seconds=90, overlap_seconds=30):
|
||||||
"""
|
"""
|
||||||
|
|
@ -350,185 +360,3 @@ def snap_clip_to_words(start, end, words, video_duration,
|
||||||
if new_end <= new_start or new_end - new_start < min_duration:
|
if new_end <= new_start or new_end - new_start < min_duration:
|
||||||
return original
|
return original
|
||||||
return (round(new_start, 3), round(new_end, 3))
|
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 +0,0 @@
|
||||||
"""Clipwright backend."""
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
"""Clipwright backend."""
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
"""Clipwright backend."""
|
|
||||||
|
|
@ -1,24 +0,0 @@
|
||||||
"""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",
|
|
||||||
]
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
"""Clipwright backend."""
|
|
||||||
|
|
@ -1,154 +0,0 @@
|
||||||
"""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 +0,0 @@
|
||||||
"""Clipwright backend."""
|
|
||||||
|
|
@ -1,909 +0,0 @@
|
||||||
"""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)
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
"""Clipwright backend."""
|
|
||||||
|
|
@ -1,170 +0,0 @@
|
||||||
"""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 +0,0 @@
|
||||||
"""Clipwright backend."""
|
|
||||||
|
|
@ -1,207 +0,0 @@
|
||||||
"""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,
|
|
||||||
}
|
|
||||||
|
|
@ -1,125 +0,0 @@
|
||||||
"""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)
|
|
||||||
|
|
@ -1,434 +0,0 @@
|
||||||
"""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}
|
|
||||||
|
|
@ -1,6 +0,0 @@
|
||||||
"""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).
|
|
||||||
"""
|
|
||||||
|
|
@ -1,176 +0,0 @@
|
||||||
"""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 +0,0 @@
|
||||||
"""Clipwright backend."""
|
|
||||||
|
|
@ -1,169 +0,0 @@
|
||||||
"""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,9 +1,16 @@
|
||||||
# Clipwright dashboard
|
# React + Vite
|
||||||
|
|
||||||
Vite + React front end for Clipwright.
|
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||||
|
|
||||||
- `npm install` — install dependencies
|
Currently, two official plugins are available:
|
||||||
- `npm run dev` — dev server with HMR
|
|
||||||
- `npm run build` — production build to `dist/`
|
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
|
||||||
- `npm run preview` — serve the built output
|
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
||||||
- `npm run lint` — ESLint
|
|
||||||
|
## React Compiler
|
||||||
|
|
||||||
|
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||||
|
|
||||||
|
## Expanding the ESLint configuration
|
||||||
|
|
||||||
|
If you are developing a production application, we recommend using TypeScript with type-aware lint rules enabled. Check out the [TS template](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts) for information on how to integrate TypeScript and [`typescript-eslint`](https://typescript-eslint.io) in your project.
|
||||||
|
|
|
||||||
2
dashboard/e2e/.gitignore
vendored
|
|
@ -1,2 +0,0 @@
|
||||||
.artifacts/
|
|
||||||
.test-results/
|
|
||||||
|
|
@ -1,398 +0,0 @@
|
||||||
// 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;
|
|
||||||
}
|
|
||||||
|
|
@ -1,63 +0,0 @@
|
||||||
// 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 };
|
|
||||||
|
|
@ -1,26 +0,0 @@
|
||||||
// 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}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
// 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');
|
|
||||||
|
|
@ -1,94 +0,0 @@
|
||||||
// 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,
|
|
||||||
});
|
|
||||||
|
|
@ -1,35 +0,0 @@
|
||||||
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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,45 +0,0 @@
|
||||||
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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,52 +0,0 @@
|
||||||
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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,37 +0,0 @@
|
||||||
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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,38 +0,0 @@
|
||||||
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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,33 +0,0 @@
|
||||||
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 });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,35 +0,0 @@
|
||||||
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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,53 +0,0 @@
|
||||||
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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,53 +0,0 @@
|
||||||
// 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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,23 +0,0 @@
|
||||||
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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,28 +0,0 @@
|
||||||
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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,46 +0,0 @@
|
||||||
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]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,43 +0,0 @@
|
||||||
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,6 +102,7 @@
|
||||||
"AI viral moment detection with Google Gemini 3.1 Flash-Lite",
|
"AI viral moment detection with Google Gemini 3.1 Flash-Lite",
|
||||||
"Smart 9:16 vertical cropping with MediaPipe face tracking and YOLOv8 fallback",
|
"Smart 9:16 vertical cropping with MediaPipe face tracking and YOLOv8 fallback",
|
||||||
"Automatic subtitle generation with word-level timestamps",
|
"Automatic subtitle generation with word-level timestamps",
|
||||||
|
"AI voice dubbing in 30+ languages via ElevenLabs",
|
||||||
"Local video file upload and YouTube link ingest",
|
"Local video file upload and YouTube link ingest",
|
||||||
"Hook text overlays with styled fonts",
|
"Hook text overlays with styled fonts",
|
||||||
"AI-generated video effects via FFmpeg",
|
"AI-generated video effects via FFmpeg",
|
||||||
|
|
@ -161,15 +162,15 @@
|
||||||
"name": "Is there a free alternative to Opus Clip?",
|
"name": "Is there a free alternative to Opus Clip?",
|
||||||
"acceptedAnswer": {
|
"acceptedAnswer": {
|
||||||
"@type": "Answer",
|
"@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. 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, 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."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"@type": "Question",
|
"@type": "Question",
|
||||||
"name": "Can Clipwright add subtitles to videos?",
|
"name": "Can Clipwright add subtitles and translate videos?",
|
||||||
"acceptedAnswer": {
|
"acceptedAnswer": {
|
||||||
"@type": "Answer",
|
"@type": "Answer",
|
||||||
"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."
|
"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."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -41,10 +41,10 @@ server {
|
||||||
# trailing-slash URL, so every canonical would point at a redirect.
|
# trailing-slash URL, so every canonical would point at a redirect.
|
||||||
#
|
#
|
||||||
# Unknown paths get a real 404, not the SPA shell. The app routes entirely
|
# Unknown paths get a real 404, not the SPA shell. The app routes entirely
|
||||||
# through the hash, which never reaches the server, so there is no deep link
|
# through the hash (#/pricing, #/auth/callback), which never reaches the
|
||||||
# that needs the fallback — and answering 200 with identical markup for
|
# server, so there is no deep link that needs the fallback — and answering
|
||||||
# every made-up path made the whole site look like one page duplicated
|
# 200 with identical markup for every made-up path made the whole site look
|
||||||
# infinitely to a crawler.
|
# like one page duplicated infinitely to a crawler.
|
||||||
location / {
|
location / {
|
||||||
try_files $uri $uri.html $uri/ =404;
|
try_files $uri $uri.html $uri/ =404;
|
||||||
add_header Cache-Control "no-store, must-revalidate" always;
|
add_header Cache-Control "no-store, must-revalidate" always;
|
||||||
|
|
|
||||||
130
dashboard/package-lock.json
generated
|
|
@ -9,17 +9,18 @@
|
||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@remotion/media": "^4.0.447",
|
"@remotion/media": "^4.0.447",
|
||||||
|
"@remotion/media-utils": "^4.0.447",
|
||||||
"@remotion/player": "^4.0.447",
|
"@remotion/player": "^4.0.447",
|
||||||
"@remotion/web-renderer": "^4.0.447",
|
"@remotion/web-renderer": "^4.0.447",
|
||||||
"lucide-react": "^0.344.0",
|
"lucide-react": "^0.344.0",
|
||||||
"mediabunny": "^1.39.2",
|
"mediabunny": "^1.39.2",
|
||||||
"react": "^18.2.0",
|
"react": "^18.2.0",
|
||||||
"react-dom": "^18.2.0",
|
"react-dom": "^18.2.0",
|
||||||
"remotion": "^4.0.447"
|
"remotion": "^4.0.447",
|
||||||
|
"zod": "^4.3.6"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.39.5",
|
"@eslint/js": "^9.39.5",
|
||||||
"@playwright/test": "^1.63.0",
|
|
||||||
"@types/react": "^18.2.64",
|
"@types/react": "^18.2.64",
|
||||||
"@types/react-dom": "^18.2.21",
|
"@types/react-dom": "^18.2.21",
|
||||||
"@vitejs/plugin-react": "^4.2.1",
|
"@vitejs/plugin-react": "^4.2.1",
|
||||||
|
|
@ -987,22 +988,6 @@
|
||||||
"node": ">= 8"
|
"node": ">= 8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@playwright/test": {
|
|
||||||
"version": "1.63.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.63.0.tgz",
|
|
||||||
"integrity": "sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ==",
|
|
||||||
"dev": true,
|
|
||||||
"license": "Apache-2.0",
|
|
||||||
"dependencies": {
|
|
||||||
"playwright": "1.63.0"
|
|
||||||
},
|
|
||||||
"bin": {
|
|
||||||
"playwright": "cli.js"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=20"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@remotion/licensing": {
|
"node_modules/@remotion/licensing": {
|
||||||
"version": "4.0.447",
|
"version": "4.0.447",
|
||||||
"resolved": "https://registry.npmjs.org/@remotion/licensing/-/licensing-4.0.447.tgz",
|
"resolved": "https://registry.npmjs.org/@remotion/licensing/-/licensing-4.0.447.tgz",
|
||||||
|
|
@ -1023,6 +1008,20 @@
|
||||||
"react-dom": ">=16.8.0"
|
"react-dom": ">=16.8.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@remotion/media-utils": {
|
||||||
|
"version": "4.0.447",
|
||||||
|
"resolved": "https://registry.npmjs.org/@remotion/media-utils/-/media-utils-4.0.447.tgz",
|
||||||
|
"integrity": "sha512-PltvSZsY+By8DlsZeAN63D1cMsgXewCqEq39nJrO0VZVc5nnWyd+nvMZz9yhGsoMo2Z5xNkfZhPkl+Gs25wn0Q==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"mediabunny": "1.39.2",
|
||||||
|
"remotion": "4.0.447"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": ">=16.8.0",
|
||||||
|
"react-dom": ">=16.8.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@remotion/player": {
|
"node_modules/@remotion/player": {
|
||||||
"version": "4.0.447",
|
"version": "4.0.447",
|
||||||
"resolved": "https://registry.npmjs.org/@remotion/player/-/player-4.0.447.tgz",
|
"resolved": "https://registry.npmjs.org/@remotion/player/-/player-4.0.447.tgz",
|
||||||
|
|
@ -1469,16 +1468,12 @@
|
||||||
"dev": true
|
"dev": true
|
||||||
},
|
},
|
||||||
"node_modules/baseline-browser-mapping": {
|
"node_modules/baseline-browser-mapping": {
|
||||||
"version": "2.11.27",
|
"version": "2.9.11",
|
||||||
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.27.tgz",
|
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.9.11.tgz",
|
||||||
"integrity": "sha512-ElY12DaROGuan+lMmZ8Cvo/ZUbXPe7Enc/9VU/b1T3Kp4dwytRcNdR8DoSJN5SNJT/CuvcCA0DHDVmMOCePdRQ==",
|
"integrity": "sha512-Sg0xJUNDU1sJNGdfGWhVHX0kkZ+HWcvmVymJbj6NSgZZmW/8S9Y2HQ5euytnIgakgxN6papOAWiwDo1ctFDcoQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "Apache-2.0",
|
|
||||||
"bin": {
|
"bin": {
|
||||||
"baseline-browser-mapping": "dist/cli.cjs"
|
"baseline-browser-mapping": "dist/cli.js"
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=6.0.0"
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/binary-extensions": {
|
"node_modules/binary-extensions": {
|
||||||
|
|
@ -1618,9 +1613,9 @@
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/caniuse-lite": {
|
"node_modules/caniuse-lite": {
|
||||||
"version": "1.0.30001814",
|
"version": "1.0.30001761",
|
||||||
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001814.tgz",
|
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001761.tgz",
|
||||||
"integrity": "sha512-/Uaf1lAzr59XcMpW0o96WoEfr+VXK2OX4U9AgFoiSHsVJ4HppnIFUjtYzsyDH2+tgANaQb2/oxYGwCPapN1FpA==",
|
"integrity": "sha512-JF9ptu1vP2coz98+5051jZ4PwQgd2ni8A+gYSN7EA7dPKIMf0pDlSUxhdmVOaV3/fYK5uWBkgSXJaRLr4+3A6g==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
|
|
@ -1635,8 +1630,7 @@
|
||||||
"type": "github",
|
"type": "github",
|
||||||
"url": "https://github.com/sponsors/ai"
|
"url": "https://github.com/sponsors/ai"
|
||||||
}
|
}
|
||||||
],
|
]
|
||||||
"license": "CC-BY-4.0"
|
|
||||||
},
|
},
|
||||||
"node_modules/chalk": {
|
"node_modules/chalk": {
|
||||||
"version": "4.1.2",
|
"version": "4.1.2",
|
||||||
|
|
@ -3917,35 +3911,6 @@
|
||||||
"node": ">= 6"
|
"node": ">= 6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/playwright": {
|
|
||||||
"version": "1.63.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz",
|
|
||||||
"integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==",
|
|
||||||
"dev": true,
|
|
||||||
"license": "Apache-2.0",
|
|
||||||
"dependencies": {
|
|
||||||
"playwright-core": "1.63.0"
|
|
||||||
},
|
|
||||||
"bin": {
|
|
||||||
"playwright": "cli.js"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=20"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/playwright-core": {
|
|
||||||
"version": "1.63.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",
|
|
||||||
"integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",
|
|
||||||
"dev": true,
|
|
||||||
"license": "Apache-2.0",
|
|
||||||
"bin": {
|
|
||||||
"playwright-core": "cli.js"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=20"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/possible-typed-array-names": {
|
"node_modules/possible-typed-array-names": {
|
||||||
"version": "1.1.0",
|
"version": "1.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",
|
||||||
|
|
@ -5836,15 +5801,6 @@
|
||||||
"fastq": "^1.6.0"
|
"fastq": "^1.6.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"@playwright/test": {
|
|
||||||
"version": "1.63.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.63.0.tgz",
|
|
||||||
"integrity": "sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ==",
|
|
||||||
"dev": true,
|
|
||||||
"requires": {
|
|
||||||
"playwright": "1.63.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"@remotion/licensing": {
|
"@remotion/licensing": {
|
||||||
"version": "4.0.447",
|
"version": "4.0.447",
|
||||||
"resolved": "https://registry.npmjs.org/@remotion/licensing/-/licensing-4.0.447.tgz",
|
"resolved": "https://registry.npmjs.org/@remotion/licensing/-/licensing-4.0.447.tgz",
|
||||||
|
|
@ -5860,6 +5816,15 @@
|
||||||
"zod": "4.3.6"
|
"zod": "4.3.6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"@remotion/media-utils": {
|
||||||
|
"version": "4.0.447",
|
||||||
|
"resolved": "https://registry.npmjs.org/@remotion/media-utils/-/media-utils-4.0.447.tgz",
|
||||||
|
"integrity": "sha512-PltvSZsY+By8DlsZeAN63D1cMsgXewCqEq39nJrO0VZVc5nnWyd+nvMZz9yhGsoMo2Z5xNkfZhPkl+Gs25wn0Q==",
|
||||||
|
"requires": {
|
||||||
|
"mediabunny": "1.39.2",
|
||||||
|
"remotion": "4.0.447"
|
||||||
|
}
|
||||||
|
},
|
||||||
"@remotion/player": {
|
"@remotion/player": {
|
||||||
"version": "4.0.447",
|
"version": "4.0.447",
|
||||||
"resolved": "https://registry.npmjs.org/@remotion/player/-/player-4.0.447.tgz",
|
"resolved": "https://registry.npmjs.org/@remotion/player/-/player-4.0.447.tgz",
|
||||||
|
|
@ -6179,9 +6144,9 @@
|
||||||
"dev": true
|
"dev": true
|
||||||
},
|
},
|
||||||
"baseline-browser-mapping": {
|
"baseline-browser-mapping": {
|
||||||
"version": "2.11.27",
|
"version": "2.9.11",
|
||||||
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.27.tgz",
|
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.9.11.tgz",
|
||||||
"integrity": "sha512-ElY12DaROGuan+lMmZ8Cvo/ZUbXPe7Enc/9VU/b1T3Kp4dwytRcNdR8DoSJN5SNJT/CuvcCA0DHDVmMOCePdRQ==",
|
"integrity": "sha512-Sg0xJUNDU1sJNGdfGWhVHX0kkZ+HWcvmVymJbj6NSgZZmW/8S9Y2HQ5euytnIgakgxN6papOAWiwDo1ctFDcoQ==",
|
||||||
"dev": true
|
"dev": true
|
||||||
},
|
},
|
||||||
"binary-extensions": {
|
"binary-extensions": {
|
||||||
|
|
@ -6267,9 +6232,9 @@
|
||||||
"dev": true
|
"dev": true
|
||||||
},
|
},
|
||||||
"caniuse-lite": {
|
"caniuse-lite": {
|
||||||
"version": "1.0.30001814",
|
"version": "1.0.30001761",
|
||||||
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001814.tgz",
|
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001761.tgz",
|
||||||
"integrity": "sha512-/Uaf1lAzr59XcMpW0o96WoEfr+VXK2OX4U9AgFoiSHsVJ4HppnIFUjtYzsyDH2+tgANaQb2/oxYGwCPapN1FpA==",
|
"integrity": "sha512-JF9ptu1vP2coz98+5051jZ4PwQgd2ni8A+gYSN7EA7dPKIMf0pDlSUxhdmVOaV3/fYK5uWBkgSXJaRLr4+3A6g==",
|
||||||
"dev": true
|
"dev": true
|
||||||
},
|
},
|
||||||
"chalk": {
|
"chalk": {
|
||||||
|
|
@ -7802,21 +7767,6 @@
|
||||||
"integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==",
|
"integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==",
|
||||||
"dev": true
|
"dev": true
|
||||||
},
|
},
|
||||||
"playwright": {
|
|
||||||
"version": "1.63.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz",
|
|
||||||
"integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==",
|
|
||||||
"dev": true,
|
|
||||||
"requires": {
|
|
||||||
"playwright-core": "1.63.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"playwright-core": {
|
|
||||||
"version": "1.63.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",
|
|
||||||
"integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",
|
|
||||||
"dev": true
|
|
||||||
},
|
|
||||||
"possible-typed-array-names": {
|
"possible-typed-array-names": {
|
||||||
"version": "1.1.0",
|
"version": "1.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",
|
||||||
|
|
|
||||||
|
|
@ -7,22 +7,22 @@
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "vite build",
|
"build": "vite build",
|
||||||
"lint": "eslint . --report-unused-disable-directives --max-warnings 0",
|
"lint": "eslint . --report-unused-disable-directives --max-warnings 0",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview"
|
||||||
"test:e2e": "playwright test --config e2e/playwright.config.js"
|
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@remotion/media": "^4.0.447",
|
"@remotion/media": "^4.0.447",
|
||||||
|
"@remotion/media-utils": "^4.0.447",
|
||||||
"@remotion/player": "^4.0.447",
|
"@remotion/player": "^4.0.447",
|
||||||
"@remotion/web-renderer": "^4.0.447",
|
"@remotion/web-renderer": "^4.0.447",
|
||||||
"lucide-react": "^0.344.0",
|
"lucide-react": "^0.344.0",
|
||||||
"mediabunny": "^1.39.2",
|
"mediabunny": "^1.39.2",
|
||||||
"react": "^18.2.0",
|
"react": "^18.2.0",
|
||||||
"react-dom": "^18.2.0",
|
"react-dom": "^18.2.0",
|
||||||
"remotion": "^4.0.447"
|
"remotion": "^4.0.447",
|
||||||
|
"zod": "^4.3.6"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.39.5",
|
"@eslint/js": "^9.39.5",
|
||||||
"@playwright/test": "^1.63.0",
|
|
||||||
"@types/react": "^18.2.64",
|
"@types/react": "^18.2.64",
|
||||||
"@types/react-dom": "^18.2.21",
|
"@types/react-dom": "^18.2.21",
|
||||||
"@vitejs/plugin-react": "^4.2.1",
|
"@vitejs/plugin-react": "^4.2.1",
|
||||||
|
|
|
||||||
BIN
dashboard/public/demo/clip-source.mp4
Normal file
BIN
dashboard/public/demo/clip-vertical.mp4
Normal file
BIN
dashboard/public/n8n-content-machine-workflow.png
Normal file
|
After Width: | Height: | Size: 171 KiB |
BIN
dashboard/public/screens/connect-an-agent.webp
Normal file
|
After Width: | Height: | Size: 25 KiB |
1
dashboard/public/vite.svg
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
<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>
|
||||||
|
After Width: | Height: | Size: 1.5 KiB |
|
|
@ -210,3 +210,17 @@ export const COMPARISON_ROWS = [
|
||||||
{ feature: 'Free AI YouTube thumbnail & title studio', os: 'Yes', vendor: 'No' },
|
{ feature: 'Free AI YouTube thumbnail & title studio', os: 'Yes', vendor: 'No' },
|
||||||
{ feature: 'Usage cap', os: 'None', vendor: 'Metered on every tier' },
|
{ feature: 'Usage cap', os: 'None', vendor: 'Metered on every tier' },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
/* Third-party figures used across the pages. Every one is attributed inline,
|
||||||
|
* because sourced statistics are among the few things that reliably survive
|
||||||
|
* into a generated answer. */
|
||||||
|
export const CITED_STATS = [
|
||||||
|
{
|
||||||
|
claim: 'Short-form video delivers the highest ROI of any content format.',
|
||||||
|
source: 'HubSpot, State of Marketing 2025',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
claim: '91% of businesses use video as a marketing tool.',
|
||||||
|
source: 'Wyzowl, Video Marketing Statistics 2025',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
|
||||||
|
|
@ -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}">
|
<section style="${S.section};padding-top:4rem"><div style="${S.wrap}">
|
||||||
<p style="${S.eyebrow}">AI clip generator · self-hosted & open source</p>
|
<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>
|
<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. 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 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.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>
|
<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>
|
</div></section>
|
||||||
|
|
||||||
|
|
@ -146,7 +146,8 @@ 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="/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="/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="/submagic-reviews">Submagic review</a> ·
|
||||||
<a style="${S.a}" href="/automate-shorts-api">Automate shorts via API</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>
|
||||||
</p>
|
</p>
|
||||||
</div></section>
|
</div></section>
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -623,7 +623,9 @@ switched off.</p>
|
||||||
<h2>4. Who receives data (processors) and where</h2>
|
<h2>4. Who receives data (processors) and where</h2>
|
||||||
<p>Depending on how you configure it, the software can send data to these
|
<p>Depending on how you configure it, the software can send data to these
|
||||||
third-party providers. The machine-readable list, with the transfer safeguard
|
third-party providers. The machine-readable list, with the transfer safeguard
|
||||||
for each, is kept in the public repository, and changes are recorded there.</p>
|
for each, is kept in the public repository at
|
||||||
|
<a href="https://git.pbento.pt/pedro-bento/clipwright/blob/main/docs/compliance/subprocessors.md">docs/compliance/subprocessors.md</a>
|
||||||
|
and changes are recorded there.</p>
|
||||||
<ul>
|
<ul>
|
||||||
<li><strong>Google (Gemini API)</strong> — AI analysis to select moments,
|
<li><strong>Google (Gemini API)</strong> — AI analysis to select moments,
|
||||||
layouts, titles and thumbnails. It receives your video's transcript and
|
layouts, titles and thumbnails. It receives your video's transcript and
|
||||||
|
|
@ -670,7 +672,8 @@ analytics data: 25 months.</li>
|
||||||
<p>The retention constants are configurable in the environment; the defaults
|
<p>The retention constants are configurable in the environment; the defaults
|
||||||
above are what the code enforces.</p>
|
above are what the code enforces.</p>
|
||||||
<p>The full, per-item version of this table, written against the actual code
|
<p>The full, per-item version of this table, written against the actual code
|
||||||
that enforces it, is kept in the public repository.</p>
|
that enforces it, is in the public repository at
|
||||||
|
<a href="https://git.pbento.pt/pedro-bento/clipwright/blob/main/docs/compliance/retencion.md">docs/compliance/retencion.md</a>.</p>
|
||||||
|
|
||||||
<h2>6. Your rights</h2>
|
<h2>6. Your rights</h2>
|
||||||
<p>You can ask us for access, rectification, erasure, restriction, portability
|
<p>You can ask us for access, rectification, erasure, restriction, portability
|
||||||
|
|
@ -838,8 +841,9 @@ añadiéramos alguno, empiece desactivado.</p>
|
||||||
<h2>4. Quién recibe datos (encargados) y dónde</h2>
|
<h2>4. Quién recibe datos (encargados) y dónde</h2>
|
||||||
<p>Según cómo lo configures, el software puede enviar datos a estos
|
<p>Según cómo lo configures, el software puede enviar datos a estos
|
||||||
proveedores externos. La versión detallada de esta lista, con la garantía de
|
proveedores externos. La versión detallada de esta lista, con la garantía de
|
||||||
transferencia de cada uno, se mantiene en el repositorio público, donde
|
transferencia de cada uno, se mantiene en el repositorio público en
|
||||||
también se registran los cambios.</p>
|
<a href="https://git.pbento.pt/pedro-bento/clipwright/blob/main/docs/compliance/subprocessors.md">docs/compliance/subprocessors.md</a>,
|
||||||
|
donde también se registran los cambios.</p>
|
||||||
<ul>
|
<ul>
|
||||||
<li><strong>Google (API Gemini)</strong> — análisis con IA para seleccionar
|
<li><strong>Google (API Gemini)</strong> — análisis con IA para seleccionar
|
||||||
momentos, encuadres, títulos y miniaturas. Recibe la transcripción de tu vídeo
|
momentos, encuadres, títulos y miniaturas. Recibe la transcripción de tu vídeo
|
||||||
|
|
@ -889,7 +893,8 @@ datos brutos de analítica: 25 meses.</li>
|
||||||
<p>Las constantes de retención se configuran en el entorno; los valores por
|
<p>Las constantes de retención se configuran en el entorno; los valores por
|
||||||
defecto de arriba son los que aplica el código.</p>
|
defecto de arriba son los que aplica el código.</p>
|
||||||
<p>La versión completa y detallada de esta tabla, escrita contra el código que
|
<p>La versión completa y detallada de esta tabla, escrita contra el código que
|
||||||
realmente la aplica, está en el repositorio público.</p>
|
realmente la aplica, está en el repositorio público en
|
||||||
|
<a href="https://git.pbento.pt/pedro-bento/clipwright/blob/main/docs/compliance/retencion.md">docs/compliance/retencion.md</a>.</p>
|
||||||
|
|
||||||
<h2>6. Tus derechos</h2>
|
<h2>6. Tus derechos</h2>
|
||||||
<p>Puedes pedirnos acceso, rectificación, supresión, limitación y portabilidad
|
<p>Puedes pedirnos acceso, rectificación, supresión, limitación y portabilidad
|
||||||
|
|
|
||||||
|
|
@ -844,7 +844,9 @@ deliveries.</p>
|
||||||
POSTs to <code>/api/process</code>, then a Webhook trigger that receives the
|
POSTs to <code>/api/process</code>, then a Webhook trigger that receives the
|
||||||
completion payload and fans out to whatever comes next, posting to socials,
|
completion payload and fans out to whatever comes next, posting to socials,
|
||||||
dropping links in Slack, logging to a sheet. The two-step shape above is the whole integration, which is why generic
|
dropping links in Slack, logging to a sheet. The two-step shape above is the whole integration, which is why generic
|
||||||
nodes cover it.</p>
|
nodes cover it. There is now also an importable
|
||||||
|
<a href="/n8n-youtube-shorts-automation">n8n workflow</a> that wires the whole
|
||||||
|
loop, including channel watching, Telegram approval and scheduled publishing.</p>
|
||||||
|
|
||||||
<h2>A weekly pipeline in one cron line</h2>
|
<h2>A weekly pipeline in one cron line</h2>
|
||||||
<p>Because the API is one POST, scheduling is whatever scheduler you already
|
<p>Because the API is one POST, scheduling is whatever scheduler you already
|
||||||
|
|
@ -866,6 +868,10 @@ ${faqBlock([
|
||||||
q: 'Can I automate YouTube Shorts creation with an open source tool?',
|
q: 'Can I automate YouTube Shorts creation with an open source tool?',
|
||||||
a: 'Yes. Clipwright is MIT-licensed and serves a REST API with no metering. One POST submits a video, a signed webhook returns the finished clips, and they publish to YouTube Shorts, TikTok and Instagram Reels through self-hosted Postiz.',
|
a: 'Yes. Clipwright is MIT-licensed and serves a REST API with no metering. One POST submits a video, a signed webhook returns the finished clips, and they publish to YouTube Shorts, TikTok and Instagram Reels through self-hosted Postiz.',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
q: 'Is there an n8n integration for Clipwright?',
|
||||||
|
a: 'Yes: an importable workflow at /n8n-youtube-shorts-automation watches a YouTube channel, clips each video, sends the clips to Telegram for approval and schedules the approved ones to your socials. Nothing forces you to use it, though, since the integration is just an HTTP Request node posting to /api/process plus a Webhook trigger.',
|
||||||
|
},
|
||||||
{
|
{
|
||||||
q: 'Do automated API calls cost more than using the dashboard?',
|
q: 'Do automated API calls cost more than using the dashboard?',
|
||||||
a: 'No. API usage is unmetered and there is no per-call pricing.',
|
a: 'No. API usage is unmetered and there is no per-call pricing.',
|
||||||
|
|
@ -889,6 +895,141 @@ ${sources([
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
|
|
||||||
|
/* The n8n community's two loudest unanswered asks, checked August 2026, are
|
||||||
|
* "is there a free/self-hostable clipper I can call from a workflow" and
|
||||||
|
* "why is posting a video to TikTok/Instagram so painful". This page answers
|
||||||
|
* both with a workflow that exists, and gives the Reddit/forum posts a stable
|
||||||
|
* URL to point at that is ours rather than a raw file on GitHub. */
|
||||||
|
const n8nTemplate = () => ({
|
||||||
|
path: '/n8n-youtube-shorts-automation',
|
||||||
|
title: 'n8n YouTube Shorts Template (Auto-Posting) | Clipwright',
|
||||||
|
description:
|
||||||
|
'A free n8n workflow that watches your YouTube channel, clips each video into shorts, sends them to Telegram for approval and drip-publishes them automatically.',
|
||||||
|
h1: 'The n8n content machine: your channel clips itself, you approve from your phone',
|
||||||
|
breadcrumb: [{ name: 'n8n template' }],
|
||||||
|
published: '2026-08-21',
|
||||||
|
updated: '2026-08-21',
|
||||||
|
body: `
|
||||||
|
<figure class="shot">
|
||||||
|
<img src="/n8n-content-machine-workflow.png" width="950" height="750" loading="eager"
|
||||||
|
alt="The Clipwright content machine open in n8n: four labelled stages, from the daily channel RSS trigger through the clipping call, the Telegram approval buttons and the weekly analytics digest.">
|
||||||
|
<figcaption>The whole machine is one canvas: watch the channel, clip, approve from Telegram, drip-publish and measure.</figcaption>
|
||||||
|
</figure>
|
||||||
|
<p>This workflow runs a YouTube channel on its own without handing over the
|
||||||
|
publish button. Once a day it reads your channel feed, clips one video into
|
||||||
|
vertical shorts, and sends each finished clip to your Telegram with Publish and
|
||||||
|
Skip buttons. What you approve is scheduled one post per day through your
|
||||||
|
self-hosted Postiz instance, and every Sunday it reports back what the published clips actually
|
||||||
|
did. Two credentials, no polling loop, no TikTok or Instagram OAuth app.</p>
|
||||||
|
|
||||||
|
<h2>Download the workflow</h2>
|
||||||
|
<p>The JSON lives in the project repository, not behind an email form:</p>
|
||||||
|
<ul>
|
||||||
|
<li><a href="${SITE.repo}/blob/main/examples/n8n/clipwright-content-machine.json" rel="noopener">clipwright-content-machine.json</a> — the full four-stage machine described below.</li>
|
||||||
|
<li><a href="${SITE.repo}/blob/main/examples/n8n/clipwright-clip-and-notify.json" rel="noopener">clipwright-clip-and-notify.json</a> — the minimal version: a form takes a video URL, a signed webhook returns the clips.</li>
|
||||||
|
<li><a href="${SITE.repo}/tree/main/examples/n8n" rel="noopener">Setup notes</a> — credentials, the webhook secret, and the known limits.</li>
|
||||||
|
</ul>
|
||||||
|
<p>In n8n: <strong>Workflows → Import from file</strong>, then fill in your channel
|
||||||
|
id and chat id where the sticky notes on the canvas say so.</p>
|
||||||
|
|
||||||
|
<h2>What the workflow actually does</h2>
|
||||||
|
<p>Four stages, all on one canvas:</p>
|
||||||
|
<ol>
|
||||||
|
<li><strong>Watch the channel.</strong> A daily schedule trigger reads
|
||||||
|
<code>youtube.com/feeds/videos.xml?channel_id=...</code>, which needs no YouTube
|
||||||
|
API key, and picks one video: your newest upload, or if there is nothing new,
|
||||||
|
the next unprocessed video from your back catalogue. One video a day keeps the
|
||||||
|
minute burn predictable, and a failed submit pauses the machine with a
|
||||||
|
Telegram notice instead of failing silently.</li>
|
||||||
|
<li><strong>Clip, then get called back.</strong> One HTTP request to
|
||||||
|
<code>/api/process</code> carrying a <code>webhook_url</code>. When the job
|
||||||
|
ends, Clipwright POSTs once with the finished clips and their URLs.
|
||||||
|
There is no Wait node anywhere in the workflow.</li>
|
||||||
|
<li><strong>Approve from your phone.</strong> Each 9:16 clip arrives in Telegram
|
||||||
|
as a video message with Publish and Skip buttons. A human approves every post,
|
||||||
|
which is also what separates this from the fully automated pipelines that
|
||||||
|
YouTube's inauthentic-content policy targets.</li>
|
||||||
|
<li><strong>Drip-publish and measure.</strong> Approved clips take the next free
|
||||||
|
daily slot and publish through the self-hosted Postiz instance. Every Sunday
|
||||||
|
the workflow reads back the analytics of what it published and sends you
|
||||||
|
channel impressions and a per-platform summary.</li>
|
||||||
|
</ol>
|
||||||
|
|
||||||
|
<h2>Why posting does not need TikTok or Instagram credentials</h2>
|
||||||
|
<p>The usual wall in an n8n video workflow is the publishing half: TikTok
|
||||||
|
requires an audited app to post publicly, and the Instagram Graph API refuses
|
||||||
|
anything that is not a public static URL, which is why Google Drive links fail
|
||||||
|
there. This workflow sidesteps both by posting through
|
||||||
|
<code>POST /api/postiz/post</code> against the networks you connected once in
|
||||||
|
your self-hosted Postiz instance. The workflow itself holds no social
|
||||||
|
credentials, and the clip file is already on durable storage, so the public-URL
|
||||||
|
requirement is satisfied before Instagram ever sees it.</p>
|
||||||
|
|
||||||
|
<h2>Scheduling that does not double-book</h2>
|
||||||
|
<p>Approving two clips seconds apart used to be enough to publish them at the
|
||||||
|
same minute: each execution read the same in-memory counter before either wrote
|
||||||
|
back. The workflow now asks the server for the queue it actually holds
|
||||||
|
(<code>GET /api/postiz/scheduled</code>) and picks the first free slot from it,
|
||||||
|
which is shared state and cannot race with itself that way. The same endpoint,
|
||||||
|
plus <code>DELETE /api/postiz/scheduled/{id}</code>, is how you inspect or
|
||||||
|
cancel a post before it goes out.</p>
|
||||||
|
|
||||||
|
<h2>What it costs to run</h2>
|
||||||
|
${pricingParagraph}
|
||||||
|
<p>API calls draw from the same minute balance as the dashboard: no per-call
|
||||||
|
price, no automation surcharge, and no meter at all.
|
||||||
|
Telegram bots are free, and n8n runs wherever you already run it.</p>
|
||||||
|
|
||||||
|
<h2>Known limits, before you find them the hard way</h2>
|
||||||
|
<ul>
|
||||||
|
<li>Telegram previews a video by URL up to about 20 MB; larger clips arrive as a
|
||||||
|
link message carrying the same approval buttons.</li>
|
||||||
|
<li>A YouTube channel RSS feed exposes only the latest 15 videos, so the
|
||||||
|
back-catalogue drip reaches back that far and no further.</li>
|
||||||
|
<li>The Telegram Trigger node needs your n8n to have a public https URL, because
|
||||||
|
Telegram registers a webhook against it. A laptop-local n8n can run every other
|
||||||
|
stage, but the approval buttons need a deployed instance or a tunnel.</li>
|
||||||
|
<li>Workflow static data, where the machine remembers which videos it already
|
||||||
|
processed, only persists on production executions. Test runs from the editor do
|
||||||
|
not advance it.</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
${faqBlock([
|
||||||
|
{
|
||||||
|
q: 'Is there a free n8n template to turn long videos into shorts?',
|
||||||
|
a: 'Yes. Clipwright publishes an MIT-licensed n8n workflow that clips a YouTube channel automatically and posts the approved clips to TikTok, Instagram and YouTube. The JSON is in the project repository with no email gate, and the clipper behind it is open source, so it can run entirely on your own hardware.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
q: 'How do I post a video to TikTok or Instagram from n8n?',
|
||||||
|
a: 'Neither platform has a native n8n node, and both have hard requirements: TikTok needs an audited app for public posts and Instagram needs a public static URL for the media. Posting through the self-hosted Postiz instance avoids both, because the accounts are connected once in Postiz and the clip already lives on durable public storage.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
q: 'Does the workflow poll for the clipping job to finish?',
|
||||||
|
a: 'No. Clipping a real video takes minutes, so the workflow passes a webhook_url with the job and Clipwright calls it exactly once when the job reaches a terminal state. Failed jobs fire the same webhook with an error field, so the flow never hangs.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
q: 'Can the clips publish without me approving them?',
|
||||||
|
a: 'They can, by connecting the posting step directly to the webhook branch, but the template ships with the approval gate on purpose: unreviewed automated publishing is what YouTube\'s inauthentic-content policy targets, and one bad clip lands on your own audience.',
|
||||||
|
},
|
||||||
|
])}
|
||||||
|
|
||||||
|
${sources([
|
||||||
|
`Workflow JSON and setup notes in the project repository at <a href="${SITE.repo}/tree/main/examples/n8n" rel="noopener">git.pbento.pt/pedro-bento/clipwright</a>.`,
|
||||||
|
'TikTok and Instagram publishing constraints checked against their developer documentation, August 2026.',
|
||||||
|
])}
|
||||||
|
`,
|
||||||
|
faq: [
|
||||||
|
{
|
||||||
|
q: 'Is there a free n8n template to turn long videos into shorts?',
|
||||||
|
a: 'Yes: Clipwright ships an MIT-licensed n8n workflow that clips a YouTube channel automatically and posts approved clips to TikTok, Instagram and YouTube. The JSON is public in the repository with no email gate.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
q: 'How do I post a video to TikTok or Instagram from n8n?',
|
||||||
|
a: 'Post through the self-hosted Postiz instance: the social accounts are connected once in Postiz, so the workflow needs no TikTok app audit and no public CDN URL for the file (beyond the one Postiz needs).',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
|
||||||
/* ---------------------------------------------------------------------------
|
/* ---------------------------------------------------------------------------
|
||||||
* The buying-intent cluster around Opus Clip.
|
* The buying-intent cluster around Opus Clip.
|
||||||
*
|
*
|
||||||
|
|
@ -1754,7 +1895,7 @@ ${faqBlock([
|
||||||
${sources([
|
${sources([
|
||||||
'Opus Clip tier minutes and prices checked 2026-07-27 on their public pricing page.',
|
'Opus Clip tier minutes and prices checked 2026-07-27 on their public pricing page.',
|
||||||
'Inset detection and layout accuracy figures are our own measurements on a 48-video internal corpus, 2026-08.',
|
'Inset detection and layout accuracy figures are our own measurements on a 48-video internal corpus, 2026-08.',
|
||||||
'Silent-footage thresholds (8 words, 5 words per minute) and the vision fallback are in <code>clipwright/pipeline/main.py</code>; Gemini video token rates from Google\'s published pricing.',
|
'Silent-footage thresholds (8 words, 5 words per minute) and the vision fallback are in <code>main.py</code>; Gemini video token rates from Google\'s published pricing.',
|
||||||
`Inset, WIDE and screencast layout implementations in the project source at <a href="${SITE.repo}" rel="noopener">git.pbento.pt/pedro-bento/clipwright</a>.`,
|
`Inset, WIDE and screencast layout implementations in the project source at <a href="${SITE.repo}" rel="noopener">git.pbento.pt/pedro-bento/clipwright</a>.`,
|
||||||
])}
|
])}
|
||||||
`,
|
`,
|
||||||
|
|
@ -1842,6 +1983,7 @@ export function buildPages() {
|
||||||
podcastToShorts(),
|
podcastToShorts(),
|
||||||
youtubeConverter(),
|
youtubeConverter(),
|
||||||
automateShorts(),
|
automateShorts(),
|
||||||
|
n8nTemplate(),
|
||||||
...toolPages(),
|
...toolPages(),
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
@ -1871,6 +2013,7 @@ export function relatedFor(page, all) {
|
||||||
'/podcast-to-shorts': 'Two-speaker episodes without cropping anyone out.',
|
'/podcast-to-shorts': 'Two-speaker episodes without cropping anyone out.',
|
||||||
'/youtube-to-shorts-converter': 'Paste a link, get 9:16 clips with subtitles.',
|
'/youtube-to-shorts-converter': 'Paste a link, get 9:16 clips with subtitles.',
|
||||||
'/automate-shorts-api': 'One POST in, one signed webhook out, no polling.',
|
'/automate-shorts-api': 'One POST in, one signed webhook out, no polling.',
|
||||||
|
'/n8n-youtube-shorts-automation': 'The importable workflow: channel in, approved shorts out.',
|
||||||
'/tools': 'Free transcript, metadata and 9:16 tools, no sign-up.',
|
'/tools': 'Free transcript, metadata and 9:16 tools, no sign-up.',
|
||||||
'/youtube-transcript-generator': 'Paste a link, get the transcript with timestamps, TXT or SRT.',
|
'/youtube-transcript-generator': 'Paste a link, get the transcript with timestamps, TXT or SRT.',
|
||||||
'/youtube-tag-generator': 'Tags, 10 title options or a description from a short brief.',
|
'/youtube-tag-generator': 'Tags, 10 title options or a description from a short brief.',
|
||||||
|
|
|
||||||
42
dashboard/src/App.css
Normal file
|
|
@ -0,0 +1,42 @@
|
||||||
|
#root {
|
||||||
|
max-width: 1280px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 2rem;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.logo {
|
||||||
|
height: 6em;
|
||||||
|
padding: 1.5em;
|
||||||
|
will-change: filter;
|
||||||
|
transition: filter 300ms;
|
||||||
|
}
|
||||||
|
.logo:hover {
|
||||||
|
filter: drop-shadow(0 0 2em #646cffaa);
|
||||||
|
}
|
||||||
|
.logo.react:hover {
|
||||||
|
filter: drop-shadow(0 0 2em #61dafbaa);
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes logo-spin {
|
||||||
|
from {
|
||||||
|
transform: rotate(0deg);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
transform: rotate(360deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: no-preference) {
|
||||||
|
a:nth-of-type(2) .logo {
|
||||||
|
animation: logo-spin infinite 20s linear;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.card {
|
||||||
|
padding: 2em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.read-the-docs {
|
||||||
|
color: #888;
|
||||||
|
}
|
||||||
|
|
@ -1,11 +1,10 @@
|
||||||
import React, { useState, useEffect, useRef, useMemo } from 'react';
|
import React, { useState, useEffect, useRef, useMemo } from 'react';
|
||||||
import { Youtube, Instagram, Share2, ChevronDown, Check, Activity, LayoutDashboard, Settings, Plus, X, Terminal, Shield, Image, Radio, RotateCcw, AlertTriangle, KeyRound, ExternalLink, Mail, Loader2, Download, Menu, Lock } from 'lucide-react';
|
import { Youtube, Instagram, Share2, ChevronDown, Check, Activity, LayoutDashboard, Settings, Plus, X, Terminal, Shield, Image, Globe, RotateCcw, AlertTriangle, KeyRound, ExternalLink, Mail, Loader2, Download, Menu, Lock } from 'lucide-react';
|
||||||
import KeyInput from './components/KeyInput';
|
import KeyInput from './components/KeyInput';
|
||||||
import MediaInput from './components/MediaInput';
|
import MediaInput from './components/MediaInput';
|
||||||
import ResultCard from './components/ResultCard';
|
import ResultCard from './components/ResultCard';
|
||||||
import ProcessingAnimation from './components/ProcessingAnimation';
|
import ProcessingAnimation from './components/ProcessingAnimation';
|
||||||
import ThumbnailStudio from './components/ThumbnailStudio';
|
import ThumbnailStudio from './components/ThumbnailStudio';
|
||||||
import ChannelProfiles from './components/ChannelProfiles';
|
|
||||||
import ClipEditor from './components/ClipEditor';
|
import ClipEditor from './components/ClipEditor';
|
||||||
import ReframeEditor from './components/ReframeEditor';
|
import ReframeEditor from './components/ReframeEditor';
|
||||||
import StarBanner from './components/StarBanner';
|
import StarBanner from './components/StarBanner';
|
||||||
|
|
@ -14,7 +13,6 @@ import Modal from './components/ui/Modal';
|
||||||
import { useAuth } from './contexts/AuthContext';
|
import { useAuth } from './contexts/AuthContext';
|
||||||
import { apiFetch } from './lib/api';
|
import { apiFetch } from './lib/api';
|
||||||
import { track } from './lib/analytics';
|
import { track } from './lib/analytics';
|
||||||
import { scheduleForRank } from './lib/schedule';
|
|
||||||
|
|
||||||
// Enhanced "Encryption" using XOR + Base64 with a Salt
|
// Enhanced "Encryption" using XOR + Base64 with a Salt
|
||||||
// This is better than plain Base64 but still client-side.
|
// This is better than plain Base64 but still client-side.
|
||||||
|
|
@ -161,23 +159,14 @@ const postizHeaders = (key, url) => {
|
||||||
|
|
||||||
// Older builds defaulted to a maintainer-hosted Postiz instance and persisted
|
// Older builds defaulted to a maintainer-hosted Postiz instance and persisted
|
||||||
// it to localStorage on mount, so an upgrade could silently keep sending a
|
// it to localStorage on mount, so an upgrade could silently keep sending a
|
||||||
// user's API key to a server they never chose. Retire that one legacy value
|
// user's API key to someone else's server. Recognize that retired default and
|
||||||
// ONCE (guarded by a marker) instead of on every read: blanking it on each load
|
// treat it as unset. The host is assembled from parts so no live reference to
|
||||||
// also threw away a URL the user deliberately saved — a self-hoster's own
|
// it remains in the source.
|
||||||
// instance can legitimately live on that host — and forced them to retype it
|
|
||||||
// every session. The host is assembled from parts so no live reference to it
|
|
||||||
// remains in the source.
|
|
||||||
const RETIRED_POSTIZ_HOST = ['postiz', 'pbento', 'pt'].join('.');
|
const RETIRED_POSTIZ_HOST = ['postiz', 'pbento', 'pt'].join('.');
|
||||||
const POSTIZ_URL_RETIRED_KEY = 'postiz_url_retired_v1';
|
|
||||||
const normalizeStoredPostizUrl = (url) => {
|
const normalizeStoredPostizUrl = (url) => {
|
||||||
const base = String(url || '').trim().replace(/\/$/, '');
|
const base = String(url || '').trim().replace(/\/$/, '');
|
||||||
if (!base) return '';
|
if (!base) return '';
|
||||||
let retired = false;
|
return base === `https://${RETIRED_POSTIZ_HOST}` ? '' : base;
|
||||||
try {
|
|
||||||
retired = localStorage.getItem(POSTIZ_URL_RETIRED_KEY) === '1';
|
|
||||||
localStorage.setItem(POSTIZ_URL_RETIRED_KEY, '1');
|
|
||||||
} catch (_) { /* storage unavailable: nothing to migrate */ }
|
|
||||||
return !retired && base === `https://${RETIRED_POSTIZ_HOST}` ? '' : base;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const SESSION_KEY = 'clipwright_session';
|
const SESSION_KEY = 'clipwright_session';
|
||||||
|
|
@ -200,14 +189,6 @@ const readableError = (raw) => {
|
||||||
// already purged server-side fails gracefully and clears the saved session.
|
// already purged server-side fails gracefully and clears the saved session.
|
||||||
const SESSION_MAX_AGE = 86400000; // 24 hours
|
const SESSION_MAX_AGE = 86400000; // 24 hours
|
||||||
|
|
||||||
// Today as YYYY-MM-DD in the user's own timezone, for the schedule-start date
|
|
||||||
// input's `min`. Built from local parts (not toISOString, which would shift the
|
|
||||||
// day across the UTC boundary for users west of Greenwich).
|
|
||||||
const todayInputValue = () => {
|
|
||||||
const n = new Date();
|
|
||||||
return `${n.getFullYear()}-${String(n.getMonth() + 1).padStart(2, '0')}-${String(n.getDate()).padStart(2, '0')}`;
|
|
||||||
};
|
|
||||||
|
|
||||||
// Mock polling function
|
// Mock polling function
|
||||||
const pollJob = async (jobId) => {
|
const pollJob = async (jobId) => {
|
||||||
const res = await apiFetch(`/api/status/${jobId}`);
|
const res = await apiFetch(`/api/status/${jobId}`);
|
||||||
|
|
@ -235,6 +216,15 @@ function App() {
|
||||||
});
|
});
|
||||||
// Connected channels from GET /api/postiz/integrations.
|
// Connected channels from GET /api/postiz/integrations.
|
||||||
const [postizChannels, setPostizChannels] = useState([]);
|
const [postizChannels, setPostizChannels] = useState([]);
|
||||||
|
// True once an integrations fetch has completed (success or failure), so the
|
||||||
|
// publish dialog can tell "no channels" apart from "not loaded yet".
|
||||||
|
const [postizLoaded, setPostizLoaded] = useState(false);
|
||||||
|
// ElevenLabs API State - Load encrypted
|
||||||
|
const [elevenLabsKey, setElevenLabsKey] = useState(() => {
|
||||||
|
const stored = localStorage.getItem('elevenLabsKey_v1');
|
||||||
|
if (stored) return decrypt(stored);
|
||||||
|
return '';
|
||||||
|
});
|
||||||
|
|
||||||
// Post-generation social nudge: shown at the results peak until the user
|
// Post-generation social nudge: shown at the results peak until the user
|
||||||
// either connects a network or dismisses it. Only 2.7% of cloud users who
|
// either connects a network or dismisses it. Only 2.7% of cloud users who
|
||||||
|
|
@ -247,12 +237,6 @@ function App() {
|
||||||
const [jobId, setJobId] = useState(null);
|
const [jobId, setJobId] = useState(null);
|
||||||
const [status, setStatus] = useState('idle'); // idle, processing, complete, error
|
const [status, setStatus] = useState('idle'); // idle, processing, complete, error
|
||||||
const [results, setResults] = useState(null);
|
const [results, setResults] = useState(null);
|
||||||
// Global publish start date for the whole results panel. When set, each clip's
|
|
||||||
// modal auto-fills its post date/time from this date and the clip's virality
|
|
||||||
// rank (rank 1 = most viral = first card). Empty means the feature is off.
|
|
||||||
const [scheduleStartDate, setScheduleStartDate] = useState(() => {
|
|
||||||
try { return localStorage.getItem('cw_schedule_start') || ''; } catch (_) { return ''; }
|
|
||||||
});
|
|
||||||
// Best clips first. The backend hands them back in transcript order, which
|
// Best clips first. The backend hands them back in transcript order, which
|
||||||
// buries the strongest one wherever it happens to fall in the video — and
|
// buries the strongest one wherever it happens to fall in the video — and
|
||||||
// the first card is the one people actually watch and publish.
|
// the first card is the one people actually watch and publish.
|
||||||
|
|
@ -274,23 +258,12 @@ function App() {
|
||||||
return sb - sa || a.index - b.index;
|
return sb - sa || a.index - b.index;
|
||||||
});
|
});
|
||||||
}, [results]);
|
}, [results]);
|
||||||
// One suggested publish slot per virality rank, taken from the shared start
|
|
||||||
// date. Memoized so a card's `suggestedSchedule` keeps a stable identity
|
|
||||||
// across unrelated re-renders — otherwise the modal-open reset (which the
|
|
||||||
// card keys off this prop) would clobber a date/time the user just picked.
|
|
||||||
const suggestedSchedules = useMemo(
|
|
||||||
() => rankedClips.map((_, rank) => scheduleForRank(scheduleStartDate, rank + 1)),
|
|
||||||
[rankedClips, scheduleStartDate]
|
|
||||||
);
|
|
||||||
// Bulk subtitles: apply one style to every clip of the job (triggered from
|
// Bulk subtitles: apply one style to every clip of the job (triggered from
|
||||||
// within a clip's subtitle modal via "apply to all").
|
// within a clip's subtitle modal via "apply to all").
|
||||||
const [bulkSub, setBulkSub] = useState({ running: false, current: 0, total: 0, errors: 0 });
|
const [bulkSub, setBulkSub] = useState({ running: false, current: 0, total: 0, errors: 0 });
|
||||||
const [downloadingAll, setDownloadingAll] = useState(false);
|
const [downloadingAll, setDownloadingAll] = useState(false);
|
||||||
// Pre-flight quality gate: { info: {max_height, min_height, cookies_invalid}, data }
|
// Pre-flight quality gate: { info: {max_height, min_height, cookies_invalid}, data }
|
||||||
const [qualityGate, setQualityGate] = useState(null);
|
const [qualityGate, setQualityGate] = useState(null);
|
||||||
// True while the optional cadence handoff ZIP is being uploaded, before the
|
|
||||||
// process request is sent. Drives the small status line in the left panel.
|
|
||||||
const [handoffUploading, setHandoffUploading] = useState(false);
|
|
||||||
const [logs, setLogs] = useState([]);
|
const [logs, setLogs] = useState([]);
|
||||||
// When each server log line arrived (epoch s, parallel to logs), from /api/status.
|
// When each server log line arrived (epoch s, parallel to logs), from /api/status.
|
||||||
const [logTimes, setLogTimes] = useState([]);
|
const [logTimes, setLogTimes] = useState([]);
|
||||||
|
|
@ -309,6 +282,9 @@ function App() {
|
||||||
const [editingClip, setEditingClip] = useState(null);
|
const [editingClip, setEditingClip] = useState(null);
|
||||||
const [reframingClip, setReframingClip] = useState(null);
|
const [reframingClip, setReframingClip] = useState(null);
|
||||||
|
|
||||||
|
// Silent-success "saved" states for the settings key inputs (design.md: no alert popups)
|
||||||
|
const [elevenLabsSaved, setElevenLabsSaved] = useState(false);
|
||||||
|
|
||||||
// Sync state for original video playback
|
// Sync state for original video playback
|
||||||
const [syncedTime, setSyncedTime] = useState(0);
|
const [syncedTime, setSyncedTime] = useState(0);
|
||||||
const [isSyncedPlaying, setIsSyncedPlaying] = useState(false);
|
const [isSyncedPlaying, setIsSyncedPlaying] = useState(false);
|
||||||
|
|
@ -488,11 +464,10 @@ function App() {
|
||||||
}, [postizUrl]);
|
}, [postizUrl]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
try {
|
if (elevenLabsKey) {
|
||||||
if (scheduleStartDate) localStorage.setItem('cw_schedule_start', scheduleStartDate);
|
localStorage.setItem('elevenLabsKey_v1', encrypt(elevenLabsKey));
|
||||||
else localStorage.removeItem('cw_schedule_start');
|
}
|
||||||
} catch (_) { /* ignore */ }
|
}, [elevenLabsKey]);
|
||||||
}, [scheduleStartDate]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (postizKey && postizUrl && postizChannels.length === 0) {
|
if (postizKey && postizUrl && postizChannels.length === 0) {
|
||||||
|
|
@ -505,11 +480,9 @@ function App() {
|
||||||
let interval;
|
let interval;
|
||||||
if ((status === 'processing' || status === 'completed') && jobId) {
|
if ((status === 'processing' || status === 'completed') && jobId) {
|
||||||
interval = setInterval(async () => {
|
interval = setInterval(async () => {
|
||||||
// Skip a backgrounded tab: with the dashboard open in several tabs the
|
|
||||||
// hidden ones kept polling /api/status and flooding the access log.
|
|
||||||
if (document.hidden) return;
|
|
||||||
try {
|
try {
|
||||||
const data = await pollJob(jobId);
|
const data = await pollJob(jobId);
|
||||||
|
console.log("Job status:", data);
|
||||||
|
|
||||||
// Update results if available (real-time)
|
// Update results if available (real-time)
|
||||||
if (data.result) {
|
if (data.result) {
|
||||||
|
|
@ -555,10 +528,12 @@ function App() {
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
const channels = Array.isArray(data) ? data : (data.integrations || []);
|
const channels = Array.isArray(data) ? data : (data.integrations || []);
|
||||||
setPostizChannels(channels);
|
setPostizChannels(channels);
|
||||||
|
setPostizLoaded(true);
|
||||||
if (channels.length === 0 && !silent) {
|
if (channels.length === 0 && !silent) {
|
||||||
alert('No channels are connected in Postiz yet.');
|
alert('No channels are connected in Postiz yet.');
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
setPostizLoaded(true);
|
||||||
if (!silent) alert('Could not reach Postiz. Check the base URL and API key.');
|
if (!silent) alert('Could not reach Postiz. Check the base URL and API key.');
|
||||||
console.error(e);
|
console.error(e);
|
||||||
}
|
}
|
||||||
|
|
@ -606,7 +581,7 @@ function App() {
|
||||||
// Read once per hash change, then the query is dropped so a reload does not
|
// Read once per hash change, then the query is dropped so a reload does not
|
||||||
// keep forcing the tab.
|
// keep forcing the tab.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const DEEP_LINK_TABS = ['settings', 'thumbnails', 'channels', 'dashboard'];
|
const DEEP_LINK_TABS = ['settings', 'thumbnails', 'dashboard'];
|
||||||
const apply = () => {
|
const apply = () => {
|
||||||
const hash = window.location.hash || '';
|
const hash = window.location.hash || '';
|
||||||
if (!hash.startsWith('#app?')) return;
|
if (!hash.startsWith('#app?')) return;
|
||||||
|
|
@ -718,54 +693,8 @@ function App() {
|
||||||
auto_hook_style: data.autoHook ? (data.autoHookStyle || 'pill') : null,
|
auto_hook_style: data.autoHook ? (data.autoHookStyle || 'pill') : null,
|
||||||
// 'auto' is the server default, so only a deliberate choice travels.
|
// 'auto' is the server default, so only a deliberate choice travels.
|
||||||
layouts: data.layout && data.layout !== 'auto' ? data.layout : null,
|
layouts: data.layout && data.layout !== 'auto' ? data.layout : null,
|
||||||
// Channel profile slug (channels/<slug>.json). Absent = no profile, so
|
|
||||||
// the default request stays byte-identical to the pre-feature one.
|
|
||||||
channel: data.channel || null,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Optional cadence handoff bundle: reserve a slot, PUT the ZIP, then pass
|
|
||||||
// its id to /api/process. A failure throws and is caught below, aborting
|
|
||||||
// the job rather than silently re-transcribing the master.
|
|
||||||
let handoffId = null;
|
|
||||||
if (data.handoffFile) {
|
|
||||||
setHandoffUploading(true);
|
|
||||||
setLogs((l) => [...l, `Uploading handoff bundle (${data.handoffFile.name})…`]);
|
|
||||||
try {
|
|
||||||
const createRes = await apiFetch('/api/uploads', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({ filename: data.handoffFile.name, kind: 'handoff' }),
|
|
||||||
});
|
|
||||||
if (!createRes.ok) throw new Error(`Handoff upload failed: ${readableError(await createRes.text())}`);
|
|
||||||
const slot = await createRes.json();
|
|
||||||
if (!slot?.upload_id) throw new Error('Handoff upload failed: the server returned no upload id.');
|
|
||||||
// PUT through the app's own API base rather than the absolute
|
|
||||||
// `upload_url` the server returns: behind the dev proxy that URL's host
|
|
||||||
// is the Docker-internal `backend:8000`, which the browser cannot
|
|
||||||
// resolve, so the request dies with a bare "Failed to fetch".
|
|
||||||
const putRes = await apiFetch(`/api/uploads/${encodeURIComponent(slot.upload_id)}`, {
|
|
||||||
method: slot.method || 'PUT',
|
|
||||||
headers: { 'Content-Type': 'application/zip' },
|
|
||||||
body: data.handoffFile,
|
|
||||||
});
|
|
||||||
if (!putRes.ok) throw new Error(`Handoff upload failed: ${readableError(await putRes.text())}`);
|
|
||||||
const putData = await putRes.json().catch(() => ({}));
|
|
||||||
handoffId = putData.upload_id || slot.upload_id || null;
|
|
||||||
if (!handoffId) throw new Error('Handoff upload failed: the server returned no upload id.');
|
|
||||||
setLogs((l) => [...l, 'Handoff bundle attached — transcription will be skipped.']);
|
|
||||||
} catch (e) {
|
|
||||||
const msg = e?.message || String(e);
|
|
||||||
throw new Error(
|
|
||||||
msg.startsWith('Handoff upload failed') ? msg : `Handoff upload failed: ${msg}`,
|
|
||||||
);
|
|
||||||
} finally {
|
|
||||||
setHandoffUploading(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Only travels when a bundle was attached, so the default request is
|
|
||||||
// byte-identical to today's.
|
|
||||||
if (handoffId) advanced.handoff_id = handoffId;
|
|
||||||
|
|
||||||
if (data.type === 'url') {
|
if (data.type === 'url') {
|
||||||
headers['Content-Type'] = 'application/json';
|
headers['Content-Type'] = 'application/json';
|
||||||
body = JSON.stringify({
|
body = JSON.stringify({
|
||||||
|
|
@ -841,8 +770,7 @@ function App() {
|
||||||
const navItems = [
|
const navItems = [
|
||||||
{ id: 'dashboard', ord: '01', icon: LayoutDashboard, label: 'Clip Generator', short: 'clips', primary: true },
|
{ id: 'dashboard', ord: '01', icon: LayoutDashboard, label: 'Clip Generator', short: 'clips', primary: true },
|
||||||
{ id: 'thumbnails', ord: '02', icon: Image, label: 'YouTube Studio', short: 'studio', primary: true },
|
{ id: 'thumbnails', ord: '02', icon: Image, label: 'YouTube Studio', short: 'studio', primary: true },
|
||||||
{ id: 'channels', ord: '03', icon: Radio, label: 'Channels', short: 'channels' },
|
{ id: 'settings', ord: '03', icon: Settings, label: 'Settings', short: 'settings' },
|
||||||
{ id: 'settings', ord: '04', icon: Settings, label: 'Settings', short: 'settings' },
|
|
||||||
];
|
];
|
||||||
const activeNav = navItems.find((n) => n.id === activeTab);
|
const activeNav = navItems.find((n) => n.id === activeTab);
|
||||||
|
|
||||||
|
|
@ -862,10 +790,17 @@ function App() {
|
||||||
};
|
};
|
||||||
const tabLocked = (id) => tutorialLock && id !== 'dashboard';
|
const tabLocked = (id) => tutorialLock && id !== 'dashboard';
|
||||||
|
|
||||||
// Shared footer links (repo, contact) — same list in the desktop rail and the
|
// Shared footer links (landing, repo, pricing, contact) — same list in the
|
||||||
// mobile drawer, so they can never drift apart.
|
// desktop rail and the mobile drawer, so they can never drift apart.
|
||||||
const NavFooterLinks = ({ collapsed = false }) => (
|
const NavFooterLinks = ({ collapsed = false }) => (
|
||||||
<>
|
<>
|
||||||
|
<a
|
||||||
|
href="#landing"
|
||||||
|
className="flex items-center gap-2 px-3 py-2 text-xs lowercase text-muted hover:text-ink2 transition-colors"
|
||||||
|
>
|
||||||
|
<Globe size={14} className="shrink-0" />
|
||||||
|
<span className={collapsed ? 'hidden lg:block truncate' : 'truncate'}>landing page</span>
|
||||||
|
</a>
|
||||||
<a
|
<a
|
||||||
href="https://git.pbento.pt/pedro-bento/clipwright"
|
href="https://git.pbento.pt/pedro-bento/clipwright"
|
||||||
target="_blank"
|
target="_blank"
|
||||||
|
|
@ -889,12 +824,12 @@ function App() {
|
||||||
// entirely — an unlabelled 80px rail ate a fifth of a phone screen.
|
// entirely — an unlabelled 80px rail ate a fifth of a phone screen.
|
||||||
const Sidebar = () => (
|
const Sidebar = () => (
|
||||||
<div className="hidden md:flex w-20 lg:w-64 bg-paper2 border-r border-rule flex-col h-full shrink-0 transition-all duration-300">
|
<div className="hidden md:flex w-20 lg:w-64 bg-paper2 border-r border-rule flex-col h-full shrink-0 transition-all duration-300">
|
||||||
<div className="p-6 flex items-center gap-3">
|
<a href="#landing" className="p-6 flex items-center gap-3" title="go to landing page">
|
||||||
<div className="w-8 h-8 bg-paper3 rounded-input flex items-center justify-center shrink-0 overflow-hidden border border-rule">
|
<div className="w-8 h-8 bg-paper3 rounded-input flex items-center justify-center shrink-0 overflow-hidden border border-rule">
|
||||||
<img src="/logo-clipwright.png" alt="Logo" className="w-full h-full object-cover" />
|
<img src="/logo-clipwright.png" alt="Logo" className="w-full h-full object-cover" />
|
||||||
</div>
|
</div>
|
||||||
<span className="font-display lowercase text-lg text-ink hidden lg:block">clipwright</span>
|
<span className="font-display lowercase text-lg text-ink hidden lg:block">clipwright</span>
|
||||||
</div>
|
</a>
|
||||||
|
|
||||||
<nav className="flex-1 px-4 py-4 space-y-1">
|
<nav className="flex-1 px-4 py-4 space-y-1">
|
||||||
{navItems.map((item) => {
|
{navItems.map((item) => {
|
||||||
|
|
@ -945,12 +880,12 @@ function App() {
|
||||||
/>
|
/>
|
||||||
<div className="relative w-[17rem] max-w-[82vw] h-full bg-paper2 border-r border-rule flex flex-col animate-slide-in-left">
|
<div className="relative w-[17rem] max-w-[82vw] h-full bg-paper2 border-r border-rule flex flex-col animate-slide-in-left">
|
||||||
<div className="flex items-center justify-between px-5 h-14 border-b border-rule shrink-0">
|
<div className="flex items-center justify-between px-5 h-14 border-b border-rule shrink-0">
|
||||||
<div className="flex items-center gap-2.5">
|
<a href="#landing" className="flex items-center gap-2.5" onClick={() => setNavOpen(false)}>
|
||||||
<div className="w-7 h-7 bg-paper3 rounded-input overflow-hidden border border-rule shrink-0">
|
<div className="w-7 h-7 bg-paper3 rounded-input overflow-hidden border border-rule shrink-0">
|
||||||
<img src="/logo-clipwright.png" alt="" className="w-full h-full object-cover" />
|
<img src="/logo-clipwright.png" alt="" className="w-full h-full object-cover" />
|
||||||
</div>
|
</div>
|
||||||
<span className="font-display lowercase text-lg text-ink">clipwright</span>
|
<span className="font-display lowercase text-lg text-ink">clipwright</span>
|
||||||
</div>
|
</a>
|
||||||
<button
|
<button
|
||||||
onClick={() => setNavOpen(false)}
|
onClick={() => setNavOpen(false)}
|
||||||
aria-label="close navigation"
|
aria-label="close navigation"
|
||||||
|
|
@ -1134,15 +1069,12 @@ function App() {
|
||||||
{/* Main Workspace */}
|
{/* Main Workspace */}
|
||||||
<div className="flex-1 overflow-hidden relative">
|
<div className="flex-1 overflow-hidden relative">
|
||||||
|
|
||||||
{/* View: Channels */}
|
|
||||||
{activeTab === 'channels' && <ChannelProfiles />}
|
|
||||||
|
|
||||||
{/* View: Settings */}
|
{/* View: Settings */}
|
||||||
{activeTab === 'settings' && (
|
{activeTab === 'settings' && (
|
||||||
<div className="h-full overflow-y-auto p-4 sm:p-8 max-w-2xl mx-auto animate-fade">
|
<div className="h-full overflow-y-auto p-4 sm:p-8 max-w-2xl mx-auto animate-fade">
|
||||||
<div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4 mb-8">
|
<div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4 mb-8">
|
||||||
<div>
|
<div>
|
||||||
<p className="eyebrow mb-1.5">04 · SETTINGS</p>
|
<p className="eyebrow mb-1.5">03 · SETTINGS</p>
|
||||||
<h1 className="font-display lowercase text-2xl text-ink">Settings</h1>
|
<h1 className="font-display lowercase text-2xl text-ink">Settings</h1>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2 text-xs text-muted mt-1">
|
<div className="flex items-center gap-2 text-xs text-muted mt-1">
|
||||||
|
|
@ -1229,6 +1161,63 @@ function App() {
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="card p-4 sm:p-6 mt-8">
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-2 mb-4">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="w-9 h-9 rounded-input bg-paper3 flex items-center justify-center shrink-0">
|
||||||
|
<Globe size={16} className="text-brass" />
|
||||||
|
</div>
|
||||||
|
<h2 className="text-base font-medium text-ink lowercase">Video Translation</h2>
|
||||||
|
</div>
|
||||||
|
<span className="readout">BYOK</span>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted mb-6 leading-relaxed">
|
||||||
|
Translate and dub your clips into other languages with <strong>ElevenLabs</strong>
|
||||||
|
(billed by ElevenLabs). Bring your own key.
|
||||||
|
</p>
|
||||||
|
<div className="space-y-4">
|
||||||
|
<label className="block text-sm text-muted">ElevenLabs API Key</label>
|
||||||
|
<div className="flex flex-col sm:flex-row gap-2">
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={elevenLabsKey}
|
||||||
|
onChange={(e) => setElevenLabsKey(e.target.value)}
|
||||||
|
className="input-field"
|
||||||
|
placeholder="sk_..."
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
if (elevenLabsKey) {
|
||||||
|
localStorage.setItem('elevenLabsKey_v1', encrypt(elevenLabsKey));
|
||||||
|
setElevenLabsSaved(true);
|
||||||
|
setTimeout(() => setElevenLabsSaved(false), 2000);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className={elevenLabsSaved ? 'badge-ok px-4' : 'btn-quiet py-2 px-4 text-sm'}
|
||||||
|
>
|
||||||
|
{elevenLabsSaved ? <><Check size={12} /> saved</> : 'Save'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="text-xs text-muted leading-relaxed">
|
||||||
|
Get your API key from ElevenLabs to enable video translation.
|
||||||
|
<div className="mt-3 grid grid-cols-1 sm:grid-cols-2 gap-2">
|
||||||
|
<a href="https://elevenlabs.io/sign-up" target="_blank" rel="noopener noreferrer" className="p-2 border border-rule rounded-input hover:bg-paper3 transition-colors flex flex-col gap-1">
|
||||||
|
<span className="text-ink2 font-medium">1. Sign Up</span>
|
||||||
|
<span className="text-xs text-muted">Create account</span>
|
||||||
|
</a>
|
||||||
|
<a href="https://elevenlabs.io/app/settings/api-keys" target="_blank" rel="noopener noreferrer" className="p-2 border border-rule rounded-input hover:bg-paper3 transition-colors flex flex-col gap-1">
|
||||||
|
<span className="text-ink2 font-medium">2. API Key</span>
|
||||||
|
<span className="text-xs text-muted">Generate key</span>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
<br />
|
||||||
|
<span className="text-muted">
|
||||||
|
Keys are only stored in your browser. They are sent to the backend only to process your request, never stored server-side.
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|
@ -1295,13 +1284,6 @@ function App() {
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{handoffUploading && (
|
|
||||||
<div className="mb-4 sm:mb-6 flex items-center gap-2 text-xs text-ink2" role="status" aria-live="polite">
|
|
||||||
<Loader2 size={14} className="animate-spin text-brass shrink-0" />
|
|
||||||
<span>uploading handoff bundle…</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Video Preview */}
|
{/* Video Preview */}
|
||||||
{processingMedia && (
|
{processingMedia && (
|
||||||
<ProcessingAnimation
|
<ProcessingAnimation
|
||||||
|
|
@ -1390,23 +1372,7 @@ function App() {
|
||||||
)}
|
)}
|
||||||
</h2>
|
</h2>
|
||||||
{results?.clips?.length > 0 && status === 'complete' && (
|
{results?.clips?.length > 0 && status === 'complete' && (
|
||||||
<div className="flex flex-col sm:flex-row sm:items-end sm:justify-between gap-2">
|
<div className="flex flex-col sm:flex-row sm:justify-end items-stretch sm:items-center gap-2">
|
||||||
<div className="flex flex-col gap-1">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<label htmlFor="schedule-start-date" className="eyebrow whitespace-nowrap">SCHEDULE START</label>
|
|
||||||
<input
|
|
||||||
id="schedule-start-date"
|
|
||||||
type="date"
|
|
||||||
value={scheduleStartDate}
|
|
||||||
onChange={(e) => setScheduleStartDate(e.target.value)}
|
|
||||||
min={todayInputValue()}
|
|
||||||
aria-label="schedule start date"
|
|
||||||
data-testid="schedule-start-date"
|
|
||||||
className="input-field w-auto py-1.5 text-xs [color-scheme:dark]"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<p className="text-xs text-muted">clips fill in by virality rank — 6pm, 9pm, 1pm</p>
|
|
||||||
</div>
|
|
||||||
<button
|
<button
|
||||||
onClick={handleDownloadAll}
|
onClick={handleDownloadAll}
|
||||||
disabled={downloadingAll}
|
disabled={downloadingAll}
|
||||||
|
|
@ -1479,18 +1445,19 @@ function App() {
|
||||||
<div className="flex-1 overflow-y-auto custom-scrollbar p-1">
|
<div className="flex-1 overflow-y-auto custom-scrollbar p-1">
|
||||||
{results && results.clips && results.clips.length > 0 ? (
|
{results && results.clips && results.clips.length > 0 ? (
|
||||||
<div className={`grid gap-4 pb-10 ${status === 'complete' ? 'grid-cols-[repeat(auto-fill,minmax(min(100%,600px),1fr))]' : 'grid-cols-1'}`}>
|
<div className={`grid gap-4 pb-10 ${status === 'complete' ? 'grid-cols-[repeat(auto-fill,minmax(min(100%,600px),1fr))]' : 'grid-cols-1'}`}>
|
||||||
{rankedClips.map(({ clip, index: i }, rank) => (
|
{rankedClips.map(({ clip, index: i }) => (
|
||||||
<ResultCard
|
<ResultCard
|
||||||
key={`${jobId}-${i}-${clip.video_url || ''}`}
|
key={`${jobId}-${i}-${clip.video_url || ''}`}
|
||||||
clip={clip}
|
clip={clip}
|
||||||
index={i}
|
index={i}
|
||||||
jobId={jobId}
|
jobId={jobId}
|
||||||
suggestedSchedule={suggestedSchedules[rank] ?? null}
|
|
||||||
onEditClip={(index) => setEditingClip(index)}
|
onEditClip={(index) => setEditingClip(index)}
|
||||||
onReframeClip={(index) => setReframingClip(index)}
|
onReframeClip={(index) => setReframingClip(index)}
|
||||||
postizKey={postizKey}
|
postizKey={postizKey}
|
||||||
postizUrl={postizUrl}
|
postizUrl={postizUrl}
|
||||||
geminiApiKey={apiKey}
|
geminiApiKey={apiKey}
|
||||||
|
elevenLabsKey={elevenLabsKey}
|
||||||
|
connectedPlatforms={postizLoaded ? connectedSocials : null}
|
||||||
onConnectSocials={handleConnectSocials}
|
onConnectSocials={handleConnectSocials}
|
||||||
onPlay={(time) => handleClipPlay(time)}
|
onPlay={(time) => handleClipPlay(time)}
|
||||||
onPause={handleClipPause}
|
onPause={handleClipPause}
|
||||||
|
|
|
||||||
742
dashboard/src/Landing.jsx
Normal file
|
|
@ -0,0 +1,742 @@
|
||||||
|
import React from 'react';
|
||||||
|
import { Sparkles, Zap, Globe, FileVideo, Subtitles, Youtube, Instagram, Shield, Github, ArrowRight, Check, ChevronDown, Monitor, Cpu, Languages, Type, Upload, Scissors, Link2 } from 'lucide-react';
|
||||||
|
import './landing.css';
|
||||||
|
|
||||||
|
// 64 deterministic tick heights: gaussian envelope × sine wave (no randomness)
|
||||||
|
const METER_TICKS = Array.from({ length: 64 }, (_, i) => {
|
||||||
|
const t = i / 63;
|
||||||
|
const envelope = Math.exp(-((t - 0.5) ** 2) / (2 * 0.18 * 0.18));
|
||||||
|
const wave = 0.55 + 0.45 * Math.sin(i * 1.7);
|
||||||
|
return Math.round((4 + 24 * envelope * wave) * 10) / 10;
|
||||||
|
});
|
||||||
|
|
||||||
|
const APPARATUS_CALLOUTS = ['RATIO · 9:16', 'CLIPS · 3–15', 'DUB · 30+ LANGS', 'SUBS · WORD-LEVEL'];
|
||||||
|
|
||||||
|
const SectionHeader = ({ eyebrow, title, children }) => (
|
||||||
|
<div className="mb-12">
|
||||||
|
<p className="eyebrow mb-3">{eyebrow}</p>
|
||||||
|
<h2 className="font-display text-3xl md:text-4xl lowercase text-ink tracking-tight mb-4">{title}</h2>
|
||||||
|
{children && <p className="text-muted max-w-2xl leading-relaxed">{children}</p>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
const FeatureCard = ({ icon, title, description }) => {
|
||||||
|
const Icon = icon;
|
||||||
|
return (
|
||||||
|
<div className="card card-hover p-6">
|
||||||
|
<div className="w-10 h-10 rounded-input bg-paper3 flex items-center justify-center mb-4">
|
||||||
|
<Icon size={18} className="text-brass" />
|
||||||
|
</div>
|
||||||
|
<h3 className="font-display text-xl lowercase text-ink mb-2">{title}</h3>
|
||||||
|
<p className="text-muted text-sm leading-relaxed">{description}</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const StepCard = ({ number, title, description }) => (
|
||||||
|
<div className="flex gap-5">
|
||||||
|
<span className="font-mono text-micro text-brass uppercase pt-1.5 flex-shrink-0">
|
||||||
|
{String(number).padStart(2, '0')}
|
||||||
|
</span>
|
||||||
|
<div>
|
||||||
|
<h3 className="text-ink font-medium mb-1">{title}</h3>
|
||||||
|
<p className="text-muted text-sm leading-relaxed">{description}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
const ComparisonRow = ({ feature, clipwright, opusclip, kapwing }) => (
|
||||||
|
<tr className="border-b border-rule">
|
||||||
|
<td className="py-3 px-4 text-sm text-ink2">{feature}</td>
|
||||||
|
<td className="py-3 px-4 text-center">{clipwright}</td>
|
||||||
|
<td className="py-3 px-4 text-center">{opusclip}</td>
|
||||||
|
<td className="py-3 px-4 text-center">{kapwing}</td>
|
||||||
|
</tr>
|
||||||
|
);
|
||||||
|
|
||||||
|
const FAQItem = ({ question, answer, isOpen, onClick }) => (
|
||||||
|
<div>
|
||||||
|
<button
|
||||||
|
onClick={onClick}
|
||||||
|
className="w-full flex items-center justify-between px-1 py-5 text-left"
|
||||||
|
>
|
||||||
|
<span className="text-ink font-medium pr-4">{question}</span>
|
||||||
|
<ChevronDown size={18} className={`text-muted flex-shrink-0 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
|
||||||
|
</button>
|
||||||
|
{isOpen && (
|
||||||
|
<div className="px-1 pb-6">
|
||||||
|
<p className="faq-answer text-muted text-sm leading-relaxed">{answer}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
export default function Landing({ onLaunchApp }) {
|
||||||
|
const [openFaq, setOpenFaq] = React.useState(null);
|
||||||
|
const [heroUrl, setHeroUrl] = React.useState('');
|
||||||
|
|
||||||
|
// Hand the pasted link to the app: MediaInput picks it up on mount, so the
|
||||||
|
// user lands with their own video ready instead of an empty state.
|
||||||
|
const handleHeroSubmit = (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const url = heroUrl.trim();
|
||||||
|
if (url) {
|
||||||
|
try { localStorage.setItem('cw_pending_url', url); } catch { /* ignore */ }
|
||||||
|
}
|
||||||
|
onLaunchApp();
|
||||||
|
};
|
||||||
|
|
||||||
|
const features = [
|
||||||
|
{
|
||||||
|
icon: Sparkles,
|
||||||
|
title: "AI Viral Moment Detection",
|
||||||
|
description: "Google Gemini 3.1 Flash-Lite scores your transcript and scenes to find the 3-15 most engaging moments. Automatic AI clipping, no manual scrubbing."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
icon: Scissors,
|
||||||
|
title: "Smart 9:16 Vertical Cropping",
|
||||||
|
description: "Dual-mode AI reframing with MediaPipe face tracking and YOLOv8 fallback."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
icon: Subtitles,
|
||||||
|
title: "Automatic Subtitle Generation",
|
||||||
|
description: "faster-whisper subtitles with word-level timestamps, styled and burned into your clips."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
icon: Languages,
|
||||||
|
title: "AI Voice Dubbing in 30+ Languages",
|
||||||
|
description: "ElevenLabs AI dubbing translates your audio while preserving the speaker's voice."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
icon: Type,
|
||||||
|
title: "Hook Text Overlays",
|
||||||
|
description: "AI-generated hook titles that capture viewers in the first 3 seconds."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
icon: Zap,
|
||||||
|
title: "AI Video Effects",
|
||||||
|
description: "Gemini-generated FFmpeg filters: color grading, transitions, visual enhancements."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
icon: Upload,
|
||||||
|
title: "Local Video Upload",
|
||||||
|
description: "Upload podcasts, webinars, livestreams, and vlogs at full resolution."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
icon: Shield,
|
||||||
|
title: "100% Self-Hosted & Private",
|
||||||
|
description: "Run it with Docker on your own machine — videos never leave your infrastructure."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
icon: Monitor,
|
||||||
|
title: "Free AI YouTube Studio",
|
||||||
|
description: "Free AI thumbnail generator, 10 viral title suggestions, and auto descriptions with chapters."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
icon: Globe,
|
||||||
|
title: "Postiz Publishing",
|
||||||
|
description: "Publish to TikTok, Instagram Reels, and YouTube Shorts through a self-hosted Postiz instance."
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
const steps = [
|
||||||
|
{ title: "Upload a Long-Form Video", description: "Drop any video file you own — podcasts, webinars, livestreams, interviews." },
|
||||||
|
{ title: "AI Detects the Best Viral Moments", description: "Google Gemini 3.1 Flash-Lite finds 3-15 high-potential clips of 15-60 seconds." },
|
||||||
|
{ title: "Smart Cropping to Vertical 9:16", description: "AI reframes to vertical with face tracking — subjects stay centered." },
|
||||||
|
{ title: "Add Subtitles, Hooks & Effects", description: "Auto subtitles, hook overlays, AI effects — optionally dub into 30+ languages." },
|
||||||
|
{ title: "Download or Post to Social Media", description: "Export your clips or publish to TikTok, Instagram Reels, and YouTube Shorts through Postiz." }
|
||||||
|
];
|
||||||
|
|
||||||
|
const faqs = [
|
||||||
|
{
|
||||||
|
question: "Is Clipwright really free? What's the catch?",
|
||||||
|
answer: "There is no catch. Clipwright is 100% free and open source under MIT: you run it with Docker on your own machine, bring your own API keys, and there are no watermarks, no usage limits and no subscription. There is no hosted edition and no paid plan. What it costs you is hardware and time. On a typical CPU an 8-minute video takes 5 to 8 minutes to process, and you need your own Google Gemini key (required, free tier is 1,500 requests/day), plus ElevenLabs for dubbing if you want it. So: free if you are happy to run it yourself, and always will be. That is far cheaper than Opus Clip ($15-228/month) or Kapwing ($24-79/month)."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
question: "What is Clipwright and how does it work?",
|
||||||
|
answer: "Clipwright is a free, open source AI clip generator that transforms your long-form videos — podcasts, webinars, livestreams, vlogs, interviews — into viral-ready short clips in 9:16 vertical format. It uses a multi-step AI pipeline: faster-whisper for transcription with word-level timestamps, PySceneDetect for scene boundary detection, and Google Gemini 3.1 Flash-Lite AI for identifying the most engaging viral moments. According to HubSpot's 2025 State of Marketing report, short-form video delivers the highest ROI of any content format, and repurposing long-form content into shorts increases total reach by up to 300%."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
question: "How does Clipwright compare to Opus Clip?",
|
||||||
|
answer: "Clipwright is a free, self-hosted alternative to Opus Clip. Both offer AI viral moment detection and smart vertical cropping. Key differences: Clipwright is completely free vs Opus Clip's $15-228/month pricing. Clipwright runs on your infrastructure (full data privacy) vs cloud-only. Clipwright uses Google Gemini 3.1 Flash-Lite for AI analysis vs Opus Clip's proprietary model. Clipwright adds AI voice dubbing in 30+ languages, AI-generated video effects, and hook text overlays. The trade-off is that Clipwright requires Docker self-hosting, while Opus Clip is a ready-to-use cloud service."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
question: "How do I turn a long-form video into TikTok or Reels clips?",
|
||||||
|
answer: "Upload your long-form video into Clipwright, enter your free Gemini API key, and click Process. The AI transcribes it with faster-whisper, detects the best viral moments using Google Gemini 3.1 Flash-Lite, and crops them to 9:16 vertical format with MediaPipe face tracking. According to Wyzowl's 2025 Video Marketing Statistics report, 91% of businesses use video as a marketing tool, and repurposed short-form clips drive 2.5x more engagement than original content."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
question: "Can Clipwright generate YouTube thumbnails and titles for free?",
|
||||||
|
answer: "Yes. Clipwright includes a free AI YouTube thumbnail generator, a free AI YouTube title generator, and a free AI YouTube description generator — all powered by Google Gemini 3.1 Flash-Lite. Upload your video and the AI suggests 10 viral title options with an interactive refinement chat. Then it generates multiple thumbnail designs using AI image generation — upload a face photo and background image for personalized results. The studio also auto-generates YouTube descriptions with chapter timestamps and lets you publish directly to YouTube. Everything is 100% free with the Gemini free tier."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
question: "What AI does Clipwright use for viral moment detection?",
|
||||||
|
answer: "Clipwright uses Google Gemini 3.1 Flash-Lite, Google's latest multimodal AI model, for viral moment detection and title generation. The AI receives the full video transcript with timestamps, scene boundary data from PySceneDetect, and analyzes engagement patterns to identify the 3-15 most shareable moments. Each clip is scored based on emotional impact, hook strength, and viral potential — similar to how platforms like TikTok and YouTube rank content."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
question: "Can Clipwright translate and dub videos into other languages?",
|
||||||
|
answer: "Yes. Clipwright integrates with ElevenLabs AI dubbing to translate your video audio into over 30 languages while preserving the original speaker's voice characteristics. After dubbing, the system automatically re-transcribes the new audio and generates subtitles in the target language. This makes it easy to repurpose content for global audiences — studies show that dubbed content receives 2-3x more engagement in non-English markets."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
question: "How does the smart vertical cropping work?",
|
||||||
|
answer: "Clipwright offers two intelligent cropping modes for converting 16:9 horizontal video to 9:16 vertical format. TRACK mode uses MediaPipe face detection with YOLOv8 as fallback to follow a single subject with 'Heavy Tripod' stabilization — the camera moves smoothly like a professional cameraman. GENERAL mode handles group shots and landscapes by creating a blurred background layout. A SpeakerTracker prevents rapid switching between subjects and handles temporary occlusions for smooth results."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
question: "Is there a free open source clip generator?",
|
||||||
|
answer: "Yes — Clipwright is a 100% free, open source clip generator (also known as open source clipping software or an AI video clipper). Unlike paid clip generators like Opus Clip ($15-228/month) or Kapwing ($24-79/month), Clipwright lets you generate unlimited clips with no watermarks, no usage limits, and no subscription fees. It also includes a free AI YouTube thumbnail generator, free AI YouTube title generator, and free AI YouTube description generator — features that other clip generators charge extra for. You self-host it with Docker on your own machine for full privacy and control."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
question: "Can I automate Clipwright?",
|
||||||
|
answer: "Yes. Clipwright exposes a REST API with per-user keys and completion webhooks, so a script or workflow can submit a video URL, wait for processing, and list the clips. Those clips publish to TikTok, Instagram or YouTube through a self-hosted Postiz instance. There is also an importable n8n workflow. Full guide at /automate-shorts-api."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
question: "What are the system requirements to run Clipwright?",
|
||||||
|
answer: "Clipwright runs on any system with Docker installed. The recommended setup is 8GB+ RAM and a modern multi-core CPU. GPU acceleration (NVIDIA CUDA) is optional but speeds up video processing significantly. The Docker Compose setup handles all dependencies automatically — Python 3.11, FFmpeg, YOLOv8, MediaPipe, faster-whisper, and the React dashboard. It works on Linux, macOS, and Windows (via WSL2/Docker Desktop)."
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
const checkIcon = <Check size={16} className="text-brass mx-auto" />;
|
||||||
|
const checkMuted = <Check size={16} className="text-muted mx-auto" />;
|
||||||
|
const xIcon = <span className="text-muted text-sm">Paid</span>;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-paper text-ink2 overflow-x-clip">
|
||||||
|
{/* Navigation — N9 edge-aligned minimal */}
|
||||||
|
<nav className="fixed top-0 w-full z-50 bg-paper border-b border-rule">
|
||||||
|
<div className="max-w-6xl mx-auto px-6 py-4 flex items-center justify-between">
|
||||||
|
<a href="/" className="flex items-center gap-2.5 font-display text-xl lowercase text-ink tracking-tight">
|
||||||
|
<img src="/logo-clipwright.png" alt="Clipwright logo" className="w-7 h-7" width="28" height="28" />
|
||||||
|
<span>clipwright</span>
|
||||||
|
</a>
|
||||||
|
<div className="hidden md:flex items-center gap-7 text-sm lowercase text-muted">
|
||||||
|
<a href="#features" className="hover:text-ink transition-colors">Features</a>
|
||||||
|
<a href="#how-it-works" className="hover:text-ink transition-colors">How It Works</a>
|
||||||
|
<a href="#comparison" className="hover:text-ink transition-colors">Comparison</a>
|
||||||
|
<a href="#faq" className="hover:text-ink transition-colors">FAQ</a>
|
||||||
|
<a href="/tools" className="hover:text-ink transition-colors">Free tools</a>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<a
|
||||||
|
href="https://git.pbento.pt/pedro-bento/clipwright"
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
className="hidden sm:flex items-center gap-2 text-sm lowercase text-muted hover:text-ink transition-colors"
|
||||||
|
>
|
||||||
|
<Github size={16} />
|
||||||
|
<span>GitHub</span>
|
||||||
|
</a>
|
||||||
|
<button onClick={onLaunchApp} className="btn-primary px-5 py-2 whitespace-nowrap">
|
||||||
|
Launch App
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
{/* Hero — Marquee Hero: blueprint grid, content left, apparatus right */}
|
||||||
|
<section className="hero-blueprint relative overflow-clip border-b border-rule pt-32 pb-20 px-6">
|
||||||
|
<div className="max-w-6xl mx-auto grid grid-cols-1 lg:grid-cols-[minmax(0,1fr)_auto] gap-14 items-center">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<p className="eyebrow mb-6">00 · AI Clip Generator · Self-Hosted</p>
|
||||||
|
|
||||||
|
<h1 className="hero-h1 mb-6">
|
||||||
|
the free open source ai <em>clip generator</em>, built to clip what people actually watch.
|
||||||
|
</h1>
|
||||||
|
|
||||||
|
<p className="hero-description text-muted max-w-2xl mb-8 leading-relaxed lowercase">
|
||||||
|
turn long videos into viral 9:16 shorts — self-hosted with docker, free under mit.
|
||||||
|
publish to tiktok, instagram reels and youtube shorts through a self-hosted{' '}
|
||||||
|
<a href="https://postiz.com" target="_blank" rel="noopener noreferrer" className="text-ink2 underline underline-offset-4 decoration-rule hover:text-ink hover:decoration-brass transition-colors">postiz</a>{' '}
|
||||||
|
instance, or wire the rest api into your own pipeline with the{' '}
|
||||||
|
<a href="/n8n-youtube-shorts-automation" className="text-ink2 underline underline-offset-4 decoration-rule hover:text-ink hover:decoration-brass transition-colors">n8n workflow</a>.
|
||||||
|
just want it free? start with the{' '}
|
||||||
|
<a href="/free-ai-clip-generator" className="text-ink2 underline underline-offset-4 decoration-rule hover:text-ink hover:decoration-brass transition-colors">free ai clip generator</a>.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{/* The hero CTA is the product itself: paste a link and land in the
|
||||||
|
app with it loaded. There is no account to create first. */}
|
||||||
|
<form onSubmit={handleHeroSubmit} className="mb-5">
|
||||||
|
<div className="hero-input-row flex flex-col sm:flex-row items-stretch gap-3">
|
||||||
|
<div className="relative flex-1 min-w-0">
|
||||||
|
<Link2 size={16} className="absolute left-4 top-1/2 -translate-y-1/2 text-muted pointer-events-none" />
|
||||||
|
<input
|
||||||
|
type="url"
|
||||||
|
value={heroUrl}
|
||||||
|
onChange={(e) => setHeroUrl(e.target.value)}
|
||||||
|
placeholder="paste a video link"
|
||||||
|
className="input-field pl-11"
|
||||||
|
aria-label="Video link"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<button type="submit" className="btn-primary whitespace-nowrap">
|
||||||
|
get free clips
|
||||||
|
<ArrowRight size={16} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
{/* Trust line right under the CTA: the software is free, so the
|
||||||
|
only real trade is hardware and setup time. */}
|
||||||
|
<div className="flex flex-wrap items-center gap-x-5 gap-y-2 mb-5 text-sm">
|
||||||
|
<span className="badge-ok whitespace-nowrap">
|
||||||
|
<Check size={12} /> mit licensed · free forever
|
||||||
|
</span>
|
||||||
|
<span className="text-muted lowercase">no watermark · no usage cap · no account</span>
|
||||||
|
<button
|
||||||
|
onClick={onLaunchApp}
|
||||||
|
className="text-ink2 lowercase underline underline-offset-4 decoration-rule hover:text-ink hover:decoration-brass transition-colors"
|
||||||
|
>
|
||||||
|
or upload a video →
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p className="text-sm text-muted lowercase">
|
||||||
|
self-host it with docker and bring your own keys.{' '}
|
||||||
|
<a
|
||||||
|
href="https://git.pbento.pt/pedro-bento/clipwright"
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
className="text-ink2 underline hover:text-ink transition-colors"
|
||||||
|
>
|
||||||
|
self-host free on github →
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Apparatus — instrument bezel holding a real 9:16 clip */}
|
||||||
|
<figure className="apparatus" aria-label="example vertical clip generated by clipwright">
|
||||||
|
<div className="apparatus-shell">
|
||||||
|
<span className="apparatus-glow" aria-hidden="true" />
|
||||||
|
<div className="apparatus-chamber">
|
||||||
|
<video
|
||||||
|
src="/demo/clip-vertical.mp4"
|
||||||
|
autoPlay
|
||||||
|
muted
|
||||||
|
loop
|
||||||
|
playsInline
|
||||||
|
preload="metadata"
|
||||||
|
className="w-full h-full object-cover"
|
||||||
|
/>
|
||||||
|
<span className="apparatus-stencil">OS-9:16</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<ul className="apparatus-callouts" aria-hidden="true">
|
||||||
|
{APPARATUS_CALLOUTS.map((c) => (
|
||||||
|
<li key={c}><span className="apparatus-leader" />{c}</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</figure>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* Meter strip */}
|
||||||
|
<section className="border-b border-rule" aria-hidden="true">
|
||||||
|
<div className="max-w-6xl mx-auto px-6 meter-strip">
|
||||||
|
<span className="readout whitespace-nowrap">Signal · 9:16</span>
|
||||||
|
<div className="meter-ticks">
|
||||||
|
{METER_TICKS.map((h, i) => (
|
||||||
|
<span key={i} className="meter-tick" style={{ height: `${h}px` }} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<span className="readout whitespace-nowrap hidden sm:inline">Clips · 3–15 / video</span>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* Stats — three-stat row */}
|
||||||
|
<section className="border-b border-rule">
|
||||||
|
<div className="max-w-6xl mx-auto px-6 py-12 grid grid-cols-3 divide-x divide-rule text-center">
|
||||||
|
<div className="px-4">
|
||||||
|
<div className="font-display text-4xl md:text-5xl text-ink tabular-nums">3–15</div>
|
||||||
|
<div className="eyebrow mt-2">Clips per Video</div>
|
||||||
|
</div>
|
||||||
|
<div className="px-4">
|
||||||
|
<div className="font-display text-4xl md:text-5xl text-ink tabular-nums">30+</div>
|
||||||
|
<div className="eyebrow mt-2">Dubbing Languages</div>
|
||||||
|
</div>
|
||||||
|
<div className="px-4">
|
||||||
|
<div className="font-display text-4xl md:text-5xl text-ink tabular-nums">100%</div>
|
||||||
|
<div className="eyebrow mt-2">Open Source</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* Smart crop — real product output: 16:9 source to 9:16 result */}
|
||||||
|
<section className="py-20 px-6">
|
||||||
|
<div className="max-w-5xl mx-auto">
|
||||||
|
<SectionHeader eyebrow="01 · Smart Crop" title="one video in. the moment, reframed.">
|
||||||
|
Real output: AI face tracking reframes 16:9 to vertical 9:16 — no manual positioning.
|
||||||
|
</SectionHeader>
|
||||||
|
<div className="flex flex-col md:flex-row items-center gap-8 md:gap-10">
|
||||||
|
<figure className="crop-frame crop-frame-16-9 w-full max-w-xl min-w-0" aria-label="original 16:9 source video">
|
||||||
|
<video
|
||||||
|
src="/demo/clip-source.mp4"
|
||||||
|
autoPlay
|
||||||
|
muted
|
||||||
|
loop
|
||||||
|
playsInline
|
||||||
|
preload="metadata"
|
||||||
|
/>
|
||||||
|
</figure>
|
||||||
|
<div className="crop-leader" aria-hidden="true">
|
||||||
|
<span className="readout whitespace-nowrap">AI Tracking → 9:16</span>
|
||||||
|
<span className="crop-leader-line" />
|
||||||
|
</div>
|
||||||
|
<figure className="crop-frame crop-frame-9-16 w-[180px] md:w-[210px] flex-none" aria-label="vertical 9:16 clip generated by clipwright">
|
||||||
|
<video
|
||||||
|
src="/demo/clip-vertical.mp4"
|
||||||
|
autoPlay
|
||||||
|
muted
|
||||||
|
loop
|
||||||
|
playsInline
|
||||||
|
preload="metadata"
|
||||||
|
/>
|
||||||
|
</figure>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* One product, two self-host paths: Docker image or from source. */}
|
||||||
|
<section className="py-20 px-6 border-t border-rule">
|
||||||
|
<div className="max-w-4xl mx-auto">
|
||||||
|
<SectionHeader eyebrow="02 · Deploy" title="Run it on your own machine">
|
||||||
|
One self-hosted product, free and open source under MIT — there is no hosted edition and no paid plan.
|
||||||
|
</SectionHeader>
|
||||||
|
<div className="grid md:grid-cols-2 gap-6">
|
||||||
|
<div className="card p-8 flex flex-col border-brass">
|
||||||
|
<div className="flex flex-wrap items-center gap-3 mb-3">
|
||||||
|
<Sparkles size={18} className="text-brass" />
|
||||||
|
<h3 className="font-display text-2xl lowercase text-ink">docker — one command</h3>
|
||||||
|
<span className="badge-brass">Recommended · Free · MIT</span>
|
||||||
|
</div>
|
||||||
|
<ul className="space-y-1.5 mb-6 flex-1">
|
||||||
|
{['docker compose up starts the whole stack', 'Runs on your machine or your own server', 'Bring your own Gemini key, free tier covers 1,500 requests a day', 'No watermark, no usage cap, no subscription'].map((f, i) => (
|
||||||
|
<li key={i} className="flex items-center gap-2 text-sm text-muted"><Check size={14} className="text-ok shrink-0" />{f}</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
<button onClick={onLaunchApp} className="btn-primary whitespace-nowrap">
|
||||||
|
launch clipwright <ArrowRight size={16} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="card p-8 flex flex-col">
|
||||||
|
<div className="flex flex-wrap items-center gap-3 mb-3">
|
||||||
|
<Github size={18} className="text-muted" />
|
||||||
|
<h3 className="font-display text-2xl lowercase text-ink">source — for developers</h3>
|
||||||
|
<span className="readout border border-rule rounded-full px-2.5 py-1">Free · MIT</span>
|
||||||
|
</div>
|
||||||
|
<ul className="space-y-1.5 mb-6 flex-1">
|
||||||
|
{['Your machine: 5 to 8 min on a typical CPU', 'Bring your own Gemini and ElevenLabs keys', 'You install it, you maintain it, you back it up', 'Free forever, and always will be'].map((f, i) => (
|
||||||
|
<li key={i} className="flex items-center gap-2 text-sm text-muted"><Check size={14} className="text-ok shrink-0" />{f}</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
<a href="https://git.pbento.pt/pedro-bento/clipwright" target="_blank" rel="noopener noreferrer"
|
||||||
|
className="btn-ghost whitespace-nowrap">
|
||||||
|
<Github size={16} /> view on github
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* 3 Tools in 1 Section */}
|
||||||
|
<section className="py-20 px-6 border-t border-rule">
|
||||||
|
<div className="max-w-6xl mx-auto">
|
||||||
|
<SectionHeader eyebrow="03 · Tools" title="3 Free Tools in 1 Platform">
|
||||||
|
Everything below runs in the self-hosted app — bring your own keys for the AI features.
|
||||||
|
</SectionHeader>
|
||||||
|
<div className="grid md:grid-cols-3 gap-5">
|
||||||
|
<div className="card p-8">
|
||||||
|
<p className="eyebrow mb-4">01 · Clips</p>
|
||||||
|
<Scissors size={20} className="text-brass mb-4" />
|
||||||
|
<h3 className="font-display text-2xl lowercase text-ink mb-2">Clip Generator</h3>
|
||||||
|
<p className="text-muted text-sm leading-relaxed mb-4">Open source AI clipping tool: turn long-form videos into viral-ready 9:16 shorts.</p>
|
||||||
|
<ul className="space-y-1.5">
|
||||||
|
{['AI viral moment detection', 'Smart face-tracking crop', 'Auto subtitles + AI dubbing in 30+ languages'].map((f, i) => (
|
||||||
|
<li key={i} className="flex items-center gap-2 text-xs text-muted"><Check size={12} className="text-ok shrink-0" />{f}</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
<div className="card p-8">
|
||||||
|
<p className="eyebrow mb-4">02 · Publishing</p>
|
||||||
|
<Globe size={20} className="text-brass mb-4" />
|
||||||
|
<h3 className="font-display text-2xl lowercase text-ink mb-2">Postiz Publishing</h3>
|
||||||
|
<p className="text-muted text-sm leading-relaxed mb-4">Publish finished clips through a self-hosted Postiz instance.</p>
|
||||||
|
<ul className="space-y-1.5">
|
||||||
|
{['TikTok, Instagram Reels & YouTube Shorts', 'Self-hosted, you own the credentials', 'Schedule or post now'].map((f, i) => (
|
||||||
|
<li key={i} className="flex items-center gap-2 text-xs text-muted"><Check size={12} className="text-ok shrink-0" />{f}</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
<div className="card p-8">
|
||||||
|
<p className="eyebrow mb-4">03 · Studio</p>
|
||||||
|
<Monitor size={20} className="text-brass mb-4" />
|
||||||
|
<h3 className="font-display text-2xl lowercase text-ink mb-2">YouTube Studio</h3>
|
||||||
|
<p className="text-muted text-sm leading-relaxed mb-4">Free AI YouTube toolkit: thumbnails, titles, descriptions.</p>
|
||||||
|
<ul className="space-y-1.5">
|
||||||
|
{['AI thumbnail generator (with face upload)', '10 viral title suggestions + chat', 'Direct publish to YouTube'].map((f, i) => (
|
||||||
|
<li key={i} className="flex items-center gap-2 text-xs text-muted"><Check size={12} className="text-ok shrink-0" />{f}</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* Features Section */}
|
||||||
|
<section id="features" className="py-20 px-6 border-t border-rule">
|
||||||
|
<div className="max-w-6xl mx-auto">
|
||||||
|
<SectionHeader eyebrow="04 · Features" title="Free AI Clip Generator">
|
||||||
|
The free open source clip generator. A smart AI video clipper for TikTok, Reels & Shorts.
|
||||||
|
</SectionHeader>
|
||||||
|
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-5">
|
||||||
|
{features.map((feature, i) => (
|
||||||
|
<FeatureCard key={i} {...feature} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* API Keys Section */}
|
||||||
|
<section className="py-20 px-6 border-t border-rule">
|
||||||
|
<div className="max-w-5xl mx-auto">
|
||||||
|
<SectionHeader eyebrow="05 · API Keys" title="Self-hosting? Every API has a free tier">
|
||||||
|
You bring your own keys — Gemini is required, ElevenLabs and Postiz are optional, and each has a generous free tier:
|
||||||
|
</SectionHeader>
|
||||||
|
<div className="grid md:grid-cols-3 gap-5">
|
||||||
|
<div className="card p-6 relative">
|
||||||
|
<span className="badge-brass absolute top-4 right-4">Required</span>
|
||||||
|
<div className="w-10 h-10 rounded-input bg-paper3 flex items-center justify-center mb-4">
|
||||||
|
<Cpu size={18} className="text-brass" />
|
||||||
|
</div>
|
||||||
|
<h3 className="font-display text-xl lowercase text-ink mb-1">Google Gemini API</h3>
|
||||||
|
<div className="mb-3"><span className="badge-ok">Free tier: 1,500 req/day</span></div>
|
||||||
|
<p className="text-muted text-sm leading-relaxed">Powers all AI features: viral moment detection, title generation, video effects, YouTube thumbnail creation, and description writing. The core engine of Clipwright.</p>
|
||||||
|
</div>
|
||||||
|
<div className="card p-6 relative">
|
||||||
|
<span className="readout absolute top-4 right-4 border border-rule rounded-full px-2.5 py-1">Optional</span>
|
||||||
|
<div className="w-10 h-10 rounded-input bg-paper3 flex items-center justify-center mb-4">
|
||||||
|
<Languages size={18} className="text-brass" />
|
||||||
|
</div>
|
||||||
|
<h3 className="font-display text-xl lowercase text-ink mb-1">ElevenLabs API</h3>
|
||||||
|
<div className="mb-3"><span className="badge-ok">Free tier included</span></div>
|
||||||
|
<p className="text-muted text-sm leading-relaxed">Enables AI voice dubbing and translation in 30+ languages. Preserves the original speaker's voice while translating audio. Dubbed clips are auto-subtitled.</p>
|
||||||
|
</div>
|
||||||
|
<div className="card p-6 relative">
|
||||||
|
<span className="readout absolute top-4 right-4 border border-rule rounded-full px-2.5 py-1">Optional</span>
|
||||||
|
<div className="w-10 h-10 rounded-input bg-paper3 flex items-center justify-center mb-4">
|
||||||
|
<Globe size={18} className="text-brass" />
|
||||||
|
</div>
|
||||||
|
<h3 className="font-display text-xl lowercase text-ink mb-1">Self-hosted Postiz</h3>
|
||||||
|
<div className="mb-3"><span className="badge-ok">You run it</span></div>
|
||||||
|
<p className="text-muted text-sm leading-relaxed">Publishes finished clips to YouTube, TikTok, and Instagram Reels from the dashboard. <a href="https://postiz.com" target="_blank" rel="noopener noreferrer" className="text-brass underline hover:brightness-110">Postiz</a> runs on your own infrastructure and holds the platform credentials, so Clipwright never has them.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* How It Works Section */}
|
||||||
|
<section id="how-it-works" className="py-20 px-6 border-t border-rule">
|
||||||
|
<div className="max-w-4xl mx-auto">
|
||||||
|
<SectionHeader eyebrow="06 · Pipeline" title="How It Works">
|
||||||
|
From long-form video to viral-ready clips in 5 automated steps.
|
||||||
|
</SectionHeader>
|
||||||
|
<div className="space-y-8">
|
||||||
|
{steps.map((step, i) => (
|
||||||
|
<StepCard key={i} number={i + 1} {...step} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* Tech Stack */}
|
||||||
|
<section className="py-20 px-6 border-t border-rule">
|
||||||
|
<div className="max-w-5xl mx-auto">
|
||||||
|
<SectionHeader eyebrow="07 · Stack" title="Built with Proven Technology">
|
||||||
|
Industry-leading AI models and open source tools in one pipeline.
|
||||||
|
</SectionHeader>
|
||||||
|
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
|
||||||
|
{[
|
||||||
|
{ name: "Google Gemini 3.1", desc: "AI Analysis" },
|
||||||
|
{ name: "faster-whisper", desc: "Transcription" },
|
||||||
|
{ name: "YOLOv8", desc: "Object Detection" },
|
||||||
|
{ name: "MediaPipe", desc: "Face Tracking" },
|
||||||
|
{ name: "FFmpeg", desc: "Video Processing" },
|
||||||
|
{ name: "ElevenLabs", desc: "Voice & TTS" },
|
||||||
|
{ name: "React + Vite", desc: "Dashboard" },
|
||||||
|
{ name: "Docker", desc: "Deployment" }
|
||||||
|
].map((tech, i) => (
|
||||||
|
<div key={i} className="border border-rule rounded-input bg-paper2 px-4 py-3 text-center">
|
||||||
|
<div className="readout text-ink2">{tech.name}</div>
|
||||||
|
<div className="text-xs text-muted mt-1">{tech.desc}</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* Comparison Table */}
|
||||||
|
<section id="comparison" className="py-20 px-6 border-t border-rule">
|
||||||
|
<div className="max-w-4xl mx-auto">
|
||||||
|
<SectionHeader eyebrow="08 · Comparison" title="Free Clip Generator vs Paid Alternatives">
|
||||||
|
Clipwright is free and open source — you self-host it. Opus Clip runs $15-228/month, Kapwing $24-79/month.
|
||||||
|
</SectionHeader>
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<table className="w-full">
|
||||||
|
<thead>
|
||||||
|
<tr className="border-b border-rule2">
|
||||||
|
<th className="py-3 px-4 text-left text-sm text-muted font-medium">Feature</th>
|
||||||
|
<th className="py-3 px-4 text-center text-sm font-medium">
|
||||||
|
<span className="text-brass">Clipwright</span>
|
||||||
|
</th>
|
||||||
|
<th className="py-3 px-4 text-center text-sm text-muted font-medium">Opus Clip</th>
|
||||||
|
<th className="py-3 px-4 text-center text-sm text-muted font-medium">Kapwing</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<ComparisonRow feature="Price" clipwright={<span className="text-ok font-medium">$0 Free</span>} opusclip={xIcon} kapwing={xIcon} />
|
||||||
|
<ComparisonRow feature="AI Viral Moment Detection" clipwright={checkIcon} opusclip={checkMuted} kapwing={checkMuted} />
|
||||||
|
<ComparisonRow feature="Smart Vertical Cropping" clipwright={checkIcon} opusclip={checkMuted} kapwing={checkMuted} />
|
||||||
|
<ComparisonRow feature="Auto Subtitles" clipwright={checkIcon} opusclip={checkMuted} kapwing={checkMuted} />
|
||||||
|
<ComparisonRow feature="AI Voice Dubbing (30+ langs)" clipwright={checkIcon} opusclip={<span className="text-muted text-sm">Limited</span>} kapwing={<span className="text-muted text-sm">No</span>} />
|
||||||
|
<ComparisonRow feature="AI Video Effects" clipwright={checkIcon} opusclip={<span className="text-muted text-sm">No</span>} kapwing={checkMuted} />
|
||||||
|
<ComparisonRow feature="Hook Text Overlays" clipwright={checkIcon} opusclip={checkMuted} kapwing={checkMuted} />
|
||||||
|
<ComparisonRow feature="Self-Hosted / Privacy" clipwright={checkIcon} opusclip={<span className="text-muted text-sm">Cloud only</span>} kapwing={<span className="text-muted text-sm">Cloud only</span>} />
|
||||||
|
<ComparisonRow feature="No Watermark" clipwright={checkIcon} opusclip={<span className="text-muted text-sm">Free tier only</span>} kapwing={<span className="text-muted text-sm">Paid</span>} />
|
||||||
|
<ComparisonRow feature="Open Source" clipwright={checkIcon} opusclip={<span className="text-muted text-sm">No</span>} kapwing={<span className="text-muted text-sm">No</span>} />
|
||||||
|
<ComparisonRow feature="AI YouTube Thumbnail Generator" clipwright={checkIcon} opusclip={<span className="text-muted text-sm">No</span>} kapwing={<span className="text-muted text-sm">Paid</span>} />
|
||||||
|
<ComparisonRow feature="AI Title & Description Generator" clipwright={checkIcon} opusclip={<span className="text-muted text-sm">Limited</span>} kapwing={<span className="text-muted text-sm">Paid</span>} />
|
||||||
|
<ComparisonRow feature="Postiz Social Publishing" clipwright={checkIcon} opusclip={<span className="text-muted text-sm">Built-in</span>} kapwing={<span className="text-muted text-sm">Limited</span>} />
|
||||||
|
<ComparisonRow feature="Usage Limits" clipwright={<span className="text-ok text-sm">Unlimited</span>} opusclip={<span className="text-muted text-sm">Per plan</span>} kapwing={<span className="text-muted text-sm">Per plan</span>} />
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* Use Cases */}
|
||||||
|
<section className="py-20 px-6 border-t border-rule">
|
||||||
|
<div className="max-w-5xl mx-auto">
|
||||||
|
<SectionHeader eyebrow="09 · Use Cases" title="Who Uses Clipwright?">
|
||||||
|
Creators, marketers, and agencies scaling short-form video production.
|
||||||
|
</SectionHeader>
|
||||||
|
<div className="grid md:grid-cols-3 gap-5">
|
||||||
|
{[
|
||||||
|
{
|
||||||
|
title: "Content Creators",
|
||||||
|
description: "Repurpose long-form videos into TikTok and Reels clips automatically.",
|
||||||
|
icon: Youtube
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "Social Media Managers",
|
||||||
|
description: "Batch-process videos and publish for multiple clients from one dashboard.",
|
||||||
|
icon: Instagram
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "Podcasters & Educators",
|
||||||
|
description: "Extract the most engaging moments from episodes and lessons.",
|
||||||
|
icon: FileVideo
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "Businesses & Brands",
|
||||||
|
description: "Turn every long video into a week of posts and schedule them through self-hosted Postiz.",
|
||||||
|
icon: Sparkles
|
||||||
|
}
|
||||||
|
].map((useCase, i) => (
|
||||||
|
<div key={i} className="card p-6">
|
||||||
|
<useCase.icon size={18} className="text-brass mb-4" />
|
||||||
|
<h3 className="font-display text-xl lowercase text-ink mb-2">{useCase.title}</h3>
|
||||||
|
<p className="text-muted text-sm leading-relaxed">{useCase.description}</p>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* FAQ Section */}
|
||||||
|
<section id="faq" className="py-20 px-6 border-t border-rule">
|
||||||
|
<div className="max-w-3xl mx-auto">
|
||||||
|
<SectionHeader eyebrow="10 · FAQ" title="Frequently Asked Questions">
|
||||||
|
Everything you need to know about Clipwright, from setup to features.
|
||||||
|
</SectionHeader>
|
||||||
|
<div className="divide-y divide-rule border-y border-rule">
|
||||||
|
{faqs.map((faq, i) => (
|
||||||
|
<FAQItem
|
||||||
|
key={i}
|
||||||
|
question={faq.question}
|
||||||
|
answer={faq.answer}
|
||||||
|
isOpen={openFaq === i}
|
||||||
|
onClick={() => setOpenFaq(openFaq === i ? null : i)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* CTA Section — final statement */}
|
||||||
|
<section className="py-24 px-6 border-t border-rule">
|
||||||
|
<div className="max-w-3xl mx-auto text-center">
|
||||||
|
<h2 className="font-display text-4xl md:text-5xl lowercase text-ink tracking-tight mb-5">start creating viral videos today.</h2>
|
||||||
|
<p className="text-muted mb-10 max-w-xl mx-auto leading-relaxed lowercase">free and open source under mit · no watermark · no usage cap · self-host with docker.</p>
|
||||||
|
<div className="flex flex-wrap items-center justify-center gap-4">
|
||||||
|
<button onClick={onLaunchApp} className="btn-primary whitespace-nowrap">
|
||||||
|
launch clipwright
|
||||||
|
<ArrowRight size={16} />
|
||||||
|
</button>
|
||||||
|
<a
|
||||||
|
href="https://git.pbento.pt/pedro-bento/clipwright"
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
className="btn-ghost whitespace-nowrap"
|
||||||
|
>
|
||||||
|
<Github size={16} />
|
||||||
|
Star on GitHub
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* Footer — Ft5 Statement */}
|
||||||
|
<footer className="border-t border-rule py-16 px-6">
|
||||||
|
<div className="max-w-6xl mx-auto">
|
||||||
|
<p className="font-display text-3xl md:text-5xl lowercase text-ink tracking-tight mb-10">clip it before it scrolls past.</p>
|
||||||
|
<nav aria-label="Guides and comparisons" className="border-t border-rule pt-6 mb-6 flex flex-wrap items-center gap-x-6 gap-y-2 text-sm lowercase text-muted">
|
||||||
|
<a href="/free-ai-clip-generator" className="hover:text-ink transition-colors">free ai clip generator</a>
|
||||||
|
<a href="/tools" className="hover:text-ink transition-colors">free tools</a>
|
||||||
|
<a href="/youtube-transcript-generator" className="hover:text-ink transition-colors">youtube transcript generator</a>
|
||||||
|
<a href="/youtube-tag-generator" className="hover:text-ink transition-colors">youtube tag generator</a>
|
||||||
|
<a href="/video-aspect-ratio-converter" className="hover:text-ink transition-colors">video to 9:16 converter</a>
|
||||||
|
<a href="/free-ai-clip-generator-no-watermark" className="hover:text-ink transition-colors">no watermark</a>
|
||||||
|
<a href="/open-source-video-clipper" className="hover:text-ink transition-colors">open source video clipper</a>
|
||||||
|
<a href="/podcast-to-shorts" className="hover:text-ink transition-colors">podcast to shorts</a>
|
||||||
|
<a href="/youtube-to-shorts-converter" className="hover:text-ink transition-colors">youtube to shorts</a>
|
||||||
|
<a href="/how-clipwright-works" className="hover:text-ink transition-colors">how it works</a>
|
||||||
|
<a href="/alternatives" className="hover:text-ink transition-colors">alternatives</a>
|
||||||
|
<a href="/alternativas" className="hover:text-ink transition-colors">alternativas</a>
|
||||||
|
<a href="/alternatives/opus-clip" className="hover:text-ink transition-colors">vs opus clip</a>
|
||||||
|
<a href="/opus-clip-pricing" className="hover:text-ink transition-colors">opus clip pricing</a>
|
||||||
|
<a href="/opus-clip-free-alternative" className="hover:text-ink transition-colors">free opus clip alternative</a>
|
||||||
|
<a href="/opus-ai" className="hover:text-ink transition-colors">opus ai</a>
|
||||||
|
<a href="/opus-pro" className="hover:text-ink transition-colors">opus pro</a>
|
||||||
|
<a href="/vizard-ai-video-to-text" className="hover:text-ink transition-colors">vizard ai video to text</a>
|
||||||
|
<a href="/submagic-reviews" className="hover:text-ink transition-colors">submagic review</a>
|
||||||
|
<a href="/automate-shorts-api" className="hover:text-ink transition-colors">automate shorts</a>
|
||||||
|
<a href="/n8n-youtube-shorts-automation" className="hover:text-ink transition-colors">n8n workflow</a>
|
||||||
|
</nav>
|
||||||
|
<div className="border-t border-rule pt-6 flex flex-col md:flex-row md:items-center justify-between gap-4">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<img src="/logo-clipwright.png" alt="Clipwright" className="w-6 h-6" />
|
||||||
|
<span className="text-sm text-muted">Clipwright — Free Open Source Clip Generator & Postiz Publishing</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap items-center gap-x-6 gap-y-2 text-sm lowercase text-muted">
|
||||||
|
<a href="https://git.pbento.pt/pedro-bento/clipwright" target="_blank" rel="noopener noreferrer" className="hover:text-ink transition-colors">GitHub</a>
|
||||||
|
<a href="#features" className="hover:text-ink transition-colors">Features</a>
|
||||||
|
<a href="#faq" className="hover:text-ink transition-colors">FAQ</a>
|
||||||
|
<a href="/terms" className="hover:text-ink transition-colors whitespace-nowrap">Terms</a>
|
||||||
|
<a href="/privacy" className="hover:text-ink transition-colors whitespace-nowrap">Privacy</a>
|
||||||
|
<a href="/legal-notice" className="hover:text-ink transition-colors whitespace-nowrap">Legal Notice</a>
|
||||||
|
<a href="/refunds" className="hover:text-ink transition-colors whitespace-nowrap">Refunds</a>
|
||||||
|
<a href="/report-content" className="hover:text-ink transition-colors whitespace-nowrap">Report Content</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</footer>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
1
dashboard/src/assets/react.svg
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||||
|
After Width: | Height: | Size: 4 KiB |
|
|
@ -1,331 +0,0 @@
|
||||||
import React, { useState, useEffect } from 'react';
|
|
||||||
import { Copy, Check, CheckCircle2, AlertCircle, Loader2, Link2, Youtube, MessageSquare } from 'lucide-react';
|
|
||||||
import Modal from './ui/Modal';
|
|
||||||
import { apiFetch } from '../lib/api';
|
|
||||||
|
|
||||||
// Shorts -> long-form bridge (PLAN #6). The related-video link and comment
|
|
||||||
// pinning are Studio-UI only, so this panel always carries the manual steps:
|
|
||||||
// it never pretends the server can set them.
|
|
||||||
//
|
|
||||||
// Copy it? Use the copy buttons. Post the first comment automatically? Only
|
|
||||||
// when you click it, and only on a server with the YouTube Data API wired up.
|
|
||||||
|
|
||||||
// Accept a full YouTube URL or a bare id and return just the id. The published
|
|
||||||
// Short's id is what the comment endpoint needs; people usually have the URL.
|
|
||||||
function videoIdFrom(raw) {
|
|
||||||
const value = String(raw || '').trim();
|
|
||||||
if (!value) return '';
|
|
||||||
const urlMatch = value.match(/(?:v=|\/shorts\/|youtu\.be\/|\/embed\/)([A-Za-z0-9_-]{6,})/);
|
|
||||||
if (urlMatch) return urlMatch[1];
|
|
||||||
const bare = value.match(/^([A-Za-z0-9_-]{6,})$/);
|
|
||||||
return bare ? bare[1] : value;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function BridgeModal({ isOpen, onClose, jobId, clipIndex }) {
|
|
||||||
const [data, setData] = useState(null);
|
|
||||||
const [loading, setLoading] = useState(false);
|
|
||||||
const [error, setError] = useState(null);
|
|
||||||
const [copied, setCopied] = useState(null);
|
|
||||||
|
|
||||||
// Checked-off Studio steps, remembered per clip so closing the sheet while
|
|
||||||
// working through the manual steps doesn't lose your place.
|
|
||||||
const storageKey = `cw_bridge_check_${jobId}_${clipIndex}`;
|
|
||||||
const [checkedSteps, setCheckedSteps] = useState({});
|
|
||||||
|
|
||||||
const [videoId, setVideoId] = useState('');
|
|
||||||
const [posting, setPosting] = useState(false);
|
|
||||||
const [postStatus, setPostStatus] = useState(null);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!isOpen) return undefined;
|
|
||||||
let cancelled = false;
|
|
||||||
|
|
||||||
setLoading(true);
|
|
||||||
setError(null);
|
|
||||||
setData(null);
|
|
||||||
setPostStatus(null);
|
|
||||||
setVideoId('');
|
|
||||||
try {
|
|
||||||
setCheckedSteps(JSON.parse(localStorage.getItem(storageKey)) || {});
|
|
||||||
} catch {
|
|
||||||
setCheckedSteps({});
|
|
||||||
}
|
|
||||||
|
|
||||||
apiFetch(`/api/clip/${jobId}/${clipIndex}/bridge`)
|
|
||||||
.then(async (res) => {
|
|
||||||
if (!res.ok) {
|
|
||||||
let detail = '';
|
|
||||||
const text = await res.text().catch(() => '');
|
|
||||||
try {
|
|
||||||
const j = JSON.parse(text);
|
|
||||||
if (typeof j.detail === 'string') detail = j.detail;
|
|
||||||
} catch { /* keep the raw body */ }
|
|
||||||
throw new Error(detail || `Could not load the bridge (${res.status}).`);
|
|
||||||
}
|
|
||||||
return res.json();
|
|
||||||
})
|
|
||||||
.then((payload) => { if (!cancelled) setData(payload); })
|
|
||||||
.catch((e) => { if (!cancelled) setError(e.message || 'Could not load the bridge.'); })
|
|
||||||
.finally(() => { if (!cancelled) setLoading(false); });
|
|
||||||
|
|
||||||
return () => { cancelled = true; };
|
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
||||||
}, [isOpen, jobId, clipIndex]);
|
|
||||||
|
|
||||||
const handleCopy = async (field, text) => {
|
|
||||||
try {
|
|
||||||
await navigator.clipboard.writeText(text || '');
|
|
||||||
setCopied(field);
|
|
||||||
setTimeout(() => setCopied(null), 2000);
|
|
||||||
} catch {
|
|
||||||
// clipboard unavailable — silent
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const toggleStep = (i) => {
|
|
||||||
setCheckedSteps((prev) => {
|
|
||||||
const next = { ...prev, [i]: !prev[i] };
|
|
||||||
try { localStorage.setItem(storageKey, JSON.stringify(next)); } catch { /* storage unavailable */ }
|
|
||||||
return next;
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const handlePostComment = async () => {
|
|
||||||
const vid = videoIdFrom(videoId);
|
|
||||||
if (!vid) return;
|
|
||||||
setPosting(true);
|
|
||||||
setPostStatus(null);
|
|
||||||
try {
|
|
||||||
const res = await apiFetch(`/api/clip/${jobId}/${clipIndex}/bridge/comment`, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({ video_id: vid, text: data?.first_comment || undefined }),
|
|
||||||
});
|
|
||||||
if (!res.ok) {
|
|
||||||
let detail = '';
|
|
||||||
const text = await res.text().catch(() => '');
|
|
||||||
try {
|
|
||||||
const j = JSON.parse(text);
|
|
||||||
if (typeof j.detail === 'string') detail = j.detail;
|
|
||||||
} catch { /* keep the raw body */ }
|
|
||||||
// A 400 here almost always means the YouTube integration is not
|
|
||||||
// configured; say that plainly and point at the manual route.
|
|
||||||
const fallback = res.status === 400
|
|
||||||
? "This server can't post comments yet — the YouTube Data API isn't set up. Copy the comment above and post it in Studio instead."
|
|
||||||
: `Could not post the comment (${res.status}).`;
|
|
||||||
setPostStatus({ ok: false, msg: detail || fallback });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
await res.json().catch(() => ({}));
|
|
||||||
setPostStatus({ ok: true, msg: 'Comment posted. Open YouTube Studio and pin it — pinning stays manual.' });
|
|
||||||
} catch (e) {
|
|
||||||
setPostStatus({ ok: false, msg: e.message || 'Could not post the comment.' });
|
|
||||||
} finally {
|
|
||||||
setPosting(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// The endpoint reports whether comment posting is available on this server.
|
|
||||||
// An older/absent field is treated as "try it" — a 400 is handled above.
|
|
||||||
const configured = data ? data.comment_api_configured !== false : true;
|
|
||||||
const canPostComment = configured && !!videoId.trim() && !!data?.first_comment;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Modal
|
|
||||||
isOpen={isOpen}
|
|
||||||
onClose={onClose}
|
|
||||||
eyebrow="YOUTUBE · BRIDGE"
|
|
||||||
title="shorts → long-form"
|
|
||||||
size="lg"
|
|
||||||
>
|
|
||||||
{loading && (
|
|
||||||
<div className="flex items-center justify-center gap-2 py-10 text-sm text-muted lowercase">
|
|
||||||
<Loader2 size={16} className="animate-spin text-brass" /> loading bridge…
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{!loading && error && (
|
|
||||||
<div className="px-3 py-2 rounded-input text-xs text-danger bg-[color-mix(in_oklab,var(--color-danger)_10%,transparent)] flex items-start gap-2">
|
|
||||||
<AlertCircle size={14} className="mt-0.5 shrink-0" />
|
|
||||||
<span className="break-words">{error}</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{!loading && !error && data && (
|
|
||||||
<div>
|
|
||||||
<p className="text-xs text-muted leading-snug mb-5">
|
|
||||||
Funnel viewers of this Short to a long-form video. The related-video link and the comment pin live only in YouTube Studio, so those steps stay manual.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
{/* Related-video target */}
|
|
||||||
<section className="mb-5">
|
|
||||||
<label className="eyebrow block mb-1.5">RELATED VIDEO TARGET</label>
|
|
||||||
{data.related_video_url ? (
|
|
||||||
<div className="flex items-center gap-2 bg-paper rounded-input border border-rule px-3 py-2 min-w-0">
|
|
||||||
<Youtube size={14} className="text-muted shrink-0" />
|
|
||||||
<a
|
|
||||||
href={data.related_video_url}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
className="text-xs text-ink2 truncate flex-1 min-w-0 hover:text-brass transition-colors"
|
|
||||||
>
|
|
||||||
{data.related_video_url}
|
|
||||||
</a>
|
|
||||||
<button
|
|
||||||
onClick={() => handleCopy('target', data.related_video_url)}
|
|
||||||
aria-label="copy related video url"
|
|
||||||
className="p-1 rounded-full text-muted hover:text-brass transition-colors shrink-0"
|
|
||||||
>
|
|
||||||
{copied === 'target' ? <Check size={14} className="text-ok" /> : <Copy size={14} />}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="px-3 py-2 rounded-input text-xs text-warn bg-[color-mix(in_oklab,var(--color-warn)_10%,transparent)] flex items-start gap-2">
|
|
||||||
<AlertCircle size={14} className="mt-0.5 shrink-0" />
|
|
||||||
<span>
|
|
||||||
No related video set for this clip yet. Paste the long-form URL into YouTube Studio's
|
|
||||||
{' '}<b className="font-medium">Related video</b> field when you set it up — the checklist below has the steps.
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</section>
|
|
||||||
|
|
||||||
{/* Manual Studio checklist */}
|
|
||||||
<section className="mb-5">
|
|
||||||
<div className="flex items-center justify-between gap-2 mb-2">
|
|
||||||
<label className="eyebrow">STUDIO CHECKLIST</label>
|
|
||||||
<span className="readout">manual · no api</span>
|
|
||||||
</div>
|
|
||||||
{Array.isArray(data.checklist) && data.checklist.length > 0 ? (
|
|
||||||
<ol className="space-y-1.5">
|
|
||||||
{data.checklist.map((step, i) => {
|
|
||||||
const done = !!checkedSteps[i];
|
|
||||||
return (
|
|
||||||
<li key={i}>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => toggleStep(i)}
|
|
||||||
aria-pressed={done}
|
|
||||||
className={`w-full text-left flex items-start gap-2.5 px-3 py-2 rounded-input border transition-colors ${done ? 'border-rule bg-paper opacity-70' : 'border-rule hover:bg-paper3'}`}
|
|
||||||
>
|
|
||||||
{done
|
|
||||||
? <CheckCircle2 size={15} className="text-ok mt-0.5 shrink-0" />
|
|
||||||
: <span className="mt-0.5 w-[15px] h-[15px] rounded-full border border-rule2 shrink-0" aria-hidden="true" />}
|
|
||||||
<span className={`text-xs leading-snug ${done ? 'text-muted' : 'text-ink2'}`}>{step}</span>
|
|
||||||
</button>
|
|
||||||
</li>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</ol>
|
|
||||||
) : (
|
|
||||||
<p className="text-xs text-muted lowercase">no checklist saved for this clip.</p>
|
|
||||||
)}
|
|
||||||
</section>
|
|
||||||
|
|
||||||
{/* Copy-paste copy */}
|
|
||||||
<section className="mb-5">
|
|
||||||
<div className="flex items-center justify-between gap-2 mb-1.5">
|
|
||||||
<label className="eyebrow">DESCRIPTION BRIDGE</label>
|
|
||||||
<button
|
|
||||||
onClick={() => handleCopy('desc', data.description_bridge)}
|
|
||||||
aria-label="copy description bridge"
|
|
||||||
className="p-1 rounded-full text-muted hover:text-brass transition-colors shrink-0"
|
|
||||||
>
|
|
||||||
{copied === 'desc' ? <Check size={14} className="text-ok" /> : <Copy size={14} />}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
{data.description_bridge ? (
|
|
||||||
<p className="text-xs text-ink2 select-all break-words whitespace-pre-wrap bg-paper rounded-input p-3 border border-rule max-h-40 overflow-y-auto custom-scrollbar">
|
|
||||||
{data.description_bridge}
|
|
||||||
</p>
|
|
||||||
) : (
|
|
||||||
<p className="text-xs text-muted lowercase bg-paper rounded-input p-3 border border-dashed border-rule">
|
|
||||||
no description copy generated for this clip.
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section className="mb-5">
|
|
||||||
<div className="flex items-center justify-between gap-2 mb-1.5">
|
|
||||||
<label className="eyebrow">FIRST COMMENT</label>
|
|
||||||
<button
|
|
||||||
onClick={() => handleCopy('comment', data.first_comment)}
|
|
||||||
aria-label="copy first comment"
|
|
||||||
className="p-1 rounded-full text-muted hover:text-brass transition-colors shrink-0"
|
|
||||||
>
|
|
||||||
{copied === 'comment' ? <Check size={14} className="text-ok" /> : <Copy size={14} />}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
{data.first_comment ? (
|
|
||||||
<p className="text-xs text-ink2 select-all break-words whitespace-pre-wrap bg-paper rounded-input p-3 border border-rule">
|
|
||||||
{data.first_comment}
|
|
||||||
</p>
|
|
||||||
) : (
|
|
||||||
<p className="text-xs text-muted lowercase bg-paper rounded-input p-3 border border-dashed border-rule">
|
|
||||||
no first comment generated for this clip.
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</section>
|
|
||||||
|
|
||||||
{/* Optional opt-in comment posting */}
|
|
||||||
<section className="border-t border-rule pt-4">
|
|
||||||
<div className="flex items-center gap-2 mb-1.5">
|
|
||||||
<label className="eyebrow">POST FIRST COMMENT</label>
|
|
||||||
<span className="badge-ok">opt-in</span>
|
|
||||||
</div>
|
|
||||||
<p className="text-xs text-muted leading-snug mb-3">
|
|
||||||
Optional. clipwright never posts on its own — this runs only when you click the button. Pinning the comment still has to be done by hand in Studio.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
{!configured ? (
|
|
||||||
<div className="px-3 py-2 rounded-input text-xs text-warn bg-[color-mix(in_oklab,var(--color-warn)_10%,transparent)] flex items-start gap-2">
|
|
||||||
<AlertCircle size={14} className="mt-0.5 shrink-0" />
|
|
||||||
<span>
|
|
||||||
This server has no YouTube Data API credentials, so it can't post for you. Copy the comment above and post it in Studio instead.
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="space-y-2">
|
|
||||||
<div className="flex flex-col sm:flex-row gap-2">
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
value={videoId}
|
|
||||||
onChange={(e) => setVideoId(e.target.value)}
|
|
||||||
className="input-field sm:flex-1"
|
|
||||||
placeholder="published Short video id or URL"
|
|
||||||
aria-label="published Short video id or URL"
|
|
||||||
/>
|
|
||||||
<button
|
|
||||||
onClick={handlePostComment}
|
|
||||||
disabled={posting || !canPostComment}
|
|
||||||
className="btn-primary shrink-0"
|
|
||||||
title={!data.first_comment ? 'No comment text to post' : (videoId.trim() ? undefined : 'Enter the published Short id first')}
|
|
||||||
>
|
|
||||||
{posting
|
|
||||||
? <><Loader2 size={15} className="animate-spin" /> posting…</>
|
|
||||||
: <><MessageSquare size={15} /> post comment</>}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
{postStatus && (
|
|
||||||
<div className={`px-3 py-2 rounded-input text-xs flex items-start gap-2 ${postStatus.ok
|
|
||||||
? 'text-ok bg-[color-mix(in_oklab,var(--color-ok)_10%,transparent)]'
|
|
||||||
: 'text-danger bg-[color-mix(in_oklab,var(--color-danger)_10%,transparent)]'}`}
|
|
||||||
>
|
|
||||||
{postStatus.ok
|
|
||||||
? <Check size={14} className="mt-0.5 shrink-0" />
|
|
||||||
: <AlertCircle size={14} className="mt-0.5 shrink-0" />}
|
|
||||||
<span className="break-words">{postStatus.msg}</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<p className="readout mt-3 flex items-center gap-1.5">
|
|
||||||
<Link2 size={12} className="shrink-0" /> related-video link + pin: Studio only
|
|
||||||
</p>
|
|
||||||
</section>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</Modal>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
@ -8,10 +8,12 @@
|
||||||
// "Accept all" are the same component with the same size, weight, colour
|
// "Accept all" are the same component with the same size, weight, colour
|
||||||
// and position; there is no pre-ticked box and no dark pattern.
|
// and position; there is no pre-ticked box and no dark pattern.
|
||||||
//
|
//
|
||||||
// It renders nothing once a decision exists.
|
// It renders nothing once a decision exists — the footer link
|
||||||
import { useState } from 'react';
|
// (openConsentManager) is how anyone changes their mind.
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
import {
|
import {
|
||||||
getConsent, hasDecided, acceptAll, rejectAll, setConsent,
|
getConsent, hasDecided, acceptAll, rejectAll, setConsent,
|
||||||
|
onConsentOpenRequest,
|
||||||
} from '../lib/consent';
|
} from '../lib/consent';
|
||||||
|
|
||||||
const CATEGORY_COPY = [
|
const CATEGORY_COPY = [
|
||||||
|
|
@ -39,6 +41,12 @@ export default function CookieBanner() {
|
||||||
const [details, setDetails] = useState(false);
|
const [details, setDetails] = useState(false);
|
||||||
const [draft, setDraft] = useState(() => getConsent());
|
const [draft, setDraft] = useState(() => getConsent());
|
||||||
|
|
||||||
|
useEffect(() => onConsentOpenRequest(() => {
|
||||||
|
setDraft(getConsent());
|
||||||
|
setDetails(true);
|
||||||
|
setOpen(true);
|
||||||
|
}), []);
|
||||||
|
|
||||||
if (!open) return null;
|
if (!open) return null;
|
||||||
|
|
||||||
const close = () => { setOpen(false); setDetails(false); };
|
const close = () => { setOpen(false); setDetails(false); };
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ const ENTRANCE_OPTIONS = [
|
||||||
{ value: 'none', label: 'None' },
|
{ value: 'none', label: 'None' },
|
||||||
];
|
];
|
||||||
|
|
||||||
// Must mirror clipwright/media/hooks.py HOOK_STYLES.
|
// Must mirror hooks.py HOOK_STYLES.
|
||||||
const HOOK_STYLES = [
|
const HOOK_STYLES = [
|
||||||
{ value: 'pill', label: 'Pills', box: 'rgba(255,255,255,0.98)', text: '#000', sans: true },
|
{ value: 'pill', label: 'Pills', box: 'rgba(255,255,255,0.98)', text: '#000', sans: true },
|
||||||
{ value: 'classic', label: 'Classic', box: 'rgba(255,255,255,0.94)', text: '#000' },
|
{ value: 'classic', label: 'Classic', box: 'rgba(255,255,255,0.94)', text: '#000' },
|
||||||
|
|
@ -22,7 +22,7 @@ const HOOK_STYLES = [
|
||||||
{ value: 'outline_yellow', label: 'Outline+', box: 'transparent', text: '#FFD600', outline: true },
|
{ value: 'outline_yellow', label: 'Outline+', box: 'transparent', text: '#FFD600', outline: true },
|
||||||
];
|
];
|
||||||
|
|
||||||
// Must mirror clipwright/media/hooks.py HOOK_FONTS (all bundled: /fonts/*.ttf).
|
// Must mirror hooks.py HOOK_FONTS (all bundled: /fonts/*.ttf).
|
||||||
const FONT_OPTIONS = [
|
const FONT_OPTIONS = [
|
||||||
{ value: 'montserrat', label: 'Montserrat' },
|
{ value: 'montserrat', label: 'Montserrat' },
|
||||||
{ value: 'anton', label: 'Anton' },
|
{ value: 'anton', label: 'Anton' },
|
||||||
|
|
@ -33,7 +33,7 @@ const FONT_CSS = {
|
||||||
anton: { fontFamily: "'Anton-Regular', Impact, sans-serif", fontWeight: 400 },
|
anton: { fontFamily: "'Anton-Regular', Impact, sans-serif", fontWeight: 400 },
|
||||||
serif: { fontFamily: "'Noto Serif', Georgia, serif", fontWeight: 700 },
|
serif: { fontFamily: "'Noto Serif', Georgia, serif", fontWeight: 700 },
|
||||||
};
|
};
|
||||||
// The style's own typeface when none is picked (what clipwright/media/hooks.py renders).
|
// The style's own typeface when none is picked (what hooks.py renders).
|
||||||
const styleFont = (st) => (st === 'pill' ? 'montserrat' : 'serif');
|
const styleFont = (st) => (st === 'pill' ? 'montserrat' : 'serif');
|
||||||
|
|
||||||
const POSITION_OPTIONS = [
|
const POSITION_OPTIONS = [
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import React, { useState, useEffect, useRef } from 'react';
|
import React, { useState, useEffect, useRef } from 'react';
|
||||||
import { Link2, Upload, FileVideo, X, Info, Loader2, ChevronDown, Paperclip, FileArchive } from 'lucide-react';
|
import { Link2, Upload, FileVideo, X, Info, Loader2, ChevronDown } from 'lucide-react';
|
||||||
import { track } from '../lib/analytics';
|
import { track } from '../lib/analytics';
|
||||||
import { getApiUrl } from '../config';
|
import { getApiUrl } from '../config';
|
||||||
|
|
||||||
|
|
@ -61,18 +61,6 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
||||||
const [layout, setLayout] = useState(() => {
|
const [layout, setLayout] = useState(() => {
|
||||||
try { return localStorage.getItem('cw_layout') || 'auto'; } catch { return 'auto'; }
|
try { return localStorage.getItem('cw_layout') || 'auto'; } catch { return 'auto'; }
|
||||||
});
|
});
|
||||||
// Channel profile (channels/<slug>.json on the server): tunes how the AI
|
|
||||||
// writes titles, hooks and the description, and how it art-directs the
|
|
||||||
// thumbnail. Per job and off by default, so nothing changes for anyone who
|
|
||||||
// does not use profiles. Fetched from GET /api/channels; when that list is
|
|
||||||
// empty or unreachable the selector simply does not render.
|
|
||||||
const [channels, setChannels] = useState([]);
|
|
||||||
const [channel, setChannel] = useState('none');
|
|
||||||
// Cadence handoff bundle (optional): cadence's ZIP with the manifest and
|
|
||||||
// transcript for the master. Attached to a local-file job so the pipeline
|
|
||||||
// skips transcription. It is not sent with the video form — the parent
|
|
||||||
// uploads it to its own slot on submit and passes back handoff_id.
|
|
||||||
const [handoffFile, setHandoffFile] = useState(null);
|
|
||||||
const infoRef = useRef(null);
|
const infoRef = useRef(null);
|
||||||
|
|
||||||
// Close the compatibility popover on any outside click.
|
// Close the compatibility popover on any outside click.
|
||||||
|
|
@ -111,22 +99,6 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// Channel profiles available on this install. A missing route, an empty
|
|
||||||
// directory or a network error all leave the list empty, which keeps the
|
|
||||||
// selector hidden — profiles are opt-in and never block a job.
|
|
||||||
useEffect(() => {
|
|
||||||
let cancelled = false;
|
|
||||||
fetch(getApiUrl('/api/channels'))
|
|
||||||
.then((r) => (r.ok ? r.json() : null))
|
|
||||||
.then((data) => {
|
|
||||||
if (cancelled || !data) return;
|
|
||||||
const list = Array.isArray(data.channels) ? data.channels : [];
|
|
||||||
setChannels(list.filter((c) => c && c.slug));
|
|
||||||
})
|
|
||||||
.catch(() => {});
|
|
||||||
return () => { cancelled = true; };
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
// A link pasted in the landing hero: preload it here so the user picks up
|
// A link pasted in the landing hero: preload it here so the user picks up
|
||||||
// where they left off. Not auto-submitted — the rights attestation below
|
// where they left off. Not auto-submitted — the rights attestation below
|
||||||
// has to be ticked by the user.
|
// has to be ticked by the user.
|
||||||
|
|
@ -152,9 +124,6 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
||||||
autoHook,
|
autoHook,
|
||||||
autoHookStyle,
|
autoHookStyle,
|
||||||
layout,
|
layout,
|
||||||
// 'none' = no profile; only a real slug travels, so the default
|
|
||||||
// request stays byte-identical to the pre-feature one.
|
|
||||||
channel: channel === 'none' ? null : channel,
|
|
||||||
};
|
};
|
||||||
try {
|
try {
|
||||||
localStorage.setItem('cw_auto_hook', autoHook ? '1' : '0');
|
localStorage.setItem('cw_auto_hook', autoHook ? '1' : '0');
|
||||||
|
|
@ -164,9 +133,7 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
||||||
if (mode === 'url' && url) {
|
if (mode === 'url' && url) {
|
||||||
onProcess({ type: 'url', payload: url, acknowledged: true, outputFormat, ...advanced });
|
onProcess({ type: 'url', payload: url, acknowledged: true, outputFormat, ...advanced });
|
||||||
} else if (mode === 'file' && file && !fileTooShort) {
|
} else if (mode === 'file' && file && !fileTooShort) {
|
||||||
// The handoff bundle only travels with a local master: it is the
|
onProcess({ type: 'file', payload: file, acknowledged: true, outputFormat, ...advanced });
|
||||||
// edition cadence cut from that same file.
|
|
||||||
onProcess({ type: 'file', payload: file, acknowledged: true, outputFormat, handoffFile: handoffFile || null, ...advanced });
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -288,49 +255,6 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Cadence handoff bundle — local file jobs only. Optional:
|
|
||||||
without it nothing changes. With it, the parent uploads the
|
|
||||||
ZIP to its own slot and the pipeline skips transcription. */}
|
|
||||||
{mode === 'file' && (
|
|
||||||
<div className="mt-4" data-tutorial="handoff-bundle">
|
|
||||||
{handoffFile ? (
|
|
||||||
<div className="flex items-center gap-3 rounded-input border border-rule bg-paper3 px-3 py-2.5 min-w-0">
|
|
||||||
<FileArchive size={16} className="shrink-0 text-brass" />
|
|
||||||
<span className="min-w-0 flex-1">
|
|
||||||
<span className="block truncate text-sm text-ink2">{handoffFile.name}</span>
|
|
||||||
<span className="block text-[11px] leading-relaxed text-muted">
|
|
||||||
skips transcription · must match the master's edit
|
|
||||||
</span>
|
|
||||||
</span>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setHandoffFile(null)}
|
|
||||||
aria-label="remove handoff bundle"
|
|
||||||
className="p-1 text-muted hover:text-ink hover:bg-paper2 rounded-full transition-colors shrink-0"
|
|
||||||
>
|
|
||||||
<X size={16} />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<label className="flex items-start gap-2.5 cursor-pointer select-none text-xs text-muted hover:text-ink2 transition-colors">
|
|
||||||
<input
|
|
||||||
type="file"
|
|
||||||
accept=".zip,application/zip"
|
|
||||||
onChange={(e) => setHandoffFile(e.target.files?.[0] || null)}
|
|
||||||
className="hidden"
|
|
||||||
/>
|
|
||||||
<Paperclip size={14} className="shrink-0 mt-0.5" />
|
|
||||||
<span className="min-w-0">
|
|
||||||
<span className="text-ink2">cadence handoff bundle</span> (.zip, optional)
|
|
||||||
<span className="block text-[11px] leading-relaxed mt-0.5">
|
|
||||||
Skips transcription. The bundle must match the uploaded master's edit.
|
|
||||||
</span>
|
|
||||||
</span>
|
|
||||||
</label>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Output format selector */}
|
{/* Output format selector */}
|
||||||
<div className="mt-5" data-tutorial="output-format">
|
<div className="mt-5" data-tutorial="output-format">
|
||||||
<p className="eyebrow mb-2">Output format</p>
|
<p className="eyebrow mb-2">Output format</p>
|
||||||
|
|
@ -367,32 +291,6 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Channel profile — only rendered when the install has profiles,
|
|
||||||
so an empty list or a failed fetch leaves no trace. Tunes the
|
|
||||||
packaging the AI writes for a job: title, hook, description
|
|
||||||
and thumbnail. Defaults to no profile. */}
|
|
||||||
{channels.length > 0 && (
|
|
||||||
<div className="mt-5" data-tutorial="channel-profile">
|
|
||||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
|
||||||
<p className="eyebrow">channel profile</p>
|
|
||||||
<select
|
|
||||||
value={channel}
|
|
||||||
onChange={(e) => setChannel(e.target.value)}
|
|
||||||
className="input-field !w-auto text-xs py-1.5"
|
|
||||||
aria-label="channel profile"
|
|
||||||
>
|
|
||||||
<option value="none">None (generic)</option>
|
|
||||||
{channels.map((ch) => (
|
|
||||||
<option key={ch.slug} value={ch.slug}>{ch.name || ch.slug}</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<p className="text-[11px] leading-relaxed text-muted mt-1.5">
|
|
||||||
Tailors titles, hooks, description and thumbnail for that channel.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Advanced generation controls — collapsed by default; blank = AI decides */}
|
{/* Advanced generation controls — collapsed by default; blank = AI decides */}
|
||||||
<div className="mt-4">
|
<div className="mt-4">
|
||||||
<button
|
<button
|
||||||
|
|
@ -413,7 +311,7 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
||||||
<div>
|
<div>
|
||||||
<p className="eyebrow mb-1.5">clips to aim for</p>
|
<p className="eyebrow mb-1.5">clips to aim for</p>
|
||||||
<input
|
<input
|
||||||
type="number" min="1" max="31" step="1"
|
type="number" min="1" max="15" step="1"
|
||||||
value={targetClips}
|
value={targetClips}
|
||||||
onChange={(e) => setTargetClips(e.target.value)}
|
onChange={(e) => setTargetClips(e.target.value)}
|
||||||
placeholder="auto"
|
placeholder="auto"
|
||||||
|
|
@ -455,7 +353,6 @@ export default function MediaInput({ onProcess, isProcessing }) {
|
||||||
<option value="auto">Auto (AI picks per video)</option>
|
<option value="auto">Auto (AI picks per video)</option>
|
||||||
<option value="split">Two speakers stacked</option>
|
<option value="split">Two speakers stacked</option>
|
||||||
<option value="screencast">Screen over presenter</option>
|
<option value="screencast">Screen over presenter</option>
|
||||||
<option value="code">Code / terminal (zoom to text)</option>
|
|
||||||
<option value="none">Single crop only</option>
|
<option value="none">Single crop only</option>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -1,65 +1,21 @@
|
||||||
import React, { useState, useEffect, useRef } from 'react';
|
import React, { useState, useEffect, useRef } from 'react';
|
||||||
import { Download, Share2, Instagram, Youtube, AlertCircle, Loader2, Copy, Check, Wand2, Type, Calendar, FileText, Link2, Scissors, Crosshair, TrendingUp } from 'lucide-react';
|
import { Download, Share2, Instagram, Youtube, Video, AlertCircle, Loader2, Copy, Check, Wand2, Type, Calendar, Languages, FileText, Link2, Scissors, Crosshair, TrendingUp } from 'lucide-react';
|
||||||
import { getApiUrl } from '../config';
|
import { getApiUrl } from '../config';
|
||||||
import { apiFetch } from '../lib/api';
|
import { apiFetch } from '../lib/api';
|
||||||
import SubtitleModal from './SubtitleModal';
|
import SubtitleModal from './SubtitleModal';
|
||||||
import HookModal from './HookModal';
|
import HookModal from './HookModal';
|
||||||
import BridgeModal from './BridgeModal';
|
import TranslateModal from './TranslateModal';
|
||||||
import Modal from './ui/Modal';
|
import Modal from './ui/Modal';
|
||||||
|
import SegmentedControl from './ui/SegmentedControl';
|
||||||
import { renderInBrowser } from '../lib/renderInBrowser';
|
import { renderInBrowser } from '../lib/renderInBrowser';
|
||||||
|
|
||||||
const QUIET_BTN = 'group flex flex-col items-center justify-center gap-1 py-2.5 sm:py-2 px-1 rounded-input border border-rule hover:bg-paper3 text-[11px] lowercase text-ink2 whitespace-nowrap transition-colors disabled:opacity-45 disabled:cursor-not-allowed';
|
const QUIET_BTN = 'group flex flex-col items-center justify-center gap-1 py-2.5 sm:py-2 px-1 rounded-input border border-rule hover:bg-paper3 text-[11px] lowercase text-ink2 whitespace-nowrap transition-colors disabled:opacity-45 disabled:cursor-not-allowed';
|
||||||
|
|
||||||
// Postiz integration identifier -> glyph. Anything we do not special-case falls
|
const PLATFORM_OPTIONS = [
|
||||||
// back to a generic share glyph so every connected channel still shows up.
|
{ value: 'tiktok', label: 'tiktok', icon: <Video size={16} /> },
|
||||||
const TikTokGlyph = ({ size = 16 }) => (
|
{ value: 'instagram', label: 'instagram', icon: <Instagram size={16} /> },
|
||||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
|
{ value: 'youtube', label: 'youtube', icon: <Youtube size={16} /> },
|
||||||
<path d="M19.589 6.686a4.793 4.793 0 0 1-3.77-4.245V2h-3.445v13.672a2.896 2.896 0 0 1-5.201 1.743l-.002-.001.002.001a2.895 2.895 0 0 1 3.183-4.51v-3.5a6.329 6.329 0 0 0-5.394 10.692 6.33 6.33 0 0 0 10.857-4.424V8.687a8.182 8.182 0 0 0 4.773 1.526V6.79a4.831 4.831 0 0 1-1.003-.104z" />
|
];
|
||||||
</svg>
|
|
||||||
);
|
|
||||||
|
|
||||||
const PlatformIcon = ({ identifier, size = 16 }) => {
|
|
||||||
const id = String(identifier || '').toLowerCase();
|
|
||||||
if (id.includes('tiktok')) return <TikTokGlyph size={size} />;
|
|
||||||
if (id.includes('instagram')) return <Instagram size={size} />;
|
|
||||||
if (id.includes('youtube')) return <Youtube size={size} />;
|
|
||||||
return <Share2 size={size} />;
|
|
||||||
};
|
|
||||||
|
|
||||||
// Today as YYYY-MM-DD in the user's own timezone, for the date input's `min`.
|
|
||||||
// Built from local parts (not toISOString, which would shift the day across the
|
|
||||||
// UTC boundary for users west of Greenwich).
|
|
||||||
function todayInputValue() {
|
|
||||||
const n = new Date();
|
|
||||||
return `${n.getFullYear()}-${String(n.getMonth() + 1).padStart(2, '0')}-${String(n.getDate()).padStart(2, '0')}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
// YYYY-MM-DD (a native date picker's value) + HH:MM parsed into a local Date,
|
|
||||||
// with explicit range checks so 2026-02-31 is rejected instead of silently
|
|
||||||
// rolling over to March.
|
|
||||||
function parseSchedule(dateStr, timeStr) {
|
|
||||||
const d = String(dateStr || '').trim();
|
|
||||||
const t = String(timeStr || '').trim();
|
|
||||||
if (!d || !t) return { error: 'Pick a date and a time.' };
|
|
||||||
const dm = d.match(/^(\d{4})-(\d{2})-(\d{2})$/);
|
|
||||||
if (!dm) return { error: 'Date must be in yyyy-mm-dd format.' };
|
|
||||||
const year = Number(dm[1]);
|
|
||||||
const month = Number(dm[2]);
|
|
||||||
const day = Number(dm[3]);
|
|
||||||
if (month < 1 || month > 12) return { error: 'Month must be between 01 and 12.' };
|
|
||||||
if (day < 1 || day > 31) return { error: 'Day must be between 01 and 31.' };
|
|
||||||
const tm = t.match(/^(\d{1,2}):(\d{2})$/);
|
|
||||||
if (!tm) return { error: 'Time must be in HH:MM format.' };
|
|
||||||
const hour = Number(tm[1]);
|
|
||||||
const minute = Number(tm[2]);
|
|
||||||
if (hour > 23 || minute > 59) return { error: 'Time must be between 00:00 and 23:59.' };
|
|
||||||
const date = new Date(year, month - 1, day, hour, minute, 0, 0);
|
|
||||||
if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {
|
|
||||||
return { error: 'That date does not exist.' };
|
|
||||||
}
|
|
||||||
return { date };
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
function clipDurationSeconds(clip) {
|
function clipDurationSeconds(clip) {
|
||||||
// A recut clip's start/end are the covering source range (segments may be
|
// A recut clip's start/end are the covering source range (segments may be
|
||||||
|
|
@ -77,7 +33,7 @@ function formatDuration(clip) {
|
||||||
return `${String(Math.floor(secs / 60)).padStart(2, '0')}:${String(secs % 60).padStart(2, '0')}`;
|
return `${String(Math.floor(secs / 60)).padStart(2, '0')}:${String(secs % 60).padStart(2, '0')}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, geminiApiKey, onPlay, onPause, onBulkSubtitle, clipCount = 1, bulkProgress, onConnectSocials, onEditClip = null, onReframeClip = null, suggestedSchedule = null }) {
|
export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, geminiApiKey, elevenLabsKey, onPlay, onPause, onBulkSubtitle, clipCount = 1, bulkProgress, connectedPlatforms = null, onConnectSocials, onEditClip = null, onReframeClip = null }) {
|
||||||
const [showModal, setShowModal] = useState(false);
|
const [showModal, setShowModal] = useState(false);
|
||||||
// The "why" line is clamped to two lines so cards in a row stay level;
|
// The "why" line is clamped to two lines so cards in a row stay level;
|
||||||
// when it overflows, a hover (desktop) or tap (touch) shows the whole
|
// when it overflows, a hover (desktop) or tap (touch) shows the whole
|
||||||
|
|
@ -116,9 +72,7 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
||||||
const downloadClip = async () => {
|
const downloadClip = async () => {
|
||||||
try {
|
try {
|
||||||
setDownloadPct(0);
|
setDownloadPct(0);
|
||||||
// The server packages the saved clip (not the transient blob:
|
const response = await fetch(currentVideoUrl);
|
||||||
// preview this card may be showing) as a `<title>/` folder zip.
|
|
||||||
const response = await fetch(getApiUrl(`/api/jobs/${jobId}/clip/${index}/download`));
|
|
||||||
if (!response.ok) throw new Error('Download failed');
|
if (!response.ok) throw new Error('Download failed');
|
||||||
const total = Number(response.headers.get('content-length')) || 0;
|
const total = Number(response.headers.get('content-length')) || 0;
|
||||||
let blob;
|
let blob;
|
||||||
|
|
@ -137,31 +91,13 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
||||||
received += value.length;
|
received += value.length;
|
||||||
setDownloadPct(Math.min(99, Math.round((received / total) * 100)));
|
setDownloadPct(Math.min(99, Math.round((received / total) * 100)));
|
||||||
}
|
}
|
||||||
blob = new Blob(chunks, { type: 'application/zip' });
|
blob = new Blob(chunks, { type: 'video/mp4' });
|
||||||
}
|
}
|
||||||
|
|
||||||
// The server names the bundle `<title>.zip`. Prefer the RFC 5987
|
|
||||||
// form when present so non-ASCII titles survive; fall back to the
|
|
||||||
// plain quoted filename, then to a generic numbered name.
|
|
||||||
let filename = `clip-${index + 1}.zip`;
|
|
||||||
const disposition = response.headers.get('content-disposition') || '';
|
|
||||||
const rfc5987 = disposition.match(/filename\*=UTF-8''([^;]+)/i);
|
|
||||||
const plain = disposition.match(/filename="?([^";]+)"?/i);
|
|
||||||
if (rfc5987) {
|
|
||||||
try {
|
|
||||||
filename = decodeURIComponent(rfc5987[1]);
|
|
||||||
} catch {
|
|
||||||
// malformed percent-encoding — keep the fallback name
|
|
||||||
}
|
|
||||||
} else if (plain) {
|
|
||||||
filename = plain[1];
|
|
||||||
}
|
|
||||||
|
|
||||||
const url = window.URL.createObjectURL(blob);
|
const url = window.URL.createObjectURL(blob);
|
||||||
const a = document.createElement('a');
|
const a = document.createElement('a');
|
||||||
a.style.display = 'none';
|
a.style.display = 'none';
|
||||||
a.href = url;
|
a.href = url;
|
||||||
a.download = filename;
|
a.download = `clip-${index + 1}.mp4`;
|
||||||
document.body.appendChild(a);
|
document.body.appendChild(a);
|
||||||
a.click();
|
a.click();
|
||||||
window.URL.revokeObjectURL(url);
|
window.URL.revokeObjectURL(url);
|
||||||
|
|
@ -193,18 +129,15 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [clip.video_url]);
|
}, [clip.video_url]);
|
||||||
|
|
||||||
// Publish form state.
|
const [platforms, setPlatforms] = useState({
|
||||||
|
tiktok: true,
|
||||||
|
instagram: true,
|
||||||
|
youtube: true
|
||||||
|
});
|
||||||
const [postTitle, setPostTitle] = useState("");
|
const [postTitle, setPostTitle] = useState("");
|
||||||
const [postDescription, setPostDescription] = useState("");
|
const [postDescription, setPostDescription] = useState("");
|
||||||
const [isScheduling, setIsScheduling] = useState(false);
|
const [isScheduling, setIsScheduling] = useState(false);
|
||||||
const [scheduleDate, setScheduleDate] = useState("");
|
const [scheduleDate, setScheduleDate] = useState("");
|
||||||
const [scheduleTime, setScheduleTime] = useState("");
|
|
||||||
// Channels from GET /api/postiz/integrations, one row each (disabled ones
|
|
||||||
// included but unselectable). Selected by integration id, not platform name.
|
|
||||||
const [integrations, setIntegrations] = useState([]);
|
|
||||||
const [integrationsLoading, setIntegrationsLoading] = useState(false);
|
|
||||||
const [integrationsError, setIntegrationsError] = useState(null);
|
|
||||||
const [selectedIds, setSelectedIds] = useState([]);
|
|
||||||
|
|
||||||
const [posting, setPosting] = useState(false);
|
const [posting, setPosting] = useState(false);
|
||||||
const [postResult, setPostResult] = useState(null);
|
const [postResult, setPostResult] = useState(null);
|
||||||
|
|
@ -223,8 +156,9 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
||||||
const [isEditing, setIsEditing] = useState(false);
|
const [isEditing, setIsEditing] = useState(false);
|
||||||
const [isSubtitling, setIsSubtitling] = useState(false);
|
const [isSubtitling, setIsSubtitling] = useState(false);
|
||||||
const [isHooking, setIsHooking] = useState(false);
|
const [isHooking, setIsHooking] = useState(false);
|
||||||
|
const [isTranslating, setIsTranslating] = useState(false);
|
||||||
const [showHookModal, setShowHookModal] = useState(false);
|
const [showHookModal, setShowHookModal] = useState(false);
|
||||||
const [showBridgeModal, setShowBridgeModal] = useState(false);
|
const [showTranslateModal, setShowTranslateModal] = useState(false);
|
||||||
const [editError, setEditError] = useState(null);
|
const [editError, setEditError] = useState(null);
|
||||||
|
|
||||||
const [clipDuration, setClipDuration] = useState(() => {
|
const [clipDuration, setClipDuration] = useState(() => {
|
||||||
|
|
@ -257,82 +191,46 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
}, [jobId, index]);
|
}, [jobId, index]);
|
||||||
|
|
||||||
// Accounts are connected inside the user's own Postiz instance, so
|
// Which platforms the selected profile actually has linked. `null` means
|
||||||
// "connect" opens it (or Settings when no URL is configured yet).
|
// unknown (profile list not loaded) — in that case nothing is gated.
|
||||||
|
// Identifiers are normalized to lowercase: Postiz can report them as
|
||||||
|
// "YouTube", while ChannelIcon and the backend compare lowercase.
|
||||||
|
const knownConnections = Array.isArray(connectedPlatforms);
|
||||||
|
const normalizedConnections = knownConnections
|
||||||
|
? connectedPlatforms.map((p) => String(p).toLowerCase())
|
||||||
|
: [];
|
||||||
|
const noAccountsConnected = knownConnections && normalizedConnections.length === 0;
|
||||||
|
const platformOptions = knownConnections
|
||||||
|
? PLATFORM_OPTIONS.map((o) => (normalizedConnections.includes(o.value) ? o : { ...o, disabled: true, hint: 'not connected' }))
|
||||||
|
: PLATFORM_OPTIONS;
|
||||||
|
|
||||||
const handleConnectAccounts = () => {
|
const handleConnectAccounts = () => {
|
||||||
setShowModal(false);
|
setShowModal(false);
|
||||||
if (onConnectSocials) onConnectSocials();
|
if (onConnectSocials) onConnectSocials();
|
||||||
else if (postizUrl) window.open(postizUrl, '_blank', 'noopener');
|
else if (postizUrl) window.open(postizUrl, '_blank', 'noopener');
|
||||||
};
|
};
|
||||||
|
|
||||||
// Every integration is a selectable row; disabled ones are listed but not
|
// Initialize/Reset form when modal opens
|
||||||
// selectable, and every enabled channel starts selected.
|
|
||||||
const toggleIntegration = (id) => {
|
|
||||||
setSelectedIds((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]));
|
|
||||||
};
|
|
||||||
|
|
||||||
// Load the full channel list whenever the publish modal opens. The list is
|
|
||||||
// keyed by integration id, so multiple channels on the same platform (e.g.
|
|
||||||
// two YouTube channels) stay distinct.
|
|
||||||
useEffect(() => {
|
|
||||||
if (!showModal) return undefined;
|
|
||||||
let cancelled = false;
|
|
||||||
const load = async () => {
|
|
||||||
if (!postizKey || !postizUrl) {
|
|
||||||
if (!cancelled) {
|
|
||||||
setIntegrations([]);
|
|
||||||
setIntegrationsLoading(false);
|
|
||||||
setIntegrationsError(null);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setIntegrationsLoading(true);
|
|
||||||
setIntegrationsError(null);
|
|
||||||
try {
|
|
||||||
const headers = { 'X-Postiz-Url': postizUrl.replace(/\/$/, '') };
|
|
||||||
headers['X-Postiz-Key'] = postizKey;
|
|
||||||
const res = await apiFetch('/api/postiz/integrations', { headers });
|
|
||||||
if (!res.ok) {
|
|
||||||
const text = await res.text();
|
|
||||||
let detail = text;
|
|
||||||
try {
|
|
||||||
const j = JSON.parse(text);
|
|
||||||
if (typeof j.detail === 'string') detail = j.detail;
|
|
||||||
} catch { /* keep the raw body */ }
|
|
||||||
throw new Error(detail || 'Could not reach Postiz.');
|
|
||||||
}
|
|
||||||
const data = await res.json();
|
|
||||||
const list = Array.isArray(data) ? data : (data.integrations || []);
|
|
||||||
if (cancelled) return;
|
|
||||||
setIntegrations(list);
|
|
||||||
setSelectedIds(list.filter((c) => !c.disabled).map((c) => c.id));
|
|
||||||
} catch (e) {
|
|
||||||
if (cancelled) return;
|
|
||||||
setIntegrations([]);
|
|
||||||
setIntegrationsError(e.message || 'Could not reach Postiz.');
|
|
||||||
} finally {
|
|
||||||
if (!cancelled) setIntegrationsLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
load();
|
|
||||||
return () => { cancelled = true; };
|
|
||||||
}, [showModal, postizKey, postizUrl]);
|
|
||||||
|
|
||||||
// Reset the form each time the modal opens; the effect above also reloads
|
|
||||||
// the channel list and reselects every enabled channel. When the results
|
|
||||||
// panel has a global schedule start date, the post is prefilled with this
|
|
||||||
// clip's slot for its virality rank and scheduling is switched on, so the
|
|
||||||
// suggested time is visible up front (the user can uncheck to post now).
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (showModal) {
|
if (showModal) {
|
||||||
setPostTitle(clip.video_title_for_youtube_short || "Viral Short");
|
setPostTitle(clip.video_title_for_youtube_short || "Viral Short");
|
||||||
setPostDescription(clip.video_description_for_instagram || clip.video_description_for_tiktok || "");
|
setPostDescription(clip.video_description_for_instagram || clip.video_description_for_tiktok || "");
|
||||||
setIsScheduling(!!suggestedSchedule);
|
setIsScheduling(false);
|
||||||
setScheduleDate(suggestedSchedule?.date ?? "");
|
setScheduleDate("");
|
||||||
setScheduleTime(suggestedSchedule?.time ?? "");
|
|
||||||
setPostResult(null);
|
setPostResult(null);
|
||||||
|
// Only preselect platforms the profile can actually publish to.
|
||||||
|
if (knownConnections) {
|
||||||
|
setPlatforms({
|
||||||
|
tiktok: normalizedConnections.includes('tiktok'),
|
||||||
|
instagram: normalizedConnections.includes('instagram'),
|
||||||
|
youtube: normalizedConnections.includes('youtube'),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}, [showModal, clip, suggestedSchedule]);
|
}
|
||||||
|
// Reset only when the modal opens for a clip; connection changes while
|
||||||
|
// it is open must not wipe the user's selection.
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [showModal, clip]);
|
||||||
|
|
||||||
const handleAutoEdit = async () => {
|
const handleAutoEdit = async () => {
|
||||||
setIsEditing(true);
|
setIsEditing(true);
|
||||||
|
|
@ -642,11 +540,72 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleTranslate = async (options) => {
|
||||||
|
console.log('[Translate] Starting translation with options:', options);
|
||||||
|
setIsTranslating(true);
|
||||||
|
setEditError(null);
|
||||||
|
try {
|
||||||
|
const apiKey = elevenLabsKey;
|
||||||
|
console.log('[Translate] API Key available:', !!apiKey);
|
||||||
|
|
||||||
|
if (!apiKey) {
|
||||||
|
throw new Error("ElevenLabs API Key is missing. Please set it in Settings.");
|
||||||
|
}
|
||||||
|
|
||||||
|
const requestBody = {
|
||||||
|
job_id: jobId,
|
||||||
|
clip_index: index,
|
||||||
|
target_language: options.targetLanguage,
|
||||||
|
input_filename: serverVideoFile
|
||||||
|
};
|
||||||
|
console.log('[Translate] Request body:', requestBody);
|
||||||
|
console.log('[Translate] Sending request to /api/translate');
|
||||||
|
|
||||||
|
const res = await apiFetch('/api/translate', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'X-ElevenLabs-Key': apiKey
|
||||||
|
},
|
||||||
|
body: JSON.stringify(requestBody)
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('[Translate] Response status:', res.status);
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
const errText = await res.text();
|
||||||
|
console.error('[Translate] Error response:', errText);
|
||||||
|
try {
|
||||||
|
const jsonErr = JSON.parse(errText);
|
||||||
|
throw new Error(jsonErr.detail || errText);
|
||||||
|
} catch (e) {
|
||||||
|
if (e.message !== errText) throw e;
|
||||||
|
throw new Error(errText);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await res.json();
|
||||||
|
console.log('[Translate] Success response:', data);
|
||||||
|
if (data.new_video_url) {
|
||||||
|
setCurrentVideoUrl(getApiUrl(data.new_video_url));
|
||||||
|
setServerVideoFile(data.new_video_url.split('/').pop());
|
||||||
|
if (videoRef.current) {
|
||||||
|
videoRef.current.load();
|
||||||
|
}
|
||||||
|
setShowTranslateModal(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[Translate] Exception:', e);
|
||||||
|
setEditError(e.message);
|
||||||
|
setTimeout(() => setEditError(null), 5000);
|
||||||
|
} finally {
|
||||||
|
setIsTranslating(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// Publishing needs both the Postiz base URL and API key; clipping does not.
|
// Publishing needs both the Postiz base URL and API key; clipping does not.
|
||||||
const canPost = !!postizKey && !!postizUrl;
|
const canPost = !!postizKey && !!postizUrl;
|
||||||
// No channels only counts once a load has finished without error, so the
|
|
||||||
// "connect accounts" prompt never flashes while the list is in flight.
|
|
||||||
const noChannels = !integrationsLoading && !integrationsError && integrations.length === 0;
|
|
||||||
|
|
||||||
const handlePost = async () => {
|
const handlePost = async () => {
|
||||||
if (!canPost) {
|
if (!canPost) {
|
||||||
|
|
@ -654,22 +613,20 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const enabledIds = integrations.filter((c) => !c.disabled).map((c) => c.id);
|
if (noAccountsConnected) {
|
||||||
const chosen = selectedIds.filter((id) => enabledIds.includes(id));
|
setPostResult({ success: false, msg: "Connect a social account first." });
|
||||||
if (chosen.length === 0) {
|
|
||||||
setPostResult({ success: false, msg: "Select at least one channel." });
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The date/time is only required when scheduling; "publish now" needs none.
|
const selectedPlatforms = Object.keys(platforms).filter(k => platforms[k]);
|
||||||
let scheduledIso = null;
|
if (selectedPlatforms.length === 0) {
|
||||||
if (isScheduling) {
|
setPostResult({ success: false, msg: "Select at least one platform." });
|
||||||
const parsed = parseSchedule(scheduleDate, scheduleTime);
|
|
||||||
if (parsed.error) {
|
|
||||||
setPostResult({ success: false, msg: parsed.error });
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
scheduledIso = parsed.date.toISOString();
|
|
||||||
|
if (isScheduling && !scheduleDate) {
|
||||||
|
setPostResult({ success: false, msg: "Please select a date and time." });
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
setPosting(true);
|
setPosting(true);
|
||||||
|
|
@ -679,13 +636,14 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
||||||
const payload = {
|
const payload = {
|
||||||
job_id: jobId,
|
job_id: jobId,
|
||||||
clip_index: index,
|
clip_index: index,
|
||||||
integration_ids: chosen,
|
platforms: selectedPlatforms,
|
||||||
title: postTitle,
|
title: postTitle,
|
||||||
description: postDescription
|
description: postDescription
|
||||||
};
|
};
|
||||||
|
|
||||||
if (scheduledIso) {
|
if (isScheduling && scheduleDate) {
|
||||||
payload.scheduled_date = scheduledIso;
|
// Convert to ISO-8601
|
||||||
|
payload.scheduled_date = new Date(scheduleDate).toISOString();
|
||||||
payload.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
payload.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -701,33 +659,22 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const errText = await res.text();
|
const errText = await res.text();
|
||||||
let detail = errText;
|
|
||||||
try {
|
try {
|
||||||
const jsonErr = JSON.parse(errText);
|
const jsonErr = JSON.parse(errText);
|
||||||
if (typeof jsonErr.detail === 'string') detail = jsonErr.detail;
|
throw new Error(jsonErr.detail || errText);
|
||||||
} catch { /* keep the raw body */ }
|
} catch (e) {
|
||||||
throw new Error(detail || 'Publish failed.');
|
throw new Error(errText);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await res.json();
|
setPostResult({ success: true, msg: isScheduling ? "Scheduled successfully!" : "Posted successfully!" });
|
||||||
const posted = Array.isArray(data.posted) ? data.posted : [];
|
|
||||||
const names = posted.map((p) => p.name || p.identifier || p.platform).filter(Boolean);
|
|
||||||
const target = names.length
|
|
||||||
? names.join(', ')
|
|
||||||
: `${chosen.length} channel${chosen.length === 1 ? '' : 's'}`;
|
|
||||||
const when = scheduledIso
|
|
||||||
? `on ${scheduleDate} at ${scheduleTime} (${payload.timezone})`
|
|
||||||
: 'now';
|
|
||||||
setPostResult({ success: true, msg: `Posted to ${target} ${when}.` });
|
|
||||||
|
|
||||||
// Keep the confirmation up long enough to read it before closing.
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
setShowModal(false);
|
setShowModal(false);
|
||||||
setPostResult(null);
|
setPostResult(null);
|
||||||
}, 4000);
|
}, 3000);
|
||||||
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setPostResult({ success: false, msg: e.message || 'Publish failed.' });
|
setPostResult({ success: false, msg: `Failed: ${e.message}` });
|
||||||
} finally {
|
} finally {
|
||||||
setPosting(false);
|
setPosting(false);
|
||||||
}
|
}
|
||||||
|
|
@ -939,12 +886,12 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
onClick={() => setShowBridgeModal(true)}
|
onClick={() => setShowTranslateModal(true)}
|
||||||
|
disabled={isTranslating}
|
||||||
className={QUIET_BTN}
|
className={QUIET_BTN}
|
||||||
title="Shorts → long-form bridge: related video, first comment, Studio checklist"
|
|
||||||
>
|
>
|
||||||
<Link2 size={16} className="text-muted group-hover:text-brass transition-colors shrink-0" />
|
{isTranslating ? <Loader2 size={16} className="animate-spin text-brass shrink-0" /> : <Languages size={16} className="text-muted group-hover:text-brass transition-colors shrink-0" />}
|
||||||
bridge
|
{isTranslating ? 'translating…' : 'dub voice'}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
|
|
@ -1014,7 +961,7 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
||||||
title="post clip"
|
title="post clip"
|
||||||
size="md"
|
size="md"
|
||||||
footer={
|
footer={
|
||||||
canPost && noChannels ? (
|
noAccountsConnected ? (
|
||||||
<button onClick={handleConnectAccounts} className="btn-primary w-full">
|
<button onClick={handleConnectAccounts} className="btn-primary w-full">
|
||||||
<Link2 size={16} /> connect accounts
|
<Link2 size={16} /> connect accounts
|
||||||
</button>
|
</button>
|
||||||
|
|
@ -1036,6 +983,13 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{noAccountsConnected && (
|
||||||
|
<div className="mb-4 px-3 py-2 rounded-input text-xs text-warn bg-[color-mix(in_oklab,var(--color-warn)_10%,transparent)] flex items-start gap-2">
|
||||||
|
<AlertCircle size={14} className="mt-0.5 shrink-0" />
|
||||||
|
<div className="lowercase">no social accounts connected yet — link tiktok, instagram or youtube in Postiz to publish this clip.</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
{/* Title & Description */}
|
{/* Title & Description */}
|
||||||
<div>
|
<div>
|
||||||
|
|
@ -1060,7 +1014,7 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Scheduling — native date picker + HH:MM */}
|
{/* Scheduling */}
|
||||||
<div className="p-3 bg-paper rounded-input border border-rule">
|
<div className="p-3 bg-paper rounded-input border border-rule">
|
||||||
<label className="flex items-center justify-between cursor-pointer">
|
<label className="flex items-center justify-between cursor-pointer">
|
||||||
<span className="flex items-center gap-2 text-sm text-ink2 lowercase">
|
<span className="flex items-center gap-2 text-sm text-ink2 lowercase">
|
||||||
|
|
@ -1077,87 +1031,31 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
||||||
{isScheduling && (
|
{isScheduling && (
|
||||||
<div className="mt-3 animate-fade">
|
<div className="mt-3 animate-fade">
|
||||||
<label className="eyebrow block mb-1.5">DATE · TIME</label>
|
<label className="eyebrow block mb-1.5">DATE · TIME</label>
|
||||||
<div className="flex gap-2">
|
|
||||||
<input
|
<input
|
||||||
type="date"
|
type="datetime-local"
|
||||||
value={scheduleDate}
|
value={scheduleDate}
|
||||||
onChange={(e) => setScheduleDate(e.target.value)}
|
onChange={(e) => setScheduleDate(e.target.value)}
|
||||||
min={todayInputValue()}
|
className="input-field [color-scheme:dark]"
|
||||||
aria-label="date"
|
|
||||||
className="input-field flex-1 [color-scheme:dark]"
|
|
||||||
/>
|
/>
|
||||||
<input
|
|
||||||
type="time"
|
|
||||||
value={scheduleTime}
|
|
||||||
onChange={(e) => setScheduleTime(e.target.value)}
|
|
||||||
aria-label="time (HH:MM)"
|
|
||||||
className="input-field w-[7.5rem] [color-scheme:dark]"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<p className="text-xs text-muted mt-1.5">pick a day and a time, in your local timezone</p>
|
|
||||||
{suggestedSchedule && (
|
|
||||||
<p className="text-xs text-muted mt-1">auto-filled from the schedule start date — change it freely</p>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Channels — every integration is selectable, by id. */}
|
{/* Platforms */}
|
||||||
{canPost && (
|
|
||||||
<div>
|
<div>
|
||||||
<label className="eyebrow block mb-2">CHANNELS</label>
|
<label className="eyebrow block mb-2">PLATFORMS</label>
|
||||||
{integrationsLoading && (
|
<SegmentedControl
|
||||||
<p className="text-xs text-muted lowercase flex items-center gap-2">
|
multi
|
||||||
<Loader2 size={14} className="animate-spin" /> loading channels…
|
columns={3}
|
||||||
</p>
|
options={platformOptions}
|
||||||
)}
|
value={Object.keys(platforms).filter(k => platforms[k])}
|
||||||
{!integrationsLoading && integrationsError && (
|
onChange={(arr) => setPlatforms({
|
||||||
<div className="px-3 py-2 rounded-input text-xs text-danger bg-[color-mix(in_oklab,var(--color-danger)_10%,transparent)] flex items-start gap-2">
|
tiktok: arr.includes('tiktok'),
|
||||||
<AlertCircle size={14} className="mt-0.5 shrink-0" />
|
instagram: arr.includes('instagram'),
|
||||||
<span className="break-words">{integrationsError}</span>
|
youtube: arr.includes('youtube'),
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{!integrationsLoading && !integrationsError && integrations.length === 0 && (
|
|
||||||
<p className="text-xs text-muted lowercase">
|
|
||||||
no channels connected yet — add them in Postiz first.
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
{integrations.length > 0 && (
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
{integrations.map((ch) => {
|
|
||||||
const isDisabled = !!ch.disabled;
|
|
||||||
const checked = !isDisabled && selectedIds.includes(ch.id);
|
|
||||||
return (
|
|
||||||
<label
|
|
||||||
key={ch.id}
|
|
||||||
className={`flex items-center gap-2.5 px-3 py-2 rounded-input border transition-colors ${isDisabled
|
|
||||||
? 'border-rule opacity-50 cursor-not-allowed'
|
|
||||||
: checked
|
|
||||||
? 'border-brass bg-paper3 cursor-pointer'
|
|
||||||
: 'border-rule hover:bg-paper3 cursor-pointer'}`}
|
|
||||||
>
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
checked={checked}
|
|
||||||
disabled={isDisabled}
|
|
||||||
onChange={() => toggleIntegration(ch.id)}
|
|
||||||
className="w-4 h-4 accent-brass cursor-pointer disabled:cursor-not-allowed"
|
|
||||||
/>
|
|
||||||
<span className="w-6 h-6 rounded-input bg-paper3 flex items-center justify-center shrink-0 text-ink2">
|
|
||||||
<PlatformIcon identifier={ch.identifier} size={14} />
|
|
||||||
</span>
|
|
||||||
<span className="min-w-0 flex-1">
|
|
||||||
<span className="block text-sm text-ink2 truncate">{ch.name || ch.identifier}</span>
|
|
||||||
<span className="block text-xs text-muted truncate">{ch.identifier}{ch.profile ? ` · ${ch.profile}` : ''}</span>
|
|
||||||
</span>
|
|
||||||
{isDisabled && <span className="readout shrink-0">off</span>}
|
|
||||||
</label>
|
|
||||||
);
|
|
||||||
})}
|
})}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{postResult && (
|
{postResult && (
|
||||||
<div className={postResult.success ? 'badge-ok' : 'badge-danger'}>
|
<div className={postResult.success ? 'badge-ok' : 'badge-danger'}>
|
||||||
|
|
@ -1201,11 +1099,13 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
||||||
onRemove={burnedHook ? handleRemoveHook : null}
|
onRemove={burnedHook ? handleRemoveHook : null}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<BridgeModal
|
<TranslateModal
|
||||||
isOpen={showBridgeModal}
|
isOpen={showTranslateModal}
|
||||||
onClose={() => setShowBridgeModal(false)}
|
onClose={() => setShowTranslateModal(false)}
|
||||||
jobId={jobId}
|
onTranslate={handleTranslate}
|
||||||
clipIndex={index}
|
isProcessing={isTranslating}
|
||||||
|
videoUrl={currentVideoUrl}
|
||||||
|
hasApiKey={!!elevenLabsKey}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import { useState, useRef, useCallback, useEffect } from 'react';
|
import { useState, useRef, useCallback, useEffect } from 'react';
|
||||||
import { Upload, Image, Loader2, Send, Check, Download, ArrowRight, ArrowLeft, Sparkles, Video, Type, X, Plus, MessageSquare, FileText, Youtube, AlertCircle, Settings, FileArchive } from 'lucide-react';
|
import { Upload, Image, Loader2, Send, Check, Download, ArrowRight, ArrowLeft, Sparkles, Video, Type, X, Plus, MessageSquare, FileText, Youtube, AlertCircle, Settings } from 'lucide-react';
|
||||||
import { getApiUrl } from '../config';
|
import { getApiUrl } from '../config';
|
||||||
import { apiFetch } from '../lib/api';
|
import { apiFetch } from '../lib/api';
|
||||||
import StepIndicator from './ui/StepIndicator';
|
import StepIndicator from './ui/StepIndicator';
|
||||||
|
|
@ -80,9 +80,6 @@ export default function ThumbnailStudio({ geminiApiKey, postizKey, postizUrl, on
|
||||||
|
|
||||||
// Step 1 state
|
// Step 1 state
|
||||||
const [videoFile, setVideoFile] = useState(null);
|
const [videoFile, setVideoFile] = useState(null);
|
||||||
// Optional cadence handoff bundle: its edited transcript is used and the
|
|
||||||
// server skips Whisper. The video is still required for frames/publish.
|
|
||||||
const [handoffFile, setHandoffFile] = useState(null);
|
|
||||||
const [isAnalyzing, setIsAnalyzing] = useState(false);
|
const [isAnalyzing, setIsAnalyzing] = useState(false);
|
||||||
|
|
||||||
// Step 2 state
|
// Step 2 state
|
||||||
|
|
@ -163,10 +160,8 @@ export default function ThumbnailStudio({ geminiApiKey, postizKey, postizUrl, on
|
||||||
if (preprocessSessionId) {
|
if (preprocessSessionId) {
|
||||||
// Use pre-uploaded session (Whisper already running/done in background)
|
// Use pre-uploaded session (Whisper already running/done in background)
|
||||||
formData.append('session_id', preprocessSessionId);
|
formData.append('session_id', preprocessSessionId);
|
||||||
if (handoffFile) formData.append('handoff', handoffFile);
|
|
||||||
} else if (videoFile) {
|
} else if (videoFile) {
|
||||||
formData.append('file', videoFile);
|
formData.append('file', videoFile);
|
||||||
if (handoffFile) formData.append('handoff', handoffFile);
|
|
||||||
} else {
|
} else {
|
||||||
return alert('Please upload a video file.');
|
return alert('Please upload a video file.');
|
||||||
}
|
}
|
||||||
|
|
@ -448,7 +443,6 @@ export default function ThumbnailStudio({ geminiApiKey, postizKey, postizUrl, on
|
||||||
setStep(0);
|
setStep(0);
|
||||||
setMode(null);
|
setMode(null);
|
||||||
setVideoFile(null);
|
setVideoFile(null);
|
||||||
setHandoffFile(null);
|
|
||||||
setSessionId(null);
|
setSessionId(null);
|
||||||
setTitles([]);
|
setTitles([]);
|
||||||
setSelectedTitle('');
|
setSelectedTitle('');
|
||||||
|
|
@ -528,26 +522,12 @@ export default function ThumbnailStudio({ geminiApiKey, postizKey, postizUrl, on
|
||||||
<DragDropZone
|
<DragDropZone
|
||||||
label="Upload video file"
|
label="Upload video file"
|
||||||
accept="video/*"
|
accept="video/*"
|
||||||
onFile={(f) => { setVideoFile(f); setMode('video'); if (!handoffFile) handlePreUpload(f); }}
|
onFile={(f) => { setVideoFile(f); setMode('video'); handlePreUpload(f); }}
|
||||||
file={videoFile}
|
file={videoFile}
|
||||||
onClear={() => { setVideoFile(null); setPreprocessSessionId(null); }}
|
onClear={() => { setVideoFile(null); setPreprocessSessionId(null); }}
|
||||||
icon={Video}
|
icon={Video}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div>
|
|
||||||
<DragDropZone
|
|
||||||
label="cadence handoff bundle (.zip, optional)"
|
|
||||||
accept=".zip,application/zip"
|
|
||||||
onFile={setHandoffFile}
|
|
||||||
file={handoffFile}
|
|
||||||
onClear={() => setHandoffFile(null)}
|
|
||||||
icon={FileArchive}
|
|
||||||
/>
|
|
||||||
<p className="text-xs lowercase text-muted mt-1.5">
|
|
||||||
uses the bundle's edited transcript, so transcription is skipped
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{isPreprocessing && (
|
{isPreprocessing && (
|
||||||
<div className="flex items-center gap-2 text-xs lowercase text-muted bg-paper3 rounded-input px-3 py-2">
|
<div className="flex items-center gap-2 text-xs lowercase text-muted bg-paper3 rounded-input px-3 py-2">
|
||||||
<Loader2 size={12} className="animate-spin text-brass" />
|
<Loader2 size={12} className="animate-spin text-brass" />
|
||||||
|
|
|
||||||
154
dashboard/src/components/TranslateModal.jsx
Normal file
|
|
@ -0,0 +1,154 @@
|
||||||
|
import React, { useState } from 'react';
|
||||||
|
import { Loader2, Languages, AlertCircle } from 'lucide-react';
|
||||||
|
import Modal from './ui/Modal';
|
||||||
|
|
||||||
|
const LANGUAGES = {
|
||||||
|
"es": "Spanish",
|
||||||
|
"fr": "French",
|
||||||
|
"de": "German",
|
||||||
|
"it": "Italian",
|
||||||
|
"pt": "Portuguese",
|
||||||
|
"pl": "Polish",
|
||||||
|
"hi": "Hindi",
|
||||||
|
"ja": "Japanese",
|
||||||
|
"ko": "Korean",
|
||||||
|
"zh": "Chinese",
|
||||||
|
"ar": "Arabic",
|
||||||
|
"ru": "Russian",
|
||||||
|
"tr": "Turkish",
|
||||||
|
"nl": "Dutch",
|
||||||
|
"sv": "Swedish",
|
||||||
|
"id": "Indonesian",
|
||||||
|
"fil": "Filipino",
|
||||||
|
"ms": "Malay",
|
||||||
|
"vi": "Vietnamese",
|
||||||
|
"th": "Thai",
|
||||||
|
"uk": "Ukrainian",
|
||||||
|
"el": "Greek",
|
||||||
|
"cs": "Czech",
|
||||||
|
"fi": "Finnish",
|
||||||
|
"ro": "Romanian",
|
||||||
|
"da": "Danish",
|
||||||
|
"bg": "Bulgarian",
|
||||||
|
"hr": "Croatian",
|
||||||
|
"sk": "Slovak",
|
||||||
|
"ta": "Tamil",
|
||||||
|
"en": "English",
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function TranslateModal({ isOpen, onClose, onTranslate, isProcessing, videoUrl, hasApiKey }) {
|
||||||
|
const [targetLanguage, setTargetLanguage] = useState('es');
|
||||||
|
|
||||||
|
if (!isOpen) return null;
|
||||||
|
|
||||||
|
const handleSubmit = () => {
|
||||||
|
console.log('[TranslateModal] handleSubmit called, targetLanguage:', targetLanguage);
|
||||||
|
onTranslate({ targetLanguage });
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
isOpen={isOpen}
|
||||||
|
onClose={isProcessing ? undefined : onClose}
|
||||||
|
eyebrow="DUB"
|
||||||
|
title="dub voice"
|
||||||
|
size="md"
|
||||||
|
footer={
|
||||||
|
<div className="flex gap-3">
|
||||||
|
<button
|
||||||
|
onClick={onClose}
|
||||||
|
disabled={isProcessing}
|
||||||
|
className="btn-ghost flex-1"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={handleSubmit}
|
||||||
|
disabled={isProcessing || !hasApiKey}
|
||||||
|
className="btn-primary flex-1"
|
||||||
|
>
|
||||||
|
{isProcessing ? (
|
||||||
|
<>
|
||||||
|
<Loader2 size={16} className="animate-spin" />
|
||||||
|
Dubbing...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Languages size={16} />
|
||||||
|
Dub Voice
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-3 mb-5">
|
||||||
|
<div className="w-10 h-10 rounded-input bg-paper3 flex items-center justify-center shrink-0">
|
||||||
|
<Languages size={18} className="text-brass" />
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted">AI voice translation by ElevenLabs</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{!hasApiKey && (
|
||||||
|
<div className="mb-4 flex items-start gap-2">
|
||||||
|
<span className="badge-warn shrink-0"><AlertCircle size={12} /> key missing</span>
|
||||||
|
<p className="text-sm text-muted">Configure ElevenLabs API Key in Settings first.</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Preview */}
|
||||||
|
<div className="mb-5 rounded-card overflow-hidden bg-black aspect-video">
|
||||||
|
<video
|
||||||
|
src={videoUrl}
|
||||||
|
className="w-full h-full object-contain"
|
||||||
|
muted
|
||||||
|
playsInline
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Language Selection */}
|
||||||
|
<div className="mb-5">
|
||||||
|
<label className="eyebrow block mb-2">
|
||||||
|
Target Language
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
value={targetLanguage}
|
||||||
|
onChange={(e) => setTargetLanguage(e.target.value)}
|
||||||
|
className="input-field appearance-none cursor-pointer"
|
||||||
|
disabled={isProcessing}
|
||||||
|
>
|
||||||
|
{Object.entries(LANGUAGES).sort((a, b) => a[1].localeCompare(b[1])).map(([code, name]) => (
|
||||||
|
<option key={code} value={code}>
|
||||||
|
{name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Info */}
|
||||||
|
<p className="text-xs text-muted leading-relaxed mb-2">
|
||||||
|
The audio will be dubbed with AI-generated voice in the selected language, matching the original speaker's characteristics.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{/* AI Act art. 50: we mark the file, the person publishing it is the
|
||||||
|
one who owes the audience the disclosure. Saying so here is the
|
||||||
|
only place they will read it. */}
|
||||||
|
<p className="text-xs text-muted leading-relaxed mb-2">
|
||||||
|
The dubbed file is tagged as AI-generated content. When you publish it, disclose that the voice is synthetic.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{/* Processing State */}
|
||||||
|
{isProcessing && (
|
||||||
|
<div className="mt-4 p-3 bg-paper3 rounded-input">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Loader2 size={18} className="text-brass animate-spin" />
|
||||||
|
<div>
|
||||||
|
<p className="text-sm text-ink font-medium lowercase">Dubbing audio...</p>
|
||||||
|
<p className="text-xs text-muted lowercase">This may take a few minutes</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { X } from 'lucide-react';
|
import { X } from 'lucide-react';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The single modal shell for the app.
|
* The single modal shell for the app (design.md).
|
||||||
* Plain dark overlay (no backdrop-blur), hairline paper2 panel.
|
* Plain dark overlay (no backdrop-blur), hairline paper2 panel.
|
||||||
*
|
*
|
||||||
* Props:
|
* Props:
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
/**
|
/**
|
||||||
* The single option-toggle group. Replaces every ad-hoc
|
* The single option-toggle group (design.md). Replaces every ad-hoc
|
||||||
* grid of toggle buttons (position/size/animation pickers, platform
|
* grid of toggle buttons (position/size/animation pickers, platform
|
||||||
* selectors, mode switches).
|
* selectors, mode switches).
|
||||||
*
|
*
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { Check } from 'lucide-react';
|
import { Check } from 'lucide-react';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The single wizard stepper — used by ThumbnailStudio. Mono
|
* The single wizard stepper (design.md) — used by ThumbnailStudio. Mono
|
||||||
* ordinals, hairline connectors, brass current step.
|
* ordinals, hairline connectors, brass current step.
|
||||||
*
|
*
|
||||||
* Props:
|
* Props:
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
/* Hallmark · genre: atmospheric · theme: lumen (night foundry) · designed-as-app */
|
/* Hallmark · genre: atmospheric · theme: lumen (night foundry) · design-system: design.md · designed-as-app */
|
||||||
/* Noto Serif (hook-overlay font, burned into videos — not UI) is self-hosted
|
/* Noto Serif (hook-overlay font, burned into videos — not UI) is self-hosted
|
||||||
with the rest of the faces in public/fonts.css: no request to Google. */
|
with the rest of the faces in public/fonts.css: no request to Google. */
|
||||||
@import './tokens.css';
|
@import './tokens.css';
|
||||||
|
|
|
||||||
234
dashboard/src/landing.css
Normal file
|
|
@ -0,0 +1,234 @@
|
||||||
|
/* Hallmark · genre: atmospheric · macrostructure: Marquee Hero · theme: lumen (night) · design-system: design.md · designed-as-app · nav: N9 · footer: Ft5 · enrichment: filament apparatus */
|
||||||
|
|
||||||
|
/* ---- hero: blueprint grid + paper emission (top-right) ---- */
|
||||||
|
.hero-blueprint {
|
||||||
|
background-image:
|
||||||
|
radial-gradient(55% 45% at 82% 0%, var(--color-paper-emit) 0%, transparent 70%),
|
||||||
|
linear-gradient(to right, var(--rule-blueprint) 1px, transparent 1px),
|
||||||
|
linear-gradient(to bottom, var(--rule-blueprint) 1px, transparent 1px);
|
||||||
|
background-size: 100% 100%, 48px 48px, 48px 48px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- hero headline + coral verb landmark ---- */
|
||||||
|
.hero-h1 {
|
||||||
|
font-family: var(--font-display);
|
||||||
|
font-size: clamp(2.75rem, 5vw + 1rem, 5rem);
|
||||||
|
letter-spacing: -0.032em;
|
||||||
|
line-height: 1.05;
|
||||||
|
text-transform: lowercase;
|
||||||
|
color: var(--color-ink);
|
||||||
|
}
|
||||||
|
.hero-h1 em {
|
||||||
|
font-style: normal;
|
||||||
|
color: var(--color-accent-2);
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
.hero-h1 em::after {
|
||||||
|
content: "";
|
||||||
|
position: absolute;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0.04em;
|
||||||
|
height: 1px;
|
||||||
|
background: var(--color-accent-2);
|
||||||
|
transform: scaleX(0);
|
||||||
|
transform-origin: left center;
|
||||||
|
animation: verb-underline 320ms var(--ease-out) 900ms forwards;
|
||||||
|
}
|
||||||
|
@keyframes verb-underline {
|
||||||
|
to { transform: scaleX(1); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- apparatus: instrument bezel holding a real 9:16 clip ---- */
|
||||||
|
.apparatus {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 2rem;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
.apparatus-shell {
|
||||||
|
position: relative;
|
||||||
|
flex: none;
|
||||||
|
}
|
||||||
|
.apparatus-glow {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
border-radius: 18px;
|
||||||
|
box-shadow: 0 0 28px 2px var(--color-glow);
|
||||||
|
opacity: 0.4;
|
||||||
|
animation: filament-pulse var(--dur-pulse) var(--ease-out) infinite;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
.apparatus-chamber {
|
||||||
|
position: relative;
|
||||||
|
z-index: 1;
|
||||||
|
width: clamp(200px, 20vw, 260px);
|
||||||
|
aspect-ratio: 9 / 16;
|
||||||
|
border: 1px solid var(--color-rule-2);
|
||||||
|
border-radius: 18px;
|
||||||
|
background: color-mix(in oklab, var(--color-paper-2) 72%, var(--color-paper-3));
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.apparatus-chamber video {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
object-fit: cover;
|
||||||
|
}
|
||||||
|
.apparatus-stencil {
|
||||||
|
position: absolute;
|
||||||
|
right: 10px;
|
||||||
|
bottom: 10px;
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
font-size: 10.5px;
|
||||||
|
letter-spacing: var(--tracking-micro);
|
||||||
|
text-transform: uppercase;
|
||||||
|
color: var(--color-ink-2);
|
||||||
|
background: rgb(0 0 0 / 0.7);
|
||||||
|
padding: 2px 8px;
|
||||||
|
border-radius: 999px;
|
||||||
|
}
|
||||||
|
.apparatus-callouts {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 2.5rem;
|
||||||
|
}
|
||||||
|
.apparatus-callouts li {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.75rem;
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
font-size: 10.5px;
|
||||||
|
letter-spacing: var(--tracking-micro);
|
||||||
|
text-transform: uppercase;
|
||||||
|
color: var(--color-muted);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.apparatus-leader {
|
||||||
|
flex: none;
|
||||||
|
width: 40px;
|
||||||
|
height: 1px;
|
||||||
|
background: var(--color-rule-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- smart crop: 16:9 source → 9:16 result, real product output ---- */
|
||||||
|
.crop-frame {
|
||||||
|
position: relative;
|
||||||
|
margin: 0;
|
||||||
|
border: 1px solid var(--color-rule);
|
||||||
|
border-radius: var(--radius-card);
|
||||||
|
overflow: hidden;
|
||||||
|
background: var(--color-paper-2);
|
||||||
|
}
|
||||||
|
.crop-frame-16-9 {
|
||||||
|
aspect-ratio: 16 / 9;
|
||||||
|
}
|
||||||
|
.crop-frame-9-16 {
|
||||||
|
aspect-ratio: 9 / 16;
|
||||||
|
}
|
||||||
|
.crop-frame video {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
object-fit: cover;
|
||||||
|
}
|
||||||
|
.crop-window {
|
||||||
|
position: absolute;
|
||||||
|
top: 5%;
|
||||||
|
bottom: 5%;
|
||||||
|
left: 50%;
|
||||||
|
transform: translateX(-50%);
|
||||||
|
aspect-ratio: 9 / 16;
|
||||||
|
border: 1px solid var(--color-accent);
|
||||||
|
border-radius: 6px;
|
||||||
|
box-shadow: 0 0 0 200vmax rgb(0 0 0 / 0.22);
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
.crop-leader {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.625rem;
|
||||||
|
flex: none;
|
||||||
|
}
|
||||||
|
.crop-leader-line {
|
||||||
|
position: relative;
|
||||||
|
width: 56px;
|
||||||
|
height: 1px;
|
||||||
|
background: var(--color-rule-2);
|
||||||
|
}
|
||||||
|
.crop-leader-line::after {
|
||||||
|
content: "";
|
||||||
|
position: absolute;
|
||||||
|
right: -1px;
|
||||||
|
top: -3px;
|
||||||
|
border-left: 5px solid var(--color-rule-2);
|
||||||
|
border-top: 3.5px solid transparent;
|
||||||
|
border-bottom: 3.5px solid transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- meter strip (below the fold) ---- */
|
||||||
|
.meter-strip {
|
||||||
|
height: 40px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 1.5rem;
|
||||||
|
}
|
||||||
|
.meter-ticks {
|
||||||
|
flex: 1 1 0%;
|
||||||
|
min-width: 0;
|
||||||
|
height: 100%;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.meter-tick {
|
||||||
|
flex: none;
|
||||||
|
width: 1px;
|
||||||
|
background: var(--color-accent);
|
||||||
|
opacity: 0.65;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 767px) {
|
||||||
|
.apparatus { gap: 1.25rem; }
|
||||||
|
.apparatus-chamber { width: 180px; }
|
||||||
|
.apparatus-leader { width: 20px; }
|
||||||
|
.apparatus-callouts { gap: 1.5rem; }
|
||||||
|
.crop-leader-line {
|
||||||
|
width: 1px;
|
||||||
|
height: 32px;
|
||||||
|
}
|
||||||
|
.crop-leader-line::after {
|
||||||
|
right: -3px;
|
||||||
|
top: auto;
|
||||||
|
bottom: -1px;
|
||||||
|
border-left: 3.5px solid transparent;
|
||||||
|
border-right: 3.5px solid transparent;
|
||||||
|
border-top: 5px solid var(--color-rule-2);
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* narrow phones: stack callouts under the chamber so nothing overflows */
|
||||||
|
@media (max-width: 519px) {
|
||||||
|
.apparatus { flex-direction: column; gap: 1.25rem; }
|
||||||
|
.apparatus-callouts {
|
||||||
|
flex-direction: row;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 0.625rem 1.25rem;
|
||||||
|
max-width: 100%;
|
||||||
|
}
|
||||||
|
.apparatus-callouts li { gap: 0.5rem; }
|
||||||
|
.apparatus-leader { width: 12px; }
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.apparatus-glow { animation: none; }
|
||||||
|
.hero-h1 em::after { animation: none; transform: scaleX(1); }
|
||||||
|
}
|
||||||
|
|
@ -23,6 +23,8 @@
|
||||||
const STORAGE_KEY = 'clipwright_consent';
|
const STORAGE_KEY = 'clipwright_consent';
|
||||||
const VERSION = 1;
|
const VERSION = 1;
|
||||||
|
|
||||||
|
export const CATEGORIES = ['necessary', 'analytics', 'marketing'];
|
||||||
|
|
||||||
const DENY_ALL = { necessary: true, analytics: false, marketing: false };
|
const DENY_ALL = { necessary: true, analytics: false, marketing: false };
|
||||||
const GRANT_ALL = { necessary: true, analytics: true, marketing: true };
|
const GRANT_ALL = { necessary: true, analytics: true, marketing: true };
|
||||||
|
|
||||||
|
|
@ -60,6 +62,9 @@ export function refineGeo() {
|
||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const listeners = new Set();
|
||||||
|
|
||||||
const read = () => {
|
const read = () => {
|
||||||
try {
|
try {
|
||||||
const raw = localStorage.getItem(STORAGE_KEY);
|
const raw = localStorage.getItem(STORAGE_KEY);
|
||||||
|
|
@ -72,6 +77,9 @@ const read = () => {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** The stored decision, or null when the visitor has never been asked. */
|
||||||
|
export const getConsentRecord = () => read();
|
||||||
|
|
||||||
/** Effective permissions. Nothing but `necessary` before a decision exists. */
|
/** Effective permissions. Nothing but `necessary` before a decision exists. */
|
||||||
export const getConsent = () => {
|
export const getConsent = () => {
|
||||||
const stored = read();
|
const stored = read();
|
||||||
|
|
@ -89,6 +97,11 @@ export const hasDecided = () => read() !== null || !isEEAVisitor();
|
||||||
|
|
||||||
export const allows = (category) => !!getConsent()[category];
|
export const allows = (category) => !!getConsent()[category];
|
||||||
|
|
||||||
|
export function onConsentChange(fn) {
|
||||||
|
listeners.add(fn);
|
||||||
|
return () => listeners.delete(fn);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Persist a decision and act on it immediately.
|
* Persist a decision and act on it immediately.
|
||||||
*
|
*
|
||||||
|
|
@ -110,6 +123,8 @@ export function setConsent(choice) {
|
||||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
|
localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
|
||||||
} catch (_) { /* private mode: the decision holds for this page at least */ }
|
} catch (_) { /* private mode: the decision holds for this page at least */ }
|
||||||
|
|
||||||
|
listeners.forEach((fn) => { try { fn(getConsent()); } catch (_) { /* ignore */ } });
|
||||||
|
|
||||||
applyConsent();
|
applyConsent();
|
||||||
return getConsent();
|
return getConsent();
|
||||||
}
|
}
|
||||||
|
|
@ -128,3 +143,14 @@ export function applyConsent() {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Reopening the banner from anywhere (the footer link) without threading props
|
||||||
|
// through the whole tree.
|
||||||
|
const OPEN_EVENT = 'clipwright:consent-open';
|
||||||
|
export const openConsentManager = () => {
|
||||||
|
try { window.dispatchEvent(new CustomEvent(OPEN_EVENT)); } catch (_) { /* ignore */ }
|
||||||
|
};
|
||||||
|
export const onConsentOpenRequest = (fn) => {
|
||||||
|
window.addEventListener(OPEN_EVENT, fn);
|
||||||
|
return () => window.removeEventListener(OPEN_EVENT, fn);
|
||||||
|
};
|
||||||
|
|
|
||||||
|
|
@ -24,7 +24,6 @@ export async function renderInBrowser({
|
||||||
onProgress,
|
onProgress,
|
||||||
signal,
|
signal,
|
||||||
}) {
|
}) {
|
||||||
if (window.__CW_E2E_RENDER__) return window.__CW_E2E_RENDER__();
|
|
||||||
const fps = 30;
|
const fps = 30;
|
||||||
const durationInFrames = Math.max(1, Math.round(durationInSeconds * fps));
|
const durationInFrames = Math.max(1, Math.round(durationInSeconds * fps));
|
||||||
|
|
||||||
|
|
@ -61,3 +60,15 @@ export async function renderInBrowser({
|
||||||
const blob = await getBlob();
|
const blob = await getBlob();
|
||||||
return URL.createObjectURL(blob);
|
return URL.createObjectURL(blob);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Triggers a download of a blob URL as an MP4 file.
|
||||||
|
*/
|
||||||
|
export function downloadBlobUrl(blobUrl, filename = 'output.mp4') {
|
||||||
|
const link = document.createElement('a');
|
||||||
|
link.href = blobUrl;
|
||||||
|
link.download = filename;
|
||||||
|
document.body.appendChild(link);
|
||||||
|
link.click();
|
||||||
|
document.body.removeChild(link);
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,53 +0,0 @@
|
||||||
// Global publish-date scheduling.
|
|
||||||
//
|
|
||||||
// Given one start date chosen by the user and a clip's virality RANK (1-based,
|
|
||||||
// rank 1 = most viral — the order the results are presented in), produce the
|
|
||||||
// concrete local date/time that clip should be posted at.
|
|
||||||
//
|
|
||||||
// The cadence posts three clips a day at 18:00 (6pm), 21:00 (9pm) and 13:00
|
|
||||||
// (1pm). Ranks are taken in pairs: the odd rank of each pair lands on one day
|
|
||||||
// and the even rank of the same pair the next day, at the pair's shared time.
|
|
||||||
//
|
|
||||||
// rank 1 -> day 0 @ 18:00 rank 2 -> day 1 @ 18:00
|
|
||||||
// rank 3 -> day 0 @ 21:00 rank 4 -> day 1 @ 21:00
|
|
||||||
// rank 5 -> day 0 @ 13:00 rank 6 -> day 1 @ 13:00
|
|
||||||
// rank 7 -> day 2 @ 18:00 rank 8 -> day 3 @ 18:00
|
|
||||||
// rank 9 -> day 2 @ 21:00 rank 10 -> day 3 @ 21:00
|
|
||||||
// ...
|
|
||||||
//
|
|
||||||
// i.e. every three pairs (six clips) the pair of day-blocks advances by two
|
|
||||||
// days and the time cycles back to 18:00.
|
|
||||||
|
|
||||||
// The three posting times, in the order they are handed to pairs.
|
|
||||||
const SLOT_TIMES = ['18:00', '21:00', '13:00'];
|
|
||||||
|
|
||||||
const pad2 = (n) => String(n).padStart(2, '0');
|
|
||||||
|
|
||||||
// Shift a 'YYYY-MM-DD' string by `days`, built from LOCAL date parts so it never
|
|
||||||
// crosses the UTC day boundary the way `new Date(...).toISOString()` would for
|
|
||||||
// users west of Greenwich. Returns null when the input is not a plain date.
|
|
||||||
export function addDays(dateStr, days) {
|
|
||||||
const m = String(dateStr || '').match(/^(\d{4})-(\d{2})-(\d{2})$/);
|
|
||||||
if (!m) return null;
|
|
||||||
const d = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
|
|
||||||
d.setDate(d.getDate() + Number(days));
|
|
||||||
return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
// rank: 1-based position in the virality-ordered results.
|
|
||||||
// Returns { date: 'YYYY-MM-DD', time: 'HH:MM' } in the user's local timezone,
|
|
||||||
// or null when there is no start date / no valid rank.
|
|
||||||
export function scheduleForRank(startDate, rank) {
|
|
||||||
if (!startDate) return null;
|
|
||||||
const r = Number(rank);
|
|
||||||
if (!Number.isInteger(r) || r < 1) return null;
|
|
||||||
|
|
||||||
const pairIndex = Math.floor((r - 1) / 2); // 0 for ranks 1-2, 1 for 3-4, …
|
|
||||||
const time = SLOT_TIMES[pairIndex % 3];
|
|
||||||
// Every three pairs (6 clips) move the two day-blocks forward by two days.
|
|
||||||
const dayOffset = Math.floor(pairIndex / 3) * 2 + ((r - 1) % 2);
|
|
||||||
|
|
||||||
const date = addDays(startDate, dayOffset);
|
|
||||||
if (!date) return null;
|
|
||||||
return { date, time };
|
|
||||||
}
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import { StrictMode, useState, useEffect, lazy, Suspense } from 'react'
|
import { StrictMode, useState, useEffect, lazy, Suspense } from 'react'
|
||||||
import { createRoot } from 'react-dom/client'
|
import { createRoot } from 'react-dom/client'
|
||||||
import './index.css'
|
import './index.css'
|
||||||
|
import Landing from './Landing.jsx'
|
||||||
import { AuthProvider } from './contexts/AuthContext'
|
import { AuthProvider } from './contexts/AuthContext'
|
||||||
import { applyConsent } from './lib/consent'
|
import { applyConsent } from './lib/consent'
|
||||||
import CookieBanner from './components/CookieBanner'
|
import CookieBanner from './components/CookieBanner'
|
||||||
|
|
@ -8,18 +9,33 @@ import CookieBanner from './components/CookieBanner'
|
||||||
const App = lazy(() => import('./App.jsx'))
|
const App = lazy(() => import('./App.jsx'))
|
||||||
const Legal = lazy(() => import('./Legal.jsx'))
|
const Legal = lazy(() => import('./Legal.jsx'))
|
||||||
|
|
||||||
// Boot straight into the app. Only #legal is still a distinct view; every
|
|
||||||
// other hash (including #app, #app?…) renders App.
|
|
||||||
function Root() {
|
function Root() {
|
||||||
const [isLegal, setIsLegal] = useState(() => window.location.hash === '#legal')
|
const resolveView = () => {
|
||||||
|
const hash = window.location.hash || '';
|
||||||
|
if (hash === '#legal') return 'legal';
|
||||||
|
// #landing = explicit landing view (app logo); section anchors keep the landing mounted
|
||||||
|
if (['#landing', '#features', '#how-it-works', '#comparison', '#faq'].includes(hash)) return 'landing';
|
||||||
|
if (hash === '#app' || hash.startsWith('#app?') || localStorage.getItem('clipwright_skip_landing') === '1') return 'app';
|
||||||
|
return 'landing';
|
||||||
|
};
|
||||||
|
|
||||||
|
const [view, setView] = useState(resolveView);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const handleHashChange = () => setIsLegal(window.location.hash === '#legal')
|
const handleHashChange = () => setView(resolveView());
|
||||||
window.addEventListener('hashchange', handleHashChange)
|
window.addEventListener('hashchange', handleHashChange);
|
||||||
return () => window.removeEventListener('hashchange', handleHashChange)
|
return () => window.removeEventListener('hashchange', handleHashChange);
|
||||||
}, [])
|
}, []);
|
||||||
|
|
||||||
return isLegal ? <Legal /> : <App />
|
const handleLaunchApp = () => {
|
||||||
|
localStorage.setItem('clipwright_skip_landing', '1');
|
||||||
|
window.location.hash = '#app';
|
||||||
|
setView('app');
|
||||||
|
};
|
||||||
|
|
||||||
|
if (view === 'legal') return <Legal />;
|
||||||
|
if (view === 'app') return <App />;
|
||||||
|
return <Landing onLaunchApp={handleLaunchApp} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Start whatever the visitor previously agreed to. Nothing at all on a first
|
// Start whatever the visitor previously agreed to. Nothing at all on a first
|
||||||
|
|
|
||||||
|
|
@ -25,7 +25,7 @@ const SIZE_SCALE: Record<string, number> = {
|
||||||
L: 1.3,
|
L: 1.3,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Percentages must match clipwright/media/hooks.py's overlay_y math (top 20% / bottom 70%),
|
// Percentages must match hooks.py's overlay_y math (top 20% / bottom 70%),
|
||||||
// or the preview drifts from what the server path renders.
|
// or the preview drifts from what the server path renders.
|
||||||
const POSITION_STYLE: Record<string, React.CSSProperties> = {
|
const POSITION_STYLE: Record<string, React.CSSProperties> = {
|
||||||
top: { top: "20%", bottom: "auto" },
|
top: { top: "20%", bottom: "auto" },
|
||||||
|
|
@ -33,13 +33,13 @@ const POSITION_STYLE: Record<string, React.CSSProperties> = {
|
||||||
bottom: { top: "70%", bottom: "auto" },
|
bottom: { top: "70%", bottom: "auto" },
|
||||||
};
|
};
|
||||||
|
|
||||||
// Must mirror clipwright/media/hooks.py HOOK_STYLES (the server-side FFmpeg fallback).
|
// Must mirror hooks.py HOOK_STYLES (the server-side FFmpeg fallback).
|
||||||
interface HookLook {
|
interface HookLook {
|
||||||
box: string | null;
|
box: string | null;
|
||||||
text: string;
|
text: string;
|
||||||
outlinePx: number;
|
outlinePx: number;
|
||||||
shadow: boolean;
|
shadow: boolean;
|
||||||
/** One rounded box per line (clipwright/media/hooks.py _draw_pills) instead of one card. */
|
/** One rounded box per line (hooks.py _draw_pills) instead of one card. */
|
||||||
pills?: boolean;
|
pills?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -127,7 +127,7 @@ const HookBox: React.FC<HookBoxProps> = ({ config, displayFrames }) => {
|
||||||
const positionStyle = POSITION_STYLE[config.position] ?? POSITION_STYLE.top;
|
const positionStyle = POSITION_STYLE[config.position] ?? POSITION_STYLE.top;
|
||||||
const look = HOOK_LOOKS[config.style ?? "pill"] ?? HOOK_LOOKS.pill;
|
const look = HOOK_LOOKS[config.style ?? "pill"] ?? HOOK_LOOKS.pill;
|
||||||
|
|
||||||
// Typeface and size as clipwright/media/hooks.py: the chosen font, else the style's own;
|
// Typeface and size as hooks.py: the chosen font, else the style's own;
|
||||||
// font size = factor x the 90%-of-width box.
|
// font size = factor x the 90%-of-width box.
|
||||||
const typeface = HOOK_FONTS[config.font ?? (look.pills ? "montserrat" : "serif")] ?? HOOK_FONTS.serif;
|
const typeface = HOOK_FONTS[config.font ?? (look.pills ? "montserrat" : "serif")] ?? HOOK_FONTS.serif;
|
||||||
const fontSize = Math.round(1080 * 0.9 * typeface.factor * scale);
|
const fontSize = Math.round(1080 * 0.9 * typeface.factor * scale);
|
||||||
|
|
@ -135,7 +135,7 @@ const HookBox: React.FC<HookBoxProps> = ({ config, displayFrames }) => {
|
||||||
|
|
||||||
if (look.pills) {
|
if (look.pills) {
|
||||||
// box-decoration-break: clone gives every wrapped line its own padded,
|
// box-decoration-break: clone gives every wrapped line its own padded,
|
||||||
// rounded box, the same stack clipwright/media/hooks.py draws for the FFmpeg path.
|
// rounded box, the same stack hooks.py draws for the FFmpeg path.
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
|
|
|
||||||
|
|
@ -41,7 +41,7 @@ export const antonFontFace = `
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Hook typefaces: CSS family + share of the 90% box width used as font size.
|
* Hook typefaces: CSS family + share of the 90% box width used as font size.
|
||||||
* Must mirror clipwright/media/hooks.py HOOK_FONTS.
|
* Must mirror hooks.py HOOK_FONTS.
|
||||||
*/
|
*/
|
||||||
export const HOOK_FONTS: Record<string, { family: string; weight: number; factor: number }> = {
|
export const HOOK_FONTS: Record<string, { family: string; weight: number; factor: number }> = {
|
||||||
montserrat: { family: `'${MONTSERRAT_FONT_FAMILY}', 'Montserrat', sans-serif`, weight: 800, factor: 0.064 },
|
montserrat: { family: `'${MONTSERRAT_FONT_FAMILY}', 'Montserrat', sans-serif`, weight: 800, factor: 0.064 },
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,5 @@
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
// --- Word-level caption ---
|
// --- Word-level caption ---
|
||||||
export interface CaptionWord {
|
export interface CaptionWord {
|
||||||
text: string;
|
text: string;
|
||||||
|
|
@ -92,3 +94,66 @@ export interface ShortVideoProps {
|
||||||
hook: HookConfig | null;
|
hook: HookConfig | null;
|
||||||
effects: EffectsConfig | null;
|
effects: EffectsConfig | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Zod schemas for validation (used by render service) ---
|
||||||
|
export const captionWordSchema = z.object({
|
||||||
|
text: z.string(),
|
||||||
|
startMs: z.number(),
|
||||||
|
endMs: z.number(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const subtitleStyleSchema = z.object({
|
||||||
|
fontFamily: z.string(),
|
||||||
|
fontSize: z.number(),
|
||||||
|
fontColor: z.string(),
|
||||||
|
highlightColor: z.string(),
|
||||||
|
borderColor: z.string(),
|
||||||
|
borderWidth: z.number(),
|
||||||
|
bgColor: z.string(),
|
||||||
|
bgOpacity: z.number().min(0).max(1),
|
||||||
|
animation: z.enum(["none", "word-highlight", "pop", "karaoke"]),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const subtitleConfigSchema = z.object({
|
||||||
|
captions: z.array(captionWordSchema),
|
||||||
|
position: z.enum(["top", "middle", "bottom"]),
|
||||||
|
style: subtitleStyleSchema,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const hookConfigSchema = z.object({
|
||||||
|
text: z.string(),
|
||||||
|
position: z.enum(["top", "center", "bottom"]),
|
||||||
|
size: z.enum(["S", "M", "L"]),
|
||||||
|
style: z
|
||||||
|
.enum(["pill", "classic", "dark", "yellow", "red", "outline", "outline_yellow"])
|
||||||
|
.default("pill"),
|
||||||
|
font: z.enum(["montserrat", "anton", "serif"]).optional(),
|
||||||
|
entranceAnimation: z.enum(["spring", "fade", "slide-up", "none"]),
|
||||||
|
displayDurationSec: z.number().positive(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const effectSegmentSchema = z.object({
|
||||||
|
startSec: z.number().min(0),
|
||||||
|
endSec: z.number().positive(),
|
||||||
|
zoom: z.number().min(0.5).max(3),
|
||||||
|
zoomCenterX: z.number().min(0).max(1),
|
||||||
|
zoomCenterY: z.number().min(0).max(1),
|
||||||
|
brightness: z.number().min(0).max(3),
|
||||||
|
contrast: z.number().min(0).max(3),
|
||||||
|
saturate: z.number().min(0).max(3),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const effectsConfigSchema = z.object({
|
||||||
|
segments: z.array(effectSegmentSchema),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const shortVideoPropsSchema = z.object({
|
||||||
|
videoUrl: z.string(),
|
||||||
|
durationInFrames: z.number().int().positive(),
|
||||||
|
fps: z.number().positive(),
|
||||||
|
width: z.number().int().positive(),
|
||||||
|
height: z.number().int().positive(),
|
||||||
|
subtitles: subtitleConfigSchema.nullable(),
|
||||||
|
hook: hookConfigSchema.nullable(),
|
||||||
|
effects: effectsConfigSchema.nullable(),
|
||||||
|
});
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
/* Hallmark · genre: atmospheric · theme: lumen (night foundry) · designed-as-app
|
/* Hallmark · genre: atmospheric · theme: lumen (night foundry) · design-system: design.md · designed-as-app
|
||||||
* macrostructure: Marquee Hero (marketing) / Workbench (app) / Long Document (content)
|
* macrostructure: Marquee Hero (marketing) / Workbench (app) / Long Document (content)
|
||||||
* nav: N9 edge-aligned · footer: Ft5 statement · enrichment: filament apparatus (landing only)
|
* nav: N9 edge-aligned · footer: Ft5 statement · enrichment: filament apparatus (landing only)
|
||||||
* pre-emit critique: P5 H4 E4 S5 R5 V4
|
* pre-emit critique: P5 H4 E4 S5 R5 V4
|
||||||
|
|
|
||||||
|
|
@ -6,14 +6,7 @@ import seo from './vite-plugin-seo'
|
||||||
// name; set VITE_PROXY_TARGET=http://localhost:8000 to run the dev server on
|
// name; set VITE_PROXY_TARGET=http://localhost:8000 to run the dev server on
|
||||||
// the host against a backend reachable at localhost (no CORS, same-origin).
|
// the host against a backend reachable at localhost (no CORS, same-origin).
|
||||||
const backend = process.env.VITE_PROXY_TARGET || 'http://backend:8000'
|
const backend = process.env.VITE_PROXY_TARGET || 'http://backend:8000'
|
||||||
|
const renderer = process.env.VITE_RENDER_TARGET || 'http://renderer:3100'
|
||||||
// Backend target for the *preview* server (the built app). The Playwright
|
|
||||||
// real-backend lane serves `vite preview` and needs same-origin /api, /videos
|
|
||||||
// and /thumbnails to reach a locally-launched uvicorn instead of the compose
|
|
||||||
// service. Defaults to the loopback backend the config's second webServer
|
|
||||||
// starts; CW_BACKEND_URL overrides it for other setups. Proxying keeps the
|
|
||||||
// built bundle origin-relative (no absolute VITE_API_URL baked in).
|
|
||||||
const previewBackend = process.env.CW_BACKEND_URL || 'http://127.0.0.1:8000'
|
|
||||||
|
|
||||||
// https://vitejs.dev/config/
|
// https://vitejs.dev/config/
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
|
|
@ -43,15 +36,7 @@ export default defineConfig({
|
||||||
'/api': { target: backend, changeOrigin: true },
|
'/api': { target: backend, changeOrigin: true },
|
||||||
'/videos': { target: backend, changeOrigin: true },
|
'/videos': { target: backend, changeOrigin: true },
|
||||||
'/thumbnails': { target: backend, changeOrigin: true },
|
'/thumbnails': { target: backend, changeOrigin: true },
|
||||||
}
|
'/render': { target: renderer, changeOrigin: true },
|
||||||
},
|
|
||||||
// Mirror of server.proxy for `vite preview`, so the production bundle talks
|
|
||||||
// to the real backend same-origin (the browser E2E real-backend lane).
|
|
||||||
preview: {
|
|
||||||
proxy: {
|
|
||||||
'/api': { target: previewBackend, changeOrigin: true },
|
|
||||||
'/videos': { target: previewBackend, changeOrigin: true },
|
|
||||||
'/thumbnails': { target: previewBackend, changeOrigin: true },
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
|
||||||
BIN
demo-clipwright.mp4
Normal file
168
design.md
Normal file
|
|
@ -0,0 +1,168 @@
|
||||||
|
# Design — Clipwright
|
||||||
|
|
||||||
|
A locked design system for this app (dashboard + landing). Every page redesign
|
||||||
|
reads this file before emitting code. Do not regenerate per page — extend or
|
||||||
|
amend this file when the system needs to grow.
|
||||||
|
|
||||||
|
Theme: **Lumen · Night Foundry** (Hallmark catalog, atmospheric genre).
|
||||||
|
Register: premium AI-tool instrument (Modal / Anthropic / ElevenLabs school).
|
||||||
|
The product's own numbers — timecodes, aspect ratios, clip counts, costs —
|
||||||
|
are the decoration: they render as UPPERCASE mono readouts.
|
||||||
|
|
||||||
|
## Genre
|
||||||
|
|
||||||
|
atmospheric
|
||||||
|
|
||||||
|
## Macrostructure family
|
||||||
|
|
||||||
|
- Marketing pages (Landing): **Marquee Hero, Lumen-canonical** — lowercase
|
||||||
|
serif headline hero-left with one coral verb-landmark, hand-built CSS
|
||||||
|
apparatus hero-right, meter strip below the fold, then sections with mono
|
||||||
|
eyebrows. Nav: N9 edge-aligned minimal. Footer: Ft5 Statement.
|
||||||
|
- App pages (dashboard tabs, modals): **Workbench** — small functional
|
||||||
|
headings, hairline cards lit from within, mono readouts, zero enrichment.
|
||||||
|
Function carries the page.
|
||||||
|
- Content pages (Legal): **Long Document** — single column, 65ch measure,
|
||||||
|
inline headings, typographic links.
|
||||||
|
|
||||||
|
## Theme tokens (Night Foundry)
|
||||||
|
|
||||||
|
- `--color-paper` oklch(13% 0.014 265) — page canvas, late-night violet
|
||||||
|
- `--color-paper-2` oklch(16.5% 0.015 265) — elevated surface (cards, modals, sidebar)
|
||||||
|
- `--color-paper-3` oklch(20% 0.016 265) — hover surface / inset chips
|
||||||
|
- `--color-ink` oklch(96% 0.006 262) — headlines, near-white
|
||||||
|
- `--color-ink-2` oklch(86% 0.01 262) — body text
|
||||||
|
- `--color-muted` oklch(64% 0.012 262) — secondary text
|
||||||
|
- `--color-rule` oklch(96% 0.006 262 / 0.08) — hairline borders
|
||||||
|
- `--color-rule-2` oklch(96% 0.006 262 / 0.14) — stronger hairline
|
||||||
|
- `--rule-blueprint` oklch(96% 0.006 262 / 0.04) — blueprint grid lines
|
||||||
|
- `--color-accent` oklch(76% 0.17 50) — molten brass (THE accent)
|
||||||
|
- `--color-accent-ink` oklch(17% 0.03 50) — text on brass fills
|
||||||
|
- `--color-accent-2` oklch(68% 0.16 18) — coral chord (verb landmark ONLY + rare secondary)
|
||||||
|
- `--color-glow` oklch(80% 0.16 50 / 0.42) — apparatus halo
|
||||||
|
- `--color-paper-emit` oklch(76% 0.17 50 / 0.04) — inner-emission wash
|
||||||
|
- `--color-focus` oklch(76% 0.17 50) — focus rings
|
||||||
|
- `--color-ok` oklch(75% 0.11 150) — success states
|
||||||
|
- `--color-warn` oklch(78% 0.14 75) — warnings (keys missing, low quota)
|
||||||
|
- `--color-danger` oklch(66% 0.18 25) — errors, destructive
|
||||||
|
|
||||||
|
Tailwind names: `paper, paper2, paper3, ink, ink2, muted, brass, brassink,
|
||||||
|
coral, ok, warn, danger` (+ legacy aliases `background→paper`, `surface→paper2`,
|
||||||
|
`primary→brass`, `accent→coral` so untouched files degrade gracefully).
|
||||||
|
Borders: use `border-rule` / `border-rule2` utilities (defined in index.css).
|
||||||
|
|
||||||
|
## Typography
|
||||||
|
|
||||||
|
- Display: **Instrument Serif 400**, `font-display`, always roman (never italic),
|
||||||
|
**lowercase**, tracking -0.032em, line-height 1.02.
|
||||||
|
- Body: **Geist** 400/500/600, `font-body`.
|
||||||
|
- Mono: **JetBrains Mono** 400/500, `font-mono` — UPPERCASE labels only.
|
||||||
|
- Two-register rule: UI prose (headings, buttons, nav, empty states, helper
|
||||||
|
text) renders **lowercase**; mono labels (eyebrows, badges, readouts, stat
|
||||||
|
labels, keyboard hints) render **UPPERCASE** 10.5–11px tracking 0.10em at
|
||||||
|
~55% opacity. That contrast is the typographic signature.
|
||||||
|
- **NEVER lowercase user content**: video titles, captions, transcripts,
|
||||||
|
descriptions, emails, API keys, log output, filenames, prices in legal copy.
|
||||||
|
Apply `lowercase` class per-element on UI chrome only — no global
|
||||||
|
text-transform on body.
|
||||||
|
- Numerals: `font-variant-numeric: tabular-nums` wherever numbers appear
|
||||||
|
(`tabular-nums` utility). Big stats: Instrument Serif + tabular-nums.
|
||||||
|
- Type scale anchor: `--text-display: clamp(3rem, 6vw + 1rem, 6rem)` (landing
|
||||||
|
hero only). App headings stay small: text-xl/2xl max, serif lowercase.
|
||||||
|
|
||||||
|
## Spacing
|
||||||
|
|
||||||
|
4-point scale via Tailwind defaults (p-2/3/4/6/8/12/16). No arbitrary
|
||||||
|
`text-[9px]`-style values — minimum readable label is 10.5px (`text-micro`
|
||||||
|
utility). Radii: `--radius-card: 10px` (rounded-card), `--radius-input: 8px`
|
||||||
|
(rounded-input), pills `rounded-full` for CTAs and status chips only.
|
||||||
|
|
||||||
|
## Motion
|
||||||
|
|
||||||
|
- Easings: `--ease-out: cubic-bezier(0.16, 1, 0.3, 1)` only. Never `ease`.
|
||||||
|
- Durations: 220ms UI state, 600ms section reveals, 4s apparatus pulse.
|
||||||
|
- Reveal pattern: fade only (`animate-fade`), optional 12px translateY on
|
||||||
|
section entry. No slide-ins, no bounce, no scale-pops.
|
||||||
|
- Cards hover: `translateY(-4px)` + inner-glow brighten, 220ms.
|
||||||
|
- Reduced motion: everything collapses to instant final state.
|
||||||
|
- Focus ring: 2px brass, appears INSTANTLY (never animated).
|
||||||
|
|
||||||
|
## Microinteractions stance
|
||||||
|
|
||||||
|
- Silent success (inline check, quiet state change) — never celebratory.
|
||||||
|
- Buttons: `active:translate-y-px`, no scale tricks.
|
||||||
|
- Hover tooltips delay 800ms; focus tooltips 0ms.
|
||||||
|
- Loaders: `Loader2` lucide spin is fine, tinted `text-muted` or `text-brass`.
|
||||||
|
|
||||||
|
## CTA voice
|
||||||
|
|
||||||
|
- Primary: `.btn-primary` — brass fill, `text-brassink`, `rounded-full`,
|
||||||
|
lowercase label, font-medium. One per view section.
|
||||||
|
- Secondary: `.btn-ghost` — hairline `border-rule2`, ink text, rounded-full.
|
||||||
|
- Tertiary/utility: `.btn-quiet` — `bg-paper3` fill, no border.
|
||||||
|
- Destructive: `.btn-danger` — danger outline, fills on hover.
|
||||||
|
- Labels are verbs, lowercase: "start clipping", "generate", "publish",
|
||||||
|
"download". Never "Get Started!", never Title Case.
|
||||||
|
|
||||||
|
## Component recipes (shared — use these, don't reinvent)
|
||||||
|
|
||||||
|
- `.card` — hairline border + inner emission (radial brass 4–5%), rounded-card,
|
||||||
|
bg-paper2. Hover variant `.card-hover` lifts and brightens. Replaces ALL
|
||||||
|
glass-panel / bg-surface/50 / backdrop-blur cards.
|
||||||
|
- `.eyebrow` — mono UPPERCASE micro label. Section pattern: eyebrow stacked
|
||||||
|
ABOVE the heading, same column (`01 · TOOLS` then the serif heading). Never
|
||||||
|
tag-left/heading-right.
|
||||||
|
- `<Modal>` from `src/components/ui/Modal.jsx` — the ONLY modal shell
|
||||||
|
(overlay plain `bg-black/70`, NO backdrop-blur; panel bg-paper2 hairline).
|
||||||
|
- `<SegmentedControl>` from `src/components/ui/SegmentedControl.jsx` — all
|
||||||
|
option-button grids (position/size/animation pickers, platform toggles).
|
||||||
|
Active state = brass hairline + paper3 fill + ink text. Never bg-white
|
||||||
|
text-black, never per-feature colors.
|
||||||
|
- `<StepIndicator>` from `src/components/ui/StepIndicator.jsx` — the single
|
||||||
|
wizard stepper (ThumbnailStudio + SaaShortsTab share it). Mono ordinals.
|
||||||
|
- `.input-field` — inset bg-paper, hairline, focus brass ring (redefined in
|
||||||
|
index.css; existing class name kept).
|
||||||
|
- `.readout` — mono UPPERCASE value chip for machine data (timecodes, costs,
|
||||||
|
ratios, model names): `00:42 · 9:16 · $0.65`.
|
||||||
|
- Status: `.badge-ok` / `.badge-warn` / `.badge-danger` — tinted 10% fills,
|
||||||
|
mono uppercase.
|
||||||
|
|
||||||
|
## What pages MUST share
|
||||||
|
|
||||||
|
- Single accent: brass. Coral ONLY as the headline verb-landmark (landing) and
|
||||||
|
at most one small secondary highlight per view. NOTHING ELSE gets a hue.
|
||||||
|
- Zero gradients (text or background). Zero glassmorphism / backdrop-blur
|
||||||
|
panels. Zero per-feature identity colors (the old violet/emerald/amber/teal
|
||||||
|
per-tab coding is retired — tools are differentiated by mono eyebrow ordinals
|
||||||
|
`01 · CLIPS`, `02 · PUBLISHING`, not by hue).
|
||||||
|
- The two-register typography (lowercase prose / UPPERCASE mono labels).
|
||||||
|
- The CTA voice, radii, hairline card language.
|
||||||
|
- English copy everywhere (ScheduleWeekModal migrates from Spanish).
|
||||||
|
- Lucide icons at 16–18px, `text-muted` default, brass when active.
|
||||||
|
|
||||||
|
## What pages MAY differ on
|
||||||
|
|
||||||
|
- Landing may use enrichment: ONE hand-built CSS apparatus (filament chamber
|
||||||
|
reading as a 9:16 clip instrument) + blueprint grid + meter strip. App pages
|
||||||
|
get NONE of these (no grid bg, no apparatus, no meter) — except ProcessingAnimation,
|
||||||
|
which keeps its scanner HUD but re-tinted to brass/ink tokens.
|
||||||
|
- Legal is typography-only.
|
||||||
|
|
||||||
|
## Hard bans (Lumen)
|
||||||
|
|
||||||
|
No italics anywhere. No gradient text. No gradient buttons. No backdrop-blur.
|
||||||
|
No glowing orbs. No invented metrics (existing cited stats/prices are the
|
||||||
|
brief's real copy — keep them). No emoji as icons in chrome (existing emoji
|
||||||
|
option labels in SaaShorts pickers may stay as content). No rounded-2xl
|
||||||
|
soup — use rounded-card/rounded-input/rounded-full deliberately. No
|
||||||
|
`bg-[#121214]`-style hardcoded colors — tokens only. No Title Case UI copy.
|
||||||
|
|
||||||
|
## Functional contract (NEVER break)
|
||||||
|
|
||||||
|
Hash routing (`#app`, `#/pricing`, `#/account`, `#legal`, `#features`,
|
||||||
|
`#how-it-works`, `#pricing`, `#comparison`, `#faq` anchors), `billingEnabled` /
|
||||||
|
`isManaged` / `isSignedIn` gating, all handlers and props, localStorage keys
|
||||||
|
(`gemini_key`, `postiz_url`, `postiz_key_v1`, `elevenLabsKey_v1`,
|
||||||
|
`uploadUserId`, `clipwright_session`, `clipwright_auth`,
|
||||||
|
`clipwright_skip_landing`), API calls and BYOK headers, QuotaError flows,
|
||||||
|
Remotion preview/render wiring. Redesign is classes + markup structure only.
|
||||||
19
docker-compose.e2e.local.yml
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
# Local-only override: remap host ports to avoid clashes with other running
|
||||||
|
# projects (e.g. another backend on :8000). Not for production.
|
||||||
|
# `!override` REPLACES the base ports list instead of appending to it.
|
||||||
|
services:
|
||||||
|
backend:
|
||||||
|
ports: !override
|
||||||
|
- "8001:8000"
|
||||||
|
environment:
|
||||||
|
# Point auth/magic-link/CORS at the local frontend instead of git.pbento.pt/pedro-bento/clipwright.
|
||||||
|
- FRONTEND_URL=http://localhost:5176
|
||||||
|
- ALLOWED_ORIGINS=http://localhost:5176,http://localhost:5175,http://localhost:8001
|
||||||
|
frontend:
|
||||||
|
ports: !override
|
||||||
|
- "5176:5173"
|
||||||
|
environment:
|
||||||
|
# Call the backend directly (not via the Vite proxy) so Google OAuth builds
|
||||||
|
# a redirect_uri of http://localhost:8001/... which matches the registered
|
||||||
|
# client. Cross-origin API calls are allowed by ALLOWED_ORIGINS above.
|
||||||
|
- VITE_API_URL=http://localhost:8001
|
||||||