diff --git a/.env.example b/.env.example index 1bafa52..cbdda93 100644 --- a/.env.example +++ b/.env.example @@ -72,7 +72,7 @@ GEMINI_IMAGE_MODEL=gemini-3.1-flash-image # close-ups of a real person; the clock runs from the last download. # THUMBNAIL_RETENTION_SECONDS=86400 -# Per-IP rate limiting (rate_limit.py). "/". +# Per-IP rate limiting. "/". # Defaults: auth 30/600, process 60/3600. Set RATE_LIMIT_ENABLED=0 # to turn the whole thing off (self-host behind your own firewall). # RATE_LIMIT_ENABLED=1 @@ -110,11 +110,6 @@ GEMINI_IMAGE_MODEL=gemini-3.1-flash-image # disables it. Do not add "preload" without understanding that it is one-way. # HSTS_HEADER=max-age=31536000; includeSubDomains -# Encrypted PostgreSQL backups (ops/pg_backup.sh — installed and scheduled on -# the database host, not by the app). +# Optional PostgreSQL database (only needed if you run the app against one). # DATABASE_URL=postgres://user:pass@host:5432/clipwright -# BACKUP_AGE_RECIPIENT=age1... -# BACKUP_DEST=s3://clipwright-backups/pg -# BACKUP_S3_ENDPOINT=https://.r2.cloudflarestorage.com -# RETENTION_DAYS=30 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2c6db46..8660be5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,17 +16,12 @@ jobs: container: nikolaik/python-nodejs:python3.11-nodejs20 steps: - uses: actions/checkout@v4 - # Everything the collected tests import at module level, WITHOUT the - # heavy ML stack (torch/ultralytics/mediapipe/faster-whisper) — the - # pipeline modules import those lazily behind their feature gates, and - # the tests exercise the gated-off paths. numpy+opencv cover the layout - # modules, fastapi/python-multipart cover importing app.py for the MCP - # endpoint tests, google-genai covers gemini_worker. + # Shared thin test environment (see requirements-test.txt): everything the + # collected tests import at module level, WITHOUT the heavy ML stack + # (torch/ultralytics/mediapipe/faster-whisper), which the pipeline modules + # import lazily behind their feature gates. - name: Install test dependencies - run: > - pip install pytest pillow httpx pydantic numpy - opencv-python-headless python-dotenv google-genai fastapi - python-multipart + run: pip install -r requirements-test.txt - name: Run tests run: pytest tests/ -v diff --git a/.gitignore b/.gitignore index 0ec1dd6..6af5a38 100644 --- a/.gitignore +++ b/.gitignore @@ -33,14 +33,16 @@ output/ # Cache dirs .cache/ .config/ +.pytest_cache/ + # Multi-agent Skills .agents/ .agent/ .claude/ -# skills/ holds third-party installs (symlinks); our own published skill is versioned -skills/* -!skills/clipwright/ -skills-lock.json + +# Design-tool / agent-local state +.hallmark/ +.opencode/ # Cloud env example kept local only (avoid leaking infra hints) diff --git a/.hallmark/log.json b/.hallmark/log.json deleted file mode 100644 index 3e9effa..0000000 --- a/.hallmark/log.json +++ /dev/null @@ -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" } -] diff --git a/.opencode/.gitignore b/.opencode/.gitignore deleted file mode 100644 index 47241b6..0000000 --- a/.opencode/.gitignore +++ /dev/null @@ -1 +0,0 @@ -images/ diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index 43873b8..0000000 --- a/CLAUDE.md +++ /dev/null @@ -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. **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 | -| `subtitles.py` | SRT generation and FFmpeg subtitle burning | -| `dashboard/src/App.jsx` | Main React component with state management | -| `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 `
`. 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 `.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 `.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 | -| POST | `/api/hook` | Add text hook overlays | -| POST | `/api/postiz/post` | Publish one clip to specific Postiz channels (by integration id), scheduled or 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`. Auth is the raw key, no `Bearer`. - -`POST /api/postiz/post` selects channels by **integration id** -(`integration_ids`, preferred), so several channels of the same network stay -distinct (Postiz lists Instagram as `instagram-standalone`, YouTube once per -channel). The legacy `platforms` list remains a fallback that picks the first -enabled match. Per-post provider settings are keyed by the integration's real -identifier and built server-side from the clip title and caption. The -dashboard's publish modal takes the date as **DD/MM/YYYY** and sends the -resolved instant as ISO. - -### 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=` 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 -`/` 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). diff --git a/Dockerfile b/Dockerfile index 28713dd..a16c400 100644 --- a/Dockerfile +++ b/Dockerfile @@ -31,6 +31,11 @@ FROM python:3.11-slim WORKDIR /app +# The FastAPI app lives in the `clipwright` package and job workers are launched +# as `python -m clipwright.pipeline.main`, so the repo root must be importable +# regardless of the process cwd. +ENV PYTHONPATH=/app + # Install FFmpeg, OpenCV deps, Node.js + npm + git (for yt-dlp JS + bgutil build). # fontconfig + fonts-liberation back the subtitle font choices: without real # fonts libass falls back to DejaVu for every UI option (issue #57). @@ -126,4 +131,4 @@ EXPOSE 8000 HEALTHCHECK --interval=5s --timeout=3s --start-period=30s --retries=2 \ CMD curl -sf http://127.0.0.1:8000/health/ready > /dev/null || exit 1 -CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers", "--forwarded-allow-ips", "*", "--timeout-graceful-shutdown", "15"] +CMD ["uvicorn", "clipwright.api.app:app", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers", "--forwarded-allow-ips", "*", "--timeout-graceful-shutdown", "15"] diff --git a/README.md b/README.md index ebddd84..c3067ff 100644 --- a/README.md +++ b/README.md @@ -97,7 +97,28 @@ curl -X POST http://localhost:8000/api/process \ "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`. + +## Project structure + +``` +clipwright/ # Python backend package + core/ # shared helpers (security, filesystem paths) + api/ # FastAPI app, auth, free tools + pipeline/ # download → transcribe → clip orchestration, Gemini, quality probe + layouts/ # reframing: active speaker, split/screencast/panel, punch-in + media/ # FFmpeg helpers, subtitles, hooks, thumbnails, recut + integrations/ # Postiz, YouTube, file hosts + tools/ # local verification scripts (python -m clipwright.tools.verify_hooks) +dashboard/ # React + Vite dashboard (its own build) +remotion/ # Remotion compositions used by the renderer +render-service/ # Node render microservice (its own Dockerfile) +cli/ # published `clipwright` HTTP client (own pyproject) +tests/ # pytest suite (pythonpath = ["."]) +fonts/ assets/ # shared runtime resources (kept at repo root) +``` + +The backend runs from the source tree (no install step): `uvicorn clipwright.api.app:app` serves the API and clip jobs run as `python -m clipwright.pipeline.main`. ## Tech stack diff --git a/assets/make_watermark.py b/assets/make_watermark.py deleted file mode 100644 index 8189209..0000000 --- a/assets/make_watermark.py +++ /dev/null @@ -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) diff --git a/churchil_queen_vertical.gif b/churchil_queen_vertical.gif deleted file mode 100644 index 3ca18ce..0000000 Binary files a/churchil_queen_vertical.gif and /dev/null differ diff --git a/churchil_queen_vertical_short.gif b/churchil_queen_vertical_short.gif deleted file mode 100644 index a686198..0000000 Binary files a/churchil_queen_vertical_short.gif and /dev/null differ diff --git a/cli/README.md b/cli/README.md index d38d948..bb2b591 100644 --- a/cli/README.md +++ b/cli/README.md @@ -53,6 +53,3 @@ Clipwright POSTs once (HMAC-signed, `X-Clipwright-Signature: sha256=`) when the job ends, with each clip's title and `video_url`. Set `PUBLIC_API_URL` on the server so those links are absolute; otherwise they are relative to your instance. - -The agent-native version of the same surface is the Clipwright skill in -[`skills/clipwright/`](../skills/clipwright/). diff --git a/clipwright/__init__.py b/clipwright/__init__.py new file mode 100644 index 0000000..73ee758 --- /dev/null +++ b/clipwright/__init__.py @@ -0,0 +1 @@ +"""Clipwright backend.""" diff --git a/clipwright/api/__init__.py b/clipwright/api/__init__.py new file mode 100644 index 0000000..73ee758 --- /dev/null +++ b/clipwright/api/__init__.py @@ -0,0 +1 @@ +"""Clipwright backend.""" diff --git a/app.py b/clipwright/api/app.py similarity index 99% rename from app.py rename to clipwright/api/app.py index 0694359..a703544 100644 --- a/app.py +++ b/clipwright/api/app.py @@ -1,5 +1,5 @@ import os -import llm_backend +from clipwright.pipeline import llm_backend import re import sys import uuid @@ -26,11 +26,12 @@ from fastapi.responses import FileResponse, JSONResponse from starlette.background import BackgroundTask from pydantic import BaseModel import httpx -import recut -import layout_ranges -import watermarked -import media_auth -import postiz +from clipwright.media import recut +from clipwright.layouts import layout_ranges +from clipwright.media import watermarked +from clipwright.api import media_auth +from clipwright.integrations import postiz +from clipwright.core.paths import REPO_ROOT load_dotenv() @@ -61,7 +62,6 @@ QUALITY_GATE_MIN_HEIGHT = int(os.environ.get("QUALITY_GATE_MIN_HEIGHT", "720")) # managed minutes and dies with "no usable clips" (prod 20-ago: 3 of 5 recent # failures were exactly this, one user retrying the same 24s video). MIN_SOURCE_SECONDS = int(os.environ.get("MIN_SOURCE_SECONDS", "45")) -QUALITY_PROBE_SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "quality_probe.py") # Server credentials the pipeline subprocesses (main.py, quality_probe.py) never # read: main.py and everything it imports use GEMINI_API_KEY / LLM_* / the @@ -88,6 +88,11 @@ def child_env(base=None): env = dict(os.environ if base is None else base) for name in CHILD_ENV_DENYLIST: env.pop(name, None) + # The pipeline modules run as ``-m clipwright.pipeline.``; make the + # package importable regardless of the child's cwd. + env["PYTHONPATH"] = os.pathsep.join( + filter(None, [env.get("PYTHONPATH"), str(REPO_ROOT)]) + ) return env @@ -466,7 +471,7 @@ def _reapply_captions(job_id, clip_index, video_path): if not transcript or clip_index >= len(clips): return None clip = clips[clip_index] - import main as _main + from clipwright.pipeline import main as _main # A recut clip is a concatenation of source segments, so the flat # start..end window is wrong for it — caption against the clip-relative # remapped transcript instead (same trick /api/subtitle uses). @@ -1409,7 +1414,7 @@ async def _deliver_webhook(url, body: bytes, secret): headers = {"Content-Type": "application/json", "User-Agent": "Clipwright-Webhook/1.0"} if secret: headers["X-Clipwright-Signature"] = _sign_webhook(body, secret) - from security_utils import assert_public_url, UnsafeURLError + from clipwright.core.security_utils import assert_public_url, UnsafeURLError loop = asyncio.get_event_loop() for attempt, delay in enumerate(WEBHOOK_RETRY_DELAYS, 1): if delay: @@ -1477,7 +1482,7 @@ app = FastAPI(lifespan=lifespan) # Free public tools behind the /tools SEO pages: YouTube transcript (existing # captions only, never the GPU) and the title/description/tag generator. -import free_tools as _free_tools +from clipwright.api import free_tools as _free_tools app.include_router(_free_tools.router) # Enable CORS for frontend. Self-host allows any origin (permissive wildcard). @@ -1495,7 +1500,7 @@ app.add_middleware( # Mount static files for serving videos. ``guard`` refuses non-deliverables # (``*_metadata.json``, ``.owner``, ``.resume.json``) so they are never served. -from restoring_static import RestoringStaticFiles +from clipwright.api.restoring_static import RestoringStaticFiles app.mount("/videos", RestoringStaticFiles( directory=OUTPUT_DIR, guard=_media_guard), name="videos") @@ -1761,7 +1766,7 @@ async def _probe_youtube_quality(url: str) -> dict: def _run(): try: proc = subprocess.run( - [sys.executable, QUALITY_PROBE_SCRIPT, "--url", url], + [sys.executable, "-m", "clipwright.pipeline.quality_probe", "--url", url], capture_output=True, timeout=75, env=child_env(), ) return json.loads(proc.stdout.decode(errors="replace").strip() or "{}") @@ -1779,8 +1784,8 @@ async def _validate_source_url(url: str): search / playlist / channel page (yt_clients). The download and the metering probe check the same things again; this is the one in front of the quality probe, which used to have none.""" - from security_utils import assert_public_url, UnsafeURLError - from yt_clients import youtube_non_video_reason + from clipwright.core.security_utils import assert_public_url, UnsafeURLError + from clipwright.integrations.yt_clients import youtube_non_video_reason try: await asyncio.get_event_loop().run_in_executor(None, assert_public_url, url) except UnsafeURLError as e: @@ -2103,7 +2108,7 @@ async def process_endpoint( # Completion callback: reject unsafe targets NOW (clear 400) — delivery # re-validates anyway, but failing at submit is the debuggable behavior. if webhook_url: - from security_utils import assert_public_url, UnsafeURLError + from clipwright.core.security_utils import assert_public_url, UnsafeURLError try: await asyncio.get_event_loop().run_in_executor( None, assert_public_url, webhook_url) @@ -2146,7 +2151,7 @@ async def process_endpoint( # outside Docker is whatever interpreter happens to be first — not the venv # running this server. Every job then dies on `import cv2`. The quality # probe above already gets this right. - cmd = [sys.executable, "-u", "main.py"] # -u for unbuffered + cmd = [sys.executable, "-u", "-m", "clipwright.pipeline.main"] # -u for unbuffered env = child_env() if api_key: env["GEMINI_API_KEY"] = api_key # Override with key from request @@ -2170,7 +2175,7 @@ async def process_endpoint( # byte-for-byte; the dashboard sends an explicit value either way. if str(auto_hook).lower() in ("1", "true", "yes"): env["AUTO_HOOK"] = "1" - from hooks import HOOK_STYLES + from clipwright.media.hooks import HOOK_STYLES if auto_hook_style in HOOK_STYLES: env["AUTO_HOOK_STYLE"] = auto_hook_style print(f"[auto-hook] job={job_id} style={env.get('AUTO_HOOK_STYLE', 'classic')}") @@ -2540,10 +2545,10 @@ async def download_all_clips(job_id: str, request: Request): # Files live on local disk in this self-host fork, so there is nothing to restore. -from editor import VideoEditor -from subtitles import generate_srt, generate_ass, burn_subtitles, CAPTION_PRESETS -from hooks import add_hook_to_video -from thumbnail import (analyze_video_for_titles, refine_titles, generate_thumbnail, +from clipwright.media.editor import VideoEditor +from clipwright.media.subtitles import generate_srt, generate_ass, burn_subtitles, CAPTION_PRESETS +from clipwright.media.hooks import add_hook_to_video +from clipwright.media.thumbnail import (analyze_video_for_titles, refine_titles, generate_thumbnail, generate_youtube_description, extract_face_frames) class EditRequest(BaseModel): @@ -3195,7 +3200,7 @@ async def get_clip_scenes(job_id: str, clip_index: int, request: Request): def build(): import cv2 - import main as m + from clipwright.pipeline import main as m # Stable for the files the browser fetches (no accumulation), unique # for the temp cut (no collision between overlapping requests). @@ -4413,19 +4418,19 @@ async def thumbnail_upload( vpath = video_path # Download YouTube video if URL was provided if not vpath and url: - from main import download_youtube_video + from clipwright.pipeline.main import download_youtube_video loop = asyncio.get_event_loop() vpath, _ = await loop.run_in_executor(None, download_youtube_video, url, UPLOAD_DIR) thumbnail_sessions[session_id]["video_path"] = vpath - from main import transcribe_video + from clipwright.pipeline.main import transcribe_video loop = asyncio.get_event_loop() try: transcript = await loop.run_in_executor(None, transcribe_video, vpath) finally: # See transcribe_backends.release_models: the API process is # long-lived and the GPU is shared with every running job. - import transcribe_backends + from clipwright.pipeline import transcribe_backends await loop.run_in_executor(None, transcribe_backends.release_models) segments = transcript.get("segments", []) duration = segments[-1]["end"] if segments else 0 @@ -4492,7 +4497,7 @@ async def thumbnail_analyze( session_id = str(uuid.uuid4()) if url: - from main import download_youtube_video + from clipwright.pipeline.main import download_youtube_video video_path, _ = await asyncio.get_event_loop().run_in_executor( None, download_youtube_video, url, UPLOAD_DIR) else: diff --git a/free_tools.py b/clipwright/api/free_tools.py similarity index 100% rename from free_tools.py rename to clipwright/api/free_tools.py diff --git a/media_auth.py b/clipwright/api/media_auth.py similarity index 100% rename from media_auth.py rename to clipwright/api/media_auth.py diff --git a/restoring_static.py b/clipwright/api/restoring_static.py similarity index 100% rename from restoring_static.py rename to clipwright/api/restoring_static.py diff --git a/clipwright/core/__init__.py b/clipwright/core/__init__.py new file mode 100644 index 0000000..73ee758 --- /dev/null +++ b/clipwright/core/__init__.py @@ -0,0 +1 @@ +"""Clipwright backend.""" diff --git a/clipwright/core/paths.py b/clipwright/core/paths.py new file mode 100644 index 0000000..7c1ef27 --- /dev/null +++ b/clipwright/core/paths.py @@ -0,0 +1,31 @@ +"""Canonical filesystem locations for the Clipwright backend. + +The importable package lives at ``/clipwright`` while the shared runtime +resources (``fonts/``, ``assets/``, ``yolov8n.pt``) stay at the repository root. +Keeping the constants here means every module resolves them the same way, +independently of the current working directory or of how deep a module sits in +the package. +""" + +from __future__ import annotations + +from pathlib import Path + +# .../clipwright +PACKAGE_DIR = Path(__file__).resolve().parent.parent +# Repository root (also the Docker WORKDIR /app). +REPO_ROOT = PACKAGE_DIR.parent + +FONTS_DIR = REPO_ROOT / "fonts" +ASSETS_DIR = REPO_ROOT / "assets" +UPLOADS_DIR = REPO_ROOT / "uploads" +OUTPUT_DIR = REPO_ROOT / "output" + +__all__ = [ + "PACKAGE_DIR", + "REPO_ROOT", + "FONTS_DIR", + "ASSETS_DIR", + "UPLOADS_DIR", + "OUTPUT_DIR", +] diff --git a/security_utils.py b/clipwright/core/security_utils.py similarity index 100% rename from security_utils.py rename to clipwright/core/security_utils.py diff --git a/clipwright/integrations/__init__.py b/clipwright/integrations/__init__.py new file mode 100644 index 0000000..73ee758 --- /dev/null +++ b/clipwright/integrations/__init__.py @@ -0,0 +1 @@ +"""Clipwright backend.""" diff --git a/file_hosts.py b/clipwright/integrations/file_hosts.py similarity index 100% rename from file_hosts.py rename to clipwright/integrations/file_hosts.py diff --git a/postiz.py b/clipwright/integrations/postiz.py similarity index 100% rename from postiz.py rename to clipwright/integrations/postiz.py diff --git a/yt_clients.py b/clipwright/integrations/yt_clients.py similarity index 100% rename from yt_clients.py rename to clipwright/integrations/yt_clients.py diff --git a/clipwright/layouts/__init__.py b/clipwright/layouts/__init__.py new file mode 100644 index 0000000..73ee758 --- /dev/null +++ b/clipwright/layouts/__init__.py @@ -0,0 +1 @@ +"""Clipwright backend.""" diff --git a/active_speaker.py b/clipwright/layouts/active_speaker.py similarity index 99% rename from active_speaker.py rename to clipwright/layouts/active_speaker.py index a3147f3..7b55da5 100644 --- a/active_speaker.py +++ b/clipwright/layouts/active_speaker.py @@ -220,7 +220,7 @@ def speaker_xs(held, centres, crop_w, orig_w, n_frames, fps, def verdicts_for_scene(video_path, start_f, end_f, fps, centres): """Per-window speaker verdicts for one scene, from its two face centres.""" - import split_layout + from clipwright.layouts import split_layout start_s = start_f / fps duration_s = (end_f - start_f) / fps diff --git a/camera_inset.py b/clipwright/layouts/camera_inset.py similarity index 98% rename from camera_inset.py rename to clipwright/layouts/camera_inset.py index c95b1c0..afc55bb 100644 --- a/camera_inset.py +++ b/clipwright/layouts/camera_inset.py @@ -20,7 +20,7 @@ them with margin. """ import os -from ffmpeg_utils import blurred_backdrop +from clipwright.media.ffmpeg_utils import blurred_backdrop CORNER_MARGIN = 0.20 # a subject this far from an edge (as a fraction of the # frame) still counts as anchored to it @@ -159,8 +159,8 @@ def detect(video_path, samples=10): """ import cv2 import numpy as np - import main as m - import screencast_layout + from clipwright.pipeline import main as m + from clipwright.layouts import screencast_layout cap = cv2.VideoCapture(video_path) if not cap.isOpened(): diff --git a/layout_picker.py b/clipwright/layouts/layout_picker.py similarity index 97% rename from layout_picker.py rename to clipwright/layouts/layout_picker.py index 9fa6ef2..a34e150 100644 --- a/layout_picker.py +++ b/clipwright/layouts/layout_picker.py @@ -82,9 +82,9 @@ def apply(decision): stacking regardless of what the model thinks, and a model that says "none" must not quietly undo that. """ - import active_speaker - import screencast_layout - import split_layout + from clipwright.layouts import active_speaker + from clipwright.layouts import screencast_layout + from clipwright.layouts import split_layout modules = {"split_layout": split_layout, "screencast_layout": screencast_layout, @@ -191,7 +191,7 @@ def pick(video_path, video_duration): # raises, and an unimportable SDK is just one more reason to fall back. from google import genai from google.genai import types as genai_types - import gemini_worker + from clipwright.pipeline import gemini_worker frames = sample_frames(video_path) if not frames: diff --git a/layout_ranges.py b/clipwright/layouts/layout_ranges.py similarity index 100% rename from layout_ranges.py rename to clipwright/layouts/layout_ranges.py diff --git a/panel_layout.py b/clipwright/layouts/panel_layout.py similarity index 99% rename from panel_layout.py rename to clipwright/layouts/panel_layout.py index c04f286..5f7c671 100644 --- a/panel_layout.py +++ b/clipwright/layouts/panel_layout.py @@ -24,7 +24,7 @@ import os import numpy as np -import split_layout +from clipwright.layouts import split_layout ENABLED = os.environ.get("PANEL_LAYOUT", "0") == "1" @@ -223,7 +223,7 @@ def detect_panel_scenes(video_path, scenes, strategies, samples=None): # Below the gate on purpose: main pulls torch/mediapipe, and the disabled # path (the default, and what CI exercises) must not pay that import. import cv2 - import main as m + from clipwright.pipeline import main as m cap = cv2.VideoCapture(video_path) if not cap.isOpened(): diff --git a/punch_in.py b/clipwright/layouts/punch_in.py similarity index 99% rename from punch_in.py rename to clipwright/layouts/punch_in.py index 320fcb0..c76ba8f 100644 --- a/punch_in.py +++ b/clipwright/layouts/punch_in.py @@ -162,7 +162,7 @@ def emphasis_times(video_path, duration, window=BEAT_WINDOW, A stand-in for the hook words until the transcript is wired through. Returns [] for silent or unreadable audio, which simply means no punches. """ - import active_speaker + from clipwright.layouts import active_speaker envelope = active_speaker.audio_envelope(video_path, 0.0, duration, window_s=window) diff --git a/reframe_v2.py b/clipwright/layouts/reframe_v2.py similarity index 98% rename from reframe_v2.py rename to clipwright/layouts/reframe_v2.py index cfb3a75..dbb6748 100644 --- a/reframe_v2.py +++ b/clipwright/layouts/reframe_v2.py @@ -21,13 +21,13 @@ import os import subprocess import tempfile -import active_speaker -import camera_inset -import punch_in -import screencast_layout -import layout_ranges -import split_layout -from ffmpeg_utils import (video_encode_args, blurred_backdrop, escape_filter_value, +from clipwright.layouts import active_speaker +from clipwright.layouts import camera_inset +from clipwright.layouts import punch_in +from clipwright.layouts import screencast_layout +from clipwright.layouts import layout_ranges +from clipwright.layouts import split_layout +from clipwright.media.ffmpeg_utils import (video_encode_args, blurred_backdrop, escape_filter_value, QUALITY_FAST, METADATA_SCRUB) ANALYSIS_MAX_WIDTH = 640 @@ -255,7 +255,7 @@ def _analyze_trajectory(input_video, scenes_boundaries, scene_strategies, """Replays v1's per-frame decision loop on a downscaled ffmpeg-decoded stream. Returns xs: crop x per frame (None on GENERAL frames).""" import numpy as np - import main as m + from clipwright.pipeline import main as m small_w = min(ANALYSIS_MAX_WIDTH, orig_w) if small_w % 2: @@ -362,7 +362,7 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None, segment's own encode, instead of main.apply_watermark re-encoding the finished clip once more. """ - import main as m + from clipwright.pipeline import main as m content_ranges = content_ranges or [] print(" 🚀 Reframe engine v2 (ffmpeg-native render)") diff --git a/screencast_layout.py b/clipwright/layouts/screencast_layout.py similarity index 98% rename from screencast_layout.py rename to clipwright/layouts/screencast_layout.py index af1d604..8e8b317 100644 --- a/screencast_layout.py +++ b/clipwright/layouts/screencast_layout.py @@ -123,7 +123,7 @@ def detect_faces_full_res(frame): screencast candidates only. """ import cv2 - import main as m + from clipwright.pipeline import main as m h, w, _ = frame.shape rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) @@ -178,7 +178,7 @@ def detect_content_ranges(video_path, video_duration): from google import genai from google.genai import types as genai_types - import gemini_worker + from clipwright.pipeline import gemini_worker model_name = os.environ.get("GEMINI_MODEL") or 'gemini-3.1-flash-lite' print("🔎 Checking for full-width on-screen content…") @@ -268,7 +268,7 @@ def detect_screencast_scenes(video_path, scenes, strategies, ranges, samples=6): # Below the gate on purpose: main pulls torch/mediapipe, and the disabled # path (the default, and what CI exercises) must not pay that import. import cv2 - import main as m + from clipwright.pipeline import main as m cap = cv2.VideoCapture(video_path) if not cap.isOpened(): diff --git a/split_layout.py b/clipwright/layouts/split_layout.py similarity index 99% rename from split_layout.py rename to clipwright/layouts/split_layout.py index 15325e6..7f3e90a 100644 --- a/split_layout.py +++ b/clipwright/layouts/split_layout.py @@ -18,7 +18,7 @@ import os import numpy as np -import frame_sampler +from clipwright.media import frame_sampler ENABLED = os.environ.get("SPLIT_LAYOUT", "0") == "1" @@ -221,7 +221,7 @@ def detect_split_scenes(video_path, scenes, strategies, samples=None): touching the single-speaker material that is most of the corpus. """ import cv2 - import main as m + from clipwright.pipeline import main as m if not ENABLED: return {} diff --git a/clipwright/media/__init__.py b/clipwright/media/__init__.py new file mode 100644 index 0000000..73ee758 --- /dev/null +++ b/clipwright/media/__init__.py @@ -0,0 +1 @@ +"""Clipwright backend.""" diff --git a/edit_builder.py b/clipwright/media/edit_builder.py similarity index 100% rename from edit_builder.py rename to clipwright/media/edit_builder.py diff --git a/editor.py b/clipwright/media/editor.py similarity index 99% rename from editor.py rename to clipwright/media/editor.py index 4b10309..9158cd1 100644 --- a/editor.py +++ b/clipwright/media/editor.py @@ -8,9 +8,9 @@ from google import genai from google.genai import types from pydantic import BaseModel -import gemini_worker -from edit_builder import build_filter_string -from ffmpeg_utils import video_encode_args, QUALITY, METADATA_SCRUB +from clipwright.pipeline import gemini_worker +from clipwright.media.edit_builder import build_filter_string +from clipwright.media.ffmpeg_utils import video_encode_args, QUALITY, METADATA_SCRUB class EditDecision(BaseModel): diff --git a/ffmpeg_utils.py b/clipwright/media/ffmpeg_utils.py similarity index 100% rename from ffmpeg_utils.py rename to clipwright/media/ffmpeg_utils.py diff --git a/frame_sampler.py b/clipwright/media/frame_sampler.py similarity index 100% rename from frame_sampler.py rename to clipwright/media/frame_sampler.py diff --git a/hooks.py b/clipwright/media/hooks.py similarity index 99% rename from hooks.py rename to clipwright/media/hooks.py index 279e9e5..3eb5e0f 100644 --- a/hooks.py +++ b/clipwright/media/hooks.py @@ -6,7 +6,8 @@ import urllib.request import uuid from PIL import Image, ImageDraw, ImageFont, ImageFilter -from ffmpeg_utils import video_encode_args, QUALITY, METADATA_SCRUB +from clipwright.media.ffmpeg_utils import video_encode_args, QUALITY, METADATA_SCRUB +from clipwright.core.paths import FONTS_DIR def _truncate_bytes(text, max_bytes): @@ -21,7 +22,7 @@ def _truncate_bytes(text, max_bytes): return encoded[:max_bytes].decode("utf-8", "ignore") FONT_URL = "https://github.com/googlefonts/noto-fonts/raw/main/hinted/ttf/NotoSerif/NotoSerif-Bold.ttf" -FONT_DIR = "fonts" +FONT_DIR = str(FONTS_DIR) FONT_PATH = os.path.join(FONT_DIR, "NotoSerif-Bold.ttf") # Bundled (SIL OFL, see fonts/Montserrat-OFL.txt): the "pill" look's sans. PILL_FONT_PATH = os.path.join(FONT_DIR, "Montserrat-ExtraBold.ttf") diff --git a/recut.py b/clipwright/media/recut.py similarity index 97% rename from recut.py rename to clipwright/media/recut.py index d9ed6b7..4c886fd 100644 --- a/recut.py +++ b/clipwright/media/recut.py @@ -24,7 +24,7 @@ import subprocess import time import uuid -from ffmpeg_utils import (METADATA_SCRUB, QUALITY_FAST, audio_encode_args, +from clipwright.media.ffmpeg_utils import (METADATA_SCRUB, QUALITY_FAST, audio_encode_args, video_encode_args) # EDL limits. Deliberately generous — the editor is for humans fixing cuts, @@ -109,7 +109,7 @@ def rebase_segments(segments, range_start, range_end=None): def snap_segments(segments, transcript, source_duration): """Snap each segment's bounds onto word boundaries (ground truth beats millisecond arithmetic — same rationale as the pipeline's snapping).""" - from clip_selection import snap_clip_to_words + from clipwright.pipeline.clip_selection import snap_clip_to_words words = transcript_words(transcript) if not words: @@ -316,7 +316,7 @@ def perform_recut(*, input_path, segments, output_dir, clean_name, # No reframe means no fresh layout sidecar; the captions would fall # back to the bottom on a stacked clip. Carry the input's layout # ranges through the cut instead (empty when the input has none). - import layout_ranges + from clipwright.layouts import layout_ranges layout_ranges.write(out_path, [ (r["start"], r["end"], r["layout"]) for r in layout_ranges.remap(layout_ranges.read(input_path), segments)]) @@ -338,5 +338,5 @@ def perform_recut(*, input_path, segments, output_dir, clean_name, def _main_attr(name): - import main # heavy — resolved only when a real render/caption runs + from clipwright.pipeline import main # heavy — resolved only when a real render/caption runs return getattr(main, name) diff --git a/scene_detection.py b/clipwright/media/scene_detection.py similarity index 100% rename from scene_detection.py rename to clipwright/media/scene_detection.py diff --git a/subtitles.py b/clipwright/media/subtitles.py similarity index 99% rename from subtitles.py rename to clipwright/media/subtitles.py index 78a22a8..9abe1c6 100644 --- a/subtitles.py +++ b/clipwright/media/subtitles.py @@ -3,8 +3,9 @@ import re import subprocess import sys -from ffmpeg_utils import (video_encode_args, escape_filter_value, QUALITY, +from clipwright.media.ffmpeg_utils import (video_encode_args, escape_filter_value, QUALITY, METADATA_SCRUB) +from clipwright.core.paths import FONTS_DIR _STDIO_CONFIGURED = False @@ -119,7 +120,7 @@ def transcribe_audio(video_path): Returns transcript in the same format as main.py for compatibility. """ # Lazy import: transcribe_backends imports helpers from this module. - from transcribe_backends import transcribe_media + from clipwright.pipeline.transcribe_backends import transcribe_media _log(f"🎙️ Transcribing audio from: {video_path}") transcript = transcribe_media(video_path) @@ -629,7 +630,7 @@ def subtitles_filter(srt_path, alignment=2, fontsize=16, # Let libass see the fonts bundled with the app (e.g. Anton for Impact) # even when the system fontconfig has no cache for them. - fonts_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fonts") + fonts_dir = str(FONTS_DIR) safe_fonts_dir = _escape_ffmpeg_filter_value(fonts_dir) # The first option is named explicitly (filename=) rather than positional: diff --git a/thumbnail.py b/clipwright/media/thumbnail.py similarity index 99% rename from thumbnail.py rename to clipwright/media/thumbnail.py index e4d460d..9cfe85e 100644 --- a/thumbnail.py +++ b/clipwright/media/thumbnail.py @@ -9,6 +9,7 @@ from google import genai from google.genai import types from google.genai import errors as genai_errors from PIL import Image, ImageDraw, ImageFont, ImageFilter +from clipwright.core.paths import FONTS_DIR # Text/analysis model (titles, concepts, description). Deliberately NOT tied to # GEMINI_MODEL: the pipeline runs flash-lite for a closed-choice layout pick, @@ -30,7 +31,7 @@ TITLE_MAX_CHARS = 65 THUMB_W, THUMB_H = 1280, 720 THUMB_MAX_BYTES = 2 * 1024 * 1024 # YouTube's upload limit -THUMB_FONT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fonts", "Anton-Regular.ttf") +THUMB_FONT = str(FONTS_DIR / "Anton-Regular.ttf") TEXT_POSITIONS = ("left", "right", "top", "bottom") @@ -49,7 +50,7 @@ def _parse_json(text): def _frame_parts(video_path, n=TITLE_FRAMES, width=TITLE_FRAME_WIDTH): """Evenly spaced frames as Gemini image parts (empty list on any failure).""" try: - from layout_picker import sample_frames + from clipwright.layouts.layout_picker import sample_frames return [types.Part.from_bytes(data=b, mime_type="image/jpeg") for b in sample_frames(video_path, n=n, width=width)] except Exception as e: @@ -70,7 +71,7 @@ def analyze_video_for_titles(api_key, video_path, transcript=None): "segments", "video_duration", "recommended" } """ if transcript is None: - from main import transcribe_video + from clipwright.pipeline.main import transcribe_video print("🎬 [Thumbnail] Transcribing video...") transcript = transcribe_video(video_path) else: @@ -265,7 +266,7 @@ def extract_face_frames(video_path, session_id, n=5, samples=40): thumbnails dir. Returns [{"url", "path", "time", "face": [x, y, w, h]}]. """ import cv2 - from main import detect_face_candidates + from clipwright.pipeline.main import detect_face_candidates out_dir = os.path.join("output", "thumbnails", session_id, "frames") os.makedirs(out_dir, exist_ok=True) diff --git a/watermarked.py b/clipwright/media/watermarked.py similarity index 100% rename from watermarked.py rename to clipwright/media/watermarked.py diff --git a/clipwright/pipeline/__init__.py b/clipwright/pipeline/__init__.py new file mode 100644 index 0000000..73ee758 --- /dev/null +++ b/clipwright/pipeline/__init__.py @@ -0,0 +1 @@ +"""Clipwright backend.""" diff --git a/clip_selection.py b/clipwright/pipeline/clip_selection.py similarity index 100% rename from clip_selection.py rename to clipwright/pipeline/clip_selection.py diff --git a/gemini_worker.py b/clipwright/pipeline/gemini_worker.py similarity index 99% rename from gemini_worker.py rename to clipwright/pipeline/gemini_worker.py index 0f98517..685d4d1 100644 --- a/gemini_worker.py +++ b/clipwright/pipeline/gemini_worker.py @@ -10,7 +10,7 @@ from google import genai from google.genai import types as genai_types from pydantic import BaseModel -from clip_selection import (clip_count_targets, clip_duration_bounds, +from clipwright.pipeline.clip_selection import (clip_count_targets, clip_duration_bounds, lookup_model_prices) load_dotenv() diff --git a/hook_grounding.py b/clipwright/pipeline/hook_grounding.py similarity index 97% rename from hook_grounding.py rename to clipwright/pipeline/hook_grounding.py index cb70785..12d744e 100644 --- a/hook_grounding.py +++ b/clipwright/pipeline/hook_grounding.py @@ -42,7 +42,7 @@ def screen_video() -> bool: (verified on a product update video: every GENERAL scene was a stats card), even when the width gate did not upgrade it to SCREENCAST.""" try: - import screencast_layout + from clipwright.layouts import screencast_layout return bool(getattr(screencast_layout, "ENABLED", False)) except Exception: return False @@ -50,7 +50,7 @@ def screen_video() -> bool: def screen_ranges(ranges, on_screen_video=None): """(start, end) pairs, clip seconds, of the stretches rendered on-screen.""" - import layout_ranges + from clipwright.layouts import layout_ranges layouts = set(SCREEN_LAYOUTS) if screen_video() if on_screen_video is None else on_screen_video: layouts.add("general") @@ -125,7 +125,7 @@ def _ask_gemini(frames, prompt, api_key): """One vision call; returns the parsed dict. Split out so tests can stub it.""" from google import genai from google.genai import types as genai_types - import gemini_worker + from clipwright.pipeline import gemini_worker client = genai.Client(api_key=api_key) model_name = os.environ.get("GEMINI_MODEL") or "gemini-3.1-flash-lite" @@ -151,7 +151,7 @@ def reground(clip_path, clip, transcript, start, end) -> Optional[dict]: "keeping the transcript hook.") return None try: - import gemini_worker + from clipwright.pipeline import gemini_worker times = sample_times(clip.get("layout_ranges"), float(end) - float(start)) frames = frames_at(clip_path, times) diff --git a/llm_backend.py b/clipwright/pipeline/llm_backend.py similarity index 98% rename from llm_backend.py rename to clipwright/pipeline/llm_backend.py index 4ba16da..96a5cbf 100644 --- a/llm_backend.py +++ b/clipwright/pipeline/llm_backend.py @@ -108,7 +108,7 @@ def generate_json(prompt: str, schema: Type[BaseModel], model: Optional[str] = N provider. Raises on HTTP errors, empty bodies and schema violations; the retry policy lives in the caller, same as for Gemini. """ - import gemini_worker # local import: keeps this module free of the google SDK + from clipwright.pipeline import gemini_worker # local import: keeps this module free of the google SDK url = f"{base_url()}/chat/completions" model = model or model_name() diff --git a/main.py b/clipwright/pipeline/main.py similarity index 98% rename from main.py rename to clipwright/pipeline/main.py index a0fd78d..4f6a580 100644 --- a/main.py +++ b/clipwright/pipeline/main.py @@ -23,16 +23,17 @@ import mediapipe as mp from google import genai from google.genai import types as genai_types -import frame_sampler -import gemini_worker -import hook_grounding -import layout_picker -import llm_backend -from clip_selection import (build_transcript_windows, clip_count_targets, +from clipwright.media import frame_sampler +from clipwright.pipeline import gemini_worker +from clipwright.pipeline import hook_grounding +from clipwright.layouts import layout_picker +from clipwright.pipeline import llm_backend +from clipwright.core.paths import ASSETS_DIR +from clipwright.pipeline.clip_selection import (build_transcript_windows, clip_count_targets, clip_duration_bounds, dedupe_overlapping, score_batches, shortlist_target, snap_clip_to_words, trim_to_best) -from ffmpeg_utils import (video_encode_args, audio_encode_args, cut_clip, QUALITY, +from clipwright.media.ffmpeg_utils import (video_encode_args, audio_encode_args, cut_clip, QUALITY, QUALITY_FAST, METADATA_SCRUB) from dotenv import load_dotenv import json @@ -633,7 +634,7 @@ def analyze_scenes_strategy(video_path, scenes): return strategies def detect_scenes(video_path): - import scene_detection + from clipwright.media import scene_detection return scene_detection.detect_scenes(video_path) def get_video_resolution(video_path): @@ -836,14 +837,14 @@ def download_youtube_video(url, output_dir=".", on_audio=None): """ # SSRF guard: block non-http(s) schemes and private/loopback/metadata hosts # before handing the URL to yt-dlp. - from security_utils import assert_public_url + from clipwright.core.security_utils import assert_public_url assert_public_url(url) # Throwaway hosts agents fall back to (tmpfiles.org) hand out short-lived # signed links; refresh through the host's page so yt-dlp gets the file. - import file_hosts + from clipwright.integrations import file_hosts url = file_hosts.resolve(url) # Reject non-video YouTube links before the download starts. - from yt_clients import NotASingleVideo, youtube_non_video_reason + from clipwright.integrations.yt_clients import NotASingleVideo, youtube_non_video_reason reason = youtube_non_video_reason(url) if reason: raise NotASingleVideo(f"This link is {reason}.") @@ -899,7 +900,7 @@ def download_youtube_video(url, output_dir=".", on_audio=None): # explicit `default,mweb` because the authed defaults alone return # "Video unavailable" on a share of videos, from every IP, and that was # what fed the per-GB proxy (6-sep-2026, verified in the prod container). - from yt_clients import hd_extractor_args, fallback_extractor_args + from clipwright.integrations.yt_clients import hd_extractor_args, fallback_extractor_args hd_args = hd_extractor_args(_bgutil_http, _bgutil_script) fallback_args = fallback_extractor_args(_bgutil_http, _bgutil_script) @@ -1210,7 +1211,7 @@ def auto_caption_clip(clip_path, transcript, clip_start, clip_end, split_ranges= if not transcript or not transcript.get('segments'): return None # silent video: nothing to caption try: - import subtitles as _subs + from clipwright.media import subtitles as _subs style = _subs.AUTO_CAPTION_STYLE output_dir = os.path.dirname(clip_path) stem = os.path.basename(clip_path) @@ -1242,7 +1243,7 @@ def auto_caption_clip(clip_path, transcript, clip_start, clip_end, split_ranges= out_path = os.path.join(output_dir, f"subtitled_{generation_id}_{stem}") if split_ranges is None: - import layout_ranges as _layouts + from clipwright.layouts import layout_ranges as _layouts split_ranges = _layouts.split_ranges(_layouts.read(clip_path)) if not _subs.generate_ass( transcript, clip_start, clip_end, ass_path, @@ -1302,7 +1303,7 @@ def auto_hook_clip(clip_path, clip, captions=None): except ValueError: seconds = 5.0 try: - from hooks import add_hook_to_video, HOOK_STYLES + from clipwright.media.hooks import add_hook_to_video, HOOK_STYLES if style not in HOOK_STYLES: style = "pill" output_dir = os.path.dirname(clip_path) @@ -1378,8 +1379,7 @@ WATERMARK_OPACITY = 0.85 def watermark_logo_path(): - return os.path.join(os.path.dirname(os.path.abspath(__file__)), - "assets", "watermark.png") + return str(ASSETS_DIR / "watermark.png") def watermark_filter(vw, vh, video="[0:v]", logo="[1:v]", out=""): @@ -1451,7 +1451,7 @@ def mark_delivery(final_path, marker=None): be made: the mark must never cost the user the clip (same fail-open rule apply_watermark has always had). """ - import watermarked + from clipwright.media import watermarked out_path = os.path.join(os.path.dirname(final_path), watermarked.marked_name(final_path)) if os.path.exists(out_path) and os.path.getsize(out_path) > 0: @@ -1484,7 +1484,7 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE # falls back to the v1 frame loop below so a v2 edge case can't kill jobs. if os.environ.get("REFRAME_ENGINE", "v2").strip().lower() != "v1": try: - import reframe_v2 + from clipwright.layouts import reframe_v2 t0 = time.time() result = reframe_v2.render(input_video, final_output_video, aspect_ratio, force_strategy=force_strategy, @@ -1536,7 +1536,7 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE # Same delivery floor as the v2 engine — a fallback render is still the clip # the user posts, so it must not ship sub-HD. The frame loop below already # resizes every cropped frame to these dims, so nothing else changes. - from reframe_v2 import delivery_size + from clipwright.layouts.reframe_v2 import delivery_size OUTPUT_WIDTH, OUTPUT_HEIGHT = delivery_size(original_width, original_height, aspect_ratio) @@ -1776,7 +1776,7 @@ def _free_gpu_cache(): def transcribe_video(video_path): print("🎙️ Transcribing video...") - from transcribe_backends import transcribe_media, release_models, host_asr_slot + from clipwright.pipeline.transcribe_backends import transcribe_media, release_models, host_asr_slot # At most ASR_HOST_SLOTS jobs transcribe on the GPU at once, host-wide. # Inside the slot, the model's VRAM is handed back before the long render @@ -2308,7 +2308,7 @@ if __name__ == '__main__': _w = int(_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) _h = int(_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) _cap.release() - from reframe_v2 import source_already_fits # imports main back + from clipwright.layouts.reframe_v2 import source_already_fits # imports main back # A source already shot vertical has no width to reorganise, and # the render passes it through whatever the model says. Asking # anyway costs a Gemini call per upload to be ignored. @@ -2340,7 +2340,7 @@ if __name__ == '__main__': # 3. Transcribe — unless the video has no audio, in which case fall back # to Gemini vision (picks clips from the imagery instead of the speech). - from transcribe_backends import NoAudioError + from clipwright.pipeline.transcribe_backends import NoAudioError transcript = None # Module handover (issue #68): another module already transcribed this # exact source with the same backend, so reuse its output. Any problem @@ -2453,7 +2453,7 @@ if __name__ == '__main__': deliver_path = clip_final_path # Which stretches were stacked (SPLIT): captions go on the # seam there, and /api/subtitle needs it again later. - import layout_ranges as _layouts + from clipwright.layouts import layout_ranges as _layouts clip['layout_ranges'] = _layouts.read(clip_final_path) # The hook was written from the transcript alone. When the # render put this clip's meaning on the screen, rewrite hook @@ -2505,7 +2505,7 @@ if __name__ == '__main__': if os.environ.get("WATERMARK") == "1": # Tells the /videos guard that the clean twins in this # directory are not for serving (watermarked.MARKER_FILE). - import watermarked + from clipwright.media import watermarked watermarked.mark_job(output_dir) with ThreadPoolExecutor(max_workers=min(clip_workers, len(shorts))) as pool: # Best clip first: the pool starts work in submission order, so diff --git a/quality_probe.py b/clipwright/pipeline/quality_probe.py similarity index 93% rename from quality_probe.py rename to clipwright/pipeline/quality_probe.py index 1fd55b5..db85838 100644 --- a/quality_probe.py +++ b/clipwright/pipeline/quality_probe.py @@ -16,15 +16,16 @@ import sys from dotenv import load_dotenv +from clipwright.core.paths import REPO_ROOT + load_dotenv() def _find_cookies_path(): # Mirrors main.py's cookie discovery. - script_dir = os.path.dirname(os.path.abspath(__file__)) for candidate in [ - os.path.join(script_dir, 'www.youtube.com_cookies.txt'), - os.path.join(script_dir, 'cookies.txt'), + str(REPO_ROOT / 'www.youtube.com_cookies.txt'), + str(REPO_ROOT / 'cookies.txt'), '/app/cookies.txt', ]: if os.path.exists(candidate): @@ -44,8 +45,8 @@ def main() -> int: # result is the fail-open "unknown", so the caller carries on and the # real probe / download refuse the URL with their own message. try: - from security_utils import assert_public_url - from yt_clients import youtube_non_video_reason + from clipwright.core.security_utils import assert_public_url + from clipwright.integrations.yt_clients import youtube_non_video_reason assert_public_url(args.url) if youtube_non_video_reason(args.url): raise ValueError("not a single video") diff --git a/transcribe_backends.py b/clipwright/pipeline/transcribe_backends.py similarity index 99% rename from transcribe_backends.py rename to clipwright/pipeline/transcribe_backends.py index 9da46a1..576f60b 100644 --- a/transcribe_backends.py +++ b/clipwright/pipeline/transcribe_backends.py @@ -32,7 +32,7 @@ import tempfile import threading import time -from subtitles import ( +from clipwright.media.subtitles import ( get_whisper_config, WHISPER_TRANSCRIBE_PARAMS, merge_continuation_words, @@ -368,7 +368,7 @@ def release_models(): del whisper, parakeet # TransNetV2 is the other torch tenant an in-process pipeline leaves # behind (scene_detection keeps it as a module singleton too). - tn2 = sys.modules.get("scene_detection") + tn2 = sys.modules.get("clipwright.media.scene_detection") if tn2 is not None: tn2._tn2_model = None import gc diff --git a/clipwright/tools/__init__.py b/clipwright/tools/__init__.py new file mode 100644 index 0000000..73ee758 --- /dev/null +++ b/clipwright/tools/__init__.py @@ -0,0 +1 @@ +"""Clipwright backend.""" diff --git a/verify_aesthetic.py b/clipwright/tools/verify_aesthetic.py similarity index 95% rename from verify_aesthetic.py rename to clipwright/tools/verify_aesthetic.py index b288f86..e4f5ee9 100644 --- a/verify_aesthetic.py +++ b/clipwright/tools/verify_aesthetic.py @@ -2,7 +2,7 @@ import os import shutil # Check if PIL is installed, if not we can't run this locally but it will run in docker try: - from hooks import create_hook_image + from clipwright.media.hooks import create_hook_image except ImportError: print("⚠️ PIL not found locally. Please run this inside the Docker container.") # Mocking for local check if needed or just exit diff --git a/verify_custom_hook.py b/clipwright/tools/verify_custom_hook.py similarity index 94% rename from verify_custom_hook.py rename to clipwright/tools/verify_custom_hook.py index e645927..028bffc 100644 --- a/verify_custom_hook.py +++ b/clipwright/tools/verify_custom_hook.py @@ -1,6 +1,6 @@ import os try: - from hooks import create_hook_image + from clipwright.media.hooks import create_hook_image except ImportError: print("⚠️ PIL not found locally. Run inside Docker.") exit(1) diff --git a/verify_hooks.py b/clipwright/tools/verify_hooks.py similarity index 94% rename from verify_hooks.py rename to clipwright/tools/verify_hooks.py index 9c7a51c..a1bee1b 100644 --- a/verify_hooks.py +++ b/clipwright/tools/verify_hooks.py @@ -1,6 +1,6 @@ import os import shutil -from hooks import create_hook_image +from clipwright.media.hooks import create_hook_image def verify(): print("🧪 Verifying Hook Image Generation...") diff --git a/dashboard/public/n8n-content-machine-workflow.png b/dashboard/public/n8n-content-machine-workflow.png deleted file mode 100644 index bf5a1bd..0000000 Binary files a/dashboard/public/n8n-content-machine-workflow.png and /dev/null differ diff --git a/dashboard/seo/landing-fallback.js b/dashboard/seo/landing-fallback.js index 189839c..0393c6d 100644 --- a/dashboard/seo/landing-fallback.js +++ b/dashboard/seo/landing-fallback.js @@ -90,7 +90,7 @@ export const LANDING_FALLBACK = `

AI clip generator · self-hosted & open source

the free open source ai clip generator, built to clip what people actually watch.

-

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 Postiz instance, or wire the REST API into your own pipeline with the n8n workflow. Just want it free? Start with the free AI clip generator.

+

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 Postiz instance, or wire the REST API into your own pipeline. Just want it free? Start with the free AI clip generator.

No account, no card, no watermark. Run it yourself: self-host free on GitHub and bring your own Gemini key.

@@ -146,8 +146,7 @@ export const LANDING_FALLBACK = ` diff --git a/dashboard/seo/pages.js b/dashboard/seo/pages.js index 153f79a..76282c5 100644 --- a/dashboard/seo/pages.js +++ b/dashboard/seo/pages.js @@ -844,9 +844,7 @@ deliveries.

POSTs to /api/process, then a Webhook trigger that receives the 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 -nodes cover it. There is now also an importable -n8n workflow that wires the whole -loop, including channel watching, Telegram approval and scheduled publishing.

+nodes cover it.

A weekly pipeline in one cron line

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?', 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?', 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: ` -

-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. -
The whole machine is one canvas: watch the channel, clip, approve from Telegram, drip-publish and measure.
-
-

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.

- -

Download the workflow

-

The JSON lives in the project repository, not behind an email form:

- -

In n8n: Workflows → Import from file, then fill in your channel -id and chat id where the sticky notes on the canvas say so.

- -

What the workflow actually does

-

Four stages, all on one canvas:

-
    -
  1. Watch the channel. A daily schedule trigger reads -youtube.com/feeds/videos.xml?channel_id=..., 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.
  2. -
  3. Clip, then get called back. One HTTP request to -/api/process carrying a webhook_url. When the job -ends, Clipwright POSTs once with the finished clips and their URLs. -There is no Wait node anywhere in the workflow.
  4. -
  5. Approve from your phone. 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.
  6. -
  7. Drip-publish and measure. 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.
  8. -
- -

Why posting does not need TikTok or Instagram credentials

-

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 -POST /api/postiz/post 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.

- -

Scheduling that does not double-book

-

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 -(GET /api/postiz/scheduled) and picks the first free slot from it, -which is shared state and cannot race with itself that way. The same endpoint, -plus DELETE /api/postiz/scheduled/{id}, is how you inspect or -cancel a post before it goes out.

- -

What it costs to run

-${pricingParagraph} -

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.

- -

Known limits, before you find them the hard way

-
    -
  • Telegram previews a video by URL up to about 20 MB; larger clips arrive as a -link message carrying the same approval buttons.
  • -
  • A YouTube channel RSS feed exposes only the latest 15 videos, so the -back-catalogue drip reaches back that far and no further.
  • -
  • 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.
  • -
  • 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.
  • -
- -${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 git.pbento.pt/pedro-bento/clipwright.`, - '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. * @@ -1895,7 +1754,7 @@ ${faqBlock([ ${sources([ 'Opus Clip tier minutes and prices checked 2026-07-27 on their public pricing page.', 'Inset detection and layout accuracy figures are our own measurements on a 48-video internal corpus, 2026-08.', - 'Silent-footage thresholds (8 words, 5 words per minute) and the vision fallback are in main.py; Gemini video token rates from Google\'s published pricing.', + 'Silent-footage thresholds (8 words, 5 words per minute) and the vision fallback are in clipwright/pipeline/main.py; Gemini video token rates from Google\'s published pricing.', `Inset, WIDE and screencast layout implementations in the project source at git.pbento.pt/pedro-bento/clipwright.`, ])} `, @@ -1983,7 +1842,6 @@ export function buildPages() { podcastToShorts(), youtubeConverter(), automateShorts(), - n8nTemplate(), ...toolPages(), ] } @@ -2013,7 +1871,6 @@ export function relatedFor(page, all) { '/podcast-to-shorts': 'Two-speaker episodes without cropping anyone out.', '/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.', - '/n8n-youtube-shorts-automation': 'The importable workflow: channel in, approved shorts out.', '/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-tag-generator': 'Tags, 10 title options or a description from a short brief.', diff --git a/dashboard/src/components/HookModal.jsx b/dashboard/src/components/HookModal.jsx index a77c4d6..8bb3c9e 100644 --- a/dashboard/src/components/HookModal.jsx +++ b/dashboard/src/components/HookModal.jsx @@ -11,7 +11,7 @@ const ENTRANCE_OPTIONS = [ { value: 'none', label: 'None' }, ]; -// Must mirror hooks.py HOOK_STYLES. +// Must mirror clipwright/media/hooks.py HOOK_STYLES. const HOOK_STYLES = [ { value: 'pill', label: 'Pills', box: 'rgba(255,255,255,0.98)', text: '#000', sans: true }, { value: 'classic', label: 'Classic', box: 'rgba(255,255,255,0.94)', text: '#000' }, @@ -22,7 +22,7 @@ const HOOK_STYLES = [ { value: 'outline_yellow', label: 'Outline+', box: 'transparent', text: '#FFD600', outline: true }, ]; -// Must mirror hooks.py HOOK_FONTS (all bundled: /fonts/*.ttf). +// Must mirror clipwright/media/hooks.py HOOK_FONTS (all bundled: /fonts/*.ttf). const FONT_OPTIONS = [ { value: 'montserrat', label: 'Montserrat' }, { value: 'anton', label: 'Anton' }, @@ -33,7 +33,7 @@ const FONT_CSS = { anton: { fontFamily: "'Anton-Regular', Impact, sans-serif", fontWeight: 400 }, serif: { fontFamily: "'Noto Serif', Georgia, serif", fontWeight: 700 }, }; -// The style's own typeface when none is picked (what hooks.py renders). +// The style's own typeface when none is picked (what clipwright/media/hooks.py renders). const styleFont = (st) => (st === 'pill' ? 'montserrat' : 'serif'); const POSITION_OPTIONS = [ diff --git a/dashboard/src/remotion/compositions/HookOverlay.tsx b/dashboard/src/remotion/compositions/HookOverlay.tsx index 808a00c..a53009d 100644 --- a/dashboard/src/remotion/compositions/HookOverlay.tsx +++ b/dashboard/src/remotion/compositions/HookOverlay.tsx @@ -25,7 +25,7 @@ const SIZE_SCALE: Record = { L: 1.3, }; -// Percentages must match hooks.py's overlay_y math (top 20% / bottom 70%), +// Percentages must match clipwright/media/hooks.py's overlay_y math (top 20% / bottom 70%), // or the preview drifts from what the server path renders. const POSITION_STYLE: Record = { top: { top: "20%", bottom: "auto" }, @@ -33,13 +33,13 @@ const POSITION_STYLE: Record = { bottom: { top: "70%", bottom: "auto" }, }; -// Must mirror hooks.py HOOK_STYLES (the server-side FFmpeg fallback). +// Must mirror clipwright/media/hooks.py HOOK_STYLES (the server-side FFmpeg fallback). interface HookLook { box: string | null; text: string; outlinePx: number; shadow: boolean; - /** One rounded box per line (hooks.py _draw_pills) instead of one card. */ + /** One rounded box per line (clipwright/media/hooks.py _draw_pills) instead of one card. */ pills?: boolean; } @@ -127,7 +127,7 @@ const HookBox: React.FC = ({ config, displayFrames }) => { const positionStyle = POSITION_STYLE[config.position] ?? POSITION_STYLE.top; const look = HOOK_LOOKS[config.style ?? "pill"] ?? HOOK_LOOKS.pill; - // Typeface and size as hooks.py: the chosen font, else the style's own; + // Typeface and size as clipwright/media/hooks.py: the chosen font, else the style's own; // font size = factor x the 90%-of-width box. const typeface = HOOK_FONTS[config.font ?? (look.pills ? "montserrat" : "serif")] ?? HOOK_FONTS.serif; const fontSize = Math.round(1080 * 0.9 * typeface.factor * scale); @@ -135,7 +135,7 @@ const HookBox: React.FC = ({ config, displayFrames }) => { if (look.pills) { // box-decoration-break: clone gives every wrapped line its own padded, - // rounded box, the same stack hooks.py draws for the FFmpeg path. + // rounded box, the same stack clipwright/media/hooks.py draws for the FFmpeg path. return (
= { montserrat: { family: `'${MONTSERRAT_FONT_FAMILY}', 'Montserrat', sans-serif`, weight: 800, factor: 0.064 }, diff --git a/demo-clipwright.mp4 b/demo-clipwright.mp4 deleted file mode 100644 index fe65ed1..0000000 Binary files a/demo-clipwright.mp4 and /dev/null differ diff --git a/docs/compliance/retencion.md b/docs/compliance/retencion.md index e36be20..62eac71 100644 --- a/docs/compliance/retencion.md +++ b/docs/compliance/retencion.md @@ -33,15 +33,14 @@ La retención de fotos de actor se retiró con la función de vídeo UGC | Qué | Plazo | Dónde se aplica | |---|---|---| -| 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 | `clipwright.api.app.cleanup_jobs`, `JOB_RETENTION_SECONDS` | ## 3. Base de datos de la aplicación (si usas cuentas) | Qué | Plazo | Dónde se aplica | |---|---|---| -| Datos de cuenta y proyectos | Mientras exista la cuenta; **inmediato** al borrarla | `app.py`, la ruta de borrado de cuenta | -| **Declaración de derechos** (IP truncada a /24, user-agent, fecha, origen) | Con el proyecto al que pertenece → hasta 5 años | `app.py` (captura) → `Project.state.rights_attestation` | -| `proxy_usage` (host de la URL, id de trabajo; **sin usuario**) | Contabilidad de costes; sin datos personales | `metering.py` | +| Datos de cuenta y proyectos | Mientras exista la cuenta; **inmediato** al borrarla | `clipwright/api/app.py`, la ruta de borrado de cuenta | +| **Declaración de derechos** (IP truncada a /24, user-agent, fecha, origen) | Con el proyecto al que pertenece → hasta 5 años | `clipwright/api/app.py` (captura) → `Project.state.rights_attestation` | ## 4. Navegador del usuario (localStorage, nunca cookies de terceros) @@ -58,7 +57,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 | | 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 | --- @@ -69,8 +67,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 arriba describe la intención; hasta que esté configurado, el plazo real depende 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 que los perfiles caducan a 13 meses y los eventos a 25, y borra el perfil por `profileId` cuando llega el evento `AccountDeleted`. diff --git a/docs/dsa-notice-and-action.md b/docs/dsa-notice-and-action.md deleted file mode 100644 index 826378c..0000000 --- a/docs/dsa-notice-and-action.md +++ /dev/null @@ -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 and it has reference . 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 of : we have access to it / decided not to act>. 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: , and to -> which content, identified precisely. -> - Facts relied on: . -> - Ground: . -> - Automated means: none. A person reviewed this. being true.> -> - Territorial scope: . -> - 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. diff --git a/examples/n8n/README.md b/examples/n8n/README.md deleted file mode 100644 index 98597d9..0000000 --- a/examples/n8n/README.md +++ /dev/null @@ -1,107 +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=`; 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 the connected Postiz channels. - The example node uses the legacy `platforms` list; swap it for - `integration_ids` (from `GET /api/postiz/integrations`) to target an exact - channel, since several channels of the same network are distinct entries. - 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=&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/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). -Prefer `integration_ids` from `GET /api/postiz/integrations` to pick an exact -channel (multiple channels per network are supported); `platforms` is the legacy -fallback. 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=&days=7` (one channel) and -`GET /api/postiz/analytics/posts?post_id=&days=7` (one post) — both the -channel and the post id are required. -Full API reference: `/docs` (OpenAPI) on your instance. diff --git a/examples/n8n/clipwright-clip-and-notify.json b/examples/n8n/clipwright-clip-and-notify.json deleted file mode 100644 index 58c5471..0000000 --- a/examples/n8n/clipwright-clip-and-notify.json +++ /dev/null @@ -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=`), 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": {} -} \ No newline at end of file diff --git a/examples/n8n/clipwright-content-machine.json b/examples/n8n/clipwright-content-machine.json deleted file mode 100644 index 2eb90af..0000000 --- a/examples/n8n/clipwright-content-machine.json +++ /dev/null @@ -1,1012 +0,0 @@ -{ - "name": "Clip new YouTube uploads into viral shorts with open-source Clipwright and publish after Telegram approval", - "nodes": [ - { - "parameters": { - "content": "## Clip your YouTube channel and publish after approval\n\n**Who's it for**\nCreators and small teams who publish long videos and want shorts from them without\nhanding the publish button to a machine. It suits anyone who already runs n8n and\ndoes not want to build the clipping and the multi-platform posting themselves.\n\n**What it does**\nOnce a day it reads your channel RSS feed and picks one video: your newest upload,\nor the next unprocessed one from the back catalogue. It sends that video to\nClipwright, which returns finished 9:16 clips with subtitles through a webhook, so\nthere is no polling loop. Each clip arrives in Telegram with Publish and Skip\nbuttons. Approved clips are scheduled one per day through your\nself-hosted Postiz instance, and every Sunday the workflow reports the impressions\nand best post of what it published.\n\n**How to set up**\n1. Point the request nodes at your self-hosted instance\n (`http://localhost:8000`); no API key is needed on a self-hosted instance.\n2. Create a Telegram bot with @BotFather and add the Telegram credential.\n3. Fill the three **Settings** nodes with your YouTube channel id and Telegram chat id.\n4. Copy the production URL of the *Clips ready* webhook node into the\n `webhook_url` field of *Start Clipwright job*.\n\n**Requirements**\nA self-hosted Clipwright instance, a self-hosted Postiz instance, a Telegram bot, and an n8n reachable\nover https so Telegram can register the approval buttons.\n\n**How to customize**\nChange the schedule to clip more or less often, edit the channels targeted by\n*Schedule Postiz post* (by integration id, or the legacy platforms list), widen the posting rhythm in *Pick next free slot*, or\nreplace the Telegram approval with your own review step.", - "height": 900, - "width": 460, - "color": 3 - }, - "id": "note-overview", - "name": "Read me first", - "type": "n8n-nodes-base.stickyNote", - "typeVersion": 1, - "position": [ - -1060, - -120 - ] - }, - { - "parameters": { - "content": "## ACT 1 \u2014 Watch the channel (daily)\n\nOnce a day this branch reads your channel's RSS feed and picks **one** video to clip: a new upload if there is one, otherwise the next unprocessed video from your back catalog (newest first). One video per day keeps your quota burn predictable.\n\n**Setup**: put your channel id in the *Channel RSS feed* node (`https://www.youtube.com/feeds/videos.xml?channel_id=UC...`). Find it at youtube.com \u2192 your channel \u2192 About \u2192 Share \u2192 Copy channel ID.\n\nIf Clipwright rejects the job, the machine tells you on Telegram instead of failing silently, and the video is retried tomorrow.", - "height": 420, - "width": 400, - "color": 7 - }, - "id": "note-act1", - "name": "Act 1 note", - "type": "n8n-nodes-base.stickyNote", - "typeVersion": 1, - "position": [ - -560, - -120 - ] - }, - { - "parameters": { - "rule": { - "interval": [ - { - "field": "days", - "triggerAtHour": 9 - } - ] - } - }, - "id": "daily-schedule", - "name": "Every day 09:00", - "type": "n8n-nodes-base.scheduleTrigger", - "typeVersion": 1.2, - "position": [ - -80, - 0 - ] - }, - { - "parameters": { - "url": "=https://www.youtube.com/feeds/videos.xml?channel_id={{ $json.youtube_channel_id }}", - "options": {} - }, - "id": "channel-rss", - "name": "Channel RSS feed", - "type": "n8n-nodes-base.rssFeedRead", - "typeVersion": 1.1, - "position": [ - 220, - 0 - ] - }, - { - "parameters": { - "jsCode": "// One video per run: the newest video we have not processed yet.\n// A fresh upload is by definition the newest unprocessed one, so new\n// uploads win automatically; with nothing new, the back catalog drains\n// newest-first. Processed links persist in workflow static data\n// (production executions only \u2014 manual test runs do not save it).\nconst staticData = $getWorkflowStaticData('global');\nconst done = staticData.processedVideos || [];\nconst videos = $input.all().map((i) => i.json);\nconst fresh = videos.filter((v) => v.link && !done.includes(v.link));\nif (fresh.length === 0) {\n return [];\n}\nconst pick = fresh[0];\nreturn [{ json: { url: pick.link, title: pick.title, published: pick.isoDate } }];" - }, - "id": "pick-video", - "name": "Pick next video", - "type": "n8n-nodes-base.code", - "typeVersion": 2, - "position": [ - 440, - 0 - ] - }, - { - "parameters": { - "method": "POST", - "url": "http://localhost:8000/api/process", - "sendBody": true, - "specifyBody": "json", - "jsonBody": "={\n \"url\": \"{{ $json.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": [ - 660, - 0 - ], - "onError": "continueErrorOutput" - }, - { - "parameters": { - "jsCode": "// Only mark the video done once Clipwright accepted the job \u2014 a failed\n// submit (quota, downtime) leaves it unmarked so tomorrow retries it.\nconst staticData = $getWorkflowStaticData('global');\nconst done = staticData.processedVideos || [];\nconst url = $('Pick next video').first().json.url;\nif (!done.includes(url)) {\n done.push(url);\n}\nstaticData.processedVideos = done;\nreturn $input.all();" - }, - "id": "mark-processed", - "name": "Mark video as processed", - "type": "n8n-nodes-base.code", - "typeVersion": 2, - "position": [ - 800, - -60 - ] - }, - { - "parameters": { - "chatId": "={{ $('Settings').first().json.telegram_chat_id }}", - "text": "=\ud83c\udfac Clipping started: {{ $('Pick next video').first().json.title }}\n\nI'll send the clips here for approval when they're ready.", - "additionalFields": {} - }, - "id": "tg-clipping", - "name": "Notify: clipping started", - "type": "n8n-nodes-base.telegram", - "typeVersion": 1.2, - "position": [ - 1020, - -60 - ], - "credentials": { - "telegramApi": { - "name": "Telegram bot" - } - } - }, - { - "parameters": { - "chatId": "={{ $('Settings').first().json.telegram_chat_id }}", - "text": "\u26a0\ufe0f Content machine paused: Clipwright rejected the job. The video was NOT marked as processed, so it will be retried tomorrow. Check the Clipwright server logs for the error.", - "additionalFields": {} - }, - "id": "tg-quota", - "name": "Notify: submit failed", - "type": "n8n-nodes-base.telegram", - "typeVersion": 1.2, - "position": [ - 800, - 120 - ], - "credentials": { - "telegramApi": { - "name": "Telegram bot" - } - } - }, - { - "parameters": { - "content": "## ACT 2 \u2014 Clips arrive on your phone\n\n**No polling, no Wait-node loop.** Clipwright calls this webhook once per job (success **and** failure, so nothing ever hangs). Each finished 9:16 clip lands in your Telegram with two buttons: \u2705 publish or \u274c skip \u2014 a human approves every post, which is also what keeps you on the right side of YouTube's inauthentic-content policy.\n\n**Setup**: copy the **production** URL of the *Clips ready* webhook node and paste it as `webhook_url` inside *Start Clipwright job*. Telegram fetches videos by URL up to ~20 MB; bigger clips fall back to a message with the clip URL and the same buttons.", - "height": 380, - "width": 400, - "color": 7 - }, - "id": "note-act2", - "name": "Act 2 note", - "type": "n8n-nodes-base.stickyNote", - "typeVersion": 1, - "position": [ - -560, - 340 - ] - }, - { - "parameters": { - "httpMethod": "POST", - "path": "clipwright-machine-clips", - "options": {} - }, - "id": "clips-webhook", - "name": "Clips ready (webhook)", - "type": "n8n-nodes-base.webhook", - "typeVersion": 2, - "position": [ - -80, - 440 - ], - "webhookId": "30f3bc66-1f03-4d2f-94b8-aed49571238d" - }, - { - "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": [ - 200, - 440 - ] - }, - { - "parameters": { - "jsCode": "// One Telegram message per clip, carrying everything the approval\n// buttons need inside callback_data (Telegram caps it at 64 bytes:\n// action|job_id|clip_index fits).\nconst body = $json.body;\nconst base = 'http://localhost:8000';\nreturn (body.clips || []).map((clip, i) => ({\n json: {\n job_id: body.job_id,\n clip_index: i,\n title: clip.title || `Clip ${i + 1}`,\n // The webhook returns a path relative to the instance unless the server\n // sets PUBLIC_API_URL; make it absolute so Telegram can fetch it.\n video_url: clip.video_url && clip.video_url.startsWith('/')\n ? base + clip.video_url\n : clip.video_url,\n },\n}));" - }, - "id": "split-clips", - "name": "One item per clip", - "type": "n8n-nodes-base.code", - "typeVersion": 2, - "position": [ - 360, - 380 - ] - }, - { - "parameters": { - "operation": "sendVideo", - "chatId": "={{ $('Settings (clips)').first().json.telegram_chat_id }}", - "file": "={{ $json.video_url }}", - "replyMarkup": "inlineKeyboard", - "inlineKeyboard": { - "rows": [ - { - "row": { - "buttons": [ - { - "text": "\u2705 Publish", - "additionalFields": { - "callback_data": "=pub|{{ $json.job_id }}|{{ $json.clip_index }}" - } - }, - { - "text": "\u274c Skip", - "additionalFields": { - "callback_data": "skip" - } - } - ] - } - } - ] - }, - "additionalFields": { - "caption": "={{ $json.title }}" - } - }, - "id": "tg-clip-video", - "name": "Send clip for approval", - "type": "n8n-nodes-base.telegram", - "typeVersion": 1.2, - "position": [ - 580, - 380 - ], - "onError": "continueErrorOutput", - "credentials": { - "telegramApi": { - "name": "Telegram bot" - } - } - }, - { - "parameters": { - "chatId": "={{ $('Settings (clips)').first().json.telegram_chat_id }}", - "text": "=\ud83c\udfac {{ $json.title }}\n\nToo big for Telegram preview \u2014 watch it here:\n{{ $json.video_url }}", - "replyMarkup": "inlineKeyboard", - "inlineKeyboard": { - "rows": [ - { - "row": { - "buttons": [ - { - "text": "\u2705 Publish", - "additionalFields": { - "callback_data": "=pub|{{ $json.job_id }}|{{ $json.clip_index }}" - } - }, - { - "text": "\u274c Skip", - "additionalFields": { - "callback_data": "skip" - } - } - ] - } - } - ] - }, - "additionalFields": {} - }, - "id": "tg-clip-link", - "name": "Send clip link instead", - "type": "n8n-nodes-base.telegram", - "typeVersion": 1.2, - "position": [ - 800, - 480 - ], - "credentials": { - "telegramApi": { - "name": "Telegram bot" - } - } - }, - { - "parameters": { - "chatId": "={{ $('Settings (clips)').first().json.telegram_chat_id }}", - "text": "=\u274c Clipwright job failed: {{ $json.body.error || 'unknown error' }}\n\nNothing was published. The machine keeps running tomorrow.", - "additionalFields": {} - }, - "id": "tg-job-failed", - "name": "Notify: job failed", - "type": "n8n-nodes-base.telegram", - "typeVersion": 1.2, - "position": [ - 360, - 560 - ], - "credentials": { - "telegramApi": { - "name": "Telegram bot" - } - } - }, - { - "parameters": { - "content": "## ACT 3 \u2014 Tap \u2705, it gets scheduled\n\nThe Telegram trigger listens for the approval buttons. Every approved clip is scheduled through Clipwright and your self-hosted Postiz instance (which holds every connected account) at a rate of **one post per day**: approve five clips today and you just filled five days of content.\n\nThe next free slot is computed from the **queue the server actually holds** (`GET /api/postiz/scheduled`), not from a counter inside n8n \u2014 two clips approved seconds apart would otherwise both book the same slot and go out together.\n\n**Setup**: none beyond the Telegram credential \u2014 the chat id comes from the button tap itself. Change the channels targeted by *Schedule Postiz post* (by integration id) if you want fewer networks.", - "height": 380, - "width": 400, - "color": 7 - }, - "id": "note-act3", - "name": "Act 3 note", - "type": "n8n-nodes-base.stickyNote", - "typeVersion": 1, - "position": [ - -560, - 800 - ] - }, - { - "parameters": { - "updates": [ - "callback_query" - ], - "additionalFields": {} - }, - "id": "tg-trigger", - "name": "Approval buttons", - "type": "n8n-nodes-base.telegramTrigger", - "typeVersion": 1.2, - "position": [ - -80, - 900 - ], - "credentials": { - "telegramApi": { - "name": "Telegram bot" - } - }, - "webhookId": "906a710d-3e76-4911-b7e6-f336e6da5d66" - }, - { - "parameters": { - "jsCode": "const cb = $json.callback_query || {};\nconst [action, jobId, clipIndex] = String(cb.data || '').split('|');\nreturn [{\n json: {\n action: action || 'skip',\n job_id: jobId || '',\n clip_index: parseInt(clipIndex || '0', 10),\n chat_id: cb.message && cb.message.chat ? cb.message.chat.id : null,\n clip_title: cb.message ? (cb.message.caption || '') : '',\n },\n}];" - }, - "id": "parse-button", - "name": "Parse button", - "type": "n8n-nodes-base.code", - "typeVersion": 2, - "position": [ - 140, - 900 - ] - }, - { - "parameters": { - "conditions": { - "options": { - "caseSensitive": true, - "typeValidation": "strict", - "version": 2 - }, - "conditions": [ - { - "id": "c2", - "leftValue": "={{ $json.action }}", - "rightValue": "pub", - "operator": { - "type": "string", - "operation": "equals" - } - } - ], - "combinator": "and" - }, - "options": {} - }, - "id": "if-approved", - "name": "Approved?", - "type": "n8n-nodes-base.if", - "typeVersion": 2.2, - "position": [ - 360, - 900 - ] - }, - { - "parameters": { - "jsCode": "// One post per day, derived from the queue the server actually holds.\n// Workflow static data was the obvious place to remember the last slot, but\n// two approvals tapped seconds apart run as two executions that both read the\n// old value and book the SAME slot. The scheduled list is shared state, so\n// counting it cannot race with itself in that way.\nconst queue = $input.first().json.scheduled_posts || [];\nconst item = $('Parse button').first().json;\nconst DAY = 24 * 60 * 60 * 1000;\nconst taken = queue\n .map((p) => Date.parse(p.scheduled_date || p.publishDate || p.date))\n .filter((t) => !Number.isNaN(t))\n .sort((a, b) => a - b);\nlet slot = Date.now() + 10 * 60 * 1000; // never schedule in the past\nfor (const t of taken) {\n if (Math.abs(t - slot) < DAY) slot = t + DAY;\n}\nreturn [{ json: { ...item, scheduled_date: new Date(slot).toISOString() } }];" - }, - "id": "reserve-slot", - "name": "Pick next free slot", - "type": "n8n-nodes-base.code", - "typeVersion": 2, - "position": [ - 800, - 840 - ] - }, - { - "parameters": { - "method": "POST", - "url": "http://localhost:8000/api/postiz/post", - "sendBody": true, - "specifyBody": "json", - "jsonBody": "={\n \"job_id\": \"{{ $json.job_id }}\",\n \"clip_index\": {{ $json.clip_index }},\n \"platforms\": [\"tiktok\", \"instagram\", \"youtube\"],\n \"scheduled_date\": \"{{ $json.scheduled_date }}\",\n \"timezone\": \"UTC\"\n}", - "options": {} - }, - "id": "social-post", - "name": "Schedule social post", - "type": "n8n-nodes-base.httpRequest", - "typeVersion": 4.2, - "position": [ - 1020, - 840 - ], - "onError": "continueErrorOutput" - }, - { - "parameters": { - "chatId": "={{ $('Parse button').first().json.chat_id }}", - "text": "=\ud83d\udcc5 Scheduled! Going out to your connected accounts on {{ $('Pick next free slot').first().json.scheduled_date.slice(0, 10) }}.", - "additionalFields": {} - }, - "id": "tg-scheduled", - "name": "Confirm: scheduled", - "type": "n8n-nodes-base.telegram", - "typeVersion": 1.2, - "position": [ - 1240, - 780 - ], - "credentials": { - "telegramApi": { - "name": "Telegram bot" - } - } - }, - { - "parameters": { - "chatId": "={{ $('Parse button').first().json.chat_id }}", - "text": "=\u26a0\ufe0f Could not schedule that clip: {{ $json.error && $json.error.message ? $json.error.message : 'posting failed' }}. Make sure your social accounts are connected in your Postiz instance and POSTIZ_URL / POSTIZ_API_KEY are set on the server.", - "additionalFields": {} - }, - "id": "tg-post-failed", - "name": "Confirm: posting failed", - "type": "n8n-nodes-base.telegram", - "typeVersion": 1.2, - "position": [ - 1240, - 900 - ], - "credentials": { - "telegramApi": { - "name": "Telegram bot" - } - } - }, - { - "parameters": { - "chatId": "={{ $('Parse button').first().json.chat_id }}", - "text": "\ud83d\uddd1 Skipped. It stays in your Clipwright dashboard if you change your mind.", - "additionalFields": {} - }, - "id": "tg-skipped", - "name": "Confirm: skipped", - "type": "n8n-nodes-base.telegram", - "typeVersion": 1.2, - "position": [ - 580, - 980 - ], - "credentials": { - "telegramApi": { - "name": "Telegram bot" - } - } - }, - { - "parameters": { - "content": "## ACT 4 \u2014 The feedback loop: learn what worked\n\nOnce a week the machine lists the channels connected in Postiz (`GET /api/postiz/integrations`) and asks for each channel's analytics over the last 7 days (`GET /api/postiz/analytics?integration=&days=7`), then sends you the totals. The analytics endpoint takes one integration id at a time, so the workflow loops over the channels the instance holds. The server needs `POSTIZ_URL` / `POSTIZ_API_KEY` (or per-request `X-Postiz-Key` headers) for these calls.\n\nThe machine that posts is the machine that measures \u2014 so every approval you make next week is informed by what actually landed.", - "height": 340, - "width": 400, - "color": 7 - }, - "id": "note-act4", - "name": "Act 4 note", - "type": "n8n-nodes-base.stickyNote", - "typeVersion": 1, - "position": [ - -560, - 1260 - ] - }, - { - "parameters": { - "rule": { - "interval": [ - { - "field": "weeks", - "triggerAtDay": [ - 0 - ], - "triggerAtHour": 18 - } - ] - } - }, - "id": "weekly-schedule", - "name": "Every Sunday 18:00", - "type": "n8n-nodes-base.scheduleTrigger", - "typeVersion": 1.2, - "position": [ - -80, - 1360 - ] - }, - { - "parameters": { - "method": "GET", - "url": "http://localhost:8000/api/postiz/integrations", - "options": {} - }, - "id": "weekly-channels", - "name": "List channels", - "type": "n8n-nodes-base.httpRequest", - "typeVersion": 4.2, - "position": [ - 200, - 1360 - ] - }, - { - "parameters": { - "fieldToSplitOut": "integrations", - "options": {} - }, - "id": "split-channels", - "name": "One item per channel", - "type": "n8n-nodes-base.splitOut", - "typeVersion": 1, - "position": [ - 360, - 1360 - ] - }, - { - "parameters": { - "method": "GET", - "url": "=http://localhost:8000/api/postiz/analytics?integration={{ $json.id }}&days=7", - "options": {} - }, - "id": "weekly-impressions", - "name": "Channel analytics", - "type": "n8n-nodes-base.httpRequest", - "typeVersion": 4.2, - "position": [ - 520, - 1360 - ] - }, - { - "parameters": { - "jsCode": "// One analytics response per connected channel (the endpoint takes a single\n// integration id, so the workflow asks once per channel).\nconst channels = $('One item per channel').all().map((i) => i.json);\nconst responses = $('Channel analytics').all().map((i) => i.json);\n\nconst metricValue = (body) => {\n const m = body.metrics || body.post_metrics || body.analytics || body;\n const v = m.views ?? m.impressions ?? m.plays ?? m.reach ?? 0;\n return Number(v) || 0;\n};\n\nlet total = 0;\nconst lines = channels.map((ch, i) => {\n const value = metricValue(responses[i] || {});\n total += value;\n const label = ch.identifier || ch.name || ch.id || `channel ${i + 1}`;\n return ` \u2022 ${label}: ${value.toLocaleString('en-US')}`;\n});\n\nlet text = `\ud83d\udcca Your week\\n\\n`;\nif (channels.length === 0) {\n text += 'No channels connected in Postiz yet. Connect one and rerun.';\n} else {\n text += `Connected channels: ${channels.length}\\n`;\n text += `Totals (last 7 days): ${total.toLocaleString('en-US')}\\n`;\n text += lines.join('\\n') + '\\n';\n}\nreturn [{ json: { digest: text } }];" - }, - "id": "write-digest", - "name": "Write the digest", - "type": "n8n-nodes-base.code", - "typeVersion": 2, - "position": [ - 580, - 1360 - ] - }, - { - "parameters": { - "chatId": "={{ $('Settings (weekly)').first().json.telegram_chat_id }}", - "text": "={{ $json.digest }}", - "additionalFields": {} - }, - "id": "tg-digest", - "name": "Send weekly digest", - "type": "n8n-nodes-base.telegram", - "typeVersion": 1.2, - "position": [ - 800, - 1360 - ], - "credentials": { - "telegramApi": { - "name": "Telegram bot" - } - } - }, - { - "parameters": { - "url": "http://localhost:8000/api/postiz/scheduled", - "options": {} - }, - "id": "read-queue", - "name": "Read publishing queue", - "type": "n8n-nodes-base.httpRequest", - "typeVersion": 4.2, - "position": [ - 580, - 840 - ] - }, - { - "parameters": { - "assignments": { - "assignments": [ - { - "id": "s0", - "name": "youtube_channel_id", - "value": "YOUR_CHANNEL_ID", - "type": "string" - }, - { - "id": "s1", - "name": "telegram_chat_id", - "value": "YOUR_TELEGRAM_CHAT_ID", - "type": "string" - } - ] - }, - "options": {} - }, - "id": "cfg-main", - "name": "Settings", - "type": "n8n-nodes-base.set", - "typeVersion": 3.4, - "position": [ - 60, - 0 - ] - }, - { - "parameters": { - "assignments": { - "assignments": [ - { - "id": "s0", - "name": "telegram_chat_id", - "value": "YOUR_TELEGRAM_CHAT_ID", - "type": "string" - } - ] - }, - "options": {}, - "includeOtherFields": true - }, - "id": "cfg-clips", - "name": "Settings (clips)", - "type": "n8n-nodes-base.set", - "typeVersion": 3.4, - "position": [ - 40, - 440 - ] - }, - { - "parameters": { - "assignments": { - "assignments": [ - { - "id": "s0", - "name": "telegram_chat_id", - "value": "YOUR_TELEGRAM_CHAT_ID", - "type": "string" - } - ] - }, - "options": {} - }, - "id": "cfg-weekly", - "name": "Settings (weekly)", - "type": "n8n-nodes-base.set", - "typeVersion": 3.4, - "position": [ - 40, - 1360 - ] - } - ], - "connections": { - "Every day 09:00": { - "main": [ - [ - { - "node": "Settings", - "type": "main", - "index": 0 - } - ] - ] - }, - "Channel RSS feed": { - "main": [ - [ - { - "node": "Pick next video", - "type": "main", - "index": 0 - } - ] - ] - }, - "Pick next video": { - "main": [ - [ - { - "node": "Start Clipwright job", - "type": "main", - "index": 0 - } - ] - ] - }, - "Start Clipwright job": { - "main": [ - [ - { - "node": "Mark video as processed", - "type": "main", - "index": 0 - } - ], - [ - { - "node": "Notify: submit failed", - "type": "main", - "index": 0 - } - ] - ] - }, - "Mark video as processed": { - "main": [ - [ - { - "node": "Notify: clipping started", - "type": "main", - "index": 0 - } - ] - ] - }, - "Clips ready (webhook)": { - "main": [ - [ - { - "node": "Settings (clips)", - "type": "main", - "index": 0 - } - ] - ] - }, - "Job completed?": { - "main": [ - [ - { - "node": "One item per clip", - "type": "main", - "index": 0 - } - ], - [ - { - "node": "Notify: job failed", - "type": "main", - "index": 0 - } - ] - ] - }, - "One item per clip": { - "main": [ - [ - { - "node": "Send clip for approval", - "type": "main", - "index": 0 - } - ] - ] - }, - "Send clip for approval": { - "main": [ - [], - [ - { - "node": "Send clip link instead", - "type": "main", - "index": 0 - } - ] - ] - }, - "Approval buttons": { - "main": [ - [ - { - "node": "Parse button", - "type": "main", - "index": 0 - } - ] - ] - }, - "Parse button": { - "main": [ - [ - { - "node": "Approved?", - "type": "main", - "index": 0 - } - ] - ] - }, - "Approved?": { - "main": [ - [ - { - "node": "Read publishing queue", - "type": "main", - "index": 0 - } - ], - [ - { - "node": "Confirm: skipped", - "type": "main", - "index": 0 - } - ] - ] - }, - "Schedule social post": { - "main": [ - [ - { - "node": "Confirm: scheduled", - "type": "main", - "index": 0 - } - ], - [ - { - "node": "Confirm: posting failed", - "type": "main", - "index": 0 - } - ] - ] - }, - "Every Sunday 18:00": { - "main": [ - [ - { - "node": "Settings (weekly)", - "type": "main", - "index": 0 - } - ] - ] - }, - "Write the digest": { - "main": [ - [ - { - "node": "Send weekly digest", - "type": "main", - "index": 0 - } - ] - ] - }, - "Read publishing queue": { - "main": [ - [ - { - "node": "Pick next free slot", - "type": "main", - "index": 0 - } - ] - ] - }, - "Pick next free slot": { - "main": [ - [ - { - "node": "Schedule social post", - "type": "main", - "index": 0 - } - ] - ] - }, - "Settings": { - "main": [ - [ - { - "node": "Channel RSS feed", - "type": "main", - "index": 0 - } - ] - ] - }, - "Settings (clips)": { - "main": [ - [ - { - "node": "Job completed?", - "type": "main", - "index": 0 - } - ] - ] - }, - "Settings (weekly)": { - "main": [ - [ - { - "node": "List channels", - "type": "main", - "index": 0 - } - ] - ] - }, - "List channels": { - "main": [ - [ - { - "node": "One item per channel", - "type": "main", - "index": 0 - } - ] - ] - }, - "One item per channel": { - "main": [ - [ - { - "node": "Channel analytics", - "type": "main", - "index": 0 - } - ] - ] - }, - "Channel analytics": { - "main": [ - [ - { - "node": "Write the digest", - "type": "main", - "index": 0 - } - ] - ] - } - }, - "settings": { - "executionOrder": "v1" - }, - "pinData": {} -} diff --git a/ops/README.md b/ops/README.md deleted file mode 100644 index 425e0de..0000000 --- a/ops/README.md +++ /dev/null @@ -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://.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. diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..ba47db1 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,30 @@ +# The backend is not packaged or published: it runs from a bind-mounted source +# tree (docker-compose.yml) and `requirements.txt` is the single runtime +# dependency source for the Docker image. This file therefore carries tool +# configuration only — no [build-system] and no [project] table — which also +# avoids colliding with the published `clipwright` CLI distribution under +# `cli/`. + +[tool.pytest.ini_options] +minversion = "7.0" +testpaths = ["tests"] +# Makes the repo-root `clipwright/` package importable without a sys.path hack +# in tests/conftest.py. +pythonpath = ["."] + +[tool.ruff] +line-length = 100 +target-version = "py311" +extend-exclude = [ + "dashboard", + "render-service", + "remotion", + "cli", + "output", + "uploads", +] + +[tool.ruff.lint] +# Correctness only for now: keep this migration reviewable. Style/import rules +# can be ratcheted later without conflicting with the structural change. +select = ["E4", "E7", "E9", "F"] diff --git a/remotion/src/compositions/HookOverlay.tsx b/remotion/src/compositions/HookOverlay.tsx index 061c806..961bb5c 100644 --- a/remotion/src/compositions/HookOverlay.tsx +++ b/remotion/src/compositions/HookOverlay.tsx @@ -26,7 +26,7 @@ const POSITION_STYLE: Record = { bottom: { top: "68%", bottom: "auto" }, }; -// Must mirror hooks.py HOOK_STYLES so preview == burned output. +// Must mirror clipwright/media/hooks.py HOOK_STYLES so preview == burned output. interface HookLook { box: string | null; text: string; @@ -126,7 +126,7 @@ const HookBox: React.FC = ({ config, displayFrames }) => { const positionStyle = POSITION_STYLE[config.position] ?? POSITION_STYLE.top; const look = HOOK_LOOKS[config.style ?? "classic"] ?? HOOK_LOOKS.classic; - // Base font size: 5% of 1080 width (matches hooks.py logic) + // Base font size: 5% of 1080 width (matches clipwright/media/hooks.py logic) const baseFontSize = 1080 * 0.05; const fontSize = Math.round(baseFontSize * scale); diff --git a/requirements-test.txt b/requirements-test.txt new file mode 100644 index 0000000..3a452c3 --- /dev/null +++ b/requirements-test.txt @@ -0,0 +1,14 @@ +# Thin test environment: everything the collected tests import at module level, +# WITHOUT the heavy ML stack (torch/ultralytics/mediapipe/faster-whisper). The +# pipeline modules import those lazily behind their feature gates, and the tests +# exercise the gated-off paths. +pytest +pillow +httpx +pydantic +numpy +opencv-python-headless +python-dotenv +google-genai +fastapi +python-multipart diff --git a/skills/clipwright/.claude-plugin/plugin.json b/skills/clipwright/.claude-plugin/plugin.json deleted file mode 100644 index 994bf6f..0000000 --- a/skills/clipwright/.claude-plugin/plugin.json +++ /dev/null @@ -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": [ - "." - ] -} diff --git a/skills/clipwright/README.md b/skills/clipwright/README.md deleted file mode 100644 index e296917..0000000 --- a/skills/clipwright/README.md +++ /dev/null @@ -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 /`. - -**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. diff --git a/skills/clipwright/SKILL.md b/skills/clipwright/SKILL.md deleted file mode 100644 index d8de70e..0000000 --- a/skills/clipwright/SKILL.md +++ /dev/null @@ -1,108 +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=` = 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: `GET /api/postiz/integrations` first, then `POST /api/postiz/post` - with `{"job_id", "clip_index", "integration_ids": ["", ...]}`, optional - `title`, `description`, `scheduled_date` (ISO) + `timezone`. Prefer the exact - integration ids: several channels of the same network are distinct (multiple - YouTube channels, `instagram-standalone`), so you pick the channel, not the - network; the legacy `platforms` list is a fallback. 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 channels 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. diff --git a/skills/clipwright/reference.md b/skills/clipwright/reference.md deleted file mode 100644 index 1cd7887..0000000 --- a/skills/clipwright/reference.md +++ /dev/null @@ -1,156 +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=`. 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, - "integration_ids": ["", ""], - "title": "...", "description": "...", - "scheduled_date": "2026-08-25T18:00:00Z", "timezone": "Europe/Madrid" } -``` - -Prefer `integration_ids`: the exact channels to publish to, taken from -`GET /api/postiz/integrations` (each entry has `id`, `name`, `identifier`, -`disabled`). Several channels of the same network are distinct entries — Postiz -lists Instagram as `instagram-standalone` and YouTube once per channel — so pick -the channel, not the network. The legacy `platforms` list -(`["tiktok", "instagram", "youtube"]`) still works as a fallback that picks the -first enabled match per platform. - -Omit `scheduled_date` to post now; with one, the resolved instant must be in the -future. The backend uploads the clip bytes to your self-hosted Postiz instance -and creates the post there, keyed by each integration's real identifier. The -dashboard's publish modal takes the date as **DD/MM/YYYY** and sends the ISO -instant. - -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`. diff --git a/tests/conftest.py b/tests/conftest.py index b551e8a..0a79c82 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,5 +1,7 @@ -import os -import sys +"""Shared pytest configuration. -# Make the repo root importable so tests can import the app modules directly. -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +The repo-root ``clipwright/`` package is made importable by +``[tool.pytest.ini_options] pythonpath = ["."]`` in the root ``pyproject.toml``, +so no manual ``sys.path`` manipulation is needed here. This module is kept for +future shared fixtures. +""" diff --git a/tests/test_active_speaker.py b/tests/test_active_speaker.py index 044a209..895b4c3 100644 --- a/tests/test_active_speaker.py +++ b/tests/test_active_speaker.py @@ -1,4 +1,4 @@ -from active_speaker import ( +from clipwright.layouts.active_speaker import ( attribute_windows, hold, is_conversation, diff --git a/tests/test_ai_disclosure.py b/tests/test_ai_disclosure.py index 9d3b1b3..ca535f7 100644 --- a/tests/test_ai_disclosure.py +++ b/tests/test_ai_disclosure.py @@ -13,7 +13,7 @@ import os import pytest Image = pytest.importorskip("PIL.Image") -thumbnail = pytest.importorskip("thumbnail") +thumbnail = pytest.importorskip("clipwright.media.thumbnail") TRAINED = b"trainedAlgorithmicMedia" diff --git a/tests/test_audit_hardening.py b/tests/test_audit_hardening.py index 24322bc..629b28f 100644 --- a/tests/test_audit_hardening.py +++ b/tests/test_audit_hardening.py @@ -14,7 +14,9 @@ import os import httpx import pytest -app_module = pytest.importorskip("app") +app_module = pytest.importorskip("clipwright.api.app") + +from clipwright.core import security_utils # noqa: E402 def _client_call(method, path, **kw): @@ -105,7 +107,7 @@ def test_youtube_search_page_is_refused_before_any_probe(dirs, monkeypatch): probed.append(u) return {} monkeypatch.setattr(app_module, "_probe_youtube_quality", _probe) - monkeypatch.setattr("security_utils.assert_public_url", lambda u: u) + monkeypatch.setattr(security_utils, "assert_public_url", lambda u: u) resp = _post_process({"url": "https://www.youtube.com/results?search_query=x", "acknowledged": True}) assert resp.status_code == 400 @@ -194,29 +196,51 @@ def test_child_env_drops_server_secrets(monkeypatch): def test_pipeline_code_reads_none_of_the_dropped_secrets(): - """If main.py (or anything it imports) ever needs one of these, the + """If the pipeline (or anything it imports) ever needs one of these, the denylist would silently break jobs: fail here instead.""" import ast - root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - local = {f[:-3] for f in os.listdir(root) if f.endswith(".py")} - seen, stack = set(), ["main", "quality_probe"] + from pathlib import Path + + root = Path(__file__).resolve().parents[1] + package = root / "clipwright" + # Every importable module name -> its source file, e.g. + # ``clipwright.media.subtitles`` -> clipwright/media/subtitles.py. + sources = {} + for path in package.rglob("*.py"): + parts = list(path.relative_to(root).with_suffix("").parts) + if parts[-1] == "__init__": + parts = parts[:-1] + sources[".".join(parts)] = path + + seen, stack = set(), ["clipwright.pipeline.main", "clipwright.pipeline.quality_probe"] while stack: mod = stack.pop() - if mod in seen: + if mod in seen or mod not in sources: continue seen.add(mod) - src = open(os.path.join(root, mod + ".py"), encoding="utf-8").read() + src = sources[mod].read_text(encoding="utf-8") for name in app_module.CHILD_ENV_DENYLIST: assert f'"{name}"' not in src and f"'{name}'" not in src, (mod, name) for node in ast.walk(ast.parse(src)): - names = [] if isinstance(node, ast.Import): - names = [a.name.split(".")[0] for a in node.names] - elif isinstance(node, ast.ImportFrom) and node.module: - names = [node.module.split(".")[0]] - for n in names: - if n in local: - stack.append(n) + targets = [a.name for a in node.names] + elif isinstance(node, ast.ImportFrom): + if node.level: + base = mod.split(".")[:-1] + base = base[: len(base) - (node.level - 1)] + prefix = ".".join(base) + base_mod = f"{prefix}.{node.module}" if node.module else prefix + else: + base_mod = node.module or "" + if node.module: + targets = [base_mod] + [f"{base_mod}.{a.name}" for a in node.names] + else: + targets = [f"{base_mod}.{a.name}" for a in node.names] + else: + continue + for target in targets: + if target in sources: + stack.append(target) def test_job_env_has_no_server_secrets(dirs, calls, monkeypatch): @@ -240,7 +264,7 @@ import subprocess class TestSafetyCap: @pytest.fixture() def source(self, tmp_path): - main = pytest.importorskip("main") + main = pytest.importorskip("clipwright.pipeline.main") path = tmp_path / "src.mp4" subprocess.run([ "ffmpeg", "-y", "-loglevel", "error", diff --git a/tests/test_auto_retry.py b/tests/test_auto_retry.py index 3b22c4e..5309adf 100644 --- a/tests/test_auto_retry.py +++ b/tests/test_auto_retry.py @@ -9,7 +9,7 @@ import json import pytest -app_module = pytest.importorskip("app") +app_module = pytest.importorskip("clipwright.api.app") @pytest.fixture diff --git a/tests/test_camera_inset.py b/tests/test_camera_inset.py index 7b22318..479e9c0 100644 --- a/tests/test_camera_inset.py +++ b/tests/test_camera_inset.py @@ -1,4 +1,4 @@ -from camera_inset import ( +from clipwright.layouts.camera_inset import ( INSET_ASPECT, inset_box, inset_filtergraph, diff --git a/tests/test_caption_presets.py b/tests/test_caption_presets.py index bf6c5dc..cd446d4 100644 --- a/tests/test_caption_presets.py +++ b/tests/test_caption_presets.py @@ -2,7 +2,7 @@ import asyncio import re -from subtitles import AUTO_CAPTION_STYLE, CAPTION_PRESETS, line_budget +from clipwright.media.subtitles import AUTO_CAPTION_STYLE, CAPTION_PRESETS, line_budget def test_dashboard_offers_every_server_preset(): @@ -28,14 +28,14 @@ def test_line_budget_shrinks_with_size_and_wide_fonts(): def test_unknown_preset_is_a_400(): import pytest from fastapi import HTTPException - from app import SubtitleRequest, add_subtitles + from clipwright.api.app import SubtitleRequest, add_subtitles with pytest.raises(HTTPException) as exc: asyncio.run(add_subtitles(SubtitleRequest(job_id="j", clip_index=0, preset="nope"), None)) assert exc.value.status_code == 400 def test_preset_fills_only_fields_not_sent(): - from app import SubtitleRequest + from clipwright.api.app import SubtitleRequest req = SubtitleRequest(job_id="j", clip_index=0, preset="hormozi", highlight_color="#00FF00") merged = req.model_copy(update={k: v for k, v in CAPTION_PRESETS["hormozi"].items() if k not in req.model_fields_set}) diff --git a/tests/test_cleanup_live_jobs.py b/tests/test_cleanup_live_jobs.py index 2f496e9..e0696a1 100644 --- a/tests/test_cleanup_live_jobs.py +++ b/tests/test_cleanup_live_jobs.py @@ -9,7 +9,7 @@ import time import pytest -app_module = pytest.importorskip("app") +app_module = pytest.importorskip("clipwright.api.app") OLD = 2 * 3600 # older than the 1 h JOB_RETENTION_SECONDS the fixture sets diff --git a/tests/test_clip_floor.py b/tests/test_clip_floor.py index 4dde4cf..8f28986 100644 --- a/tests/test_clip_floor.py +++ b/tests/test_clip_floor.py @@ -9,7 +9,7 @@ import json import pytest -main = pytest.importorskip("main") +main = pytest.importorskip("clipwright.pipeline.main") def _transcript(n_segments=40): diff --git a/tests/test_clip_ready_marker.py b/tests/test_clip_ready_marker.py index 2c63912..62bc3ca 100644 --- a/tests/test_clip_ready_marker.py +++ b/tests/test_clip_ready_marker.py @@ -10,10 +10,13 @@ main.py now announces each clip once its whole chain is done and names the file to serve; app.py consumes the marker the way it already consumes PROXY_BYTES. """ import io +from pathlib import Path import pytest -app = pytest.importorskip("app") +app = pytest.importorskip("clipwright.api.app") + +MAIN_PY = Path(__file__).resolve().parents[1] / "clipwright" / "pipeline" / "main.py" def _feed(job_id, *lines): @@ -69,7 +72,7 @@ class TestMainAnnouncesTheDeliveredFile: Announcing the pre-caption path would put the poller back on a file the pipeline is about to supersede, which is the bug this fixes. """ - main_src = open("main.py", encoding="utf-8").read() + main_src = MAIN_PY.read_text(encoding="utf-8") caption_at = main_src.index("captioned = auto_caption_clip(") # The free plan's served file is a wm_ copy of the captioned final # (mark_delivery), so the marker must also come after that step. diff --git a/tests/test_clip_render_order.py b/tests/test_clip_render_order.py index b660f53..73e1872 100644 --- a/tests/test_clip_render_order.py +++ b/tests/test_clip_render_order.py @@ -1,7 +1,7 @@ """The strongest clip renders first, so it is the first one the user sees.""" import pytest -main = pytest.importorskip("main") +main = pytest.importorskip("clipwright.pipeline.main") def test_best_score_first(): diff --git a/tests/test_clip_selection.py b/tests/test_clip_selection.py index c546ba4..c984b58 100644 --- a/tests/test_clip_selection.py +++ b/tests/test_clip_selection.py @@ -3,7 +3,7 @@ import re import pytest -from clip_selection import ( +from clipwright.pipeline.clip_selection import ( build_transcript_windows, clip_count_targets, dedupe_overlapping, @@ -157,7 +157,7 @@ class TestClipCountTargets: class TestDetailPromptCarriesTheCount: def test_template_formats_with_the_targets(self): - gw = pytest.importorskip("gemini_worker") + gw = pytest.importorskip("clipwright.pipeline.gemini_worker") low, high = clip_count_targets(5) prompt = gw.DETAIL_PROMPT_TEMPLATE.format( video_duration=300, language="es", min_clips=low, max_clips=high, diff --git a/tests/test_deploy_drain.py b/tests/test_deploy_drain.py index d3c63c7..e22e16b 100644 --- a/tests/test_deploy_drain.py +++ b/tests/test_deploy_drain.py @@ -13,7 +13,7 @@ import time import httpx import pytest -app_module = pytest.importorskip("app") +app_module = pytest.importorskip("clipwright.api.app") @pytest.fixture diff --git a/tests/test_download_plan.py b/tests/test_download_plan.py index 84f6b63..74ccfe2 100644 --- a/tests/test_download_plan.py +++ b/tests/test_download_plan.py @@ -7,7 +7,7 @@ bytes) -> per-GB paid proxy (720p cost cap) -> conservative fallback. The """ import pytest -main = pytest.importorskip("main") +main = pytest.importorskip("clipwright.pipeline.main") plan = main.plan_download_attempts diff --git a/tests/test_edit_builder.py b/tests/test_edit_builder.py index d24a1c1..0209ec9 100644 --- a/tests/test_edit_builder.py +++ b/tests/test_edit_builder.py @@ -1,6 +1,6 @@ import pytest -from edit_builder import EFFECT_LIMITS, build_filter_string, normalize_edits +from clipwright.media.edit_builder import EFFECT_LIMITS, build_filter_string, normalize_edits def _edit(type_, start, end, strength=0.0): diff --git a/tests/test_ffmpeg_utils.py b/tests/test_ffmpeg_utils.py index c8eb41f..be2c4d4 100644 --- a/tests/test_ffmpeg_utils.py +++ b/tests/test_ffmpeg_utils.py @@ -2,8 +2,8 @@ import subprocess import pytest -import ffmpeg_utils -from ffmpeg_utils import ( +from clipwright.media import ffmpeg_utils +from clipwright.media.ffmpeg_utils import ( AI_DISCLOSURE, DELIVERY, METADATA_SCRUB, diff --git a/tests/test_filename_limits.py b/tests/test_filename_limits.py index 399d280..a006940 100644 --- a/tests/test_filename_limits.py +++ b/tests/test_filename_limits.py @@ -6,8 +6,8 @@ already being ~300 bytes, and the derived temp name pushed it further. """ import pytest -main = pytest.importorskip("main") # cv2 etc., absent in minimal CI -hooks = pytest.importorskip("hooks") +main = pytest.importorskip("clipwright.pipeline.main") # cv2 etc., absent in minimal CI +hooks = pytest.importorskip("clipwright.media.hooks") # ext4/APFS cap a single name at 255 bytes. FS_LIMIT = 255 diff --git a/tests/test_frame_sampler.py b/tests/test_frame_sampler.py index 658d55c..a963870 100644 --- a/tests/test_frame_sampler.py +++ b/tests/test_frame_sampler.py @@ -2,7 +2,7 @@ import cv2 import numpy as np import pytest -import frame_sampler +from clipwright.media import frame_sampler N_FRAMES = 60 diff --git a/tests/test_free_tools.py b/tests/test_free_tools.py index 70819d7..508a4e6 100644 --- a/tests/test_free_tools.py +++ b/tests/test_free_tools.py @@ -10,7 +10,7 @@ import pytest from fastapi import FastAPI from fastapi.testclient import TestClient -import free_tools as ft +from clipwright.api import free_tools as ft class TestExtractVideoId: diff --git a/tests/test_gemini_block_split.py b/tests/test_gemini_block_split.py index 7eded77..fab23a6 100644 --- a/tests/test_gemini_block_split.py +++ b/tests/test_gemini_block_split.py @@ -1,7 +1,7 @@ """A policy block on a batch of windows must bisect, not kill the job.""" import pytest -main = pytest.importorskip("main") -import gemini_worker +main = pytest.importorskip("clipwright.pipeline.main") +from clipwright.pipeline import gemini_worker def _windows(n): diff --git a/tests/test_gemini_retry.py b/tests/test_gemini_retry.py index 130ca1f..05a5383 100644 --- a/tests/test_gemini_retry.py +++ b/tests/test_gemini_retry.py @@ -9,7 +9,7 @@ import pytest # main pulls in cv2/torch/mediapipe at import time; the minimal CI env lacks # them, so skip there. Runs fully in the container/local where deps exist. -main = pytest.importorskip("main") +main = pytest.importorskip("clipwright.pipeline.main") class _FakeResponse: @@ -112,7 +112,7 @@ def test_policy_block_fails_fast_without_retrying(): _Models.calls += 1 return _BlockedResponse() - import gemini_worker + from clipwright.pipeline import gemini_worker with pytest.raises(gemini_worker.GeminiBlockedError) as exc: main._run_gemini_stage(_client(_Models()), "m", "prompt", object) assert _Models.calls == 1 @@ -120,7 +120,7 @@ def test_policy_block_fails_fast_without_retrying(): def test_blocked_finish_reason_also_raises(): - import gemini_worker + from clipwright.pipeline import gemini_worker class _Cand: class _FR: @@ -137,7 +137,7 @@ def test_blocked_finish_reason_also_raises(): def test_clean_response_is_not_flagged_as_blocked(): - import gemini_worker + from clipwright.pipeline import gemini_worker class _Resp: prompt_feedback = None diff --git a/tests/test_gemini_upload_unicode_name.py b/tests/test_gemini_upload_unicode_name.py index 7908dda..3c2758f 100644 --- a/tests/test_gemini_upload_unicode_name.py +++ b/tests/test_gemini_upload_unicode_name.py @@ -12,7 +12,7 @@ import io import httpx import pytest -import gemini_worker +from clipwright.pipeline import gemini_worker def _prepared_headers(file_arg, mime_type=None): @@ -77,7 +77,12 @@ def test_every_whole_file_upload_goes_through_the_helper(): import re root = pathlib.Path(__file__).resolve().parent.parent offenders = [] - for name in ("main.py", "editor.py", "screencast_layout.py", "thumbnail.py"): + for name in ( + "clipwright/pipeline/main.py", + "clipwright/media/editor.py", + "clipwright/layouts/screencast_layout.py", + "clipwright/media/thumbnail.py", + ): src = (root / name).read_text() if re.search(r"\.files\.upload\(", src): offenders.append(name) diff --git a/tests/test_generation_controls.py b/tests/test_generation_controls.py index 6ec4e5e..c30dabe 100644 --- a/tests/test_generation_controls.py +++ b/tests/test_generation_controls.py @@ -9,7 +9,7 @@ import os import pytest -import clip_selection +from clipwright.pipeline import clip_selection @pytest.fixture(autouse=True) @@ -49,6 +49,7 @@ def _templates(): """The prompt template constants, read without importing gemini_worker (which pulls google-genai — absent in the thin CI env).""" mod = ast.parse(open(os.path.join(os.path.dirname(__file__), "..", + "clipwright", "pipeline", "gemini_worker.py")).read()) return { node.targets[0].id: node.value.value diff --git a/tests/test_hook_grounding.py b/tests/test_hook_grounding.py index 31dccb7..cc79bfd 100644 --- a/tests/test_hook_grounding.py +++ b/tests/test_hook_grounding.py @@ -7,8 +7,8 @@ detail pass only ever reads the transcript. """ import pytest -import gemini_worker -import hook_grounding as hg +from clipwright.pipeline import gemini_worker +from clipwright.pipeline import hook_grounding as hg SCREEN = [{"start": 0, "end": 30, "layout": "screencast"}] diff --git a/tests/test_hook_layers.py b/tests/test_hook_layers.py index f7dc377..9e957fd 100644 --- a/tests/test_hook_layers.py +++ b/tests/test_hook_layers.py @@ -10,7 +10,7 @@ import time import pytest -app_module = pytest.importorskip("app") +app_module = pytest.importorskip("clipwright.api.app") _strip_burned_captions = app_module._strip_burned_captions _strip_burned_hook = app_module._strip_burned_hook diff --git a/tests/test_hooks.py b/tests/test_hooks.py index b41c607..dad4321 100644 --- a/tests/test_hooks.py +++ b/tests/test_hooks.py @@ -4,7 +4,7 @@ import os from PIL import Image, ImageDraw, ImageFont -from hooks import ( +from clipwright.media.hooks import ( HOOK_STYLES, _break_long_word, _emoji_scale, @@ -135,7 +135,7 @@ class TestCreateHookImage: def test_pill_hook_image_stacks_one_box_per_line(tmp_path): """Two lines of text -> two rows of box pixels with a boxless column beside the shorter one (it is its own pill, not one shared card).""" - from hooks import create_hook_image + from clipwright.media.hooks import create_hook_image from PIL import Image out = tmp_path / "pill.png" path, w, h = create_hook_image("una frase bastante larga para partirse en dos lineas", diff --git a/tests/test_layout_picker.py b/tests/test_layout_picker.py index 845b224..b419fc5 100644 --- a/tests/test_layout_picker.py +++ b/tests/test_layout_picker.py @@ -1,18 +1,30 @@ import sys import types -import layout_picker -from layout_picker import _module_flags, apply, pick +from clipwright import layouts +from clipwright.layouts import layout_picker +from clipwright.layouts.layout_picker import _module_flags, apply, pick + +# Decision labels are bare layout names; the modules they switch on live in the +# ``clipwright.layouts`` package and are imported lazily by apply(). +_FAKE_LAYOUT_MODULES = { + "split_layout": "clipwright.layouts.split_layout", + "screencast_layout": "clipwright.layouts.screencast_layout", + "active_speaker": "clipwright.layouts.active_speaker", +} def fake_modules(monkeypatch, **initial): """Install stand-in layout modules so apply() can be tested without them.""" made = {} - for name in ("split_layout", "screencast_layout", "active_speaker"): - module = types.ModuleType(name) - module.ENABLED = initial.get(name, False) - monkeypatch.setitem(sys.modules, name, module) - made[name] = module + for label, dotted in _FAKE_LAYOUT_MODULES.items(): + module = types.ModuleType(dotted) + module.ENABLED = initial.get(label, False) + monkeypatch.setitem(sys.modules, dotted, module) + # apply() does ``from clipwright.layouts import