refactor: self-hosted fork — Postiz publishing, drop AI Shorts/UGC/agent/autopilot/MCP, fix Studio image API, remove upload cap

- Replace Upload-Post with a self-hosted Postiz client (postiz.py) and /api/postiz/* endpoints
- Remove AI Shorts, UGC gallery, AI Agent tab, Autopilot, MCP/agent layer, and their UIs
- Fix YouTube Studio thumbnail generation (google-genai >=2 Interactions API) and blocking download
- Make the video upload size cap configurable/unlimited (MAX_FILE_SIZE_MB, default 0)
- Update SEO/marketing/docs to the single-product self-hosted reality; lint+build green
This commit is contained in:
pedro-bento 2026-10-04 16:30:44 +01:00
parent 06a119c280
commit fbabb4ec5d
62 changed files with 4268 additions and 9413 deletions

View file

@ -1,4 +1,4 @@
# AWS S3 (optional — for clip backup/gallery)
# AWS S3 (optional — for clip backup)
AWS_ACCESS_KEY_ID=your_aws_access_key_here
AWS_SECRET_ACCESS_KEY=your_aws_secret_key_here
AWS_REGION=eu-west-3
@ -85,24 +85,40 @@ GEMINI_IMAGE_MODEL=gemini-3.1-flash-image
# MEDIA_TOKEN_TTL_SECONDS: life of the per-user token the dashboard appends to
# <video src> / <img src> URLs (default 43200 = 12 h).
# MEDIA_URL_TTL_SECONDS: life of the path-signed capability handed to consumers
# that cannot send a header — webhook payloads and MCP tool results
# that cannot send a header — webhook payloads
# (default 86400 = 24 h).
# MEDIA_TOKEN_TTL_SECONDS=43200
# MEDIA_URL_TTL_SECONDS=86400
# Retention for the two kinds of file that had none. Thumbnails and the frames
# sampled to make them are close-ups of a real person; the clock runs from the
# last download. Uploaded actor photos die with the job that used them.
# Retention for thumbnails. Thumbnails and the frames sampled to make them are
# close-ups of a real person; the clock runs from the last download.
# THUMBNAIL_RETENTION_SECONDS=86400
# ACTOR_UPLOAD_RETENTION_SECONDS=3600
# Per-IP rate limiting (rate_limit.py). "<max requests>/<window seconds>".
# Defaults: auth 30/600, process 60/3600, mcp 240/60. Set RATE_LIMIT_ENABLED=0
# Defaults: auth 30/600, process 60/3600. Set RATE_LIMIT_ENABLED=0
# to turn the whole thing off (self-host behind your own firewall).
# RATE_LIMIT_ENABLED=1
# RATE_LIMIT_AUTH=30/600
# RATE_LIMIT_PROCESS=60/3600
# RATE_LIMIT_MCP=240/60
# ---------------------------------------------------------------------------
# Publishing (self-hosted Postiz)
# ---------------------------------------------------------------------------
# Base URL of your self-hosted Postiz instance (no trailing slash) and the API
# key used server-side when the dashboard does not send the user's own
# X-Postiz-Url / X-Postiz-Key headers. Postiz holds the social platform tokens;
# OpenShorts only uploads clip bytes to it.
# POSTIZ_URL=https://postiz.pbento.pt
# POSTIZ_API_KEY=your_postiz_api_key
# ---------------------------------------------------------------------------
# Upload size
# ---------------------------------------------------------------------------
# Maximum upload size in MB. 0 (the default) means unlimited. Set a positive
# number to cap uploads and reject larger files with HTTP 413.
# MAX_FILE_SIZE_MB=0
# Which hop may declare the client's address in X-Forwarded-For. The Dockerfile
# defaults to the private Docker ranges; narrow it to Traefik's own address on

263
CLAUDE.md
View file

@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Project Overview
OpenShorts is an AI-powered vertical video generator that transforms long YouTube videos or local uploads into viral-ready short clips (9:16 format) for TikTok, Instagram Reels, and YouTube Shorts. Uses Google Gemini 3.1 Flash-Lite (`gemini-3.1-flash-lite`, overridable with `GEMINI_MODEL`) for viral moment detection and title generation.
OpenShorts 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
@ -43,7 +43,7 @@ uvicorn app:app --host 0.0.0.0 --port 8000
8. **Hook Overlay** - Text overlays with styled fonts
9. **Voice Dubbing** - Optional ElevenLabs AI translation (30+ languages)
10. **S3 Backup** - Silent background upload
11. **Social Distribution** - Upload-Post API (async upload)
11. **Social Distribution** - Self-hosted Postiz (clip uploaded, then scheduled or posted)
### Key Files
| File | Purpose |
@ -71,7 +71,7 @@ homepage as zero characters of text. `vite-plugin-seo.js` fixes that at build ti
`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, use-case and automation pages, and `/mcp`; the full list is
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
@ -95,8 +95,8 @@ answers describe the paid product as free.
`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) and `seo/autopilot-pages.js`
(`/auto-clip`, `/youtube-automation`). A tool page carries `tool: {entry, html}`:
- 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
@ -163,131 +163,12 @@ 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.
### The quota wall offers the first N minutes (`app.partial_offer`)
The wall (`TopUpModal`, context `wall`) opens on a 402 from `/api/process`.
Measured on 16-sep-2026, 93 of 99 walls were shown to accounts with their
20 free minutes **untouched** that had pasted a 21-90 min video: the user was
asked for $12 before seeing one clip, and 41 of the 68 subscriptions Stripe
created in 30 days expired unpaid, none of them a card decline. So the 402
now carries `partial_minutes` (the floored balance, when it is at least
`PARTIAL_MIN_MINUTES` and shorter than the source), the wall shows "clip the
first N min" next to the plans, and the dashboard resubmits the same job with
`max_minutes=N`. `reserve_process_minutes` then reserves N (never more than
the balance, whatever the client asks) and sets `MAX_SOURCE_MINUTES` for
`main.py`, whose `cap_source_duration` cuts the downloaded/uploaded file **in
place** before anything reads it, so transcription, the layout picker, the
editor and `/api/source` all see a short video. The cut travels in the
resume manifest: a resumed job downloads the source again and would
otherwise process 45 minutes on a 20-minute reservation. `/api/status` and
the process response carry `partial`, and the results view says which part
of the video the clips came from, with the upsell for the rest.
### The free plan's watermark is a copy, and paying removes it (`watermarked.py`)
Every file the pipeline and the clip editor write is clean. On the free plan
the file that is *served* is `wm_<final>`, a copy of the final file with the
mark burned in (`main.mark_delivery`, the last step after captions; the
editor endpoints get it from `app._deliver`, decided from the caller's plan
right now, not from the job's flag, which a restart loses). Both twins live
on disk and in R2 (`cloud.videos._twins_to_archive`). Before 30-sep-2026 the
mark was burned into the canonical reframe, so every derivative inherited it
and the upgrade modal's "upgrade to remove the watermark" was false for the
clips already made: the first cancellation for "clip quality" was a user who
paid 15 minutes after their first job and kept the mark on every download.
- **Upgrade**: `cloud/billing._upsert_subscription` fires
`videos.unmark_user_library` on the free→live transition
(`became_live`). Per clip it checks the clean twin exists in R2, moves the
history row and the project state to it, deletes the marked object and
calls back into `app._unmark_local_job` so an open dashboard polls the
clean URL. No render, no source video. The dashboard chases the job
result after the plan flips (`App.jsx`, the `wm_` regex) and refreshes
the durable map.
- **Walk-backs**: `wm_` is the outermost layer; `_strip_burned_captions` /
`_strip_burned_hook` drop it first, `_canonical_clip_file` globs
`wm_*{clean}`.
- **`/videos` guard** (`app._media_guard`): a job rendered for the free plan
carries a `.marked` dotfile (`watermarked.MARKER_FILE`, written by
main.py, restored with the project, removed on unmark; `_deliver` marks
only jobs that carry it, so a job from before this scheme, whose canonical
has the mark burned in, never gets a second one);
while it exists the clean deliverables of that job are refused, so the
twin cannot be fetched by stripping the prefix off a URL. The editor's
`temp_*` scratch files and the caption sidecars stay servable.
- **Notice**: `WatermarkModal` shows once per job when the clips land on a
free account (`source=results`, 2.5 s after the grid) and, if skipped,
before the first download; tracked as `WatermarkNoticeSeen` /
`WatermarkNoticeUpgrade` with `source`. Its Upgrade opens the upsell
`TopUpModal`.
### Free sources past the balance never meet the wall (`app.free_overflow`)
Since 28-sep-2026 the wall above only shows to paid plans and to free
accounts with less than `PARTIAL_MIN_MINUTES` left. For a free account whose
source is longer than its balance, `reserve_process_minutes` decides on its
own (the client sends no `max_minutes`):
- **First video, up to `FIRST_VIDEO_MAX_MINUTES` (60):** clipped whole. Only
the floored balance is reserved (it lands at zero) and the download's safety
cap (`SOURCE_CAP_MINUTES`) is the probed length, not the reservation. Once
per account: `metering.has_processed_before` (any reserved/committed
`process` row; a released one keeps the grant for the retry), and once per
client IP every `FIRST_VIDEO_IP_WINDOW_DAYS` (30): `first_video_grants`
holds an HMAC of the IP (never the IP), is not tied to the user row so an
account deletion does not reset it, and only counts grants whose job
reservation is live. A blocked network gets the first-N-minutes cut. The response
carries `first_video: true`; the dashboard says so and tracks
`FirstVideoGrant`.
- **Anything else:** `max_minutes` becomes the balance, so the job clips the
first N minutes exactly as if the user had taken the wall's offer. Tracked
client-side as `AutoPartial`.
### Lifecycle emails (`cloud/lifecycle.py`)
Welcome (minutes after sign-up), first-clip nudge (24-72 h, nothing
processed), win-back (2-7 days after the first committed video, no plan; with
`WINBACK_PROMO_CODE` when set) and checkout recovery (`checkout.session.expired`
with the `after_expiration.recovery` URL that `create_checkout` now enables).
Each at most once per account: a `lifecycle_emails` row is claimed before the
send (unique `user_id, kind`). The loop sends at most `BATCH` per 10-minute
tick. All four are commercial: `emails.send_commercial_email` skips
`marketing_opt_out` accounts and adds the unsubscribe footer and
`List-Unsubscribe` headers (the out-of-minutes upsell goes through it too).
The Stripe webhook endpoint must have `checkout.session.expired` enabled.
Promotion codes and coupon ids live in the env / Stripe, never in this repo.
### Cancel flow (`cloud/cancellation.py`, `CancelPlanModal.jsx`)
Account → "Cancel subscription" opens three steps: reason (closed list,
`CANCEL_REASONS`, plus an optional detail box), a 1-5 rating with an optional
review (and an "OK to quote publicly" box), then confirm.
`POST /api/billing/cancel` sets `cancel_at_period_end` in Stripe with
`cancellation_details` (our reason mapped to Stripe's feedback enum), and only
after Stripe accepts writes a `cancellation_feedback` row (user-owned, erased
with the account) and flips the local row, so the webhook sees no transition
and the generic churn alert does not fire twice. The alert names the reason and
rating, never the written text (Telegram, see `alerts.user_ref`): read reviews
in the table.
The last step leads with a retention offer (`RETENTION_COUPON_ID` env, the
coupon the portal used to offer): `GET /api/billing/retention-offer` says
whether this subscription gets it (live monthly plan, no discount on it, never
offered before: `retention_offer` in the Stripe subscription metadata; any
Stripe error means no offer), `POST /api/billing/retention-offer/accept` applies
it and stores the feedback row with `outcome="retained"` (cancels store
`"canceled"`). Cancelling is OFF in the Stripe portal config since 2026-09-28,
so this flow is the only way to cancel; `POST /api/billing/resume` undoes a
scheduled cancel ("Keep my subscription" on the account page), since the
portal's renew went with its cancel feature. The webhook alert for a portal
cancel stays for cancels made from the Stripe Dashboard.
### Sign-up survey (`cloud/onboarding.py`, `OnboardingSurvey.jsx`)
`signup_attribution` says which page a user came from, not why. Accounts
younger than 7 days get one skippable screen before the clip tutorial (never
over a running job): what they want to make (multi-select: clips, AI avatar /
UGC videos, autopilot, thumbnails...), how they heard of us, and who they are.
over a running job): what they want to make (multi-select: clip long videos
into shorts, publish to my socials, thumbnails...), how they heard of us, and who they are.
Closed lists mirrored in the JSX (a test checks), stored in
`onboarding_surveys` (user-owned; a skip is a row too, so it is asked once),
and tracked as `SignupSurveyAnswered` with one `goal_<x>` prop per goal so
@ -377,7 +258,7 @@ 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. Never wired in cloud mode: `BILLING_ENABLED` ignores it.
key. On a self-hosted instance it is always available.
### Thumbnail Studio (`thumbnail.py`, `/api/thumbnail/*`)
@ -484,125 +365,33 @@ portrait clip cannot reproduce the shrink either.
| POST | `/api/hook` | Add text hook overlays |
| POST | `/api/translate` | AI voice dubbing via ElevenLabs |
| GET | `/api/translate/languages` | List supported dubbing languages |
| POST | `/api/social/post` | Post to social media (async upload) |
| POST | `/mcp` | MCP server (JSON-RPC): the pipeline as agent tools |
| POST/GET/DELETE | `/api/keys` | User API keys (cloud mode, session JWT only) |
| POST | `/api/postiz/post` | Upload a clip to Postiz, then schedule or post it now |
| GET | `/api/postiz/integrations` | List the channels connected in Postiz |
| GET | `/api/postiz/scheduled` | List scheduled posts in a date window |
| DELETE | `/api/postiz/scheduled/{id}` | Delete a scheduled post |
| GET | `/api/postiz/analytics` | Analytics for a Postiz channel or post |
| DELETE | `/api/account` | Erase the account and everything in it (GDPR art. 17) |
| GET/PUT | `/api/autopilot` | Autopilot settings, connected accounts, recent runs (cloud only) |
| GET | `/api/autopilot/videos` | Latest uploads of the connected YouTube channel + what Autopilot did |
| POST | `/api/autopilot/run` | Clip one channel video now (`{video_id}`) |
### Agent access (MCP, API keys, webhooks)
### Publishing through Postiz
- **API keys** (`cloud/api_keys.py`): `osk_...` tokens, sha256-stored, created in
the dashboard account page. `cloud/auth.get_current_user_optional` accepts
them (`Bearer osk_...` or `X-API-Key`) and resolves the owner, so metering,
entitlement, plan priority and job ownership apply to agents with zero
endpoint changes. Key management itself refuses API-key auth: a leaked key
cannot mint replacements.
- **MCP server** (`mcp_server.py`, mounted always): stateless Streamable-HTTP
JSON-RPC at `/mcp` — no SDK dependency, ~3 methods + 8 tools. Each tool calls
back into this same app in-process (`httpx.ASGITransport`) forwarding the
caller's auth headers, so it can never drift from the REST behavior. Cloud
mode 401s without a resolvable user; self-host stays BYOK-open.
- **stdio transport** (`mcp_stdio.py`): the same `handle_message` / `call_tool`
as a subprocess, for hosts that only launch MCP servers as a command (Glama's
Dockerfile deployments wrap one; a local client can skip the web server).
Two invariants: `sys.stdout` is swapped for stderr **before `app` is
imported**, because the pipeline prints everywhere and one stray line
corrupts the JSON-RPC stream; and the app's lifespan is entered
(`router.lifespan_context`), which `ASGITransport` does not do on its own.
- **OAuth for MCP clients** (`cloud/mcp_oauth.py`, cloud mode only): claude.ai
and ChatGPT connect by URL, so the server publishes RFC 9728/8414 metadata
under `/.well-known/`, accepts dynamic client registration (`POST
/oauth/register`, public clients, PKCE S256 mandatory) and bounces
`GET /oauth/authorize` to the dashboard consent screen (`#/oauth/authorize`),
because the session JWT lives in localStorage on the frontend host and a
bare API GET cannot see it. `POST /api/oauth/authorize` (session auth) mints
the code; `POST /oauth/token` redeems it by **minting an ordinary `osk_`
key** named after the client and returning it as the access token. No new
auth path, no refresh tokens: the key shows up in Account → API keys and
revoking it disconnects the app. The `/mcp` 401 carries
`WWW-Authenticate: Bearer resource_metadata=...` so clients find the flow.
`oauth_codes` is in `USER_OWNED_TABLES`; `oauth_clients` deliberately not.
- **Webhooks**: `POST /api/process` takes `webhook_url` + optional
`postiz.py` is a thin client for a self-hosted [Postiz](https://postiz.pbento.pt/)
instance. The dashboard sends the user's `X-Postiz-Key` / `X-Postiz-Url`
headers; the backend falls back to the `POSTIZ_API_KEY` / `POSTIZ_URL` env
vars. Because the clip file lives on the app server, the backend reads it and
uploads the bytes to Postiz (`POST /upload`, multipart), then references the
returned `{id, path}` in `POST /posts`. Provider settings (`tiktok`,
`instagram`, `youtube`) are built server-side from the clip title and caption.
Auth is the raw key, no `Bearer`. The old Upload-Post integration is gone.
### Webhooks
`POST /api/process` takes `webhook_url` + optional
`webhook_secret` (HMAC-SHA256, `X-OpenShorts-Signature`). Validated with
`security_utils.assert_public_url` at submit AND at delivery (DNS rebinding).
Fired once per job from `run_job_wrapper` after the R2 archive so the payload
can carry durable download links; survives redeploys via the resume manifest.
`PUBLIC_API_URL` env sets the absolute-URL base when behind a proxy.
### Autopilot (`cloud/autopilot.py`, dashboard tab "Autopilot")
Cloud-only retention feature: every new video on the user's connected YouTube
channel becomes clips on its own, and optionally the best ones are scheduled
on their socials, one a day. Paid plans only (it spends minutes unattended).
- **Channel listing** comes from Upload-Post, not scraping:
`GET /api/uploadposts/media?platform=youtube&user=os_<id>` reads the
channel's uploads playlist with the user's own OAuth token, so it includes
videos uploaded straight to YouTube. There is no push from Upload-Post, so a
loop polls (tick 5 min, each user at most once per 55 min).
- **Jobs go through the normal pipeline**: an in-process `POST /api/process`
(`httpx.ASGITransport`, like the MCP server) authenticated with a freshly
issued session JWT for the user. Metering, the probe, the per-plan job
limit, the quality gate and the download proxies apply unchanged. The
per-job content attestation is recorded once as `rights_ack_at`.
- **Guard rails**: only videos published after `enabled_at` (switching on never
clips the back catalogue) and at most 3 days old; 1 automatic job per user
per 24 h; `max_minutes` per video (default 30, sent as the partial-clip
`max_minutes`); YouTube Shorts are skipped (`HEAD /shorts/<id>` answers 200
for a Short and 303 to `/watch` for a regular video; the SOCS consent cookie is required, from the EU servers every request is otherwise a 302 to consent.youtube.com).
- **Dedupe across the deploy handover**: two containers poll at once during a
rolling deploy, so a video is claimed by INSERTing its `autopilot_runs` row
(unique `user_id, video_id`) before anything is submitted. A draining
instance stops polling. A 429 (job limit) or 5xx drops the claim to retry.
- **Completion**: `run_job_wrapper` calls `on_job_finished` after the R2
archive. A guarded UPDATE (`status='processing'` → final) makes it once-only;
it sends the Autopilot email (replacing the generic clips-ready one) and,
with autopublish on, uploads the top `clips_to_publish` clips by
`predicted_score` to Upload-Post in a background task, scheduled one a day at
`publish_hour` in the user's IANA `timezone`. Runs stuck in processing for
6 h are marked `timeout`.
- `AUTOPILOT_DISABLED=1` turns the poller off without touching the API.
- Both tables are in `account.USER_OWNED_TABLES`.
### Account erasure (GDPR art. 17)
`DELETE /api/account` (`cloud/account.py`, dashboard: Account → Delete account)
is immediate and irreversible: there is no recovery window because after the
delete there is nothing left to authenticate a recovery request against. It
refuses API-key auth (a leaked `osk_` must not destroy its own account) and
requires the caller to retype the account email.
The order of the steps is the design, and each one is a failure mode:
**Stripe cancel first**, aborting the whole thing if it fails, so we never erase
a user we are still billing; **R2 before the database**, because those rows are
the only index of which objects are theirs and dropping them first turns a
failed purge into permanent orphans; the DB delete is **one transaction** over
an explicit table list (`USER_OWNED_TABLES`) rather than the declared ON DELETE
CASCADEs, since `create_all` never ALTERs an existing table and a constraint
added after a table shipped exists in the models but not in production.
`tests/test_account_erasure.py` fails if a new table references `users.id`
without joining that list.
`app.py` registers a callback for the local working files, which record
ownership three different ways: the `.owner` file clip jobs write (so jobs
recovered from disk after a restart count too), `saas_jobs`, and
`thumbnail_sessions`. That last one is the only thing that ever deletes
generated thumbnails: the hourly sweep skips their directory and they are
served publicly at `/thumbnails/`.
What deliberately survives: the Stripe customer and its invoices (6-year
retention, Spanish commercial law) and one `account_deletions` row holding a
sha256 of the email as proof the erasure happened, itself purged after 5 years.
The "why are you leaving" answer is a closed list (`DELETION_REASONS`), never
free text — anything the user could type would land in a row designed to
outlive them. Deleting users also made one webhook path reachable that never
was before: `_apply_topup` reads the user id from Stripe metadata, so it now
confirms the row still exists before inserting, or the FK violation makes
Stripe retry the same doomed event for three days.
### 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.

282
README.md
View file

@ -1,4 +1,4 @@
# OpenShorts.app
# OpenShorts
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Open Source](https://badges.frapsoft.com/os/v1/open-source.svg?v=103)](https://opensource.org/)
@ -7,74 +7,31 @@
[![GitHub stars](https://img.shields.io/github/stars/mutonby/openshorts?style=social)](https://github.com/mutonby/openshorts)
[![Last Commit](https://img.shields.io/github/last-commit/mutonby/openshorts)](https://github.com/mutonby/openshorts/commits/main)
**Open source AI video platform** with 3 tools in one: **Clip Generator**, **AI Shorts (UGC videos with AI actors)**, and **YouTube Studio**.
**Self-hosted AI video platform** with 2 tools in one: **Clip Generator** and **YouTube Studio**, publishing through a self-hosted **Postiz** instance.
![Your podcast, and the vertical clip OpenShorts makes of it: both speakers stacked, captions on the seam](screenshots/split-before-after.gif)
Two people on camera? OpenShorts stacks them instead of shrinking the wide shot, puts the captions on the seam where they cover nobody, and switches back to a face-tracked crop when the cut goes to one person. The AI picks the layout per video; nothing to configure.
**Two ways to run it, same software either way:**
| | Self-hosted (this repo) | Hosted on [openshorts.app](https://www.openshorts.app/) |
|---|---|---|
| **Price** | Free forever, MIT | Free plan, paid from $12/mo |
| **Speed** | 5 to 8 min per 8-min video on CPU | About 50s on our NVIDIA GPU |
| **API keys** | Bring your own Gemini, ElevenLabs, fal.ai | Gemini included, nothing to set up |
| **Watermark / limits** | None, ever | Watermark and 20 min/mo on the free plan, neither on paid |
| **Setup** | Docker, 8GB+ RAM, model downloads | Sign in and paste a link |
| **MCP / API for agents** | Same `/mcp` endpoint, but only while your machine is on | Always-on endpoint at [mcp.openshorts.app](https://www.openshorts.app/mcp), API keys in one click |
| **Your data** | Your server | Ours |
Self-hosting is genuinely free and always will be. It costs you a machine, your own API keys and the time to keep it running. The hosted plans exist to cover that hardware and those keys, not to unlock features.
https://github.com/user-attachments/assets/b45fa983-16b4-48b5-ac5b-a267836b9ad9
### Video Tutorial: How it works
[![OpenShorts Tutorial](https://img.youtube.com/vi/xlyjD1qCaX0/maxresdefault.jpg)](https://www.youtube.com/watch?v=xlyjD1qCaX0 "Click to watch the video on YouTube")
*Click the image above to watch the full walkthrough.*
This is a clean, self-hosted fork. You run it on your own machine with Docker and bring your own Gemini and ElevenLabs keys. There is no hosted service, no billing, and no usage cap. Publishing to TikTok, Instagram Reels and YouTube Shorts goes through your own [Postiz](https://postiz.pbento.pt/) instance.
---
## 3 Tools in 1 Platform
## 2 Tools in 1 Platform
### 1. Clip Generator
Turn your long-form videos — podcasts, webinars, livestreams, vlogs, interviews — into viral-ready 9:16 shorts for TikTok, Instagram Reels, and YouTube Shorts.
![Clip Results](screenshots/clip-results.png)
### 2. AI Shorts (UGC Video Creator)
Generate marketing videos with AI actors for **any product or business**. No camera, no studio, no influencer budget. Just describe your product or paste a URL.
![AI Shorts Setup](screenshots/ai-shorts.png)
- **Two cost modes**: Low Cost (~$0.65/video) and Premium (~$2/video)
- Works for any business: SaaS, restaurants, e-commerce, coaching, local businesses
- AI-generated actors with lip-sync, voiceover, b-roll, and TikTok-style subtitles
- Choose from a shared avatar gallery or upload your own photo
- Publish directly to TikTok, Instagram, and YouTube
### 3. YouTube Studio
Complete free AI YouTube toolkit: thumbnails, titles, descriptions, and direct publishing.
### 2. YouTube Studio
Free AI YouTube toolkit: thumbnails, titles and descriptions.
![YouTube Studio](screenshots/youtube-studio.png)
- AI thumbnail generator with face overlay
- 10 viral title suggestions with refinement chat
- Auto-generated descriptions with chapter timestamps
- One-click publish to YouTube
### UGC Video Gallery
All generated videos and avatars are saved to a public gallery with SEO pages for each video.
![UGC Gallery](screenshots/ugc-gallery.png)
- Public gallery page with hover-to-play (`/gallery`)
- Individual SEO video pages with og:video meta tags (`/video/{id}`)
- JSON-LD structured data for search engines
- Avatar gallery with prompt history
---
@ -85,37 +42,23 @@ All generated videos and avatars are saved to a public gallery with SEO pages fo
- **Runs fully local if you want**: point `LLM_BASE_URL` at Ollama, LM Studio, vLLM or any OpenAI-compatible server and the moment picker runs on your own model, no Google key needed (see [Run without a Google key](#6-run-without-a-google-key-local-llm-optional))
- **Smart 9:16 Cropping**: AI reframing per scene — TRACK mode (MediaPipe + YOLOv8 face tracking), GENERAL mode (blurred background), SPLIT mode (two speakers stacked, captions on the seam) and SCREENCAST mode (screen over presenter); the layout is picked per video by Gemini or forced from the dashboard
- **Auto Subtitles**: faster-whisper with word-level timestamps, styled and burned into clips
- **AI Voice Dubbing**: ElevenLabs integration for 30+ languages with voice cloning
- **AI Voice Dubbing**: ElevenLabs integration for 30+ languages
- **Hook Text Overlays**: AI-generated attention-grabbing text overlays
- **AI Video Effects**: Gemini-generated FFmpeg filters for professional effects
### AI Shorts Pipeline
1. **Analyze**: Scrape website URL + web research, or generate from manual description
2. **Script**: AI writes viral scripts (hook - problem - solution - CTA format)
3. **Actor**: Generate AI actors with Flux 2 Pro or select from shared gallery
4. **Voice**: ElevenLabs TTS voiceover (English/Spanish, male/female)
5. **Video**: Talking head generation (Hailuo 2.3 Fast img2video + VEED Lipsync)
6. **B-roll**: AI-generated visuals with Ken Burns effect
7. **Composite**: FFmpeg final assembly with subtitles and hook overlays
8. **Publish**: Direct posting to TikTok, Instagram Reels, YouTube Shorts via Upload-Post
### YouTube Studio
- AI-powered title generation with 10 viral options
- Interactive refinement chat for titles
- AI thumbnail generation with custom face + background
- Auto descriptions with chapter timestamps from Whisper transcript
- Direct YouTube publishing via Upload-Post
- Auto descriptions with chapter timestamps from the Whisper transcript
### Social Auto-Publishing
- **One-click posting** to TikTok, Instagram Reels, and YouTube Shorts simultaneously
- **Schedule uploads** for any date and time — plan your content calendar and let OpenShorts publish automatically
- **Multi-platform distribution** — publish to all your social networks at once from a single interface
- Upload-Post integration with async uploads
### Postiz Publishing
- **One-click posting** to TikTok, Instagram Reels, and YouTube Shorts through your self-hosted Postiz instance
- **Schedule uploads** for any date and time — plan your content calendar and let Postiz publish
- **You own the credentials**: Postiz runs on your infrastructure and holds the platform tokens, so OpenShorts never has them
### Infrastructure
- S3 cloud backup (private bucket for clips, public bucket for gallery/avatars)
- SEO gallery pages served by FastAPI with JSON-LD structured data
- Shared avatar gallery across all users
- S3 cloud backup (optional; private bucket for clips)
- Async job queue with configurable concurrency
---
@ -123,48 +66,9 @@ All generated videos and avatars are saved to a public gallery with SEO pages fo
## Who Is This For?
- **Content creators** — Turn long videos into shorts automatically, publish to all platforms at once
- **Marketing agencies** — Generate UGC videos for clients at scale, no actors or studios needed
- **SaaS founders** — Create product demos and marketing shorts from just a URL
- **E-commerce brands** — Product videos with AI actors for TikTok Shop, Instagram, YouTube
- **Local businesses** — Restaurants, gyms, real estate, coaching — affordable video marketing
- **Podcasters & educators** — Extract the most engaging moments from episodes and lessons
- **Developers** — Self-host, customize the pipeline, integrate via API
---
## AI Shorts Showcase
Videos generated with OpenShorts AI Shorts — no camera, no studio, no actors:
| | | |
|:---:|:---:|:---:|
| [![Biohacking for Investors](https://test-videos-upload-post.s3.eu-west-3.amazonaws.com/videos/cdceec1b/actor.png)](https://openshorts.app/video/cdceec1b) | [![Secret Weapon for Devs](https://test-videos-upload-post.s3.eu-west-3.amazonaws.com/videos/d3a80b6b/actor.png)](https://openshorts.app/video/d3a80b6b) | [![El Secreto de los Agentes de IA](https://test-videos-upload-post.s3.eu-west-3.amazonaws.com/videos/8ab7de92/actor.png)](https://openshorts.app/video/8ab7de92) |
| **Biohacking for Investors** · LOW COST | **Secret Weapon for Devs** · LOW COST | **El Secreto de los Agentes de IA** · PREMIUM |
> Browse all videos at [openshorts.app/gallery](https://openshorts.app/gallery)
---
## OpenShorts vs Competitors
| Feature | OpenShorts | Opus Clip | CapCut | Vizard | Klap | Descript |
|---------|:---:|:---:|:---:|:---:|:---:|:---:|
| **Price** | **Free self-hosted**<br>from $12/mo hosted | $15-29/mo | $8/mo | $15-20/mo | $23-63/mo | $24-65/mo |
| **Self-hosted** | **Yes** | No | No | No | No | No |
| **Open source** | **Yes** | No | No | No | No | No |
| **Watermark** | **Never self-hosted**<br>free plan only when hosted | Free tier | Some | Free tier | Free tier | Free tier |
| **Upload limits** | **None self-hosted**<br>by plan when hosted | 10-30GB | Credit-based | 60min-10hr | 10-100 vids/mo | 60min-40hr |
| **AI clip detection** | Yes | Yes | Yes | Yes | Yes | Yes |
| **Smart 9:16 reframing** | Yes | Yes | Yes | Yes | Yes | No |
| **Auto subtitles** | Yes | Yes | Yes | Yes | Yes | Yes |
| **Voice dubbing (30+ langs)** | Yes | No | Pro only | No | Pro only | Business only |
| **AI UGC actors** | **Yes** | No | No | No | No | No |
| **AI video effects** | Yes | No | Yes | No | No | No |
| **Hook text overlays** | Yes | No | No | No | No | No |
| **YouTube Studio (titles, thumbnails)** | **Yes** | No | No | No | No | No |
| **Social auto-publishing** | Yes | Pro only | TikTok only | Paid only | Paid only | No |
| **Schedule uploads** | Yes | Pro only | No | Paid only | Paid only | No |
| **Data privacy** | **Your server** | Their cloud | Their cloud | Their cloud | Their cloud | Their cloud |
| **Works with a local LLM (Ollama)** | **Yes** | No | No | No | No | No |
- **Privacy-conscious teams** — The source video stays on your infrastructure
---
@ -174,26 +78,22 @@ Self-hosting OpenShorts is free. You provide the machine and you only pay for th
| Service | Free Tier | Paid Cost | Used For |
|---------|-----------|-----------|----------|
| **Google Gemini** | Free trial with generous limits | < $0.01 per 10-min video | Viral moment detection, script generation, web research |
| **Google Gemini** | Free trial with generous limits | < $0.01 per 10-min video | Viral moment detection, titles, thumbnails, descriptions |
| **Local LLM (Ollama, LM Studio, vLLM...)** | **Free, your hardware** | $0 | Viral moment detection instead of Gemini (`LLM_BASE_URL`) |
| **fal.ai** | Pay-per-use | ~$0.50-1.50 per AI Short | Actor generation, talking head video, lip-sync |
| **ElevenLabs** | Free tier available | Pay-per-use | Voiceover, voice dubbing |
| **Upload-Post** | **10 free uploads/month** to all networks (no credit card) | Pay-per-use | Auto-publishing to TikTok, Instagram, YouTube |
| **AWS S3** | Optional | ~$0.023/GB | Cloud backup for clips and gallery |
| **ElevenLabs** | Free tier available | Pay-per-use | Voice dubbing |
| **Postiz** | **Open source, self-hosted** | $0 (your hardware) | Publishing to TikTok, Instagram, YouTube |
| **AWS S3** | Optional | ~$0.023/GB | Backup for clips |
**Bottom line:** You can clip videos for practically free with Gemini, and publish 10 videos/month to all social networks at zero cost with Upload-Post.
**Don't want to run any of that?** [openshorts.app](https://www.openshorts.app/) is the same software on our hardware: our NVIDIA GPU clips an 8-minute video in about 50 seconds instead of the 5 to 8 minutes it takes on a typical CPU, the Gemini key is included, and auto-publishing is already wired up. Free plan is 20 minutes a month with a watermark and no credit card; paid plans start at $12/mo for 100 minutes without watermark.
**Bottom line:** you can clip and publish videos for practically free with a Gemini free-tier key and a self-hosted Postiz.
---
## Requirements
- **Docker & Docker Compose**
- **Google Gemini API Key** ([Free — get it here](https://aistudio.google.com/app/apikey)) — required for all AI features
- **fal.ai API Key** ([Pay-per-use](https://fal.ai)) — required for AI Shorts (actor generation, video, lip-sync)
- **ElevenLabs API Key** ([Free tier](https://elevenlabs.io)) — required for voiceover/dubbing
- **Upload-Post API Key** ([free tier](https://upload-post.com)) — required for direct social posting
- **Google Gemini API Key** ([Free — get it here](https://aistudio.google.com/app/apikey)) — required for all AI features unless `LLM_BASE_URL` is set
- **ElevenLabs API Key** ([Free tier](https://elevenlabs.io)) — optional, for voice dubbing
- **Self-hosted Postiz** ([Postiz docs](https://docs.postiz.com/)) — optional, for social publishing
---
@ -208,7 +108,7 @@ cd openshorts
### 2. Configure (optional)
```bash
cp .env.example .env
# Edit .env with your AWS keys for S3 backup
# Edit .env with your AWS keys for S3 backup and your Postiz URL/key
```
### 3. Launch
@ -219,11 +119,9 @@ docker compose up --build
### 4. Open Dashboard
Navigate to **`http://localhost:5175`**
1. Go to **Settings** and enter your API keys (Gemini, fal.ai, ElevenLabs, Upload-Post)
1. Go to **Settings** and enter your API keys (Gemini, ElevenLabs) and your Postiz URL + API key
2. **Clip Generator**: Upload a long-form video to generate viral shorts
3. **AI Shorts**: Describe your product or paste a URL to generate UGC marketing videos
4. **YouTube Studio**: Generate thumbnails, titles, and descriptions for YouTube
5. **UGC Gallery**: Browse all generated videos and avatars
3. **YouTube Studio**: Generate thumbnails, titles, and descriptions for YouTube
### 5. GPU acceleration (optional, NVIDIA)
@ -312,52 +210,24 @@ know:
5. **Extract** — FFmpeg precise clip cutting
6. **Reframe** — AI vertical cropping with subject tracking
7. **Effects** — Subtitles, hooks, AI video effects
8. **Publish** — S3 backup + Upload-Post social distribution
8. **Publish** — S3 backup + publishing through Postiz
### AI Shorts
1. **Analyze** — Website scraping + Gemini web research (or manual description)
2. **Script** — Gemini generates viral scripts with segments
3. **Actor** — Flux 2 Pro portrait generation (or gallery/upload)
4. **Voice** — ElevenLabs TTS voiceover
5. **Video** — Hailuo 2.3 Fast img2video + VEED Lipsync (Low Cost) or Kling Avatar v2 (Premium)
6. **B-roll** — Flux 2 Pro image generation + Ken Burns effect
7. **Composite** — FFmpeg assembly with ASS subtitles and hook overlays
8. **Gallery** — Upload to public S3 with metadata for SEO pages
9. **Publish** — Upload-Post to TikTok, Instagram, YouTube
### YouTube Studio
1. **Titles** — Gemini generates 10 options with an interactive refinement chat
2. **Thumbnails** — AI image generation with an optional uploaded face and background
3. **Descriptions** — auto-written from the Whisper transcript with chapter timestamps
---
## Automate It: MCP Server, REST API and Webhooks
## Automate It: REST API and Webhooks
You don't need the dashboard. The whole pipeline is callable by AI agents and scripts.
You don't need the dashboard. The pipeline is callable by scripts and workflows.
### MCP server (`/mcp`)
OpenShorts ships a built-in [MCP](https://modelcontextprotocol.io) server, so Claude, ChatGPT, Cursor or any MCP client can clip and publish videos for you:
**claude.ai and ChatGPT**: paste `https://mcp.openshorts.app/mcp` as a custom connector (Settings → Connectors) and approve the access on openshorts.app. The server does OAuth 2.1 with dynamic client registration, so there is no key to copy; the connection shows up under Account → API keys, where revoking it disconnects the app.
### REST API
```bash
# Claude Code / Cursor / n8n (hosted): create an API key in your account page
claude mcp add --transport http openshorts https://mcp.openshorts.app/mcp \
--header "Authorization: Bearer osk_..."
# Self-hosted (no key needed, BYOK rules apply):
claude mcp add --transport http openshorts http://localhost:8000/mcp
# Self-hosted without running the web server: same tools over stdio
claude mcp add openshorts -- python mcp_stdio.py
```
Tools: `process_video` (URL or `upload_id`; `captions: false` when the source already has subtitles, `auto_hook: false` to skip the hook line, burned by default like the dashboard), `create_upload` (hand the agent a local file: PUT the bytes, then process), `get_job_status`, `list_clips`, `get_quota`, `add_subtitles`, `recut_clip`, `publish_clip`. A prompt like *"clip this podcast and schedule the best 3 to TikTok"* is now a one-liner in your agent of choice.
### REST API + API keys
Hosted accounts can mint `osk_...` API keys (account page). A key authenticates as you everywhere — same plan, same minutes, same job ownership:
```bash
curl -X POST https://api.openshorts.app/api/process \
-H "Authorization: Bearer osk_..." -H "Content-Type: application/json" \
curl -X POST http://localhost:8000/api/process \
-H "Content-Type: application/json" \
-d '{"url": "https://youtube.com/watch?v=...", "acknowledged": true,
"webhook_url": "https://your-server.com/hooks/openshorts"}'
```
@ -366,7 +236,7 @@ Interactive docs at `/docs` (OpenAPI) on any instance.
### Completion webhooks
Pass `webhook_url` (and optionally `webhook_secret`) to `POST /api/process` and you get exactly one `POST` when the job reaches a terminal state — no polling loops in your n8n / Zapier / cron pipelines:
Pass `webhook_url` (and optionally `webhook_secret`) to `POST /api/process` and you get exactly one `POST` when the job reaches a terminal state — no polling loops in your n8n / cron pipelines:
```json
{"event": "job.completed", "job_id": "…",
@ -375,42 +245,11 @@ Pass `webhook_url` (and optionally `webhook_secret`) to `POST /api/process` and
With a secret, the body is signed: `X-OpenShorts-Signature: sha256=<hmac-sha256(body)>`.
### CLI
The same API from the terminal, zero dependencies (`cli/`):
```bash
pip install openshorts # or: uvx openshorts
export OPENSHORTS_API_KEY=osk_... # hosted
# export OPENSHORTS_API_URL=http://localhost:8000 # self-hosted, no key
openshorts process "https://youtube.com/watch?v=..." --wait
openshorts clips <job_id>
openshorts publish <job_id> 0 --platforms tiktok,youtube
```
### Agent skill
`skills/openshorts/SKILL.md` follows the open
[Agent Skills](https://agentskills.io) standard, so it works in any
skill-capable agent:
```bash
# Claude Code (and most agents): copy the folder into the skills directory
cp -r skills/openshorts ~/.claude/skills/
# Hermes Agent: install straight from this repo
hermes skills install mutonby/openshorts/skills/openshorts
# OpenClaw: from ClawHub
openclaw skills install @mutonby/openshorts
```
### n8n
An importable workflow (video URL in, published-ready clips out, no polling)
lives in [`examples/n8n/`](examples/n8n/).
An importable workflow (video URL in, clips out, no polling) lives in
[`examples/n8n/`](examples/n8n/). Publishing in the workflow goes through your
Postiz instance.
---
@ -420,9 +259,9 @@ lives in [`examples/n8n/`](examples/n8n/).
|-------|-----------|
| Backend | Python 3.11, FastAPI, google-genai, faster-whisper, ultralytics (YOLOv8), mediapipe, opencv-python, yt-dlp, FFmpeg, httpx |
| Frontend | React 18, Vite 4, Tailwind CSS 3.4 |
| AI APIs | Google Gemini, fal.ai (Flux, Hailuo, VEED, Kling), ElevenLabs |
| Infrastructure | Docker + Docker Compose, AWS S3 |
| Publishing | Upload-Post API (TikTok, Instagram, YouTube) |
| AI APIs | Google Gemini, ElevenLabs |
| Infrastructure | Docker + Docker Compose, AWS S3 (optional) |
| Publishing | Self-hosted [Postiz](https://postiz.pbento.pt/) (TikTok, Instagram, YouTube) |
---
@ -431,24 +270,26 @@ lives in [`examples/n8n/`](examples/n8n/).
**Server-side (.env):**
| Variable | Description |
|----------|------------|
| `AWS_ACCESS_KEY_ID` | AWS access key for S3 |
| `AWS_SECRET_ACCESS_KEY` | AWS secret key |
| `AWS_ACCESS_KEY_ID` | AWS access key for S3 (optional) |
| `AWS_SECRET_ACCESS_KEY` | AWS secret key (optional) |
| `AWS_REGION` | AWS region (default: us-east-1) |
| `AWS_S3_BUCKET` | Private bucket for clip backup |
| `AWS_S3_PUBLIC_BUCKET` | Public bucket for gallery/avatars |
| `AWS_S3_BUCKET` | Private bucket for clip backup (optional) |
| `MAX_CONCURRENT_JOBS` | Concurrent processing limit (default: 5) |
| `MAX_FILE_SIZE_MB` | Upload size cap in MB. `0` (default) is unlimited |
| `LLM_BASE_URL` | OpenAI-compatible server for the moment picker (Ollama, vLLM, LM Studio...). Set it and the Gemini key becomes optional |
| `LLM_MODEL` | Model name on that server (default `llama3.1:8b`) |
| `LLM_API_KEY` | Bearer token for that server, if it checks one |
| `LLM_SCORE_BATCH` | Transcript windows per scoring call (default 3 local, 8 Gemini) |
| `POSTIZ_URL` | Base URL of your self-hosted Postiz instance |
| `POSTIZ_API_KEY` | Postiz API key used server-side when the dashboard does not send one |
**Client-side (encrypted in localStorage):**
| Key | Description |
|-----|------------|
| `GEMINI_API_KEY` | Google Gemini — required unless `LLM_BASE_URL` is set (then only for layout picking and silent videos) |
| `FAL_KEY` | fal.ai — required for AI Shorts |
| `ELEVENLABS_API_KEY` | ElevenLabs — required for voiceover/dubbing |
| `UPLOAD_POST_API_KEY` | Upload-Post — required, for social posting |
| `ELEVENLABS_API_KEY` | ElevenLabs — optional, for voice dubbing |
| `postiz_url` | Base URL of your self-hosted Postiz instance |
| `postiz_key_v1` | Postiz API key, sent to the backend as `X-Postiz-Key` |
---
@ -459,17 +300,16 @@ lives in [`examples/n8n/`](examples/n8n/).
- **Auto-Cleanup**: Automatic purging of old jobs (1h retention)
- **Encrypted Keys**: API keys encrypted client-side, never stored server-side
- **Upload Validation**: Image uploads validated for format and minimum size
- **File Limits**: 2GB upload limit protection
- **Configurable File Limits**: `MAX_FILE_SIZE_MB` (0 = unlimited)
---
## Social Media Setup (Upload-Post)
## Social Publishing Setup (Postiz)
1. **Register**: [app.upload-post.com/login](https://app.upload-post.com/login)
2. **Create Profile**: Go to [Manage Users](https://app.upload-post.com/manage-users)
3. **Connect Accounts**: Link TikTok, Instagram, and/or YouTube
4. **Get API Key**: Navigate to [API Keys](https://app.upload-post.com/api-keys)
5. **Use in OpenShorts**: Paste the key in Settings
1. **Deploy Postiz**: run your own instance with Docker (see the [Postiz docs](https://docs.postiz.com/))
2. **Connect accounts**: link TikTok, Instagram and/or YouTube inside Postiz
3. **Create an API key**: in Postiz settings, generate a public API key
4. **Use in OpenShorts**: paste the Postiz URL and key in Settings, then use "Test connection" to list the connected channels
---
@ -479,10 +319,8 @@ lives in [`examples/n8n/`](examples/n8n/).
## Contributions
Contributions are welcome! Whether it's adding new AI models, improving the lip-sync pipeline, or building new features — feel free to open a PR.
Contributions are welcome! Whether it's improving the crop and subtitle pipeline or the dashboard — feel free to open a PR.
## License
MIT License for the core application — OpenShorts is yours to use, modify, and scale.
**Exception:** the [`cloud/`](cloud/LICENSE) directory (billing, managed keys, and the hosted-service infrastructure behind the optional `BILLING_ENABLED` flag) is source-available under the OpenShorts Commercial License. You can read it, modify it, and self-host it for personal or internal use, but you can't offer it to third parties as a paid/hosted service. Self-hosting the core app never requires this directory.
MIT License — OpenShorts is yours to use, modify, and scale.

1527
app.py

File diff suppressed because it is too large Load diff

View file

@ -1,11 +1,13 @@
import js from '@eslint/js'
import globals from 'globals'
import react from 'eslint-plugin-react'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
// `public/` holds vendored/minified assets (e.g. op1.js) — not our source.
globalIgnores(['dist', 'public']),
{
files: ['**/*.{js,jsx}'],
extends: [
@ -13,6 +15,7 @@ export default defineConfig([
reactHooks.configs['recommended-latest'],
reactRefresh.configs.vite,
],
plugins: { react },
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
@ -28,6 +31,10 @@ export default defineConfig([
'no-unused-vars': ['error', {
varsIgnorePattern: '^[A-Z_]', argsIgnorePattern: '^_', caughtErrors: 'none',
}],
// Core no-unused-vars does not count JSX tags as references, so a
// destructured component param (`({ icon: Icon }) => <Icon/>`) reads as
// unused. This rule marks those identifiers used.
'react/jsx-uses-vars': 'error',
// Contexts and modals export a hook or a constant next to the component.
'react-refresh/only-export-components': ['error', { allowConstantExport: true }],
},

View file

@ -30,17 +30,6 @@ server {
try_files $uri =404;
}
# The public gallery and per-video pages are server-rendered by the backend
# and only exist on api.openshorts.app. The README has always linked them
# here, where they silently served the landing page instead. Send them to
# the host that actually has them rather than answering with the wrong page.
location /gallery {
return 301 https://api.openshorts.app$request_uri;
}
location /video/ {
return 301 https://api.openshorts.app$request_uri;
}
# index.html must NOT be cached — it points at the hashed asset bundle, so a
# stale cached copy keeps loading the previous deploy's JS. (nginx add_header
# doesn't inherit into a location that sets its own, so the security headers

File diff suppressed because it is too large Load diff

View file

@ -28,6 +28,7 @@
"@vitejs/plugin-react": "^4.2.1",
"autoprefixer": "^10.4.23",
"eslint": "^9.39.5",
"eslint-plugin-react": "^7.37.5",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.26",
"globals": "^15.15.0",

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

View file

@ -1,301 +0,0 @@
/* /auto-clip and /youtube-automation: the two pages about running a channel's
* clipping without opening the app.
*
* Every rule stated here is a constant in cloud/autopilot.py (checked
* 23-sep-2026); if one changes there, change it here. Screenshots are the real
* Autopilot tab in production with the connected channel's name, handle,
* thumbnails and video titles blurred: that channel belongs to someone who did
* not agree to be on a marketing page. The usage numbers are aggregates over
* all accounts from usage_ledger, nothing per user.
*/
import { SITE } from './data.js'
import { esc } from './render.js'
const PUBLISHED = '2026-09-23'
const faqBlock = (faq) =>
`<h2>Common questions</h2><dl class="faq">${faq
.map((f) => `<dt>${esc(f.q)}</dt><dd>${esc(f.a)}</dd>`)
.join('')}</dl>`
const sources = (items) =>
`<h2>Sources</h2><ul class="sources">${items.map((s) => `<li>${s}</li>`).join('')}</ul>`
/* Checked against GET https://api.openshorts.app/api/billing/plans on
* 23-sep-2026. Autopilot is in every paid plan and in none of the free ones. */
const PLANS = [
['Starter', '$12/month', '100 minutes'],
['Creator', '$29/month', '300 minutes'],
['Pro', '$59/month', '750 minutes'],
]
/* usage_ledger, job_type "process", status committed, 24-aug to 23-sep-2026. */
const USAGE = { jobs: '4,641', minutes: '56,590', median: 12, window: '24 August to 23 September 2026' }
const plansTable = `
<table>
<thead><tr><th>Plan</th><th>Price</th><th>Source video per month</th><th>Autopilot</th></tr></thead>
<tbody>
<tr><td>Free</td><td>$0</td><td>20 minutes, watermarked</td><td>No (clip by hand)</td></tr>
${PLANS.map(([n, p, m]) => `<tr><td class="os">${n}</td><td>${p}</td><td>${m}</td><td class="yes">Yes</td></tr>`).join('\n')}
</tbody>
</table>
<p class="sources">Prices from the OpenShorts billing API, checked 23 September 2026. Yearly plans cost ten times the monthly price.</p>`
const autoClip = () => ({
path: '/auto-clip',
title: 'Auto Clip Your YouTube Videos Into Shorts | OpenShorts',
description:
'Autopilot auto clips every new video on your YouTube channel into vertical shorts with subtitles and can post the best ones daily. Rules, limits, price.',
h1: 'Auto clip: every new YouTube video turned into shorts on its own',
breadcrumb: [{ name: 'Auto clip' }],
published: PUBLISHED,
updated: PUBLISHED,
relatedTitle: 'Related',
related: ['/youtube-automation', '/n8n-youtube-shorts-automation', '/how-openshorts-works'],
cta: {
label: 'Autopilot',
title: 'Connect your channel once',
body: 'Included in every paid plan from $12/month. On the free plan you can still clip any video by hand.',
button: 'Open Autopilot',
href: `${SITE.url}/#app?tab=autopilot`,
},
tldr: [
'Automatic clipping means software watches a long video, picks the moments that stand on their own and cuts them into short vertical clips. OpenShorts does that for any video you paste, and Autopilot does it for every new upload on your YouTube channel without you opening anything.',
'Autopilot checks your channel about once an hour, clips each new video (only videos published after you switch it on, at most one a day, the first 10 to 90 minutes of each), emails you when the clips are ready and, if you turn on autopublish, schedules the best 1 to 5 of them one a day on TikTok, Instagram and YouTube Shorts.',
],
body: `
<h2>What "auto clip" does, step by step</h2>
<ol>
<li><strong>Transcribe.</strong> The audio is transcribed with word-level timestamps, so every clip can start and end on a word.</li>
<li><strong>Find the cuts.</strong> Scene detection marks where the picture changes.</li>
<li><strong>Score the moments.</strong> Google Gemini reads the transcript and rates stretches of 15 to 60 seconds on whether they make sense alone and hold attention, then keeps the 3 to 15 best.</li>
<li><strong>Reframe to 9:16.</strong> Face tracking keeps the speaker in the frame; screen recordings and two-person shots get their own layouts.</li>
<li><strong>Subtitle and title.</strong> Captions are burned in from the transcript and each clip gets a hook and a title.</li>
</ol>
<p>That pipeline is the same whether you paste a link by hand or Autopilot starts
it. The details are on <a href="/how-openshorts-works">how OpenShorts works</a>.
Across all accounts, OpenShorts Cloud ran ${USAGE.jobs} clipping jobs on
${USAGE.minutes} minutes of source video between ${USAGE.window}; the median
source video was ${USAGE.median} minutes long.</p>
<h2>Autopilot: the channel clips itself</h2>
<figure class="shot">
<img src="/screens/autopilot-settings.webp" width="920" height="672" loading="eager"
alt="The Autopilot tab in OpenShorts: a connected YouTube channel, the Autopilot switch turned on with the first 10 minutes of each video selected, and the autopublish switch off.">
<figcaption>The Autopilot tab in production, 23 September 2026. The channel name is blurred because it belongs to a user.</figcaption>
</figure>
<p>You connect your YouTube channel once. From then on Autopilot reads your
channel's uploads through the YouTube account you connected, so it also sees
videos you upload straight to YouTube, and it clips them through the normal
pipeline. The rules are deliberately conservative, because it spends your
plan's minutes while you are not looking:</p>
<ul>
<li><strong>Only new videos.</strong> Switching it on never clips your back catalogue: only videos published after that moment, and only while they are at most 3 days old.</li>
<li><strong>One automatic video a day.</strong> If you publish three videos in a day, the others wait for you. You can still clip up to 5 more a day by hand from the same tab.</li>
<li><strong>A cap per video.</strong> Autopilot clips the first 10, 20, 30, 45, 60 or 90 minutes of each video (30 by default), so a three-hour stream cannot empty your plan.</li>
<li><strong>Shorts are skipped.</strong> A video that is already a Short is not clipped again.</li>
<li><strong>You get an email</strong> when the clips of each video are ready.</li>
</ul>
<figure class="shot">
<img src="/screens/autopilot-channel-videos.webp" width="920" height="454" loading="lazy"
alt="The latest videos list in the Autopilot tab: each upload with its date, a clips count or not clipped, and open or clip it buttons.">
<figcaption>Your latest uploads, what Autopilot did with each, and a "clip it" button for any of them. Titles and thumbnails blurred.</figcaption>
</figure>
<h2>Autopublish: the best clips go out one a day</h2>
<p>Off by default. Turn it on and, for each video, Autopilot takes the 1 to 5
clips with the highest predicted score (3 by default) and schedules them one per
day at the hour you choose, in your own time zone, on the accounts you pick:
TikTok, Instagram and YouTube Shorts. TikTok clips arrive as drafts in your
TikTok inbox, so you open the app to post them. Leave autopublish off and you
review and post the clips yourself.</p>
<h2>What it costs</h2>
<p>Autopilot runs on your plan's minutes, so it is part of the paid plans and not
the free one. A 30-minute cap per video uses at most 30 minutes of your plan for
that video.</p>
${plansTable}
<p>The free plan still includes the clip generator itself: 20 minutes a month,
with a watermark, clipped by hand. Or self-host the
<a href="/open-source-video-clipper">open source video clipper</a> and wire the
same automation yourself with the
<a href="/n8n-youtube-shorts-automation">n8n workflow</a>.</p>
<h2>What it does not do</h2>
<ul>
<li>It only watches YouTube. Podcasts, Twitch VODs or files on your drive have to be pasted or sent through <a href="/automate-shorts-api">the API</a>.</li>
<li>It does not guarantee views. It picks the moments the model scores highest; some weeks those will be the wrong ones, which is why autopublish is off until you turn it on.</li>
<li>It is new: Autopilot launched on 22 September 2026.</li>
</ul>
${faqBlock([
{
q: 'What is auto clipping?',
a: 'Software that watches a long video, finds the moments that work on their own and cuts them into short vertical clips with subtitles, instead of you scrubbing the timeline by hand. OpenShorts returns 3 to 15 clips of 15 to 60 seconds per video.',
},
{
q: 'Can OpenShorts clip my new YouTube videos automatically?',
a: 'Yes. Autopilot checks your connected channel about once an hour and clips each new video on its own: only videos published after you switch it on, at most one a day, up to the minute cap you set.',
},
{
q: 'Does Autopilot post the clips for me?',
a: 'Only if you turn on autopublish. Then it schedules the best 1 to 5 clips of each video one a day on TikTok, Instagram and YouTube Shorts. TikTok clips arrive as drafts you post from the app.',
},
{
q: 'Is automatic clipping free?',
a: 'Clipping a video you paste is free for 20 minutes a month on OpenShorts Cloud, or unlimited if you self-host. Autopilot, which runs on its own, is included in the paid plans from $12/month.',
},
{
q: 'Will it clip my whole back catalogue and burn my minutes?',
a: 'No. It only picks up videos published after you switch it on, at most 3 days old, one a day, and only the first 10 to 90 minutes of each.',
},
])}
${sources([
`Autopilot rules: <code>cloud/autopilot.py</code> in the <a href="${SITE.repo}" rel="noopener">OpenShorts source</a>, checked 23 September 2026.`,
'Usage figures: OpenShorts Cloud billing ledger, all accounts aggregated, 24 August to 23 September 2026.',
])}
`,
faq: [
{ q: 'What is auto clipping?', a: 'Software that finds the moments of a long video that work on their own and cuts them into short vertical clips with subtitles. OpenShorts returns 3 to 15 clips of 15 to 60 seconds per video.' },
{ q: 'Can OpenShorts clip my new YouTube videos automatically?', a: 'Yes. Autopilot checks your connected channel about once an hour and clips each new video: only videos published after you switch it on, at most one a day.' },
{ q: 'Does Autopilot post the clips for me?', a: 'Only if you turn on autopublish. Then it schedules the best 1 to 5 clips of each video one a day on TikTok, Instagram and YouTube Shorts.' },
{ q: 'Is automatic clipping free?', a: 'Clipping a pasted video is free for 20 minutes a month, or unlimited self-hosted. Autopilot is included in the paid plans from $12/month.' },
],
})
const youtubeAutomation = () => ({
path: '/youtube-automation',
title: 'YouTube Automation for Shorts, Step by Step | OpenShorts',
description:
'Automate the repetitive part of a real YouTube channel: clip every upload into Shorts, schedule them, or wire it to n8n, the API or Claude over MCP.',
h1: 'YouTube automation: hand the repetitive work to software, keep the channel yours',
breadcrumb: [{ name: 'YouTube automation' }],
published: PUBLISHED,
updated: PUBLISHED,
relatedTitle: 'Related',
related: ['/auto-clip', '/n8n-youtube-shorts-automation', '/mcp'],
cta: {
label: 'Start with no code',
title: 'Turn on Autopilot for your channel',
body: 'Every new upload clipped on its own, the best clips scheduled one a day if you want. In every paid plan from $12/month.',
button: 'Open Autopilot',
href: `${SITE.url}/#app?tab=autopilot`,
},
tldr: [
'"YouTube automation" means two different things. One is faceless channels that mass-produce videos from templates; YouTube demonetises that as inauthentic content. The other is taking the repetitive work off a real channel: cutting every long video into Shorts, writing the metadata, scheduling the posts. This page is about the second.',
'With OpenShorts there are three ways to automate it: Autopilot in the app (no code), the n8n template (you approve each clip from Telegram), or the REST API and MCP server for your own scripts and for agents like Claude and ChatGPT.',
],
body: `
<h2>What is worth automating on a YouTube channel</h2>
<p>The work that does not need your judgement, every single week:</p>
<ul>
<li><strong>Cutting Shorts from each long video.</strong> Finding the moments, reframing to 9:16, adding subtitles. This is the slowest part to do by hand and the easiest to automate well.</li>
<li><strong>Posting them on a schedule</strong> to YouTube Shorts, TikTok and Instagram, one a day instead of all at once.</li>
<li><strong>The first draft of titles, descriptions and tags.</strong> You still edit them; the free <a href="/youtube-tag-generator">tag, title and description generator</a> writes the draft.</li>
<li><strong>Transcripts</strong> for show notes and blog posts, from the <a href="/youtube-transcript-generator">transcript generator</a>.</li>
</ul>
<p>What should stay yours: the long video itself, and the decision to publish.
YouTube's monetisation policy was changed on 15 July 2025 to name "inauthentic
content", which includes "AI-generated content made with generic or unoriginal
templates giving the impression of mass production". Automating the chores of a
channel you actually make is not that. Generating the channel is.</p>
<h2>Three ways to automate it, from no code to full control</h2>
<table>
<thead><tr><th>Route</th><th>Who it is for</th><th>You approve each post?</th><th>What you need</th></tr></thead>
<tbody>
<tr><td class="os">Autopilot</td><td>Creators who want it done, no setup</td><td>Your choice: autopublish on or off</td><td>A paid plan, your YouTube channel connected</td></tr>
<tr><td class="os">n8n template</td><td>People who already run n8n</td><td>Yes, from Telegram</td><td>n8n, an OpenShorts API key, a Telegram bot</td></tr>
<tr><td class="os">API and MCP</td><td>Developers and AI agents</td><td>Whatever your code decides</td><td>An API key, or a claude.ai / ChatGPT connector</td></tr>
</tbody>
</table>
<h2>Route 1: Autopilot, no code</h2>
<ol>
<li>Sign in to OpenShorts and open the <strong>Autopilot</strong> tab.</li>
<li>Connect your YouTube channel.</li>
<li>Switch Autopilot on, confirm you own the content, and choose how many minutes of each video to clip (10 to 90).</li>
<li>Optionally switch on autopublish: pick TikTok, Instagram and/or YouTube Shorts, how many clips per video (1 to 5) and the hour to post.</li>
</ol>
<figure class="shot">
<img src="/screens/autopilot-settings.webp" width="920" height="672" loading="eager"
alt="The Autopilot settings in OpenShorts: connected channel, Autopilot on with a 10 minute cap, autopublish off.">
<figcaption>Autopilot in production, 23 September 2026. Channel name blurred.</figcaption>
</figure>
<p>From then on Autopilot looks at your channel about once an hour, starts a
job for each new upload it finds and emails you when the clips are ready. The exact rules (one automatic
video a day, only new videos, Shorts skipped) are on the
<a href="/auto-clip">auto clip page</a>.</p>
<h2>Route 2: the n8n template, with a human in the loop</h2>
<figure class="shot">
<img src="/n8n-content-machine-workflow.png" width="950" height="750" loading="lazy"
alt="The OpenShorts content machine workflow open in n8n, from the channel trigger to Telegram approval and weekly analytics.">
<figcaption>The importable n8n workflow: watch the channel, clip, approve from Telegram, drip-publish, report weekly.</figcaption>
</figure>
<p>If you run n8n, the free <a href="/n8n-youtube-shorts-automation">n8n YouTube
Shorts template</a> does the same job with one difference that matters: every
clip reaches your Telegram with Publish and Skip buttons, and nothing goes out
until you tap Publish. It reads your channel's public RSS feed, so it needs no
YouTube API key, and a self-hosted OpenShorts works too: change the base URL in
the workflow.</p>
<h2>Route 3: the API and MCP, for your own code and for agents</h2>
<p>Everything the app does is one HTTP call away. <code>POST /api/process</code>
takes a video URL and a <code>webhook_url</code>, and OpenShorts calls you back
once with the finished clips; the details and a working example are on
<a href="/automate-shorts-api">automate shorts with the API</a>. The same
pipeline is exposed as an MCP server, so Claude, ChatGPT, Cursor or n8n's agent
node can clip and publish when you ask them in plain language.</p>
<figure class="shot">
<img src="/screens/connect-an-agent.webp" width="684" height="366" loading="lazy"
alt="The connect an agent card in the OpenShorts account page, with setup steps for claude.ai and the MCP server URL https://mcp.openshorts.app/mcp.">
<figcaption>Connecting Claude takes one URL: <code>https://mcp.openshorts.app/mcp</code>. The card also has tabs for ChatGPT, Claude Code, Claude Desktop, Cursor, n8n and curl.</figcaption>
</figure>
<p>More on the tools the server exposes on the <a href="/mcp">MCP server page</a>.</p>
<h2>What it costs</h2>
<p>Autopilot, the API and MCP all use the same minutes as the app: 20 free
minutes a month on the free plan (Autopilot itself needs a paid plan), then
$12/month for 100 minutes, $29 for 300 or $59 for 750, as of 23 September 2026.
Self-hosting the MIT licensed code is free with no minute cap; you pay for your
own hardware and API keys.</p>
${faqBlock([
{
q: 'Is YouTube automation allowed?',
a: 'Automating chores on a channel you create is fine. What YouTube does not monetise is inauthentic content: mass-produced, generic or repetitive videos, including AI-generated content made from generic templates. Clipping your own long videos into Shorts is not that.',
},
{
q: 'Can I automate YouTube Shorts from my long videos?',
a: 'Yes. OpenShorts Autopilot clips each new upload on your channel into vertical Shorts with subtitles and can schedule the best ones one a day. The n8n template and the API do the same for people who want to build their own flow.',
},
{
q: 'Do I need to code?',
a: 'No. Autopilot is a switch in the app. The n8n template needs n8n; the API and the MCP server are for developers and AI agents.',
},
{
q: 'Can an AI agent run my channel with OpenShorts?',
a: 'An agent such as Claude or ChatGPT can call OpenShorts over MCP to clip a video, list the clips and publish them. Whether it publishes without asking you is up to how you set it up; the n8n template keeps a human approval step on purpose.',
},
])}
${sources([
'<a href="https://support.google.com/youtube/answer/1311392" rel="noopener">YouTube channel monetization policies</a> (inauthentic content, renamed from repetitious content on 15 July 2025), checked 23 September 2026.',
`Autopilot rules: <code>cloud/autopilot.py</code> in the <a href="${SITE.repo}" rel="noopener">OpenShorts source</a>; plan prices from the OpenShorts billing API, both checked 23 September 2026.`,
])}
`,
faq: [
{ q: 'Is YouTube automation allowed?', a: 'Automating chores on a channel you create is fine. YouTube does not monetise inauthentic content: mass-produced, generic or repetitive videos, including AI-generated content from generic templates.' },
{ q: 'Can I automate YouTube Shorts from my long videos?', a: 'Yes. OpenShorts Autopilot clips each new upload into vertical Shorts with subtitles and can schedule the best ones one a day.' },
{ q: 'Do I need to code?', a: 'No. Autopilot is a switch in the app. The n8n template needs n8n; the API and MCP server are for developers and AI agents.' },
],
})
export function autopilotPages() {
return [autoClip(), youtubeAutomation()]
}

View file

@ -87,7 +87,7 @@ export const PIPELINE_STEPS = [
},
{
title: 'Dubbing and publishing',
body: 'ElevenLabs dubbing translates the audio into 30+ languages while preserving the speaker\'s voice, and the dubbed track is re-transcribed so the subtitles match the new language. Finished clips post directly to TikTok, Instagram Reels and YouTube Shorts.',
body: 'ElevenLabs dubbing translates the audio into 30+ languages while preserving the speaker\'s voice, and the dubbed track is re-transcribed so the subtitles match the new language. Finished clips publish to TikTok, Instagram Reels and YouTube Shorts through a self-hosted Postiz instance.',
},
]
@ -116,7 +116,7 @@ export const COMPETITORS = {
whereWeDiffer: [
'OpenShorts can be self-hosted, so the source video never leaves your machine. Opus Clip is cloud only.',
'OpenShorts is MIT-licensed and auditable. Opus Clip is closed source.',
'OpenShorts includes AI voice dubbing into 30+ languages and an AI UGC generator with lip-synced actors; Opus Clip has neither.',
'OpenShorts includes AI voice dubbing into 30+ languages; Opus Clip has neither.',
'Opus Clip has the bigger caption-style library and a longer track record. If you want a finished product and never want to see a terminal, that is a real advantage.',
],
bestFor:
@ -219,7 +219,6 @@ export const COMPARISON_ROWS = [
{ feature: 'Face-tracked 9:16 reframing', os: 'Yes, MediaPipe + YOLOv8', vendor: 'Yes' },
{ feature: 'Word-level auto subtitles', os: 'Yes, faster-whisper', vendor: 'Yes' },
{ feature: 'AI voice dubbing, 30+ languages', os: 'Yes, ElevenLabs', vendor: 'No' },
{ feature: 'AI UGC video with lip-synced actors', os: 'Yes, from $0.65/video', vendor: 'No' },
{ feature: 'Free AI YouTube thumbnail & title studio', os: 'Yes', vendor: 'No' },
{ feature: 'Usage cap', os: 'None when self-hosted · metered on Cloud', vendor: 'Metered on every tier' },
]

View file

@ -46,10 +46,7 @@ const FEATURES = [
['Local video upload', 'Podcasts, webinars, livestreams, interviews and vlogs, at full resolution, from a file or a YouTube link.'],
['Self-hosted and private', 'Run it with Docker on your own machine and the source video never leaves your infrastructure.'],
['Free AI YouTube studio', 'AI thumbnail generator, 10 viral title suggestions and auto-written descriptions with chapter timestamps.'],
['Direct social publishing', 'Post to TikTok, Instagram Reels and YouTube Shorts from the dashboard.'],
['MCP server, API and CLI for AI agents', 'Connect Claude, ChatGPT or n8n to an always-on endpoint (mcp.openshorts.app/mcp) and automate clipping end to end, with a REST API, per-user keys, completion webhooks and a zero-dependency CLI (pip install openshorts). Guide at /mcp.'],
['AI UGC video generator', 'The AI writes a script and generates a lip-synced avatar video for any product or business, from $0.65 per video.'],
['AI actors with lip-sync', 'Pick an AI actor or upload a photo to get a talking-head video with matched lip movement.'],
['Direct social publishing', 'Publish to TikTok, Instagram Reels and YouTube Shorts from the dashboard through a self-hosted Postiz instance.'],
]
const STEPS = [
@ -57,7 +54,7 @@ const STEPS = [
['AI finds the best moments', 'Gemini 3.1 Flash-Lite returns 3 to 15 candidate clips of 15 to 60 seconds each.'],
['Smart cropping to vertical 9:16', 'Face-tracked reframing keeps the subject centred without the camera swinging.'],
['Subtitles, hooks and effects', 'Word-level subtitles, an AI hook overlay, optional effects and dubbing into 30+ languages.'],
['Download or post directly', 'Export the clips or publish straight to TikTok, Instagram Reels and YouTube Shorts.'],
['Download or post directly', 'Export the clips or publish straight to TikTok, Instagram Reels and YouTube Shorts through Postiz.'],
]
const FAQ = [
@ -69,7 +66,7 @@ const FAQ = [
['What is OpenShorts and how does it work?', CANONICAL_ANSWERS.whatIsIt + ' ' + CANONICAL_ANSWERS.howItWorks],
[
'How does OpenShorts compare to Opus Clip?',
'Both do AI viral moment detection and smart vertical cropping. OpenShorts is MIT-licensed and can be self-hosted, so the source video never leaves your machine, and it adds voice dubbing into 30+ languages plus an AI UGC generator with lip-synced actors. Opus Clip is closed source and cloud only, starting at $15/month as of July 2026, and it ships a larger caption-style library. Full comparison at /alternatives/opus-clip.',
'Both do AI viral moment detection and smart vertical cropping. OpenShorts is MIT-licensed and can be self-hosted, so the source video never leaves your machine, and it adds voice dubbing into 30+ languages. Opus Clip is closed source and cloud only, starting at $15/month as of July 2026, and it ships a larger caption-style library. Full comparison at /alternatives/opus-clip.',
],
[
'How does the smart vertical cropping work?',
@ -79,14 +76,6 @@ const FAQ = [
'Can OpenShorts translate and dub videos?',
'Yes, into more than 30 languages through ElevenLabs, preserving the original speaker\'s voice characteristics. After dubbing, the audio is re-transcribed so the burned-in subtitles are in the target language rather than the original.',
],
[
'What is the AI UGC video generator?',
'It generates marketing videos with AI actors for any product or business. You describe the business or paste a website URL, and the AI writes a script, generates a lip-synced actor with voiceover, adds b-roll, subtitles and a hook overlay. Low Cost mode is about $0.65 per video and Premium is about $2.00. It works for restaurants, e-commerce, coaching, local businesses and apps, not only software.',
],
[
'Can I automate OpenShorts from Claude, ChatGPT or n8n?',
'Yes. OpenShorts has a native MCP server at mcp.openshorts.app/mcp plus a REST API with per-user keys and completion webhooks, so an agent can submit a video URL, wait for processing, list the clips and publish them. The hosted endpoint is always on, with the API key created in your account page; the self-hosted edition serves the same /mcp endpoint while your machine is running. A zero-dependency CLI is on PyPI as openshorts. Full guide at /mcp.',
],
[
'What are the system requirements to self-host?',
'Any machine with Docker, realistically 8GB of RAM and a modern multi-core CPU. An NVIDIA GPU is optional and cuts processing time by roughly an order of magnitude. Docker Compose pulls Python 3.11, FFmpeg, YOLOv8, MediaPipe, faster-whisper and the React dashboard. Linux, macOS and Windows via WSL2 are supported.',
@ -101,7 +90,7 @@ export const LANDING_FALLBACK = `<div id="seo-content" style="background:oklch(1
<section style="${S.section};padding-top:4rem"><div style="${S.wrap}">
<p style="${S.eyebrow}">AI clip generator &middot; cloud or self-hosted</p>
<h1 style="${S.h1}">the free open source ai clip generator, built to clip what people actually watch.</h1>
<p style="${S.p};max-width:44rem;font-size:1.05rem">Turn long videos into viral 9:16 shorts, or generate UGC marketing videos with AI actors. Online in the cloud with zero setup, or self-hosted with Docker for free. Also a clipping tool for AI agents: Claude, ChatGPT and n8n drive it over <a href="/mcp" style="${S.a}">MCP</a>, or run a channel on autopilot with <a href="/auto-clip" style="${S.a}">Autopilot</a> or the <a href="/n8n-youtube-shorts-automation" style="${S.a}">n8n workflow</a>. Just want it free? Start with the <a href="/free-ai-clip-generator" style="${S.a}">free AI clip generator</a>.</p>
<p style="${S.p};max-width:44rem;font-size:1.05rem">Turn long videos into viral 9:16 shorts. Online in the cloud with zero setup, or self-hosted with Docker for free. Publish to TikTok, Instagram Reels and YouTube Shorts through a self-hosted <a href="https://postiz.pbento.pt/" rel="noopener" style="${S.a}">Postiz</a> instance, or wire the REST API into your own pipeline with the <a href="/n8n-youtube-shorts-automation" style="${S.a}">n8n workflow</a>. Just want it free? Start with the <a href="/free-ai-clip-generator" style="${S.a}">free AI clip generator</a>.</p>
<p style="${S.muted};max-width:44rem"><strong style="color:oklch(75% 0.11 150)">No credit card required.</strong> Your first video is free up to 60 minutes, then 20 free minutes every month. Paid plans from $12/month without a watermark. Prefer to run it yourself? <a style="${S.a}" href="https://github.com/mutonby/openshorts" rel="noopener">Self-host free on GitHub</a>.</p>
</div></section>
@ -144,8 +133,6 @@ export const LANDING_FALLBACK = `<div id="seo-content" style="background:oklch(1
<a style="${S.a}" href="/youtube-transcript-generator">YouTube transcript generator</a> &middot;
<a style="${S.a}" href="/youtube-tag-generator">YouTube tag generator</a> &middot;
<a style="${S.a}" href="/video-aspect-ratio-converter">Video to 9:16 converter</a> &middot;
<a style="${S.a}" href="/auto-clip">Auto clip</a> &middot;
<a style="${S.a}" href="/youtube-automation">YouTube automation</a> &middot;
<a style="${S.a}" href="/free-ai-clip-generator-no-watermark">No-watermark clip generator</a> &middot;
<a style="${S.a}" href="/open-source-video-clipper">Open source video clipper</a> &middot;
<a style="${S.a}" href="/open-source-ai-video-generator">Open source AI video generator</a> &middot;
@ -160,9 +147,8 @@ export const LANDING_FALLBACK = `<div id="seo-content" style="background:oklch(1
<a style="${S.a}" href="/opus-pro">Opus Pro</a> &middot;
<a style="${S.a}" href="/vizard-ai-video-to-text">Vizard AI video to text</a> &middot;
<a style="${S.a}" href="/submagic-reviews">Submagic review</a> &middot;
<a style="${S.a}" href="/mcp">MCP server &amp; API</a> &middot;
<a style="${S.a}" href="/automate-shorts-api">Automate shorts via API</a> &middot;
<a style="${S.a}" href="/n8n-youtube-shorts-automation">n8n template: channel on autopilot</a>
<a style="${S.a}" href="/n8n-youtube-shorts-automation">n8n template</a>
</p>
</div></section>

View file

@ -115,12 +115,10 @@ in full.</p>
<p>The service uses AI systems to do its work, and we name them: transcription
runs on our own servers (Whisper-family and NVIDIA Parakeet models); moment
selection, titling, layout decisions and generated thumbnails use Google's
Gemini API; optional voice dubbing and AI voices use ElevenLabs; AI Shorts
uses fal.ai (Flux for actor images, Kling and Hailuo for the animated
presenter). Your video content, audio, transcript, sampled frames and any
actor photo you supply are sent to these providers only as needed to perform
the job you requested, under agreements that prohibit them from using
paid-API customer data to train their models. Section 4 of the
Gemini API; optional voice dubbing and AI voices use ElevenLabs. Your video
content, audio, transcript and sampled frames are sent to these providers only
as needed to perform the job you requested, under agreements that prohibit them
from using paid-API customer data to train their models. Section 4 of the
<a href="/privacy">Privacy Policy</a> says exactly what each one receives.</p>
<p><strong>We do not train AI models on your content, and we do not sell it or
share it for training.</strong></p>
@ -130,8 +128,8 @@ similar outputs for different customers, so results are not guaranteed to be
unique. You are responsible for reviewing AI output before you use or publish
it. You may not use the service or its output to develop or train a competing
model or service.</p>
<p>Clips that use AI dubbing contain synthetic speech, and so do videos made
with an AI actor and thumbnails generated by the image model. We mark those
<p>Clips that use AI dubbing contain synthetic speech, and so do thumbnails
generated by the image model. We mark those
files as AI-generated in a machine-readable format — a metadata tag on video,
an XMP <code>DigitalSourceType: trainedAlgorithmicMedia</code> marking on
generated images — which is what Article 50(2) of Regulation (EU) 2024/1689
@ -153,7 +151,7 @@ submitting URLs of content you have no rights to;</li>
<li>impersonate any person, or produce media of an identifiable person's image
or voice without authorisation (deepfakes);</li>
<li>probe, disrupt or overload the service, scrape it, or access it by any
automated means other than the documented API and MCP endpoints within their
automated means other than the documented API endpoints within their
rate limits;</li>
<li>reverse engineer the hosted service or attempt to extract its models,
prompts or non-public components;</li>
@ -186,11 +184,9 @@ Article 16 DSA.</p>
following agent to receive notifications of claimed infringement under 17
U.S.C. § 512(c)(2):</p>
<p>Copyright Agent, TONVI TECH SL, Calle Puerta del Mar 18, 5th floor, 29005
Málaga, Spain. Email: <a href="mailto:info@upload-post.com">info@upload-post.com</a>.</p>
Málaga, Spain. Email: <a href="mailto:info@openshorts.app">info@openshorts.app</a>.</p>
<p>That address is the one on file with the US Copyright Office for this
company, which operates openshorts.app and upload-post.com. Notices sent to
<a href="mailto:info@openshorts.app">info@openshorts.app</a> are acted upon too, but the address above is the formal
channel.</p>
company, which operates openshorts.app.</p>
<p>A notification must be in writing and include: a physical or electronic
signature of the owner or of a person authorised to act for them; identification
of the copyrighted work claimed to be infringed; identification of the material
@ -214,13 +210,13 @@ that material is infringing, or that it was removed by mistake, is liable for
the damages that misrepresentation causes.</p>
<h2>10. Publishing to your social accounts</h2>
<p>If you connect social accounts (via our publishing partner, Upload-Post),
you expressly authorise us and our partner to publish content to those accounts
on your instruction. You remain the publisher of everything posted: you are
<p>If you connect social accounts to a self-hosted Postiz instance, you
authorise that instance to publish content to those accounts on your
instruction. You remain the publisher of everything posted: you are
responsible for the content, its scheduling and its compliance with each
platform's terms (YouTube, TikTok, Instagram and the rest). You can disconnect
your accounts at any time from the dashboard or from the platform's own
settings, which revokes our access.</p>
your accounts at any time from Postiz or from the platform's own
settings, which revokes access.</p>
<h2>11. Plans, billing and renewals</h2>
<p>Paid subscriptions and minute top-ups are billed by Stripe; we never see or
@ -401,10 +397,9 @@ nuestros servidores, es decir que el contenido pasa por ellos y esta cláusula
en nuestros propios servidores (modelos de la familia Whisper y NVIDIA
Parakeet); la selección de momentos, los títulos, las decisiones de encuadre y
las miniaturas generadas usan la API Gemini de Google; el doblaje de voz y las
voces de IA opcionales usan ElevenLabs; AI Shorts usa fal.ai (Flux para las
imágenes de actor, Kling y Hailuo para el presentador animado). Tu vídeo,
audio, transcripción, fotogramas muestreados y cualquier foto de actor que
aportes se envían a estos proveedores solo en la medida necesaria para
voces de IA opcionales usan ElevenLabs. Tu vídeo,
audio, transcripción y fotogramas muestreados se envían a estos proveedores
solo en la medida necesaria para
realizar el trabajo que pediste, bajo acuerdos que les prohíben usar los datos
de clientes de API de pago para entrenar sus modelos. El apartado 4 de la
<a href="/privacidad">Política de Privacidad</a> detalla qué recibe cada
@ -417,8 +412,8 @@ y entradas similares pueden producir salidas similares para distintos clientes,
por lo que los resultados no se garantizan únicos. Eres responsable de revisar
el resultado antes de usarlo o publicarlo. No puedes usar el servicio ni sus
resultados para desarrollar o entrenar un modelo o servicio competidor.</p>
<p>Los clips con doblaje de IA contienen voz sintética, y también los vídeos
hechos con un actor de IA y las miniaturas generadas por el modelo de imagen.
<p>Los clips con doblaje de IA contienen voz sintética, y también las miniaturas
generadas por el modelo de imagen.
Marcamos esos ficheros como generados con IA en un formato legible por máquina
— una etiqueta de metadatos en el vídeo y un marcado XMP
<code>DigitalSourceType: trainedAlgorithmicMedia</code> en las imágenes
@ -442,7 +437,7 @@ incluido enviar URLs de contenido sobre el que no tienes derechos;</li>
<li>suplantar a nadie ni producir medios con la imagen o la voz de una persona
identificable sin autorización (deepfakes);</li>
<li>sondear, interrumpir o sobrecargar el servicio, hacer scraping, o acceder
por medios automatizados distintos de la API y el endpoint MCP documentados y
por medios automatizados distintos de la API documentada y
dentro de sus límites de uso;</li>
<li>hacer ingeniería inversa del servicio alojado o intentar extraer sus
modelos, prompts o componentes no públicos;</li>
@ -478,11 +473,9 @@ de la DSA.</p>
siguiente agente para recibir notificaciones de presunta infracción conforme al
17 U.S.C. § 512(c)(2):</p>
<p>Copyright Agent, TONVI TECH SL, Calle Puerta del Mar 18, 5ª planta, 29005
Málaga, España. Email: <a href="mailto:info@upload-post.com">info@upload-post.com</a>.</p>
Málaga, España. Email: <a href="mailto:info@openshorts.app">info@openshorts.app</a>.</p>
<p>Esa es la dirección que consta en el Copyright Office estadounidense para
esta empresa, que opera openshorts.app y upload-post.com. Las notificaciones
enviadas a <a href="mailto:info@openshorts.app">info@openshorts.app</a> también se atienden, pero el canal formal es la
dirección anterior.</p>
esta empresa, que opera openshorts.app.</p>
<p>La notificación debe hacerse por escrito e incluir: la firma física o
electrónica del titular o de quien esté autorizado a actuar en su nombre; la
identificación de la obra protegida presuntamente infringida; la identificación
@ -506,14 +499,13 @@ sustancialmente falsa que un material infringe derechos, o que se retiró por
error, responde de los daños que esa manifestación cause.</p>
<h2>10. Publicación en tus cuentas sociales</h2>
<p>Si conectas cuentas sociales (a través de nuestro socio de publicación,
Upload-Post), nos autorizas expresamente a nosotros y a nuestro socio a
publicar contenido en esas cuentas siguiendo tu instrucción. Tú sigues siendo
el editor de todo lo publicado: respondes del contenido, de su programación y
de su conformidad con las condiciones de cada plataforma (YouTube, TikTok,
Instagram y las demás). Puedes desconectar tus cuentas en cualquier momento
desde el panel o desde los ajustes de la propia plataforma, lo que revoca
nuestro acceso.</p>
<p>Si conectas cuentas sociales a una instancia de Postiz autoalojada, autorizas
a esa instancia a publicar contenido en esas cuentas siguiendo tu instrucción. Tú
sigues siendo el editor de todo lo publicado: respondes del contenido, de su
programación y de su conformidad con las condiciones de cada plataforma
(YouTube, TikTok, Instagram y las demás). Puedes desconectar tus cuentas en
cualquier momento desde Postiz o desde los ajustes de la propia plataforma, lo
que revoca el acceso.</p>
<h2>11. Planes, facturación y renovaciones</h2>
<p>Las suscripciones y recargas de pago se facturan a través de Stripe; nunca
@ -720,10 +712,6 @@ prohibit using customer data to train models. USA.</li>
<li><strong>ElevenLabs</strong> — AI dubbing and AI voices, only when you ask
for it. Receives the clip's audio, which means the voice of whoever is
speaking in it. USA.</li>
<li><strong>fal.ai</strong> — the image and video models behind AI Shorts
(Flux for actor images, Kling and Hailuo for the talking avatar). Receives the
actor photo you upload or generate — which may be a photograph of a real
person — and the audio to lip-sync it to. USA.</li>
<li><strong>Stripe</strong> — payments and invoicing. USA/EU.</li>
<li><strong>Cloudflare R2 and Amazon Web Services S3</strong> — storage of your
clips and project files. EU/USA regions.</li>
@ -735,9 +723,10 @@ Germany.</li>
when a video platform refuses our servers directly, the download is routed
through a commercial proxy. It sees the URL of the video and carries its
bytes; it receives no account data of yours.</li>
<li><strong>Upload-Post</strong> — publishing to social accounts you connect,
only on your instruction, and the custodian of the platform tokens those
connections produce. Operated by TONVI TECH SL under this same policy.</li>
<li><strong>Postiz (self-hosted, operated by you)</strong> — publishing to social
accounts you connect, only on your instruction, and the custodian of the
platform tokens those connections produce. The app server sends clip bytes to
your Postiz instance; we do not receive those tokens.</li>
<li><strong>Aikount</strong> — our own invoicing system, which issues the
Spanish legal invoice for your payment and therefore receives your billing
name, address and email from Stripe. Operated by TONVI TECH SL, servers in
@ -778,8 +767,6 @@ account if you delete it sooner.</li>
copies): 1 hour after the job finishes. Uploads waiting for a job: 6 hours.</li>
<li>Generated thumbnails and the video frames sampled to make them: 24 hours
after you last downloaded one.</li>
<li>Photos you upload to drive an AI actor: deleted with the job that used
them, within the hour.</li>
<li>Application logs: 7 days in the container's rotating log.</li>
<li>Encrypted database backups: 30 days, after which a deletion you made is
also gone from every copy.</li>
@ -847,17 +834,17 @@ you are asked to confirm that when you sign up. If you believe a minor has
created an account, write to <a href="mailto:info@openshorts.app">info@openshorts.app</a> and we will delete it.</p>
<h2>8 bis. AI-generated content</h2>
<p>Dubbing, AI Shorts and AI thumbnails produce synthetic content. We mark
<p>Dubbing and AI thumbnails produce synthetic content. We mark
what we generate in a machine-readable way — a metadata tag on video files and
an XMP <code>DigitalSourceType: trainedAlgorithmicMedia</code> marking on
generated images — as required by Art. 50(2) of Regulation (EU) 2024/1689 (the
AI Act). That marking does not always survive a platform re-encoding your
upload, so when you publish synthetic content you are the one who must turn on
the platform's own AI-content label (Art. 50(4)); the app reminds you at the
moment you post. Cloning a voice or animating a photograph of a real person
without their agreement is prohibited by the
<a href="/terms">Terms of Service</a>, and both features ask you to confirm
you have that agreement before they run.</p>
moment you post. Cloning a voice without the speaker's agreement is prohibited
by the
<a href="/terms">Terms of Service</a>, and the dubbing feature asks you to
confirm you have that agreement before it runs.</p>
<h2>9. Changes</h2>
<p>If we change this policy in any meaningful way we will tell you by email or
@ -984,11 +971,6 @@ los datos de clientes para entrenar modelos. EE. UU.</li>
<li><strong>ElevenLabs</strong> — doblaje y voces con IA, solo cuando lo
solicitas. Recibe el audio del clip, es decir la voz de quien habla en él.
EE. UU.</li>
<li><strong>fal.ai</strong> — los modelos de imagen y vídeo que hay detrás de
AI Shorts (Flux para las imágenes de actor, Kling y Hailuo para el avatar que
habla). Recibe la foto de actor que subes o generas — que puede ser la
fotografía de una persona real — y el audio con el que se sincronizan sus
labios. EE. UU.</li>
<li><strong>Stripe</strong> — pagos y facturación. EE. UU./UE.</li>
<li><strong>Cloudflare R2 y Amazon Web Services S3</strong> — almacenamiento de
tus clips y archivos de proyecto. Regiones UE/EE. UU.</li>
@ -1001,10 +983,11 @@ servicio. Alemania.</li>
cuando una plataforma de vídeo rechaza a nuestros servidores directamente, la
descarga se enruta por un proxy comercial. Ve la URL del vídeo y transporta
sus bytes; no recibe ningún dato de tu cuenta.</li>
<li><strong>Upload-Post</strong> — publicación en las cuentas sociales que
conectes, solo siguiendo tu instrucción, y custodio de los tokens de
plataforma que esas conexiones generan. Operado por TONVI TECH SL bajo esta
misma política.</li>
<li><strong>Postiz (autoalojado, operado por ti)</strong> — publicación en las
cuentas sociales que conectes, solo siguiendo tu instrucción, y custodio de los
tokens de plataforma que esas conexiones generan. El servidor de la app envía
los bytes del clip a tu instancia de Postiz; nosotros no recibimos esos
tokens.</li>
<li><strong>Aikount</strong> — nuestro propio sistema de facturación, que
emite la factura legal española de tu pago y por tanto recibe de Stripe tu
nombre fiscal, dirección y email. Operado por TONVI TECH SL, servidores en
@ -1047,8 +1030,6 @@ las copias intermedias): 1 hora tras finalizar el trabajo. Subidas pendientes
de trabajo: 6 horas.</li>
<li>Miniaturas generadas y fotogramas muestreados para crearlas: 24 horas
desde la última vez que descargaste una.</li>
<li>Fotos que subes para animar un actor de IA: se eliminan con el trabajo que
las usó, dentro de la hora siguiente.</li>
<li>Registros de aplicación: 7 días en el log rotatorio del contenedor.</li>
<li>Copias de seguridad cifradas de la base de datos: 30 días, pasados los
cuales una eliminación que hayas hecho desaparece también de toda copia.</li>
@ -1119,7 +1100,7 @@ se te pide confirmarlo al registrarte. Si crees que un menor ha creado una
cuenta, escribe a <a href="mailto:info@openshorts.app">info@openshorts.app</a> y la eliminaremos.</p>
<h2>8 bis. Contenido generado por IA</h2>
<p>El doblaje, AI Shorts y las miniaturas con IA producen contenido sintético.
<p>El doblaje y las miniaturas con IA producen contenido sintético.
Marcamos lo que generamos de forma legible por máquina — una etiqueta de
metadatos en los archivos de vídeo y un marcado XMP
<code>DigitalSourceType: trainedAlgorithmicMedia</code> en las imágenes
@ -1128,9 +1109,9 @@ IA). Ese marcado no siempre sobrevive a la recodificación que hacen las
plataformas al subir un archivo, así que cuando publiques contenido sintético
eres tú quien debe activar la etiqueta de contenido de IA de la propia
plataforma (art. 50.4); la aplicación te lo recuerda en el momento de
publicar. Clonar una voz o animar la fotografía de una persona real sin su
consentimiento está prohibido por los <a href="/terminos">Términos de
Servicio</a>, y ambas funciones te piden confirmar que cuentas con ese
publicar. Clonar una voz sin el consentimiento de quien habla está prohibido
por los <a href="/terminos">Términos de
Servicio</a>, y la función de doblaje te pide confirmar que cuentas con ese
consentimiento antes de ejecutarse.</p>
<h2>9. Cambios</h2>

View file

@ -16,7 +16,6 @@
import { SITE, COMPETITORS, COMPARISON_ROWS, EDITIONS, PIPELINE_STEPS, CANONICAL_ANSWERS } from './data.js'
import { esc } from './render.js'
import { toolPages } from './tools.js'
import { autopilotPages } from './autopilot-pages.js'
const li = (items) => `<ul>${items.map((i) => `<li>${i}</li>`).join('')}</ul>`
@ -74,9 +73,9 @@ ${c.brandBlurb ? `<h2>What is ${esc(c.name)}${c.brandAlias ? ` (${esc(c.brandAli
<h2>Is OpenShorts a real alternative to ${esc(c.name)}?</h2>
<p>Yes, with one honest caveat. OpenShorts covers the same core job:
it takes a long video, finds the segments worth clipping, cuts them, reframes
them to 9:16 and burns in subtitles. It adds two things ${esc(c.name)} does not
have, AI voice dubbing into more than 30 languages and an AI UGC generator with
lip-synced actors. The caveat is that the free edition is self-hosted, which
them to 9:16 and burns in subtitles. It adds AI voice dubbing into more than 30
languages, which ${esc(c.name)} does not have. The caveat is that the free
edition is self-hosted, which
means Docker and a machine to run it on. If you want a hosted product with no
setup, that is OpenShorts Cloud, and it is a paid service above 20 minutes a month.</p>
@ -124,7 +123,7 @@ ${sources([
breadcrumb: [{ name: 'Alternatives', path: '/alternatives' }, { name: c.name }],
tldr: [
`OpenShorts is an open source AI clip generator you can run yourself for free, or use hosted from $12/month. ${esc(c.name)} is a closed-source cloud product starting at ${esc(c.entryPrice)}.`,
`Both find viral moments in long video and reframe them to 9:16 with face tracking. OpenShorts adds dubbing into 30+ languages and AI UGC video with lip-synced actors. ${esc(c.name)} has the more polished caption library.`,
`Both find viral moments in long video and reframe them to 9:16 with face tracking. OpenShorts adds dubbing into 30+ languages. ${esc(c.name)} has the more polished caption library.`,
`Pick ${esc(c.name)} if you want zero setup and nothing else matters. Pick OpenShorts if you want to self-host for privacy, keep costs near zero, or change how the pipeline behaves.`,
],
body,
@ -281,7 +280,7 @@ ${faqBlock([
},
{
q: 'Do I need to pay for an API key?',
a: 'You need a Google Gemini API key for the self-hosted edition. Its free tier covers 1,500 requests a day, which is more than enough for individual use. ElevenLabs for dubbing and fal.ai for AI UGC video are optional and billed by those vendors. OpenShorts Cloud includes the keys.',
a: 'You need a Google Gemini API key for the self-hosted edition. Its free tier covers 1,500 requests a day, which is more than enough for individual use. ElevenLabs for dubbing is optional and billed by that vendor. OpenShorts Cloud includes the keys.',
},
{
q: 'How many clips does it generate per video?',
@ -373,7 +372,7 @@ ${faqBlock([
},
{
q: 'Can I run it without sending video to any third party?',
a: 'Transcription, scene detection, reframing and encoding all run locally. Moment scoring calls the Google Gemini API, which receives the transcript rather than the video file. Dubbing and AI UGC generation are optional and call ElevenLabs and fal.ai respectively; leave them off and nothing but transcript text leaves the machine.',
a: 'Transcription, scene detection, reframing and encoding all run locally. Moment scoring calls the Google Gemini API, which receives the transcript rather than the video file. Dubbing is optional and calls ElevenLabs; leave it off and nothing but transcript text leaves the machine.',
},
{
q: 'What licence is OpenShorts released under?',
@ -608,9 +607,7 @@ are about), and pretending otherwise would not survive one GitHub search. The no
<li><strong>MoneyPrinterTurbo</strong>: generates videos from text plus stock footage, which is a different job than clipping your own recordings.</li>
</ul>
<p>Where OpenShorts differs from all of them is surface area: a web dashboard, a
REST API with keys, completion webhooks, an MCP server for agents, split-screen
and screencast layouts for two-person and screen-share footage, dubbing into 30+
languages, and direct publishing to TikTok, Instagram Reels and YouTube Shorts.
languages, and publishing through a self-hosted Postiz instance.
If you want a small script you can read in an hour, the smaller repos are a
better fit, and that is a real recommendation rather than false modesty.</p>
@ -625,7 +622,7 @@ ${faqBlock([
},
{
q: 'What is the best open source AI video generator for shorts?',
a: 'For turning long recordings into publishable vertical shorts with subtitles, OpenShorts covers the widest pipeline: AI moment scoring, face-tracked reframing, split-screen layouts, dubbing and direct social publishing, MIT-licensed. Simpler repos like AI-Youtube-Shorts-Generator cover a leaner version of the same job with less to configure.',
a: 'For turning long recordings into publishable vertical shorts with subtitles, OpenShorts covers the widest pipeline: AI moment scoring, face-tracked reframing, split-screen layouts, dubbing and publishing through self-hosted Postiz, MIT-licensed. Simpler repos like AI-Youtube-Shorts-Generator cover a leaner version of the same job with less to configure.',
},
])}
@ -660,7 +657,7 @@ const podcastToShorts = () => ({
updated: '2026-08-04',
tldr: [
'A two-person podcast is the hardest input an auto-clipper faces: a single centered crop shows the wrong person half the time, or an empty chair. OpenShorts detects a real two-shot and renders both speakers stacked in half-frames, so a reply never happens off screen.',
'The rest of the pipeline is the same as for any long video: word-level transcription, scene detection, Gemini scoring the 3 to 15 strongest moments, subtitles burned in, and direct publishing to TikTok, Instagram Reels and YouTube Shorts.',
'The rest of the pipeline is the same as for any long video: word-level transcription, scene detection, Gemini scoring the 3 to 15 strongest moments, subtitles burned in, and publishing to TikTok, Instagram Reels and YouTube Shorts through Postiz.',
'Cost is where podcasts punish credit-based tools: they bill the whole episode length before you see a clip. Self-hosted OpenShorts has no meter at all; hosted plans start at $12/month.',
],
body: `
@ -690,7 +687,7 @@ one side of the table.</p>
<li>faster-whisper transcribes with word-level timestamps, and PySceneDetect maps the cuts.</li>
<li>Google Gemini reads the transcript against the scene boundaries and returns the 3 to 15 segments that stand alone best, 15 to 60 seconds each.</li>
<li>Each segment is reframed for its content: split layout for two-shots, face tracking for single speakers, screencast layout if the episode shares a screen.</li>
<li>Subtitles are burned in from the word-level transcript, and finished clips post directly to TikTok, Instagram Reels and YouTube Shorts, or come back through the API.</li>
<li>Subtitles are burned in from the word-level transcript, and finished clips publish to TikTok, Instagram Reels and YouTube Shorts through Postiz, or come back through the API.</li>
</ol>
<h2>What a full episode costs to clip</h2>
@ -822,9 +819,9 @@ ${faqBlock([
],
})
/* Recipe-shaped counterpart to /mcp: that page explains the protocol surface,
* this one shows the working loop. Kept separate so each can rank for its own
* intent instead of one page diluting both. */
/* The working automation loop, in one page: the intent is "automate shorts",
* which is answered by a concrete request/response shape rather than a
* protocol description. */
const automateShorts = () => ({
path: '/automate-shorts-api',
title: 'Automate Shorts: Clip and Publish on a Schedule | OpenShorts',
@ -837,7 +834,7 @@ const automateShorts = () => ({
tldr: [
'The whole automation loop is two HTTP messages. You POST a video URL with an API key and a webhook address; when processing ends, OpenShorts sends exactly one signed webhook carrying clip titles and durable download links. No polling loop, no timeout guessing.',
'API calls draw from the same minute balance as the dashboard, with no separate meter and no per-call pricing. On the self-hosted edition there is no meter at all, which is what makes an always-on pipeline affordable.',
'For agent-driven automation (Claude, ChatGPT, custom agents) the same account also exposes an MCP server; that protocol surface is documented on its own page.',
'Publishing the finished clips to TikTok, Instagram or YouTube goes through a self-hosted Postiz instance, so one request covers clipping and scheduling.',
],
body: `
<h2>The loop, end to end</h2>
@ -874,15 +871,11 @@ loop, including channel watching, Telegram approval and scheduled publishing.</p
<h2>A weekly pipeline in one cron line</h2>
<p>Because the API is one POST, scheduling is whatever scheduler you already
have. A cron job that submits the latest episode URL every Monday, a GitHub
Action on your podcast repo, or an agent that watches a feed. The webhook does
the second half, so nothing stays running in between. If you would rather not
write the curl, the CLI wraps it:</p>
<pre><code>uvx openshorts process "$EPISODE_URL" \\
--webhook https://your-server.com/hooks/openshorts \\
--webhook-secret "$SECRET"</code></pre>
Action on your podcast repo, or a watcher on a feed. The webhook does
the second half, so nothing stays running in between.</p>
<h2>What automation costs</h2>
<p>API and MCP calls draw from the same minute balance as the dashboard. There
<p>API calls draw from the same minute balance as the dashboard. There
is no per-call price, no separate API tier and no automation surcharge. As of
August 2026 that is not the market default: the mainstream tools meter their
APIs per source minute or per operation, on top of subscription tiers, so an
@ -890,16 +883,10 @@ always-on pipeline runs with a taxi meter attached. Self-hosted OpenShorts has
no meter of any kind, and the hosted plans are flat:</p>
${pricingParagraph}
<h2>Agents instead of scripts</h2>
<p>If the thing driving the pipeline is an AI agent rather than a script, the
same account exposes a native MCP server with six tools covering process,
status, clips, quota, subtitles and publishing. The endpoint, the tool table and
client setup live on the <a href="/mcp">MCP server and API page</a>.</p>
${faqBlock([
{
q: 'Can I automate YouTube Shorts creation with an open source tool?',
a: 'Yes. OpenShorts is MIT-licensed and its self-hosted edition serves the same REST API and MCP server as the hosted service, with no metering. One POST submits a video, a signed webhook returns the finished clips, and the publishing endpoint posts them to YouTube Shorts, TikTok and Instagram Reels.',
a: 'Yes. OpenShorts is MIT-licensed and its self-hosted edition serves the same REST API as the hosted service, 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 OpenShorts?',
@ -907,7 +894,7 @@ ${faqBlock([
},
{
q: 'Do automated API calls cost more than using the dashboard?',
a: 'No. API and MCP usage draws from the same minute balance as the dashboard with no per-call pricing: 20 free minutes a month on the hosted free tier, flat paid plans from $12/month, and no meter at all on the self-hosted edition.',
a: 'No. API usage draws from the same minute balance as the dashboard with no per-call pricing: 20 free minutes a month on the hosted free tier, flat paid plans from $12/month, and no meter at all on the self-hosted edition.',
},
])}
@ -919,11 +906,11 @@ ${sources([
faq: [
{
q: 'Can I automate YouTube Shorts creation with an open source tool?',
a: 'Yes: OpenShorts self-hosted serves the same REST API, MCP server and signed webhooks as the hosted service, MIT-licensed and unmetered. One POST in, one signed webhook out.',
a: 'Yes: OpenShorts self-hosted serves the same REST API and signed webhooks as the hosted service, MIT-licensed and unmetered. One POST in, one signed webhook out.',
},
{
q: 'Do automated API calls cost more than using the dashboard?',
a: 'No. API and MCP calls draw from the same minute balance with no per-call pricing; the self-hosted edition has no meter at all.',
a: 'No. API calls draw from the same minute balance with no per-call pricing; the self-hosted edition has no meter at all.',
},
],
})
@ -951,8 +938,8 @@ const n8nTemplate = () => ({
<p>This workflow runs a YouTube channel on its own without handing over the
publish button. Once a day it reads your channel feed, clips one video into
vertical shorts, and sends each finished clip to your Telegram with Publish and
Skip buttons. What you approve is scheduled one post per day to the accounts you
connected, and every Sunday it reports back what the published clips actually
Skip buttons. What you approve is scheduled one post per day through your
self-hosted Postiz instance, and every Sunday it reports back what the published clips actually
did. Two credentials, no polling loop, no TikTok or Instagram OAuth app.</p>
<h2>Download the workflow</h2>
@ -983,7 +970,7 @@ as a video message with Publish and Skip buttons. A human approves every post,
which is also what separates this from the fully automated pipelines that
YouTube's inauthentic-content policy targets.</li>
<li><strong>Drip-publish and measure.</strong> Approved clips take the next free
daily slot and post to the accounts you connected in OpenShorts. Every Sunday
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
impressions, per-platform split and your best post.</li>
</ol>
@ -993,18 +980,18 @@ impressions, per-platform split and your best post.</li>
requires an audited app to post publicly, and the Instagram Graph API refuses
anything that is not a public static URL, which is why Google Drive links fail
there. This workflow sidesteps both by posting through
<code>POST /api/social/post</code> against the networks you connected once in
your OpenShorts account. The workflow itself holds no social credentials, and
the clip file is already on durable storage, so the public-URL requirement is
satisfied before Instagram ever sees it.</p>
<code>POST /api/postiz/post</code> against the networks you connected once in
your self-hosted Postiz instance. The workflow itself holds no social
credentials, and the clip file is already on durable storage, so the public-URL
requirement is satisfied before Instagram ever sees it.</p>
<h2>Scheduling that does not double-book</h2>
<p>Approving two clips seconds apart used to be enough to publish them at the
same minute: each execution read the same in-memory counter before either wrote
back. The workflow now asks the server for the queue it actually holds
(<code>GET /api/social/scheduled</code>) and picks the first free slot from it,
(<code>GET /api/postiz/scheduled</code>) and picks the first free slot from it,
which is shared state and cannot race with itself that way. The same endpoint,
plus <code>DELETE /api/social/scheduled/{job_id}</code>, is how you inspect or
plus <code>DELETE /api/postiz/scheduled/{id}</code>, is how you inspect or
cancel a post before it goes out.</p>
<h2>What it costs to run</h2>
@ -1027,12 +1014,6 @@ processed, only persists on production executions. Test runs from the editor do
not advance it.</li>
</ul>
<h2>Prefer an agent to a workflow?</h2>
<p>The same account exposes an MCP server, so Claude, ChatGPT or an n8n AI Agent
node can drive the pipeline as tools instead of fixed steps. That surface is
documented on the <a href="/mcp">MCP server and API page</a>, and the raw REST
loop on the <a href="/automate-shorts-api">automation page</a>.</p>
${faqBlock([
{
q: 'Is there a free n8n template to turn long videos into shorts?',
@ -1040,7 +1021,7 @@ ${faqBlock([
},
{
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 OpenShorts API avoids both, because the accounts are connected once in your OpenShorts account and the clip already lives on durable public storage.',
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?',
@ -1064,189 +1045,7 @@ ${sources([
},
{
q: 'How do I post a video to TikTok or Instagram from n8n?',
a: 'Post through the OpenShorts API: the social accounts are connected once in your OpenShorts account, so the workflow needs no TikTok app audit and no public CDN URL for the file.',
},
],
})
const mcpAgentsPage = () => ({
path: '/mcp',
title: 'OpenShorts MCP Server: Clip Video From Claude or ChatGPT',
description:
'Connect Claude, ChatGPT, Cursor or n8n with one URL and clip, subtitle and publish videos from a chat. 8 MCP tools, a REST API and signed webhooks.',
h1: 'Clip and publish video from an AI agent',
breadcrumb: [{ name: 'MCP server and API' }],
cta: {
label: 'For agents',
title: 'Point your agent at a real pipeline',
body: 'Connect Claude or ChatGPT to mcp.openshorts.app/mcp, or copy an API key. Self-hosted serves the same endpoint, unmetered.',
button: 'Get an API key',
},
tldr: [
'OpenShorts has a native MCP server at mcp.openshorts.app/mcp. Connect any MCP client, Claude, ChatGPT, Cursor or a custom agent, and a prompt like "clip this podcast and schedule the best three to TikTok" becomes one instruction instead of an afternoon in an editor.',
'Eight tools cover the whole pipeline: process_video, create_upload, get_job_status, list_clips, get_quota, add_subtitles, recut_clip and publish_clip. There is also a plain REST API with per-user keys, and completion webhooks so pipelines never poll.',
'The difference that survives comparison shopping is the meter. Most clipping tools now have an API, and Opus Clip added an MCP server in July 2026, but they meter agent calls per source minute or per operation. OpenShorts API calls draw from the same flat minute balance as the dashboard, and the self-hosted edition, free and MIT-licensed, serves the same MCP endpoint with no meter at all.',
],
body: `
<h2>What can an agent actually do with OpenShorts?</h2>
<p>Everything the dashboard does. The MCP server is not a wrapper around a
subset of features: each tool calls the same pipeline the web app uses, with the
same account, the same minutes and the same job history. An agent can take a
YouTube URL, turn it into 3 to 15 vertical clips with word-level captions,
restyle those captions, and publish or schedule the result to TikTok, Instagram
Reels and YouTube Shorts.</p>
<h2>How do I connect Claude or ChatGPT?</h2>
<p>With the URL alone. The server implements OAuth 2.1 with dynamic client
registration, which is what claude.ai and ChatGPT expect from a remote MCP
server, so there is no key to copy:</p>
<ol>
<li><strong>claude.ai:</strong> Settings, Connectors, Add custom connector, paste <code>https://mcp.openshorts.app/mcp</code>, Connect.</li>
<li><strong>ChatGPT:</strong> Settings, Connectors, Create, paste the same URL, choose OAuth.</li>
<li>Approve the access on openshorts.app (sign in if you are not). The 8 tools appear in every chat, and the connection is listed under Account, API keys, where revoking it disconnects the app.</li>
</ol>
<h2>How do I connect Claude Code, Cursor or n8n?</h2>
<p>CLI and workflow clients take an API key instead: create one in your account
page (shown once, starts with <code>osk_</code>) and pass it as a Bearer
token. With Claude Code:</p>
<pre><code>claude mcp add --transport http openshorts https://mcp.openshorts.app/mcp \\
--header "Authorization: Bearer osk_..."</code></pre>
<p>Any client that speaks Streamable HTTP works the same way: the endpoint is
<code>https://mcp.openshorts.app/mcp</code>, the server describes itself over
the protocol, tool schemas included, and the account page has copy-ready
snippets for Claude Desktop, Cursor, n8n and curl.</p>
<h2>What tools does the MCP server expose?</h2>
<table>
<thead><tr><th>Tool</th><th>What it does</th></tr></thead>
<tbody>
<tr><td><code>process_video</code></td><td>Starts clipping a video from a URL or an upload_id. Returns a job id immediately; processing takes minutes. Pass captions: false when the source already has subtitles burned in, auto_hook: false to skip the hook line (on by default).</td></tr>
<tr><td><code>create_upload</code></td><td>Reserves an upload slot for a local file: the agent PUTs the bytes to the returned URL, then processes it by upload_id.</td></tr>
<tr><td><code>get_job_status</code></td><td>Progress, recent log lines, and the clips once the job completes.</td></tr>
<tr><td><code>list_clips</code></td><td>Titles, durations, platform-ready descriptions and download URLs for a finished job.</td></tr>
<tr><td><code>get_quota</code></td><td>Plan and remaining minutes, so an agent can check before starting a large job.</td></tr>
<tr><td><code>add_subtitles</code></td><td>Restyles the burned-in captions of one clip: presets (default, hormozi, pill, lime, oneword, clean), size, word-by-word reveal, a box behind the active word or one word at a time.</td></tr>
<tr><td><code>publish_clip</code></td><td>Posts or schedules one clip to TikTok, Instagram or YouTube through the connected account.</td></tr>
</tbody>
</table>
<p>In clients that support the MCP Apps extension (ChatGPT apps, mcp-ui hosts),
<code>list_clips</code> also renders as an interactive clip picker: preview each
9:16 clip inline, select the keepers and publish them without leaving the
conversation. Clients without UI support see the same data as plain results.</p>
<h2>How does this compare to the other clipping tools' agent access?</h2>
<p class="checked">Checked 2026-08-04 on vendor developer documentation and pricing pages. This market is moving fast; verify before committing a pipeline.</p>
<p>Agent access stopped being exclusive in 2026: Opus Clip launched its own MCP
server in July, Reap ships MCP plus a CLI, and Klap, Vizard and Submagic have
REST APIs. A comparison that pretended otherwise would not deserve your trust.
What still separates the offerings is how agent calls are billed and where the
server can run:</p>
<table>
<thead><tr><th>Tool</th><th>MCP server</th><th>REST API</th><th>How agent calls are billed</th></tr></thead>
<tbody>
<tr><td class="os">OpenShorts</td><td class="os yes">Yes, hosted and self-hosted</td><td class="os yes">Yes, with signed webhooks</td><td class="os">Same flat minute balance as the dashboard; self-hosted has no meter</td></tr>
<tr><td>Opus Clip</td><td class="yes">Yes, since July 2026</td><td>Yes</td><td>Credits per source minute, expiring in 60 days</td></tr>
<tr><td>Reap</td><td class="yes">Yes, plus CLI</td><td>Yes</td><td>Subscription from $9.99/month, metered minutes</td></tr>
<tr><td>Klap</td><td>No</td><td>Yes</td><td>Per operation, roughly $0.32 to $0.48 each</td></tr>
<tr><td>Vizard</td><td>No</td><td>Yes, with webhooks</td><td>Consumes plan upload minutes</td></tr>
<tr><td>Submagic</td><td>No</td><td>Yes, Business tier ($69/month)</td><td>Metered per minute on top of the tier</td></tr>
</tbody>
</table>
<p>The consequence for an autonomous pipeline is simple: an agent loop on a
metered API runs with the bill still attached to every decision it makes. On a
flat plan the worst an agent can do is spend your minutes; on the self-hosted
edition there is nothing to spend. For the recipe-shaped version of this,
webhooks, n8n and cron, see <a href="/automate-shorts-api">automating shorts
with the API</a>.</p>
<h2>Can I use a plain REST API instead of MCP?</h2>
<p>Yes. The same <code>osk_</code> key authenticates against the REST API, and
interactive documentation lives at
<a href="https://api.openshorts.app/docs" rel="noopener">api.openshorts.app/docs</a>
with the OpenAPI spec at <code>/openapi.json</code>. A processing job is one
request:</p>
<pre><code>curl -X POST https://api.openshorts.app/api/process \\
-H "Authorization: Bearer osk_..." -H "Content-Type: application/json" \\
-d '{"url": "https://youtube.com/watch?v=...", "acknowledged": true,
"webhook_url": "https://your-server.com/hooks/openshorts"}'</code></pre>
<h2>Is there a CLI?</h2>
<p>Yes, a zero-dependency one on PyPI. It talks to the same REST surface as
everything else, so the terminal, the dashboard and the agents can never
disagree about what a job did:</p>
<pre><code>pip install openshorts # or: uvx openshorts
export OPENSHORTS_API_KEY=osk_...
openshorts process "https://youtube.com/watch?v=..." --wait
openshorts clips &lt;job_id&gt;
openshorts publish &lt;job_id&gt; 0 --platforms tiktok,youtube</code></pre>
<p>Point <code>OPENSHORTS_API_URL</code> at <code>http://localhost:8000</code>
and the same binary drives a self-hosted instance with no key.</p>
<h2>How do completion webhooks work?</h2>
<p>Pass <code>webhook_url</code> when starting a job and OpenShorts sends
exactly one POST when the job finishes or fails, with clip titles and download
links in the body. Add a <code>webhook_secret</code> and the body is signed with
HMAC-SHA256 in the <code>X-OpenShorts-Signature</code> header so your receiver
can verify the sender. This is what lets an n8n, Zapier or cron pipeline run
without a polling loop.</p>
<h2>Does this work on the self-hosted edition?</h2>
<p>Yes. The self-hosted edition serves the same <code>/mcp</code> endpoint on
your own machine, with no API key required because there is no account system:
it follows the same bring-your-own-key rules as the rest of the self-hosted app.
Point your MCP client at <code>http://localhost:8000/mcp</code> and the same six
tools appear.</p>
<h2>What does it cost?</h2>
${pricingParagraph}
<p>API and MCP calls are not billed separately: they draw from the same minute
balance as the dashboard, so automation does not change the price of anything.</p>
${faqBlock([
{
q: 'Does OpenShorts have an MCP server?',
a: 'Yes, a native one at mcp.openshorts.app/mcp using the Streamable HTTP transport. It exposes eight tools covering the full pipeline: process_video, create_upload, get_job_status, list_clips, get_quota, add_subtitles, recut_clip and publish_clip. Authentication is an API key created in the dashboard, sent as a Bearer token.',
},
{
q: 'Can Claude or ChatGPT create video clips with OpenShorts?',
a: 'Yes. Any MCP-capable client, including Claude and ChatGPT, can connect to mcp.openshorts.app/mcp with an API key and drive the whole flow: submit a video URL, wait for processing, list the generated clips and publish them to TikTok, Instagram or YouTube.',
},
{
q: 'Is there an API for OpenShorts?',
a: 'Yes, a REST API documented at api.openshorts.app/docs, authenticated with per-user osk_ keys created in the dashboard. It covers processing, status, subtitles, publishing and completion webhooks.',
},
{
q: 'Do API calls cost extra?',
a: 'No. API and MCP usage draws from the same minute balance as the dashboard: 20 free minutes a month on the hosted free tier, and paid plans from $12/month. The self-hosted edition is free under MIT and serves the same endpoints with no metering. Most competing APIs are billed per source minute or per operation on top of a subscription.',
},
{
q: 'How is this different from the Opus Clip MCP server?',
a: 'The tool surface is similar: both expose around six tools covering processing, captions and publishing. The differences are billing and deployment. Opus Clip meters MCP usage in credits per source minute, and those credits expire in 60 days; OpenShorts draws from a flat minute balance with no per-call pricing. And only OpenShorts can run the same MCP server on your own machine, unmetered, because the code is MIT-licensed.',
},
])}
${sources([
`MCP specification and transports at <a href="https://modelcontextprotocol.io" rel="noopener">modelcontextprotocol.io</a>.`,
`OpenShorts server implementation in the project source at <a href="${SITE.repo}" rel="noopener">github.com/mutonby/openshorts</a>.`,
])}
`,
faq: [
{
q: 'Does OpenShorts have an MCP server?',
a: 'Yes, a native MCP server at mcp.openshorts.app/mcp with six tools covering the full pipeline, authenticated with an API key created in the dashboard.',
},
{
q: 'Can Claude or ChatGPT create video clips with OpenShorts?',
a: 'Yes. Any MCP-capable client can connect with an API key and drive the whole flow from video URL to published clip.',
},
{
q: 'Do API calls cost extra?',
a: 'No. API and MCP usage draws from the same minute balance as the dashboard: 20 free minutes a month on the hosted free tier, paid plans from $12/month, and the self-hosted edition is free under MIT.',
},
{
q: 'How is this different from the Opus Clip MCP server?',
a: 'Similar tool surface, different billing and deployment: Opus Clip meters MCP usage in credits per source minute that expire in 60 days, while OpenShorts draws from a flat minute balance, and only OpenShorts can run the same MCP server self-hosted and unmetered.',
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).',
},
],
})
@ -1519,7 +1318,7 @@ ${li(OPUS.tiers.map(([n, d]) => `<strong>${esc(n)}</strong>: ${esc(d)}`))}
<h2>Where OpenShorts differs</h2>
${li([
`OpenShorts is MIT-licensed and can be self-hosted with Docker, so the source video never leaves your machine. Opus AI is cloud only.`,
`OpenShorts adds AI voice dubbing into 30+ languages and an AI UGC generator with lip-synced actors; the Opus AI feature set is clipping and captioning.`,
`OpenShorts adds AI voice dubbing into 30+ languages; the Opus AI feature set is clipping and captioning.`,
`Opus AI has the larger caption-style library and a longer track record. If your clips live or die on animated caption design, that advantage is real and this page is not going to pretend otherwise.`,
`OpenShorts self-hosted has no meter of any kind; Opus AI bills credits per minute of source imported, and those credits expire 60 days after purchase.`,
])}
@ -1538,7 +1337,7 @@ ${faqBlock([
},
{
q: 'Does Opus AI have an open source alternative?',
a: 'Yes. OpenShorts is MIT-licensed, self-hostable with Docker, and covers the same core job: AI moment detection, face-tracked 9:16 reframing and word-level burned-in subtitles. It also adds dubbing into 30+ languages and AI UGC video, which Opus AI does not have.',
a: 'Yes. OpenShorts is MIT-licensed, self-hostable with Docker, and covers the same core job: AI moment detection, face-tracked 9:16 reframing and word-level burned-in subtitles. It also adds dubbing into 30+ languages, which Opus AI does not have.',
},
])}
`,
@ -1600,7 +1399,7 @@ ${pricingParagraph}
<p>Two differences are worth stating plainly rather than leaving to a table.
Self-hosted has no meter at all, so a 90-minute interview and a 9-minute one cost
the same: nothing. Hosted is a flat minute balance with no per-call or per-clip
charge, and API and MCP usage draws from the same balance as the dashboard.</p>
charge, and API usage draws from the same balance as the dashboard.</p>
<p>What you give up: the caption-style library. Opus Clip's presets are more
numerous and more polished than ours, and if animated captions are the product
you are selling, that is a reason to stay. What you gain: the code is MIT and
@ -1618,7 +1417,7 @@ ${faqBlock([
},
{
q: 'Is there a cheaper way to do what Opus Pro does?',
a: 'Yes, two: OpenShorts self-hosted is free under MIT with no cap (you supply your own machine and a free-tier Gemini key), and OpenShorts Cloud is $12/month for 100 minutes with no watermark, drawing API and MCP usage from the same balance.',
a: 'Yes, two: OpenShorts self-hosted is free under MIT with no cap (you supply your own machine and a free-tier Gemini key), and OpenShorts Cloud is $12/month for 100 minutes with no watermark, drawing API usage from the same balance.',
},
])}
`,
@ -1693,7 +1492,7 @@ next to the clips, and the burned-in captions are cut from it.</p>
<ul>
<li><strong>Self-hosted:</strong> free, MIT-licensed, no watermark, no cap. Transcription runs locally, so the audio never leaves your machine.</li>
<li><strong>Hosted:</strong> 20 free minutes a month with no credit card, then flat plans from $12/month with no watermark.</li>
<li><strong>Via API or MCP:</strong> the transcript and the clips come back from the same job, so an agent can summarise the text without a second transcription bill.</li>
<li><strong>Via API:</strong> the transcript and the clips come back from the same job, so an agent can summarise the text without a second transcription bill.</li>
</ul>
<h2>Which one should you pick?</h2>
@ -2219,10 +2018,8 @@ export function buildPages() {
gtaClips(),
podcastToShorts(),
youtubeConverter(),
mcpAgentsPage(),
automateShorts(),
n8nTemplate(),
...autopilotPages(),
...toolPages(),
]
}
@ -2251,11 +2048,8 @@ export function relatedFor(page, all) {
'/gta-5-clips': 'Stream VODs, webcam inset kept, no per-minute meter.',
'/podcast-to-shorts': 'Two-speaker episodes without cropping anyone out.',
'/youtube-to-shorts-converter': 'Paste a link, get 9:16 clips with subtitles.',
'/mcp': 'Drive the whole pipeline from Claude, ChatGPT or n8n.',
'/automate-shorts-api': 'One POST in, one signed webhook out, no polling.',
'/n8n-youtube-shorts-automation': 'The importable workflow: channel in, approved shorts out.',
'/auto-clip': 'Every new upload on your channel clipped on its own, with the rules.',
'/youtube-automation': 'Autopilot, n8n or the API: automate a real channel, not a content farm.',
'/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.',

View file

@ -275,7 +275,6 @@ const NAV = `
<a href="/free-ai-clip-generator">Clip generator</a>
<a href="/tools" class="keep">Free tools</a>
<a href="/alternatives">Alternatives</a>
<a href="/mcp">MCP &amp; API</a>
<a href="${SITE.repo}" rel="noopener">GitHub</a>
</nav>
<a class="cta" href="${SITE.url}/">Get free clips</a>
@ -296,7 +295,6 @@ const footer = (_related) => `
<a href="/how-openshorts-works">How it works</a>
<a href="/alternatives">Alternatives compared</a>
<a href="/alternativas">Alternativas (ES)</a>
<a href="/mcp">MCP server and API</a>
<a href="/automate-shorts-api">Automate shorts</a>
</div>
<div class="row">
@ -304,8 +302,6 @@ const footer = (_related) => `
<a href="/youtube-transcript-generator">YouTube transcript generator</a>
<a href="/youtube-tag-generator">YouTube tag, title and description generator</a>
<a href="/video-aspect-ratio-converter">Video to 9:16 converter</a>
<a href="/auto-clip">Auto clip</a>
<a href="/youtube-automation">YouTube automation</a>
</div>
<div class="row">
<a href="/opus-clip-pricing">Opus Clip pricing</a>
@ -420,7 +416,6 @@ const DEFAULT_CTA = {
const ctaBlock = (page) => {
const c = { ...DEFAULT_CTA, ...(page.cta || {}) }
// Pages about Autopilot send readers to the app tab, not the landing page.
const target = c.href || `${SITE.url}/`
const href = target
return `

View file

@ -1,5 +1,4 @@
/* The free tools (/tools) and the two automation pages built around
* Autopilot (/auto-clip, /youtube-automation).
/* The free tools (/tools) and the three tool pages.
*
* Tool pages carry `tool: { entry, html }`. The html is the tool's real form,
* rendered straight into the static document right under the H1, so it is in
@ -71,7 +70,7 @@ const toolsHub = () => ({
updated: PUBLISHED,
cta: false,
relatedTitle: 'Also on this site',
related: ['/auto-clip', '/youtube-automation', '/free-ai-clip-generator'],
related: ['/free-ai-clip-generator', '/youtube-transcript-generator', '/open-source-video-clipper'],
body: `
<div class="tools-grid">
${TOOLS.map((t) => `<a href="${t.path}"><strong>${esc(t.name)}</strong><span>${esc(t.blurb)}</span></a>`).join('\n')}
@ -96,8 +95,7 @@ bars. It does not follow faces: that is what the clip generator is for.</p>
cut into several vertical clips with subtitles and the speaker kept in frame,
that is <a href="/free-ai-clip-generator">the free AI clip generator</a>: 20 free
minutes a month on OpenShorts Cloud, or unlimited if you self-host the MIT
licensed code. To have every new upload on your channel clipped without opening
anything, see <a href="/auto-clip">auto clip with Autopilot</a>.</p>
licensed code.</p>
`,
faq: [],
})
@ -284,7 +282,7 @@ const metadataPage = () => ({
cta: false,
tool: { entry: 'tool-metadata', html: metadataTool },
relatedTitle: 'More free tools',
related: ['/youtube-transcript-generator', '/video-aspect-ratio-converter', '/youtube-automation'],
related: ['/youtube-transcript-generator', '/video-aspect-ratio-converter', '/youtube-to-shorts-converter'],
body: `
<h2>How to use it</h2>
<ol>

File diff suppressed because it is too large Load diff

View file

@ -1,5 +1,5 @@
import React from 'react';
import { Sparkles, Zap, Globe, FileVideo, Subtitles, Youtube, Instagram, Shield, Github, ArrowRight, Check, ChevronDown, Monitor, Cpu, Languages, Type, Upload, Scissors, Link2, Bot } from 'lucide-react';
import { Sparkles, Zap, Globe, FileVideo, Subtitles, Youtube, Instagram, Shield, Github, ArrowRight, Check, ChevronDown, Monitor, Cpu, Languages, Type, Upload, Scissors, Link2 } from 'lucide-react';
import PricingSection from './components/PricingSection';
import { useAuth } from './contexts/AuthContext';
import './landing.css';
@ -137,23 +137,8 @@ export default function Landing({ onLaunchApp }) {
},
{
icon: Globe,
title: "Direct Social Publishing",
description: "Post to TikTok, Instagram Reels, and YouTube Shorts from the dashboard."
},
{
icon: Bot,
title: "MCP Server, API & CLI for AI Agents",
description: "Connect Claude, ChatGPT or n8n to an always-on endpoint, or run pip install openshorts and clip from the terminal. Same pipeline, no dashboard needed."
},
{
icon: Sparkles,
title: "AI UGC Video Generator",
description: "AI writes the script and generates a lip-synced avatar video — from $0.65/video."
},
{
icon: FileVideo,
title: "AI Actors & Lip-Sync",
description: "Pick an AI actor or upload a photo for a lip-synced talking head video."
title: "Postiz Publishing",
description: "Publish to TikTok, Instagram Reels, and YouTube Shorts through a self-hosted Postiz instance."
}
];
@ -162,13 +147,13 @@ export default function Landing({ onLaunchApp }) {
{ title: "AI Detects the Best Viral Moments", description: "Google Gemini 3.1 Flash-Lite finds 3-15 high-potential clips of 15-60 seconds." },
{ title: "Smart Cropping to Vertical 9:16", description: "AI reframes to vertical with face tracking — subjects stay centered." },
{ title: "Add Subtitles, Hooks & Effects", description: "Auto subtitles, hook overlays, AI effects — optionally dub into 30+ languages." },
{ title: "Download or Post to Social Media", description: "Export your clips or post directly to TikTok, Instagram Reels, and YouTube Shorts." }
{ title: "Download or Post to Social Media", description: "Export your clips or publish to TikTok, Instagram Reels, and YouTube Shorts through Postiz." }
];
const faqs = [
{
question: "Is OpenShorts really free? What's the catch?",
answer: "There is no catch, but there are two different things on offer. (1) Self-hosted is 100% free and open source: you run it with Docker on your own machine, bring your own API keys, and there are no watermarks, no usage limits and no subscription. What it costs you is hardware and time. On a typical CPU an 8-minute video takes 5 to 8 minutes to process, and you need your own Google Gemini key (required, free tier is 1,500 requests/day), plus ElevenLabs for dubbing and fal.ai for AI Shorts if you want those. (2) Hosted at openshorts.app is the same software with the running costs covered: our NVIDIA GPU clips that same 8-minute video in about 50 seconds, the Gemini key is included so there is nothing to create or paste, auto-posting to TikTok, Instagram and YouTube is already wired up, and your clips are stored and re-openable from any browser. It has a free plan (20 minutes a month, watermark, no credit card) and paid plans from $12/mo for 100 minutes without watermark. So: free if you are happy to run it yourself, paid if you would rather it just ran fast. Both are far cheaper than Opus Clip ($15-228/month) or Kapwing ($24-79/month)."
answer: "There is no catch, but there are two different things on offer. (1) Self-hosted is 100% free and open source: you run it with Docker on your own machine, bring your own API keys, and there are no watermarks, no usage limits and no subscription. What it costs you is hardware and time. On a typical CPU an 8-minute video takes 5 to 8 minutes to process, and you need your own Google Gemini key (required, free tier is 1,500 requests/day), plus ElevenLabs for dubbing if you want it. (2) Hosted at openshorts.app is the same software with the running costs covered: our NVIDIA GPU clips that same 8-minute video in about 50 seconds, the Gemini key is included so there is nothing to create or paste, and your clips are stored and re-openable from any browser. It has a free plan (20 minutes a month, watermark, no credit card) and paid plans from $12/mo for 100 minutes without watermark. So: free if you are happy to run it yourself, paid if you would rather it just ran fast. Both are far cheaper than Opus Clip ($15-228/month) or Kapwing ($24-79/month)."
},
{
question: "What is OpenShorts and how does it work?",
@ -186,18 +171,6 @@ export default function Landing({ onLaunchApp }) {
question: "Can OpenShorts generate YouTube thumbnails and titles for free?",
answer: "Yes. OpenShorts includes a free AI YouTube thumbnail generator, a free AI YouTube title generator, and a free AI YouTube description generator — all powered by Google Gemini 3.1 Flash-Lite. Upload your video and the AI suggests 10 viral title options with an interactive refinement chat. Then it generates multiple thumbnail designs using AI image generation — upload a face photo and background image for personalized results. The studio also auto-generates YouTube descriptions with chapter timestamps and lets you publish directly to YouTube. Everything is 100% free with the Gemini free tier."
},
{
question: "What is the AI UGC Video Generator?",
answer: "OpenShorts includes an AI UGC (User Generated Content) video creator that generates marketing videos with AI actors for any product or business. You describe your product or paste a website URL — the AI writes a viral script, generates a realistic AI actor with lip-synced voiceover, adds b-roll visuals, TikTok-style subtitles, and hook text overlays. The result is a ready-to-post vertical video for TikTok, Instagram Reels, or YouTube Shorts. Two cost modes: Low Cost (~$0.65/video using Hailuo + VEED Lipsync) and Premium (~$2/video using Kling Avatar v2)."
},
{
question: "Can I use the AI UGC Video Generator for any type of business?",
answer: "Yes. The AI Shorts generator works for any product, service, or business — not just SaaS. You can use it for restaurants, e-commerce stores, coaching services, local businesses, personal brands, apps, and more. Just describe your business in the text field (e.g. 'Artisan pizza restaurant in Madrid, wood-fired oven, home delivery') or paste your website URL, and the AI generates viral marketing scripts tailored to your business."
},
{
question: "How much does it cost to generate an AI UGC video?",
answer: "OpenShorts itself is free, but the AI Shorts feature uses external APIs (fal.ai for video generation, ElevenLabs for voiceover) that charge per use. Low Cost mode costs approximately $0.65 per video (Flux image $0.05 + ElevenLabs voice $0.10 + Hailuo img2video $0.19 + VEED Lipsync $0.20 + b-roll $0.10). Premium mode costs approximately $2.00 per video using Kling Avatar v2 for higher quality. Both modes are significantly cheaper than hiring UGC creators ($50-500 per video) or using platforms like HeyGen ($24-180/month)."
},
{
question: "What AI does OpenShorts use for viral moment detection?",
answer: "OpenShorts uses Google Gemini 3.1 Flash-Lite, Google's latest multimodal AI model, for viral moment detection and title generation. The AI receives the full video transcript with timestamps, scene boundary data from PySceneDetect, and analyzes engagement patterns to identify the 3-15 most shareable moments. Each clip is scored based on emotional impact, hook strength, and viral potential — similar to how platforms like TikTok and YouTube rank content."
@ -215,8 +188,8 @@ export default function Landing({ onLaunchApp }) {
answer: "Yes — OpenShorts is a 100% free, open source clip generator (also known as open source clipping software or an AI video clipper). Unlike paid clip generators like Opus Clip ($15-228/month) or Kapwing ($24-79/month), OpenShorts lets you generate unlimited clips with no watermarks, no usage limits, and no subscription fees. It also includes a free AI YouTube thumbnail generator, free AI YouTube title generator, and free AI YouTube description generator — features that other clip generators charge extra for. You self-host it with Docker on your own machine for full privacy and control."
},
{
question: "Can I automate OpenShorts from Claude, ChatGPT or n8n?",
answer: "Yes. OpenShorts has a native MCP server at mcp.openshorts.app/mcp plus a REST API with per-user keys and completion webhooks, so an AI agent can run the whole flow: submit a video URL, wait for processing, list the clips and publish them to TikTok, Instagram or YouTube. This is where the hosted service shines: an agent needs an endpoint that is always on, and the hosted one is, with the API key created in your account page in one click. The self-hosted edition serves the same /mcp endpoint, but only while your own machine is running. There is also a zero-dependency CLI (pip install openshorts) and an importable n8n workflow. Full guide at openshorts.app/mcp."
question: "Can I automate OpenShorts?",
answer: "Yes. OpenShorts exposes a REST API with per-user keys and completion webhooks, so a script or workflow can submit a video URL, wait for processing, and list the clips. Those clips publish to TikTok, Instagram or YouTube through a self-hosted Postiz instance. There is also an importable n8n workflow. Full guide at openshorts.app/automate-shorts-api."
},
{
question: "What are the system requirements to run OpenShorts?",
@ -273,12 +246,10 @@ export default function Landing({ onLaunchApp }) {
</h1>
<p className="hero-description text-muted max-w-2xl mb-8 leading-relaxed lowercase">
turn long videos into viral 9:16 shorts, or generate ugc marketing videos with ai actors. online, in the cloud, zero setup.
also a clipping tool for ai agents: claude, chatgpt and n8n drive it over{' '}
<a href="/mcp" className="text-ink2 underline underline-offset-4 decoration-rule hover:text-ink hover:decoration-brass transition-colors">mcp</a>,
or run your channel on{' '}
<a href="/auto-clip" className="text-ink2 underline underline-offset-4 decoration-rule hover:text-ink hover:decoration-brass transition-colors">autopilot</a>{' '}
or with the{' '}
turn long videos into viral 9:16 shorts. online, in the cloud, zero setup, or self-hosted with docker for free.
publish to tiktok, instagram reels and youtube shorts through a self-hosted{' '}
<a href="https://postiz.pbento.pt/" target="_blank" rel="noopener noreferrer" className="text-ink2 underline underline-offset-4 decoration-rule hover:text-ink hover:decoration-brass transition-colors">postiz</a>{' '}
instance, or wire the rest api into your own pipeline with the{' '}
<a href="/n8n-youtube-shorts-automation" className="text-ink2 underline underline-offset-4 decoration-rule hover:text-ink hover:decoration-brass transition-colors">n8n workflow</a>.
just want it free? start with the{' '}
<a href="/free-ai-clip-generator" className="text-ink2 underline underline-offset-4 decoration-rule hover:text-ink hover:decoration-brass transition-colors">free ai clip generator</a>.
@ -462,7 +433,7 @@ export default function Landing({ onLaunchApp }) {
<span className="readout border border-rule rounded-full px-2.5 py-1">Free · Docker</span>
</div>
<ul className="space-y-1.5 mb-6 flex-1">
{['Your machine: 5 to 8 min on a typical CPU', 'Bring your own Gemini, ElevenLabs and fal.ai keys', 'You install it, you maintain it, you back it up', 'Free forever, and always will be'].map((f, i) => (
{['Your machine: 5 to 8 min on a typical CPU', 'Bring your own Gemini and ElevenLabs keys', 'You install it, you maintain it, you back it up', 'Free forever, and always will be'].map((f, i) => (
<li key={i} className="flex items-center gap-2 text-sm text-muted"><Check size={14} className="text-ok shrink-0" />{f}</li>
))}
</ul>
@ -506,12 +477,12 @@ export default function Landing({ onLaunchApp }) {
</ul>
</div>
<div className="card p-8">
<p className="eyebrow mb-4">02 · AI Shorts</p>
<Sparkles size={20} className="text-brass mb-4" />
<h3 className="font-display text-2xl lowercase text-ink mb-2">AI Shorts</h3>
<p className="text-muted text-sm leading-relaxed mb-4">UGC marketing videos with AI actors for any business.</p>
<p className="eyebrow mb-4">02 · Publishing</p>
<Globe size={20} className="text-brass mb-4" />
<h3 className="font-display text-2xl lowercase text-ink mb-2">Postiz Publishing</h3>
<p className="text-muted text-sm leading-relaxed mb-4">Publish finished clips through a self-hosted Postiz instance.</p>
<ul className="space-y-1.5">
{['AI actor generation + lip-sync', 'B-roll + TikTok-style subtitles', 'From $0.65 per video'].map((f, i) => (
{['TikTok, Instagram Reels & YouTube Shorts', 'Self-hosted, you own the credentials', 'Schedule or post now'].map((f, i) => (
<li key={i} className="flex items-center gap-2 text-xs text-muted"><Check size={12} className="text-ok shrink-0" />{f}</li>
))}
</ul>
@ -534,8 +505,8 @@ export default function Landing({ onLaunchApp }) {
{/* Features Section */}
<section id="features" className="py-20 px-6 border-t border-rule">
<div className="max-w-6xl mx-auto">
<SectionHeader eyebrow="05 · Features" title="Free AI Clip Generator + UGC Video Creator">
The free open source clip generator & AI UGC video creator. A smart AI video clipper for TikTok, Reels & Shorts.
<SectionHeader eyebrow="05 · Features" title="Free AI Clip Generator">
The free open source clip generator. A smart AI video clipper for TikTok, Reels & Shorts.
</SectionHeader>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-5">
{features.map((feature, i) => (
@ -549,7 +520,7 @@ export default function Landing({ onLaunchApp }) {
<section className="py-20 px-6 border-t border-rule">
<div className="max-w-5xl mx-auto">
<SectionHeader eyebrow="06 · API Keys" title="Self-hosting? Every API has a free tier">
Cloud plans include managed Gemini and social publishing — you never touch an API key. Self-hosters bring their own keys (all with generous free tiers):
Cloud plans include managed Gemini and Postiz publishing — self-hosters bring their own keys (all with generous free tiers):
</SectionHeader>
<div className="grid md:grid-cols-3 gap-5">
<div className="card p-6 relative">
@ -575,29 +546,9 @@ export default function Landing({ onLaunchApp }) {
<div className="w-10 h-10 rounded-input bg-paper3 flex items-center justify-center mb-4">
<Globe size={18} className="text-brass" />
</div>
<h3 className="font-display text-xl lowercase text-ink mb-1">Upload-Post API</h3>
<div className="mb-3"><span className="badge-ok">Free tier included</span></div>
<p className="text-muted text-sm leading-relaxed">Enables direct publishing to YouTube, TikTok, and Instagram Reels from the dashboard. <a href="https://www.upload-post.com" target="_blank" rel="noopener noreferrer" className="text-brass underline hover:brightness-110">Social media API</a> that lets you post your clips and thumbnails without leaving OpenShorts.</p>
</div>
</div>
<div className="grid md:grid-cols-2 gap-5 mt-5">
<div className="card p-6 relative">
<span className="readout absolute top-4 right-4 border border-rule rounded-full px-2.5 py-1">AI Shorts</span>
<div className="w-10 h-10 rounded-input bg-paper3 flex items-center justify-center mb-4">
<Zap size={18} className="text-brass" />
</div>
<h3 className="font-display text-xl lowercase text-ink mb-1">fal.ai API</h3>
<div className="mb-3"><span className="badge-ok">Pay-per-use from $0.04</span></div>
<p className="text-muted text-sm leading-relaxed">Powers AI Shorts: generates AI actor images (Flux), talking head videos (Hailuo/Kling), and lip-sync (VEED). Required only for the AI UGC video generator.</p>
</div>
<div className="card p-6 relative">
<span className="readout absolute top-4 right-4 border border-rule rounded-full px-2.5 py-1">AI Shorts</span>
<div className="w-10 h-10 rounded-input bg-paper3 flex items-center justify-center mb-4">
<Languages size={18} className="text-brass" />
</div>
<h3 className="font-display text-xl lowercase text-ink mb-1">ElevenLabs TTS</h3>
<div className="mb-3"><span className="badge-ok">Free tier included</span></div>
<p className="text-muted text-sm leading-relaxed">Generates natural voiceovers for AI Shorts from the script. Multiple voice options for male and female actors in English and Spanish.</p>
<h3 className="font-display text-xl lowercase text-ink mb-1">Self-hosted Postiz</h3>
<div className="mb-3"><span className="badge-ok">You run it</span></div>
<p className="text-muted text-sm leading-relaxed">Publishes finished clips to YouTube, TikTok, and Instagram Reels from the dashboard. <a href="https://postiz.pbento.pt/" target="_blank" rel="noopener noreferrer" className="text-brass underline hover:brightness-110">Postiz</a> runs on your own infrastructure and holds the platform credentials, so OpenShorts never has them.</p>
</div>
</div>
</div>
@ -631,7 +582,6 @@ export default function Landing({ onLaunchApp }) {
{ name: "MediaPipe", desc: "Face Tracking" },
{ name: "FFmpeg", desc: "Video Processing" },
{ name: "ElevenLabs", desc: "Voice & TTS" },
{ name: "fal.ai", desc: "AI Video Gen" },
{ name: "React + Vite", desc: "Dashboard" },
{ name: "Docker", desc: "Deployment" }
].map((tech, i) => (
@ -675,8 +625,7 @@ export default function Landing({ onLaunchApp }) {
<ComparisonRow feature="Open Source" openshorts={checkIcon} opusclip={<span className="text-muted text-sm">No</span>} kapwing={<span className="text-muted text-sm">No</span>} />
<ComparisonRow feature="AI YouTube Thumbnail Generator" openshorts={checkIcon} opusclip={<span className="text-muted text-sm">No</span>} kapwing={<span className="text-muted text-sm">Paid</span>} />
<ComparisonRow feature="AI Title & Description Generator" openshorts={checkIcon} opusclip={<span className="text-muted text-sm">Limited</span>} kapwing={<span className="text-muted text-sm">Paid</span>} />
<ComparisonRow feature="AI UGC Video Generator" openshorts={checkIcon} opusclip={<span className="text-muted text-sm">No</span>} kapwing={<span className="text-muted text-sm">No</span>} />
<ComparisonRow feature="AI Actors with Lip-Sync" openshorts={checkIcon} opusclip={<span className="text-muted text-sm">No</span>} kapwing={<span className="text-muted text-sm">No</span>} />
<ComparisonRow feature="Postiz Social Publishing" openshorts={checkIcon} opusclip={<span className="text-muted text-sm">Built-in</span>} kapwing={<span className="text-muted text-sm">Limited</span>} />
<ComparisonRow feature="Usage Limits" openshorts={<span className="text-ok text-sm">Unlimited</span>} opusclip={<span className="text-muted text-sm">Per plan</span>} kapwing={<span className="text-muted text-sm">Per plan</span>} />
</tbody>
</table>
@ -709,7 +658,7 @@ export default function Landing({ onLaunchApp }) {
},
{
title: "Businesses & Brands",
description: "UGC-style marketing videos with AI actors — from $0.65 per video.",
description: "Turn every long video into a week of posts and schedule them through self-hosted Postiz.",
icon: Sparkles
}
].map((useCase, i) => (
@ -783,8 +732,6 @@ export default function Landing({ onLaunchApp }) {
<a href="/youtube-transcript-generator" className="hover:text-ink transition-colors">youtube transcript generator</a>
<a href="/youtube-tag-generator" className="hover:text-ink transition-colors">youtube tag generator</a>
<a href="/video-aspect-ratio-converter" className="hover:text-ink transition-colors">video to 9:16 converter</a>
<a href="/auto-clip" className="hover:text-ink transition-colors">auto clip</a>
<a href="/youtube-automation" className="hover:text-ink transition-colors">youtube automation</a>
<a href="/free-ai-clip-generator-no-watermark" className="hover:text-ink transition-colors">no watermark</a>
<a href="/open-source-video-clipper" className="hover:text-ink transition-colors">open source video clipper</a>
<a href="/podcast-to-shorts" className="hover:text-ink transition-colors">podcast to shorts</a>
@ -799,14 +746,13 @@ export default function Landing({ onLaunchApp }) {
<a href="/opus-pro" className="hover:text-ink transition-colors">opus pro</a>
<a href="/vizard-ai-video-to-text" className="hover:text-ink transition-colors">vizard ai video to text</a>
<a href="/submagic-reviews" className="hover:text-ink transition-colors">submagic review</a>
<a href="/mcp" className="hover:text-ink transition-colors">mcp server & api</a>
<a href="/automate-shorts-api" className="hover:text-ink transition-colors">automate shorts</a>
<a href="/n8n-youtube-shorts-automation" className="hover:text-ink transition-colors">n8n workflow</a>
</nav>
<div className="border-t border-rule pt-6 flex flex-col md:flex-row md:items-center justify-between gap-4">
<div className="flex items-center gap-3">
<img src="/logo-openshorts.png" alt="OpenShorts" className="w-6 h-6" />
<span className="text-sm text-muted">OpenShorts — Free Open Source Clip Generator & AI UGC Video Creator</span>
<span className="text-sm text-muted">OpenShorts — Free Open Source Clip Generator & Postiz Publishing</span>
</div>
<div className="flex flex-wrap items-center gap-x-6 gap-y-2 text-sm lowercase text-muted">
<a href="https://github.com/mutonby/openshorts" target="_blank" rel="noopener noreferrer" className="hover:text-ink transition-colors">GitHub</a>

View file

@ -4,9 +4,7 @@ import { useAuth } from '../contexts/AuthContext';
import { apiJson } from '../lib/api';
import { track } from '../lib/analytics';
import ApiKeysCard from './ApiKeysCard';
import McpConnectCard from './McpConnectCard';
import DeleteAccountCard from './DeleteAccountCard';
import SocialAnalyticsCard from './SocialAnalyticsCard';
import InvoicesCard from './InvoicesCard';
import CancelPlanModal from './CancelPlanModal';
@ -62,15 +60,6 @@ export default function AccountPage() {
try { localStorage.removeItem('os_pending_checkout'); } catch (_) { /* ignore */ }
}
}
// First time a plan activates, take the user straight to connect their
// socials. Guard with a flag so top-up checkouts don't re-trigger it.
if (paidPlan && !localStorage.getItem('os_socials_prompted')) {
localStorage.setItem('os_socials_prompted', '1');
try {
const { access_url } = await apiJson('/api/social/connect', { method: 'POST' });
if (access_url) { window.location.href = access_url; return; }
} catch (_) { /* fall through to the account page */ }
}
window.location.hash = '#/account';
}
}, 2000);
@ -232,8 +221,6 @@ export default function AccountPage() {
{/* Only accounts that ever had a Stripe relationship can have invoices. */}
{me.has_billing_account && <InvoicesCard />}
<SocialAnalyticsCard />
{topups.length > 0 && (
<div className="card p-6">
<h3 className="font-display lowercase text-lg text-ink mb-1 flex items-center gap-2"><Plus size={16} className="text-brass" /> Buy more minutes</h3>
@ -252,8 +239,6 @@ export default function AccountPage() {
</div>
)}
<McpConnectCard cloud />
<ApiKeysCard />
<DeleteAccountCard />

View file

@ -1,27 +0,0 @@
import React from 'react';
import { KeyRound, ArrowRight } from 'lucide-react';
// Banner for advanced tools (AI Shorts, AI Agent) that use fal.ai + ElevenLabs.
// These are BYOK: the plan covers the script/orchestration, the user brings their
// own keys for the premium generation. If they have no plan yet, also nudge trial.
export default function AdvancedBanner({ needsPlan, onKeys }) {
return (
<div className="card mx-3 sm:mx-6 mt-3 px-3.5 sm:px-4 py-3 flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-4 shrink-0 animate-fade">
<div className="flex items-start sm:items-center gap-2.5 sm:gap-3 text-sm min-w-0">
<KeyRound size={16} className="shrink-0 text-warn mt-0.5 sm:mt-0" />
<div className="text-ink2 lowercase leading-relaxed min-w-0">
<span className="font-medium text-ink">Advanced tool.</span>{' '}
{needsPlan
? <>Sign in with <span className="font-medium text-ink">Google</span> to unlock free. This tool also uses your own <span className="font-medium text-ink normal-case">fal.ai + ElevenLabs</span> keys (you pay those providers).</>
: <>AI video &amp; voice generation use your own <span className="font-medium text-ink normal-case">fal.ai + ElevenLabs</span> keys — add them in Settings. Script &amp; orchestration are included in your plan.</>}
</div>
</div>
<button
onClick={needsPlan ? () => { window.location.hash = '#/pricing'; } : onKeys}
className="btn-quiet shrink-0 text-xs px-3 py-1.5 w-full sm:w-auto"
>
{needsPlan ? <>See plans <ArrowRight size={14} /></> : 'Add keys'}
</button>
</div>
);
}

View file

@ -1,483 +0,0 @@
import React, { useState, useEffect, useCallback, useRef } from 'react';
import {
Rocket, Youtube, Loader2, RefreshCw, Play, CheckCircle2, AlertTriangle,
Clock, Scissors, Send, ExternalLink, FolderOpen, Lock,
} from 'lucide-react';
import { apiJson } from '../lib/api';
import { track } from '../lib/analytics';
// Autopilot: every new video on the user's connected YouTube channel is turned
// into shorts automatically, and optionally the best ones are scheduled on
// their socials, one a day. The channel comes from the Upload-Post connection
// the app already uses for posting (GET /api/uploadposts/media under the hood),
// so there is nothing to paste: connect once, switch it on.
const PLATFORM_LABELS = { tiktok: 'TikTok', instagram: 'Instagram', youtube: 'YouTube Shorts' };
const ERROR_TEXT = {
plan_required: 'Autopilot is paused: it needs an active Starter, Creator or Pro plan.',
youtube_not_connected: 'Connect your YouTube channel so Autopilot can see your new videos.',
youtube_reauth_required: 'YouTube asked to reconnect your channel. Reconnect it to keep Autopilot running.',
channel_unavailable: 'We could not read your channel on the last check. We will try again shortly.',
};
const REASON_TEXT = {
youtube_short: 'already a short',
private_video: 'private on YouTube — set it to Unlisted to clip it',
out_of_minutes: 'out of minutes',
too_short: 'too short to clip',
unavailable: 'not available yet (private or processing)',
low_quality: 'only low quality available',
timeout: 'did not finish',
processing_failed: 'processing failed',
publish_partial: 'some clips could not be scheduled',
url_ingest_disabled: 'links are disabled on this server',
};
const fmtDate = (iso) => (iso
? new Date(iso).toLocaleDateString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })
: '');
// ApiError.detail is a string or {error, message}; never hand an object to JSX.
const errText = (e, fallback) => {
const d = e?.detail;
if (typeof d === 'string' && d) return d;
if (d && typeof d.message === 'string') return d.message;
return fallback;
};
const browserTimezone = () => {
try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'; } catch { return 'UTC'; }
};
function Switch({ checked, onChange, disabled, label }) {
return (
<span className="relative inline-flex items-center shrink-0">
<input
type="checkbox"
role="switch"
aria-label={label}
checked={checked}
disabled={disabled}
onChange={(e) => onChange(e.target.checked)}
className="sr-only peer"
/>
<span className="w-11 h-6 rounded-full bg-paper3 border border-rule2 peer-checked:bg-brass peer-disabled:opacity-40 transition-colors after:content-[''] after:absolute after:left-1 after:top-1 after:w-4 after:h-4 after:rounded-full after:bg-ink after:transition-transform peer-checked:after:translate-x-5" />
</span>
);
}
function StatusBadge({ run }) {
if (!run) return <span className="readout">not clipped</span>;
const { status } = run;
if (status === 'completed') {
return (
<span className="badge-ok inline-flex items-center gap-1">
<CheckCircle2 size={11} /> {run.clips_count || 0} clips
{run.posted_count ? ` · ${run.posted_count} scheduled` : ''}
</span>
);
}
if (status === 'processing' || status === 'queued') {
return <span className="badge-brass inline-flex items-center gap-1"><Loader2 size={11} className="animate-spin" /> clipping</span>;
}
if (status === 'skipped') return <span className="badge-warn">{REASON_TEXT[run.reason] || 'skipped'}</span>;
return <span className="badge-danger">{REASON_TEXT[run.reason] || 'failed'}</span>;
}
export default function AutopilotTab({ onOpenProject, onUpgrade, justConnected }) {
const [data, setData] = useState(null); // GET /api/autopilot
const [videos, setVideos] = useState(null); // GET /api/autopilot/videos
const [videosError, setVideosError] = useState(null);
const [loadError, setLoadError] = useState('');
const [saving, setSaving] = useState(false);
const [running, setRunning] = useState(null); // video id being submitted
const [notice, setNotice] = useState('');
// Feedback for "clip it", shown next to the list: the page-level notice sits
// at the top of the tab, off screen from the button, so a click looked dead.
const [listNotice, setListNotice] = useState('');
const [opening, setOpening] = useState(null);
const pollRef = useRef(null);
const load = useCallback(async () => {
try {
const d = await apiJson('/api/autopilot');
setData(d);
setLoadError('');
if (d.youtube) {
const v = await apiJson('/api/autopilot/videos');
setVideos(v.videos || []);
setVideosError(v.error || null);
} else {
setVideos([]);
}
} catch (e) {
setLoadError(errText(e, 'Could not load Autopilot. Please try again.'));
}
}, []);
useEffect(() => { load(); }, [load]);
// Coming back from the connect page (#app?tab=autopilot&connected=1).
useEffect(() => {
if (justConnected) {
setNotice('Accounts connected.');
track('AutopilotChannelConnected');
}
}, [justConnected]);
// Refresh while something is being clipped, so the badge flips on its own.
const busy = (data?.runs || []).some((r) => r.status === 'processing' || r.status === 'queued');
useEffect(() => {
clearInterval(pollRef.current);
if (busy) pollRef.current = setInterval(load, 20000);
return () => clearInterval(pollRef.current);
}, [busy, load]);
const save = useCallback(async (patch) => {
setSaving(true);
setNotice('');
try {
const d = await apiJson('/api/autopilot', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ timezone: browserTimezone(), ...patch }),
});
setData((prev) => ({ ...prev, settings: d.settings }));
return d.settings;
} catch (e) {
setNotice(errText(e, 'Could not save. Please try again.'));
return null;
} finally {
setSaving(false);
}
}, []);
const connect = useCallback(async () => {
track('AutopilotConnectClick');
try {
const { access_url } = await apiJson('/api/social/connect?return_to=autopilot', { method: 'POST' });
if (access_url) window.location.href = access_url;
} catch (e) {
setNotice(errText(e, 'Could not open the connection page. Please try again.'));
}
}, []);
const toggleEnabled = useCallback(async (on) => {
const s = await save(on ? { enabled: true, rights_ack: true } : { enabled: false });
if (s) {
track(on ? 'AutopilotEnabled' : 'AutopilotDisabled', { props: { autopublish: String(!!s.autopublish) } });
setNotice(on ? 'Autopilot is on. Your next video will be clipped automatically.' : 'Autopilot paused.');
}
}, [save]);
const togglePlatform = useCallback((p) => {
const cur = data?.settings?.publish_platforms || [];
const next = cur.includes(p) ? cur.filter((x) => x !== p) : [...cur, p];
save({ publish_platforms: next });
}, [data, save]);
const runNow = useCallback(async (video) => {
setRunning(video.id);
setListNotice('');
try {
const r = await apiJson('/api/autopilot/run', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ video_id: video.id }),
});
track('AutopilotManualRun', { props: { status: r.status } });
if (r.status === 'processing') setListNotice(`Clipping “${video.title || 'your video'}”. We will email you when the clips are ready.`);
else setListNotice(`Not clipped: ${REASON_TEXT[r.reason] || r.reason || r.status}.`);
} catch (e) {
if (e?.name === 'QuotaError') setListNotice('You are out of minutes for this period.');
else setListNotice(errText(e, 'Could not start the job.'));
} finally {
setRunning(null);
load();
}
}, [load]);
const openProject = useCallback(async (jobId) => {
if (!onOpenProject || opening) return;
setOpening(jobId);
try { await onOpenProject(jobId); } catch { setNotice('Could not open this project yet. Find it in History.'); }
setOpening(null);
}, [onOpenProject, opening]);
if (!data && !loadError) {
return <div className="flex justify-center py-20"><Loader2 className="animate-spin text-brass" /></div>;
}
const s = data?.settings || {};
const yt = data?.youtube;
const accounts = data?.accounts || {};
const eligible = !!data?.eligible;
const limits = data?.limits || { max_minutes_choices: [10, 20, 30, 45, 60, 90], max_clips_to_publish: 5, platforms: ['tiktok', 'instagram', 'youtube'] };
const runs = data?.runs || [];
const errorText = s.enabled && s.last_error ? ERROR_TEXT[s.last_error] : null;
return (
<div className="max-w-4xl mx-auto animate-fade">
<p className="eyebrow mb-1.5">02 · AUTOPILOT</p>
<h1 className="font-display lowercase text-3xl text-ink mb-2">your channel, clipped on its own</h1>
<p className="text-muted text-sm mb-8 max-w-2xl">
Publish on YouTube as usual. Autopilot notices every new video, turns it into shorts
and emails you when they are ready. Switch on autopublish and the best ones go out on
TikTok, Instagram and YouTube Shorts, one a day.
</p>
{loadError && <p className="text-danger text-sm mb-4">{loadError}</p>}
{notice && (
<div className="mb-6 rounded-card border border-brass/40 bg-brass/5 px-4 py-3 text-sm text-ink2">{notice}</div>
)}
{/* Plan gate: Autopilot spends minutes on its own, so it is a paid feature. */}
{!eligible && (
<div className="card p-6 mb-6">
<h3 className="font-display lowercase text-lg text-ink mb-1 flex items-center gap-2">
<Lock size={16} className="text-brass" /> included in paid plans
</h3>
<p className="text-muted text-sm mb-4">
Autopilot runs on your plan&apos;s minutes, so it comes with Starter, Creator and Pro.
Every new upload turns into shorts without you opening OpenShorts.
</p>
<button onClick={() => { track('AutopilotUpgradeClick'); onUpgrade?.(); }} className="btn-primary">
<Rocket size={16} /> choose a plan
</button>
</div>
)}
{/* 1 · channel */}
<div className="card p-6 mb-6">
<div className="flex flex-wrap items-center justify-between gap-4">
<div className="flex items-center gap-3 min-w-0">
<div className="w-10 h-10 rounded-full bg-paper3 border border-rule flex items-center justify-center shrink-0">
<Youtube size={18} className={yt ? 'text-brass' : 'text-muted'} />
</div>
<div className="min-w-0">
<p className="eyebrow">01 · CHANNEL</p>
{yt ? (
<p className="text-ink truncate">{yt.display_name || yt.handle} <span className="readout ml-1">{yt.handle}</span></p>
) : (
<p className="text-muted text-sm">no YouTube channel connected yet</p>
)}
</div>
</div>
{(!yt || yt.reauth_required) && (
<button onClick={connect} className="btn-primary" disabled={!eligible}>
<Youtube size={16} /> {yt ? 'reconnect youtube' : 'connect youtube'}
</button>
)}
{yt && !yt.reauth_required && (
<button onClick={connect} className="btn-quiet text-xs">manage accounts</button>
)}
</div>
{yt?.reauth_required && (
<p className="text-warn text-sm mt-3 flex items-center gap-2"><AlertTriangle size={14} /> YouTube needs you to reconnect this channel.</p>
)}
</div>
{/* 2 · switch */}
<div className="card p-6 mb-6">
<div className="flex items-start justify-between gap-4">
<div>
<p className="eyebrow mb-1">02 · AUTOPILOT</p>
<p className="text-ink">{s.enabled ? 'on: new videos are clipped automatically' : 'off'}</p>
<p className="text-muted text-sm mt-1">
Only videos you publish from now on. Up to {limits.daily_auto || 1} video a day, the first
{' '}{s.max_minutes || 30} minutes of each. Shorts are skipped.
</p>
{s.enabled && s.last_checked_at && (
<p className="readout mt-2 flex items-center gap-1"><Clock size={11} /> last check {fmtDate(s.last_checked_at)} · every hour</p>
)}
</div>
<Switch
label="autopilot"
checked={!!s.enabled}
disabled={saving || !eligible || !yt}
onChange={toggleEnabled}
/>
</div>
{errorText && (
<p className="text-warn text-sm mt-4 flex items-center gap-2"><AlertTriangle size={14} /> {errorText}</p>
)}
<div className="grid sm:grid-cols-2 gap-4 mt-6">
<label className="block">
<span className="eyebrow block mb-2">minutes per video</span>
<select
className="input-field"
value={s.max_minutes || 30}
disabled={saving || !eligible}
onChange={(e) => save({ max_minutes: Number(e.target.value) })}
>
{limits.max_minutes_choices.map((m) => <option key={m} value={m}>first {m} min</option>)}
</select>
</label>
</div>
</div>
{/* 3 · autopublish */}
<div className="card p-6 mb-6">
<div className="flex items-start justify-between gap-4">
<div>
<p className="eyebrow mb-1">03 · AUTOPUBLISH</p>
<p className="text-ink">{s.autopublish ? 'the best clips are scheduled for you' : 'off: you review and post the clips yourself'}</p>
<p className="text-muted text-sm mt-1">
Picks the {s.clips_to_publish || 3} highest-scoring clips of each video and schedules
them one a day at {String(s.publish_hour ?? 17).padStart(2, '0')}:00 ({s.timezone || browserTimezone()}).
</p>
</div>
<Switch
label="autopublish"
checked={!!s.autopublish}
disabled={saving || !eligible}
onChange={(on) => { track('AutopilotAutopublish', { props: { on: String(on) } }); save({ autopublish: on }); }}
/>
</div>
{s.autopublish && (
<>
<div className="mt-5">
<span className="eyebrow block mb-2">publish to</span>
<div className="flex flex-wrap gap-2">
{limits.platforms.map((p) => {
const connected = !!accounts[p];
const on = (s.publish_platforms || []).includes(p);
return connected ? (
<button
key={p}
onClick={() => togglePlatform(p)}
disabled={saving}
aria-pressed={on}
className={`px-4 py-2 rounded-full text-sm lowercase border transition-colors ${on ? 'border-brass bg-brass/10 text-ink' : 'border-rule2 text-muted hover:text-ink2'}`}
>
{on && <CheckCircle2 size={13} className="inline mr-1.5 -mt-0.5 text-brass" />}{PLATFORM_LABELS[p]}
</button>
) : (
<button key={p} onClick={connect} className="px-4 py-2 rounded-full text-sm lowercase border border-dashed border-rule2 text-muted hover:text-ink2">
+ connect {PLATFORM_LABELS[p]}
</button>
);
})}
</div>
{(s.publish_platforms || []).length === 0 && (
<p className="text-warn text-sm mt-3">Pick at least one account, or nothing gets published.</p>
)}
{(s.publish_platforms || []).includes('tiktok') && (
<p className="text-muted text-xs mt-3">TikTok clips arrive as drafts in your TikTok inbox: open the app to post them.</p>
)}
</div>
<div className="grid sm:grid-cols-2 gap-4 mt-5">
<label className="block">
<span className="eyebrow block mb-2">clips per video</span>
<select
className="input-field"
value={s.clips_to_publish || 3}
disabled={saving}
onChange={(e) => save({ clips_to_publish: Number(e.target.value) })}
>
{Array.from({ length: limits.max_clips_to_publish || 5 }, (_, i) => i + 1).map((n) => (
<option key={n} value={n}>{n} {n === 1 ? 'clip' : 'clips'} (one a day)</option>
))}
</select>
</label>
<label className="block">
<span className="eyebrow block mb-2">time of day</span>
<select
className="input-field"
value={s.publish_hour ?? 17}
disabled={saving}
onChange={(e) => save({ publish_hour: Number(e.target.value) })}
>
{Array.from({ length: 24 }, (_, h) => h).map((h) => (
<option key={h} value={h}>{String(h).padStart(2, '0')}:00</option>
))}
</select>
</label>
</div>
</>
)}
</div>
{/* 4 · channel videos */}
{yt && (
<div className="card p-6 mb-6">
<div className="flex items-center justify-between gap-3 mb-4">
<div>
<p className="eyebrow mb-1">04 · YOUR LATEST VIDEOS</p>
<p className="text-muted text-sm">Clip any of them now, or let Autopilot handle the next one.</p>
</div>
<button onClick={load} className="btn-quiet text-xs" aria-label="refresh"><RefreshCw size={13} /> refresh</button>
</div>
{listNotice && (
<div className="mb-4 rounded-card border border-brass/40 bg-brass/5 px-4 py-3 text-sm text-ink2" role="status">{listNotice}</div>
)}
{videosError && <p className="text-warn text-sm mb-3">{ERROR_TEXT[videosError] || 'Could not read your channel.'}</p>}
{videos === null && <div className="flex justify-center py-6"><Loader2 className="animate-spin text-brass" size={18} /></div>}
{videos && videos.length === 0 && !videosError && (
<p className="text-muted text-sm">No videos on this channel yet.</p>
)}
<div className="divide-y divide-rule">
{(videos || []).map((v) => {
const run = v.run;
// Skipped runs can be retried too: private videos used to be
// misread as Shorts, and a real Short just skips again.
const canRun = eligible && (!run || run.status === 'failed' || run.status === 'skipped');
return (
<div key={v.id} className="flex items-center gap-3 py-3">
{v.thumbnail_url ? (
<img src={v.thumbnail_url} alt="" className="w-20 sm:w-24 h-[45px] sm:h-[54px] object-cover rounded-input border border-rule shrink-0" loading="lazy" />
) : (
<div className="w-20 sm:w-24 h-[45px] sm:h-[54px] rounded-input bg-paper3 shrink-0" />
)}
<div className="min-w-0 flex-1">
<a href={v.url} target="_blank" rel="noopener noreferrer" className="text-sm text-ink2 hover:text-ink line-clamp-2">
{v.title || v.id} <ExternalLink size={11} className="inline -mt-0.5 text-muted" />
</a>
<div className="flex flex-wrap items-center gap-2 mt-1">
<span className="readout">{fmtDate(v.published_at)}</span>
<StatusBadge run={run} />
</div>
</div>
{run?.status === 'completed' && run.job_id ? (
<button onClick={() => openProject(run.job_id)} className="btn-quiet text-xs shrink-0" disabled={opening === run.job_id}>
{opening === run.job_id ? <Loader2 size={13} className="animate-spin" /> : <FolderOpen size={13} />} open
</button>
) : canRun ? (
<button onClick={() => runNow(v)} className="btn-ghost px-4 py-2 text-xs shrink-0" disabled={!!running}>
{running === v.id ? <Loader2 size={13} className="animate-spin" /> : <Scissors size={13} />} clip it
</button>
) : null}
</div>
);
})}
</div>
</div>
)}
{/* 5 · activity */}
{runs.length > 0 && (
<div className="card p-6 mb-10">
<p className="eyebrow mb-4">05 · ACTIVITY</p>
<div className="space-y-3">
{runs.map((r) => (
<div key={r.id} className="flex items-center gap-3 text-sm">
{r.status === 'completed' ? <CheckCircle2 size={15} className="text-ok shrink-0" />
: (r.status === 'processing' || r.status === 'queued') ? <Loader2 size={15} className="animate-spin text-brass shrink-0" />
: r.status === 'skipped' ? <Play size={15} className="text-muted shrink-0" />
: <AlertTriangle size={15} className="text-danger shrink-0" />}
<span className="text-ink2 truncate flex-1">{r.video_title || r.video_id}</span>
{r.posted_count ? <span className="readout hidden sm:inline-flex items-center gap-1"><Send size={11} /> {r.posted_count} scheduled</span> : null}
<span className="readout shrink-0">{r.trigger === 'manual' ? 'manual' : 'auto'} · {fmtDate(r.created_at)}</span>
</div>
))}
</div>
</div>
)}
</div>
);
}

View file

@ -16,7 +16,7 @@ const TOUR = [
{
target: '[data-tutorial="drop-zone"]',
title: 'Your video',
body: 'Click the box or paste the link here. Keep files under 500MB.',
body: 'Click the box or paste the link here. File size is limited only by your server and proxy.',
},
{
target: '[data-tutorial="output-format"]',

View file

@ -1,148 +0,0 @@
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { AlertCircle, Loader2 } from 'lucide-react';
import { getApiUrl } from '../config';
import GalleryCard from './GalleryCard';
const CLIPS_PER_PAGE = 20;
export default function Gallery() {
const [clips, setClips] = useState([]);
const [loading, setLoading] = useState(true);
const [loadingMore, setLoadingMore] = useState(false);
const [error, setError] = useState(null);
const [hasMore, setHasMore] = useState(true);
const [offset, setOffset] = useState(0);
const loaderRef = useRef(null);
const fetchClips = useCallback(async (currentOffset = 0, append = false) => {
try {
if (currentOffset === 0) setLoading(true);
else setLoadingMore(true);
const res = await fetch(
getApiUrl(`/api/gallery/clips?limit=${CLIPS_PER_PAGE}&offset=${currentOffset}`)
);
if (!res.ok) throw new Error('Failed to fetch clips');
const data = await res.json();
const newClips = data.clips || [];
if (append) {
setClips(prev => [...prev, ...newClips]);
} else {
setClips(newClips);
}
setHasMore(data.has_more ?? newClips.length === CLIPS_PER_PAGE);
setOffset(currentOffset + newClips.length);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
setLoadingMore(false);
}
}, []);
// Initial load
useEffect(() => {
fetchClips(0, false);
}, [fetchClips]);
// Infinite scroll observer
useEffect(() => {
if (!hasMore || loadingMore || loading) return;
const observer = new IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting && hasMore && !loadingMore) {
fetchClips(offset, true);
}
},
{ rootMargin: '200px', threshold: 0.1 }
);
const node = loaderRef.current;
if (node) {
observer.observe(node);
}
return () => {
if (node) {
observer.unobserve(node);
}
};
}, [hasMore, loadingMore, loading, offset, fetchClips]);
if (loading) {
return (
<div className="h-full flex flex-col items-center justify-center text-muted animate-fade">
<Loader2 size={32} className="animate-spin mb-4 text-brass" />
<p className="lowercase">Loading your viral history...</p>
</div>
);
}
if (error) {
return (
<div className="h-full flex flex-col items-center justify-center text-danger p-6">
<AlertCircle size={32} className="mb-4" />
<p>Error loading gallery: {error}</p>
<button
onClick={() => {
setError(null);
setOffset(0);
fetchClips(0, false);
}}
className="btn-quiet mt-4"
>
Retry
</button>
</div>
);
}
return (
<div className="h-full overflow-y-auto p-6 md:p-8 animate-fade">
<div className="flex items-end justify-between mb-8">
<div>
<p className="eyebrow mb-1.5">Library</p>
<h1 className="font-display lowercase text-2xl text-ink">Clip Gallery</h1>
</div>
<span className="readout">
{clips.length} {clips.length === 1 ? 'Clip' : 'Clips'}{hasMore ? '+' : ''}
</span>
</div>
{clips.length === 0 ? (
<div className="text-center py-20 text-muted">
<p className="text-lg mb-2 lowercase">No clips found yet.</p>
<p className="text-sm lowercase">Process some videos to populate your gallery!</p>
</div>
) : (
<>
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4 gap-6 pb-10">
{clips.map((clip) => (
<GalleryCard key={`${clip.job_id}-${clip.index}`} clip={clip} />
))}
</div>
{/* Infinite scroll loader trigger */}
{hasMore && (
<div
ref={loaderRef}
className="flex justify-center py-8"
>
{loadingMore && (
<div className="flex items-center gap-2 text-muted">
<Loader2 size={20} className="animate-spin" />
<span className="text-sm lowercase">Loading more clips...</span>
</div>
)}
</div>
)}
</>
)}
</div>
);
}

View file

@ -1,151 +0,0 @@
import React, { useRef, useState, useEffect } from 'react';
import { Download, Copy, Check, Play } from 'lucide-react';
export default function GalleryCard({ clip }) {
const [copied, setCopied] = useState(null);
const [isVisible, setIsVisible] = useState(false);
const [_hasLoaded, setHasLoaded] = useState(false);
const cardRef = useRef(null);
const videoRef = useRef(null);
// Lazy loading with IntersectionObserver
useEffect(() => {
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
setIsVisible(true);
// Once loaded, we don't need to observe anymore
observer.unobserve(entry.target);
}
});
},
{
rootMargin: '200px', // Start loading 200px before entering viewport
threshold: 0.1
}
);
const node = cardRef.current;
if (node) {
observer.observe(node);
}
return () => {
if (node) {
observer.unobserve(node);
}
};
}, []);
const handleCopy = (text, field) => {
navigator.clipboard.writeText(text);
setCopied(field);
setTimeout(() => setCopied(null), 2000);
};
const handleDownload = async (e) => {
e.preventDefault();
try {
const response = await fetch(clip.url);
if (!response.ok) throw new Error('Download failed');
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = `clip_${clip.job_id}_${clip.index + 1}.mp4`;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
} catch (err) {
console.error('Download error:', err);
window.open(clip.url, '_blank');
}
};
return (
<div
ref={cardRef}
className="card card-hover overflow-hidden flex flex-col group animate-fade"
>
{/* Video Player - Lazy loaded */}
<div className="aspect-[9/16] bg-black relative group/video">
{isVisible ? (
<video
ref={videoRef}
src={clip.url}
controls
className="w-full h-full object-cover"
playsInline
preload="metadata"
onLoadedData={() => setHasLoaded(true)}
/>
) : (
<div className="w-full h-full flex items-center justify-center bg-paper">
<div className="w-12 h-12 rounded-full bg-paper3 flex items-center justify-center">
<Play size={24} className="text-muted ml-1" />
</div>
</div>
)}
<div className="absolute top-2 left-2">
<span className="readout bg-black/70 px-2 py-1 rounded-full">
{new Date(clip.created_at).toLocaleDateString()}
</span>
</div>
</div>
{/* Content & Details */}
<div className="flex-1 p-4 flex flex-col min-w-0">
<div className="mb-3">
<h3 className="text-sm font-semibold text-ink leading-tight line-clamp-2 mb-2 break-words" title={clip.title}>
{clip.title}
</h3>
<div className="flex flex-wrap gap-2">
<span className="readout bg-paper3 px-1.5 py-0.5 rounded-full">{clip.duration.toFixed(1)}s</span>
<span className="readout bg-paper3 px-1.5 py-0.5 rounded-full truncate max-w-[150px]" title={clip.job_id}>ID: {clip.job_id.substring(0, 8)}</span>
</div>
</div>
<div className="space-y-2 flex-1 overflow-y-auto custom-scrollbar max-h-[150px] pr-1 mb-3">
{/* YouTube Title */}
<div className="bg-paper rounded-input p-2 relative group/item">
<p className="eyebrow mb-1">YouTube Title</p>
<p className="text-xs text-ink2 select-all line-clamp-2 hover:line-clamp-none transition-all">{clip.title}</p>
<button
onClick={() => handleCopy(clip.title, 'yt')}
className="absolute top-2 right-2 p-1 text-muted hover:text-brass transition-colors opacity-0 group-hover/item:opacity-100"
title="Copy Title"
>
{copied === 'yt' ? <Check size={12} className="text-ok" /> : <Copy size={12} />}
</button>
</div>
{/* TikTok / IG Caption */}
<div className="bg-paper rounded-input p-2 relative group/item">
<p className="eyebrow mb-1">TikTok · IG Caption</p>
<p className="text-xs text-ink2 select-all line-clamp-3 hover:line-clamp-none transition-all cursor-pointer">
{clip.tiktok_desc || clip.insta_desc}
</p>
<button
onClick={() => handleCopy(clip.tiktok_desc || clip.insta_desc, 'caption')}
className="absolute top-2 right-2 p-1 text-muted hover:text-brass transition-colors opacity-0 group-hover/item:opacity-100"
title="Copy Caption"
>
{copied === 'caption' ? <Check size={12} className="text-ok" /> : <Copy size={12} />}
</button>
</div>
</div>
{/* Footer Action */}
<button
onClick={handleDownload}
className="btn-quiet w-full"
>
<Download size={14} className="shrink-0" /> Download Clip
</button>
</div>
</div>
);
}

View file

@ -56,7 +56,7 @@ export default function HistoryTab({ onReopenProject }) {
return (
<div className="h-full overflow-y-auto p-8 max-w-5xl mx-auto animate-fade">
<p className="eyebrow mb-1.5">07 · HISTORY</p>
<p className="eyebrow mb-1.5">03 · HISTORY</p>
<h1 className="font-display lowercase text-2xl text-ink mb-2">Your library</h1>
<p className="text-muted text-sm mb-8 lowercase">
All the shorts you've generated, saved while your plan is active. Kept for 7 days after your plan ends. Reopen a project to keep editing its clips.

View file

@ -1,140 +0,0 @@
import React, { useState, useCallback } from 'react';
import { Plug, Copy, Check } from 'lucide-react';
import { getApiUrl } from '../config';
// "Connect an agent": the one place that tells a person how to drive
// OpenShorts from Claude, ChatGPT, Cursor or n8n. Cloud accounts connect by
// URL (claude.ai and ChatGPT run the OAuth flow themselves; CLI clients take
// an API key); a self-hosted install has no auth, so every snippet is the
// local URL and nothing else.
const CLOUD_MCP_URL = 'https://mcp.openshorts.app/mcp';
// The self-hosted dashboard proxies /api and /videos to the backend but not
// /mcp (neither the Vite dev proxy nor nginx.conf), so an MCP client must
// talk to the API container itself: VITE_API_URL when it is set, otherwise
// the backend's default port on the same host.
function localMcpUrl() {
const u = getApiUrl('/mcp');
if (u.startsWith('http')) return u;
try { return `${window.location.protocol}//${window.location.hostname}:8000/mcp`; } catch { return 'http://localhost:8000/mcp'; }
}
function buildClients({ cloud, url }) {
const key = cloud ? 'osk_YOUR_KEY' : null;
const header = key ? ` \\\n --header "Authorization: Bearer ${key}"` : '';
const desktopArgs = key
? `["-y", "mcp-remote", "${url}", "--header", "Authorization: Bearer ${key}"]`
: `["-y", "mcp-remote", "${url}"]`;
const cursorHeaders = key ? `,\n "headers": { "Authorization": "Bearer ${key}" }` : '';
return [
cloud && {
id: 'claude-ai', label: 'Claude (claude.ai)', kind: 'steps',
steps: [
'Open claude.ai → Settings → Connectors → Add custom connector.',
`Paste this URL and save: ${url}`,
'Click Connect: you will land on OpenShorts to approve the access, then the 8 tools appear in every chat.',
],
snippet: url,
},
cloud && {
id: 'chatgpt', label: 'ChatGPT', kind: 'steps',
steps: [
'Open ChatGPT → Settings → Connectors → Create (developer mode).',
`Name it OpenShorts, paste this MCP server URL, choose OAuth: ${url}`,
'Approve the access on OpenShorts when asked. Done: ask ChatGPT to clip a video.',
],
snippet: url,
},
{
id: 'claude-code', label: 'Claude Code', kind: 'code', lang: 'bash',
snippet: `claude mcp add --transport http openshorts ${url}${header}`,
note: cloud ? 'Create a key below and paste it in place of osk_YOUR_KEY.' : 'No key needed on a self-hosted install.',
},
{
id: 'claude-desktop', label: 'Claude Desktop', kind: 'code', lang: 'json',
snippet: `{\n "mcpServers": {\n "openshorts": {\n "command": "npx",\n "args": ${desktopArgs}\n }\n }\n}`,
note: 'Settings → Developer → Edit config (claude_desktop_config.json), then restart Claude.',
},
{
id: 'cursor', label: 'Cursor', kind: 'code', lang: 'json',
snippet: `{\n "mcpServers": {\n "openshorts": {\n "url": "${url}"${cursorHeaders}\n }\n }\n}`,
note: 'Settings → MCP → Add new global MCP server (.cursor/mcp.json).',
},
{
id: 'n8n', label: 'n8n', kind: 'steps',
steps: [
'Add an "MCP Client Tool" node to your AI Agent.',
`Endpoint: ${url} · Transport: HTTP Streamable.`,
cloud ? 'Authentication: Bearer, with a key from below.' : 'Authentication: none.',
],
snippet: url,
},
{
id: 'curl', label: 'curl', kind: 'code', lang: 'bash',
snippet: `curl -X POST ${url} \\\n -H "Content-Type: application/json"${key ? ` \\\n -H "Authorization: Bearer ${key}"` : ''} \\\n -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'`,
note: 'Plain JSON-RPC over HTTP: the same endpoint every client above talks to.',
},
].filter(Boolean);
}
export default function McpConnectCard({ cloud = true, compact = false }) {
const url = cloud ? CLOUD_MCP_URL : localMcpUrl();
const clients = buildClients({ cloud, url });
const [active, setActive] = useState(clients[0].id);
const [copied, setCopied] = useState(false);
const current = clients.find((c) => c.id === active) || clients[0];
const copy = useCallback(() => {
navigator.clipboard?.writeText(current.snippet).then(() => {
setCopied(true);
setTimeout(() => setCopied(false), 1600);
}).catch(() => {});
}, [current]);
return (
<div className="card p-6" id="connect-agent">
<h3 className="font-display lowercase text-lg text-ink mb-1 flex items-center gap-2">
<Plug size={16} className="text-brass" /> Connect an agent
</h3>
<p className="text-muted text-sm mb-4">
Let Claude, ChatGPT, Cursor or n8n clip and publish for you through the built-in MCP server:
8 tools (process a video or upload one, check a job, list clips, add subtitles, recut, publish, quota).
{cloud
? ' claude.ai and ChatGPT connect with one URL and a sign-in; CLI clients use an API key.'
: ' This install runs without accounts, so no key is needed.'}
</p>
<div className="flex flex-wrap gap-1.5 mb-4" role="tablist" aria-label="client">
{clients.map((c) => (
<button
key={c.id}
role="tab"
aria-selected={c.id === active}
onClick={() => { setActive(c.id); setCopied(false); }}
className={`px-3 py-1.5 rounded-input text-xs border transition-colors ${
c.id === active ? 'border-brass text-ink bg-brass/10' : 'border-rule text-muted hover:text-ink'}`}
>
{c.label}
</button>
))}
</div>
{current.kind === 'steps' && (
<ol className="list-decimal pl-5 space-y-1.5 text-sm text-ink2 mb-3">
{current.steps.map((s) => <li key={s}>{s}</li>)}
</ol>
)}
<div className="relative">
<pre className={`font-mono text-ink2 whitespace-pre-wrap break-all rounded-card border border-rule bg-paper p-3 pr-20 text-xs ${compact ? '' : 'leading-relaxed'}`}>
{current.snippet}
</pre>
<button onClick={copy} className="btn-ghost absolute top-2 right-2 px-2.5 py-1 text-xs" aria-label="copy">
{copied ? <Check size={13} /> : <Copy size={13} />} {copied ? 'Copied' : 'Copy'}
</button>
</div>
{current.note && <p className="text-muted text-xs mt-2">{current.note}</p>}
</div>
);
}

View file

@ -248,7 +248,8 @@ export default function MediaInput({ onProcess, isProcessing }) {
/>
<Upload className="mx-auto mb-3 text-muted" size={18} />
<p className="text-ink2 lowercase">Click to upload or drag and drop</p>
<p className="readout mt-2">MP4, MOV up to 500MB · at least {MIN_SOURCE_SECONDS}s long</p>
<p className="readout mt-2">MP4, MOV · at least {MIN_SOURCE_SECONDS}s long</p>
<p className="text-muted text-xs mt-1 lowercase">file size is limited only by your server and proxy</p>
</label>
)}
</div>

View file

@ -21,8 +21,8 @@ const SOURCES = [
const GOALS = [
['clips_from_long_videos', 'Clips from my long videos'],
['ai_avatar_videos', 'AI avatar / UGC videos'],
['autopilot_posting', 'Auto-posting to my socials'],
['ai_avatar_videos', 'Clip long videos into shorts'],
['autopilot_posting', 'Publish to my socials'],
['thumbnails', 'YouTube titles & thumbnails'],
['subtitles', 'Subtitles'],
['dubbing', 'Dubbing into other languages'],

View file

@ -19,13 +19,13 @@ const HOSTED_VS_SELF = [
icon: KeyRound,
label: 'API keys',
hosted: 'The Gemini key is included. Nothing to create, paste or top up.',
self: 'You create and pay for your own Gemini key, plus ElevenLabs and fal.ai for dubbing and AI Shorts.',
self: 'You create and pay for your own Gemini key, plus ElevenLabs for dubbing.',
},
{
icon: Send,
label: 'Auto-posting',
hosted: 'TikTok, Instagram Reels and YouTube Shorts connect straight from your account.',
self: 'You register your own Upload-Post account and wire up the credentials.',
hosted: 'Clips publish to TikTok, Instagram Reels and YouTube Shorts through Postiz.',
self: 'You run your own Postiz instance and connect the credentials there.',
},
{
icon: Server,
@ -45,7 +45,7 @@ const HOSTED_VS_SELF = [
const FAQS = [
{
question: "Is OpenShorts really free? What's the catch?",
answer: "There is no catch, but there are two different things on offer. (1) Self-hosted is 100% free and open source: you run it with Docker on your own machine, bring your own API keys, and there are no watermarks, no usage limits and no subscription. What it costs you is hardware and time. On a typical CPU an 8-minute video takes 5 to 8 minutes to process, and you need your own Google Gemini key (required, free tier is 1,500 requests/day), plus ElevenLabs for dubbing and fal.ai for AI Shorts if you want those. (2) Hosted at openshorts.app is the same software with the running costs covered: our NVIDIA GPU clips that same 8-minute video in about 50 seconds, the Gemini key is included so there is nothing to create or paste, auto-posting to TikTok, Instagram and YouTube is already wired up, and your clips are stored and re-openable from any browser. It has a free plan (20 minutes a month, watermark, no credit card) and paid plans from $12/mo for 100 minutes without watermark. So: free if you are happy to run it yourself, paid if you would rather it just ran fast. Both are far cheaper than Opus Clip ($15-228/month) or Kapwing ($24-79/month)."
answer: "There is no catch, but there are two different things on offer. (1) Self-hosted is 100% free and open source: you run it with Docker on your own machine, bring your own API keys, and there are no watermarks, no usage limits and no subscription. What it costs you is hardware and time. On a typical CPU an 8-minute video takes 5 to 8 minutes to process, and you need your own Google Gemini key (required, free tier is 1,500 requests/day), plus ElevenLabs for dubbing if you want it. (2) Hosted at openshorts.app is the same software with the running costs covered: our NVIDIA GPU clips that same 8-minute video in about 50 seconds, the Gemini key is included so there is nothing to create or paste, and your clips are stored and re-openable from any browser. It has a free plan (20 minutes a month, watermark, no credit card) and paid plans from $12/mo for 100 minutes without watermark. So: free if you are happy to run it yourself, paid if you would rather it just ran fast. Both are far cheaper than Opus Clip ($15-228/month) or Kapwing ($24-79/month)."
},
{
question: "How does OpenShorts compare to Opus Clip?",
@ -60,12 +60,8 @@ const FAQS = [
answer: "Yes — OpenShorts is a 100% free, open source clip generator. Unlike paid clip generators like Opus Clip ($15-228/month) or Kapwing ($24-79/month), OpenShorts lets you generate unlimited clips with no watermarks, no usage limits, and no subscription fees. It also includes a free AI YouTube thumbnail generator, free AI YouTube title generator, and free AI YouTube description generator — features that other clip generators charge extra for. You self-host it with Docker on your own machine for full privacy and control."
},
{
question: "How much does it cost to generate an AI UGC video?",
answer: "OpenShorts itself is free, but the AI Shorts feature uses external APIs (fal.ai for video generation, ElevenLabs for voiceover) that charge per use. Low Cost mode costs approximately $0.65 per video (Flux image $0.05 + ElevenLabs voice $0.10 + Hailuo img2video $0.19 + VEED Lipsync $0.20 + b-roll $0.10). Premium mode costs approximately $2.00 per video using Kling Avatar v2 for higher quality. Both modes are significantly cheaper than hiring UGC creators ($50-500 per video) or using platforms like HeyGen ($24-180/month)."
},
{
question: "Does API and MCP access cost extra?",
answer: "No. Every plan, including the free one, can create API keys in the account page and use the REST API and the MCP server at mcp.openshorts.app/mcp. Calls draw from the same monthly minutes as the dashboard, so automating with Claude, ChatGPT or n8n does not change the price of anything. The value of the hosted endpoint is that it is always on: an agent or a scheduled pipeline can clip and publish while your own machine is off, which is the one thing the self-hosted edition cannot do for you. Full guide at openshorts.app/mcp."
question: "Does API access cost extra?",
answer: "No. Every plan, including the free one, can create API keys in the account page and use the REST API. Calls draw from the same monthly minutes as the dashboard, so automating with a script or an n8n workflow does not change the price of anything. Clips publish to TikTok, Instagram or YouTube through a self-hosted Postiz instance. Full guide at openshorts.app/automate-shorts-api."
},
{
question: "What are the system requirements to run OpenShorts?",

View file

@ -1,5 +1,5 @@
import React, { useState, useEffect } from 'react';
import { Check, Loader2, Zap, Cpu, KeyRound, Send, HardDrive, Bot } from 'lucide-react';
import { Check, Loader2, Zap, Cpu, KeyRound, Send, HardDrive } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import { apiJson } from '../lib/api';
import { track } from '../lib/analytics';
@ -132,8 +132,8 @@ export default function PricingSection({ onRequireLogin }) {
<li className="flex items-start gap-2"><Check size={16} className="text-ok shrink-0 mt-0.5" /> <span><b>{entry.minutes} min</b> of video / month</span></li>
<li className="flex items-start gap-2"><Check size={16} className="text-ok shrink-0 mt-0.5" /> <span><b>No watermark</b>, no 7-day clip expiry</span></li>
<li className="flex items-start gap-2"><Cpu size={16} className="text-ok shrink-0 mt-0.5" /> <span><b>GPU rendering</b>, about 50s per 8-min video</span></li>
<li className="flex items-start gap-2"><KeyRound size={16} className="text-ok shrink-0 mt-0.5" /> <span>Gemini key + auto-posting included</span></li>
<li className="flex items-start gap-2"><Bot size={16} className="text-ok shrink-0 mt-0.5" /> <span><b>MCP + API access</b> for AI agents &amp; automations</span></li>
<li className="flex items-start gap-2"><KeyRound size={16} className="text-ok shrink-0 mt-0.5" /> <span>Gemini key + Postiz publishing included</span></li>
<li className="flex items-start gap-2"><Check size={16} className="text-ok shrink-0 mt-0.5" /> <span><b>REST API access</b> for automations</span></li>
{plan === 'pro' && <li className="flex items-start gap-2"><Zap size={16} className="text-brass shrink-0 mt-0.5" /> <span>Priority processing queue</span></li>}
</ul>
<button
@ -158,10 +158,10 @@ export default function PricingSection({ onRequireLogin }) {
<ul className="space-y-2 text-sm text-ink2">
<li className="flex items-start gap-2"><Cpu size={15} className="text-ok shrink-0 mt-0.5" /> <span><b>Our NVIDIA GPU does the rendering.</b> An 8-minute video is clipped in about 50 seconds, instead of the 5 to 8 minutes it takes on a typical CPU.</span></li>
<li className="flex items-start gap-2"><KeyRound size={15} className="text-ok shrink-0 mt-0.5" /> <span><b>The Gemini API key is included.</b> Nothing to sign up for, nothing to paste, no per-request quota of your own to babysit.</span></li>
<li className="flex items-start gap-2"><Send size={15} className="text-ok shrink-0 mt-0.5" /> <span><b>Auto-posting is already wired up</b> for TikTok, Instagram Reels and YouTube Shorts.</span></li>
<li className="flex items-start gap-2"><Send size={15} className="text-ok shrink-0 mt-0.5" /> <span><b>Publishing is wired up</b> for TikTok, Instagram Reels and YouTube Shorts through your Postiz instance.</span></li>
<li className="flex items-start gap-2"><HardDrive size={15} className="text-ok shrink-0 mt-0.5" /> <span><b>Clips are stored and served for you</b>, ready to re-open and re-edit from any browser.</span></li>
<li className="flex items-start gap-2"><Check size={15} className="text-ok shrink-0 mt-0.5" /> <span>Full <b>YouTube Studio</b>: titles, thumbnails and descriptions.</span></li>
<li className="flex items-start gap-2"><Bot size={15} className="text-ok shrink-0 mt-0.5" /> <span><b>MCP server &amp; API for agents.</b> Connect Claude, ChatGPT or n8n to an always-on endpoint and automate clipping end to end. API calls use the same minutes, nothing extra to buy. <a href="/mcp" className="underline underline-offset-2 hover:text-ink" target="_blank" rel="noopener">Guide</a>.</span></li>
<li className="flex items-start gap-2"><Check size={15} className="text-ok shrink-0 mt-0.5" /> <span><b>REST API for automations.</b> Drive the pipeline from a script or an n8n workflow. API calls use the same minutes, nothing extra to buy. <a href="/automate-shorts-api" className="underline underline-offset-2 hover:text-ink" target="_blank" rel="noopener">Guide</a>.</span></li>
</ul>
<p className="text-xs text-muted mt-3 pt-3 border-t border-rule">
Your monthly minutes cover video processing. Titles &amp; descriptions are free;
@ -173,9 +173,9 @@ export default function PricingSection({ onRequireLogin }) {
<span className="badge-warn"><Zap size={12} /> Bring your own key</span>
</div>
<p className="text-sm text-muted mb-3 leading-relaxed">
<b className="text-ink2">AI Shorts</b> (AI-actor UGC videos) and <b className="text-ink2">voice dubbing</b> use premium generation from
<b className="text-ink2"> fal.ai</b> and <b className="text-ink2">ElevenLabs</b>. Connect your own keys for those — you're billed by those
providers directly (typically ~$0.65-2 per video). Your plan still covers the script &amp; orchestration.
<b className="text-ink2">Voice dubbing</b> uses premium generation from
<b className="text-ink2"> ElevenLabs</b>. Connect your own key for it — you're billed by that
provider directly. Your plan still covers the script &amp; orchestration.
</p>
<p className="text-xs text-muted">Managed credits for these are coming later — no keys needed.</p>
</div>

View file

@ -8,7 +8,6 @@ import TranslateModal from './TranslateModal';
import Modal from './ui/Modal';
import SegmentedControl from './ui/SegmentedControl';
import WatermarkModal, { watermarkNoticeDismissed } from './WatermarkModal';
import TikTokDraftNotice from './TikTokDraftNotice';
import { useAuth } from '../contexts/AuthContext';
import { renderInBrowser } from '../lib/renderInBrowser';
@ -36,7 +35,7 @@ function formatDuration(clip) {
return `${String(Math.floor(secs / 60)).padStart(2, '0')}:${String(secs % 60).padStart(2, '0')}`;
}
export default function ResultCard({ clip, index, jobId, durable, uploadPostKey, uploadUserId, geminiApiKey, elevenLabsKey, isManaged, onPlay, onPause, onBulkSubtitle, clipCount = 1, bulkProgress, initialState = null, onStateChange, connectedPlatforms = null, onConnectSocials, onEditClip = null, onReframeClip = null, onUpgrade = null }) {
export default function ResultCard({ clip, index, jobId, durable, postizKey, postizUrl, geminiApiKey, elevenLabsKey, isManaged, onPlay, onPause, onBulkSubtitle, clipCount = 1, bulkProgress, initialState = null, onStateChange, connectedPlatforms = null, onConnectSocials, onEditClip = null, onReframeClip = null, onUpgrade = null }) {
const [showModal, setShowModal] = useState(false);
// The "why" line is clamped to two lines so cards in a row stay level;
// when it overflows, a hover (desktop) or tap (touch) shows the whole
@ -266,7 +265,7 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey,
const handleConnectAccounts = () => {
setShowModal(false);
if (onConnectSocials) onConnectSocials();
else window.open('https://app.upload-post.com', '_blank', 'noopener');
else window.open(postizUrl || 'https://postiz.pbento.pt', '_blank', 'noopener');
};
// Initialize/Reset form when modal opens
@ -664,11 +663,11 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey,
};
// Managed (cloud plan/trial) users post with the server-side key — no BYOK needed
const canPost = isManaged || (uploadPostKey && uploadUserId);
const canPost = isManaged || !!postizKey;
const handlePost = async () => {
if (!canPost) {
setPostResult({ success: false, msg: "Missing API Key or User ID." });
setPostResult({ success: false, msg: "Postiz is not configured. Add your base URL and API key in Settings." });
return;
}
@ -695,8 +694,6 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey,
const payload = {
job_id: jobId,
clip_index: index,
api_key: uploadPostKey,
user_id: uploadUserId,
platforms: selectedPlatforms,
title: postTitle,
description: postDescription
@ -705,13 +702,16 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey,
if (isScheduling && scheduleDate) {
// Convert to ISO-8601
payload.scheduled_date = new Date(scheduleDate).toISOString();
// Optional: pass timezone if needed, backend defaults to UTC or we can send user's timezone
payload.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
}
const res = await apiFetch('/api/social/post', {
const headers = { 'Content-Type': 'application/json' };
if (postizKey) headers['X-Postiz-Key'] = postizKey;
if (postizUrl) headers['X-Postiz-Url'] = postizUrl.replace(/\/$/, '');
const res = await apiFetch('/api/postiz/post', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
headers,
body: JSON.stringify(payload)
});
@ -1067,22 +1067,17 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey,
{!canPost && (
<div className="mb-4 px-3 py-2 rounded-input text-xs text-warn bg-[color-mix(in_oklab,var(--color-warn)_10%,transparent)] flex items-start gap-2">
<AlertCircle size={14} className="mt-0.5 shrink-0" />
<div className="lowercase">configure api key in settings first.</div>
<div className="lowercase">configure Postiz in settings first.</div>
</div>
)}
{noAccountsConnected && (
<div className="mb-4 px-3 py-2 rounded-input text-xs text-warn bg-[color-mix(in_oklab,var(--color-warn)_10%,transparent)] flex items-start gap-2">
<AlertCircle size={14} className="mt-0.5 shrink-0" />
<div className="lowercase">no social accounts connected yet — link tiktok, instagram or youtube to publish this clip.</div>
<div className="lowercase">no social accounts connected yet — link tiktok, instagram or youtube in Postiz to publish this clip.</div>
</div>
)}
{/* Both the title/description fields below and the schedule
button are downstream of this: on a tiktok draft neither
travels. See TikTokDraftNotice. */}
{platforms.tiktok && <TikTokDraftNotice />}
<div className="space-y-4">
{/* Title & Description */}
<div>

File diff suppressed because it is too large Load diff

View file

@ -1,371 +0,0 @@
import React, { useState, useMemo } from 'react';
import { Loader2, Calendar, CheckCircle, AlertCircle, Video, Instagram, Youtube, ChevronLeft, ChevronRight, Circle, ExternalLink } from 'lucide-react';
import { apiFetch } from '../lib/api';
import Modal from './ui/Modal';
import SegmentedControl from './ui/SegmentedControl';
import TikTokDraftNotice from './TikTokDraftNotice';
const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const TIMEZONES = [
{ value: 'Pacific/Midway', label: '(GMT-11:00) Midway' },
{ value: 'Pacific/Honolulu', label: '(GMT-10:00) Honolulu' },
{ value: 'America/Anchorage', label: '(GMT-09:00) Alaska' },
{ value: 'America/Los_Angeles', label: '(GMT-08:00) Los Angeles' },
{ value: 'America/Denver', label: '(GMT-07:00) Denver' },
{ value: 'America/Mexico_City', label: '(GMT-06:00) Mexico City' },
{ value: 'America/Chicago', label: '(GMT-06:00) Chicago' },
{ value: 'America/New_York', label: '(GMT-05:00) New York' },
{ value: 'America/Bogota', label: '(GMT-05:00) Bogota' },
{ value: 'America/Caracas', label: '(GMT-04:00) Caracas' },
{ value: 'America/Santiago', label: '(GMT-04:00) Santiago' },
{ value: 'America/Argentina/Buenos_Aires', label: '(GMT-03:00) Buenos Aires' },
{ value: 'America/Sao_Paulo', label: '(GMT-03:00) Sao Paulo' },
{ value: 'Atlantic/Azores', label: '(GMT-01:00) Azores' },
{ value: 'UTC', label: '(GMT+00:00) UTC' },
{ value: 'Europe/London', label: '(GMT+00:00) London' },
{ value: 'Europe/Madrid', label: '(GMT+01:00) Madrid' },
{ value: 'Europe/Paris', label: '(GMT+01:00) Paris' },
{ value: 'Europe/Berlin', label: '(GMT+01:00) Berlin' },
{ value: 'Europe/Rome', label: '(GMT+01:00) Rome' },
{ value: 'Africa/Lagos', label: '(GMT+01:00) Lagos' },
{ value: 'Europe/Istanbul', label: '(GMT+03:00) Istanbul' },
{ value: 'Asia/Dubai', label: '(GMT+04:00) Dubai' },
{ value: 'Asia/Kolkata', label: '(GMT+05:30) India' },
{ value: 'Asia/Bangkok', label: '(GMT+07:00) Bangkok' },
{ value: 'Asia/Shanghai', label: '(GMT+08:00) Shanghai' },
{ value: 'Asia/Tokyo', label: '(GMT+09:00) Tokyo' },
{ value: 'Australia/Sydney', label: '(GMT+10:00) Sydney' },
{ value: 'Pacific/Auckland', label: '(GMT+12:00) Auckland' },
];
const PLATFORM_OPTIONS = [
{ value: 'tiktok', label: 'TikTok', icon: <Video size={16} /> },
{ value: 'instagram', label: 'Instagram', icon: <Instagram size={16} /> },
{ value: 'youtube', label: 'YouTube', icon: <Youtube size={16} /> },
];
function getDayLabel(date) {
const today = new Date();
today.setHours(0, 0, 0, 0);
const tomorrow = new Date(today);
tomorrow.setDate(tomorrow.getDate() + 1);
const target = new Date(date);
target.setHours(0, 0, 0, 0);
if (target.getTime() === today.getTime()) return 'Today';
if (target.getTime() === tomorrow.getTime()) return 'Tomorrow';
return DAYS[target.getDay()];
}
function formatDate(date) {
return `${MONTHS[date.getMonth()]} ${date.getDate()}`;
}
function detectTimezone() {
try {
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
if (TIMEZONES.find(t => t.value === tz)) return tz;
return 'UTC';
} catch {
return 'UTC';
}
}
export default function ScheduleWeekModal({ isOpen, onClose, clips, jobId, uploadPostKey, uploadUserId, isManaged }) {
const [time, setTime] = useState('12:00');
const [timezone, setTimezone] = useState(detectTimezone);
const [platforms, setPlatforms] = useState({
tiktok: true,
instagram: true,
youtube: true
});
const [startOffset, setStartOffset] = useState(1);
const schedule = useMemo(() => {
if (!clips) return [];
return clips.map((clip, i) => {
const date = new Date();
date.setDate(date.getDate() + startOffset + i);
date.setHours(0, 0, 0, 0);
return { clip, index: i, date };
});
}, [clips, startOffset]);
const [scheduling, setScheduling] = useState(false);
const [progress, setProgress] = useState({ current: 0, total: 0, results: [] });
const [done, setDone] = useState(false);
// Reset state when modal reopens
const prevOpen = React.useRef(false);
React.useEffect(() => {
if (isOpen && !prevOpen.current) {
setScheduling(false);
setDone(false);
setProgress({ current: 0, total: 0, results: [] });
}
prevOpen.current = isOpen;
}, [isOpen]);
if (!isOpen) return null;
const selectedPlatforms = Object.keys(platforms).filter(k => platforms[k]);
// Managed (cloud plan/trial) users post with the server-side key — no BYOK needed
const canPost = isManaged || (uploadPostKey && uploadUserId);
const handleScheduleAll = async () => {
if (!canPost) return;
if (selectedPlatforms.length === 0) return;
setScheduling(true);
setDone(false);
const total = schedule.length;
setProgress({ current: 0, total, results: [] });
const results = [];
for (let i = 0; i < schedule.length; i++) {
const { clip, index, date } = schedule[i];
// Build local datetime string: "2026-04-06T12:00:00"
// Upload-Post accepts this + timezone IANA parameter
const pad = (n) => String(n).padStart(2, '0');
const scheduledDate = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${time}:00`;
const payload = {
job_id: jobId,
clip_index: index,
api_key: uploadPostKey,
user_id: uploadUserId,
platforms: selectedPlatforms,
title: clip.video_title_for_youtube_short || 'Viral Short',
description: clip.video_description_for_instagram || clip.video_description_for_tiktok || '',
scheduled_date: scheduledDate,
timezone
};
try {
const res = await apiFetch('/api/social/post', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (!res.ok) {
const errText = await res.text();
throw new Error(errText);
}
results.push({ index: i, success: true });
} catch (e) {
results.push({ index: i, success: false, error: e.message });
}
setProgress({ current: i + 1, total, results: [...results] });
}
setDone(true);
setScheduling(false);
};
const successCount = progress.results.filter(r => r.success).length;
const failCount = progress.results.filter(r => !r.success).length;
const footer = (
<div className="flex flex-col sm:flex-row gap-3">
<button
onClick={onClose}
disabled={scheduling}
className="btn-ghost flex-1"
>
{done ? 'close' : 'cancel'}
</button>
{!done ? (
<button
onClick={handleScheduleAll}
disabled={scheduling || !canPost || selectedPlatforms.length === 0}
className="btn-primary flex-1"
>
{scheduling ? (
<>
<Loader2 size={16} className="animate-spin" />
scheduling...
</>
) : (
<>
<Calendar size={16} />
schedule {clips?.length || 0} clips
</>
)}
</button>
) : (
<a
href="https://app.upload-post.com/calendar"
target="_blank"
rel="noopener noreferrer"
className="btn-primary flex-1 no-underline"
>
<ExternalLink size={16} />
view calendar
</a>
)}
</div>
);
return (
<Modal
isOpen={isOpen}
onClose={scheduling ? undefined : onClose}
eyebrow="PUBLISH · WEEK"
title="schedule week"
size="md"
footer={footer}
>
<p className="readout mb-4">{clips?.length || 0} CLIPS · 1/DAY</p>
{!canPost && (
<div className="mb-4 p-3 bg-warn/10 text-warn text-xs rounded-input flex items-start gap-2">
<AlertCircle size={14} className="mt-0.5 shrink-0" />
<div>Set your Upload-Post API key in Settings first.</div>
</div>
)}
{/* Time + Timezone */}
<div className="mb-5 grid grid-cols-2 gap-3">
<div>
<label className="eyebrow block mb-2">time</label>
<input
type="time"
value={time}
onChange={(e) => setTime(e.target.value)}
disabled={scheduling}
className="input-field [color-scheme:dark]"
/>
</div>
<div>
<label className="eyebrow block mb-2">timezone</label>
<select
value={timezone}
onChange={(e) => setTimezone(e.target.value)}
disabled={scheduling}
className="input-field appearance-none cursor-pointer"
>
{TIMEZONES.map(tz => (
<option key={tz.value} value={tz.value}>{tz.label}</option>
))}
</select>
</div>
</div>
{/* Start day offset */}
<div className="mb-5 flex flex-wrap items-center justify-between gap-2">
<span className="eyebrow">start from</span>
<div className="flex items-center gap-2">
<button
onClick={() => setStartOffset(Math.max(1, startOffset - 1))}
disabled={startOffset <= 1 || scheduling}
className="btn-quiet px-2 py-2 disabled:opacity-40 disabled:cursor-not-allowed"
>
<ChevronLeft size={16} />
</button>
<span className="readout text-ink2 min-w-[110px] text-center">
{(() => {
const d = new Date();
d.setDate(d.getDate() + startOffset);
return `${getDayLabel(d)} · ${formatDate(d)}`;
})()}
</span>
<button
onClick={() => setStartOffset(startOffset + 1)}
disabled={scheduling}
className="btn-quiet px-2 py-2 disabled:opacity-40 disabled:cursor-not-allowed"
>
<ChevronRight size={16} />
</button>
</div>
</div>
{/* Calendar list */}
<div className="mb-5 border-y border-rule divide-y divide-rule">
{schedule.map(({ clip, index, date }) => (
<div key={index} className="flex items-center gap-3 py-2.5">
<div className="w-24 shrink-0">
<span className="readout">{getDayLabel(date)} · {formatDate(date)}</span>
</div>
<div className="flex-1 min-w-0">
<div className="text-xs text-ink truncate">
{clip.video_title_for_youtube_short || 'Viral Short'}
</div>
<div className="readout mt-0.5 truncate">
{time} · {TIMEZONES.find(t => t.value === timezone)?.label || timezone}
</div>
</div>
<div className="shrink-0">
{progress.results[index]?.success === true && (
<CheckCircle size={16} className="text-ok" />
)}
{progress.results[index]?.success === false && (
<AlertCircle size={16} className="text-danger" />
)}
{scheduling && progress.current === index && (
<Loader2 size={16} className="text-brass animate-spin" />
)}
{!scheduling && progress.results[index] === undefined && (
<Circle size={16} className="text-muted" />
)}
</div>
</div>
))}
</div>
{/* Platforms */}
<div className="mb-5">
<label className="eyebrow block mb-2">platforms</label>
<SegmentedControl
multi
options={PLATFORM_OPTIONS.map(opt => ({ ...opt, disabled: scheduling }))}
value={selectedPlatforms}
onChange={(arr) => setPlatforms({
tiktok: arr.includes('tiktok'),
instagram: arr.includes('instagram'),
youtube: arr.includes('youtube')
})}
/>
</div>
{/* A whole week of tiktok posts is a whole week of silent drafts:
this modal writes no captions of its own either (it sends the
clip's generated title/description), and tiktok keeps none of
them on a draft. Say it before the button, not after. */}
{platforms.tiktok && !scheduling && !done && <TikTokDraftNotice />}
{/* Progress bar */}
{(scheduling || done) && (
<div className="mb-1">
<div className="flex items-center justify-between mb-2">
<span className="text-xs text-muted lowercase">{scheduling ? 'scheduling...' : 'complete'}</span>
<span className="readout">{progress.current}/{progress.total}</span>
</div>
<div className="w-full h-1.5 bg-paper3 rounded-full overflow-hidden">
<div
className={`h-full rounded-full transition-all duration-500 ${done && failCount === 0 ? 'bg-ok' : done && failCount > 0 ? 'bg-danger' : 'bg-brass'}`}
style={{ width: `${(progress.current / progress.total) * 100}%` }}
/>
</div>
{done && (
<div className="mt-3 text-xs text-center lowercase">
{failCount === 0 ? (
<span className="text-ok">all clips scheduled</span>
) : (
<span className="text-danger">{successCount} scheduled, {failCount} failed</span>
)}
</div>
)}
</div>
)}
</Modal>
);
}

View file

@ -1,104 +0,0 @@
import React, { useEffect, useState } from 'react';
import { BarChart3, ExternalLink } from 'lucide-react';
import { apiJson } from '../lib/api';
const fmtNum = (n) => new Intl.NumberFormat('en-US', {
notation: (n || 0) >= 10000 ? 'compact' : 'standard',
maximumFractionDigits: 1,
}).format(n || 0);
// Upload-Post metric shapes vary per platform; read the first count that exists.
const postViews = (p) => {
const m = p.post_metrics || p.metrics || p;
return Number(m.views || m.impressions || m.plays || 0) || 0;
};
const postTitle = (p) => p.title || p.caption || p.youtube_title || p.tiktok_title || 'untitled post';
const postUrl = (p) => p.post_url || p.url || p.share_url || null;
// Post-publication analytics: what the clips actually did out there.
// Paid-only by nature (social posting itself is paid in cloud): a 402 or any
// other failure simply hides the card — the account page works without it.
export default function SocialAnalyticsCard() {
const [data, setData] = useState(null);
useEffect(() => {
let alive = true;
(async () => {
try {
const [imp, postsResp] = await Promise.all([
apiJson('/api/social/analytics/impressions?period=last_month&breakdown=true'),
apiJson('/api/social/analytics/posts?limit=50'),
]);
if (!alive) return;
const posts = (postsResp.posts || postsResp.data || postsResp.items || [])
.slice()
.sort((a, b) => postViews(b) - postViews(a));
setData({ imp, posts });
} catch (_) { /* free plan, nothing connected, or vendor hiccup — stay hidden */ }
})();
return () => { alive = false; };
}, []);
if (!data) return null;
const total = data.imp?.total_impressions
|| data.posts.reduce((s, p) => s + postViews(p), 0);
const perPlatform = Object.entries(data.imp?.per_platform || {})
.filter(([, v]) => Number(v) > 0)
.sort((a, b) => Number(b[1]) - Number(a[1]));
const top = data.posts.slice(0, 3);
return (
<div className="card p-6">
<div className="flex items-baseline justify-between gap-4 mb-1">
<h3 className="font-display lowercase text-lg text-ink flex items-center gap-2">
<BarChart3 size={16} className="text-brass" /> Your posts
</h3>
<span className="text-muted text-xs lowercase">last 30 days</span>
</div>
{data.posts.length === 0 && !total ? (
<p className="text-muted text-sm lowercase">
Nothing published yet. Post a clip from your results and its views show up here.
</p>
) : (
<>
<div className="flex items-end gap-3 mb-3">
<span className="readout text-2xl text-ink">{fmtNum(total)}</span>
<span className="text-muted text-sm lowercase mb-0.5">impressions</span>
</div>
{perPlatform.length > 0 && (
<div className="flex flex-wrap gap-x-4 gap-y-1 mb-4 text-sm">
{perPlatform.map(([platform, v]) => (
<span key={platform} className="text-ink2 lowercase">
{platform} <span className="text-brass">{fmtNum(Number(v))}</span>
</span>
))}
</div>
)}
{top.length > 0 && (
<div className="space-y-2 border-t border-rule pt-3">
{top.map((p, i) => (
<div key={p.request_id || p.platform_post_id || i}
className="flex items-center justify-between gap-3 text-sm">
<span className="text-ink2 truncate">
{postTitle(p)}
{postUrl(p) && (
<a href={postUrl(p)} target="_blank" rel="noreferrer"
className="inline-flex align-middle ml-1.5 text-muted hover:text-ink">
<ExternalLink size={12} />
</a>
)}
</span>
<span className="text-ink shrink-0">{fmtNum(postViews(p))} views</span>
</div>
))}
</div>
)}
</>
)}
</div>
);
}

View file

@ -70,7 +70,7 @@ function DragDropZone({ label, accept, onFile, file, onClear, icon }) {
);
}
export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUserId, managed = false, onCreateClips = null }) {
export default function ThumbnailStudio({ geminiApiKey, postizKey, postizUrl, managed = false, onCreateClips = null }) {
// Managed (hosted plan): Gemini runs server-side via the bearer token, no BYOK key.
// Only send X-Gemini-Key for self-host BYOK. apiFetch attaches the bearer token.
const keyHeader = geminiApiKey ? { 'X-Gemini-Key': geminiApiKey } : {};
@ -376,7 +376,7 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
// --- Publish to YouTube ---
const handlePublish = async () => {
if (!managed && (!uploadPostKey || !uploadUserId)) return alert('Please configure your Upload-Post API key and user in Settings first.');
if (!managed && !postizKey) return alert('Please configure your Postiz base URL and API key in Settings first.');
const finalTitle = selectedTitle || manualTitle;
if (!finalTitle) return alert('No title selected.');
if (!selectedThumbnail) return alert('Please select a thumbnail first.');
@ -390,12 +390,15 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
formData.append('title', finalTitle);
formData.append('description', description);
formData.append('thumbnail_url', selectedThumbnail);
formData.append('api_key', uploadPostKey);
formData.append('user_id', uploadUserId);
const headers = {};
if (postizKey) headers['X-Postiz-Key'] = postizKey;
if (postizUrl) headers['X-Postiz-Url'] = postizUrl.replace(/\/$/, '');
// Submit the publish job — returns immediately with a publish_id
const res = await apiFetch('/api/thumbnail/publish', {
method: 'POST',
headers,
body: formData
});
@ -471,7 +474,7 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
{/* Header */}
<div className="flex items-end justify-between mb-2">
<div>
<p className="eyebrow mb-2">06 · YOUTUBE STUDIO</p>
<p className="eyebrow mb-2">02 · YOUTUBE STUDIO</p>
<h1 className="font-display lowercase text-2xl text-ink flex items-center gap-3">
<span className="w-10 h-10 rounded-card bg-paper3 flex items-center justify-center">
<Image size={18} className="text-brass" />
@ -1136,14 +1139,14 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
</div>
{/* Publish Button */}
{(!managed && (!uploadPostKey || !uploadUserId)) ? (
{(!managed && !postizKey) ? (
<div className="glass-panel p-6 space-y-3">
<div className="flex items-center gap-2 text-warn">
<AlertCircle size={16} />
<span className="text-sm font-medium lowercase">Upload-Post Not Configured</span>
<span className="text-sm font-medium lowercase">Postiz Not Configured</span>
</div>
<p className="text-xs text-muted">
To publish directly to YouTube, configure your Upload-Post API key and connect a profile in Settings.
To publish directly to YouTube, configure your Postiz base URL and API key in Settings.
</p>
<button
onClick={() => { }}

View file

@ -1,35 +0,0 @@
import React from 'react';
import { AlertCircle } from 'lucide-react';
/**
* Shown wherever tiktok is among the selected platforms, before the button
* that posts or schedules.
*
* Two different people need it. Someone who publishes one clip expects a live
* post and finds nothing on their profile, and reads that as a failure. Someone
* who schedules a week gets a silent drawer of drafts and a profile that stays
* empty for seven days.
*
* The title/description line is not a detail: TikTok's upload-to-inbox endpoint
* takes only source_info (the bytes), with no post_info anywhere in the request,
* so the caption we send is dropped on the floor for a video draft — whether the
* user typed it or the AI wrote it. Saying only "it arrives as a draft" leaves
* them to discover that in the app.
*
* Lead with the upside: finishing the post inside TikTok is what the algorithm
* rewards, so this is a better default, not a limitation we are apologising for.
*/
export default function TikTokDraftNotice() {
return (
<div className="mb-4 px-3 py-2 rounded-input text-xs text-ink2 bg-paper3 flex items-start gap-2">
<AlertCircle size={14} className="mt-0.5 shrink-0 text-brass" />
<div className="lowercase">
tiktok arrives as a <b className="text-ink">draft</b>, not a live post — you'll
get a notification in the app. its api won't carry the title or description
onto a draft, so you write those there too, along with trending sounds,
effects and hashtags — which reaches more people than posting straight
from an api.
</div>
</div>
);
}

View file

@ -1,238 +0,0 @@
import React, { useState, useEffect } from 'react';
import { Film, Download, Copy, Check, Loader2, Play, User } from 'lucide-react';
import { getApiUrl } from '../config';
import SegmentedControl from './ui/SegmentedControl';
import Modal from './ui/Modal';
export default function UGCGallery() {
const [tab, setTab] = useState('videos');
const [videos, setVideos] = useState([]);
const [avatars, setAvatars] = useState([]);
const [loadingVideos, setLoadingVideos] = useState(true);
const [loadingAvatars, setLoadingAvatars] = useState(false);
const [avatarsLoaded, setAvatarsLoaded] = useState(false);
const [copied, setCopied] = useState('');
const [selected, setSelected] = useState(null);
useEffect(() => {
setLoadingVideos(true);
fetch(getApiUrl('/api/saasshorts/gallery?limit=100'))
.then((r) => (r.ok ? r.json() : { videos: [] }))
.then((d) => setVideos(d.videos || []))
.catch(() => {})
.finally(() => setLoadingVideos(false));
}, []);
useEffect(() => {
if (tab !== 'avatars' || avatarsLoaded) return;
setLoadingAvatars(true);
fetch(getApiUrl('/api/saasshorts/actor-gallery'))
.then((r) => (r.ok ? r.json() : { images: [] }))
.then((d) => setAvatars(d.images || []))
.catch(() => {})
.finally(() => {
setLoadingAvatars(false);
setAvatarsLoaded(true);
});
}, [tab, avatarsLoaded]);
const handleCopy = (text, id) => {
navigator.clipboard.writeText(text);
setCopied(id);
setTimeout(() => setCopied(''), 2000);
};
const loading = (tab === 'videos' && loadingVideos) || (tab === 'avatars' && loadingAvatars);
return (
<div className="space-y-6">
<div>
<p className="eyebrow mb-1">05 · UGC GALLERY</p>
<h2 className="font-display lowercase text-2xl md:text-3xl text-ink">ugc gallery</h2>
<p className="readout mt-2">
{loadingVideos ? '…' : videos.length} videos
{avatarsLoaded ? ` · ${avatars.length} avatars` : ''}
</p>
</div>
<div className="max-w-xs w-full">
<SegmentedControl
size="sm"
value={tab}
onChange={setTab}
options={[
{ value: 'videos', label: `Videos (${loadingVideos ? '…' : videos.length})`, icon: <Film size={14} /> },
{ value: 'avatars', label: `Avatars (${avatarsLoaded ? avatars.length : '…'})`, icon: <User size={14} /> },
]}
/>
</div>
{loading ? (
<div className="flex items-center justify-center h-64">
<Loader2 size={24} className="animate-spin text-brass" />
<span className="ml-2 text-muted lowercase">Loading gallery...</span>
</div>
) : tab === 'videos' ? (
videos.length === 0 ? (
<div className="text-center py-16">
<Film size={40} className="mx-auto text-muted opacity-40 mb-3" />
<p className="text-sm text-muted lowercase">No videos yet. Generate one from AI Shorts.</p>
</div>
) : (
<div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-3">
{videos.map((video) => (
<VideoCard
key={video.video_id}
video={video}
copied={copied}
onCopy={handleCopy}
onOpen={() => setSelected(video)}
/>
))}
</div>
)
) : avatars.length === 0 ? (
<div className="text-center py-16">
<User size={40} className="mx-auto text-muted opacity-40 mb-3" />
<p className="text-sm text-muted lowercase">No avatars yet. Generate actors from AI Shorts.</p>
</div>
) : (
<div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-6 gap-3">
{avatars.map((avatar, i) => (
<AvatarCard key={avatar.key || i} avatar={avatar} copied={copied} onCopy={handleCopy} />
))}
</div>
)}
{selected && (
<Modal
isOpen
onClose={() => setSelected(null)}
size="sm"
eyebrow={selected.video_mode === 'lowcost' ? 'LOW COST' : 'PREMIUM'}
title={selected.title || 'Untitled'}
>
<video
src={selected.video_url}
poster={selected.actor_url}
controls
autoPlay
playsInline
className="w-full rounded-input bg-black aspect-[9/16] object-contain max-h-[60vh]"
/>
<p className="readout mt-3">
{selected.duration?.toFixed(0)}s
{selected.cost_estimate?.total != null ? ` · $${selected.cost_estimate.total.toFixed(2)}` : ''}
</p>
{selected.caption && (
<p className="text-sm text-muted mt-2 leading-relaxed">{selected.caption}</p>
)}
<a
href={selected.video_url}
download
className="btn-ghost w-full mt-4 justify-center text-sm"
>
<Download size={14} /> Download
</a>
</Modal>
)}
</div>
);
}
function AvatarCard({ avatar, copied, onCopy }) {
return (
<div className="group card overflow-hidden transition-colors hover:border-rule2">
<div className="aspect-[3/4] bg-black">
<img src={avatar.url} alt="Avatar" loading="lazy" decoding="async" className="w-full h-full object-cover" />
</div>
<div className="p-2 space-y-1">
{avatar.description ? (
<div className="relative pr-4">
<p className="text-micro text-muted line-clamp-2">{avatar.description}</p>
<button
type="button"
onClick={() => onCopy(avatar.description, `avatar-${avatar.key}`)}
className="absolute top-0 right-0 p-0.5 text-muted hover:text-brass transition-colors"
title="Copy prompt"
>
{copied === `avatar-${avatar.key}` ? <Check size={10} className="text-ok" /> : <Copy size={10} />}
</button>
</div>
) : (
<p className="text-micro text-muted opacity-60 lowercase">No description</p>
)}
<a
href={avatar.url}
download
className="block text-center text-micro lowercase bg-paper3 hover:brightness-110 text-muted hover:text-ink2 py-1 rounded-full transition-all"
>
<Download size={10} className="inline mr-0.5" />Download
</a>
</div>
</div>
);
}
function VideoCard({ video, copied, onCopy, onOpen }) {
const mode = video.video_mode;
const caption = video.caption || '';
const hashtags = (video.hashtags || []).join(' ');
return (
<div className="group card overflow-hidden transition-colors hover:border-rule2">
<button
type="button"
onClick={onOpen}
className="relative aspect-[9/16] w-full p-0 border-0 bg-black overflow-hidden cursor-pointer"
>
{video.actor_url ? (
<img
src={video.actor_url}
alt=""
loading="lazy"
decoding="async"
className="w-full h-full object-cover"
/>
) : (
<div className="w-full h-full bg-paper3" />
)}
<div className="absolute inset-0 flex items-center justify-center bg-black/20 group-hover:bg-black/30 transition-colors">
<Play size={20} className="text-white/80" />
</div>
<div className="absolute top-1.5 right-1.5">
<span className={`${mode === 'lowcost' ? 'badge-ok' : 'badge-brass'} bg-black/70`}>
{mode === 'lowcost' ? 'LOW COST' : 'PREMIUM'}
</span>
</div>
</button>
<div className="p-2 space-y-1">
<h3 className="text-xs font-semibold text-ink truncate">{video.title || 'Untitled'}</h3>
<p className="readout">
{video.duration?.toFixed(0)}s · ${video.cost_estimate?.total?.toFixed(2) || '?'}
</p>
{caption && (
<div className="relative pr-4">
<p className="text-micro text-muted line-clamp-2">{caption}</p>
<button
type="button"
onClick={() => onCopy(`${caption}\n${hashtags}`, `caption-${video.video_id}`)}
className="absolute top-0 right-0 p-0.5 text-muted hover:text-brass transition-colors"
title="Copy caption"
>
{copied === `caption-${video.video_id}` ? <Check size={10} className="text-ok" /> : <Copy size={10} />}
</button>
</div>
)}
<a
href={video.video_url}
download
className="block text-center text-micro lowercase bg-paper3 hover:brightness-110 text-muted hover:text-ink2 py-1 rounded-full transition-all"
>
<Download size={10} className="inline mr-0.5" />Download
</a>
</div>
</div>
);
}

View file

@ -1,8 +1,8 @@
import { Check } from 'lucide-react';
/**
* The single wizard stepper (design.md) — shared by ThumbnailStudio and
* SaaShortsTab. Mono ordinals, hairline connectors, brass current step.
* The single wizard stepper (design.md) — used by ThumbnailStudio. Mono
* ordinals, hairline connectors, brass current step.
*
* Props:
* - steps: string[] (labels)

View file

@ -52,12 +52,12 @@ export function isEEAVisitor() {
export function refineGeo() {
if (typeof window === "undefined" || typeof window.fetch !== "function") return;
try { if (window.localStorage.getItem(GEO_KEY)) return; } catch (e) {}
try { if (window.localStorage.getItem(GEO_KEY)) return; } catch { /* storage bloqueado */ }
fetch("/cdn-cgi/trace", { cache: "no-store" })
.then((r) => (r.ok ? r.text() : ""))
.then((t) => {
const m = /^loc=([A-Z]{2})$/m.exec(t || "");
if (m) { try { window.localStorage.setItem(GEO_KEY, m[1]); } catch (e) {} }
if (m) { try { window.localStorage.setItem(GEO_KEY, m[1]); } catch { /* ignore */ } }
})
.catch(() => {});
}
@ -111,7 +111,6 @@ export function onConsentChange(fn) {
* document that never loads it.
*/
export function setConsent(choice) {
const before = getConsent();
const next = {
v: VERSION,
ts: new Date().toISOString(),

View file

@ -80,7 +80,7 @@ const notFoundPage = () => ({
h1: 'That page does not exist',
breadcrumb: [{ name: 'Not found' }],
tldr: [
'The URL you followed is not a page on this site. It may have been a link to the app, which lives at the site root, or to the public gallery, which is served from api.openshorts.app.',
'The URL you followed is not a page on this site. It may have been a link to the app, which lives at the site root.',
'The links below cover everything openshorts.app actually publishes.',
],
body: `
@ -89,7 +89,6 @@ const notFoundPage = () => ({
<li><a href="${SITE.url}/">The app and the landing page</a>, where you can paste a video link and get clips.</li>
<li><a href="/how-openshorts-works">How OpenShorts works</a>, the pipeline stage by stage.</li>
<li><a href="/alternatives">Comparisons</a> against Opus Clip, Klap, Vizard and Submagic.</li>
<li><a href="https://api.openshorts.app/gallery" rel="noopener">The public video gallery</a>, which is served from the API host.</li>
<li><a href="${SITE.repo}" rel="noopener">The source on GitHub</a>, MIT licensed and self-hostable.</li>
</ul>`,
faq: [],

View file

@ -37,8 +37,6 @@ export default defineConfig({
'/api': { target: backend, changeOrigin: true },
'/videos': { target: backend, changeOrigin: true },
'/thumbnails': { target: backend, changeOrigin: true },
'/gallery': { target: backend, changeOrigin: true },
'/video': { target: backend, changeOrigin: true },
'/render': { target: renderer, changeOrigin: true },
}
}

View file

@ -134,7 +134,7 @@ utility). Radii: `--radius-card: 10px` (rounded-card), `--radius-input: 8px`
- Zero gradients (text or background). Zero glassmorphism / backdrop-blur
panels. Zero per-feature identity colors (the old violet/emerald/amber/teal
per-tab coding is retired — tools are differentiated by mono eyebrow ordinals
`01 · CLIPS`, `02 · AI SHORTS`, not by hue).
`01 · CLIPS`, `02 · PUBLISHING`, not by hue).
- The two-register typography (lowercase prose / UPPERCASE mono labels).
- The CTA voice, radii, hairline card language.
- English copy everywhere (ScheduleWeekModal migrates from Spanish).
@ -162,7 +162,7 @@ soup — use rounded-card/rounded-input/rounded-full deliberately. No
Hash routing (`#app`, `#/pricing`, `#/account`, `#legal`, `#features`,
`#how-it-works`, `#pricing`, `#comparison`, `#faq` anchors), `billingEnabled` /
`isManaged` / `isSignedIn` gating, all handlers and props, localStorage keys
(`gemini_key`, `uploadPostKey_v3`, `elevenLabsKey_v1`, `falKey_v1`,
(`gemini_key`, `postiz_url`, `postiz_key_v1`, `elevenLabsKey_v1`,
`uploadUserId`, `openshorts_session`, `openshorts_auth`,
`openshorts_skip_landing`), API calls and BYOK headers, QuotaError flows,
Remotion preview/render wiring. Redesign is classes + markup structure only.

View file

@ -20,6 +20,12 @@ services:
volumes:
- ./dashboard:/app
- /app/node_modules
environment:
# Optional OpenPanel analytics. Defined (empty) so Vite resolves the
# %VITE_OPENPANEL_*% placeholders in index.html instead of warning that
# they're undefined; empty keeps analytics fully inert. See index.html.
- VITE_OPENPANEL_API_URL=
- VITE_OPENPANEL_CLIENT_ID=
restart: unless-stopped
depends_on:
- backend

View file

@ -22,13 +22,11 @@ alargarlos por encima de lo que dice la política sin actualizarla.
| Subidas pendientes de trabajo (huecos de subida para agentes) | **6 h** | `app._sweep_pending_uploads`, `UPLOAD_TTL_SECONDS` |
| Ficheros en `uploads/` | **1 h** (misma vuelta del barrido) | `app.cleanup_jobs` |
| **Miniaturas generadas y fotogramas muestreados** (`output/thumbnails/<sesión>`) — recortes de la cara del presentador | **24 h desde la última descarga**; servir un fichero reinicia el reloj | `app._sweep_thumbnail_sessions`, `THUMBNAIL_RETENTION_SECONDS` |
| **Fotos de actor subidas** (`output/actor_uploads/*.png`) — fotografías de personas | **1 h** (el reloj del trabajo) | `app._sweep_actor_uploads`, `ACTOR_UPLOAD_RETENTION_SECONDS` |
| Tope de disco: se purgan los trabajos más antiguos por encima del límite | Inmediato al superarlo | `app._enforce_output_size_cap`, `OUTPUT_MAX_GB` |
Antes del 4-sep-2026 las dos filas en negrita **no tenían ningún plazo**: el
barrido horario salta deliberadamente `output/thumbnails`, y `actor_uploads`
solo desaparecía cuando el directorio entero envejecía como si fuese un
trabajo, es decir una hora después de la *última* subida de cualquier usuario.
Antes del 4-sep-2026 la fila en negrita **no tenía ningún plazo**: el
barrido horario salta deliberadamente `output/thumbnails`. La retención de
fotos de actor se retiró con la función de vídeo UGC (4-oct-2026).
## 2. Contenido del usuario en almacenamiento durable (Cloudflare R2)
@ -43,7 +41,7 @@ trabajo, es decir una hora después de la *última* subida de cualquier usuario.
| Qué | Plazo | Dónde se aplica |
|---|---|---|
| `users`, `subscriptions`, `credit_topups`, `usage_ledger`, `projects`, `user_videos`, `api_keys`, `upload_post_profiles`, `signup_attribution`, `oauth_codes`, `clip_expiry_warnings` | Mientras exista la cuenta; **inmediato** al borrarla | `cloud/account.USER_OWNED_TABLES` |
| `users`, `subscriptions`, `credit_topups`, `usage_ledger`, `projects`, `user_videos`, `api_keys`, `signup_attribution`, `clip_expiry_warnings` | Mientras exista la cuenta; **inmediato** al borrarla | `cloud/account.USER_OWNED_TABLES` |
| `magic_link_tokens` (incluye la IP que pidió el enlace) | **30 días** | `cloud/auth.py` |
| **Declaración de derechos** (IP truncada a /24, user-agent, fecha, origen) | Con el proyecto al que pertenece → hasta 5 años, y se borra con la cuenta | `app.py` (captura) → `cloud/videos.archive_job` → `Project.state.rights_attestation` |
| `account_deletions` (sha256 del email, sin la dirección) | **5 años** | `DELETION_LOG_RETENTION_DAYS` |

View file

@ -20,8 +20,7 @@ puede pedirlo en info@openshorts.app.
| Proveedor | Entidad y país | Qué recibe | Garantía de transferencia | DPA |
|---|---|---|---|---|
| **Google (Gemini API)** | Google LLC / Google Ireland Ltd. — EE. UU. | Transcripción, fotogramas muestreados (pueden incluir caras), foto de referencia del presentador para miniaturas, y el **archivo de vídeo completo** solo en la comprobación de encuadre "screencast" (se borra del File API en cuanto responde) | EU-US Data Privacy Framework (Google LLC certificado) + CCT | Google Cloud / AI Studio paid data terms — **verificar que la clave gestionada pertenece a un proyecto de pago**: los términos gratuitos permiten entrenamiento |
| **ElevenLabs** | ElevenLabs Inc. — EE. UU. | Audio del clip para doblaje (voz de personas reales), texto para TTS | DPF (certificado) + CCT | Pendiente de firma/archivo |
| **fal.ai** | Features & Labels, Inc. — EE. UU. | Foto del actor (puede ser de una persona real), audio a sincronizar, vídeo generado. Modelos: Flux 2 Pro, Kling AI-Avatar, Hailuo | **Sin certificación DPF conocida → CCT obligatorias** | Pendiente de firma/archivo |
| **ElevenLabs** | ElevenLabs Inc. — EE. UU. | Audio del clip para doblaje (voz de personas reales) | DPF (certificado) + CCT | Pendiente de firma/archivo |
## 2. Infraestructura y almacenamiento
@ -31,7 +30,7 @@ puede pedirlo en info@openshorts.app.
| **Contabo GmbH** | Alemania | Servidores | Dentro del EEE | DPA estándar de Contabo |
| **Cloudflare R2** | Cloudflare, Inc. — EE. UU. / región UE del bucket | Clips, metadatos de proyecto (incluida la transcripción), copias de seguridad | DPF + CCT (Cloudflare Customer DPA) | Automático con la cuenta — **verificar que el bucket está en jurisdicción UE** |
| **Cloudflare (DNS + CDN)** | Cloudflare, Inc. — EE. UU. / global | IP y metadatos de petición de cada visitante del sitio | DPF + CCT | Cloudflare Customer DPA |
| **Amazon Web Services (S3)** | AWS EMEA SARL — región `eu-west-3` (París) | Galería pública UGC e imágenes de actor, solo si el usuario opta por publicar | Dentro del EEE (región UE) | AWS Service Terms / DPA |
| **Amazon Web Services (S3)** | AWS EMEA SARL — región `eu-west-3` (París) | Copia de seguridad de clips, solo si el usuario configura las credenciales S3 | Dentro del EEE (región UE) | AWS Service Terms / DPA |
## 3. Pagos, facturación y correo
@ -45,7 +44,7 @@ puede pedirlo en info@openshorts.app.
| Proveedor | Entidad y país | Qué recibe | Garantía | DPA |
|---|---|---|---|---|
| **Upload-Post** | TONVI TECH SL | Publicación en las redes que el usuario conecta; **custodia los tokens OAuth** de TikTok/YouTube/Instagram (OpenShorts no almacena ninguno, solo el nombre de perfil) | Mismo responsable | Sistema interno — su política debe cubrir esta custodia |
| **Postiz** (autoalojado por el usuario) | Instancia del usuario | Publicación en las redes que el usuario conecta; **custodia los tokens OAuth** de TikTok/YouTube/Instagram. OpenShorts no almacena ningún token: el backend sube el clip a la instancia de Postiz del usuario | Responsable independiente: lo opera el usuario, no TONVI TECH SL | No aplica a TONVI TECH SL |
| **OpenPanel** (instancia propia) | TONVI TECH SL — servidores en Alemania | Eventos de uso con el uuid de la cuenta como `profileId`. **Nunca el email** (retirado del `identify` del navegador el 4-sep-2026). Solo tras consentimiento | Dentro del EEE; script servido desde el propio dominio | Sistema interno |
| **Google (iniciar sesión con Google)** | Google Ireland Ltd. / Google LLC | Solo el ámbito `openid email profile`: dirección e identificador de cuenta | DPF + CCT | Google Terms |
@ -72,7 +71,7 @@ Nada de esto se puede hacer desde el repositorio; queda para el responsable:
pago.** Los términos gratuitos de AI Studio permiten usar los datos para
mejorar los modelos, lo que haría falsa la frase "no se entrena con tu
contenido".
2. **Firmar y archivar** los DPA de ElevenLabs, fal.ai (+ CCT) y Namecheap
2. **Firmar y archivar** los DPA de ElevenLabs y Namecheap
(+ CCT). Guardar los PDF con fecha.
3. **Verificar la jurisdicción del bucket R2** (debe ser UE) y la región de S3.
4. **Identificar al proveedor de proxies estáticos** y el país de DataImpulse,
@ -80,11 +79,12 @@ Nada de esto se puede hacer desde el repositorio; queda para el responsable:
5. **Confirmar dónde están físicamente los dos servidores de producción.** La política dice
"Hetzner y Contabo, Alemania"; si alguno es hardware propio fuera de un CPD,
hay que decirlo y aplicar cifrado de disco.
6. **Comprobar que la política de Upload-Post** describe la custodia de tokens
de redes sociales en nombre de usuarios de OpenShorts.
6. **Comprobar que la instancia de Postiz** del usuario describe la custodia de
tokens de redes sociales; al ser autoalojada, no pasa por TONVI TECH SL.
## Historial de cambios
| Fecha | Cambio |
|---|---|
| 2026-09-04 | Primera versión publicada. Altas documentadas (ya en uso, no listadas antes): fal.ai, Cloudflare CDN/DNS, Aikount, OpenPanel, proxies de descarga, Google OAuth. Bajas: Google Fonts, script de openpanel.dev y datos personales hacia Telegram. |
| 2026-10-04 | Baja de fal.ai y de la galería pública UGC/imágenes de actor (función retirada). Sustitución de Upload-Post por una instancia de Postiz autoalojada por el usuario para la publicación en redes. |

View file

@ -1,44 +0,0 @@
# DMCA block for upload-post.com terms
Applied on 29-aug-2026 to `upload-post-landing/src/pages/terms-of-use.astro`,
right after **4.8 Intermediary Status** and before the `<h2>` of section 5.
Kept here as the record of what went in and of why the email is what it is.
**The agent email is info@upload-post.com, in both companies' terms.**
17 U.S.C. 512(c)(2) requires each site to publish substantially the same agent
information that is on file with the Copyright Office, and one legal entity
files one designation, so the same address has to appear on openshorts.app too.
It was chosen because that is the inbox that gets read daily and because
Upload-Post is the larger exposure of the two. Everything hinges on somebody
reading it the same working day.
```astro
<p class="text-gray-700 dark:text-slate-300 mb-6">
<strong>4.9 DMCA Designated Agent (United States):</strong> For rightsholders in the United States, TONVI TECH SL has designated the following agent to receive notifications of claimed copyright infringement under 17 U.S.C. &sect; 512(c)(2): <strong>Copyright Agent, TONVI TECH SL, Calle Puerta del Mar 18, 5th Floor, 29005 M&aacute;laga, Spain</strong>, email <a href="mailto:info@upload-post.com?subject=DMCA%20Notification" class="text-blue-600 dark:text-blue-400 underline">info@upload-post.com</a>. That is the address on file with the U.S. Copyright Office for this company, which also operates openshorts.app. Section 4.7 remains available to rightsholders anywhere in the world.
</p>
<p class="text-gray-700 dark:text-slate-300 mb-6">
<strong>4.10 Content of a DMCA Notification:</strong> A notification must be in writing and include: a physical or electronic signature of the owner of the exclusive right allegedly infringed, or of a person authorised to act on their behalf; identification of the copyrighted work claimed to have been infringed; identification of the material claimed to be infringing and information reasonably sufficient to let us locate it; your address, telephone number and email address; a statement that you have a good-faith belief that the use is not authorised by the copyright owner, its agent, or the law; and a statement, made under penalty of perjury, that the information in the notification is accurate and that you are the owner or are authorised to act on the owner's behalf. Notifications that omit these elements may not be effective to give us actual knowledge of the material.
</p>
<p class="text-gray-700 dark:text-slate-300 mb-6">
<strong>4.11 Counter-Notification and Restoration:</strong> If we remove or disable access to your material and you believe this was the result of a mistake or a misidentification, you may send a counter-notification to the designated agent under 17 U.S.C. &sect; 512(g), including your signature, identification of the material and the location at which it appeared before removal, a statement under penalty of perjury that you have a good-faith belief that the material was removed or disabled as a result of mistake or misidentification, and your consent to the jurisdiction of the United States federal district court for the judicial district in which you reside or, if your address is outside the United States, of any judicial district in which we may be found. We will forward the counter-notification to the complaining party and may restore the material in 10 to 14 business days unless that party notifies us that it has filed an action seeking a court order to restrain the allegedly infringing activity.
</p>
<p class="text-gray-700 dark:text-slate-300 mb-6">
<strong>4.12 Repeat Infringers and Misrepresentation:</strong> In accordance with 17 U.S.C. &sect; 512(i), we have adopted and reasonably implement a policy of terminating, in appropriate circumstances, the accounts of users who are repeat infringers. Under 17 U.S.C. &sect; 512(f), any person who knowingly materially misrepresents that material is infringing, or that material was removed or disabled by mistake or misidentification, may be liable for the damages that misrepresentation causes.
</p>
```
Also bump `Last Updated` at the top and bottom of that page when this goes in;
the file states the date twice.
## What must match the registration
When the designation is filed at dmca.copyright.gov, these four have to be the
same as what is published above, or the publication does not do its job:
- Agent name: Copyright Agent
- Organisation: TONVI TECH SL
- Address: Calle Puerta del Mar 18, 5th Floor, 29005 Malaga, Spain
- Email: info@upload-post.com
Alternate names on the designation: OpenShorts, openshorts.app, Upload-Post,
upload-post.com. The phone number is still missing and the form requires it.

View file

@ -1,24 +1,23 @@
# OpenShorts + n8n
Two importable workflows, from a one-shot clipper to a full channel autopilot.
Both work out of the box with [OpenShorts Cloud](https://www.openshorts.app/)
(free tier: 20 min of video, paid plans from $12/mo). OpenShorts is also open
source: self-hosters can point either workflow at their own instance by
changing the base URL (needs a GPU box, your own Gemini key, and your own
[Upload-Post](https://www.upload-post.com/) account for the posting steps).
Two importable workflows, from a one-shot clipper to a channel watcher.
Both run against a self-hosted OpenShorts instance (point them at your base URL,
default `http://localhost:8000`) and publish through a self-hosted
[Postiz](https://postiz.pbento.pt/) instance. No API key is required on a
self-hosted instance, but the server needs a Google Gemini key for the AI
stages, and Postiz needs the target channels connected.
| Workflow | What it does | Credentials |
|---|---|---|
| `openshorts-clip-and-notify.json` | A video URL goes in through a form, clips come back on a signed webhook. No polling. | OpenShorts API key |
| `openshorts-content-machine.json` | Your YouTube channel on autopilot: daily clipping, approval buttons in Telegram, drip-scheduled posting, weekly analytics digest. | OpenShorts API key + Telegram bot |
| `openshorts-clip-and-notify.json` | A video URL goes in through a form, clips come back on a signed webhook. No polling. | None (self-hosted) |
| `openshorts-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. Create a **Header Auth** credential named `OpenShorts API key`:
- Name: `Authorization`
- Value: `Bearer osk_...` (create the key in your account page at
[openshorts.app](https://www.openshorts.app/))
2. Set `OPENSHORTS_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 OpenShorts job** node body.
4. Optional: change `webhook_secret`. OpenShorts signs the webhook body with
@ -40,20 +39,18 @@ changing the base URL (needs a GPU box, your own Gemini key, and your own
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 quota burn
predictable; a 402 (out of minutes) pauses the machine and tells you on
Telegram instead of failing silently.
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/social/post` to every account you connected in
OpenShorts (TikTok, Instagram, YouTube). Approve five clips today, fill five
days of content. The slot comes from the queue the server actually holds
(`GET /api/social/scheduled`), so two clips approved seconds apart cannot
book the same one.
scheduled through `POST /api/postiz/post` to every channel connected in
Postiz. Approve five clips today, fill five days of content. The slot comes
from the queue the server actually holds (`GET /api/postiz/scheduled`), so
two clips approved seconds apart cannot book the same one.
4. **Sunday digest** — the machine reads the analytics of what it published
(`GET /api/social/analytics/*`) and reports total impressions, per-platform
(`GET /api/postiz/analytics/*`) and reports total impressions, per-platform
split, and your best post of the week.
Machine-specific setup, all inside sticky notes on the canvas:
@ -63,7 +60,7 @@ Machine-specific setup, all inside sticky notes on the canvas:
`Telegram bot` credential, and replace `YOUR_TELEGRAM_CHAT_ID` in the
notification nodes (message your bot, then check
`api.telegram.org/bot<token>/getUpdates` for your chat id).
- Connect your social accounts in your OpenShorts account page (Cloud) — the
- 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
@ -87,18 +84,14 @@ mechanism (see act 3).
Failed jobs fire the same webhook with `"event": "job.failed"` and an `error`
field, so the flow never hangs waiting.
`download_url` is a 24-hour presigned link to the archived clip (hosted
service). On the self-hosted edition the same workflow runs against
`http://localhost:8000` with no API key.
`download_url` is a 24-hour presigned link to the archived clip.
## Publishing and analytics API
Direct posting: `POST /api/social/post` (accepts `scheduled_date`, ISO-8601).
Publishing queue: `GET /api/social/scheduled`, and
`DELETE /api/social/scheduled/{job_id}` to cancel one before it goes out.
Analytics of what you published: `GET /api/social/analytics` (profile totals),
`GET /api/social/analytics/posts` (per-post metrics),
`GET /api/social/analytics/impressions` (windowed totals, `period=last_week`).
Full API reference: [api.openshorts.app/docs](https://api.openshorts.app/docs).
Agent-native version of the same pipeline (MCP):
[openshorts.app/mcp](https://www.openshorts.app/mcp).
Direct posting: `POST /api/postiz/post` (accepts `scheduled_date`, ISO-8601).
Connected channels: `GET /api/postiz/integrations`.
Publishing queue: `GET /api/postiz/scheduled`, and
`DELETE /api/postiz/scheduled/{id}` to cancel one before it goes out.
Analytics of what you published: `GET /api/postiz/analytics` (channel totals)
and `GET /api/postiz/analytics/posts` (per-post metrics).
Full API reference: `/docs` (OpenAPI) on your instance.

View file

@ -3,7 +3,7 @@
"nodes": [
{
"parameters": {
"content": "## OpenShorts + 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. Create an API key at [openshorts.app](https://www.openshorts.app/) (account page, starts with `osk_`). Add a **Header Auth** credential: name `Authorization`, value `Bearer osk_...`, and select it in the *Start OpenShorts job* node.\n2. Open the *Clips ready* webhook node, copy its **production** URL, and paste it as `webhook_url` in the *Start OpenShorts job* node body.\n3. Optional: set your own `webhook_secret`. OpenShorts signs the body with HMAC-SHA256 in the `X-OpenShorts-Signature` header (`sha256=<hex>`), so you can verify the sender.\n\n### What you get back\n`event`, `job_id`, `status`, and `clips[]` with `title`, `video_url` and a 24h `download_url` per clip. Failed jobs also fire the webhook with an `error` field, so the flow never hangs.\n\nAPI docs: https://api.openshorts.app/docs \u00b7 Self-hosted works the same on your own machine (MIT).",
"content": "## OpenShorts + 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 OpenShorts 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 OpenShorts job* node body.\n3. Optional: set your own `webhook_secret`. OpenShorts signs the body with HMAC-SHA256 in the `X-OpenShorts-Signature` header (`sha256=<hex>`), so you can verify the sender.\n\n### What you get back\n`event`, `job_id`, `status`, and `clips[]` with `title`, `video_url` and a 24h `download_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
},
@ -42,7 +42,7 @@
{
"parameters": {
"method": "POST",
"url": "https://api.openshorts.app/api/process",
"url": "http://localhost:8000/api/process",
"authentication": "genericCredentialType",
"genericAuthType": "httpHeaderAuth",
"sendBody": true,
@ -215,7 +215,7 @@
},
{
"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 post them directly via `POST /api/social/post`.\n\nEach item here is one finished 9:16 clip with subtitles burned in.",
"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
},

View file

@ -3,7 +3,7 @@
"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\nOpenShorts, 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 to the social accounts connected\nin your OpenShorts account, and every Sunday the workflow reports the impressions\nand best post of what it published.\n\n**How to set up**\n1. Create an API key at openshorts.app and add it as a Header Auth credential\n (Name: Authorization, Value: Bearer osk_...).\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 OpenShorts job*.\n\n**Requirements**\nAn OpenShorts account (free tier covers 20 minutes of video a month, paid plans\nfrom $12/month) or a self-hosted 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 platforms list in\n*Schedule social post*, widen the posting rhythm in *Pick next free slot*, or\nreplace the Telegram approval with your own review step.",
"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\nOpenShorts, 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 OpenShorts job*.\n\n**Requirements**\nA self-hosted OpenShorts 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 platforms list in\n*Schedule Postiz post*, 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
@ -83,7 +83,7 @@
{
"parameters": {
"method": "POST",
"url": "https://api.openshorts.app/api/process",
"url": "http://localhost:8000/api/process",
"authentication": "genericCredentialType",
"genericAuthType": "httpHeaderAuth",
"sendBody": true,
@ -142,7 +142,7 @@
{
"parameters": {
"chatId": "={{ $('Settings').first().json.telegram_chat_id }}",
"text": "\u26a0\ufe0f Autopilot paused: OpenShorts rejected the job (most likely you're out of minutes this month). The video was NOT marked as processed, so it will be retried tomorrow. Top up or upgrade at https://www.openshorts.app/",
"text": "\u26a0\ufe0f Content machine paused: OpenShorts rejected the job. The video was NOT marked as processed, so it will be retried tomorrow. Check the OpenShorts server logs for the error.",
"additionalFields": {}
},
"id": "tg-quota",
@ -348,7 +348,7 @@
},
{
"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 OpenShorts (which posts to every social account you connected there) 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/social/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 platforms list in *Schedule social post* if you want fewer networks.",
"content": "## ACT 3 \u2014 Tap \u2705, it gets scheduled\n\nThe Telegram trigger listens for the approval buttons. Every approved clip is scheduled through OpenShorts 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 platforms list in *Schedule Postiz post* if you want fewer networks.",
"height": 380,
"width": 400,
"color": 7
@ -445,7 +445,7 @@
{
"parameters": {
"method": "POST",
"url": "https://api.openshorts.app/api/social/post",
"url": "http://localhost:8000/api/postiz/post",
"authentication": "genericCredentialType",
"genericAuthType": "httpHeaderAuth",
"sendBody": true,
@ -569,7 +569,7 @@
},
{
"parameters": {
"url": "https://api.openshorts.app/api/social/analytics/impressions",
"url": "http://localhost:8000/api/postiz/analytics?date=7",
"authentication": "genericCredentialType",
"genericAuthType": "httpHeaderAuth",
"sendQuery": true,
@ -603,7 +603,7 @@
},
{
"parameters": {
"url": "https://api.openshorts.app/api/social/analytics/posts",
"url": "http://localhost:8000/api/postiz/analytics/posts",
"authentication": "genericCredentialType",
"genericAuthType": "httpHeaderAuth",
"sendQuery": true,
@ -633,7 +633,7 @@
},
{
"parameters": {
"jsCode": "// Turn the two analytics responses into one human digest message.\nconst impressions = $('Weekly impressions').first().json || {};\nconst postsResp = $input.first().json || {};\nconst posts = postsResp.posts || postsResp.data || postsResp.items || [];\n\nconst views = (post) => {\n const m = post.post_metrics || post.metrics || post;\n return Number(m.views || m.impressions || m.plays || 0);\n};\n\nconst total = impressions.total_impressions || posts.reduce((s, p) => s + views(p), 0);\nconst sorted = [...posts].sort((a, b) => views(b) - views(a));\nconst best = sorted[0];\n\nconst perPlatform = impressions.per_platform\n ? Object.entries(impressions.per_platform)\n .map(([p, v]) => ` \u2022 ${p}: ${Number(v).toLocaleString('en-US')}`)\n .join('\\n')\n : '';\n\nlet text = `\ud83d\udcca Your week on autopilot\\n\\n`;\ntext += `Posts published: ${posts.length}\\n`;\ntext += `Total impressions: ${Number(total).toLocaleString('en-US')}\\n`;\nif (perPlatform) {\n text += `${perPlatform}\\n`;\n}\nif (best && views(best) > 0) {\n const title = best.title || best.caption || best.platform_post_id || 'your top post';\n text += `\\n\ud83c\udfc6 Best post: \"${title}\" \u2014 ${views(best).toLocaleString('en-US')} views`;\n}\nif (posts.length === 0) {\n text += `\\nNothing published this week. Approve some clips and the machine does the rest.`;\n}\nreturn [{ json: { digest: text } }];"
"jsCode": "// Turn the two analytics responses into one human digest message.\nconst impressions = $('Weekly impressions').first().json || {};\nconst postsResp = $input.first().json || {};\nconst posts = postsResp.posts || postsResp.data || postsResp.items || [];\n\nconst views = (post) => {\n const m = post.post_metrics || post.metrics || post;\n return Number(m.views || m.impressions || m.plays || 0);\n};\n\nconst total = impressions.total_impressions || posts.reduce((s, p) => s + views(p), 0);\nconst sorted = [...posts].sort((a, b) => views(b) - views(a));\nconst best = sorted[0];\n\nconst perPlatform = impressions.per_platform\n ? Object.entries(impressions.per_platform)\n .map(([p, v]) => ` \u2022 ${p}: ${Number(v).toLocaleString('en-US')}`)\n .join('\\n')\n : '';\n\nlet text = `\ud83d\udcca Your week\\n\\n`;\ntext += `Posts published: ${posts.length}\\n`;\ntext += `Total impressions: ${Number(total).toLocaleString('en-US')}\\n`;\nif (perPlatform) {\n text += `${perPlatform}\\n`;\n}\nif (best && views(best) > 0) {\n const title = best.title || best.caption || best.platform_post_id || 'your top post';\n text += `\\n\ud83c\udfc6 Best post: \"${title}\" \u2014 ${views(best).toLocaleString('en-US')} views`;\n}\nif (posts.length === 0) {\n text += `\\nNothing published this week. Approve some clips and the machine does the rest.`;\n}\nreturn [{ json: { digest: text } }];"
},
"id": "write-digest",
"name": "Write the digest",
@ -666,7 +666,7 @@
},
{
"parameters": {
"url": "https://api.openshorts.app/api/social/scheduled",
"url": "http://localhost:8000/api/postiz/scheduled",
"authentication": "genericCredentialType",
"genericAuthType": "httpHeaderAuth",
"options": {}

View file

@ -1,671 +0,0 @@
"""Remote MCP server: the whole pipeline as agent-callable tools at ``/mcp``.
Stateless Streamable-HTTP transport (plain JSON responses, no SSE, no session
ids) implemented directly over FastAPI — the protocol surface an MCP client
actually needs for tools is three methods (initialize / tools/list / tools/call)
plus notifications, and owning those ~200 lines beats carrying the full SDK as
a dependency for them.
Tools don't reimplement anything: each one is an in-process HTTP call back into
this same app (httpx ASGITransport) with the caller's auth headers forwarded.
Cloud mode therefore meters, gates and scopes agent calls exactly like
dashboard calls — an ``osk_`` API key IS the user (see cloud/api_keys.py).
Self-host keeps its BYOK semantics: no key required, ``X-Gemini-Key`` /
env fallbacks apply unchanged.
Connect with any MCP client, e.g.:
claude mcp add --transport http openshorts https://mcp.openshorts.app/mcp \
--header "Authorization: Bearer osk_..."
(mcp.openshorts.app is a domain alias of the API app; api.openshorts.app/mcp
serves the identical endpoint.)
"""
import json
import os
from typing import Optional
import httpx
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse, Response
import mcp_ui
from subtitles import CAPTION_PRESETS, line_budget
router = APIRouter()
PROTOCOL_VERSIONS = ("2025-06-18", "2025-03-26", "2024-11-05")
SERVER_INFO = {"name": "openshorts", "title": "OpenShorts", "version": "1.0.0"}
INSTRUCTIONS = (
"OpenShorts turns long videos (YouTube URLs or direct video files) into "
"viral-ready vertical clips. When the user gives you a video URL, hand it "
"to process_video exactly as written: OpenShorts downloads, transcribes "
"and analyses the video on its own servers. Do NOT try to open, fetch, "
"search for, summarise or transcribe the URL yourself first; you cannot "
"reach the video and it is not needed. Typical flow: process_video -> "
"poll get_job_status until 'completed' (a job takes minutes; poll every "
"30-60s or pass webhook_url) -> list_clips -> optionally add_subtitles / "
"recut_clip / publish_clip. Check get_quota before large jobs. The user "
"must own the content or hold the rights: ask once, then pass "
"confirm_rights=true."
)
# Headers an MCP caller may use to authenticate / bring their own keys; they are
# forwarded verbatim to the internal endpoints so every existing auth path works.
_FORWARD_HEADERS = ("authorization", "x-api-key", "x-gemini-key", "x-upload-post-key")
_LOG_TAIL = 10 # status logs are for humans; agents only need the tail
TOOLS = [
{
"name": "process_video",
"title": "Process a video into short clips",
"description": (
"Start clipping a video from its URL. OpenShorts downloads the "
"source itself, transcribes it, finds the most viral moments with AI "
"and renders vertical (9:16) clips. Captions and the AI hook line are "
"burned by default; pass captions=false or auto_hook=false to skip either. "
"Call this directly "
"with the URL the user gave you; do not fetch, search or inspect the "
"URL yourself first (you cannot access the video, and it is not "
"needed). Returns a job_id immediately — the work takes minutes; "
"poll get_job_status or pass webhook_url to be called back. The "
"caller must own the content or hold the rights to process it "
"(confirm_rights)."
),
"inputSchema": {
"type": "object",
"properties": {
"source_url": {
"type": "string",
"description": "Public video URL, passed through exactly as the user gave it "
"(YouTube watch/short/live URL, a direct video file URL, or a "
"tmpfiles.org link from the create_upload fallback). The server "
"does the downloading. Omit when using upload_id.",
},
"upload_id": {
"type": "string",
"description": "Instead of source_url: the id from create_upload after the "
"file was PUT to its upload_url. Use when the user gave you a "
"video file rather than a link.",
},
"auto_hook": {
"type": "boolean",
"description": "Burn the AI-written hook line (the clip's title) over the first "
"seconds of each clip, as the dashboard does. Default true; set "
"false for clean clips.",
},
"hook_style": {
"type": "string",
"enum": ["classic", "dark", "yellow", "red", "outline", "outline_yellow"],
"description": "Look of the hook text (with auto_hook). Default classic.",
},
"captions": {
"type": "boolean",
"description": "Default true: burn word-level captions on every clip. Set false "
"when the source already has subtitles burned in (they would "
"stack) or the user wants clean clips; add_subtitles can still "
"caption a clip later.",
},
"confirm_rights": {
"type": "boolean",
"description": "Must be true: the user owns the content or has rights to process it.",
},
"layouts": {
"type": "array",
"items": {"type": "string",
"enum": ["auto", "split", "screencast", "speaker_cut", "punch_in"]},
"description": "Optional extra reframe layouts. 'auto' lets AI pick per video.",
},
"output_format": {
"type": "string",
"enum": ["auto", "vertical", "horizontal", "square"],
"description": "Clip aspect. Default auto (vertical).",
},
"webhook_url": {
"type": "string",
"description": "Optional public HTTPS URL POSTed once when the job finishes or fails.",
},
"webhook_secret": {
"type": "string",
"description": "Optional secret; the webhook body is then HMAC-SHA256 signed (X-OpenShorts-Signature).",
},
"force_low_quality": {
"type": "boolean",
"description": "Set true to proceed after a needs_confirmation low-resolution warning.",
},
"target_clips": {
"type": "integer", "minimum": 1, "maximum": 15,
"description": "How many clips to aim for. A target, not a guarantee: "
"fewer come back when the material doesn't hold them. "
"Default: the AI decides (usually 2-6).",
},
"clip_min_seconds": {
"type": "number", "minimum": 5, "maximum": 175,
"description": "Minimum clip length in seconds (default 15).",
},
"clip_max_seconds": {
"type": "number", "minimum": 10, "maximum": 180,
"description": "Maximum clip length in seconds (default 60). Must be ≥ 5s above the minimum.",
},
},
"required": ["confirm_rights"],
},
},
{
"name": "create_upload",
"title": "Reserve an upload slot for a local video file",
"description": (
"Use when the user hands you a video FILE instead of a link. Returns "
"an upload_url: send the file's raw bytes to it with an HTTP PUT "
"(for example `curl -T video.mp4 <upload_url>`), then call "
"process_video with the returned upload_id. Unused slots are "
"deleted after expires_in seconds (6 h); max size is max_mb. "
"FALLBACK if your sandbox cannot reach upload_url: upload the file "
"to tmpfiles.org (`curl -F file=@video.mp4 https://tmpfiles.org/api/v1/upload`), "
"and pass the returned url to process_video as source_url right "
"away (their files expire after 60 minutes; the server refreshes "
"the signed download link itself). Otherwise ask the user to run "
"the curl command or to share a public link."
),
"inputSchema": {
"type": "object",
"properties": {
"filename": {"type": "string", "description": "Original file name (optional, for the extension)."},
},
},
},
{
"name": "get_job_status",
"title": "Get processing job status",
"description": (
"Status of a processing job: 'queued', 'processing', 'completed' or "
"'failed', with recent log lines and, once completed, the clips."
),
"inputSchema": {
"type": "object",
"properties": {"job_id": {"type": "string"}},
"required": ["job_id"],
},
},
{
"name": "list_clips",
"title": "List a job's clips",
"description": (
"The clips of a completed job, with titles, platform-ready "
"descriptions and download URLs. In MCP Apps-capable clients the "
"result also renders as an interactive clip picker."
),
"inputSchema": {
"type": "object",
"properties": {"job_id": {"type": "string"}},
"required": ["job_id"],
},
# Both spellings of the tool->template link: MCP Apps hosts read
# _meta.ui.resourceUri, the ChatGPT Apps SDK reads openai/outputTemplate.
"_meta": {
"ui": {"resourceUri": mcp_ui.CLIP_PICKER_URI},
"openai/outputTemplate": mcp_ui.CLIP_PICKER_URI,
},
},
{
"name": "get_quota",
"title": "Get plan and remaining minutes",
"description": (
"The authenticated user's plan and remaining processing minutes. "
"Call before large jobs; process_video fails with quota_exceeded "
"when the balance is insufficient."
),
"inputSchema": {"type": "object", "properties": {}},
},
{
"name": "add_subtitles",
"title": "Burn styled captions onto a clip",
"description": (
"Re-style the captions of one clip (clips already ship with the "
"'default' preset). Easiest: pass a preset; any other field you send "
"overrides that part of it. Without a preset, style 'karaoke' "
"highlights the active word."
),
"inputSchema": {
"type": "object",
"properties": {
"job_id": {"type": "string"},
"clip_index": {"type": "integer", "description": "0-based index from list_clips."},
"preset": {"type": "string", "enum": list(CAPTION_PRESETS),
"description": (
"default: Anton caps, yellow active word. "
"hormozi: words appear as spoken, yellow active word. "
"pill: purple box behind the active word. "
"lime: lime box behind the active word. "
"oneword: one big word at a time. "
"clean: no outline, soft shadow, sentence case.")},
"style": {"type": "string", "enum": ["classic", "karaoke"]},
"position": {"type": "string", "enum": ["top", "middle", "bottom"]},
"font_size": {"type": "integer",
"description": "44 is the default (M); 34 = S, 56 = L, 70 = XL."},
"font_name": {"type": "string",
"description": "Anton, Montserrat ExtraBold, Verdana, Arial, Impact, Georgia..."},
"font_color": {"type": "string", "description": "Hex color, e.g. #FFFFFF."},
"highlight_color": {"type": "string", "description": "Karaoke active-word color (or box color with effect 'highlight')."},
"effect": {"type": "string", "enum": ["none", "pop", "glow", "box", "highlight"],
"description": "Karaoke active-word effect; 'highlight' = solid box behind it."},
"reveal": {"type": "boolean", "description": "Karaoke: words appear as they are spoken."},
"one_word": {"type": "boolean", "description": "Show one word at a time."},
"shadow": {"type": "integer", "description": "Drop shadow depth 0-6."},
"border_width": {"type": "integer", "description": "Outline 0-10 (0 needs a shadow to stay readable)."},
"uppercase": {"type": "boolean"},
},
"required": ["job_id", "clip_index"],
},
},
{
"name": "recut_clip",
"title": "Re-cut a clip from an edited segment list",
"description": (
"Re-render one clip from a new list of source-video segments (the "
"same engine behind the dashboard's clip editor). Times are seconds "
"in the ORIGINAL source video; segments are concatenated in the "
"given order, so you can trim, extend, drop a dead moment in the "
"middle, or reorder. Segments inside the clip's original range "
"re-render in seconds; going outside needs the retained source "
"video and re-runs the reframe engine."
),
"inputSchema": {
"type": "object",
"properties": {
"job_id": {"type": "string"},
"clip_index": {"type": "integer", "description": "0-based index from list_clips."},
"segments": {
"type": "array",
"items": {
"type": "object",
"properties": {
"start": {"type": "number", "description": "Seconds in the source video."},
"end": {"type": "number", "description": "Seconds in the source video."},
},
"required": ["start", "end"],
},
"minItems": 1,
"description": "Ordered source segments the new clip is made of.",
},
"snap_to_words": {
"type": "boolean",
"description": "Snap each boundary onto transcript word boundaries (recommended).",
},
"reapply_captions": {
"type": "boolean",
"description": "Burn default captions back on after the recut (default true).",
},
"framing": {
"type": "string", "enum": ["auto", "full", "track"],
"description": "Layout override: 'full' shows the whole source frame "
"(no side-cropping), 'track' forces the subject-tracking "
"crop, 'auto' resets to the AI classifier. Omit to keep "
"the clip's current framing. Non-auto values re-run the "
"reframe engine and need the retained source video.",
},
},
"required": ["job_id", "clip_index", "segments"],
},
},
{
"name": "publish_clip",
"title": "Publish a clip to social platforms",
"description": (
"Post one clip to the user's connected accounts (TikTok lands as a "
"draft in the app; Instagram and YouTube publish directly). Requires "
"a connected social profile (cloud) or an Upload-Post key (self-host). "
"Optionally schedule with an ISO-8601 scheduled_date."
),
"inputSchema": {
"type": "object",
"properties": {
"job_id": {"type": "string"},
"clip_index": {"type": "integer"},
"platforms": {
"type": "array",
"items": {"type": "string", "enum": ["tiktok", "instagram", "youtube"]},
},
"title": {"type": "string"},
"description": {"type": "string"},
"scheduled_date": {"type": "string", "description": "ISO-8601; omit to post now."},
"timezone": {"type": "string"},
},
"required": ["job_id", "clip_index", "platforms"],
},
},
]
# --------------------------------------------------------------------------- #
# Internal dispatch: each tool is an in-process call to the existing REST API.
# --------------------------------------------------------------------------- #
def _client(request: Request) -> httpx.AsyncClient:
headers = {k: v for k, v in request.headers.items() if k.lower() in _FORWARD_HEADERS}
return httpx.AsyncClient(
transport=httpx.ASGITransport(app=request.app, raise_app_exceptions=False),
base_url="http://openshorts.internal",
headers=headers,
timeout=300.0,
)
def _api_error(resp: httpx.Response) -> dict:
try:
detail = resp.json().get("detail")
except Exception:
detail = resp.text[:300]
return {"error": detail or f"HTTP {resp.status_code}", "http_status": resp.status_code}
async def _tool_process_video(client, args):
if not args.get("confirm_rights"):
return {"error": "confirm_rights must be true: the user must own the "
"content or hold the rights to process it."}, True
if not args.get("source_url") and not args.get("upload_id"):
return {"error": "Give source_url (a public video link) or upload_id (from create_upload)."}, True
body = {
"url": args.get("source_url"),
"upload_id": args.get("upload_id"),
"acknowledged": True,
"layouts": args.get("layouts") or [],
"output_format": args.get("output_format"),
"force_low_quality": bool(args.get("force_low_quality")),
"webhook_url": args.get("webhook_url"),
"webhook_secret": args.get("webhook_secret"),
}
for k in ("target_clips", "clip_min_seconds", "clip_max_seconds", "captions"):
if args.get(k) is not None:
body[k] = args[k]
# Same default as the dashboard: hook on unless the caller opts out. The
# REST endpoint keeps "absent = off" for older integrations; the MCP
# tool is newer than the hook and its users expect the dashboard output.
if args.get("auto_hook", True):
body["auto_hook"] = True
if args.get("hook_style"):
body["auto_hook_style"] = args["hook_style"]
resp = await client.post("/api/process", json=body)
if resp.status_code >= 400:
return _api_error(resp), True
data = resp.json()
if data.get("needs_confirmation"):
data["hint"] = ("Source resolution is below the quality gate. Ask the "
"user, then retry with force_low_quality=true to proceed.")
return data, False
data["hint"] = ("Processing takes minutes. Poll get_job_status every 30-60s"
+ ("" if body["webhook_url"] else " (or re-run with webhook_url for a callback)") + ".")
return data, False
async def _tool_create_upload(client, args):
resp = await client.post("/api/uploads", json={"filename": args.get("filename") or "video.mp4"})
if resp.status_code >= 400:
return _api_error(resp), True
return resp.json(), False
async def _tool_get_job_status(client, args):
resp = await client.get(f"/api/status/{args['job_id']}")
if resp.status_code >= 400:
return _api_error(resp), True
data = resp.json()
out = {"job_id": args["job_id"], "status": data.get("status"),
"recent_logs": (data.get("logs") or [])[-_LOG_TAIL:]}
if data.get("status") == "completed":
out["clips"] = _clip_summaries(args["job_id"], data.get("result") or {})
return out, data.get("status") == "failed"
def _clip_summaries(job_id, result):
base = os.environ.get("PUBLIC_API_URL", "").rstrip("/")
out = []
for i, clip in enumerate(result.get("clips") or []):
rel = clip.get("video_url") or ""
out.append({
"index": i,
"title": clip.get("title") or clip.get("video_title_for_youtube_short"),
"duration_seconds": (round(clip["end"] - clip["start"], 1)
if isinstance(clip.get("start"), (int, float))
and isinstance(clip.get("end"), (int, float)) else None),
"video_url": f"{base}{rel}" if base and rel.startswith("/") else rel,
"youtube_title": clip.get("video_title_for_youtube_short"),
"tiktok_description": clip.get("video_description_for_tiktok"),
"instagram_description": clip.get("video_description_for_instagram"),
})
return out
async def _tool_list_clips(client, args):
out, is_error = await _tool_get_job_status(client, args)
if is_error:
return out, True
if out.get("status") != "completed":
return {"error": f"Job is {out.get('status')}, clips are not ready yet.",
"status": out.get("status")}, True
return {"job_id": args["job_id"], "clips": out.get("clips") or []}, False
async def _tool_get_quota(client, args):
resp = await client.get("/api/me")
# 401: anonymous. 404: self-host, where /api/me isn't even mounted (the
# cloud router only registers under BILLING_ENABLED). Neither is an error
# from the agent's point of view — there is simply no quota to report.
if resp.status_code in (401, 404):
return {"self_host_or_anonymous": True,
"note": "No authenticated cloud user; if this is a self-hosted "
"instance there is no minute quota."}, False
if resp.status_code >= 400:
return _api_error(resp), True
data = resp.json()
return {"plan": data.get("plan"), "entitled": data.get("entitled"),
"minutes": data.get("minutes"),
"upload_post_profile": data.get("upload_post_profile")}, False
async def _tool_add_subtitles(client, args):
body = {"job_id": args["job_id"], "clip_index": args["clip_index"]}
for k in ("preset", "style", "position", "font_size", "font_name", "font_color",
"highlight_color", "effect", "reveal", "shadow", "border_width",
"uppercase"):
if args.get(k) is not None:
body[k] = args[k]
if args.get("one_word"):
body["max_chars"] = 1
elif ("font_size" in body or "font_name" in body) and \
CAPTION_PRESETS.get(str(body.get("preset") or "").lower(), {}).get("max_chars") != 1:
# A resized or refonted line gets the budget that keeps it on one
# line, as the dashboard does; the preset's font fills the gap.
base = CAPTION_PRESETS.get(str(body.get("preset") or "default").lower(),
CAPTION_PRESETS["default"])
body["max_chars"] = line_budget(body.get("font_name", base["font_name"]),
body.get("font_size", base["font_size"]))
resp = await client.post("/api/subtitle", json=body)
if resp.status_code >= 400:
return _api_error(resp), True
return resp.json(), False
async def _tool_recut_clip(client, args):
body = {"job_id": args["job_id"], "clip_index": args["clip_index"],
"segments": args["segments"]}
for k in ("snap_to_words", "reapply_captions", "framing"):
if args.get(k) is not None:
body[k] = args[k]
resp = await client.post("/api/clip/rerender", json=body)
if resp.status_code >= 400:
return _api_error(resp), True
return resp.json(), False
async def _tool_publish_clip(client, args):
body = {"job_id": args["job_id"], "clip_index": args["clip_index"],
"platforms": args["platforms"]}
for k in ("title", "description", "scheduled_date", "timezone"):
if args.get(k) is not None:
body[k] = args[k]
resp = await client.post("/api/social/post", json=body)
if resp.status_code >= 400:
return _api_error(resp), True
return resp.json(), False
_TOOL_IMPLS = {
"process_video": _tool_process_video,
"create_upload": _tool_create_upload,
"get_job_status": _tool_get_job_status,
"list_clips": _tool_list_clips,
"get_quota": _tool_get_quota,
"add_subtitles": _tool_add_subtitles,
"recut_clip": _tool_recut_clip,
"publish_clip": _tool_publish_clip,
}
async def call_tool(request: Request, name: str, args: dict) -> tuple[dict, bool]:
impl = _TOOL_IMPLS.get(name)
if impl is None:
return {"error": f"Unknown tool: {name}"}, True
try:
async with _client(request) as client:
return await impl(client, args or {})
except KeyError as e:
return {"error": f"Missing required argument: {e}"}, True
except Exception as e:
return {"error": f"Tool failed: {e}"}, True
# --------------------------------------------------------------------------- #
# JSON-RPC / MCP protocol layer (pure: testable without the app)
# --------------------------------------------------------------------------- #
def _rpc_error(msg_id, code, message):
return {"jsonrpc": "2.0", "id": msg_id, "error": {"code": code, "message": message}}
def _rpc_result(msg_id, result):
return {"jsonrpc": "2.0", "id": msg_id, "result": result}
async def handle_message(msg, tool_caller) -> Optional[dict]:
"""One JSON-RPC message in, one response dict out (None for notifications).
``tool_caller(name, args) -> (result_dict, is_error)`` is injected so this
layer stays free of HTTP and app state.
"""
if not isinstance(msg, dict) or msg.get("jsonrpc") != "2.0":
return _rpc_error(None, -32600, "Expected a JSON-RPC 2.0 message")
method = msg.get("method")
msg_id = msg.get("id")
if method is None:
# A response from the client (has 'result'/'error') — nothing to do.
return None
if msg_id is None:
return None # notification (e.g. notifications/initialized): accept silently
if method == "initialize":
client_version = (msg.get("params") or {}).get("protocolVersion")
version = client_version if client_version in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0]
return _rpc_result(msg_id, {
"protocolVersion": version,
"capabilities": {"tools": {"listChanged": False},
"resources": {"listChanged": False}},
"serverInfo": SERVER_INFO,
"instructions": INSTRUCTIONS,
})
if method == "ping":
return _rpc_result(msg_id, {})
if method == "tools/list":
return _rpc_result(msg_id, {"tools": TOOLS})
if method == "resources/list":
return _rpc_result(msg_id, {"resources": mcp_ui.RESOURCES})
if method == "resources/templates/list":
return _rpc_result(msg_id, {"resourceTemplates": []})
if method == "resources/read":
uri = (msg.get("params") or {}).get("uri") or ""
# Per-call URIs (ui://openshorts/clip-picker/<job>) resolve to the same
# template; the data those carried was baked into the tool result.
if uri == mcp_ui.CLIP_PICKER_URI or uri.startswith(mcp_ui.CLIP_PICKER_URI + "/"):
return _rpc_result(msg_id, {"contents": [{
"uri": uri,
"mimeType": mcp_ui.MIME_TYPE,
"text": mcp_ui.clip_picker_html(),
}]})
return _rpc_error(msg_id, -32002, f"Resource not found: {uri}")
if method == "tools/call":
params = msg.get("params") or {}
name = params.get("name")
result, is_error = await tool_caller(name, params.get("arguments") or {})
content = [{"type": "text", "text": json.dumps(result, ensure_ascii=False)}]
# A successful list_clips additionally ships the picker with its data
# baked in, so hosts that render embedded resources need no bridge.
# Non-UI clients ignore extra content entries.
if name == "list_clips" and not is_error and result.get("clips"):
content.append({"type": "resource", "resource": {
"uri": f"{mcp_ui.CLIP_PICKER_URI}/{result.get('job_id', 'result')}",
"mimeType": mcp_ui.MIME_TYPE,
"text": mcp_ui.clip_picker_html(result),
}})
return _rpc_result(msg_id, {
"content": content,
"structuredContent": result,
"isError": is_error,
})
return _rpc_error(msg_id, -32601, f"Method not found: {method}")
# --------------------------------------------------------------------------- #
# Transport endpoints
# --------------------------------------------------------------------------- #
def _billing_enabled() -> bool:
return os.environ.get("BILLING_ENABLED", "").lower() in ("1", "true", "yes")
async def _authorized(request: Request) -> bool:
"""Cloud mode requires a resolvable user (API key or JWT) before any RPC.
The internal endpoints would each reject anonymous calls anyway; failing
once here with a clear 401 is what lets MCP clients surface 'add your API
key' instead of a per-tool 402. Self-host stays open (BYOK)."""
if not _billing_enabled():
return True
from cloud.auth import get_current_user_optional
return (await get_current_user_optional(request)) is not None
@router.post("/mcp")
async def mcp_endpoint(request: Request):
if not await _authorized(request):
# OAuth-capable clients (claude.ai, ChatGPT) read resource_metadata off
# this header and run the login flow themselves; everyone else gets the
# API-key hint in the body.
from cloud import mcp_oauth
u = request.base_url
return JSONResponse(
{"error": "Authentication required. Connect with OAuth (claude.ai, ChatGPT) "
"or pass an OpenShorts API key: Authorization: Bearer osk_... "
"(create one in the dashboard)."},
status_code=401,
headers={"WWW-Authenticate": mcp_oauth.www_authenticate(f"{u.scheme}://{u.netloc}")},
)
try:
msg = json.loads(await request.body())
except Exception:
return JSONResponse(_rpc_error(None, -32700, "Parse error"), status_code=400)
if isinstance(msg, list):
return JSONResponse(_rpc_error(None, -32600, "Batching is not supported"),
status_code=400)
async def tool_caller(name, args):
return await call_tool(request, name, args)
response = await handle_message(msg, tool_caller)
if response is None:
return Response(status_code=202)
return JSONResponse(response)
@router.get("/mcp")
async def mcp_get():
# Stateless server: no server-initiated SSE stream to offer.
return Response(status_code=405, headers={"Allow": "POST"})

View file

@ -1,125 +0,0 @@
"""Stdio transport for the same MCP server that ``/mcp`` serves over HTTP.
``mcp_server.py`` owns the protocol; this file is only a transport: it reads
newline-delimited JSON-RPC from stdin, hands each message to
``mcp_server.handle_message`` and writes the response to stdout. Tool calls go
through the identical in-process path (``call_tool`` -> httpx ASGITransport ->
this app), so stdio and HTTP can never answer differently.
Why it exists: some hosts only launch MCP servers as a subprocess (Glama's
Dockerfile deployments wrap a stdio command, and a local client that would
rather not run a web server can do
``claude mcp add openshorts -- python mcp_stdio.py``). The hosted endpoint at
mcp.openshorts.app stays the HTTP one.
Two things this transport has to get right:
- **stdout belongs to the protocol.** The pipeline prints progress everywhere
(main.py, app.py, yt-dlp), and one stray line corrupts the JSON-RPC stream,
so ``sys.stdout`` is swapped for stderr before the app is imported and the
real handle is kept private to the writer below.
- **The app's lifespan must run.** Job queues, output dirs and the resume scan
are set up there; ASGITransport does not run it on its own.
"""
import asyncio
import json
import os
import sys
# Must happen before importing app: import-time prints would land on stdout.
_PROTOCOL_OUT = sys.stdout
sys.stdout = sys.stderr
from starlette.requests import Request # noqa: E402
import app as app_module # noqa: E402
import mcp_server # noqa: E402
# BYOK credentials reach the tools the same way an HTTP client would send them:
# as forwarded headers (mcp_server._FORWARD_HEADERS), not as a second code path.
_ENV_HEADERS = {
"authorization": lambda: (
f"Bearer {os.environ['OPENSHORTS_API_KEY']}"
if os.environ.get("OPENSHORTS_API_KEY") else None
),
"x-gemini-key": lambda: os.environ.get("GEMINI_API_KEY"),
"x-upload-post-key": lambda: os.environ.get("UPLOAD_POST_API_KEY"),
}
def _request() -> Request:
"""A synthetic ASGI request carrying the app and the auth headers.
``mcp_server.call_tool`` only reads ``.app`` and ``.headers`` off it."""
headers = []
for name, read in _ENV_HEADERS.items():
value = read()
if value:
headers.append((name.encode(), value.encode()))
return Request({
"type": "http",
"asgi": {"version": "3.0"},
"http_version": "1.1",
"method": "POST",
"scheme": "http",
"path": "/mcp",
"raw_path": b"/mcp",
"query_string": b"",
"root_path": "",
"headers": headers,
"client": ("127.0.0.1", 0),
"server": ("openshorts.internal", 80),
"app": app_module.app,
})
def _write(response: dict) -> None:
_PROTOCOL_OUT.write(json.dumps(response, ensure_ascii=False) + "\n")
_PROTOCOL_OUT.flush()
async def _stdin_lines():
"""Yield stdin lines without blocking the loop (tool calls run for minutes)."""
loop = asyncio.get_running_loop()
reader = asyncio.StreamReader()
await loop.connect_read_pipe(lambda: asyncio.StreamReaderProtocol(reader), sys.stdin)
while True:
line = await reader.readline()
if not line: # EOF: the host closed the pipe
return
yield line
async def _serve() -> None:
async with app_module.app.router.lifespan_context(app_module.app):
request = _request()
async def tool_caller(name, args):
return await mcp_server.call_tool(request, name, args)
async for line in _stdin_lines():
line = line.strip()
if not line:
continue
try:
msg = json.loads(line)
except Exception:
_write(mcp_server._rpc_error(None, -32700, "Parse error"))
continue
if isinstance(msg, list):
_write(mcp_server._rpc_error(None, -32600, "Batching is not supported"))
continue
response = await mcp_server.handle_message(msg, tool_caller)
if response is not None:
_write(response)
def main() -> None:
try:
asyncio.run(_serve())
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()

195
mcp_ui.py
View file

@ -1,195 +0,0 @@
"""MCP Apps surface: an embedded clip picker for UI-capable MCP clients.
The pipeline returns 3-15 clips per job; choosing which ones to publish by
looking at them beats reading titles out of JSON. Clients that support the MCP
Apps extension (ChatGPT apps, mcp-ui hosts, Claude) render the HTML below in a
sandboxed iframe; every other client ignores it and keeps working from the
text/structured content exactly as before.
One template, three data paths, because the ecosystem hasn't converged:
1. Baked-in JSON — the per-call embedded resource appended to a successful
list_clips result carries its data inline and renders with no bridge.
2. window.openai.toolOutput — the ChatGPT Apps SDK injects the tool's
structuredContent there; the tool's _meta names this template.
3. postMessage handshake — MCP Apps / mcp-ui hosts that serve the template
from resources/read and push render data after the iframe reports ready.
The iframe cannot fetch anything (host CSP), so the video previews use the
clips' absolute URLs and everything else is inline.
"""
import json
CLIP_PICKER_URI = "ui://openshorts/clip-picker"
MIME_TYPE = "text/html;profile=mcp-app"
RESOURCES = [
{
"uri": CLIP_PICKER_URI,
"name": "clip-picker",
"title": "OpenShorts clip picker",
"description": (
"Interactive picker for a job's finished clips: preview each 9:16 "
"clip, select the keepers and publish them to TikTok, Instagram or "
"YouTube without leaving the conversation."
),
"mimeType": MIME_TYPE,
},
]
# Kept as a plain string with a token instead of an f-string: the JS is full of
# braces and escaping them all is how bugs get in.
_TEMPLATE = """<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
:root{--paper:oklch(13% 0.014 265);--paper2:oklch(16.5% 0.015 265);
--ink:oklch(96% 0.006 262);--ink2:oklch(86% 0.01 262);--muted:oklch(64% 0.012 262);
--rule:oklch(96% 0.006 262 / .12);--brass:oklch(76% 0.17 50);--ok:oklch(75% 0.11 150)}
*{box-sizing:border-box}
body{margin:0;background:var(--paper);color:var(--ink2);
font-family:ui-sans-serif,system-ui,-apple-system,sans-serif;font-size:14px;padding:12px}
h1{font-size:15px;font-weight:600;color:var(--ink);margin:0 0 10px}
.grid{display:grid;gap:10px;grid-template-columns:repeat(auto-fill,minmax(150px,1fr))}
.card{background:var(--paper2);border:1px solid var(--rule);border-radius:10px;
padding:8px;cursor:pointer}
.card.sel{border-color:var(--brass)}
.card video{width:100%;aspect-ratio:9/16;border-radius:6px;background:#000;display:block}
.card .t{margin-top:6px;font-size:12px;color:var(--ink);line-height:1.3;
display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
.card .d{font-size:11px;color:var(--muted);margin-top:2px}
.bar{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin-top:12px}
.chip{border:1px solid var(--rule);border-radius:999px;padding:4px 12px;font-size:12px;
cursor:pointer;user-select:none;color:var(--muted)}
.chip.on{border-color:var(--brass);color:var(--ink)}
button{background:var(--brass);color:oklch(17% 0.03 50);border:0;border-radius:8px;
padding:7px 14px;font-size:13px;font-weight:600;cursor:pointer}
button:disabled{opacity:.4;cursor:default}
.msg{font-size:12px;color:var(--ok);margin-top:8px;min-height:16px}
.empty{color:var(--muted)}
</style>
</head>
<body>
<h1 id="hd">OpenShorts clips</h1>
<div class="grid" id="grid"><span class="empty">Waiting for clip data…</span></div>
<div class="bar" id="bar" hidden>
<span class="chip on" data-p="tiktok">TikTok</span>
<span class="chip on" data-p="instagram">Instagram</span>
<span class="chip" data-p="youtube">YouTube</span>
<button id="pub" disabled>Publish selected</button>
</div>
<div class="msg" id="msg"></div>
<script>
var inline = __OPENSHORTS_DATA__;
var state = null;
var selected = {};
function callTool(name, params) {
if (window.openai && window.openai.callTool) {
return window.openai.callTool(name, params);
}
window.parent.postMessage({type: 'tool', payload: {toolName: name, params: params}}, '*');
}
function platforms() {
var out = [];
document.querySelectorAll('.chip.on').forEach(function (c) { out.push(c.dataset.p); });
return out;
}
function refreshButton() {
var n = Object.keys(selected).length;
var btn = document.getElementById('pub');
btn.disabled = n === 0 || platforms().length === 0;
btn.textContent = n ? 'Publish ' + n + ' clip' + (n > 1 ? 's' : '') : 'Publish selected';
}
function render(data) {
state = data;
var clips = data.clips || [];
document.getElementById('hd').textContent =
clips.length + ' clip' + (clips.length !== 1 ? 's' : '') +
(data.job_id ? ' · job ' + data.job_id : '');
var grid = document.getElementById('grid');
grid.textContent = '';
clips.forEach(function (clip) {
var card = document.createElement('div');
card.className = 'card';
if (clip.video_url) {
var v = document.createElement('video');
v.src = clip.video_url;
v.muted = true; v.controls = true; v.playsInline = true; v.preload = 'metadata';
card.appendChild(v);
}
var t = document.createElement('div');
t.className = 't';
t.textContent = clip.title || ('Clip ' + clip.index);
card.appendChild(t);
var d = document.createElement('div');
d.className = 'd';
d.textContent = clip.duration_seconds ? clip.duration_seconds + 's' : '';
card.appendChild(d);
card.addEventListener('click', function (ev) {
if (ev.target.tagName === 'VIDEO') return; // let the player play
if (selected[clip.index]) { delete selected[clip.index]; card.classList.remove('sel'); }
else { selected[clip.index] = true; card.classList.add('sel'); }
refreshButton();
});
grid.appendChild(card);
});
document.getElementById('bar').hidden = clips.length === 0;
refreshButton();
}
document.querySelectorAll('.chip').forEach(function (c) {
c.addEventListener('click', function () { c.classList.toggle('on'); refreshButton(); });
});
document.getElementById('pub').addEventListener('click', function () {
var idxs = Object.keys(selected);
var ps = platforms();
idxs.forEach(function (i) {
callTool('publish_clip', {job_id: state.job_id, clip_index: parseInt(i, 10), platforms: ps});
});
document.getElementById('msg').textContent =
'Publish requested for ' + idxs.length + ' clip(s) to ' + ps.join(', ') +
'. Results arrive in the conversation.';
});
// Data path 2: ChatGPT Apps SDK injects structuredContent here.
function fromOpenai() {
var o = window.openai && (window.openai.toolOutput || window.openai.toolResponse);
if (o && o.clips) { render(o); return true; }
return false;
}
// Data path 3: MCP Apps / mcp-ui hosts push render data after we report ready.
window.addEventListener('message', function (ev) {
var m = ev.data || {};
var d = (m.payload && (m.payload.renderData || m.payload.toolOutput ||
m.payload.structuredContent)) ||
m.renderData || m.toolOutput || m.structuredContent;
if (d && d.clips) render(d);
});
window.addEventListener('openai:set_globals', fromOpenai);
if (inline && inline.clips) { render(inline); } // data path 1
else if (!fromOpenai()) {
try { window.parent.postMessage({type: 'ui-lifecycle-iframe-ready'}, '*'); } catch (e) {}
}
</script>
</body>
</html>
"""
def clip_picker_html(data=None) -> str:
"""The picker HTML; ``data`` baked in when rendering a per-call resource.
``<`` is escaped in the JSON so a clip title can never close the script
tag and inject markup.
"""
payload = "null" if data is None else json.dumps(
data, ensure_ascii=False).replace("<", "\\u003c")
return _TEMPLATE.replace("__OPENSHORTS_DATA__", payload)

161
postiz.py Normal file
View file

@ -0,0 +1,161 @@
"""Thin synchronous client for the self-hosted Postiz public API.
One place that knows the Postiz base path and auth convention so ``app.py`` can
stay about request handling. Every function is blocking; call them through
``asyncio.to_thread`` from async handlers (video uploads are tens of seconds).
Auth is the RAW API key in the ``Authorization`` header -- NO ``Bearer`` prefix
(see /tmp/opencode/cleanup/postiz-api.md). The base URL defaults to the
``POSTIZ_URL`` env var and can be overridden per call; the API path prefix
``/api/public/v1`` is appended automatically when the caller passes a bare host.
"""
import os
from typing import Any, Dict, List, Optional
import httpx
_API_PREFIX = "/api/public/v1"
_DEFAULT_BASE = "https://postiz.pbento.pt"
# Postiz sniffs the MIME of /upload payloads: video must be video/mp4. We send
# the honest content type for the file extension rather than a blanket octet.
_MIME_BY_EXT = {
".mp4": "video/mp4",
".mov": "video/quicktime",
".webm": "video/webm",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".webp": "image/webp",
".gif": "image/gif",
}
class PostizError(Exception):
"""A non-2xx response (or missing config) from Postiz.
Carries the upstream status and body so the FastAPI layer can translate it
into the same status/detail it would have surfaced before.
"""
def __init__(self, status_code: int, detail: str):
super().__init__(detail)
self.status_code = status_code
self.detail = detail
def _resolve_base(base: Optional[str]) -> str:
base = (base or os.environ.get("POSTIZ_URL") or _DEFAULT_BASE).strip().rstrip("/")
if base.endswith(_API_PREFIX):
return base
return base + _API_PREFIX
def _resolve_key(key: Optional[str]) -> str:
key = (key or os.environ.get("POSTIZ_API_KEY") or "").strip()
if not key:
raise PostizError(400, "Missing Postiz API key")
return key
def _headers(key: Optional[str]) -> Dict[str, str]:
# Raw key, no "Bearer".
return {"Authorization": _resolve_key(key)}
def _mime_for(path: str) -> str:
return _MIME_BY_EXT.get(os.path.splitext(path)[1].lower(),
"application/octet-stream")
def _handle(resp: httpx.Response) -> Any:
if resp.status_code not in (200, 201, 202):
raise PostizError(resp.status_code, f"Postiz API Error: {resp.text}")
if resp.status_code == 204 or not resp.content:
return None
try:
return resp.json()
except ValueError:
return None
def list_integrations(base: Optional[str] = None, key: Optional[str] = None,
timeout: float = 30.0) -> List[Dict[str, Any]]:
"""Connected channels: ``[{id, name, identifier, picture, disabled, profile}]``."""
with httpx.Client(timeout=timeout) as client:
resp = client.get(f"{_resolve_base(base)}/integrations", headers=_headers(key))
data = _handle(resp)
return data if isinstance(data, list) else (data or {}).get("integrations", []) or []
def list_integrations_settings(base: Optional[str], key: Optional[str],
integration_id: str,
timeout: float = 30.0) -> Dict[str, Any]:
"""Live schema/rules for one channel, to validate a post before sending it."""
with httpx.Client(timeout=timeout) as client:
resp = client.get(
f"{_resolve_base(base)}/integration-settings/{integration_id}",
headers=_headers(key))
return _handle(resp) or {}
def upload_media(base: Optional[str], key: Optional[str], path: str,
timeout: float = 600.0) -> Dict[str, Any]:
"""Upload a local file (multipart field ``file``) and return ``{id, path}``."""
filename = os.path.basename(path)
with open(path, "rb") as handle:
files = {"file": (filename, handle, _mime_for(path))}
with httpx.Client(timeout=timeout) as client:
resp = client.post(f"{_resolve_base(base)}/upload",
headers=_headers(key), files=files)
return _handle(resp) or {}
def create_post(base: Optional[str], key: Optional[str], payload: Dict[str, Any],
timeout: float = 90.0) -> Any:
"""Create draft/scheduled/immediate posts. Returns the Postiz response list."""
with httpx.Client(timeout=timeout) as client:
resp = client.post(f"{_resolve_base(base)}/posts",
headers=_headers(key), json=payload)
return _handle(resp)
def list_posts(base: Optional[str], key: Optional[str], start: str, end: str,
timeout: float = 60.0) -> List[Dict[str, Any]]:
"""Posts in a date window. Both ``startDate`` and ``endDate`` are required."""
params = {"startDate": start, "endDate": end}
with httpx.Client(timeout=timeout) as client:
resp = client.get(f"{_resolve_base(base)}/posts",
headers=_headers(key), params=params)
data = _handle(resp)
if isinstance(data, list):
return data
return (data or {}).get("posts", []) or []
def delete_post(base: Optional[str], key: Optional[str], post_id: str,
timeout: float = 30.0) -> Any:
with httpx.Client(timeout=timeout) as client:
resp = client.delete(f"{_resolve_base(base)}/posts/{post_id}",
headers=_headers(key))
return _handle(resp)
def analytics(base: Optional[str], key: Optional[str], integration: str,
days: int = 30, timeout: float = 60.0) -> Dict[str, Any]:
"""Per-channel analytics over the last ``days`` days."""
with httpx.Client(timeout=timeout) as client:
resp = client.get(f"{_resolve_base(base)}/analytics/{integration}",
headers=_headers(key), params={"date": days})
return _handle(resp) or {}
def analytics_post(base: Optional[str], key: Optional[str], post_id: str,
days: int = 30, timeout: float = 60.0) -> Dict[str, Any]:
"""Analytics for a single published post."""
with httpx.Client(timeout=timeout) as client:
resp = client.get(f"{_resolve_base(base)}/analytics/post/{post_id}",
headers=_headers(key), params={"date": days})
return _handle(resp) or {}

View file

@ -7,7 +7,7 @@ tqdm==4.67.3
yt-dlp
faster-whisper==1.2.1
py3langid==0.3.0
google-genai==1.75.0
google-genai>=2,<3
python-dotenv==1.2.2
mediapipe==0.10.14
boto3==1.43.4
@ -17,4 +17,3 @@ uvicorn==0.46.0
python-multipart==0.0.27
httpx==0.28.1
Pillow==12.2.0
beautifulsoup4==4.14.3

View file

@ -31,8 +31,6 @@ def upload_file_to_s3(file_path, bucket_name, s3_key):
region_name=region
)
try:
# Extra arguments for public read if needed, but the user didn't specify.
# Given the bucket name, it might be for a web app.
s3_client.upload_file(file_path, bucket_name, s3_key)
return True
except ClientError:
@ -42,15 +40,6 @@ def upload_file_to_s3(file_path, bucket_name, s3_key):
from botocore.config import Config
import json
import time as time_module
# Simple in-memory cache for gallery clips
_clips_cache = {
"data": None,
"timestamp": 0
}
CACHE_TTL_SECONDS = 300 # 5 minutes
def get_s3_client():
"""Returns an authenticated S3 client."""
@ -84,349 +73,6 @@ def generate_presigned_url(bucket_name, object_key, expiration=3600):
logger.error(e)
return None
def list_all_clips(bucket_name=None, limit=50, force_refresh=False):
"""
List recent clips from the S3 bucket by finding metadata files.
Returns a list of dicts containing clip info and signed URLs.
Args:
bucket_name: S3 bucket name (defaults to AWS_S3_BUCKET env var)
limit: Maximum number of clips to return (default 50 for speed)
force_refresh: If True, bypass cache
"""
global _clips_cache
# Check cache first
now = time_module.time()
if not force_refresh and _clips_cache["data"] is not None:
if now - _clips_cache["timestamp"] < CACHE_TTL_SECONDS:
cached = _clips_cache["data"]
return cached[:limit] if limit else cached
if not bucket_name:
bucket_name = os.environ.get('AWS_S3_BUCKET', 'my-clips-bucket')
s3_client = get_s3_client()
if not s3_client:
return []
all_clips = []
try:
# List all objects in bucket
# Note: For very large buckets, pagination is needed.
# Assuming reasonable size for now, but adding continuation token support is best practice.
paginator = s3_client.get_paginator('list_objects_v2')
pages = paginator.paginate(Bucket=bucket_name)
metadata_files = []
for page in pages:
if 'Contents' in page:
for obj in page['Contents']:
if obj['Key'].endswith('_metadata.json'):
metadata_files.append(obj)
# Sort metadata by LastModified (newest first)
metadata_files.sort(key=lambda x: x['LastModified'], reverse=True)
for meta_obj in metadata_files:
key = meta_obj['Key']
# key format: {job_id}/..._metadata.json
# Read metadata content
try:
obj_resp = s3_client.get_object(Bucket=bucket_name, Key=key)
content = obj_resp['Body'].read().decode('utf-8')
data = json.loads(content)
parts = key.split('/')
job_id = parts[0] if len(parts) > 1 else "unknown"
# Filename base for clips in same folder
# Meta key: "job_id/filename_metadata.json"
# Base name in metadata usually matches filename without ext
meta_filename = os.path.basename(key)
base_name = meta_filename.replace('_metadata.json', '')
clips_data = data.get('shorts', [])
for i, clip in enumerate(clips_data):
clip_filename = f"{base_name}_clip_{i+1}.mp4"
clip_key = f"{job_id}/{clip_filename}"
# Generate signed URL
signed_url = generate_presigned_url(bucket_name, clip_key, expiration=7200) # 2 hours
if signed_url:
all_clips.append({
"job_id": job_id,
"index": i,
"url": signed_url,
"title": clip.get('video_title_for_youtube_short', 'Untitled Clip'),
"tiktok_desc": clip.get('video_description_for_tiktok', ''),
"insta_desc": clip.get('video_description_for_instagram', ''),
"created_at": meta_obj['LastModified'].isoformat(),
"duration": clip.get('end', 0) - clip.get('start', 0)
})
# Early exit if we have enough clips
if limit and len(all_clips) >= limit:
break
# Early exit if we have enough clips
if limit and len(all_clips) >= limit:
break
except Exception as e:
logger.error(f"Error processing metadata {key}: {e}")
continue
except Exception as e:
logger.error(f"Error listing bucket: {e}")
return []
# Update cache with full results (keep for pagination later)
_clips_cache["data"] = all_clips
_clips_cache["timestamp"] = now
return all_clips[:limit] if limit else all_clips
def upload_actor_to_s3(file_path, description=""):
"""
Upload an actor image to the public S3 bucket.
Returns the public URL or None on failure.
"""
bucket_name = os.environ.get('AWS_S3_PUBLIC_BUCKET', 'my-public-bucket')
region = os.environ.get('AWS_REGION', 'eu-west-3')
s3_client = get_s3_client()
if not s3_client:
return None
import uuid
unique_id = str(uuid.uuid4())[:8]
filename = os.path.basename(file_path)
name, ext = os.path.splitext(filename)
s3_key = f"avatars/{name}_{unique_id}{ext}"
try:
# Skip broken/tiny files
if os.path.getsize(file_path) < 1000:
logger.warning(f"Skipping tiny file ({os.path.getsize(file_path)} bytes): {file_path}")
return None
s3_client.upload_file(
file_path, bucket_name, s3_key,
ExtraArgs={'ContentType': 'image/png'},
)
public_url = f"https://{bucket_name}.s3.{region}.amazonaws.com/{s3_key}"
# Save metadata JSON alongside the image
if description:
import datetime
meta_key = s3_key.rsplit('.', 1)[0] + '.json'
meta = json.dumps({
"description": description,
"url": public_url,
"created_at": datetime.datetime.utcnow().isoformat() + "Z",
}, ensure_ascii=False)
s3_client.put_object(
Bucket=bucket_name, Key=meta_key,
Body=meta.encode('utf-8'),
ContentType='application/json',
)
logger.info(f"Uploaded actor to S3: {public_url}")
return public_url
except Exception as e:
logger.error(f"Failed to upload actor to S3: {e}")
return None
def list_actor_gallery():
"""
List all actor images from the public S3 bucket.
Returns list with URLs and descriptions, newest first.
"""
bucket_name = os.environ.get('AWS_S3_PUBLIC_BUCKET', 'my-public-bucket')
region = os.environ.get('AWS_REGION', 'eu-west-3')
s3_client = get_s3_client()
if not s3_client:
return []
try:
paginator = s3_client.get_paginator('list_objects_v2')
pages = paginator.paginate(Bucket=bucket_name, Prefix='avatars/')
all_objects = {}
for page in pages:
for obj in page.get('Contents', []):
key = obj['Key']
base = key.rsplit('.', 1)[0]
if base not in all_objects:
all_objects[base] = {}
if key.lower().endswith(('.png', '.jpg', '.jpeg', '.webp')):
all_objects[base]['image'] = obj
elif key.endswith('.json'):
all_objects[base]['meta_key'] = key
images = []
for base, data in all_objects.items():
if 'image' not in data:
continue
obj = data['image']
key = obj['Key']
public_url = f"https://{bucket_name}.s3.{region}.amazonaws.com/{key}"
entry = {
"url": public_url,
"key": key,
"created_at": obj['LastModified'].isoformat(),
"description": "",
}
# Try to read metadata JSON
if 'meta_key' in data:
try:
meta_resp = s3_client.get_object(Bucket=bucket_name, Key=data['meta_key'])
meta = json.loads(meta_resp['Body'].read().decode('utf-8'))
entry['description'] = meta.get('description', '')
except Exception:
pass
images.append(entry)
images.sort(key=lambda x: x['created_at'], reverse=True)
return images
except Exception as e:
logger.error(f"Failed to list actor gallery: {e}")
return []
# ── SaaS Video Gallery (public S3) ──────────────────────────────────
_video_gallery_cache = {
"data": None,
"timestamp": 0,
}
def upload_video_to_gallery(video_path, actor_image_path, metadata, video_id=None):
"""
Upload a generated UGC video + actor + metadata to the public S3 bucket.
Returns dict with public URLs or None on failure.
"""
import uuid
bucket_name = os.environ.get('AWS_S3_PUBLIC_BUCKET', 'my-public-bucket')
region = os.environ.get('AWS_REGION', 'eu-west-3')
s3_client = get_s3_client()
if not s3_client:
return None
if not video_id:
video_id = str(uuid.uuid4())[:8]
base_url = f"https://{bucket_name}.s3.{region}.amazonaws.com"
results = {}
try:
# Upload video
if os.path.exists(video_path):
s3_key = f"videos/{video_id}/video.mp4"
s3_client.upload_file(video_path, bucket_name, s3_key,
ExtraArgs={'ContentType': 'video/mp4'})
results["video_url"] = f"{base_url}/{s3_key}"
# Upload actor image
if actor_image_path and os.path.exists(actor_image_path):
s3_key = f"videos/{video_id}/actor.png"
s3_client.upload_file(actor_image_path, bucket_name, s3_key,
ExtraArgs={'ContentType': 'image/png'})
results["actor_url"] = f"{base_url}/{s3_key}"
# Build and upload metadata
import datetime
metadata["video_id"] = video_id
metadata["video_url"] = results.get("video_url", "")
metadata["actor_url"] = results.get("actor_url", "")
metadata["created_at"] = datetime.datetime.utcnow().isoformat() + "Z"
meta_json = json.dumps(metadata, ensure_ascii=False, indent=2)
s3_key = f"videos/{video_id}/metadata.json"
s3_client.put_object(
Bucket=bucket_name, Key=s3_key,
Body=meta_json.encode('utf-8'),
ContentType='application/json',
)
results["metadata_url"] = f"{base_url}/{s3_key}"
results["video_id"] = video_id
logger.info(f"Uploaded video gallery: {video_id}")
# Invalidate cache
_video_gallery_cache["data"] = None
return results
except Exception as e:
logger.error(f"Failed to upload video to gallery: {e}")
return None
def list_video_gallery(limit=50, force_refresh=False):
"""
List all UGC videos from the public S3 bucket.
Returns list of metadata dicts, newest first.
"""
global _video_gallery_cache
now = time_module.time()
if not force_refresh and _video_gallery_cache["data"] is not None:
if now - _video_gallery_cache["timestamp"] < CACHE_TTL_SECONDS:
cached = _video_gallery_cache["data"]
return cached[:limit] if limit else cached
bucket_name = os.environ.get('AWS_S3_PUBLIC_BUCKET', 'my-public-bucket')
s3_client = get_s3_client()
if not s3_client:
return []
videos = []
try:
paginator = s3_client.get_paginator('list_objects_v2')
pages = paginator.paginate(Bucket=bucket_name, Prefix='videos/')
meta_files = []
for page in pages:
for obj in page.get('Contents', []):
if obj['Key'].endswith('/metadata.json'):
meta_files.append(obj)
# Newest first
meta_files.sort(key=lambda x: x['LastModified'], reverse=True)
for meta_obj in meta_files:
try:
obj_resp = s3_client.get_object(Bucket=bucket_name, Key=meta_obj['Key'])
content = obj_resp['Body'].read().decode('utf-8')
data = json.loads(content)
videos.append(data)
if limit and len(videos) >= limit:
break
except Exception as e:
logger.error(f"Error reading metadata {meta_obj['Key']}: {e}")
continue
except Exception as e:
logger.error(f"Failed to list video gallery: {e}")
return []
_video_gallery_cache["data"] = videos
_video_gallery_cache["timestamp"] = now
return videos[:limit] if limit else videos
def upload_job_artifacts(directory, job_id):
"""
Upload all generated clips and metadata for a job to S3.
@ -442,5 +88,3 @@ def upload_job_artifacts(directory, job_id):
file_path = os.path.join(directory, filename)
s3_key = f"{job_id}/{filename}"
upload_file_to_s3(file_path, bucket_name, s3_key)

File diff suppressed because it is too large Load diff

View file

@ -1,7 +1,7 @@
{
"name": "openshorts",
"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 via the OpenShorts API or MCP server.",
"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": "OpenShorts",
"url": "https://www.openshorts.app/"

View file

@ -11,25 +11,12 @@ like errors but are not, and when to stop and ask the user.
## Setup
Create an API key (`osk_...`) in your account page at
[openshorts.app](https://www.openshorts.app/) and give it to the agent the way
that host stores credentials (`OPENSHORTS_API_KEY` where an env var is the
convention). The hosted free tier includes 20 minutes of source video per month
with a watermark; paid plans start at $12/month without one. OpenShorts is also
MIT-licensed and self-hostable, which needs a GPU machine, your own Google
Gemini key, and your own [Upload-Post](https://www.upload-post.com/) account for
the publishing steps.
If the host speaks MCP, add the server too so the agent gets typed tools instead
of raw HTTP:
```bash
claude mcp add --transport http openshorts https://mcp.openshorts.app/mcp \
--header "Authorization: Bearer osk_..."
```
The skill works either way: with MCP it calls the tools, without it it calls the
REST API documented in `reference.md`.
Run OpenShorts yourself with Docker and point the agent at the instance
(`OPENSHORTS_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.pbento.pt/) instance.
## Install
@ -50,8 +37,6 @@ runs a security scan first.
## Related
- `cli/` is the same API as a zero-dependency CLI: `uvx openshorts process <url> --wait`.
- `examples/n8n/` has the same pipeline as importable n8n workflows, including a
daily channel autopilot with Telegram approval.
- [openshorts.app/mcp](https://www.openshorts.app/mcp) documents the MCP server,
and [api.openshorts.app/docs](https://api.openshorts.app/docs) the full API.
- `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.

View file

@ -1,8 +1,8 @@
---
name: openshorts
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 via the OpenShorts API or MCP server. 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://www.openshorts.app/mcp
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://github.com/mutonby/openshorts
metadata:
openclaw:
emoji: "🎬"
@ -21,40 +21,34 @@ optionally publishes them. One job takes minutes, not seconds: always work async
## Connect
Two equivalent surfaces; prefer MCP when the client supports it:
One surface: the REST API. Point the skill at your self-hosted instance
(`http://localhost:8000` by default):
- **MCP** (streamable HTTP): `https://mcp.openshorts.app/mcp` with header
`Authorization: Bearer osk_...`. Seven tools: `process_video`,
`get_job_status`, `list_clips`, `get_quota`, `add_subtitles`, `recut_clip`,
`publish_clip`.
- **REST**: same key against `https://api.openshorts.app`. Exact payloads and
error shapes are in `reference.md`; read it before the first HTTP call.
- **REST**: exact payloads and error shapes are in `reference.md`; read it
before the first HTTP call.
Keys are created in the account page at openshorts.app and start with `osk_`.
**Self-hosted instances expose the same endpoints on `http://localhost:8000`
with no key.** If a call returns 401/404 on `/api/me`, assume self-host or
anonymous: there is no minute quota to enforce.
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. If a call returns 401/404 on `/api/me`, assume self-host or anonymous:
there is no minute quota to enforce.
## The core loop
1. `get_quota` first when the job is large: `process_video` fails with
`quota_exceeded` if minutes run out; on the hosted service API calls draw
from the same minute balance as the dashboard (no separate meter). A job
costs its source duration rounded up, minimum one minute.
2. Submit: `POST /api/process` with JSON
1. Submit: `POST /api/process` with JSON
`{"url": "...", "acknowledged": true}`. Returns `{"job_id": ...}`
immediately. See the next section for the options worth setting.
3. Finish: **webhooks beat polling.** With `webhook_url` set, OpenShorts POSTs
2. Finish: **webhooks beat polling.** With `webhook_url` set, OpenShorts 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", "download_url"}]}`. If a secret was set, verify
`X-OpenShorts-Signature: sha256=<hex>` = HMAC-SHA256 of the raw body.
Without a webhook, poll `GET /api/status/{job_id}` every 30-60s; response is
`{"status", "logs", "result"}` and `result.clips` appears on completion.
4. Publish: `POST /api/social/post` with `{"job_id", "clip_index",
3. Publish: `POST /api/postiz/post` with `{"job_id", "clip_index",
"platforms": ["tiktok", "instagram", "youtube"]}`, optional `title`,
`scheduled_date` (ISO) + `timezone`. TikTok lands as a draft in the app;
Instagram and YouTube publish directly. Restyle captions first if asked:
`description`, `scheduled_date` (ISO) + `timezone`. The backend uploads the
clip to your self-hosted Postiz instance and creates the post there.
Restyle captions first if asked:
`POST /api/subtitle` with `{"job_id", "clip_index", "style"}` (`classic`
or `karaoke` word highlighting).
@ -87,33 +81,24 @@ 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.
## Three responses that are not failures
## 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: the job still costs minutes and low resolution in means low
resolution out.
- **HTTP 402 `quota_exceeded`** means out of minutes, with `minutes_required`
and `minutes_remaining` in the body. Report it and stop. Do not retry and do
not split the video to squeeze under the limit.
- **HTTP 429** means the user already has the maximum number of jobs running.
Wait for one to finish instead of resubmitting.
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; `process_video` requires the
`confirm_rights` acknowledgement and that is deliberate.
- Only submit videos the user has rights to; `/api/process` requires the
`acknowledged` rights attestation and that is deliberate.
- Publishing is public and irreversible: confirm platforms and caption with the
user before every `publish_clip` call.
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.
- `download_url` links are presigned for 24h: fetch or forward them promptly.
- Never describe OpenShorts as simply "free": the self-hosted edition is free
and MIT-licensed (and needs a GPU box plus your own Gemini key); the hosted
service has 20 free minutes/month (watermarked) and paid plans from $12/month
without watermark.
## CLI shortcut
When shell access is easier than HTTP: `uvx openshorts process <url> --wait`,
`openshorts clips <job_id>`, `openshorts publish <job_id> 0 --platforms
tiktok`. Auth via `OPENSHORTS_API_KEY` / `OPENSHORTS_API_URL` env vars.
- OpenShorts is self-hosted, MIT-licensed and needs a machine plus your own
Gemini key. Do not describe it as a hosted or metered service.

View file

@ -1,30 +1,8 @@
# OpenShorts HTTP reference
Base URL: `https://api.openshorts.app` (self-hosted: `http://localhost:8000`).
Every call carries `Authorization: Bearer osk_...` or `X-API-Key: osk_...`.
Self-hosted instances need no key, but do need a Gemini key, either in the
server's environment or as an `X-Gemini-Key` header.
The MCP server at `https://mcp.openshorts.app/mcp` wraps exactly these
endpoints, forwarding your auth headers, so the two paths cannot drift.
## Quota
`GET /api/me`
```json
{
"plan": "free",
"entitled": false,
"minutes": { "plan_allowance": 20, "plan_used": 4, "plan_remaining": 16,
"topup_remaining": 0, "remaining": 16 },
"upload_post_profile": null
}
```
`upload_post_profile` is null when no social account is connected, which means
publishing will fail. On a self-hosted instance this endpoint is not mounted at
all and returns 404, which simply means there is no quota to report.
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
@ -68,9 +46,8 @@ Quality gate, also HTTP 200:
Ask the user, then resubmit the identical body with `force_low_quality: true`.
Errors: **402** `{"detail": {"error": "quota_exceeded", "minutes_required": 12,
"minutes_remaining": 3}}`, **429** too many jobs already running, **400** the
source duration could not be determined.
Errors: **429** too many jobs already running (`MAX_CONCURRENT_JOBS`), **400**
the source duration could not be determined.
## Poll a job
@ -97,7 +74,7 @@ Fired once per job, on success and on failure, so a flow never hangs:
```
A failed job sends `"event": "job.failed"` with an `error` string and no clips.
`download_url` is a presigned link valid for 24 hours (hosted service only).
`download_url` is a presigned link valid for 24 hours.
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
@ -144,7 +121,7 @@ and needs the retained source video.
## Publish
`POST /api/social/post`
`POST /api/postiz/post`
```json
{ "job_id": "...", "clip_index": 0, "platforms": ["tiktok", "instagram", "youtube"],
@ -152,14 +129,16 @@ and needs the retained source video.
"scheduled_date": "2026-08-25T18:00:00Z", "timezone": "Europe/Madrid" }
```
Omit `scheduled_date` to post now. Uploads are asynchronous. TikTok arrives as a
draft in the app; Instagram and YouTube publish directly.
Omit `scheduled_date` to post now. The backend uploads the clip bytes to your
self-hosted Postiz instance and creates the post there; the provider settings
(`tiktok`, `instagram`, `youtube`) are built from the title and caption.
Queue: `GET /api/social/scheduled`, and
`DELETE /api/social/scheduled/{job_id}` to cancel one before it goes out.
Connected channels: `GET /api/postiz/integrations`.
Analytics of what was published: `GET /api/social/analytics` (profile totals),
`GET /api/social/analytics/posts` (per post), and
`GET /api/social/analytics/impressions` (windowed, e.g. `?period=last_week`).
Queue: `GET /api/postiz/scheduled`, and
`DELETE /api/postiz/scheduled/{id}` to cancel one before it goes out.
Full generated API docs: <https://api.openshorts.app/docs>.
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`.

View file

@ -2,10 +2,12 @@ import io
import os
import uuid
import json
import base64
from concurrent.futures import ThreadPoolExecutor
from google import genai
from google.genai import types
from google.genai import errors as genai_errors
from PIL import Image, ImageDraw, ImageFont, ImageFilter
# Text/analysis model (titles, concepts, description). Deliberately NOT tied to
@ -593,11 +595,15 @@ def finalize_thumbnail(img, out_path):
def _image_part(path):
"""A JPEG byte part for the image model (re-encoded so HEIC/PNG uploads
and odd modes all arrive the same way)."""
"""A base64 image content block for the Interactions API (re-encoded so
HEIC/PNG uploads and odd modes all arrive the same way)."""
buf = io.BytesIO()
Image.open(path).convert("RGB").save(buf, "JPEG", quality=92)
return types.Part.from_bytes(data=buf.getvalue(), mime_type="image/jpeg")
return {
"type": "image",
"mime_type": "image/jpeg",
"data": base64.b64encode(buf.getvalue()).decode("ascii"),
}
def _generate_one(client, concept, reference_images, out_path, burn_text):
@ -626,29 +632,32 @@ Style: high contrast, saturated colours, crisp subject separation, cinematic lig
"body type. Photorealistic, like a photo of them; do not idealize, slim, rejuvenate or "
"stylize them. Expression may change slightly but must stay natural and true to their face.")
response = client.models.generate_content(
interaction = client.interactions.create(
model=IMAGE_MODEL,
contents=reference_images + [prompt],
config=types.GenerateContentConfig(
response_modalities=["TEXT", "IMAGE"],
image_config=types.ImageConfig(aspect_ratio="16:9", image_size="2K"),
),
input=reference_images + [{"type": "text", "text": prompt}],
response_format={
"type": "image",
"mime_type": "image/jpeg",
"aspect_ratio": "16:9",
"image_size": "2K",
},
)
if not response.parts:
cand = (response.candidates or [None])[0]
reason = getattr(cand, "finish_reason", None) or getattr(response, "prompt_feedback", None)
raise RuntimeError(f"Gemini returned no image (finish_reason={reason})")
for part in response.parts:
if part.text is not None:
print(f"📝 [Thumbnail] Gemini text: {part.text[:200]}")
continue
if part.inline_data is None or not part.inline_data.data:
continue
pil = Image.open(io.BytesIO(part.inline_data.data))
# The SDK hoists the generated image to `output_image` (base64) and any
# model text to `output_text`. A refusal yields neither, which raises the
# "no image" RuntimeError that generate_thumbnail() retries generically.
if interaction.output_text:
print(f"📝 [Thumbnail] Gemini text: {interaction.output_text[:200]}")
image = getattr(interaction, "output_image", None)
data = getattr(image, "data", None) if image is not None else None
if not data:
reason = getattr(interaction, "status", None) or getattr(interaction, "errors", None)
raise RuntimeError(f"Gemini returned no image (status={reason})")
raw = base64.b64decode(data) if isinstance(data, str) else data
pil = Image.open(io.BytesIO(raw))
if burn_text:
pil = burn_thumbnail_text(pil, concept["text"], concept["text_position"], concept["text_color"])
return finalize_thumbnail(pil, out_path)
raise RuntimeError("Gemini returned no image")
def generate_thumbnail(api_key, title, session_id, face_image_path=None, bg_image_path=None,
@ -692,12 +701,15 @@ def generate_thumbnail(api_key, title, session_id, face_image_path=None, bg_imag
try:
_generate_one(client, concept, reference_images, out_path, burn_text)
fallback = False
except RuntimeError as e:
if "no image" not in str(e):
except (RuntimeError, genai_errors.ClientError) as e:
if isinstance(e, RuntimeError) and "no image" not in str(e):
raise
# Gemini refuses recognisable public figures, by reference photo
# and by name alike (IMAGE_OTHER). Retry once with no reference
# and a generic presenter instead of failing the whole batch.
# and by name alike (IMAGE_OTHER). Depending on the path that
# surfaces as an empty image (RuntimeError) or an API ClientError;
# retry once with no reference and a generic presenter instead of
# failing the whole batch. If the retry also fails, the real error
# is recorded for this concept.
print(f"⚠️ [Thumbnail] Generation {i + 1} blocked ({e}); retrying without the person")
generic = dict(concept, scene=(
"Do not depict any real, named or recognisable person; if a presenter is needed, "