Compare commits
3 commits
80e59db429
...
09a0c58e14
| Author | SHA1 | Date | |
|---|---|---|---|
| 09a0c58e14 | |||
| 0d961ba019 | |||
| 6721d853ef |
39 changed files with 565 additions and 4800 deletions
13
.env.example
13
.env.example
|
|
@ -1,9 +1,3 @@
|
||||||
# AWS S3 (optional — for clip backup)
|
|
||||||
AWS_ACCESS_KEY_ID=your_aws_access_key_here
|
|
||||||
AWS_SECRET_ACCESS_KEY=your_aws_secret_key_here
|
|
||||||
AWS_REGION=eu-west-3
|
|
||||||
AWS_S3_BUCKET=your-bucket-name
|
|
||||||
|
|
||||||
# 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=...
|
||||||
|
|
||||||
|
|
@ -116,11 +110,6 @@ GEMINI_IMAGE_MODEL=gemini-3.1-flash-image
|
||||||
# disables it. Do not add "preload" without understanding that it is one-way.
|
# disables it. Do not add "preload" without understanding that it is one-way.
|
||||||
# HSTS_HEADER=max-age=31536000; includeSubDomains
|
# HSTS_HEADER=max-age=31536000; includeSubDomains
|
||||||
|
|
||||||
# Encrypted PostgreSQL backups (ops/pg_backup.sh — installed and scheduled on
|
# Optional PostgreSQL database (only needed if you run the app against one).
|
||||||
# the database host, not by the app).
|
|
||||||
# DATABASE_URL=postgres://user:pass@host:5432/clipwright
|
# 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
|
|
||||||
|
|
||||||
|
|
|
||||||
19
.github/workflows/ci.yml
vendored
19
.github/workflows/ci.yml
vendored
|
|
@ -8,22 +8,25 @@ on:
|
||||||
jobs:
|
jobs:
|
||||||
backend-tests:
|
backend-tests:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
# The Forgejo runner cannot provision Python 3.11 via actions/setup-python
|
||||||
|
# ("Version 3.11 was not found in the local cache"), so the job runs inside
|
||||||
|
# a container that already has Python 3.11. It must also ship Node and git:
|
||||||
|
# the runner executes JS actions (actions/checkout) by invoking `node`
|
||||||
|
# inside the job container, so a python-only image fails at checkout.
|
||||||
|
container: nikolaik/python-nodejs:python3.11-nodejs20
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: actions/setup-python@v5
|
|
||||||
with:
|
|
||||||
python-version: "3.11"
|
|
||||||
# Everything the collected tests import at module level, WITHOUT the
|
# Everything the collected tests import at module level, WITHOUT the
|
||||||
# heavy ML stack (torch/ultralytics/mediapipe/faster-whisper) — the
|
# heavy ML stack (torch/ultralytics/mediapipe/faster-whisper) — the
|
||||||
# pipeline modules import those lazily behind their feature gates, and
|
# pipeline modules import those lazily behind their feature gates, and
|
||||||
# the tests exercise the gated-off paths. numpy+opencv cover the layout
|
# the tests exercise the gated-off paths. numpy+opencv cover the layout
|
||||||
# modules, fastapi/boto3/PyJWT/python-multipart cover importing app.py
|
# modules, fastapi/python-multipart cover importing app.py for the MCP
|
||||||
# for the MCP endpoint tests, google-genai covers gemini_worker.
|
# endpoint tests, google-genai covers gemini_worker.
|
||||||
- name: Install test dependencies
|
- name: Install test dependencies
|
||||||
run: >
|
run: >
|
||||||
pip install pytest pillow httpx pydantic sqlalchemy greenlet numpy
|
pip install pytest pillow httpx pydantic numpy
|
||||||
opencv-python-headless python-dotenv google-genai fastapi boto3
|
opencv-python-headless python-dotenv google-genai fastapi
|
||||||
PyJWT email-validator python-multipart
|
python-multipart
|
||||||
- name: Run tests
|
- name: Run tests
|
||||||
run: pytest tests/ -v
|
run: pytest tests/ -v
|
||||||
|
|
||||||
|
|
|
||||||
10
.gitignore
vendored
10
.gitignore
vendored
|
|
@ -33,14 +33,16 @@ output/
|
||||||
# Cache dirs
|
# Cache dirs
|
||||||
.cache/
|
.cache/
|
||||||
.config/
|
.config/
|
||||||
|
.pytest_cache/
|
||||||
|
|
||||||
# Multi-agent Skills
|
# Multi-agent Skills
|
||||||
.agents/
|
.agents/
|
||||||
.agent/
|
.agent/
|
||||||
.claude/
|
.claude/
|
||||||
# skills/ holds third-party installs (symlinks); our own published skill is versioned
|
|
||||||
skills/*
|
# Design-tool / agent-local state
|
||||||
!skills/clipwright/
|
.hallmark/
|
||||||
skills-lock.json
|
.opencode/
|
||||||
|
|
||||||
|
|
||||||
# Cloud env example kept local only (avoid leaking infra hints)
|
# Cloud env example kept local only (avoid leaking infra hints)
|
||||||
|
|
|
||||||
|
|
@ -1,3 +0,0 @@
|
||||||
[
|
|
||||||
{ "date": "2026-07-17", "scope": "app", "macrostructure": "Marquee Hero (marketing) / Workbench (app) / Long Document (content)", "theme": "lumen", "drop": "night", "enrichment": "filament-chamber apparatus + meter strip (landing only)", "brief": "Clipwright · full app + landing redesign, design.md-managed" }
|
|
||||||
]
|
|
||||||
600
CLAUDE.md
600
CLAUDE.md
|
|
@ -1,600 +0,0 @@
|
||||||
# CLAUDE.md
|
|
||||||
|
|
||||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
|
||||||
|
|
||||||
## Project Overview
|
|
||||||
|
|
||||||
Clipwright is an AI-powered vertical video editor that transforms long YouTube videos or local uploads into viral-ready short clips (9:16 format) for TikTok, Instagram Reels, and YouTube Shorts. It also includes YouTube Studio (titles, thumbnails, descriptions) and publishes through a self-hosted Postiz instance. Uses Google Gemini 3.1 Flash-Lite (`gemini-3.1-flash-lite`, overridable with `GEMINI_MODEL`) for viral moment detection and title generation.
|
|
||||||
|
|
||||||
## Development Commands
|
|
||||||
|
|
||||||
### Local Development (Docker)
|
|
||||||
```bash
|
|
||||||
docker compose up --build # Build and run full stack
|
|
||||||
```
|
|
||||||
- Backend: http://localhost:8000 (FastAPI/Uvicorn)
|
|
||||||
- Frontend: http://localhost:5175 (Vite proxies API calls to backend)
|
|
||||||
|
|
||||||
### Frontend Only (Dashboard)
|
|
||||||
```bash
|
|
||||||
cd dashboard
|
|
||||||
npm install
|
|
||||||
npm run dev # Dev server with HMR (port 5173)
|
|
||||||
npm run build # Production build
|
|
||||||
npm run lint # ESLint (strict, --max-warnings 0)
|
|
||||||
```
|
|
||||||
|
|
||||||
### Backend Only
|
|
||||||
```bash
|
|
||||||
pip install -r requirements.txt
|
|
||||||
uvicorn app:app --host 0.0.0.0 --port 8000
|
|
||||||
```
|
|
||||||
|
|
||||||
## Architecture
|
|
||||||
|
|
||||||
### Core Processing Pipeline
|
|
||||||
1. **Ingest** - YouTube download (yt-dlp) or local upload
|
|
||||||
2. **Transcription** - faster-whisper with word-level timestamps
|
|
||||||
3. **Scene Detection** - PySceneDetect for segment boundaries
|
|
||||||
4. **AI Analysis** - Gemini identifies 3-15 viral moments (15-60 sec each)
|
|
||||||
5. **FFmpeg Extraction** - Precise clip cutting
|
|
||||||
6. **AI Cropping** - Vertical reframing with subject tracking
|
|
||||||
7. **Effects/Subtitles** - Optional AI-generated FFmpeg filters
|
|
||||||
8. **Hook Overlay** - Text overlays with styled fonts
|
|
||||||
9. **Voice Dubbing** - Optional ElevenLabs AI translation (30+ languages)
|
|
||||||
10. **S3 Backup** - Silent background upload
|
|
||||||
11. **Social Distribution** - Self-hosted Postiz (clip uploaded, then scheduled or posted)
|
|
||||||
|
|
||||||
### Key Files
|
|
||||||
| File | Purpose |
|
|
||||||
|------|---------|
|
|
||||||
| `main.py` | Core video processing: transcription, scene detection, clip extraction, vertical reframing |
|
|
||||||
| `app.py` | FastAPI server with async job queue and REST endpoints |
|
|
||||||
| `editor.py` | Gemini AI integration for dynamic video effects (FFmpeg filter generation) |
|
|
||||||
| `hooks.py` | Hook text overlay generation with font rendering |
|
|
||||||
| `s3_uploader.py` | AWS S3 upload with caching |
|
|
||||||
| `subtitles.py` | SRT generation, FFmpeg subtitle burning, and dubbed video transcription |
|
|
||||||
| `translate.py` | ElevenLabs dubbing API for AI voice translation |
|
|
||||||
| `dashboard/src/App.jsx` | Main React component with state management |
|
|
||||||
| `dashboard/src/components/TranslateModal.jsx` | Voice dubbing UI with language selection |
|
|
||||||
| `dashboard/vite-plugin-seo.js` | Build-time SEO surface: injects crawler-visible homepage content, emits static pages, sitemap.xml and llms.txt |
|
|
||||||
| `dashboard/seo/data.js` | Single source of truth for pricing, pipeline and competitor facts used by every generated page |
|
|
||||||
|
|
||||||
### SEO / AI-crawler surface
|
|
||||||
|
|
||||||
The dashboard is a client-rendered SPA with hash routing, so the HTML served for
|
|
||||||
`/` used to contain an empty `<div id="root">`. Googlebot renders JavaScript and
|
|
||||||
saw the real page; GPTBot, ClaudeBot and PerplexityBot do not and measured the
|
|
||||||
homepage as zero characters of text. `vite-plugin-seo.js` fixes that at build time:
|
|
||||||
|
|
||||||
- Injects the content of `seo/landing-fallback.js` into `#root`. React's
|
|
||||||
`createRoot().render()` replaces it on mount, so users get the app and
|
|
||||||
non-executing clients get the copy. **Keep it in sync with `Landing.jsx`.**
|
|
||||||
- Emits the standalone pages (the `/alternatives` cluster, the clip-generator,
|
|
||||||
open-source and use-case pages; the full list is
|
|
||||||
`buildPages()` in `seo/pages.js`) as flat `.html` files.
|
|
||||||
nginx resolves the clean URL through `try_files $uri $uri.html`; serving them as
|
|
||||||
directories instead makes nginx 301 to a trailing slash and every canonical
|
|
||||||
would then point at a redirect.
|
|
||||||
- Generates `sitemap.xml` and `llms.txt` from the same page list, so they cannot
|
|
||||||
drift. Do not add a static `public/sitemap.xml` back.
|
|
||||||
|
|
||||||
When editing pricing anywhere, edit `seo/data.js` too. Clipwright has a single
|
|
||||||
self-hosted edition: free and open source under MIT. Do not reintroduce a hosted
|
|
||||||
or paid tier into the copy.
|
|
||||||
|
|
||||||
### Free tools (/tools) and SEO attribution
|
|
||||||
|
|
||||||
- `free_tools.py` (router always mounted): `GET /api/tools/youtube-transcript`
|
|
||||||
reads the captions a video **already has** on YouTube via yt-dlp (never the
|
|
||||||
GPU, never media). Routes: the `STATIC_PROXY_URLS` only (anonymous, then the
|
|
||||||
cookies), direct when there are none; **never** the per-GB `PROXY_URL`. A
|
|
||||||
static that answers with zero formats and zero captions is a degraded route,
|
|
||||||
not a "no captions" verdict (seen on one of the three statics, 23-sep-2026).
|
|
||||||
`POST /api/tools/youtube-metadata` = one Gemini text call (tags / titles /
|
|
||||||
description) with the managed key. Per-IP windows + global daily cap per tool,
|
|
||||||
24 h cache (also for "no captions"/"unavailable").
|
|
||||||
- Pages: `seo/tools.js` (hub + 3 tools). A tool page carries
|
|
||||||
`tool: {entry, html}`:
|
|
||||||
the form is in the static HTML, the behaviour is a Vite entry in
|
|
||||||
`dashboard/tools/*.js` (`vite.config.js` rollupOptions.input) that
|
|
||||||
`vite-plugin-seo.js` looks up by name in the bundle. The 9:16 converter runs
|
|
||||||
in the browser with mediabunny/WebCodecs (no upload).
|
|
||||||
- Attribution: `seo/render.js` writes the same first-touch `cw_attrib` key the
|
|
||||||
app writes, from the static page the visit started on. Before, every signup
|
|
||||||
was credited to "/" (7,481/7,481 rows, 30 days to 23-sep-2026). Signup,
|
|
||||||
CheckoutStarted and Subscribed carry `landing_path`/`referrer_host`/utm as
|
|
||||||
OpenPanel props (`lib/analytics.js`).
|
|
||||||
- Apex→www: 301 comes from the front app's **stored Coolify custom labels**
|
|
||||||
(`redirectregex.permanent=true`, patched 23-sep-2026). The nginx 301 block
|
|
||||||
below never sees the apex while that Traefik middleware exists.
|
|
||||||
|
|
||||||
### Cómo se elige el layout
|
|
||||||
|
|
||||||
`POST /api/process` acepta `layouts`: una lista (JSON) o cadena separada por
|
|
||||||
comas con `auto`, `split`, `screencast`, `speaker_cut`, `punch_in` y `none`.
|
|
||||||
Cada nombre enciende su variable de entorno para **ese** trabajo
|
|
||||||
(`app.py:layout_env`); `none` apaga el picker aunque prod corra con
|
|
||||||
`AUTO_LAYOUT=1` (recorte simple y nada más). Sin `layouts` manda el env del
|
|
||||||
despliegue, que desde el 25-ago-2026 es `AUTO_LAYOUT=1`. El dashboard lo expone
|
|
||||||
en opciones avanzadas ("vertical layout": auto / split / screencast / none,
|
|
||||||
`MediaInput.jsx`, recordado en `localStorage.cw_layout`).
|
|
||||||
|
|
||||||
`auto` activa `layout_picker.py`: **una** llamada a Gemini por vídeo de origen
|
|
||||||
(no por clip) que elige entre `none` / `screencast` / `split`. Medido sobre el
|
|
||||||
corpus de 48 contra etiquetas revisadas a mano: 94% / 92% / 96% en tres pasadas,
|
|
||||||
con 0-1 falsos positivos sobre los 28 clips que no deben tocarse, y solo 2 clips
|
|
||||||
que cambian de respuesta entre pasadas.
|
|
||||||
|
|
||||||
**Manda 12 fotogramas a 1024px, no el vídeo.** Gemini factura vídeo a ~300
|
|
||||||
tokens por segundo: una hora de fuente son ~1,08M de tokens (no cabe en una
|
|
||||||
ventana de 1M) y una subida de 1-2 GB para recibir una palabra. Doce fotogramas
|
|
||||||
cuestan ~3k tokens **dure lo que dure la fuente**, que es lo que hace viable
|
|
||||||
esto con los podcasts de una hora que entran de verdad. La resolución importa y
|
|
||||||
el número de fotogramas no: a 640px detecta 15 de 20 (una hoja de cálculo es
|
|
||||||
ilegible), a 1024px sube a 17, y pasar a 24 fotogramas lo empeora. A 1024px la
|
|
||||||
diferencia con mandar el vídeo entero cae dentro de la varianza que ya tiene el
|
|
||||||
propio modo vídeo, a 2,2 s por clip en vez de ~15 s.
|
|
||||||
|
|
||||||
Lo que hace que funcione, y que conviene no deshacer: se le pide una **decisión
|
|
||||||
entre opciones cerradas**, no una medida. Los cuatro intentos anteriores (Canny,
|
|
||||||
MSER, cobertura temporal, anchura) le pedían un número y ninguno separó una hoja
|
|
||||||
de cálculo de un marcador de esquina. La varianza que este repo atribuía a
|
|
||||||
Gemini era de las medidas continuas, no del modelo.
|
|
||||||
|
|
||||||
`layout_picker.apply()` sólo **añade**: una elección explícita del usuario nunca
|
|
||||||
se desactiva porque el modelo diga `none`.
|
|
||||||
|
|
||||||
### Hook grounding for on-screen clips (`hook_grounding.py`)
|
|
||||||
|
|
||||||
The hook and title come from the detail pass, which only reads the
|
|
||||||
transcript, so on a clip whose meaning is on the screen (a settings dialog,
|
|
||||||
a spreadsheet) they summarise the video's topic instead of naming what is
|
|
||||||
shown. After the render, if the `<clip>.layout.json` sidecar says at least
|
|
||||||
25% of the clip is `screencast` / `wide` / `inset` (plus `general` when the
|
|
||||||
layout picker called the video a screencast: a face-less scene there is a
|
|
||||||
slide or a dialog, not a group shot), three frames from those
|
|
||||||
stretches at 1024px plus the clip's own words go to Gemini
|
|
||||||
(`GroundedHook`) and `viral_hook_text` / `video_title_for_youtube_short`
|
|
||||||
are rewritten in place before `auto_hook_clip` burns them; the originals
|
|
||||||
stay under `hook_grounding.before`. Gemini-only (frames): with just a local
|
|
||||||
LLM it logs one line and keeps the transcript hook. `HOOK_GROUNDING=0`
|
|
||||||
disables it. The detail prompt itself now carries the rule "about this
|
|
||||||
moment, not the video", which is the cheap half of the same fix.
|
|
||||||
|
|
||||||
### How many clips a job returns (`clip_selection.py`)
|
|
||||||
|
|
||||||
The count is not a setting, it is derived, and every stage of the derivation
|
|
||||||
used to leak. `get_viral_clips` builds ~90s scoring windows over the
|
|
||||||
transcript, scores them in batches, shortlists the best `shortlist_target`
|
|
||||||
(`min(10, duration//90 + 2)`, floor 3) and asks the detail pass for
|
|
||||||
`clip_count_targets(len(shortlist))` clips — a floor that matters because
|
|
||||||
users who got 1-3 clips came back a second day 0.4% of the time against
|
|
||||||
16.1% for 4-9.
|
|
||||||
|
|
||||||
Two things broke that chain, both found on a 9:10 source on 22-sep-2026 that
|
|
||||||
delivered 3 clips in prod:
|
|
||||||
|
|
||||||
- **The scoring pass selected instead of ranking.** Its prompt said "choose up
|
|
||||||
to 3 windows from this batch", so the shortlist ceiling was
|
|
||||||
`3 * n_batches`, not the target: 9 windows batched 8 + 1 gave 3 + 1 = 4
|
|
||||||
against a target of 8, and `clip_count_targets` then asked for 4-8 clips
|
|
||||||
instead of 6-12. Every source under ~30 min was starved this way — this is
|
|
||||||
the mechanism behind "95% of jobs deliver 3 clips or fewer". It also threw
|
|
||||||
away the ranking it was computing, since a batch of five great moments
|
|
||||||
could still only contribute three. The prompt now scores **every** window
|
|
||||||
and the shortlist is the global top N. Batches are near-equal
|
|
||||||
(`score_batches`) for the same reason the cap is gone: a trailing batch of
|
|
||||||
one window returned that window whatever its score, so the tail of the
|
|
||||||
video entered the shortlist by arithmetic.
|
|
||||||
- **The clip floor was only a sentence in the prompt.** Nothing in code
|
|
||||||
checked it, so a detail pass that returned half was shipped as-is. When it
|
|
||||||
comes back under `min_clips`, the shortlist windows that produced nothing
|
|
||||||
get one more call for the difference. An empty answer is accepted: that is
|
|
||||||
material that genuinely holds no more, and padding is worse than a short
|
|
||||||
list.
|
|
||||||
|
|
||||||
Measured on that source, same transcript, three runs: shortlist 4 → 8 and
|
|
||||||
4 clips → 6, at the same cost (~$0.005, 3 calls). `target_clips` on
|
|
||||||
`/api/process` (dashboard: advanced options) still pins both ends via
|
|
||||||
`CLIP_TARGET_MIN`/`MAX` when the user wants an exact number.
|
|
||||||
|
|
||||||
### Silent footage: the vision fallback (`main.get_visual_clips`)
|
|
||||||
|
|
||||||
The moment picker reads the transcript, so a video with nothing said in it
|
|
||||||
would score nothing. `main.py` switches paths by itself instead, and the
|
|
||||||
switch is the part worth knowing because it is not only "no audio track":
|
|
||||||
`transcribe_video` raising `NoAudioError`, **and** `speech_is_sparse()`
|
|
||||||
coming back true, both set `transcript = None` and route to
|
|
||||||
`get_visual_clips`. Sparse means under `MIN_SPEECH_WORDS` (8) in total or
|
|
||||||
under `MIN_SPEECH_WORDS_PER_MIN` (5). Music-only footage and a session
|
|
||||||
recorded with the mic muted transcribe to a handful of stray words, which
|
|
||||||
is worse than silence: without that second test the picker scores those
|
|
||||||
words and cuts around them.
|
|
||||||
|
|
||||||
The vision pass uploads the video, Gemini watches it and returns the same
|
|
||||||
`{"shorts"}` shape (`gemini_worker.VisualResponse`) in the same 15-60s
|
|
||||||
band, so every stage after it is byte-identical: layouts, inset detection,
|
|
||||||
hooks. `CLIP_TARGET_MIN`/`MAX` apply directly here rather than being
|
|
||||||
derived from scoring windows, because there are none. The transcript is
|
|
||||||
stored as `{"language": "none", "segments": []}`, so the clips come out
|
|
||||||
with no subtitles, which is correct and not a bug.
|
|
||||||
|
|
||||||
**This is the one stage that sends Gemini the video instead of frames, and
|
|
||||||
that is deliberate** — 12 frames can say what kind of video this is (which
|
|
||||||
is all the layout picker needs), they cannot say which 40 seconds to cut.
|
|
||||||
The cost is the ceiling: Gemini bills video at ~300 tokens/second, so an
|
|
||||||
hour is ~1.08M tokens, past a 1M window, and **nothing guards the length**.
|
|
||||||
A silent multi-hour source fails at the model rather than politely. If that
|
|
||||||
needs fixing, the answer is a guard or segmenting the source, not porting
|
|
||||||
the frame trick over from the layout picker. Gemini-only either way: a
|
|
||||||
text-only `LLM_BASE_URL` server cannot see footage, and with no
|
|
||||||
`GEMINI_API_KEY` the function logs one line and returns None, which fails
|
|
||||||
the job outright.
|
|
||||||
|
|
||||||
The public `/gta-5-clips` page states these thresholds and this ceiling to
|
|
||||||
users; if the behaviour changes, change `dashboard/seo/pages.js` too.
|
|
||||||
|
|
||||||
### Local LLM for the moment picker (`llm_backend.py`)
|
|
||||||
|
|
||||||
`LLM_BASE_URL` (+ `LLM_MODEL`, `LLM_API_KEY`) routes the two transcript
|
|
||||||
passes of `get_viral_clips` to any OpenAI-compatible `/chat/completions`
|
|
||||||
instead of Gemini; the response is validated with the same pydantic schemas
|
|
||||||
Gemini enforces server-side, so `main.py` sees one shape. `main.score_batch_size`
|
|
||||||
drops to 3 windows per call there (local contexts are 4-8k; a truncated
|
|
||||||
prompt scores garbage silently). Self-host `/api/process` then accepts a
|
|
||||||
request without `X-Gemini-Key` and `/api/config.localLlm` tells the dashboard
|
|
||||||
not to demand one. Frame-based stages (`layout_picker`, `screencast_layout`,
|
|
||||||
`get_visual_clips`) stay on Gemini and degrade as they always did without a
|
|
||||||
key. On a self-hosted instance it is always available.
|
|
||||||
|
|
||||||
### Thumbnail Studio (`thumbnail.py`, `/api/thumbnail/*`)
|
|
||||||
|
|
||||||
Titles come from the transcript plus 10 frames at 1024px, never the whole
|
|
||||||
video (same reasoning as the layout picker: an hour of video is ~1M tokens for
|
|
||||||
a text task). Two calls: a 25-title brainstorm across fixed styles, then a
|
|
||||||
critic that scores, dedupes by angle and returns 10, each paired with a 1-4
|
|
||||||
word `thumbnail_text` that complements the title rather than repeating it.
|
|
||||||
Rules baked in: payoff inside 50 characters (phones cut there), keyword in the
|
|
||||||
first 3 words, same language as the transcript. Text model is
|
|
||||||
`GEMINI_MODEL_THUMBNAIL` (default `gemini-3.7-flash`), deliberately not
|
|
||||||
`GEMINI_MODEL`: flash-lite is fine for a closed-choice layout pick and visibly
|
|
||||||
worse at creative titles. Image model is `GEMINI_IMAGE_MODEL` (default
|
|
||||||
`gemini-3.1-flash-image`).
|
|
||||||
|
|
||||||
Thumbnails are `count` **different concepts**, not one prompt repeated: a text
|
|
||||||
call designs each (hook text, side for the text, palette, scene prompt), then
|
|
||||||
one image call per concept in parallel. By default (`burn_text=true`) the
|
|
||||||
image model is told to leave that side as negative space and PIL sets the text
|
|
||||||
in Anton with a black stroke, so accents and spelling are never wrong; the
|
|
||||||
`AI painted` toggle lets the model render the text itself. Every output is
|
|
||||||
cover-cropped to 1280x720 and saved under YouTube's 2 MB limit.
|
|
||||||
`GET /api/thumbnail/frames/{session}` scores sampled frames by face area and
|
|
||||||
sharpness (MediaPipe + Laplacian), keeps them spread across the runtime, and
|
|
||||||
the dashboard offers them as the person reference so the thumbnail shows the
|
|
||||||
creator instead of a stranger; an uploaded face photo still wins.
|
|
||||||
|
|
||||||
### Video Reframing Modes
|
|
||||||
|
|
||||||
**A source already shot vertical is passed through untouched.**
|
|
||||||
`reframe_v2.source_already_fits()` gates it: every layout below reorganises the
|
|
||||||
frame to buy back width the crop threw away, and on a 9:16 upload there is none
|
|
||||||
to buy. GENERAL was the visible failure — its 0.42 height ratio, which buys
|
|
||||||
presence on a landscape source by overflowing the sides, scaled a 1080x1920
|
|
||||||
source down to a 453px sliver floating over a blurred copy of itself, and the
|
|
||||||
scene classifier routes every face-less shot (a slide, a screen recording) there.
|
|
||||||
So the picker is skipped (one Gemini call saved per upload), the classifier is
|
|
||||||
skipped, and every scene renders TRACK, whose crop is the whole frame.
|
|
||||||
`general_filtergraph` additionally floors the foreground at the height where the
|
|
||||||
source fills the output width, so the editor's explicit GENERAL override on a
|
|
||||||
portrait clip cannot reproduce the shrink either.
|
|
||||||
|
|
||||||
- **TRACK Mode** (single subject): MediaPipe face detection + YOLOv8 fallback with "Heavy Tripod" stabilization
|
|
||||||
- **GENERAL Mode** (groups/landscapes): Blurred background layout preserving full width
|
|
||||||
- **SPLIT Mode** (two-shot conversation, `split_layout.py`): both speakers stacked
|
|
||||||
in half-frames. Off by default (`SPLIT_LAYOUT=1`); v2 engine only, so a
|
|
||||||
fallback to the v1 loop silently renders GENERAL instead. It upgrades scenes
|
|
||||||
the classifier already sent to GENERAL, never TRACK ones, and needs both faces
|
|
||||||
visible **in the same frame** for at least half the sampled frames — that is
|
|
||||||
what separates a real two-shot from a plano/contraplano, where stacking would
|
|
||||||
show the same person twice. `SPLIT_TIGHTNESS` (default 0.8) trades a little
|
|
||||||
upscale for keeping the other speaker out of each half. Captions on a SPLIT
|
|
||||||
stretch sit on the seam between the halves (`{\an5}` per word event in
|
|
||||||
`subtitles.generate_ass`), the one place they cover nobody; the render
|
|
||||||
records which stretches are stacked in a `<clip>.layout.json` sidecar
|
|
||||||
(`layout_ranges.py`) and every metadata writer copies it into the clip's
|
|
||||||
`layout_ranges`, so `/api/subtitle` finds it after a restyle too. The fast
|
|
||||||
rerender (cut without reframe) carries the canonical clip's ranges through
|
|
||||||
the new cut (`layout_ranges.remap`, in `recut.perform_recut`). Only the
|
|
||||||
ASS path can do this; SRT burns keep one alignment for the whole file.
|
|
||||||
- **SCREENCAST / WIDE Modes** (`screencast_layout.py`, `SCREENCAST_LAYOUT=1`):
|
|
||||||
for scenes whose meaning lives outside the centre. Gemini reports each range's
|
|
||||||
**width_fraction**, and that is the gate — coverage was tried before and did
|
|
||||||
not separate a spreadsheet from a corner ticker, while width does (a bug spans
|
|
||||||
~15% and survives any crop, a spreadsheet spans ~100% and cannot). Content
|
|
||||||
narrower than 0.5 moves nothing. Between 0.5 and 0.85 there is room beside the
|
|
||||||
content, so SCREENCAST stacks it over the presenter. Above 0.85 the presenter
|
|
||||||
is composited **on top of** the content and stacking would show it twice, so
|
|
||||||
those scenes get WIDE: the GENERAL layout with side-cropping disabled.
|
|
||||||
- **INSET Mode** (`camera_inset.py`): pantalla a ancho completo arriba, el
|
|
||||||
recuadro de la webcam ampliado abajo. Para el caso de una sola fuente con la
|
|
||||||
cámara compuesta en una esquina (OBS, VOD de stream). Se encadena detrás de
|
|
||||||
la decisión `screencast`, **no** se le pregunta a Gemini: ofrecido como cuarta
|
|
||||||
opción respondió `screencast` en los 5 clips que tienen recuadro, en dos
|
|
||||||
pasadas, y la exactitud global cayó de 92% a 83-85%. El detector geométrico
|
|
||||||
encuentra esos 5 sin falsos positivos. Los tres filtros que hacen falta, cada
|
|
||||||
uno pagado con una iteración: sujeto **pequeño**, **descentrado en
|
|
||||||
horizontal** (una cara de talking head está centrada aunque esté alta), y
|
|
||||||
**quieto entre muestras** (3-11px frente a 316px de una persona real).
|
|
||||||
- **ALTERNATE Mode** (`active_speaker.py`, `SPEAKER_SIGNAL=1` + `SPEAKER_CUT=1`):
|
|
||||||
hard cuts to whoever is talking, rendered through the TRACK path as a
|
|
||||||
trajectory with jumps. `SPEAKER_SIGNAL=1` alone just gates SPLIT on both people
|
|
||||||
actually speaking. Mouth activity **must** be normalised per speaker before
|
|
||||||
comparing (`normalise_activity`): raw frame-difference magnitude scales with
|
|
||||||
local contrast and lighting, and on a real two-shot it handed one speaker
|
|
||||||
90-100% of the scene.
|
|
||||||
- **Punch-in** (`punch_in.py`, `PUNCH_IN=1`): not a layout. A ~12% push on the
|
|
||||||
clip's beats, riding the TRACK path by widening its per-frame crop command
|
|
||||||
from x-only to w/h/x/y. Beats currently come from the audio envelope;
|
|
||||||
`emphasis_times` is a plain list of seconds so the transcript's hook words can
|
|
||||||
replace it without touching the module.
|
|
||||||
|
|
||||||
### Key Classes
|
|
||||||
- `SmoothedCameraman` - Stabilized camera movement with safe zone logic (prevents jitter)
|
|
||||||
- `SpeakerTracker` - Prevents rapid speaker switching, handles temporary occlusions
|
|
||||||
|
|
||||||
### API Endpoints
|
|
||||||
| Method | Route | Purpose |
|
|
||||||
|--------|-------|---------|
|
|
||||||
| POST | `/api/process` | Submit video for processing |
|
|
||||||
| GET | `/api/status/{job_id}` | Poll job status and logs |
|
|
||||||
| POST | `/api/edit` | Apply AI video effects |
|
|
||||||
| POST | `/api/subtitle` | Generate and apply subtitles (auto-transcribes dubbed videos) |
|
|
||||||
| POST | `/api/hook` | Add text hook overlays |
|
|
||||||
| POST | `/api/translate` | AI voice dubbing via ElevenLabs |
|
|
||||||
| GET | `/api/translate/languages` | List supported dubbing languages |
|
|
||||||
| POST | `/api/postiz/post` | Upload a clip to Postiz, then schedule or post it now |
|
|
||||||
| GET | `/api/postiz/integrations` | List the channels connected in Postiz |
|
|
||||||
| GET | `/api/postiz/scheduled` | List scheduled posts in a date window |
|
|
||||||
| DELETE | `/api/postiz/scheduled/{id}` | Delete a scheduled post |
|
|
||||||
| GET | `/api/postiz/analytics` | Channel analytics (`integration` id required) |
|
|
||||||
| GET | `/api/postiz/analytics/posts` | Analytics for one published post (`post_id` required) |
|
|
||||||
|
|
||||||
### Publishing through Postiz
|
|
||||||
|
|
||||||
`postiz.py` is a thin client for a self-hosted [Postiz](https://postiz.com/)
|
|
||||||
instance. The dashboard sends the user's `X-Postiz-Key` / `X-Postiz-Url`
|
|
||||||
headers; the backend falls back to the `POSTIZ_API_KEY` / `POSTIZ_URL` env
|
|
||||||
vars. Because the clip file lives on the app server, the backend reads it and
|
|
||||||
uploads the bytes to Postiz (`POST /upload`, multipart), then references the
|
|
||||||
returned `{id, path}` in `POST /posts`. Provider settings (`tiktok`,
|
|
||||||
`instagram`, `youtube`) are built server-side from the clip title and caption.
|
|
||||||
Auth is the raw key, no `Bearer`.
|
|
||||||
|
|
||||||
### Webhooks
|
|
||||||
|
|
||||||
`POST /api/process` takes `webhook_url` + optional
|
|
||||||
`webhook_secret` (HMAC-SHA256, `X-Clipwright-Signature`). Validated with
|
|
||||||
`security_utils.assert_public_url` at submit AND at delivery (DNS rebinding).
|
|
||||||
Fired once per job from `run_job_wrapper`; survives redeploys via the resume
|
|
||||||
manifest. Each clip carries `video_url` (the local `/videos/...` path).
|
|
||||||
`PUBLIC_API_URL` env sets the absolute-URL base when behind a proxy.
|
|
||||||
|
|
||||||
### Concurrency Model
|
|
||||||
Async job queue with semaphore-based concurrency control. Configure via `MAX_CONCURRENT_JOBS` env var (default: 5). Jobs auto-cleanup after 1 hour.
|
|
||||||
|
|
||||||
The real limit on the GPU box is VRAM, not CPU: each `main.py` job holds
|
|
||||||
Parakeet (onnxruntime CUDA), TransNetV2 (torch, ~2 GB at peak) and an
|
|
||||||
NVENC session, and when the card is full a cut fails as "Generic error in
|
|
||||||
an external library" / exit 187 with 0 bytes, TransNetV2 as CUDA OOM, and
|
|
||||||
the reframe writer as a broken pipe. The retry in `ffmpeg_utils.cut_clip`
|
|
||||||
waits for a **busy** GPU; it cannot help with a **full** one. The API
|
|
||||||
process itself was the biggest tenant (7.7 GB idle on 17-sep-2026): the
|
|
||||||
thumbnail studio and `/api/subtitle` on a dubbed clip transcribe
|
|
||||||
in-process and the ASR singletons then lived in uvicorn for good, so both
|
|
||||||
now call `transcribe_backends.release_models()` when they are done. Size
|
|
||||||
`MAX_CONCURRENT_JOBS` against the free VRAM first, then check the CPU.
|
|
||||||
|
|
||||||
The CPU is the other ceiling (a 20-thread host sat at load ~100 at peak on
|
|
||||||
22 and 25-sep-2026). Two costs were pure waste and are gone, with the
|
|
||||||
delivered clips byte-identical (decoded-frame MD5s + audio, 15 clips of 3
|
|
||||||
real videos, bench of 25-sep-2026):
|
|
||||||
- **onnxruntime threads spinning** during Parakeet: ~160 CPU-s per 9 min of
|
|
||||||
audio while the GPU did the work. `parakeet_session_options()` turns
|
|
||||||
spinning off for the ASR session only; the VAD must keep `load_vad`'s
|
|
||||||
defaults (see the docstring for why).
|
|
||||||
- **A seek per sampled frame** in `analyze_scenes_strategy` and
|
|
||||||
`split_layout`: each seek re-decoded the GOP. `frame_sampler.read_at`
|
|
||||||
reads forward once and returns the same frames.
|
|
||||||
Net: a job's CPU roughly halves (Python side -65-80%).
|
|
||||||
|
|
||||||
Then speed at equal quality (25-sep-2026; SSIM 0.990-0.9998 vs before,
|
|
||||||
checked by eye, audio identical):
|
|
||||||
- **Cut on the card** (`ffmpeg_utils.cut_clip`, NVDEC -> NVENC with
|
|
||||||
`-hwaccel_output_format cuda`) for 8-bit 4:2:0 sources; byte-identical to
|
|
||||||
the CPU cut. Other sources and a failed GPU cut decode on the CPU.
|
|
||||||
- **Silero VAD on one CPU thread** (`vad_load_kwargs`): on CUDA it ran one
|
|
||||||
32 ms chunk per launch and was most of the transcription's wall time.
|
|
||||||
- **Blur at quarter size** (`ffmpeg_utils.blurred_backdrop`).
|
|
||||||
- **hooked_ + subtitled_ from one ffmpeg** (`hooks.add_hook_to_video(also=)`):
|
|
||||||
the editor still needs both files (re-caption walks back to hooked_,
|
|
||||||
hook replace to the canonical), so nothing is skipped, only one decode.
|
|
||||||
- **CLIP_WORKERS=6** by default.
|
|
||||||
Tried and dropped: NVDEC for the analysis decodes and `scale_cuda` (slower in
|
|
||||||
wall, and scale_cuda does not match swscale); yt-dlp chunking/concurrent
|
|
||||||
fragments (YouTube serves DASH over https, no gain beyond network noise).
|
|
||||||
Measured with a side-by-side bench: Gemini decisions recorded once and
|
|
||||||
replayed, old and new code run at the same time, clips compared by
|
|
||||||
decoded-frame MD5 / SSIM.
|
|
||||||
|
|
||||||
Three guards keep the card from filling (22-sep-2026: 30-60% of jobs failing
|
|
||||||
per hour at peak with `MAX_CONCURRENT_JOBS=8`):
|
|
||||||
- **Job processes release the ASR model after transcribing**
|
|
||||||
(`main.transcribe_video` → `release_models()`). Before, a job kept Parakeet's
|
|
||||||
onnxruntime CUDA arena (~4-6 GB) for its whole render; TransNetV2 also
|
|
||||||
`empty_cache()`s after each pass.
|
|
||||||
- **Parakeet runs lean** (`transcribe_backends.parakeet_providers`,
|
|
||||||
`PARAKEET_VAD_BATCH`=4): 4 VAD segments per encoder batch instead of 8, CUDA
|
|
||||||
arena `kSameAsRequested`, no max cuDNN workspace. Peak per transcription
|
|
||||||
6.1 → 4.6 GB with the same words (benchmark 22-sep-2026: 10 real videos,
|
|
||||||
4,850 words, 1 word changed outside a clip that goes to whisper anyway).
|
|
||||||
Batch 2 dropped a sentence and int8 was 11x slower with 11.7% of words
|
|
||||||
different: both rejected.
|
|
||||||
- **Host-wide transcription slots** (`transcribe_backends.host_asr_slot`,
|
|
||||||
`ASR_HOST_SLOTS`, default 2): flock files `output/.asr-gpu-N.lock`, shared by
|
|
||||||
every job process and by both containers of a deploy.
|
|
||||||
- **Queue admission** (`app._wait_for_shared_gpu`): a job starts only when
|
|
||||||
running-here + running-on-the-draining-instance < `MAX_CONCURRENT_JOBS` and
|
|
||||||
`nvidia-smi` reports at least `GPU_MIN_FREE_MB` (4500) free; an idle card
|
|
||||||
always starts, and the wait is bounded by the drain timeout.
|
|
||||||
|
|
||||||
Failures the user should never see (`app.run_job_wrapper`):
|
|
||||||
- **Auto-retry**: a failed job whose error text is transient (CUDA/OOM,
|
|
||||||
NVENC "Generic error in an external library", cublas, Gemini 5xx, "No clips
|
|
||||||
could be rendered") is re-queued once after `AUTO_RETRY_DELAY_SECONDS` (30),
|
|
||||||
keeping its reservation and transcript checkpoint (`AUTO_RETRY_LIMIT`=1).
|
|
||||||
Content failures (no audio, private video, no clips found, policy block)
|
|
||||||
are final as before. Inside a job, `main.py` retries each failed clip once,
|
|
||||||
alone, after a pause, and renders clips best-score first.
|
|
||||||
- **Shutdown is not failure**: when the drain timeout cancels a running job,
|
|
||||||
the child is killed and the manifest + reservation are kept, so the next
|
|
||||||
instance resumes it. A manifest next to a metadata file means "stopped
|
|
||||||
mid-render" and is resumed, not recovered as completed.
|
|
||||||
- `/api/status` returns `queue: {position, ahead, eta_seconds}` while queued,
|
|
||||||
which the dashboard shows as a queue position and ETA.
|
|
||||||
|
|
||||||
### Download proxy routing and accounting (`yt_clients.py`, `metering.py`)
|
|
||||||
|
|
||||||
Downloads go direct → static ISP proxies (flat rate) → DataImpulse (per GB),
|
|
||||||
and the duration probe (`metering.probe_url_minutes`) follows the same
|
|
||||||
order, with one extra free step before any per-GB attempt: the fallback
|
|
||||||
clients through a static (`fallback-static`). **The client list is explicit
|
|
||||||
and shared** (`yt_clients.py`: `default,mweb` + the bgutil PO token
|
|
||||||
provider): with account cookies yt-dlp's own defaults are `tv_downgraded` +
|
|
||||||
`web`, and on a share of videos both come back UNPLAYABLE / SABR-only, which
|
|
||||||
yt-dlp reports as "Video unavailable". That was mistaken for an IP ban for a
|
|
||||||
week (it happened on every static IP too) and fed ~26 downloads a week to
|
|
||||||
the per-GB proxy, which then fetched 360p through the same dead list.
|
|
||||||
Measured in the prod container on 6-sep-2026, same static, same video:
|
|
||||||
cookies + defaults → unavailable; cookies + `default,mweb` → 1080p; no
|
|
||||||
cookies → 1080p. `mweb` needs the PO token, and the token needs the
|
|
||||||
webpage: never put `player_skip: webpage` back. A fallback attempt runs
|
|
||||||
anonymously when an HD attempt already failed with the cookies on that
|
|
||||||
route, and every attempt asks for the 1080p format spec (the old
|
|
||||||
`best[ext=mp4]` fallback spec was itself the 360p progressive file).
|
|
||||||
Two rules keep the per-GB proxy at zero on a normal day: the probe
|
|
||||||
reaches it **only** when a static route failed for a reason another IP can
|
|
||||||
fix (`static_failure_warrants_paid`: bot-check, 403/429, proxy/network
|
|
||||||
errors), never for a private/removed/members-only video, an uploader's
|
|
||||||
country block (the residential pool failed identically in 5 of 6 paid
|
|
||||||
probes, 3-5 sep) or a live stream
|
|
||||||
with no duration (those failed the same on every IP and used to cost ~1.7 MB
|
|
||||||
× 2 extractors each), and **never for a non-YouTube URL** (the download
|
|
||||||
plan already excluded those; Twitch, Kick, Rumble and product pages were
|
|
||||||
reaching it through the probe). The probe also carries `YOUTUBE_COOKIES`,
|
|
||||||
like the download does: an anonymous probe from the static IPs gets "Sign in
|
|
||||||
to confirm you're not a bot" in bursts (4-sep-2026: ~10 probes in one hour,
|
|
||||||
1.8 MB each on the per-GB proxy) because a datacenter IP's anonymous rate
|
|
||||||
limit is low and we make ~400 YouTube hits a day from three of them, while
|
|
||||||
the authenticated download sails through the same IPs. But the **first**
|
|
||||||
attempt on a route carries them and the second drops them, on the probe as
|
|
||||||
on the download: with the cookies attached YouTube answers UNPLAYABLE for
|
|
||||||
every client (`web_embedded`, `tv_downgraded`, `web` **and** `mweb`) on a
|
|
||||||
share of videos, which yt-dlp reports as "Video unavailable" (9-sep-2026,
|
|
||||||
same video on all three statics; anonymous on the same IP → 1080p 137+140).
|
|
||||||
Without that anonymous second attempt the probe read a cookie problem as an
|
|
||||||
IP problem and escalated to the per-GB proxy, which carries the same cookies
|
|
||||||
and fails identically, while the download recovered for free on the same
|
|
||||||
static. `main.py` prints `PROXY_ROUTE=<json>` after
|
|
||||||
every download (winner, paid bytes across all attempts including failed
|
|
||||||
paid ones, each free attempt's error); `app.py` logs `PROXY_ROUTE` at job end
|
|
||||||
and warns when the paid proxy carried bytes. Both the probe and the download pass `noplaylist`: a
|
|
||||||
`watch?v=X&list=...` or mix link is the one video the user was watching,
|
|
||||||
and without it yt-dlp walks the whole list, dies on its first private /
|
|
||||||
age-gated / bot-checked entry (a video nobody pasted), the probe reads
|
|
||||||
that as an IP problem and pays the proxy to walk the same list again, and
|
|
||||||
the user gets a 400 for a valid link (26 of the 37 paid probes between
|
|
||||||
7 and 17-sep-2026). And the probe keeps **every** attempt's error per
|
|
||||||
static route, not the last one: the anonymous retry ends in a bot-check
|
|
||||||
by design, and a "confirm your age" from the cookie attempt is the
|
|
||||||
verdict, so it must not be overwritten into an escalation. A URL that is
|
|
||||||
not one video is refused by path before any request
|
|
||||||
(`yt_clients.youtube_non_video_reason`): `noplaylist` does nothing for
|
|
||||||
those and yt-dlp walks them entry by entry (one search URL held the
|
|
||||||
probe thread for 37 min in the prod container). That check is an
|
|
||||||
**allowlist** of the paths that carry a video id, not a list of the bad
|
|
||||||
ones: while it named the pages it knew, a hashtag page and the legacy
|
|
||||||
`/<vanity>` channel URL went straight through, and one of them walked to
|
|
||||||
page 23 on the static pool and then paid the per-GB proxy to walk it
|
|
||||||
again (20-sep-2026).
|
|
||||||
Since 30-sep-2026 YouTube answers the bot-check to anonymous requests
|
|
||||||
from every one of our non-residential IPs (the 3 statics and the server's
|
|
||||||
own IP alike), **per video**: the same video fails on all of them and a few
|
|
||||||
popular ones pass on all of them, whatever the client (web, mweb, ios,
|
|
||||||
android_vr, tv, web_embedded, with or without a player PO token). Only an
|
|
||||||
authenticated session or a residential IP gets through. So when the probe
|
|
||||||
saw every static bot-checked and the paid proxy answer, the job carries
|
|
||||||
`DOWNLOAD_SKIP_STATICS=1` (`metering.pop_statics_bot_checked`, also in the
|
|
||||||
resume manifest) and `plan_download_attempts` goes straight to the paid
|
|
||||||
attempts instead of repeating four anonymous hits for the same verdict.
|
|
||||||
The proxy watcher also checks the ytcfg `LOGGED_IN` marker when
|
|
||||||
`YOUTUBE_COOKIES` is set and pages on the first probe that says the session
|
|
||||||
is gone. `PAID_PROXY_DAILY_MB` (default
|
|
||||||
500) is the hard ceiling: past it the paid proxy is dropped from the probe
|
|
||||||
and from every new job's env until UTC midnight. The watcher probes the
|
|
||||||
static pool against a real YouTube watch page (playable markers), not
|
|
||||||
google.com — the 28th happened because YouTube refused the static IPs while
|
|
||||||
google kept answering 204. On the dev Mac, do not keep
|
|
||||||
`PROXY_URL` in `.env`: every local `main.py` run then bills DataImpulse.
|
|
||||||
|
|
||||||
### Deploys and running jobs (handover + drain)
|
|
||||||
|
|
||||||
Every push to `main` redeploys the API container. Coolify starts the NEW
|
|
||||||
container before stopping the old one (rolling update) and both share
|
|
||||||
`output/`, so `app.py` coordinates them instead of relying on a fast swap:
|
|
||||||
|
|
||||||
- Each instance writes its id to `output/.instance` at startup. An instance
|
|
||||||
that sees another id there is the old one and **drains**: it finishes the
|
|
||||||
jobs it is running, starts none, and leaves queued manifests on disk.
|
|
||||||
- A running job heartbeats its `.resume.json` every 10 s. The resume scan
|
|
||||||
(startup + every 30 s) re-enqueues only manifests nobody heartbeated for
|
|
||||||
60 s, so no job runs twice and none is lost. Max 2 resume attempts.
|
|
||||||
- SIGTERM (`docker stop`) drains too, up to `DRAIN_TIMEOUT_SECONDS` (840),
|
|
||||||
then hands the signal to uvicorn. The app's Coolify stop grace period is
|
|
||||||
900 s (`application_settings.stop_grace_period`); keep the timeout below it.
|
|
||||||
After the drain hands the signal to uvicorn, `--timeout-graceful-shutdown 15`
|
|
||||||
(Dockerfile) caps the wait for in-flight connections: uvicorn's default is
|
|
||||||
unbounded, and one open range download kept a drained container alive for
|
|
||||||
the full grace period while Traefik still routed half the traffic to its
|
|
||||||
closed port.
|
|
||||||
- `/health/ready` + the Dockerfile `HEALTHCHECK` are what keep Traefik off a
|
|
||||||
dying container: its docker provider only routes to `healthy` containers,
|
|
||||||
so an instance answers 503 from the moment it gets SIGTERM (out of rotation
|
|
||||||
within ~10 s, socket still open) and a booting one gets no traffic until it
|
|
||||||
answers. Only SIGTERM flips it, not the marker drain: at that point the new
|
|
||||||
container is still booting and nobody else would be routable. The Coolify
|
|
||||||
app has its health check enabled on that path so it waits for the new
|
|
||||||
container to be `healthy` before stopping the old one. With that option on,
|
|
||||||
Coolify replaces the Dockerfile HEALTHCHECK with its own curl/wget command
|
|
||||||
AND its own interval/retries (5 s × 3), so the image must ship `curl` or
|
|
||||||
every deploy rolls back as unhealthy, and a stopping container takes 15 s
|
|
||||||
to turn `unhealthy`. That is why the drain keeps serving for
|
|
||||||
`PROXY_DRAIN_SECONDS` (20) after the jobs are done before it hands the
|
|
||||||
signal to uvicorn: closing the socket earlier is 502s until Traefik
|
|
||||||
notices (measured ~60 s per deploy with retries=12 and no grace). And
|
|
||||||
`HARD_EXIT_SECONDS` (30) after that the process is ended outright: uvicorn
|
|
||||||
finishing does not end the interpreter while an executor thread hangs in
|
|
||||||
a network probe, and that kept a drained container alive for the full 900 s.
|
|
||||||
`/health` stays a plain liveness probe for the external watcher.
|
|
||||||
- `/api/status` answers from disk for a job this instance never held, so a
|
|
||||||
poll landing on either container during the handover is fine.
|
|
||||||
- `main.py` leaves `.transcript_checkpoint.json` in the job dir so a job that
|
|
||||||
does get re-run skips the paid transcription (download and Gemini repeat).
|
|
||||||
|
|
||||||
Before pushing, still batch small commits (tests, docs) with the next real
|
|
||||||
change: every deploy is a ~5 min build plus a handover.
|
|
||||||
|
|
||||||
## CI: a green pipeline closes the task, not the push
|
|
||||||
- After every `git push`, wait for the commit's workflow and confirm it is green: `ci-wait` (Victor's Mac) or `gh run watch $(gh run list -c $(git rev-parse HEAD) -L1 --json databaseId -q ".[0].databaseId") --exit-status`.
|
|
||||||
- If it is red: fix, push, check again. Never report the task as done with a red CI.
|
|
||||||
- Before pushing, run locally what the CI runs (lint + tests of this repo).
|
|
||||||
11
README.md
11
README.md
|
|
@ -19,18 +19,17 @@ Clipwright is a fork of [OpenShorts](https://github.com/mutonby/openshorts), ren
|
||||||
- **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 tier](https://aistudio.google.com/app/apikey) — used for moment detection, layouts, titles and thumbnails. Optional if you set `LLM_BASE_URL`.
|
||||||
- **A self-hosted Postiz instance** — optional, only for publishing.
|
- **A self-hosted Postiz instance** — optional, only for publishing.
|
||||||
- **ElevenLabs API key** — optional, only for voice dubbing.
|
|
||||||
|
|
||||||
## Quick start
|
## Quick start
|
||||||
|
|
||||||
```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: S3 backup, Postiz server-side key
|
cp .env.example .env # optional: Postiz server-side key
|
||||||
docker compose up --build
|
docker compose up --build
|
||||||
```
|
```
|
||||||
|
|
||||||
Open the dashboard at **http://localhost:5175**, go to **Settings**, and paste your keys (Gemini; ElevenLabs and Postiz are optional). Then:
|
Open the dashboard at **http://localhost:5175**, go to **Settings**, and paste your keys (Gemini; Postiz is optional). Then:
|
||||||
|
|
||||||
1. **Clip Generator** — upload a long video or paste a URL.
|
1. **Clip Generator** — upload a long video or paste a URL.
|
||||||
2. **YouTube Studio** — generate titles, thumbnails and descriptions.
|
2. **YouTube Studio** — generate titles, thumbnails and descriptions.
|
||||||
|
|
@ -47,9 +46,8 @@ Server-side (`.env`):
|
||||||
| `POSTIZ_URL` / `POSTIZ_API_KEY` | Your Postiz instance + API key, used when the dashboard does not send them. |
|
| `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_CONCURRENT_JOBS` | Concurrent jobs (default 5). |
|
||||||
| `MAX_FILE_SIZE_MB` | Upload cap in MB; `0` (default) is unlimited. |
|
| `MAX_FILE_SIZE_MB` | Upload cap in MB; `0` (default) is unlimited. |
|
||||||
| `AWS_*` | Optional S3 backup for clips. |
|
|
||||||
|
|
||||||
Client-side (stored encrypted in your browser): `GEMINI_API_KEY`, `ELEVENLABS_API_KEY`, `postiz_url`, `postiz_key_v1`.
|
Client-side (stored encrypted in your browser): `GEMINI_API_KEY`, `postiz_url`, `postiz_key_v1`.
|
||||||
|
|
||||||
### Run without a Google key (optional)
|
### Run without a Google key (optional)
|
||||||
|
|
||||||
|
|
@ -86,6 +84,7 @@ services:
|
||||||
1. Run Postiz yourself and connect TikTok, Instagram and/or YouTube inside it.
|
1. Run Postiz yourself and connect TikTok, Instagram and/or YouTube inside it.
|
||||||
2. Create a public API key in Postiz (**Settings → Developers / Public API**).
|
2. Create a public API key in Postiz (**Settings → Developers / Public API**).
|
||||||
3. In Clipwright **Settings**, enter your Postiz URL and key, then **Test connection** to list your channels.
|
3. In Clipwright **Settings**, enter your Postiz URL and key, then **Test connection** to list your channels.
|
||||||
|
4. In the publish modal, tick the exact channel each clip should go to. Multiple channels per network are supported (for example two YouTube channels), so you pick the channel itself, not the platform, and schedule it with a **DD/MM/YYYY** date.
|
||||||
|
|
||||||
Clipwright uploads the clip to your Postiz instance and creates the post there; the platform tokens never leave your infrastructure.
|
Clipwright uploads the clip to your Postiz instance and creates the post there; the platform tokens never leave your infrastructure.
|
||||||
|
|
||||||
|
|
@ -98,7 +97,7 @@ 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`. An importable n8n workflow lives in [`examples/n8n/`](examples/n8n/).
|
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`.
|
||||||
|
|
||||||
## Tech stack
|
## Tech stack
|
||||||
|
|
||||||
|
|
|
||||||
347
app.py
347
app.py
|
|
@ -26,7 +26,6 @@ from fastapi.responses import FileResponse, JSONResponse
|
||||||
from starlette.background import BackgroundTask
|
from starlette.background import BackgroundTask
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
import httpx
|
import httpx
|
||||||
from s3_uploader import upload_job_artifacts
|
|
||||||
import recut
|
import recut
|
||||||
import layout_ranges
|
import layout_ranges
|
||||||
import watermarked
|
import watermarked
|
||||||
|
|
@ -79,8 +78,7 @@ CHILD_ENV_DENYLIST = frozenset({
|
||||||
"AGENTLEDGER_API_KEY",
|
"AGENTLEDGER_API_KEY",
|
||||||
"MANAGED_GEMINI_API_KEY", "POSTIZ_API_KEY", "POSTIZ_URL",
|
"MANAGED_GEMINI_API_KEY", "POSTIZ_API_KEY", "POSTIZ_URL",
|
||||||
"R2_ACCESS_KEY_ID", "R2_SECRET_ACCESS_KEY",
|
"R2_ACCESS_KEY_ID", "R2_SECRET_ACCESS_KEY",
|
||||||
"AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY",
|
"OPENPANEL_CLIENT_SECRET",
|
||||||
"OPENPANEL_CLIENT_SECRET", "ELEVENLABS_API_KEY",
|
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -1686,10 +1684,6 @@ async def run_job(job_id, job_data):
|
||||||
jobs[job_id]['status'] = 'completed'
|
jobs[job_id]['status'] = 'completed'
|
||||||
jobs[job_id]['logs'].append("Process finished successfully.")
|
jobs[job_id]['logs'].append("Process finished successfully.")
|
||||||
|
|
||||||
# Silent AWS S3 backup (optional; a no-op when S3 is unconfigured).
|
|
||||||
loop = asyncio.get_event_loop()
|
|
||||||
loop.run_in_executor(None, upload_job_artifacts, output_dir, job_id)
|
|
||||||
|
|
||||||
# Find result JSON
|
# Find result JSON
|
||||||
json_files = glob.glob(os.path.join(output_dir, "*_metadata.json"))
|
json_files = glob.glob(os.path.join(output_dir, "*_metadata.json"))
|
||||||
if not json_files:
|
if not json_files:
|
||||||
|
|
@ -2547,9 +2541,8 @@ async def download_all_clips(job_id: str, request: Request):
|
||||||
|
|
||||||
|
|
||||||
from editor import VideoEditor
|
from editor import VideoEditor
|
||||||
from subtitles import generate_srt, generate_ass, burn_subtitles, generate_srt_from_video, CAPTION_PRESETS
|
from subtitles import generate_srt, generate_ass, burn_subtitles, CAPTION_PRESETS
|
||||||
from hooks import add_hook_to_video
|
from hooks import add_hook_to_video
|
||||||
from translate import translate_video, get_supported_languages
|
|
||||||
from thumbnail import (analyze_video_for_titles, refine_titles, generate_thumbnail,
|
from thumbnail import (analyze_video_for_titles, refine_titles, generate_thumbnail,
|
||||||
generate_youtube_description, extract_face_frames)
|
generate_youtube_description, extract_face_frames)
|
||||||
|
|
||||||
|
|
@ -3726,30 +3719,10 @@ async def add_subtitles(req: SubtitleRequest, request: Request):
|
||||||
output_path = os.path.join(output_dir, output_filename)
|
output_path = os.path.join(output_dir, output_filename)
|
||||||
|
|
||||||
# Burning captions is free: the SRT comes from the transcript already
|
# Burning captions is free: the SRT comes from the transcript already
|
||||||
# sitting in metadata.json and the burn is a single short FFmpeg pass. The
|
# sitting in metadata.json and the burn is a single short FFmpeg pass.
|
||||||
# dubbed path is the exception — it runs a fresh Whisper transcription over
|
|
||||||
# the translated audio, which is real work, but self-host has no quota.
|
|
||||||
is_dubbed = filename.startswith("translated_")
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 1. Generate SRT — from the existing transcript, or a fresh
|
# 1. Generate SRT from the existing transcript.
|
||||||
# transcription when the audio was dubbed.
|
|
||||||
if is_dubbed:
|
|
||||||
print(f"🎙️ Dubbed video detected, transcribing audio for subtitles...")
|
|
||||||
def run_transcribe_srt():
|
|
||||||
if is_karaoke:
|
if is_karaoke:
|
||||||
return generate_srt_from_video(input_path, srt_path, style="karaoke", **karaoke_opts)
|
|
||||||
return generate_srt_from_video(input_path, srt_path)
|
|
||||||
|
|
||||||
loop = asyncio.get_event_loop()
|
|
||||||
try:
|
|
||||||
success = await loop.run_in_executor(None, run_transcribe_srt)
|
|
||||||
finally:
|
|
||||||
# The ASR models must not stay resident in the API process:
|
|
||||||
# they held 7.7 GB of VRAM idle (transcribe_backends.release_models).
|
|
||||||
import transcribe_backends
|
|
||||||
await loop.run_in_executor(None, transcribe_backends.release_models)
|
|
||||||
elif is_karaoke:
|
|
||||||
success = generate_ass(sub_transcript, sub_start, sub_end, srt_path, **karaoke_opts)
|
success = generate_ass(sub_transcript, sub_start, sub_end, srt_path, **karaoke_opts)
|
||||||
else:
|
else:
|
||||||
success = generate_srt(sub_transcript, sub_start, sub_end, srt_path,
|
success = generate_srt(sub_transcript, sub_start, sub_end, srt_path,
|
||||||
|
|
@ -4001,129 +3974,26 @@ async def add_hook(req: HookRequest, request: Request):
|
||||||
"burned_hook": None if req.remove else clip_data['auto_hook'],
|
"burned_hook": None if req.remove else clip_data['auto_hook'],
|
||||||
}
|
}
|
||||||
|
|
||||||
class TranslateRequest(BaseModel):
|
|
||||||
job_id: str
|
|
||||||
clip_index: int
|
|
||||||
target_language: str
|
|
||||||
source_language: Optional[str] = None
|
|
||||||
input_filename: Optional[str] = None
|
|
||||||
|
|
||||||
@app.get("/api/translate/languages")
|
|
||||||
async def get_languages():
|
|
||||||
"""Return supported languages for translation."""
|
|
||||||
return {"languages": get_supported_languages()}
|
|
||||||
|
|
||||||
@app.post("/api/translate")
|
|
||||||
async def translate_clip(
|
|
||||||
req: TranslateRequest,
|
|
||||||
request: Request,
|
|
||||||
x_elevenlabs_key: Optional[str] = Header(None, alias="X-ElevenLabs-Key")
|
|
||||||
):
|
|
||||||
"""Translate a video clip to a different language using ElevenLabs dubbing."""
|
|
||||||
if not x_elevenlabs_key:
|
|
||||||
raise HTTPException(status_code=400, detail="Missing X-ElevenLabs-Key header")
|
|
||||||
|
|
||||||
if req.job_id not in jobs:
|
|
||||||
raise HTTPException(status_code=404, detail="Job not found")
|
|
||||||
|
|
||||||
job = jobs[req.job_id]
|
|
||||||
await _assert_job_owner(request, job)
|
|
||||||
output_dir = os.path.join(OUTPUT_DIR, req.job_id)
|
|
||||||
json_files = glob.glob(os.path.join(output_dir, "*_metadata.json"))
|
|
||||||
|
|
||||||
if not json_files:
|
|
||||||
raise HTTPException(status_code=404, detail="Metadata not found")
|
|
||||||
|
|
||||||
with open(json_files[0], 'r') as f:
|
|
||||||
data = json.load(f)
|
|
||||||
|
|
||||||
clips = data.get('shorts', [])
|
|
||||||
if req.clip_index >= len(clips):
|
|
||||||
raise HTTPException(status_code=404, detail="Clip not found")
|
|
||||||
|
|
||||||
clip_data = clips[req.clip_index]
|
|
||||||
|
|
||||||
# Video Path
|
|
||||||
if req.input_filename:
|
|
||||||
filename = os.path.basename(req.input_filename)
|
|
||||||
else:
|
|
||||||
filename = clip_data.get('video_url', '').split('/')[-1]
|
|
||||||
if not filename:
|
|
||||||
base_name = os.path.basename(json_files[0]).replace('_metadata.json', '')
|
|
||||||
filename = f"{base_name}_clip_{req.clip_index+1}.mp4"
|
|
||||||
|
|
||||||
input_path = os.path.join(output_dir, filename)
|
|
||||||
if not os.path.exists(input_path):
|
|
||||||
raise HTTPException(status_code=404, detail=f"Video file not found: {input_path}")
|
|
||||||
|
|
||||||
# Output video with language suffix
|
|
||||||
base, ext = os.path.splitext(filename)
|
|
||||||
output_filename = f"translated_{req.target_language}_{base}{ext}"
|
|
||||||
output_path = os.path.join(output_dir, output_filename)
|
|
||||||
|
|
||||||
try:
|
|
||||||
# Run translation in thread pool (blocking API calls)
|
|
||||||
def run_translate():
|
|
||||||
return translate_video(
|
|
||||||
video_path=input_path,
|
|
||||||
output_path=output_path,
|
|
||||||
target_language=req.target_language,
|
|
||||||
api_key=x_elevenlabs_key,
|
|
||||||
source_language=req.source_language,
|
|
||||||
)
|
|
||||||
|
|
||||||
loop = asyncio.get_event_loop()
|
|
||||||
await loop.run_in_executor(None, run_translate)
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
print(f"❌ Translation Error: {e}")
|
|
||||||
raise HTTPException(status_code=500, detail=str(e))
|
|
||||||
|
|
||||||
# AI Act art. 50(2): the voice in this file was synthesised, so the file
|
|
||||||
# says so in a way a machine can read. Best-effort by design — see
|
|
||||||
# ffmpeg_utils.mark_ai_generated.
|
|
||||||
from ffmpeg_utils import mark_ai_generated
|
|
||||||
await loop.run_in_executor(
|
|
||||||
None, lambda: mark_ai_generated(output_path, "AI voice dubbing"))
|
|
||||||
|
|
||||||
output_filename = await _deliver(request, req.job_id, output_filename)
|
|
||||||
|
|
||||||
# Update InMemory Jobs
|
|
||||||
if req.clip_index < len(job['result']['clips']):
|
|
||||||
job['result']['clips'][req.clip_index]['video_url'] = f"/videos/{req.job_id}/{output_filename}"
|
|
||||||
|
|
||||||
# Update Metadata on Disk
|
|
||||||
try:
|
|
||||||
if req.clip_index < len(clips):
|
|
||||||
clips[req.clip_index]['video_url'] = f"/videos/{req.job_id}/{output_filename}"
|
|
||||||
data['shorts'] = clips
|
|
||||||
with open(json_files[0], 'w') as f:
|
|
||||||
json.dump(data, f, indent=4)
|
|
||||||
print(f"✅ Metadata updated with translated video for clip {req.clip_index}")
|
|
||||||
except Exception as e:
|
|
||||||
print(f"⚠️ Failed to update metadata.json: {e}")
|
|
||||||
|
|
||||||
|
|
||||||
return {
|
|
||||||
"success": True,
|
|
||||||
"new_video_url": f"/videos/{req.job_id}/{output_filename}"
|
|
||||||
}
|
|
||||||
|
|
||||||
class PostizPostRequest(BaseModel):
|
class PostizPostRequest(BaseModel):
|
||||||
job_id: str
|
job_id: str
|
||||||
clip_index: int
|
clip_index: int
|
||||||
platforms: List[str] # ["tiktok", "instagram", "youtube"]
|
integration_ids: List[str] = [] # preferred: exact Postiz integration ids
|
||||||
|
platforms: List[str] = [] # legacy fallback: platform names (first enabled match)
|
||||||
title: Optional[str] = None
|
title: Optional[str] = None
|
||||||
description: Optional[str] = None
|
description: Optional[str] = None
|
||||||
scheduled_date: Optional[str] = None # ISO-8601
|
scheduled_date: Optional[str] = None # ISO-8601
|
||||||
timezone: Optional[str] = "UTC"
|
timezone: Optional[str] = "UTC"
|
||||||
|
|
||||||
|
|
||||||
def _postiz_iso_date(scheduled_date: Optional[str], tz_name: Optional[str]) -> str:
|
def _postiz_parse_instant(scheduled_date: Optional[str],
|
||||||
"""Postiz wants an ISO-8601 instant (with millis). Convert the client's
|
tz_name: Optional[str]) -> datetime:
|
||||||
scheduled_date + IANA timezone to UTC; default to now when unscheduled."""
|
"""Parse a client-supplied scheduled date into an aware UTC datetime.
|
||||||
|
|
||||||
|
``scheduled_date`` may carry a timezone (ISO-8601 ``Z``/offset); when it is
|
||||||
|
naive, ``tz_name`` (IANA) supplies the zone. Defaults to "now" when absent.
|
||||||
|
"""
|
||||||
if not scheduled_date:
|
if not scheduled_date:
|
||||||
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")
|
return datetime.now(timezone.utc)
|
||||||
value = scheduled_date.strip().replace("Z", "+00:00")
|
value = scheduled_date.strip().replace("Z", "+00:00")
|
||||||
try:
|
try:
|
||||||
parsed = datetime.fromisoformat(value)
|
parsed = datetime.fromisoformat(value)
|
||||||
|
|
@ -4137,7 +4007,14 @@ def _postiz_iso_date(scheduled_date: Optional[str], tz_name: Optional[str]) -> s
|
||||||
parsed = parsed.replace(tzinfo=ZoneInfo(tz_name or "UTC"))
|
parsed = parsed.replace(tzinfo=ZoneInfo(tz_name or "UTC"))
|
||||||
except Exception:
|
except Exception:
|
||||||
parsed = parsed.replace(tzinfo=timezone.utc)
|
parsed = parsed.replace(tzinfo=timezone.utc)
|
||||||
return parsed.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")
|
return parsed.astimezone(timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
def _postiz_iso_date(scheduled_date: Optional[str], tz_name: Optional[str]) -> str:
|
||||||
|
"""Postiz wants an ISO-8601 instant (with millis). Convert the client's
|
||||||
|
scheduled_date + IANA timezone to UTC; default to now when unscheduled."""
|
||||||
|
return _postiz_parse_instant(
|
||||||
|
scheduled_date, tz_name).strftime("%Y-%m-%dT%H:%M:%S.000Z")
|
||||||
|
|
||||||
|
|
||||||
def _postiz_hashtags(text: str) -> List[str]:
|
def _postiz_hashtags(text: str) -> List[str]:
|
||||||
|
|
@ -4148,11 +4025,37 @@ def _postiz_hashtags(text: str) -> List[str]:
|
||||||
return tags[:5]
|
return tags[:5]
|
||||||
|
|
||||||
|
|
||||||
def _postiz_settings(platform: str, title: str, caption: str, tags: List[str]) -> dict:
|
# Postiz lists Instagram as ``instagram-standalone`` and TikTok as
|
||||||
"""Per-provider settings block (see /tmp/opencode/cleanup/postiz-api.md)."""
|
# ``tiktok-business``; duplicate YouTube channels all share the identifier
|
||||||
|
# ``youtube``. The identifier is what Postiz routes on, so it is preserved for
|
||||||
|
# ``settings.__type``; the map below only groups channels for UI/platform use.
|
||||||
|
_IDENTIFIER_PLATFORM = {
|
||||||
|
"instagram": "instagram",
|
||||||
|
"instagram-standalone": "instagram",
|
||||||
|
"tiktok": "tiktok",
|
||||||
|
"tiktok-business": "tiktok",
|
||||||
|
"youtube": "youtube",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _identifier_platform(identifier: Optional[str]) -> str:
|
||||||
|
"""Map a raw Postiz identifier to a platform label (unknown -> itself)."""
|
||||||
|
ident = (identifier or "").strip().lower()
|
||||||
|
return _IDENTIFIER_PLATFORM.get(ident, ident)
|
||||||
|
|
||||||
|
|
||||||
|
def _postiz_settings(identifier: str, title: str, caption: str, tags: List[str]) -> dict:
|
||||||
|
"""Per-provider settings block (see /tmp/opencode/cleanup/postiz-api.md).
|
||||||
|
|
||||||
|
``settings.__type`` MUST echo the integration's real identifier (e.g.
|
||||||
|
``instagram-standalone``); sending the mapped platform makes Postiz route
|
||||||
|
the post to the wrong provider.
|
||||||
|
"""
|
||||||
|
identifier = (identifier or "").strip().lower()
|
||||||
|
platform = _identifier_platform(identifier)
|
||||||
if platform == "tiktok":
|
if platform == "tiktok":
|
||||||
return {
|
return {
|
||||||
"__type": "tiktok",
|
"__type": identifier,
|
||||||
"content_posting_method": "DIRECT_POST",
|
"content_posting_method": "DIRECT_POST",
|
||||||
"title": (caption or title or "")[:90],
|
"title": (caption or title or "")[:90],
|
||||||
"privacy_level": "PUBLIC_TO_EVERYONE",
|
"privacy_level": "PUBLIC_TO_EVERYONE",
|
||||||
|
|
@ -4165,39 +4068,88 @@ def _postiz_settings(platform: str, title: str, caption: str, tags: List[str]) -
|
||||||
"video_made_with_ai": False,
|
"video_made_with_ai": False,
|
||||||
}
|
}
|
||||||
if platform == "instagram":
|
if platform == "instagram":
|
||||||
return {"__type": "instagram", "post_type": "post"}
|
return {"__type": identifier, "post_type": "post"}
|
||||||
if platform == "youtube":
|
if platform == "youtube":
|
||||||
yt_title = (title or caption or "Short").strip()[:100]
|
yt_title = (title or caption or "Short").strip()[:100]
|
||||||
if len(yt_title) < 2:
|
if len(yt_title) < 2:
|
||||||
yt_title = (yt_title + " ")[:100]
|
yt_title = (yt_title + " ")[:100]
|
||||||
return {
|
return {
|
||||||
"__type": "youtube",
|
"__type": identifier,
|
||||||
"title": yt_title,
|
"title": yt_title,
|
||||||
"type": "public",
|
"type": "public",
|
||||||
"selfDeclaredMadeForKids": "no",
|
"selfDeclaredMadeForKids": "no",
|
||||||
"tags": [{"value": t, "label": t} for t in (tags or [])],
|
"tags": [{"value": t, "label": t} for t in (tags or [])],
|
||||||
}
|
}
|
||||||
return {"__type": platform}
|
return {"__type": identifier}
|
||||||
|
|
||||||
|
|
||||||
async def _postiz_integrations(base, key):
|
async def _postiz_integration_list(base, key) -> List[dict]:
|
||||||
"""Connected channels, keyed by identifier (tiktok/instagram/youtube).
|
"""The RAW Postiz integration list, with ``disabled`` normalised to bool.
|
||||||
|
|
||||||
Every integration is kept (disabled included) so the UI can still list it.
|
Deliberately un-keyed: YouTube can appear several times (one per channel)
|
||||||
Each entry carries a normalised boolean ``disabled`` flag so callers can
|
and every integration must stay individually selectable by id.
|
||||||
refuse to post to a switched-off channel instead of posting into the void.
|
|
||||||
"""
|
"""
|
||||||
integrations = await asyncio.to_thread(postiz.list_integrations, base, key)
|
integrations = await asyncio.to_thread(postiz.list_integrations, base, key)
|
||||||
by_identifier: Dict[str, dict] = {}
|
entries: List[dict] = []
|
||||||
for integration in integrations or []:
|
for integration in integrations or []:
|
||||||
if not isinstance(integration, dict):
|
if not isinstance(integration, dict):
|
||||||
continue
|
continue
|
||||||
identifier = (integration.get("identifier") or "").strip().lower()
|
|
||||||
if identifier and identifier not in by_identifier:
|
|
||||||
entry = dict(integration)
|
entry = dict(integration)
|
||||||
entry["disabled"] = bool(integration.get("disabled"))
|
entry["disabled"] = bool(integration.get("disabled"))
|
||||||
by_identifier[identifier] = entry
|
entries.append(entry)
|
||||||
return by_identifier
|
return entries
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_postiz_integrations(integrations, integration_ids, platforms):
|
||||||
|
"""Pick the integrations a publish request targets.
|
||||||
|
|
||||||
|
Prefers explicit ``integration_ids`` (validated to exist and be enabled).
|
||||||
|
Falls back to ``platforms`` for old clients: the first enabled integration
|
||||||
|
whose mapped platform matches. Raises 400 naming whatever failed.
|
||||||
|
"""
|
||||||
|
by_id = {str(i.get("id")): i for i in integrations if i.get("id") is not None}
|
||||||
|
|
||||||
|
if integration_ids:
|
||||||
|
selected: List[dict] = []
|
||||||
|
seen = set()
|
||||||
|
for raw_id in integration_ids:
|
||||||
|
iid = str(raw_id).strip()
|
||||||
|
if not iid or iid in seen:
|
||||||
|
continue
|
||||||
|
integration = by_id.get(iid)
|
||||||
|
if integration is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail=f"Unknown Postiz integration id: {iid}")
|
||||||
|
if integration.get("disabled"):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail=(f"Disabled in Postiz: "
|
||||||
|
f"{integration.get('name') or iid}"))
|
||||||
|
seen.add(iid)
|
||||||
|
selected.append(integration)
|
||||||
|
return selected
|
||||||
|
|
||||||
|
selected = []
|
||||||
|
for raw_platform in platforms:
|
||||||
|
platform = str(raw_platform).strip().lower()
|
||||||
|
if not platform:
|
||||||
|
continue
|
||||||
|
candidates = [
|
||||||
|
i for i in integrations
|
||||||
|
if _identifier_platform(i.get("identifier")) == platform
|
||||||
|
]
|
||||||
|
if not candidates:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail=f"Not connected in Postiz: {platform}")
|
||||||
|
enabled = [i for i in candidates if not i.get("disabled")]
|
||||||
|
if not enabled:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail=f"Disabled in Postiz: {platform}")
|
||||||
|
selected.append(enabled[0])
|
||||||
|
return selected
|
||||||
|
|
||||||
|
|
||||||
def _normalise_postiz_post(post: Any) -> Any:
|
def _normalise_postiz_post(post: Any) -> Any:
|
||||||
|
|
@ -4246,9 +4198,10 @@ async def postiz_post(req: PostizPostRequest, request: Request):
|
||||||
if not os.path.exists(file_path):
|
if not os.path.exists(file_path):
|
||||||
raise HTTPException(status_code=404, detail=f"Video file not found: {file_path}")
|
raise HTTPException(status_code=404, detail=f"Video file not found: {file_path}")
|
||||||
|
|
||||||
|
integration_ids = [str(i).strip() for i in (req.integration_ids or []) if str(i).strip()]
|
||||||
platforms = [str(p).strip().lower() for p in (req.platforms or []) if str(p).strip()]
|
platforms = [str(p).strip().lower() for p in (req.platforms or []) if str(p).strip()]
|
||||||
if not platforms:
|
if not integration_ids and not platforms:
|
||||||
raise HTTPException(status_code=400, detail="No platforms requested")
|
raise HTTPException(status_code=400, detail="No channels requested")
|
||||||
|
|
||||||
caption = (req.description
|
caption = (req.description
|
||||||
or clip.get('video_description_for_instagram')
|
or clip.get('video_description_for_instagram')
|
||||||
|
|
@ -4259,42 +4212,64 @@ async def postiz_post(req: PostizPostRequest, request: Request):
|
||||||
tags = _postiz_hashtags(caption)
|
tags = _postiz_hashtags(caption)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
by_identifier = await _postiz_integrations(base, key)
|
# Resolve the real channels first so a bad id/platform is a 400 before
|
||||||
missing = [p for p in platforms if p not in by_identifier]
|
# the slow media upload starts.
|
||||||
if missing:
|
integrations = await _postiz_integration_list(base, key)
|
||||||
|
selected = _resolve_postiz_integrations(
|
||||||
|
integrations, integration_ids, platforms)
|
||||||
|
if not selected:
|
||||||
|
raise HTTPException(status_code=400, detail="No channels requested")
|
||||||
|
|
||||||
|
if req.scheduled_date:
|
||||||
|
scheduled_at = _postiz_parse_instant(req.scheduled_date, req.timezone)
|
||||||
|
# Allow a minute of clock skew between this server and the client.
|
||||||
|
if scheduled_at < datetime.now(timezone.utc) - timedelta(seconds=60):
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=400,
|
status_code=400,
|
||||||
detail=f"Not connected in Postiz: {', '.join(missing)}")
|
detail="scheduled_date is in the past")
|
||||||
disabled = [p for p in platforms if by_identifier[p].get("disabled")]
|
post_type = "schedule"
|
||||||
if disabled:
|
post_date = scheduled_at.strftime("%Y-%m-%dT%H:%M:%S.000Z")
|
||||||
raise HTTPException(
|
else:
|
||||||
status_code=400,
|
post_type = "now"
|
||||||
detail=f"Disabled in Postiz: {', '.join(disabled)}")
|
post_date = _postiz_iso_date(None, None)
|
||||||
|
|
||||||
media = await asyncio.to_thread(postiz.upload_media, base, key, file_path)
|
media = await asyncio.to_thread(postiz.upload_media, base, key, file_path)
|
||||||
if not media or not media.get("id"):
|
if not media or not media.get("id"):
|
||||||
raise HTTPException(status_code=502, detail="Postiz media upload failed")
|
raise HTTPException(status_code=502, detail="Postiz media upload failed")
|
||||||
|
|
||||||
posts = []
|
posts = []
|
||||||
for platform in platforms:
|
posted = []
|
||||||
integration = by_identifier[platform]
|
for integration in selected:
|
||||||
|
identifier = (integration.get("identifier") or "").strip().lower()
|
||||||
|
platform = _identifier_platform(identifier)
|
||||||
posts.append({
|
posts.append({
|
||||||
"integration": {"id": integration.get("id")},
|
"integration": {"id": integration.get("id")},
|
||||||
"value": [{
|
"value": [{
|
||||||
"content": caption,
|
"content": caption,
|
||||||
"image": [{"id": media.get("id"), "path": media.get("path")}],
|
"image": [{"id": media.get("id"), "path": media.get("path")}],
|
||||||
}],
|
}],
|
||||||
"settings": _postiz_settings(platform, yt_title, caption, tags),
|
"settings": _postiz_settings(identifier, yt_title, caption, tags),
|
||||||
|
})
|
||||||
|
posted.append({
|
||||||
|
"integration_id": integration.get("id"),
|
||||||
|
"identifier": identifier,
|
||||||
|
"platform": platform,
|
||||||
|
"name": integration.get("name"),
|
||||||
})
|
})
|
||||||
|
|
||||||
payload = {
|
payload = {
|
||||||
"type": "schedule" if req.scheduled_date else "now",
|
"type": post_type,
|
||||||
"shortLink": False,
|
"shortLink": False,
|
||||||
"date": _postiz_iso_date(req.scheduled_date, req.timezone),
|
"date": post_date,
|
||||||
"tags": [],
|
"tags": [],
|
||||||
"posts": posts,
|
"posts": posts,
|
||||||
}
|
}
|
||||||
|
# The payload carries no secrets; log it so a "nothing showed up in
|
||||||
|
# Postiz" report is diagnosable from the server log.
|
||||||
|
print(f"📡 Postiz create_post ({post_type}, {len(posts)} post(s)): "
|
||||||
|
f"{json.dumps(payload)[:2000]}")
|
||||||
result = await asyncio.to_thread(postiz.create_post, base, key, payload)
|
result = await asyncio.to_thread(postiz.create_post, base, key, payload)
|
||||||
return {"success": True, "results": result}
|
return {"success": True, "results": result, "posted": posted}
|
||||||
except HTTPException:
|
except HTTPException:
|
||||||
raise
|
raise
|
||||||
except postiz.PostizError as exc:
|
except postiz.PostizError as exc:
|
||||||
|
|
@ -4309,8 +4284,8 @@ async def postiz_integrations(request: Request):
|
||||||
if not key:
|
if not key:
|
||||||
raise HTTPException(status_code=400, detail="Missing X-Postiz-Key header")
|
raise HTTPException(status_code=400, detail="Missing X-Postiz-Key header")
|
||||||
try:
|
try:
|
||||||
integrations = await asyncio.to_thread(postiz.list_integrations, base, key)
|
integrations = await _postiz_integration_list(base, key)
|
||||||
return {"integrations": integrations or []}
|
return {"integrations": integrations}
|
||||||
except postiz.PostizError as exc:
|
except postiz.PostizError as exc:
|
||||||
raise postiz_http_error(exc)
|
raise postiz_http_error(exc)
|
||||||
|
|
||||||
|
|
@ -4849,12 +4824,9 @@ async def thumbnail_publish(
|
||||||
async def do_upload():
|
async def do_upload():
|
||||||
"""Uploads the local video to Postiz and creates the YouTube post."""
|
"""Uploads the local video to Postiz and creates the YouTube post."""
|
||||||
try:
|
try:
|
||||||
by_identifier = await _postiz_integrations(base, key)
|
integrations = await _postiz_integration_list(base, key)
|
||||||
integration = by_identifier.get("youtube")
|
selected = _resolve_postiz_integrations(integrations, [], ["youtube"])
|
||||||
if not integration:
|
integration = selected[0]
|
||||||
raise postiz.PostizError(400, "No YouTube channel connected in Postiz")
|
|
||||||
if integration.get("disabled"):
|
|
||||||
raise postiz.PostizError(400, "YouTube channel is disabled in Postiz")
|
|
||||||
|
|
||||||
media = await asyncio.to_thread(
|
media = await asyncio.to_thread(
|
||||||
postiz.upload_media, base, key, video_path, 600.0)
|
postiz.upload_media, base, key, video_path, 600.0)
|
||||||
|
|
@ -4873,7 +4845,8 @@ async def thumbnail_publish(
|
||||||
"image": [{"id": media.get("id"), "path": media.get("path")}],
|
"image": [{"id": media.get("id"), "path": media.get("path")}],
|
||||||
}],
|
}],
|
||||||
"settings": _postiz_settings(
|
"settings": _postiz_settings(
|
||||||
"youtube", title, description, _postiz_hashtags(description)),
|
integration.get("identifier") or "youtube",
|
||||||
|
title, description, _postiz_hashtags(description)),
|
||||||
}],
|
}],
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,46 +0,0 @@
|
||||||
"""Render the Clipwright watermark lockup (white mark + wordmark) to a PNG.
|
|
||||||
|
|
||||||
Pre-rendered at 4x so it downscales cleanly onto any clip size, with a soft
|
|
||||||
dark shadow so it stays legible over bright footage.
|
|
||||||
"""
|
|
||||||
from PIL import Image, ImageDraw, ImageFont, ImageFilter
|
|
||||||
|
|
||||||
S = 4 # supersampling
|
|
||||||
H = 64 * S # lockup height
|
|
||||||
PAD = 6 * S
|
|
||||||
|
|
||||||
font = ImageFont.truetype("/System/Library/Fonts/HelveticaNeue.ttc", int(38 * S), index=1) # Bold
|
|
||||||
text = "Clipwright"
|
|
||||||
|
|
||||||
tmp = Image.new("RGBA", (10, 10))
|
|
||||||
tb = ImageDraw.Draw(tmp).textbbox((0, 0), text, font=font)
|
|
||||||
tw, th = tb[2] - tb[0], tb[3] - tb[1]
|
|
||||||
|
|
||||||
mark = int(40 * S) # square mark
|
|
||||||
gap = int(12 * S)
|
|
||||||
W = mark + gap + tw + PAD * 2
|
|
||||||
|
|
||||||
img = Image.new("RGBA", (W, H), (0, 0, 0, 0))
|
|
||||||
d = ImageDraw.Draw(img)
|
|
||||||
|
|
||||||
# Rounded square outline + play triangle: reads as "clip/play" at small sizes.
|
|
||||||
mx, my = PAD, (H - mark) // 2
|
|
||||||
r = int(mark * 0.28)
|
|
||||||
d.rounded_rectangle([mx, my, mx + mark, my + mark], radius=r,
|
|
||||||
outline=(255, 255, 255, 255), width=int(3.5 * S))
|
|
||||||
t = mark * 0.30
|
|
||||||
cx, cy = mx + mark / 2, my + mark / 2
|
|
||||||
d.polygon([(cx - t * 0.55, cy - t), (cx - t * 0.55, cy + t), (cx + t * 0.85, cy)],
|
|
||||||
fill=(255, 255, 255, 255))
|
|
||||||
|
|
||||||
d.text((mx + mark + gap - tb[0], (H - th) // 2 - tb[1]), text, font=font,
|
|
||||||
fill=(255, 255, 255, 255))
|
|
||||||
|
|
||||||
# Soft shadow behind everything for contrast on light footage.
|
|
||||||
shadow = Image.new("RGBA", (W, H), (0, 0, 0, 0))
|
|
||||||
shadow.paste((0, 0, 0, 170), (0, 0), img.split()[3])
|
|
||||||
shadow = shadow.filter(ImageFilter.GaussianBlur(int(2.5 * S)))
|
|
||||||
out = Image.alpha_composite(shadow, img)
|
|
||||||
|
|
||||||
out.save("watermark.png")
|
|
||||||
print("watermark.png", out.size)
|
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 62 MiB |
Binary file not shown.
|
Before Width: | Height: | Size: 2.5 MiB |
|
|
@ -53,6 +53,3 @@ 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 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
|
the server so those links are absolute; otherwise they are relative to your
|
||||||
instance.
|
instance.
|
||||||
|
|
||||||
The agent-native version of the same surface is the Clipwright skill in
|
|
||||||
[`skills/clipwright/`](../skills/clipwright/).
|
|
||||||
|
|
|
||||||
|
|
@ -102,7 +102,6 @@
|
||||||
"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",
|
||||||
|
|
@ -162,15 +161,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, and adds AI voice dubbing into 30+ languages, which Opus Clip does not have. Opus Clip ships a larger caption-style library and needs no setup."
|
"text": "Yes. Clipwright self-hosted is a free and open source alternative to Opus Clip, MIT licensed, with no watermark and no usage cap, running on your own machine via Docker. As of July 2026 Opus Clip costs $15 per month for the Starter plan with 150 minutes, and $29 per month for Pro with 300 minutes, on top of a watermarked free tier of 60 minutes. Opus Clip bills one credit per minute of source video imported rather than per clip exported. Clipwright offers comparable AI moment detection using Google Gemini, face-tracked vertical cropping and automatic subtitles. Opus Clip ships a larger caption-style library and needs no setup."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"@type": "Question",
|
"@type": "Question",
|
||||||
"name": "Can Clipwright add subtitles and translate videos?",
|
"name": "Can Clipwright add subtitles to 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. For translation, ElevenLabs AI dubbing translates the audio into more than 30 languages while preserving the original speaker's voice characteristics, and the dubbed audio is then automatically re-transcribed so the burned-in subtitles are in the target language rather than the original."
|
"text": "Yes. Subtitles are generated with faster-whisper at word-level timestamps and burned into the video with FFmpeg, all locally on your own machine."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 171 KiB |
|
|
@ -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 with the <a href="/n8n-youtube-shorts-automation" style="${S.a}">n8n workflow</a>. Just want it free? Start with the <a href="/free-ai-clip-generator" style="${S.a}">free AI clip generator</a>.</p>
|
<p style="${S.p};max-width:44rem;font-size:1.05rem">Turn long videos into viral 9:16 shorts, self-hosted with Docker and free under MIT. Publish to TikTok, Instagram Reels and YouTube Shorts through your own self-hosted <a href="https://postiz.com/" rel="noopener" style="${S.a}">Postiz</a> instance, or wire the REST API into your own pipeline. Just want it free? Start with the <a href="/free-ai-clip-generator" style="${S.a}">free AI clip generator</a>.</p>
|
||||||
<p style="${S.muted};max-width:44rem"><strong style="color:oklch(75% 0.11 150)">No account, no card, no watermark.</strong> Run it yourself: <a style="${S.a}" href="https://git.pbento.pt/pedro-bento/clipwright" rel="noopener">self-host free on GitHub</a> and bring your own Gemini key.</p>
|
<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,8 +146,7 @@ export const LANDING_FALLBACK = `<div id="seo-content" style="background:oklch(1
|
||||||
<a style="${S.a}" href="/opus-pro">Opus Pro</a> ·
|
<a style="${S.a}" href="/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>
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -844,9 +844,7 @@ 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. There is now also an importable
|
nodes cover it.</p>
|
||||||
<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
|
||||||
|
|
@ -868,10 +866,6 @@ ${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.',
|
||||||
|
|
@ -895,141 +889,6 @@ ${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.
|
||||||
*
|
*
|
||||||
|
|
@ -1983,7 +1842,6 @@ export function buildPages() {
|
||||||
podcastToShorts(),
|
podcastToShorts(),
|
||||||
youtubeConverter(),
|
youtubeConverter(),
|
||||||
automateShorts(),
|
automateShorts(),
|
||||||
n8nTemplate(),
|
|
||||||
...toolPages(),
|
...toolPages(),
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
@ -2013,7 +1871,6 @@ 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.',
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
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, Globe, 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, 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';
|
||||||
|
|
@ -216,15 +216,6 @@ 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
|
||||||
|
|
@ -282,9 +273,6 @@ 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);
|
||||||
|
|
@ -463,12 +451,6 @@ function App() {
|
||||||
} catch (_) { /* ignore */ }
|
} catch (_) { /* ignore */ }
|
||||||
}, [postizUrl]);
|
}, [postizUrl]);
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (elevenLabsKey) {
|
|
||||||
localStorage.setItem('elevenLabsKey_v1', encrypt(elevenLabsKey));
|
|
||||||
}
|
|
||||||
}, [elevenLabsKey]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (postizKey && postizUrl && postizChannels.length === 0) {
|
if (postizKey && postizUrl && postizChannels.length === 0) {
|
||||||
fetchPostizChannels({ silent: true });
|
fetchPostizChannels({ silent: true });
|
||||||
|
|
@ -528,12 +510,10 @@ 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);
|
||||||
}
|
}
|
||||||
|
|
@ -790,17 +770,10 @@ function App() {
|
||||||
};
|
};
|
||||||
const tabLocked = (id) => tutorialLock && id !== 'dashboard';
|
const tabLocked = (id) => tutorialLock && id !== 'dashboard';
|
||||||
|
|
||||||
// Shared footer links (landing, repo, pricing, contact) — same list in the
|
// Shared footer links (repo, contact) — same list in the desktop rail and the
|
||||||
// desktop rail and the mobile drawer, so they can never drift apart.
|
// 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"
|
||||||
|
|
@ -824,12 +797,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">
|
||||||
<a href="#landing" className="p-6 flex items-center gap-3" title="go to landing page">
|
<div className="p-6 flex items-center gap-3">
|
||||||
<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>
|
||||||
</a>
|
</div>
|
||||||
|
|
||||||
<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) => {
|
||||||
|
|
@ -880,12 +853,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">
|
||||||
<a href="#landing" className="flex items-center gap-2.5" onClick={() => setNavOpen(false)}>
|
<div className="flex items-center gap-2.5">
|
||||||
<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>
|
||||||
</a>
|
</div>
|
||||||
<button
|
<button
|
||||||
onClick={() => setNavOpen(false)}
|
onClick={() => setNavOpen(false)}
|
||||||
aria-label="close navigation"
|
aria-label="close navigation"
|
||||||
|
|
@ -1161,63 +1134,6 @@ 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>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|
@ -1456,8 +1372,6 @@ function App() {
|
||||||
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}
|
||||||
|
|
|
||||||
|
|
@ -1,742 +0,0 @@
|
||||||
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,21 +1,55 @@
|
||||||
import React, { useState, useEffect, useRef } from 'react';
|
import React, { useState, useEffect, useRef } from 'react';
|
||||||
import { Download, Share2, Instagram, Youtube, Video, AlertCircle, Loader2, Copy, Check, Wand2, Type, Calendar, Languages, FileText, Link2, Scissors, Crosshair, TrendingUp } from 'lucide-react';
|
import { Download, Share2, Instagram, Youtube, AlertCircle, Loader2, Copy, Check, Wand2, Type, Calendar, 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 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';
|
||||||
|
|
||||||
const PLATFORM_OPTIONS = [
|
// Postiz integration identifier -> glyph. Anything we do not special-case falls
|
||||||
{ value: 'tiktok', label: 'tiktok', icon: <Video size={16} /> },
|
// back to a generic share glyph so every connected channel still shows up.
|
||||||
{ value: 'instagram', label: 'instagram', icon: <Instagram size={16} /> },
|
const TikTokGlyph = ({ size = 16 }) => (
|
||||||
{ value: 'youtube', label: 'youtube', icon: <Youtube size={16} /> },
|
<svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
|
||||||
];
|
<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} />;
|
||||||
|
};
|
||||||
|
|
||||||
|
// DD/MM/YYYY + HH:MM parsed into a local Date, with explicit range checks so
|
||||||
|
// 31/02/2026 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: 'Enter both a date (dd/mm/yyyy) and a time.' };
|
||||||
|
const dm = d.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
|
||||||
|
if (!dm) return { error: 'Date must be in dd/mm/yyyy format.' };
|
||||||
|
const day = Number(dm[1]);
|
||||||
|
const month = Number(dm[2]);
|
||||||
|
const year = 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
|
||||||
|
|
@ -33,7 +67,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, elevenLabsKey, onPlay, onPause, onBulkSubtitle, clipCount = 1, bulkProgress, connectedPlatforms = null, onConnectSocials, onEditClip = null, onReframeClip = null }) {
|
export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, geminiApiKey, onPlay, onPause, onBulkSubtitle, clipCount = 1, bulkProgress, 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
|
||||||
|
|
@ -129,15 +163,18 @@ 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]);
|
||||||
|
|
||||||
const [platforms, setPlatforms] = useState({
|
// Publish form state.
|
||||||
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);
|
||||||
|
|
@ -156,9 +193,7 @@ 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 [showTranslateModal, setShowTranslateModal] = useState(false);
|
|
||||||
const [editError, setEditError] = useState(null);
|
const [editError, setEditError] = useState(null);
|
||||||
|
|
||||||
const [clipDuration, setClipDuration] = useState(() => {
|
const [clipDuration, setClipDuration] = useState(() => {
|
||||||
|
|
@ -191,45 +226,78 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
}, [jobId, index]);
|
}, [jobId, index]);
|
||||||
|
|
||||||
// Which platforms the selected profile actually has linked. `null` means
|
// Accounts are connected inside the user's own Postiz instance, so
|
||||||
// unknown (profile list not loaded) — in that case nothing is gated.
|
// "connect" opens it (or Settings when no URL is configured yet).
|
||||||
// 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');
|
||||||
};
|
};
|
||||||
|
|
||||||
// Initialize/Reset form when modal opens
|
// Every integration is a selectable row; disabled ones are listed but not
|
||||||
|
// 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.
|
||||||
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(false);
|
setIsScheduling(false);
|
||||||
setScheduleDate("");
|
setScheduleDate("");
|
||||||
|
setScheduleTime("");
|
||||||
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'),
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
// 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]);
|
}, [showModal, clip]);
|
||||||
|
|
||||||
const handleAutoEdit = async () => {
|
const handleAutoEdit = async () => {
|
||||||
|
|
@ -540,72 +608,11 @@ 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) {
|
||||||
|
|
@ -613,20 +620,22 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (noAccountsConnected) {
|
const enabledIds = integrations.filter((c) => !c.disabled).map((c) => c.id);
|
||||||
setPostResult({ success: false, msg: "Connect a social account first." });
|
const chosen = selectedIds.filter((id) => enabledIds.includes(id));
|
||||||
|
if (chosen.length === 0) {
|
||||||
|
setPostResult({ success: false, msg: "Select at least one channel." });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const selectedPlatforms = Object.keys(platforms).filter(k => platforms[k]);
|
// The date/time is only required when scheduling; "publish now" needs none.
|
||||||
if (selectedPlatforms.length === 0) {
|
let scheduledIso = null;
|
||||||
setPostResult({ success: false, msg: "Select at least one platform." });
|
if (isScheduling) {
|
||||||
|
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);
|
||||||
|
|
@ -636,14 +645,13 @@ 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,
|
||||||
platforms: selectedPlatforms,
|
integration_ids: chosen,
|
||||||
title: postTitle,
|
title: postTitle,
|
||||||
description: postDescription
|
description: postDescription
|
||||||
};
|
};
|
||||||
|
|
||||||
if (isScheduling && scheduleDate) {
|
if (scheduledIso) {
|
||||||
// Convert to ISO-8601
|
payload.scheduled_date = scheduledIso;
|
||||||
payload.scheduled_date = new Date(scheduleDate).toISOString();
|
|
||||||
payload.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
payload.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -659,22 +667,33 @@ 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);
|
||||||
throw new Error(jsonErr.detail || errText);
|
if (typeof jsonErr.detail === 'string') detail = jsonErr.detail;
|
||||||
} catch (e) {
|
} catch { /* keep the raw body */ }
|
||||||
throw new Error(errText);
|
throw new Error(detail || 'Publish failed.');
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
setPostResult({ success: true, msg: isScheduling ? "Scheduled successfully!" : "Posted successfully!" });
|
const data = await res.json();
|
||||||
|
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);
|
||||||
}, 3000);
|
}, 4000);
|
||||||
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setPostResult({ success: false, msg: `Failed: ${e.message}` });
|
setPostResult({ success: false, msg: e.message || 'Publish failed.' });
|
||||||
} finally {
|
} finally {
|
||||||
setPosting(false);
|
setPosting(false);
|
||||||
}
|
}
|
||||||
|
|
@ -885,15 +904,6 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
||||||
{isHooking ? 'saving…' : 'edit hook'}
|
{isHooking ? 'saving…' : 'edit hook'}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<button
|
|
||||||
onClick={() => setShowTranslateModal(true)}
|
|
||||||
disabled={isTranslating}
|
|
||||||
className={QUIET_BTN}
|
|
||||||
>
|
|
||||||
{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" />}
|
|
||||||
{isTranslating ? 'translating…' : 'dub voice'}
|
|
||||||
</button>
|
|
||||||
|
|
||||||
<button
|
<button
|
||||||
onClick={() => setShowModal(true)}
|
onClick={() => setShowModal(true)}
|
||||||
className="btn-primary flex-col gap-1 py-2.5 sm:py-2 px-1 text-[11px] leading-none rounded-input whitespace-nowrap"
|
className="btn-primary flex-col gap-1 py-2.5 sm:py-2 px-1 text-[11px] leading-none rounded-input whitespace-nowrap"
|
||||||
|
|
@ -961,7 +971,7 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
||||||
title="post clip"
|
title="post clip"
|
||||||
size="md"
|
size="md"
|
||||||
footer={
|
footer={
|
||||||
noAccountsConnected ? (
|
canPost && noChannels ? (
|
||||||
<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>
|
||||||
|
|
@ -983,13 +993,6 @@ 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>
|
||||||
|
|
@ -1014,7 +1017,7 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Scheduling */}
|
{/* Scheduling — dd/mm/yyyy + HH:MM */}
|
||||||
<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">
|
||||||
|
|
@ -1031,31 +1034,85 @@ 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="datetime-local"
|
type="text"
|
||||||
|
inputMode="numeric"
|
||||||
value={scheduleDate}
|
value={scheduleDate}
|
||||||
onChange={(e) => setScheduleDate(e.target.value)}
|
onChange={(e) => setScheduleDate(e.target.value)}
|
||||||
className="input-field [color-scheme:dark]"
|
placeholder="dd/mm/yyyy"
|
||||||
|
aria-label="date (dd/mm/yyyy)"
|
||||||
|
className="input-field flex-1"
|
||||||
/>
|
/>
|
||||||
|
<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">e.g. 31/12/2026 at 18:30</p>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Platforms */}
|
{/* Channels — every integration is selectable, by id. */}
|
||||||
|
{canPost && (
|
||||||
<div>
|
<div>
|
||||||
<label className="eyebrow block mb-2">PLATFORMS</label>
|
<label className="eyebrow block mb-2">CHANNELS</label>
|
||||||
<SegmentedControl
|
{integrationsLoading && (
|
||||||
multi
|
<p className="text-xs text-muted lowercase flex items-center gap-2">
|
||||||
columns={3}
|
<Loader2 size={14} className="animate-spin" /> loading channels…
|
||||||
options={platformOptions}
|
</p>
|
||||||
value={Object.keys(platforms).filter(k => platforms[k])}
|
)}
|
||||||
onChange={(arr) => setPlatforms({
|
{!integrationsLoading && integrationsError && (
|
||||||
tiktok: arr.includes('tiktok'),
|
<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">
|
||||||
instagram: arr.includes('instagram'),
|
<AlertCircle size={14} className="mt-0.5 shrink-0" />
|
||||||
youtube: arr.includes('youtube'),
|
<span className="break-words">{integrationsError}</span>
|
||||||
})}
|
|
||||||
/>
|
|
||||||
</div>
|
</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>
|
||||||
|
)}
|
||||||
|
|
||||||
{postResult && (
|
{postResult && (
|
||||||
<div className={postResult.success ? 'badge-ok' : 'badge-danger'}>
|
<div className={postResult.success ? 'badge-ok' : 'badge-danger'}>
|
||||||
|
|
@ -1099,15 +1156,6 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
|
||||||
onRemove={burnedHook ? handleRemoveHook : null}
|
onRemove={burnedHook ? handleRemoveHook : null}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<TranslateModal
|
|
||||||
isOpen={showTranslateModal}
|
|
||||||
onClose={() => setShowTranslateModal(false)}
|
|
||||||
onTranslate={handleTranslate}
|
|
||||||
isProcessing={isTranslating}
|
|
||||||
videoUrl={currentVideoUrl}
|
|
||||||
hasApiKey={!!elevenLabsKey}
|
|
||||||
/>
|
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,154 +0,0 @@
|
||||||
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,234 +0,0 @@
|
||||||
/* 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); }
|
|
||||||
}
|
|
||||||
|
|
@ -1,7 +1,6 @@
|
||||||
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'
|
||||||
|
|
@ -9,33 +8,18 @@ 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 resolveView = () => {
|
const [isLegal, setIsLegal] = useState(() => window.location.hash === '#legal')
|
||||||
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 = () => setView(resolveView());
|
const handleHashChange = () => setIsLegal(window.location.hash === '#legal')
|
||||||
window.addEventListener('hashchange', handleHashChange);
|
window.addEventListener('hashchange', handleHashChange)
|
||||||
return () => window.removeEventListener('hashchange', handleHashChange);
|
return () => window.removeEventListener('hashchange', handleHashChange)
|
||||||
}, []);
|
}, [])
|
||||||
|
|
||||||
const handleLaunchApp = () => {
|
return isLegal ? <Legal /> : <App />
|
||||||
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
|
||||||
|
|
|
||||||
Binary file not shown.
|
|
@ -29,11 +29,10 @@ las constantes de entorno.
|
||||||
La retención de fotos de actor se retiró con la función de vídeo UGC
|
La retención de fotos de actor se retiró con la función de vídeo UGC
|
||||||
(4-oct-2026).
|
(4-oct-2026).
|
||||||
|
|
||||||
## 2. Almacenamiento opcional
|
## 2. Almacenamiento local
|
||||||
|
|
||||||
| Qué | Plazo | Dónde se aplica |
|
| Qué | Plazo | Dónde se aplica |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| Copia de seguridad en S3 | Defínelo tú: AWS lifecycle, o no uses S3 | `s3_uploader.py` (solo si configuras las credenciales S3) |
|
|
||||||
| Clips y proyectos en el disco local | Hasta que los borres o caduque el barrido de trabajos | `app.cleanup_jobs`, `JOB_RETENTION_SECONDS` |
|
| Clips y proyectos en el disco local | Hasta que los borres o caduque el barrido de trabajos | `app.cleanup_jobs`, `JOB_RETENTION_SECONDS` |
|
||||||
|
|
||||||
## 3. Base de datos de la aplicación (si usas cuentas)
|
## 3. Base de datos de la aplicación (si usas cuentas)
|
||||||
|
|
@ -59,7 +58,6 @@ La retención de fotos de actor se retiró con la función de vídeo UGC
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| Log de aplicación (stdout del contenedor) | **7 días** en el log rotatorio de Docker | Requiere `max-size`/`max-file` en el runtime — ver "pendiente" abajo |
|
| Log de aplicación (stdout del contenedor) | **7 días** en el log rotatorio de Docker | Requiere `max-size`/`max-file` en el runtime — ver "pendiente" abajo |
|
||||||
| Alertas operativas | Las conserva el canal que configures | No contienen email ni título de vídeo |
|
| Alertas operativas | Las conserva el canal que configures | No contienen email ni título de vídeo |
|
||||||
| Copias de seguridad de PostgreSQL (opcionales) | Defínelo tú | `ops/pg_backup.sh` si usas la base de datos |
|
|
||||||
| Analítica (OpenPanel, opcional, solo con consentimiento) | Identificadores 13 meses; datos brutos 25 meses | Instancia propia |
|
| Analítica (OpenPanel, opcional, solo con consentimiento) | Identificadores 13 meses; datos brutos 25 meses | Instancia propia |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
@ -70,8 +68,6 @@ La retención de fotos de actor se retiró con la función de vídeo UGC
|
||||||
equivalente en tu runtime) en el contenedor de la API. La fila de 7 días de
|
equivalente en tu runtime) en el contenedor de la API. La fila de 7 días de
|
||||||
arriba describe la intención; hasta que esté configurado, el plazo real depende
|
arriba describe la intención; hasta que esté configurado, el plazo real depende
|
||||||
del demonio de Docker del host.
|
del demonio de Docker del host.
|
||||||
- **Programar `ops/pg_backup.sh`** si usas la base de datos, y hacer **una
|
|
||||||
restauración de prueba**.
|
|
||||||
- **Retención en OpenPanel**: si activas la analítica, confirma en tu instancia
|
- **Retención en OpenPanel**: si activas la analítica, confirma en tu instancia
|
||||||
que los perfiles caducan a 13 meses y los eventos a 25, y borra el perfil por
|
que los perfiles caducan a 13 meses y los eventos a 25, y borra el perfil por
|
||||||
`profileId` cuando llega el evento `AccountDeleted`.
|
`profileId` cuando llega el evento `AccountDeleted`.
|
||||||
|
|
|
||||||
|
|
@ -21,13 +21,11 @@ Es la versión de referencia del apartado 4 de la
|
||||||
| Proveedor | Entidad y país | Qué recibe | Garantía de transferencia | DPA |
|
| Proveedor | Entidad y país | Qué recibe | Garantía de transferencia | DPA |
|
||||||
|---|---|---|---|---|
|
|---|---|---|---|---|
|
||||||
| **Google (Gemini API)** | Google LLC / Google Ireland Ltd. — EE. UU. | Transcripción, fotogramas muestreados (pueden incluir caras), foto de referencia del presentador para miniaturas, y el **archivo de vídeo completo** solo en la comprobación de encuadre "screencast" (se borra del File API en cuanto responde) | EU-US Data Privacy Framework (Google LLC certificado) + CCT | Google Cloud / AI Studio paid data terms — **usa una clave de un proyecto de pago**: los términos gratuitos permiten entrenamiento |
|
| **Google (Gemini API)** | Google LLC / Google Ireland Ltd. — EE. UU. | Transcripción, fotogramas muestreados (pueden incluir caras), foto de referencia del presentador para miniaturas, y el **archivo de vídeo completo** solo en la comprobación de encuadre "screencast" (se borra del File API en cuanto responde) | EU-US Data Privacy Framework (Google LLC certificado) + CCT | Google Cloud / AI Studio paid data terms — **usa una clave de un proyecto de pago**: los términos gratuitos permiten entrenamiento |
|
||||||
| **ElevenLabs** | ElevenLabs Inc. — EE. UU. | Audio del clip para doblaje (voz de personas reales), solo si activas el doblaje | DPF (certificado) + CCT | Pendiente de firma/archivo por tu parte |
|
|
||||||
|
|
||||||
## 2. Almacenamiento (opcional)
|
## 2. Almacenamiento local
|
||||||
|
|
||||||
| Proveedor | Entidad y país | Qué recibe | Garantía | DPA |
|
| Proveedor | Entidad y país | Qué recibe | Garantía | DPA |
|
||||||
|---|---|---|---|---|
|
|---|---|---|---|---|
|
||||||
| **Amazon Web Services (S3)** | AWS EMEA SARL — región `eu-west-3` (París) | Copia de seguridad de clips, solo si configuras las credenciales S3 | Dentro del EEE (región UE) | AWS Service Terms / DPA |
|
|
||||||
| **Almacenamiento local** | Tu propia máquina | Clips, proyectos y miniaturas | Bajo tu control | No aplica |
|
| **Almacenamiento local** | Tu propia máquina | Clips, proyectos y miniaturas | Bajo tu control | No aplica |
|
||||||
|
|
||||||
## 3. Publicación en redes
|
## 3. Publicación en redes
|
||||||
|
|
@ -60,7 +58,7 @@ desactivado y las descargas salen directamente desde tu máquina.
|
||||||
| **fal.ai** | Imágenes y vídeo generados para la función de vídeo UGC con actores | Función retirada; el proyecto ya no usa fal.ai |
|
| **fal.ai** | Imágenes y vídeo generados para la función de vídeo UGC con actores | Función retirada; el proyecto ya no usa fal.ai |
|
||||||
| **Upload-Post** | Publicación en redes y custodia de tokens | Sustituido por una instancia de Postiz autoalojada por el usuario |
|
| **Upload-Post** | Publicación en redes y custodia de tokens | Sustituido por una instancia de Postiz autoalojada por el usuario |
|
||||||
| **Stripe / Aikount** | Pagos y facturación de la edición alojada | La edición alojada y la facturación se retiraron |
|
| **Stripe / Aikount** | Pagos y facturación de la edición alojada | La edición alojada y la facturación se retiraron |
|
||||||
| **Cloudflare R2 / Cloudflare CDN** | Almacenamiento y CDN de la edición alojada | La edición alojada se retiró; el almacenamiento es local o tu propio S3 |
|
| **Cloudflare R2 / Cloudflare CDN** | Almacenamiento y CDN de la edición alojada | La edición alojada se retiró; el almacenamiento es local |
|
||||||
| **Hetzner / Contabo** | Servidores de la edición alojada | La edición alojada se retiró |
|
| **Hetzner / Contabo** | Servidores de la edición alojada | La edición alojada se retiró |
|
||||||
| **Google Fonts** (`fonts.googleapis.com`, `fonts.gstatic.com`) | La IP de cada visitante, en cada carga de página, sin consentimiento y sin base jurídica | 4-sep-2026 — las tipografías se sirven desde el propio dominio (`dashboard/public/fonts.css`) |
|
| **Google Fonts** (`fonts.googleapis.com`, `fonts.gstatic.com`) | La IP de cada visitante, en cada carga de página, sin consentimiento y sin base jurídica | 4-sep-2026 — las tipografías se sirven desde el propio dominio (`dashboard/public/fonts.css`) |
|
||||||
| **openpanel.dev** (script de terceros) | La IP de cada visitante antes de cualquier consentimiento | 4-sep-2026 — `op1.js` se sirve desde el propio dominio y solo tras aceptar |
|
| **openpanel.dev** (script de terceros) | La IP de cada visitante antes de cualquier consentimiento | 4-sep-2026 — `op1.js` se sirve desde el propio dominio y solo tras aceptar |
|
||||||
|
|
@ -74,13 +72,11 @@ instancia:
|
||||||
1. **Usar una clave de Gemini de un proyecto de pago.** Los términos gratuitos de
|
1. **Usar una clave de Gemini de un proyecto de pago.** Los términos gratuitos de
|
||||||
AI Studio permiten usar los datos para mejorar los modelos, lo que haría falsa
|
AI Studio permiten usar los datos para mejorar los modelos, lo que haría falsa
|
||||||
la frase "no se entrena con tu contenido".
|
la frase "no se entrena con tu contenido".
|
||||||
2. **Firmar y archivar** el DPA de ElevenLabs (+ CCT) si activas el doblaje.
|
2. **Identificar al proveedor de proxies estáticos** y el país de DataImpulse, y
|
||||||
Guarda los PDF con fecha.
|
|
||||||
3. **Identificar al proveedor de proxies estáticos** y el país de DataImpulse, y
|
|
||||||
firmar CCT si están fuera del EEE.
|
firmar CCT si están fuera del EEE.
|
||||||
4. **Comprobar que tu instancia de Postiz** describe la custodia de tokens de
|
3. **Comprobar que tu instancia de Postiz** describe la custodia de tokens de
|
||||||
redes sociales; al ser autoalojada, no pasa por TONVI TECH SL.
|
redes sociales; al ser autoalojada, no pasa por TONVI TECH SL.
|
||||||
5. **Sirve los emails de servicio** desde un proveedor con garantías si los
|
4. **Sirve los emails de servicio** desde un proveedor con garantías si los
|
||||||
activas.
|
activas.
|
||||||
|
|
||||||
## Historial de cambios
|
## Historial de cambios
|
||||||
|
|
@ -90,3 +86,4 @@ instancia:
|
||||||
| 2026-09-04 | Primera versión publicada. Altas documentadas: fal.ai, Cloudflare CDN/DNS, Aikount, OpenPanel, proxies de descarga, Google OAuth. Bajas: Google Fonts, script de openpanel.dev y datos personales hacia Telegram. |
|
| 2026-09-04 | Primera versión publicada. Altas documentadas: fal.ai, Cloudflare CDN/DNS, Aikount, OpenPanel, proxies de descarga, Google OAuth. Bajas: Google Fonts, script de openpanel.dev y datos personales hacia Telegram. |
|
||||||
| 2026-10-04 | Baja de fal.ai y de la galería pública UGC/imágenes de actor (función retirada). Sustitución de Upload-Post por una instancia de Postiz autoalojada por el usuario para la publicación en redes. |
|
| 2026-10-04 | Baja de fal.ai y de la galería pública UGC/imágenes de actor (función retirada). Sustitución de Upload-Post por una instancia de Postiz autoalojada por el usuario para la publicación en redes. |
|
||||||
| 2026-10-04 | Reformulado para la edición autoalojada: se eliminan la infraestructura alojada (Hetzner/Contabo, Cloudflare R2/CDN), los pagos (Stripe, Aikount), el correo gestionado (Namecheap) y el inicio de sesión con Google. El usuario es el responsable del tratamiento. |
|
| 2026-10-04 | Reformulado para la edición autoalojada: se eliminan la infraestructura alojada (Hetzner/Contabo, Cloudflare R2/CDN), los pagos (Stripe, Aikount), el correo gestionado (Namecheap) y el inicio de sesión con Google. El usuario es el responsable del tratamiento. |
|
||||||
|
| 2026-10-04 | Baja de la copia de seguridad en S3 y del doblaje de voz (funciones retiradas): se eliminan sus proveedores y variables de entorno. El almacenamiento es siempre local. |
|
||||||
|
|
|
||||||
|
|
@ -1,102 +0,0 @@
|
||||||
# Notice and action: what we actually do when a report arrives
|
|
||||||
|
|
||||||
The public half of this lives at `/report-content` and `/reportar-contenido`
|
|
||||||
(`dashboard/seo/legal.js`). This file is the half nobody outside sees: the
|
|
||||||
timings, the templates and the rule for repeat infringers. Publishing a
|
|
||||||
mechanism we do not run is worse than publishing nothing, because the page is
|
|
||||||
then evidence that we knew what was required.
|
|
||||||
|
|
||||||
## What applies to us, and what does not
|
|
||||||
|
|
||||||
TONVI TECH SL is a **hosting service** and a **micro enterprise**. That
|
|
||||||
combination decides most of this, so check it before adding work:
|
|
||||||
|
|
||||||
| Duty | Applies? |
|
|
||||||
|---|---|
|
|
||||||
| Arts. 11-12, single point of contact (users, authorities) | Yes. `https://git.pbento.pt/pedro-bento/clipwright`, published |
|
|
||||||
| Art. 14, terms with the restrictions we impose | Yes. Terms §8 and §9 |
|
|
||||||
| Art. 16, notice and action | **Yes. This document** |
|
|
||||||
| Art. 17, statement of reasons | **Yes. Template below** |
|
|
||||||
| Art. 15, transparency reports | No. Micro/small exemption, art. 15(2) |
|
|
||||||
| Arts. 20-28, complaints system, trusted flaggers, ODR obligations | No. Those bind *online platforms*, and art. 19 exempts micro/small ones anyway |
|
|
||||||
|
|
||||||
We are not an online platform: we store clips at the direction of a user, we do
|
|
||||||
not disseminate them to the public. Publishing to a user's own social accounts
|
|
||||||
is done on their instruction and they are the publisher, which Terms §10 says.
|
|
||||||
If that ever changes (a public gallery, shared clip feeds), this table changes
|
|
||||||
with it and arts. 20-24 come into play.
|
|
||||||
|
|
||||||
## The clock
|
|
||||||
|
|
||||||
1. **Acknowledge receipt without undue delay.** Art. 16(4). Same working day.
|
|
||||||
This is the step most likely to be missed, because it has to happen before
|
|
||||||
anyone has decided anything.
|
|
||||||
2. **Decide diligently, non-arbitrarily, objectively.** Art. 16(6). Target 72
|
|
||||||
hours; sooner for anything involving minors, which goes first, always.
|
|
||||||
3. **Tell the notifier what we decided and why**, with their redress options.
|
|
||||||
Art. 16(5).
|
|
||||||
4. **Tell the affected user**, with the statement of reasons below. Art. 17.
|
|
||||||
|
|
||||||
A notice that carries all four elements the public page asks for gives us
|
|
||||||
**actual knowledge**. From that moment the hosting exemption of art. 6 stops
|
|
||||||
covering that specific content, so the clock is not a courtesy.
|
|
||||||
|
|
||||||
## Templates
|
|
||||||
|
|
||||||
**Acknowledgement** (immediately, to the notifier)
|
|
||||||
|
|
||||||
> We received your report on <date> and it has reference <id>. We will review it
|
|
||||||
> and write back with our decision and the reasons for it. If we need anything
|
|
||||||
> else to identify the content, we will ask.
|
|
||||||
|
|
||||||
**Decision, to the notifier**
|
|
||||||
|
|
||||||
> About your report <id> of <date>: we have <removed the content / disabled
|
|
||||||
> access to it / decided not to act>. <One paragraph of why.> If you disagree,
|
|
||||||
> you can take the matter to a court, or to an out-of-court dispute settlement
|
|
||||||
> body certified under Article 21 DSA.
|
|
||||||
|
|
||||||
**Statement of reasons, to the affected user** (art. 17(3) wants all of these,
|
|
||||||
so keep every line even when one is short)
|
|
||||||
|
|
||||||
> - What we did: <removed / disabled access / restricted the account>, and to
|
|
||||||
> which content, identified precisely.
|
|
||||||
> - Facts relied on: <what the notice said, what we checked ourselves>.
|
|
||||||
> - Ground: <the law it breaches, or the clause of our Terms>.
|
|
||||||
> - Automated means: none. A person reviewed this. <Change only if that stops
|
|
||||||
> being true.>
|
|
||||||
> - Territorial scope: <worldwide / EU only>.
|
|
||||||
> - How to challenge it: reply to this message, or write to
|
|
||||||
> https://git.pbento.pt/pedro-bento/clipwright. A person reviews it. You may also go to an Article 21
|
|
||||||
> dispute settlement body or to the courts.
|
|
||||||
|
|
||||||
## Repeat infringers
|
|
||||||
|
|
||||||
The public pages say repeat infringers are terminated; here is what that means,
|
|
||||||
because "reasonably implemented" is the test both the DSA and DMCA 512(i) use
|
|
||||||
and an unwritten rule fails it.
|
|
||||||
|
|
||||||
- One substantiated notice against a user is a **strike**. A notice we rejected
|
|
||||||
is not.
|
|
||||||
- Strike 1 and 2: content removed, user told, strike recorded with the notice
|
|
||||||
reference and date.
|
|
||||||
- **Strike 3: the account is terminated** and re-registration blocked, as Terms
|
|
||||||
§8 allows.
|
|
||||||
- A strike ages out after 12 months.
|
|
||||||
- Manifest cases (CSAM, a court order, an obvious wholesale rip of a
|
|
||||||
commercial film) skip the count and terminate immediately.
|
|
||||||
|
|
||||||
Record strikes where they survive a redeploy, not in someone's inbox.
|
|
||||||
|
|
||||||
## Bad-faith notifiers
|
|
||||||
|
|
||||||
Someone who repeatedly sends manifestly unfounded notices gets a **warning
|
|
||||||
naming the behaviour**, then suspension of the processing of their notices for
|
|
||||||
a reasonable period. Warning first, always: art. 23(2) allows the suspension
|
|
||||||
only after it, and the pattern has to be more than two mistakes.
|
|
||||||
|
|
||||||
## Retention
|
|
||||||
|
|
||||||
Notices, decisions and strikes are kept 5 years, matching the rights
|
|
||||||
declarations in the privacy policy (§5). They are the evidence that we acted
|
|
||||||
diligently, and evidence nobody kept is evidence nobody has.
|
|
||||||
|
|
@ -1,102 +0,0 @@
|
||||||
# Clipwright + n8n
|
|
||||||
|
|
||||||
Two importable workflows, from a one-shot clipper to a channel watcher.
|
|
||||||
|
|
||||||
Both run against a self-hosted Clipwright instance (point them at your base URL,
|
|
||||||
default `http://localhost:8000`) and publish through a self-hosted
|
|
||||||
[Postiz](https://postiz.com/) instance. No Clipwright API key is required, but
|
|
||||||
the server needs a Google Gemini key for the AI stages, and Postiz needs the
|
|
||||||
target channels connected. The publishing, queue and analytics calls need the
|
|
||||||
instance configured with `POSTIZ_URL` / `POSTIZ_API_KEY` (or an `X-Postiz-Key`
|
|
||||||
header sent per request); the workflow nodes hold no credential of their own.
|
|
||||||
|
|
||||||
| Workflow | What it does | Credentials |
|
|
||||||
|---|---|---|
|
|
||||||
| `clipwright-clip-and-notify.json` | A video URL goes in through a form, clips come back on a signed webhook. No polling. | None (self-hosted) |
|
|
||||||
| `clipwright-content-machine.json` | Watches your YouTube channel: daily clipping, approval buttons in Telegram, drip-scheduled posting through Postiz, weekly analytics digest. | Telegram bot |
|
|
||||||
|
|
||||||
## Shared setup
|
|
||||||
|
|
||||||
1. In n8n: **Workflows → Import from file** → pick the workflow.
|
|
||||||
2. Set `CLIPWRIGHT_URL` / the request base URL to your instance
|
|
||||||
(`http://localhost:8000`).
|
|
||||||
3. Open the **Clips ready (webhook)** node, copy its production URL, and paste
|
|
||||||
it as `webhook_url` inside the **Start Clipwright job** node body.
|
|
||||||
4. Optional: change `webhook_secret`. Clipwright signs the webhook body with
|
|
||||||
HMAC-SHA256 and sends it as `X-Clipwright-Signature: sha256=<hex>`; verify
|
|
||||||
it in a Code node with:
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const crypto = require('crypto');
|
|
||||||
const expected = 'sha256=' + crypto
|
|
||||||
.createHmac('sha256', 'change-me')
|
|
||||||
.update(JSON.stringify($json.body))
|
|
||||||
.digest('hex');
|
|
||||||
```
|
|
||||||
|
|
||||||
## The Content Machine
|
|
||||||
|
|
||||||
`clipwright-content-machine.json` runs your channel in four acts:
|
|
||||||
|
|
||||||
1. **Watch** — once a day it reads your channel's RSS feed
|
|
||||||
(`https://www.youtube.com/feeds/videos.xml?channel_id=UC...`) and clips
|
|
||||||
**one** video: the newest upload if there is one, otherwise the next
|
|
||||||
unprocessed video from your back catalog. One video a day keeps processing
|
|
||||||
predictable.
|
|
||||||
2. **Approve from your phone** — every finished clip lands in Telegram with
|
|
||||||
✅ Publish / ❌ Skip buttons. Clips over Telegram's ~20 MB URL limit fall
|
|
||||||
back to a link message with the same buttons.
|
|
||||||
3. **Drip-publish** — each approved clip takes the next free daily slot and is
|
|
||||||
scheduled through `POST /api/postiz/post` to every channel connected in
|
|
||||||
Postiz. Approve five clips today, fill five days of content. The slot comes
|
|
||||||
from the queue the server actually holds (`GET /api/postiz/scheduled`), so
|
|
||||||
two clips approved seconds apart cannot book the same one.
|
|
||||||
4. **Sunday digest** — once a week it lists the channels connected in Postiz
|
|
||||||
(`GET /api/postiz/integrations`) and reports each channel's impressions over
|
|
||||||
the last 7 days (`GET /api/postiz/analytics?integration=<id>&days=7`).
|
|
||||||
|
|
||||||
Machine-specific setup, all inside sticky notes on the canvas:
|
|
||||||
|
|
||||||
- Put your channel id in the **Channel RSS feed** node.
|
|
||||||
- Create a Telegram bot with [@BotFather](https://t.me/BotFather), add the
|
|
||||||
`Telegram bot` credential, and replace `YOUR_TELEGRAM_CHAT_ID` in the
|
|
||||||
notification nodes (message your bot, then check
|
|
||||||
`api.telegram.org/bot<token>/getUpdates` for your chat id).
|
|
||||||
- Connect your social accounts in your self-hosted Postiz instance — the
|
|
||||||
posting step uses them directly; no extra social credentials in n8n.
|
|
||||||
|
|
||||||
Note: the machine remembers which videos it already processed in n8n workflow
|
|
||||||
static data, which only persists for **production** executions — test runs in
|
|
||||||
the editor won't advance it. Scheduling deliberately does *not* use that
|
|
||||||
mechanism (see act 3).
|
|
||||||
|
|
||||||
## Webhook payload
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"event": "job.completed",
|
|
||||||
"job_id": "…",
|
|
||||||
"status": "completed",
|
|
||||||
"clips": [
|
|
||||||
{ "index": 0, "title": "…", "video_url": "…" }
|
|
||||||
]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Failed jobs fire the same webhook with `"event": "job.failed"` and an `error`
|
|
||||||
field, so the flow never hangs waiting.
|
|
||||||
|
|
||||||
Each `video_url` is relative to your instance unless the server sets
|
|
||||||
`PUBLIC_API_URL`; point it at a host Telegram can reach (a `localhost` instance
|
|
||||||
is not reachable from Telegram's servers).
|
|
||||||
|
|
||||||
## Publishing and analytics API
|
|
||||||
|
|
||||||
Direct posting: `POST /api/postiz/post` (accepts `scheduled_date`, ISO-8601).
|
|
||||||
Connected channels: `GET /api/postiz/integrations`.
|
|
||||||
Publishing queue: `GET /api/postiz/scheduled`, and
|
|
||||||
`DELETE /api/postiz/scheduled/{id}` to cancel one before it goes out.
|
|
||||||
Analytics: `GET /api/postiz/analytics?integration=<id>&days=7` (one channel) and
|
|
||||||
`GET /api/postiz/analytics/posts?post_id=<id>&days=7` (one post) — both the
|
|
||||||
channel and the post id are required.
|
|
||||||
Full API reference: `/docs` (OpenAPI) on your instance.
|
|
||||||
|
|
@ -1,293 +0,0 @@
|
||||||
{
|
|
||||||
"name": "Clipwright: video URL in, published-ready clips out (no polling)",
|
|
||||||
"nodes": [
|
|
||||||
{
|
|
||||||
"parameters": {
|
|
||||||
"content": "## Clipwright + n8n, the whole loop\n\n**One HTTP request starts the job, one signed webhook ends it.** No polling loop, no wait nodes.\n\n### Setup (3 steps)\n1. Point the *Start Clipwright job* node at your self-hosted instance (`http://localhost:8000`); no API key is needed on a self-hosted instance.\n2. Open the *Clips ready* webhook node, copy its **production** URL, and paste it as `webhook_url` in the *Start Clipwright job* node body.\n3. Optional: set your own `webhook_secret`. Clipwright signs the body with HMAC-SHA256 in the `X-Clipwright-Signature` header (`sha256=<hex>`), so you can verify the sender.\n\n### What you get back\n`event`, `job_id`, `status`, and `clips[]` with `title` and `video_url` per clip. Failed jobs also fire the webhook with an `error` field, so the flow never hangs.\n\nAPI docs: http://localhost:8000/docs \u00b7 Self-hosted works the same on your own machine (MIT).",
|
|
||||||
"height": 460,
|
|
||||||
"width": 480
|
|
||||||
},
|
|
||||||
"id": "note-setup",
|
|
||||||
"name": "Sticky Note",
|
|
||||||
"type": "n8n-nodes-base.stickyNote",
|
|
||||||
"typeVersion": 1,
|
|
||||||
"position": [
|
|
||||||
-560,
|
|
||||||
-80
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"parameters": {
|
|
||||||
"formTitle": "Clip a video with Clipwright",
|
|
||||||
"formDescription": "Paste a YouTube link (or any public video URL). You get 3-15 vertical clips with subtitles back.",
|
|
||||||
"formFields": {
|
|
||||||
"values": [
|
|
||||||
{
|
|
||||||
"fieldLabel": "Video URL",
|
|
||||||
"requiredField": true
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"options": {}
|
|
||||||
},
|
|
||||||
"id": "form-trigger",
|
|
||||||
"name": "Video URL form",
|
|
||||||
"type": "n8n-nodes-base.formTrigger",
|
|
||||||
"typeVersion": 2,
|
|
||||||
"position": [
|
|
||||||
-80,
|
|
||||||
0
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"parameters": {
|
|
||||||
"method": "POST",
|
|
||||||
"url": "http://localhost:8000/api/process",
|
|
||||||
"sendBody": true,
|
|
||||||
"specifyBody": "json",
|
|
||||||
"jsonBody": "={\n \"url\": \"{{ $json['Video URL'] }}\",\n \"acknowledged\": true,\n \"webhook_url\": \"PASTE_THE_PRODUCTION_URL_OF_THE_CLIPS-READY_WEBHOOK_NODE_HERE\",\n \"webhook_secret\": \"change-me\"\n}",
|
|
||||||
"options": {}
|
|
||||||
},
|
|
||||||
"id": "start-job",
|
|
||||||
"name": "Start Clipwright job",
|
|
||||||
"type": "n8n-nodes-base.httpRequest",
|
|
||||||
"typeVersion": 4.2,
|
|
||||||
"position": [
|
|
||||||
180,
|
|
||||||
0
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"parameters": {
|
|
||||||
"assignments": {
|
|
||||||
"assignments": [
|
|
||||||
{
|
|
||||||
"id": "a1",
|
|
||||||
"name": "job_id",
|
|
||||||
"value": "={{ $json.job_id }}",
|
|
||||||
"type": "string"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "a2",
|
|
||||||
"name": "status",
|
|
||||||
"value": "={{ $json.status }}",
|
|
||||||
"type": "string"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"options": {}
|
|
||||||
},
|
|
||||||
"id": "job-queued",
|
|
||||||
"name": "Job queued",
|
|
||||||
"type": "n8n-nodes-base.set",
|
|
||||||
"typeVersion": 3.4,
|
|
||||||
"position": [
|
|
||||||
440,
|
|
||||||
0
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"parameters": {
|
|
||||||
"httpMethod": "POST",
|
|
||||||
"path": "clipwright-clips-ready",
|
|
||||||
"options": {}
|
|
||||||
},
|
|
||||||
"id": "clips-webhook",
|
|
||||||
"name": "Clips ready (webhook)",
|
|
||||||
"type": "n8n-nodes-base.webhook",
|
|
||||||
"typeVersion": 2,
|
|
||||||
"position": [
|
|
||||||
-80,
|
|
||||||
320
|
|
||||||
],
|
|
||||||
"webhookId": "2f8351c1-d51d-4af7-bab3-57f21e07956d"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"parameters": {
|
|
||||||
"conditions": {
|
|
||||||
"options": {
|
|
||||||
"caseSensitive": true,
|
|
||||||
"typeValidation": "strict",
|
|
||||||
"version": 2
|
|
||||||
},
|
|
||||||
"conditions": [
|
|
||||||
{
|
|
||||||
"id": "c1",
|
|
||||||
"leftValue": "={{ $json.body.event }}",
|
|
||||||
"rightValue": "job.completed",
|
|
||||||
"operator": {
|
|
||||||
"type": "string",
|
|
||||||
"operation": "equals"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"combinator": "and"
|
|
||||||
},
|
|
||||||
"options": {}
|
|
||||||
},
|
|
||||||
"id": "if-completed",
|
|
||||||
"name": "Job completed?",
|
|
||||||
"type": "n8n-nodes-base.if",
|
|
||||||
"typeVersion": 2.2,
|
|
||||||
"position": [
|
|
||||||
180,
|
|
||||||
320
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"parameters": {
|
|
||||||
"fieldToSplitOut": "body.clips",
|
|
||||||
"options": {}
|
|
||||||
},
|
|
||||||
"id": "split-clips",
|
|
||||||
"name": "One item per clip",
|
|
||||||
"type": "n8n-nodes-base.splitOut",
|
|
||||||
"typeVersion": 1,
|
|
||||||
"position": [
|
|
||||||
440,
|
|
||||||
220
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"parameters": {
|
|
||||||
"assignments": {
|
|
||||||
"assignments": [
|
|
||||||
{
|
|
||||||
"id": "b1",
|
|
||||||
"name": "title",
|
|
||||||
"value": "={{ $json.title }}",
|
|
||||||
"type": "string"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "b2",
|
|
||||||
"name": "video_url",
|
|
||||||
"value": "={{ $json.video_url }}",
|
|
||||||
"type": "string"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"options": {}
|
|
||||||
},
|
|
||||||
"id": "clip-links",
|
|
||||||
"name": "Clip title + download link",
|
|
||||||
"type": "n8n-nodes-base.set",
|
|
||||||
"typeVersion": 3.4,
|
|
||||||
"position": [
|
|
||||||
700,
|
|
||||||
220
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"parameters": {
|
|
||||||
"assignments": {
|
|
||||||
"assignments": [
|
|
||||||
{
|
|
||||||
"id": "e1",
|
|
||||||
"name": "job_id",
|
|
||||||
"value": "={{ $json.body.job_id }}",
|
|
||||||
"type": "string"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "e2",
|
|
||||||
"name": "error",
|
|
||||||
"value": "={{ $json.body.error }}",
|
|
||||||
"type": "string"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"options": {}
|
|
||||||
},
|
|
||||||
"id": "job-failed",
|
|
||||||
"name": "Job failed",
|
|
||||||
"type": "n8n-nodes-base.set",
|
|
||||||
"typeVersion": 3.4,
|
|
||||||
"position": [
|
|
||||||
440,
|
|
||||||
420
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"parameters": {
|
|
||||||
"content": "## Do something with the clips\n\nConnect *Clip title + download link* to whatever comes next: a Slack or email notification, a Google Sheet log, or publish them via `POST /api/postiz/post`.\n\nEach item here is one finished 9:16 clip with subtitles burned in.",
|
|
||||||
"height": 220,
|
|
||||||
"width": 340
|
|
||||||
},
|
|
||||||
"id": "note-next",
|
|
||||||
"name": "Sticky Note 2",
|
|
||||||
"type": "n8n-nodes-base.stickyNote",
|
|
||||||
"typeVersion": 1,
|
|
||||||
"position": [
|
|
||||||
960,
|
|
||||||
180
|
|
||||||
]
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"connections": {
|
|
||||||
"Video URL form": {
|
|
||||||
"main": [
|
|
||||||
[
|
|
||||||
{
|
|
||||||
"node": "Start Clipwright job",
|
|
||||||
"type": "main",
|
|
||||||
"index": 0
|
|
||||||
}
|
|
||||||
]
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"Start Clipwright job": {
|
|
||||||
"main": [
|
|
||||||
[
|
|
||||||
{
|
|
||||||
"node": "Job queued",
|
|
||||||
"type": "main",
|
|
||||||
"index": 0
|
|
||||||
}
|
|
||||||
]
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"Clips ready (webhook)": {
|
|
||||||
"main": [
|
|
||||||
[
|
|
||||||
{
|
|
||||||
"node": "Job completed?",
|
|
||||||
"type": "main",
|
|
||||||
"index": 0
|
|
||||||
}
|
|
||||||
]
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"Job completed?": {
|
|
||||||
"main": [
|
|
||||||
[
|
|
||||||
{
|
|
||||||
"node": "One item per clip",
|
|
||||||
"type": "main",
|
|
||||||
"index": 0
|
|
||||||
}
|
|
||||||
],
|
|
||||||
[
|
|
||||||
{
|
|
||||||
"node": "Job failed",
|
|
||||||
"type": "main",
|
|
||||||
"index": 0
|
|
||||||
}
|
|
||||||
]
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"One item per clip": {
|
|
||||||
"main": [
|
|
||||||
[
|
|
||||||
{
|
|
||||||
"node": "Clip title + download link",
|
|
||||||
"type": "main",
|
|
||||||
"index": 0
|
|
||||||
}
|
|
||||||
]
|
|
||||||
]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"settings": {
|
|
||||||
"executionOrder": "v1"
|
|
||||||
},
|
|
||||||
"pinData": {}
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,91 +0,0 @@
|
||||||
# ops/
|
|
||||||
|
|
||||||
Operational scripts for Clipwright Cloud. Nothing here runs automatically:
|
|
||||||
each file is installed and scheduled on the host that needs it.
|
|
||||||
|
|
||||||
## `pg_backup.sh` — encrypted PostgreSQL backups, 30-day retention
|
|
||||||
|
|
||||||
The only backup mechanism this project has ever had in version control. Art.
|
|
||||||
32.1.c GDPR requires being able to restore availability of personal data after
|
|
||||||
an incident, and the privacy policy now states that a deletion is gone from
|
|
||||||
every copy within 30 days — this script is what makes both sentences true.
|
|
||||||
|
|
||||||
### What it does
|
|
||||||
|
|
||||||
1. `pg_dump` the cloud database (plain SQL, `--no-owner --no-privileges`).
|
|
||||||
2. gzip and **encrypt** it, in the same pipeline, with `age` (recommended) or
|
|
||||||
`gpg`. Only ciphertext ever touches the disk or the bucket. Without a
|
|
||||||
recipient key configured the script exits with an error rather than writing a
|
|
||||||
readable dump — a plaintext copy of `users` in an object store is the
|
|
||||||
incident this file exists to prevent.
|
|
||||||
3. Upload to `s3://…` (works with Cloudflare R2 via `BACKUP_S3_ENDPOINT`) or
|
|
||||||
`gs://…`.
|
|
||||||
4. Delete backups older than `RETENTION_DAYS` (default 30).
|
|
||||||
|
|
||||||
### Install
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# On the database host (el servidor de la base de datos), as root:
|
|
||||||
apt-get install -y postgresql-client age awscli # or gnupg instead of age
|
|
||||||
install -m 0750 ops/pg_backup.sh /opt/clipwright/ops/pg_backup.sh
|
|
||||||
```
|
|
||||||
|
|
||||||
Generate a key pair **on your laptop, not on the server** — the server only
|
|
||||||
ever needs the public half, which is the whole point:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
age-keygen -o clipwright-backup.key # keep this file in a password manager
|
|
||||||
grep 'public key' clipwright-backup.key # -> age1... goes on the server
|
|
||||||
```
|
|
||||||
|
|
||||||
Then create `/etc/clipwright-backup.env` (mode `0600`):
|
|
||||||
|
|
||||||
```sh
|
|
||||||
DATABASE_URL="postgres://user:pass@127.0.0.1:5432/clipwright"
|
|
||||||
BACKUP_AGE_RECIPIENT="age1................................................"
|
|
||||||
BACKUP_DEST="s3://clipwright-backups/pg"
|
|
||||||
BACKUP_S3_ENDPOINT="https://<accountid>.r2.cloudflarestorage.com"
|
|
||||||
AWS_ACCESS_KEY_ID="..." # an R2 token scoped to THIS bucket only
|
|
||||||
AWS_SECRET_ACCESS_KEY="..."
|
|
||||||
RETENTION_DAYS=30
|
|
||||||
```
|
|
||||||
|
|
||||||
Dry run first — it dumps and encrypts locally but uploads nothing:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
set -a; . /etc/clipwright-backup.env; set +a
|
|
||||||
DRY_RUN=1 /opt/clipwright/ops/pg_backup.sh
|
|
||||||
```
|
|
||||||
|
|
||||||
Schedule it:
|
|
||||||
|
|
||||||
```cron
|
|
||||||
15 3 * * * set -a; . /etc/clipwright-backup.env; set +a; /opt/clipwright/ops/pg_backup.sh >> /var/log/clipwright-backup.log 2>&1
|
|
||||||
```
|
|
||||||
|
|
||||||
### Restore (do this once, before you need it)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
aws s3 cp --endpoint-url "$BACKUP_S3_ENDPOINT" \
|
|
||||||
s3://clipwright-backups/pg/clipwright-pg-20260904T031500Z.sql.gz.age .
|
|
||||||
age -d -i clipwright-backup.key clipwright-pg-*.sql.gz.age | gunzip \
|
|
||||||
| psql "postgres://…/clipwright_restore_test"
|
|
||||||
psql "postgres://…/clipwright_restore_test" -c 'select count(*) from users;'
|
|
||||||
```
|
|
||||||
|
|
||||||
A backup nobody has restored is a hypothesis. Write down the date of the last
|
|
||||||
successful restore test somewhere a person will read.
|
|
||||||
|
|
||||||
### Things to keep true
|
|
||||||
|
|
||||||
- **The bucket is not public and not the same bucket as user clips.** Give the
|
|
||||||
backup token write access to its own bucket and nothing else.
|
|
||||||
- **The private key is not on the server.** If it were, an attacker with the
|
|
||||||
server has both the ciphertext and the key.
|
|
||||||
- **`RETENTION_DAYS` and the privacy policy move together.** The policy tells
|
|
||||||
users a deletion disappears from backups within 30 days
|
|
||||||
(`docs/compliance/retencion.md`, `dashboard/seo/legal.js` §5). Raising the
|
|
||||||
retention without changing that text makes the policy false.
|
|
||||||
- **Object-lock / versioning on the bucket would defeat the retention.** If you
|
|
||||||
enable it for ransomware protection, set the lock window to the same 30 days,
|
|
||||||
not longer.
|
|
||||||
|
|
@ -10,7 +10,6 @@ py3langid==0.3.0
|
||||||
google-genai>=2,<3
|
google-genai>=2,<3
|
||||||
python-dotenv==1.2.2
|
python-dotenv==1.2.2
|
||||||
mediapipe==0.10.14
|
mediapipe==0.10.14
|
||||||
boto3==1.43.4
|
|
||||||
|
|
||||||
fastapi==0.136.1
|
fastapi==0.136.1
|
||||||
uvicorn==0.46.0
|
uvicorn==0.46.0
|
||||||
|
|
|
||||||
|
|
@ -1,90 +0,0 @@
|
||||||
import os
|
|
||||||
from dotenv import load_dotenv
|
|
||||||
load_dotenv()
|
|
||||||
import boto3
|
|
||||||
from botocore.exceptions import ClientError
|
|
||||||
import logging
|
|
||||||
|
|
||||||
# Configure silent logging for boto3 and botocore
|
|
||||||
logging.getLogger('boto3').setLevel(logging.CRITICAL)
|
|
||||||
logging.getLogger('botocore').setLevel(logging.CRITICAL)
|
|
||||||
logging.getLogger('s3transfer').setLevel(logging.CRITICAL)
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
logger.setLevel(logging.INFO)
|
|
||||||
|
|
||||||
def upload_file_to_s3(file_path, bucket_name, s3_key):
|
|
||||||
"""
|
|
||||||
Upload a file to an S3 bucket silently.
|
|
||||||
"""
|
|
||||||
access_key = os.environ.get('AWS_ACCESS_KEY_ID')
|
|
||||||
secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY')
|
|
||||||
region = os.environ.get('AWS_REGION', 'eu-west-3')
|
|
||||||
|
|
||||||
if not access_key or not secret_key:
|
|
||||||
return False
|
|
||||||
|
|
||||||
s3_client = boto3.client(
|
|
||||||
's3',
|
|
||||||
aws_access_key_id=access_key,
|
|
||||||
aws_secret_access_key=secret_key,
|
|
||||||
region_name=region
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
s3_client.upload_file(file_path, bucket_name, s3_key)
|
|
||||||
return True
|
|
||||||
except ClientError:
|
|
||||||
return False
|
|
||||||
except Exception:
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
from botocore.config import Config
|
|
||||||
|
|
||||||
def get_s3_client():
|
|
||||||
"""Returns an authenticated S3 client."""
|
|
||||||
access_key = os.environ.get('AWS_ACCESS_KEY_ID')
|
|
||||||
secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY')
|
|
||||||
region = os.environ.get('AWS_REGION', 'eu-west-3')
|
|
||||||
|
|
||||||
if not access_key or not secret_key:
|
|
||||||
return None
|
|
||||||
|
|
||||||
return boto3.client(
|
|
||||||
's3',
|
|
||||||
aws_access_key_id=access_key,
|
|
||||||
aws_secret_access_key=secret_key,
|
|
||||||
region_name=region,
|
|
||||||
config=Config(signature_version='s3v4')
|
|
||||||
)
|
|
||||||
|
|
||||||
def generate_presigned_url(bucket_name, object_key, expiration=3600):
|
|
||||||
"""Generate a presigned URL to share an S3 object."""
|
|
||||||
s3_client = get_s3_client()
|
|
||||||
if not s3_client:
|
|
||||||
return None
|
|
||||||
try:
|
|
||||||
response = s3_client.generate_presigned_url('get_object',
|
|
||||||
Params={'Bucket': bucket_name,
|
|
||||||
'Key': object_key},
|
|
||||||
ExpiresIn=expiration)
|
|
||||||
return response
|
|
||||||
except ClientError as e:
|
|
||||||
logger.error(e)
|
|
||||||
return None
|
|
||||||
|
|
||||||
def upload_job_artifacts(directory, job_id):
|
|
||||||
"""
|
|
||||||
Upload all generated clips and metadata for a job to S3.
|
|
||||||
"""
|
|
||||||
bucket_name = os.environ.get('AWS_S3_BUCKET', 'my-clips-bucket')
|
|
||||||
|
|
||||||
if not os.path.exists(directory):
|
|
||||||
return
|
|
||||||
|
|
||||||
for filename in os.listdir(directory):
|
|
||||||
# Upload .mp4 clips and the metadata JSON
|
|
||||||
if (filename.endswith(".mp4") or filename.endswith(".json")) and not filename.startswith("temp_"):
|
|
||||||
file_path = os.path.join(directory, filename)
|
|
||||||
s3_key = f"{job_id}/{filename}"
|
|
||||||
upload_file_to_s3(file_path, bucket_name, s3_key)
|
|
||||||
|
|
@ -1,27 +0,0 @@
|
||||||
{
|
|
||||||
"name": "clipwright",
|
|
||||||
"version": "1.1.0",
|
|
||||||
"description": "Turn long videos (podcasts, webinars, streams) into vertical 9:16 clips with subtitles, re-cut them, and publish them to TikTok, Instagram Reels and YouTube Shorts through a self-hosted Postiz instance.",
|
|
||||||
"author": {
|
|
||||||
"name": "Clipwright",
|
|
||||||
"url": "https://git.pbento.pt/pedro-bento/clipwright"
|
|
||||||
},
|
|
||||||
"homepage": "https://git.pbento.pt/pedro-bento/clipwright/tree/main/skills/clipwright",
|
|
||||||
"repository": "https://git.pbento.pt/pedro-bento/clipwright",
|
|
||||||
"license": "MIT",
|
|
||||||
"keywords": [
|
|
||||||
"video",
|
|
||||||
"clips",
|
|
||||||
"shorts",
|
|
||||||
"reels",
|
|
||||||
"tiktok",
|
|
||||||
"youtube shorts",
|
|
||||||
"subtitles",
|
|
||||||
"social media",
|
|
||||||
"publishing",
|
|
||||||
"automation"
|
|
||||||
],
|
|
||||||
"skills": [
|
|
||||||
"."
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
@ -1,42 +0,0 @@
|
||||||
# Clipwright as an Agent Skill
|
|
||||||
|
|
||||||
`SKILL.md` plus `reference.md` are an
|
|
||||||
[Agent Skill](https://github.com/agentskills/agentskills): an open standard
|
|
||||||
adopted by 26+ agent products, so this one folder installs in Claude Code,
|
|
||||||
OpenClaw, Hermes, Codex, Gemini CLI, Cursor and VS Code without changes.
|
|
||||||
|
|
||||||
It teaches an agent to turn a long video into vertical 9:16 clips through the
|
|
||||||
Clipwright API: which options actually produce good clips, which responses look
|
|
||||||
like errors but are not, and when to stop and ask the user.
|
|
||||||
|
|
||||||
## Setup
|
|
||||||
|
|
||||||
Run Clipwright yourself with Docker and point the agent at the instance
|
|
||||||
(`CLIPWRIGHT_API_URL`, default `http://localhost:8000`). No API key is required
|
|
||||||
on a self-hosted instance, but you do need a Google Gemini key in the server's
|
|
||||||
environment for the AI stages. The skill calls the REST API documented in
|
|
||||||
`reference.md`; publishing goes through your self-hosted
|
|
||||||
[Postiz](https://postiz.com/) instance.
|
|
||||||
|
|
||||||
## Install
|
|
||||||
|
|
||||||
**Claude Code.** Copy the folder into `~/.claude/skills/` for every project, or
|
|
||||||
a project's `.claude/skills/` for one:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cp -r skills/clipwright ~/.claude/skills/
|
|
||||||
```
|
|
||||||
|
|
||||||
**OpenClaw.** Copy it into your OpenClaw `skills/` directory, or install from
|
|
||||||
git with `openclaw add <owner>/<repo>`.
|
|
||||||
|
|
||||||
**Hermes.** Skills live in `~/.hermes/skills/`; installing from the marketplace
|
|
||||||
runs a security scan first.
|
|
||||||
|
|
||||||
**Anything else.** Drop the folder wherever that agent reads skills from.
|
|
||||||
|
|
||||||
## Related
|
|
||||||
|
|
||||||
- `examples/n8n/` has the same pipeline as importable n8n workflows, watched
|
|
||||||
channel in and scheduled clips out through Postiz.
|
|
||||||
- The generated API docs are served at `/docs` (OpenAPI) on any instance.
|
|
||||||
|
|
@ -1,105 +0,0 @@
|
||||||
---
|
|
||||||
name: clipwright
|
|
||||||
version: 1.1.0
|
|
||||||
description: Turn long videos (podcasts, webinars, streams) into vertical 9:16 clips with subtitles, re-cut them, and publish them to TikTok, Instagram Reels and YouTube Shorts through a self-hosted Postiz instance. Use when the user wants to clip a video into shorts, find the best moments of a video, restyle captions on a clip, re-cut a clip, schedule or post clips to social platforms, or automate a clipping pipeline.
|
|
||||||
homepage: https://git.pbento.pt/pedro-bento/clipwright
|
|
||||||
metadata:
|
|
||||||
openclaw:
|
|
||||||
emoji: "🎬"
|
|
||||||
primaryEnv: CLIPWRIGHT_API_URL
|
|
||||||
hermes:
|
|
||||||
category: media
|
|
||||||
tags: [video, clips, shorts, social-media, publishing, automation]
|
|
||||||
---
|
|
||||||
|
|
||||||
# Clipwright: clip and publish video
|
|
||||||
|
|
||||||
Clipwright turns a long video into vertical 9:16 clips (15-60s each) with
|
|
||||||
word-level subtitles burned in, reframed so the speaker stays in shot, then
|
|
||||||
optionally publishes them. One job takes minutes, not seconds: always work async
|
|
||||||
(submit, then webhook or poll).
|
|
||||||
|
|
||||||
## Connect
|
|
||||||
|
|
||||||
One surface: the REST API. Point the skill at your self-hosted instance
|
|
||||||
(`http://localhost:8000` by default):
|
|
||||||
|
|
||||||
- **REST**: exact payloads and error shapes are in `reference.md`; read it
|
|
||||||
before the first HTTP call.
|
|
||||||
|
|
||||||
Self-hosted instances are open by default: no API key is required, but you do
|
|
||||||
need a Gemini key, either in the server's environment or as an `X-Gemini-Key`
|
|
||||||
header. There is no account and no minute quota to enforce; read the instance
|
|
||||||
settings from `GET /api/config` if you need to confirm them.
|
|
||||||
|
|
||||||
## The core loop
|
|
||||||
|
|
||||||
1. Submit: `POST /api/process` with JSON
|
|
||||||
`{"url": "...", "acknowledged": true}`. Returns `{"job_id": ...}`
|
|
||||||
immediately. See the next section for the options worth setting.
|
|
||||||
2. Finish: **webhooks beat polling.** With `webhook_url` set, Clipwright POSTs
|
|
||||||
exactly once when the job ends (completed OR failed, so pipelines never
|
|
||||||
hang): `{"event": "job.completed", "job_id", "status", "clips": [{"index",
|
|
||||||
"title", "video_url"}]}`. If a secret was set, verify
|
|
||||||
`X-Clipwright-Signature: sha256=<hex>` = HMAC-SHA256 of the raw body.
|
|
||||||
Without a webhook, poll `GET /api/status/{job_id}` every 30-60s; response is
|
|
||||||
`{"status", "logs", "result"}` and `result.clips` appears on completion.
|
|
||||||
3. Publish: `POST /api/postiz/post` with `{"job_id", "clip_index",
|
|
||||||
"platforms": ["tiktok", "instagram", "youtube"]}`, optional `title`,
|
|
||||||
`description`, `scheduled_date` (ISO) + `timezone`. The backend uploads the
|
|
||||||
clip to your self-hosted Postiz instance and creates the post there.
|
|
||||||
Restyle captions first if asked:
|
|
||||||
`POST /api/subtitle` with `{"job_id", "clip_index", "style"}` (`classic`
|
|
||||||
or `karaoke` word highlighting).
|
|
||||||
|
|
||||||
## The choices the API cannot make for you
|
|
||||||
|
|
||||||
**How many clips.** Leave `target_clips` unset by default: the AI decides, and
|
|
||||||
most videos yield two to six. It is a target (1-15), not a guarantee. Asking a
|
|
||||||
short video for 15 clips does not produce 15 good ones, it produces the same
|
|
||||||
handful plus filler.
|
|
||||||
|
|
||||||
**Clip length.** `clip_min_seconds` / `clip_max_seconds` default to 15 and 60,
|
|
||||||
which is what the platforms reward. The max must sit at least 5 seconds above
|
|
||||||
the min.
|
|
||||||
|
|
||||||
**Aspect.** `output_format` is `auto` (vertical 9:16, what shorts want),
|
|
||||||
`vertical`, `horizontal` or `square`. It is not a resolution.
|
|
||||||
|
|
||||||
**Layouts.** Leave `layouts` empty unless you know the footage. The useful value
|
|
||||||
is `["auto"]`: one cheap AI call per source picks between no change, a
|
|
||||||
screencast layout and a split layout. The rest are manual overrides.
|
|
||||||
`split` stacks two people who are visible in the *same* frame, and is wrong for
|
|
||||||
shot/reverse-shot footage where it would show one person twice. `screencast` is
|
|
||||||
for scenes whose meaning lives outside the centre (a demo, slides, a
|
|
||||||
spreadsheet) that a plain crop would cut away. `speaker_cut` hard-cuts to
|
|
||||||
whoever is talking. `punch_in` is not a layout, it is a subtle push on the
|
|
||||||
clip's beats and composes with the others.
|
|
||||||
|
|
||||||
**Re-cutting.** `recut_clip` (`POST /api/clip/rerender`) takes an ordered list of
|
|
||||||
segments in seconds **of the original source video**, not of the clip, so you
|
|
||||||
can trim, extend, drop a dead moment in the middle, or reorder. Pass
|
|
||||||
`snap_to_words: true` so the boundaries land on word edges.
|
|
||||||
|
|
||||||
## Two responses that are not failures
|
|
||||||
|
|
||||||
- **`needs_confirmation`** comes back with HTTP 200, not an error: the best
|
|
||||||
available source resolution is below the quality gate. Ask the user, then
|
|
||||||
resubmit the same body with `force_low_quality: true`. Never retry
|
|
||||||
automatically: low resolution in means low resolution out.
|
|
||||||
- **HTTP 429** means the server already has the maximum number of jobs running
|
|
||||||
(`MAX_CONCURRENT_JOBS`). Wait for one to finish instead of resubmitting.
|
|
||||||
|
|
||||||
## Rules
|
|
||||||
|
|
||||||
- Only submit videos the user has rights to; `/api/process` requires the
|
|
||||||
`acknowledged` rights attestation and that is deliberate.
|
|
||||||
- Publishing is public and irreversible: confirm platforms and caption with the
|
|
||||||
user before every `POST /api/postiz/post` call.
|
|
||||||
- Postiz must have the target channels connected; check
|
|
||||||
`GET /api/postiz/integrations` first and surface a clear error if a channel is
|
|
||||||
missing.
|
|
||||||
- Each clip's `video_url` is relative to the instance unless the server sets
|
|
||||||
`PUBLIC_API_URL`; resolve it against the API base before handing it on.
|
|
||||||
- Clipwright is self-hosted, MIT-licensed and needs a machine plus your own
|
|
||||||
Gemini key. Do not describe it as a hosted or metered service.
|
|
||||||
|
|
@ -1,145 +0,0 @@
|
||||||
# Clipwright HTTP reference
|
|
||||||
|
|
||||||
Base URL: `http://localhost:8000` (self-hosted). The API is open by default and
|
|
||||||
needs no key, but it does need a Gemini key, either in the server's environment
|
|
||||||
or as an `X-Gemini-Key` header.
|
|
||||||
|
|
||||||
## Start a job
|
|
||||||
|
|
||||||
`POST /api/process`, JSON body for a URL source (use multipart form fields with
|
|
||||||
a `file` part to upload a local video instead):
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"url": "https://www.youtube.com/watch?v=...",
|
|
||||||
"acknowledged": true,
|
|
||||||
"layouts": ["auto"],
|
|
||||||
"output_format": "auto",
|
|
||||||
"target_clips": 4,
|
|
||||||
"clip_min_seconds": 15,
|
|
||||||
"clip_max_seconds": 60,
|
|
||||||
"webhook_url": "https://example.com/hooks/clipwright",
|
|
||||||
"webhook_secret": "change-me",
|
|
||||||
"force_low_quality": false
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`acknowledged: true` is the rights attestation and is required. `layouts`
|
|
||||||
accepts a JSON list or a comma separated string of `auto`, `split`,
|
|
||||||
`screencast`, `speaker_cut`, `punch_in`. `output_format` is one of `auto`,
|
|
||||||
`vertical`, `horizontal`, `square`. `target_clips` is 1 to 15;
|
|
||||||
`clip_min_seconds` 5 to 175; `clip_max_seconds` 10 to 180 and at least 5 above
|
|
||||||
the minimum.
|
|
||||||
|
|
||||||
Success:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{ "job_id": "0f0a...", "status": "queued" }
|
|
||||||
```
|
|
||||||
|
|
||||||
Quality gate, also HTTP 200:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{ "needs_confirmation": true,
|
|
||||||
"quality_check": { "max_height": 480, "min_height": 720, "cookies_invalid": false } }
|
|
||||||
```
|
|
||||||
|
|
||||||
Ask the user, then resubmit the identical body with `force_low_quality: true`.
|
|
||||||
|
|
||||||
Errors: **429** too many jobs already running (`MAX_CONCURRENT_JOBS`), **400**
|
|
||||||
the source duration could not be determined.
|
|
||||||
|
|
||||||
## Poll a job
|
|
||||||
|
|
||||||
`GET /api/status/{job_id}` returns `{"status": ..., "logs": [...], "result": ...}`
|
|
||||||
where status is `queued`, `processing`, `completed` or `failed`. `result.clips`
|
|
||||||
appears once completed, each entry carrying `title`,
|
|
||||||
`video_title_for_youtube_short`, `video_description_for_tiktok`,
|
|
||||||
`video_description_for_instagram`, `start`, `end` and `video_url`. A relative
|
|
||||||
`video_url` is relative to the API base.
|
|
||||||
|
|
||||||
Poll every 30 to 60 seconds. Prefer a webhook.
|
|
||||||
|
|
||||||
## Webhook
|
|
||||||
|
|
||||||
Fired once per job, on success and on failure, so a flow never hangs:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"event": "job.completed",
|
|
||||||
"job_id": "0f0a...",
|
|
||||||
"status": "completed",
|
|
||||||
"clips": [ { "index": 0, "title": "...", "video_url": "..." } ]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
A failed job sends `"event": "job.failed"` with an `error` string and no clips.
|
|
||||||
Each clip carries `video_url`, relative to the instance unless the server sets
|
|
||||||
`PUBLIC_API_URL`.
|
|
||||||
|
|
||||||
The URL must be public HTTPS; it is validated at submit time and re-resolved at
|
|
||||||
delivery time, so a URL that points at a private address is refused. With a
|
|
||||||
`webhook_secret`, the **raw request body** is signed HMAC-SHA256 and sent as
|
|
||||||
`X-Clipwright-Signature: sha256=<hex>`. Verify against the raw bytes, not
|
|
||||||
against a re-serialized object:
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const crypto = require('crypto');
|
|
||||||
const expected = 'sha256=' + crypto
|
|
||||||
.createHmac('sha256', secret)
|
|
||||||
.update(rawBody)
|
|
||||||
.digest('hex');
|
|
||||||
```
|
|
||||||
|
|
||||||
## Restyle captions
|
|
||||||
|
|
||||||
`POST /api/subtitle`
|
|
||||||
|
|
||||||
```json
|
|
||||||
{ "job_id": "...", "clip_index": 0, "style": "karaoke", "position": "bottom",
|
|
||||||
"font_size": 48, "font_name": "...", "font_color": "#FFFFFF",
|
|
||||||
"highlight_color": "#FFE600", "uppercase": true }
|
|
||||||
```
|
|
||||||
|
|
||||||
`style` is `classic` or `karaoke`; `position` is `top`, `middle` or `bottom`.
|
|
||||||
Only `job_id` and `clip_index` are required.
|
|
||||||
|
|
||||||
## Re-cut a clip
|
|
||||||
|
|
||||||
`POST /api/clip/rerender`
|
|
||||||
|
|
||||||
```json
|
|
||||||
{ "job_id": "...", "clip_index": 0,
|
|
||||||
"segments": [ { "start": 812.4, "end": 831.0 }, { "start": 840.2, "end": 858.9 } ],
|
|
||||||
"snap_to_words": true, "reapply_captions": true, "framing": "auto" }
|
|
||||||
```
|
|
||||||
|
|
||||||
Times are seconds in the **original source video**. Segments concatenate in the
|
|
||||||
order given. `framing` is `auto`, `full` (no side cropping) or `track` (force
|
|
||||||
subject tracking); omit it to keep the clip's current framing. Anything outside
|
|
||||||
the clip's original range, or any non-auto `framing`, re-runs the reframe engine
|
|
||||||
and needs the retained source video.
|
|
||||||
|
|
||||||
## Publish
|
|
||||||
|
|
||||||
`POST /api/postiz/post`
|
|
||||||
|
|
||||||
```json
|
|
||||||
{ "job_id": "...", "clip_index": 0, "platforms": ["tiktok", "instagram", "youtube"],
|
|
||||||
"title": "...", "description": "...",
|
|
||||||
"scheduled_date": "2026-08-25T18:00:00Z", "timezone": "Europe/Madrid" }
|
|
||||||
```
|
|
||||||
|
|
||||||
Omit `scheduled_date` to post now. The backend uploads the clip bytes to your
|
|
||||||
self-hosted Postiz instance and creates the post there; the provider settings
|
|
||||||
(`tiktok`, `instagram`, `youtube`) are built from the title and caption.
|
|
||||||
|
|
||||||
Connected channels: `GET /api/postiz/integrations`.
|
|
||||||
|
|
||||||
Queue: `GET /api/postiz/scheduled`, and
|
|
||||||
`DELETE /api/postiz/scheduled/{id}` to cancel one before it goes out.
|
|
||||||
|
|
||||||
Analytics of what was published: `GET /api/postiz/analytics` (channel totals) and
|
|
||||||
`GET /api/postiz/analytics/posts`.
|
|
||||||
|
|
||||||
Full generated API docs: `http://localhost:8000/docs`.
|
|
||||||
|
|
@ -176,8 +176,7 @@ def test_child_env_drops_server_secrets(monkeypatch):
|
||||||
"TELEGRAM_BOT_TOKEN", "TELEGRAM_CHAT_ID", "GOOGLE_CLIENT_SECRET",
|
"TELEGRAM_BOT_TOKEN", "TELEGRAM_CHAT_ID", "GOOGLE_CLIENT_SECRET",
|
||||||
"AGENTLEDGER_API_KEY", "MANAGED_GEMINI_API_KEY", "POSTIZ_API_KEY",
|
"AGENTLEDGER_API_KEY", "MANAGED_GEMINI_API_KEY", "POSTIZ_API_KEY",
|
||||||
"POSTIZ_URL", "R2_ACCESS_KEY_ID", "R2_SECRET_ACCESS_KEY",
|
"POSTIZ_URL", "R2_ACCESS_KEY_ID", "R2_SECRET_ACCESS_KEY",
|
||||||
"AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "OPENPANEL_CLIENT_SECRET",
|
"OPENPANEL_CLIENT_SECRET",
|
||||||
"ELEVENLABS_API_KEY",
|
|
||||||
)
|
)
|
||||||
keep = ("YOUTUBE_COOKIES", "PROXY_URL", "STATIC_PROXY_URLS", "GEMINI_API_KEY",
|
keep = ("YOUTUBE_COOKIES", "PROXY_URL", "STATIC_PROXY_URLS", "GEMINI_API_KEY",
|
||||||
"BGUTIL_SCRIPT_PATH", "FFMPEG_ENCODER", "WHISPER_MODEL")
|
"BGUTIL_SCRIPT_PATH", "FFMPEG_ENCODER", "WHISPER_MODEL")
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@ are stubbed with monkeypatch.
|
||||||
"""
|
"""
|
||||||
import asyncio
|
import asyncio
|
||||||
import inspect
|
import inspect
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
import pytest
|
import pytest
|
||||||
|
|
@ -94,6 +94,37 @@ class TestPostizSettings:
|
||||||
assert len(_app()._postiz_settings("youtube", "A", "caption", [])["title"]) >= 2
|
assert len(_app()._postiz_settings("youtube", "A", "caption", [])["title"]) >= 2
|
||||||
|
|
||||||
|
|
||||||
|
class TestIdentifierPlatformMap:
|
||||||
|
"""Several Postiz identifiers map to one platform; `settings.__type` must
|
||||||
|
stay the *real* identifier or Postiz routes the post to the wrong place."""
|
||||||
|
|
||||||
|
def test_map_groups_aliases_and_keeps_unknown(self):
|
||||||
|
f = _app()._identifier_platform
|
||||||
|
assert f("instagram") == "instagram"
|
||||||
|
assert f("instagram-standalone") == "instagram"
|
||||||
|
assert f("tiktok") == "tiktok"
|
||||||
|
assert f("tiktok-business") == "tiktok"
|
||||||
|
assert f("youtube") == "youtube"
|
||||||
|
# An unmapped provider keeps its identifier as the platform label.
|
||||||
|
assert f("threads") == "threads"
|
||||||
|
# Case/whitespace are normalised; a missing id is an empty label.
|
||||||
|
assert f(" INSTAGRAM-STANDALONE ") == "instagram"
|
||||||
|
assert f(None) == ""
|
||||||
|
|
||||||
|
def test_instagram_alias_keeps_identifier_as_type(self):
|
||||||
|
s = _app()._postiz_settings("instagram-standalone", "T", "caption", [])
|
||||||
|
assert s["__type"] == "instagram-standalone"
|
||||||
|
assert s["post_type"] == "post"
|
||||||
|
|
||||||
|
def test_tiktok_alias_keeps_identifier_as_type(self):
|
||||||
|
s = _app()._postiz_settings("tiktok-business", "T", "caption", [])
|
||||||
|
assert s["__type"] == "tiktok-business"
|
||||||
|
assert s["content_posting_method"] == "DIRECT_POST"
|
||||||
|
|
||||||
|
def test_youtube_identifier_is_echoed_unchanged(self):
|
||||||
|
assert _app()._postiz_settings("youtube", "T", "caption", [])["__type"] == "youtube"
|
||||||
|
|
||||||
|
|
||||||
class TestIsoDate:
|
class TestIsoDate:
|
||||||
def test_naive_date_gets_the_timezone(self):
|
def test_naive_date_gets_the_timezone(self):
|
||||||
assert _app()._postiz_iso_date("2026-12-31T12:00:00", "UTC") == \
|
assert _app()._postiz_iso_date("2026-12-31T12:00:00", "UTC") == \
|
||||||
|
|
@ -261,3 +292,98 @@ def test_scheduled_window_is_widened_and_posts_are_normalised(publish_env, monke
|
||||||
start = datetime.fromisoformat(captured["start"].replace("Z", "+00:00"))
|
start = datetime.fromisoformat(captured["start"].replace("Z", "+00:00"))
|
||||||
end = datetime.fromisoformat(captured["end"].replace("Z", "+00:00"))
|
end = datetime.fromisoformat(captured["end"].replace("Z", "+00:00"))
|
||||||
assert (end - start) >= timedelta(days=89)
|
assert (end - start) >= timedelta(days=89)
|
||||||
|
|
||||||
|
|
||||||
|
# --- /api/postiz/post channel selection ------------------------------------
|
||||||
|
|
||||||
|
def test_integration_ids_pick_exact_channels_and_report_posted(publish_env, stubbed):
|
||||||
|
stubbed["integrations"] = [
|
||||||
|
{"id": "yt-main", "identifier": "youtube", "name": "Main channel"},
|
||||||
|
{"id": "yt-second", "identifier": "youtube", "name": "Second channel"},
|
||||||
|
{"id": "ig-1", "identifier": "instagram-standalone", "name": "IG"},
|
||||||
|
]
|
||||||
|
r = _post(publish_env, {"job_id": "job1", "clip_index": 0,
|
||||||
|
"integration_ids": ["yt-second", "ig-1"],
|
||||||
|
"title": "My Title"})
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
body = r.json()
|
||||||
|
assert body["success"] is True
|
||||||
|
assert body["posted"] == [
|
||||||
|
{"integration_id": "yt-second", "identifier": "youtube",
|
||||||
|
"platform": "youtube", "name": "Second channel"},
|
||||||
|
{"integration_id": "ig-1", "identifier": "instagram-standalone",
|
||||||
|
"platform": "instagram", "name": "IG"},
|
||||||
|
]
|
||||||
|
posts = stubbed["payload"]["posts"]
|
||||||
|
assert [p["integration"]["id"] for p in posts] == ["yt-second", "ig-1"]
|
||||||
|
assert [p["settings"]["__type"] for p in posts] == \
|
||||||
|
["youtube", "instagram-standalone"]
|
||||||
|
assert posts[1]["settings"]["post_type"] == "post"
|
||||||
|
assert stubbed["payload"]["type"] == "now"
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_integration_id_is_a_400(publish_env, stubbed):
|
||||||
|
stubbed["integrations"] = [{"id": "i-tt", "identifier": "tiktok"}]
|
||||||
|
r = _post(publish_env, {"job_id": "job1", "clip_index": 0,
|
||||||
|
"integration_ids": ["nope"]})
|
||||||
|
assert r.status_code == 400
|
||||||
|
assert "nope" in r.json()["detail"]
|
||||||
|
assert "upload" not in stubbed["order"] and "create" not in stubbed["order"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_disabled_integration_id_is_a_400(publish_env, stubbed):
|
||||||
|
stubbed["integrations"] = [
|
||||||
|
{"id": "i-ig", "identifier": "instagram-standalone", "name": "IG",
|
||||||
|
"disabled": True},
|
||||||
|
]
|
||||||
|
r = _post(publish_env, {"job_id": "job1", "clip_index": 0,
|
||||||
|
"integration_ids": ["i-ig"]})
|
||||||
|
assert r.status_code == 400
|
||||||
|
assert "Disabled" in r.json()["detail"]
|
||||||
|
assert "upload" not in stubbed["order"] and "create" not in stubbed["order"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_legacy_platforms_fallback_matches_mapped_identifiers(publish_env, stubbed):
|
||||||
|
stubbed["integrations"] = [
|
||||||
|
{"id": "yt-a", "identifier": "youtube", "name": "A"},
|
||||||
|
{"id": "yt-b", "identifier": "youtube", "name": "B"},
|
||||||
|
{"id": "ig-1", "identifier": "instagram-standalone", "name": "IG"},
|
||||||
|
{"id": "tt-1", "identifier": "tiktok-business", "name": "TT"},
|
||||||
|
]
|
||||||
|
r = _post(publish_env, {"job_id": "job1", "clip_index": 0,
|
||||||
|
"platforms": ["instagram", "tiktok", "youtube"]})
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
posts = stubbed["payload"]["posts"]
|
||||||
|
# First enabled match per platform; duplicate YouTube channels do not collapse.
|
||||||
|
assert [p["integration"]["id"] for p in posts] == ["ig-1", "tt-1", "yt-a"]
|
||||||
|
assert [p["settings"]["__type"] for p in posts] == \
|
||||||
|
["instagram-standalone", "tiktok-business", "youtube"]
|
||||||
|
assert [e["platform"] for e in r.json()["posted"]] == \
|
||||||
|
["instagram", "tiktok", "youtube"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_channels_requested_is_a_400(publish_env, stubbed):
|
||||||
|
stubbed["integrations"] = [{"id": "i-tt", "identifier": "tiktok"}]
|
||||||
|
r = _post(publish_env, {"job_id": "job1", "clip_index": 0})
|
||||||
|
assert r.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_scheduled_date_in_the_past_is_a_400(publish_env, stubbed):
|
||||||
|
stubbed["integrations"] = [{"id": "i-tt", "identifier": "tiktok"}]
|
||||||
|
past = (datetime.now(timezone.utc) - timedelta(hours=1)).isoformat()
|
||||||
|
r = _post(publish_env, {"job_id": "job1", "clip_index": 0,
|
||||||
|
"integration_ids": ["i-tt"],
|
||||||
|
"scheduled_date": past})
|
||||||
|
assert r.status_code == 400
|
||||||
|
assert "past" in r.json()["detail"].lower()
|
||||||
|
assert "upload" not in stubbed["order"] and "create" not in stubbed["order"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_future_scheduled_date_sets_schedule_type(publish_env, stubbed):
|
||||||
|
stubbed["integrations"] = [{"id": "i-tt", "identifier": "tiktok"}]
|
||||||
|
future = (datetime.now(timezone.utc) + timedelta(days=2)).isoformat()
|
||||||
|
r = _post(publish_env, {"job_id": "job1", "clip_index": 0,
|
||||||
|
"integration_ids": ["i-tt"],
|
||||||
|
"scheduled_date": future})
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
assert stubbed["payload"]["type"] == "schedule"
|
||||||
|
|
|
||||||
|
|
@ -1,43 +0,0 @@
|
||||||
"""Tests for the ElevenLabs retry helper."""
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
import translate
|
|
||||||
from translate import _with_retry, _TransientHTTPError
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(autouse=True)
|
|
||||||
def no_sleep(monkeypatch):
|
|
||||||
monkeypatch.setattr(translate.time, "sleep", lambda seconds: None)
|
|
||||||
|
|
||||||
|
|
||||||
def test_succeeds_after_transient_failures():
|
|
||||||
calls = {"n": 0}
|
|
||||||
|
|
||||||
def flaky():
|
|
||||||
calls["n"] += 1
|
|
||||||
if calls["n"] < 3:
|
|
||||||
raise _TransientHTTPError("HTTP 502")
|
|
||||||
return "ok"
|
|
||||||
|
|
||||||
assert _with_retry(flaky, "test op") == "ok"
|
|
||||||
assert calls["n"] == 3
|
|
||||||
|
|
||||||
|
|
||||||
def test_gives_up_after_max_attempts():
|
|
||||||
def always_fails():
|
|
||||||
raise _TransientHTTPError("HTTP 503")
|
|
||||||
|
|
||||||
with pytest.raises(Exception, match="failed after 3 attempts"):
|
|
||||||
_with_retry(always_fails, "test op")
|
|
||||||
|
|
||||||
|
|
||||||
def test_non_transient_fails_fast():
|
|
||||||
calls = {"n": 0}
|
|
||||||
|
|
||||||
def bad_request():
|
|
||||||
calls["n"] += 1
|
|
||||||
raise ValueError("HTTP 400 - bad request")
|
|
||||||
|
|
||||||
with pytest.raises(ValueError):
|
|
||||||
_with_retry(bad_request, "test op")
|
|
||||||
assert calls["n"] == 1
|
|
||||||
285
translate.py
285
translate.py
|
|
@ -1,285 +0,0 @@
|
||||||
"""
|
|
||||||
ElevenLabs Video Translation/Dubbing Module
|
|
||||||
|
|
||||||
Uses ElevenLabs Dubbing API to translate video audio to different languages.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import os
|
|
||||||
import time
|
|
||||||
import httpx
|
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
ELEVENLABS_API_BASE = "https://api.elevenlabs.io/v1"
|
|
||||||
|
|
||||||
# Supported target languages for dubbing
|
|
||||||
SUPPORTED_LANGUAGES = {
|
|
||||||
"en": "English",
|
|
||||||
"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",
|
|
||||||
}
|
|
||||||
|
|
||||||
# HTTP status codes worth retrying (server-side / rate-limit hiccups).
|
|
||||||
_TRANSIENT_STATUS = {429, 500, 502, 503, 504}
|
|
||||||
|
|
||||||
|
|
||||||
class _TransientHTTPError(Exception):
|
|
||||||
"""Raised for retryable HTTP responses (5xx / 429)."""
|
|
||||||
|
|
||||||
|
|
||||||
def _with_retry(operation, description, max_attempts=3, base_delay=2.0):
|
|
||||||
"""
|
|
||||||
Run `operation` (a zero-arg callable) with exponential backoff on transient
|
|
||||||
failures: HTTP 5xx/429, timeouts, and connection errors. Backoff is ~2s/4s/8s.
|
|
||||||
Non-transient errors (e.g. 4xx) propagate immediately and fail fast.
|
|
||||||
"""
|
|
||||||
for attempt in range(1, max_attempts + 1):
|
|
||||||
try:
|
|
||||||
return operation()
|
|
||||||
except (_TransientHTTPError, httpx.TransportError) as e:
|
|
||||||
if attempt >= max_attempts:
|
|
||||||
raise Exception(f"{description} failed after {max_attempts} attempts: {e}")
|
|
||||||
delay = base_delay * (2 ** (attempt - 1))
|
|
||||||
print(
|
|
||||||
f"[ElevenLabs] {description} transient error "
|
|
||||||
f"(attempt {attempt}/{max_attempts}): {e}. Retrying in {int(delay)}s..."
|
|
||||||
)
|
|
||||||
time.sleep(delay)
|
|
||||||
|
|
||||||
|
|
||||||
def create_dubbing_project(
|
|
||||||
video_path: str,
|
|
||||||
target_language: str,
|
|
||||||
api_key: str,
|
|
||||||
source_language: Optional[str] = None,
|
|
||||||
) -> dict:
|
|
||||||
"""
|
|
||||||
Create a new dubbing project with ElevenLabs.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
video_path: Path to the video file
|
|
||||||
target_language: Target language code (e.g., 'es', 'fr', 'de')
|
|
||||||
api_key: ElevenLabs API key
|
|
||||||
source_language: Source language code (auto-detected if None)
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
dict with dubbing_id and expected_duration_sec
|
|
||||||
"""
|
|
||||||
url = f"{ELEVENLABS_API_BASE}/dubbing"
|
|
||||||
|
|
||||||
headers = {
|
|
||||||
"xi-api-key": api_key,
|
|
||||||
}
|
|
||||||
|
|
||||||
# Prepare form data
|
|
||||||
data = {
|
|
||||||
"target_lang": target_language,
|
|
||||||
"mode": "automatic",
|
|
||||||
"num_speakers": "0",
|
|
||||||
"watermark": "false",
|
|
||||||
}
|
|
||||||
|
|
||||||
if source_language:
|
|
||||||
data["source_lang"] = source_language
|
|
||||||
|
|
||||||
def _submit():
|
|
||||||
# Re-open the file per attempt so a retry uploads from the start.
|
|
||||||
with open(video_path, "rb") as video_file:
|
|
||||||
files = {
|
|
||||||
"file": (os.path.basename(video_path), video_file, "video/mp4")
|
|
||||||
}
|
|
||||||
with httpx.Client(timeout=300.0) as client:
|
|
||||||
resp = client.post(url, headers=headers, data=data, files=files)
|
|
||||||
if resp.status_code in _TRANSIENT_STATUS:
|
|
||||||
raise _TransientHTTPError(f"HTTP {resp.status_code}")
|
|
||||||
return resp
|
|
||||||
|
|
||||||
print(f"[ElevenLabs] Creating dubbing project for {target_language}...")
|
|
||||||
response = _with_retry(_submit, "create dubbing project")
|
|
||||||
|
|
||||||
if response.status_code not in [200, 201]:
|
|
||||||
error_msg = response.text
|
|
||||||
try:
|
|
||||||
error_data = response.json()
|
|
||||||
error_msg = error_data.get("detail", {}).get("message", response.text)
|
|
||||||
except (ValueError, AttributeError, KeyError, TypeError):
|
|
||||||
pass
|
|
||||||
raise Exception(f"ElevenLabs API error ({response.status_code}): {error_msg}")
|
|
||||||
|
|
||||||
result = response.json()
|
|
||||||
print(f"[ElevenLabs] Dubbing project created: {result.get('dubbing_id')}")
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
def get_dubbing_status(dubbing_id: str, api_key: str) -> dict:
|
|
||||||
"""
|
|
||||||
Check the status of a dubbing project.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
dict with status ('dubbing', 'dubbed', 'failed') and other metadata
|
|
||||||
"""
|
|
||||||
url = f"{ELEVENLABS_API_BASE}/dubbing/{dubbing_id}"
|
|
||||||
|
|
||||||
headers = {
|
|
||||||
"xi-api-key": api_key,
|
|
||||||
}
|
|
||||||
|
|
||||||
def _poll():
|
|
||||||
with httpx.Client(timeout=30.0) as client:
|
|
||||||
resp = client.get(url, headers=headers)
|
|
||||||
if resp.status_code in _TRANSIENT_STATUS:
|
|
||||||
raise _TransientHTTPError(f"HTTP {resp.status_code}: {resp.text[:200]}")
|
|
||||||
return resp
|
|
||||||
|
|
||||||
response = _with_retry(_poll, "dubbing status check")
|
|
||||||
|
|
||||||
if response.status_code != 200:
|
|
||||||
raise Exception(f"Failed to get dubbing status: {response.text}")
|
|
||||||
|
|
||||||
return response.json()
|
|
||||||
|
|
||||||
|
|
||||||
def download_dubbed_video(
|
|
||||||
dubbing_id: str,
|
|
||||||
target_language: str,
|
|
||||||
output_path: str,
|
|
||||||
api_key: str
|
|
||||||
) -> str:
|
|
||||||
"""
|
|
||||||
Download the dubbed video file.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
dubbing_id: The dubbing project ID
|
|
||||||
target_language: Target language code
|
|
||||||
output_path: Where to save the dubbed video
|
|
||||||
api_key: ElevenLabs API key
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Path to the downloaded file
|
|
||||||
"""
|
|
||||||
url = f"{ELEVENLABS_API_BASE}/dubbing/{dubbing_id}/audio/{target_language}"
|
|
||||||
|
|
||||||
headers = {
|
|
||||||
"xi-api-key": api_key,
|
|
||||||
}
|
|
||||||
|
|
||||||
def _download():
|
|
||||||
with httpx.Client(timeout=120.0) as client:
|
|
||||||
with client.stream("GET", url, headers=headers) as response:
|
|
||||||
if response.status_code in _TRANSIENT_STATUS:
|
|
||||||
raise _TransientHTTPError(f"HTTP {response.status_code}")
|
|
||||||
if response.status_code != 200:
|
|
||||||
# Body must be read before .text is available on a stream.
|
|
||||||
response.read()
|
|
||||||
raise Exception(f"Failed to download dubbed video: {response.text}")
|
|
||||||
|
|
||||||
with open(output_path, "wb") as f:
|
|
||||||
for chunk in response.iter_bytes(chunk_size=8192):
|
|
||||||
f.write(chunk)
|
|
||||||
return output_path
|
|
||||||
|
|
||||||
print(f"[ElevenLabs] Downloading dubbed video...")
|
|
||||||
_with_retry(_download, "dubbed video download")
|
|
||||||
|
|
||||||
print(f"[ElevenLabs] Dubbed video saved to: {output_path}")
|
|
||||||
return output_path
|
|
||||||
|
|
||||||
|
|
||||||
def translate_video(
|
|
||||||
video_path: str,
|
|
||||||
output_path: str,
|
|
||||||
target_language: str,
|
|
||||||
api_key: str,
|
|
||||||
source_language: Optional[str] = None,
|
|
||||||
max_wait_seconds: int = 600,
|
|
||||||
poll_interval: int = 5,
|
|
||||||
) -> str:
|
|
||||||
"""
|
|
||||||
Translate a video to a target language using ElevenLabs dubbing.
|
|
||||||
|
|
||||||
This is a blocking call that waits for the dubbing to complete.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
video_path: Path to input video
|
|
||||||
output_path: Path to save translated video
|
|
||||||
target_language: Target language code
|
|
||||||
api_key: ElevenLabs API key
|
|
||||||
source_language: Source language code (auto-detected if None)
|
|
||||||
max_wait_seconds: Maximum time to wait for dubbing (default 10 min)
|
|
||||||
poll_interval: Seconds between status checks
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Path to the translated video
|
|
||||||
"""
|
|
||||||
# Create dubbing project
|
|
||||||
project = create_dubbing_project(
|
|
||||||
video_path=video_path,
|
|
||||||
target_language=target_language,
|
|
||||||
api_key=api_key,
|
|
||||||
source_language=source_language,
|
|
||||||
)
|
|
||||||
|
|
||||||
dubbing_id = project["dubbing_id"]
|
|
||||||
expected_duration = project.get("expected_duration_sec", 60)
|
|
||||||
|
|
||||||
print(f"[ElevenLabs] Dubbing ID: {dubbing_id}, Expected duration: {expected_duration}s")
|
|
||||||
|
|
||||||
# Poll for completion
|
|
||||||
start_time = time.time()
|
|
||||||
while True:
|
|
||||||
elapsed = time.time() - start_time
|
|
||||||
if elapsed > max_wait_seconds:
|
|
||||||
raise Exception(f"Dubbing timed out after {max_wait_seconds} seconds")
|
|
||||||
|
|
||||||
status = get_dubbing_status(dubbing_id, api_key)
|
|
||||||
current_status = status.get("status", "unknown")
|
|
||||||
|
|
||||||
print(f"[ElevenLabs] Status: {current_status} (elapsed: {int(elapsed)}s)")
|
|
||||||
|
|
||||||
if current_status == "dubbed":
|
|
||||||
# Download the result
|
|
||||||
return download_dubbed_video(
|
|
||||||
dubbing_id=dubbing_id,
|
|
||||||
target_language=target_language,
|
|
||||||
output_path=output_path,
|
|
||||||
api_key=api_key,
|
|
||||||
)
|
|
||||||
|
|
||||||
elif current_status == "failed":
|
|
||||||
error = status.get("error", "Unknown error")
|
|
||||||
raise Exception(f"Dubbing failed: {error}")
|
|
||||||
|
|
||||||
# Still processing, wait and poll again
|
|
||||||
time.sleep(poll_interval)
|
|
||||||
|
|
||||||
|
|
||||||
def get_supported_languages() -> dict:
|
|
||||||
"""Return dict of supported language codes and names."""
|
|
||||||
return SUPPORTED_LANGUAGES.copy()
|
|
||||||
Loading…
Reference in a new issue