feat(seo): free tools hub, /auto-clip and /youtube-automation, SEO-page attribution

Free tools (no login), linked from nav and footer via /tools:
- /youtube-transcript-generator: reads the captions a video already has on
  YouTube (free_tools.py, yt-dlp over the flat-rate static proxies only, never
  the per-GB proxy, never the GPU). Per-IP limits, global daily cap, 24 h
  cache, honest "no captions" answer with a CTA to the clip generator.
  Copy / TXT / SRT export in the browser.
- /youtube-tag-generator: tags, 10 titles or a description from a brief, one
  Gemini text call, rules taken from YouTube's own docs (sourced on the page).
- /video-aspect-ratio-converter: 16:9 to 9:16 in the browser with mediabunny
  and WebCodecs (blur / crop / bars), nothing uploaded.
Tool pages keep the form in the static HTML; the behaviour is a Vite entry
(dashboard/tools) that vite-plugin-seo resolves by name.

New pages /auto-clip and /youtube-automation with real, blurred screenshots
of the Autopilot tab and the connect-an-agent card, Autopilot rules from
cloud/autopilot.py, plan prices from the billing API and aggregate usage
from the ledger (dated).

SEO fixes: titles/metas for /how-openshorts-works, /podcast-to-shorts, /mcp
and /free-ai-clip-generator (brand queries at pos 1-2 with <1% CTR); a free
AI clipper / free clipping website section and FAQ, and contextual "free AI
clip generator" anchors from sibling pages and the homepage.

Attribution: static pages now write the same first-touch os_attrib key the
app writes, so the signup is credited to the page the visit started on
(7,481 of 7,481 signups in 30 days said "/"). Signup, CheckoutStarted and
Subscribed carry landing_path / referrer_host / utm props in OpenPanel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
victorcavero14 2026-09-23 01:02:01 +02:00
parent fdad2a46fa
commit 8de011ed36
23 changed files with 2488 additions and 26 deletions

View file

@ -84,6 +84,32 @@ say "OpenShorts is free" without naming the Cloud price in the same breath: both
are true of different editions and quoting only the first one is what makes AI are true of different editions and quoting only the first one is what makes AI
answers describe the paid product as free. answers describe the paid product as free.
### Free tools (/tools) and SEO attribution
- `free_tools.py` (router always mounted): `GET /api/tools/youtube-transcript`
reads the captions a video **already has** on YouTube via yt-dlp (never the
GPU, never media). Routes: the `STATIC_PROXY_URLS` only (anonymous, then the
cookies), direct when there are none; **never** the per-GB `PROXY_URL`. A
static that answers with zero formats and zero captions is a degraded route,
not a "no captions" verdict (seen on one of the three statics, 23-sep-2026).
`POST /api/tools/youtube-metadata` = one Gemini text call (tags / titles /
description) with the managed key. Per-IP windows + global daily cap per tool,
24 h cache (also for "no captions"/"unavailable").
- Pages: `seo/tools.js` (hub + 3 tools) and `seo/autopilot-pages.js`
(`/auto-clip`, `/youtube-automation`). A tool page carries `tool: {entry, html}`:
the form is in the static HTML, the behaviour is a Vite entry in
`dashboard/tools/*.js` (`vite.config.js` rollupOptions.input) that
`vite-plugin-seo.js` looks up by name in the bundle. The 9:16 converter runs
in the browser with mediabunny/WebCodecs (no upload).
- Attribution: `seo/render.js` writes the same first-touch `os_attrib` key the
app writes, from the static page the visit started on. Before, every signup
was credited to "/" (7,481/7,481 rows, 30 days to 23-sep-2026). Signup,
CheckoutStarted and Subscribed carry `landing_path`/`referrer_host`/utm as
OpenPanel props (`lib/analytics.js`).
- Apex→www: 301 comes from the front app's **stored Coolify custom labels**
(`redirectregex.permanent=true`, patched 23-sep-2026). The nginx 301 block
below never sees the apex while that Traefik middleware exists.
### Cómo se elige el layout ### Cómo se elige el layout
`POST /api/process` acepta `layouts`: una lista (JSON) o cadena separada por `POST /api/process` acepta `layouts`: una lista (JSON) o cadena separada por

5
app.py
View file

@ -2104,6 +2104,11 @@ if BILLING_ENABLED:
import mcp_server as _mcp_server import mcp_server as _mcp_server
app.include_router(_mcp_server.router) app.include_router(_mcp_server.router)
# Free public tools behind the /tools SEO pages: YouTube transcript (existing
# captions only, never the GPU) and the title/description/tag generator.
import free_tools as _free_tools
app.include_router(_free_tools.router)
# Enable CORS for frontend. Cloud mode locks this down to the configured origins; # Enable CORS for frontend. Cloud mode locks this down to the configured origins;
# self-host keeps the permissive wildcard it has always used. # self-host keeps the permissive wildcard it has always used.
app.add_middleware( app.add_middleware(

View file

@ -13,6 +13,7 @@
"@remotion/player": "^4.0.447", "@remotion/player": "^4.0.447",
"@remotion/web-renderer": "^4.0.447", "@remotion/web-renderer": "^4.0.447",
"lucide-react": "^0.344.0", "lucide-react": "^0.344.0",
"mediabunny": "^1.39.2",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"remotion": "^4.0.447", "remotion": "^4.0.447",

View file

@ -15,6 +15,7 @@
"@remotion/player": "^4.0.447", "@remotion/player": "^4.0.447",
"@remotion/web-renderer": "^4.0.447", "@remotion/web-renderer": "^4.0.447",
"lucide-react": "^0.344.0", "lucide-react": "^0.344.0",
"mediabunny": "^1.39.2",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"remotion": "^4.0.447", "remotion": "^4.0.447",

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

View file

@ -0,0 +1,301 @@
/* /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

@ -101,7 +101,7 @@ export const LANDING_FALLBACK = `<div id="seo-content" style="background:oklch(1
<section style="${S.section};padding-top:4rem"><div style="${S.wrap}"> <section style="${S.section};padding-top:4rem"><div style="${S.wrap}">
<p style="${S.eyebrow}">AI clip generator &middot; cloud or self-hosted</p> <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> <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 the <a href="/n8n-youtube-shorts-automation" style="${S.a}">n8n workflow</a>.</p> <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.muted};max-width:44rem"><strong style="color:oklch(75% 0.11 150)">No credit card required.</strong> 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> <p style="${S.muted};max-width:44rem"><strong style="color:oklch(75% 0.11 150)">No credit card required.</strong> 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> </div></section>
@ -140,6 +140,12 @@ export const LANDING_FALLBACK = `<div id="seo-content" style="background:oklch(1
<a style="${S.a}" href="/alternatives/vizard">Vizard alternative</a> &middot; <a style="${S.a}" href="/alternatives/vizard">Vizard alternative</a> &middot;
<a style="${S.a}" href="/alternatives/submagic">Submagic alternative</a> &middot; <a style="${S.a}" href="/alternatives/submagic">Submagic alternative</a> &middot;
<a style="${S.a}" href="/free-ai-clip-generator">Free AI clip generator</a> &middot; <a style="${S.a}" href="/free-ai-clip-generator">Free AI clip generator</a> &middot;
<a style="${S.a}" href="/tools">Free tools</a> &middot;
<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="/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-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; <a style="${S.a}" href="/open-source-ai-video-generator">Open source AI video generator</a> &middot;

View file

@ -15,6 +15,8 @@
import { SITE, COMPETITORS, COMPARISON_ROWS, EDITIONS, PIPELINE_STEPS, CANONICAL_ANSWERS } from './data.js' import { SITE, COMPETITORS, COMPARISON_ROWS, EDITIONS, PIPELINE_STEPS, CANONICAL_ANSWERS } from './data.js'
import { esc } from './render.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>` const li = (items) => `<ul>${items.map((i) => `<li>${i}</li>`).join('')}</ul>`
@ -152,7 +154,9 @@ const hubPage = () => ({
do different jobs. Two of them take a long video and decide what to cut. One of do different jobs. Two of them take a long video and decide what to cut. One of
them only styles captions on a clip you cut yourself. One is really an editor them only styles captions on a clip you cut yourself. One is really an editor
with an AI first pass. Choosing on price alone is how people end up paying for with an AI first pass. Choosing on price alone is how people end up paying for
two tools that each do half the work.</p> two tools that each do half the work. If price is the deciding factor, start with
what a <a href="/free-ai-clip-generator">free AI clip generator</a> actually
includes.</p>
<h2>Entry pricing side by side</h2> <h2>Entry pricing side by side</h2>
<p class="checked">Pricing checked 2026-07-27. Verify on the vendor's site before buying.</p> <p class="checked">Pricing checked 2026-07-27. Verify on the vendor's site before buying.</p>
@ -195,9 +199,9 @@ ${faqBlock([
const freeClipGenerator = () => ({ const freeClipGenerator = () => ({
path: '/free-ai-clip-generator', path: '/free-ai-clip-generator',
title: 'Free AI Clip Generator With No Watermark (MIT) | OpenShorts', title: 'Free AI Clip Generator & Clipper, No Watermark | OpenShorts',
description: description:
'A genuinely free AI clip generator: MIT-licensed, self-hosted with Docker, no watermark and no cap. Hosted from $12/month if you would rather not run it.', 'Free AI clipper that turns long videos into 3 to 15 vertical clips with subtitles. Self-hosted: no watermark, no cap. Hosted: 20 free minutes a month.',
h1: 'A free AI clip generator that is actually free', h1: 'A free AI clip generator that is actually free',
breadcrumb: [{ name: 'Free AI clip generator' }], breadcrumb: [{ name: 'Free AI clip generator' }],
cta: { cta: {
@ -238,6 +242,18 @@ video takes about 50 seconds. Linux, macOS and Windows via WSL2 all work, and
Docker Compose pulls Python 3.11, FFmpeg, YOLOv8, MediaPipe and faster-whisper Docker Compose pulls Python 3.11, FFmpeg, YOLOv8, MediaPipe and faster-whisper
for you.</p> for you.</p>
<h2>Free AI clipper, free clipping AI, free clipping website: which one is this?</h2>
<p>All three searches mean the same job: something that watches a long video and
cuts the good parts into vertical clips without you paying. OpenShorts is that in
two forms. As a <strong>free clipping website</strong>, openshorts.app clips 20
minutes of video a month in the browser with no install and no credit card; the
clips carry a small watermark. As a <strong>free AI clipper you run
yourself</strong>, the same code from GitHub has no watermark and no monthly cap.
Either way the clipping AI is the same: Gemini picks the moments, face tracking
reframes them and the subtitles come from a word-level transcript. If you only
need one piece of that, the <a href="/tools">free tools</a> cover transcripts
and a 9:16 converter with no account at all.</p>
<h2>Is a free clip generator good enough for real posting?</h2> <h2>Is a free clip generator good enough for real posting?</h2>
<p>It depends on what you are comparing against. The moment detection uses the <p>It depends on what you are comparing against. The moment detection uses the
same class of model the paid tools use, Google Gemini 3.1 Flash-Lite, and the same class of model the paid tools use, Google Gemini 3.1 Flash-Lite, and the
@ -271,6 +287,14 @@ ${faqBlock([
q: 'How many clips does it generate per video?', q: 'How many clips does it generate per video?',
a: 'Between 3 and 15, each 15 to 60 seconds long. The number depends on how much of the source actually holds up as a standalone clip rather than on a fixed quota.', a: 'Between 3 and 15, each 15 to 60 seconds long. The number depends on how much of the source actually holds up as a standalone clip rather than on a fixed quota.',
}, },
{
q: 'Is there a free clipping website that needs no install?',
a: 'Yes. openshorts.app clips 20 minutes of video a month in the browser with no credit card. Those clips carry a watermark; paid plans from $12/month remove it.',
},
{
q: 'Is there a free AI clipper with no watermark?',
a: 'The self-hosted edition of OpenShorts: MIT licensed, run with Docker, no watermark and no usage cap. You bring your own Gemini API key.',
},
])} ])}
`, `,
faq: [ faq: [
@ -286,6 +310,14 @@ ${faqBlock([
q: 'How many clips does it generate per video?', q: 'How many clips does it generate per video?',
a: 'Between 3 and 15 clips, each 15 to 60 seconds long.', a: 'Between 3 and 15 clips, each 15 to 60 seconds long.',
}, },
{
q: 'Is there a free clipping website that needs no install?',
a: 'Yes. openshorts.app clips 20 minutes of video a month in the browser with no credit card. Those clips carry a watermark; paid plans from $12/month remove it.',
},
{
q: 'Is there a free AI clipper with no watermark?',
a: 'The self-hosted edition of OpenShorts: MIT licensed, run with Docker, no watermark and no usage cap.',
},
], ],
}) })
@ -363,9 +395,9 @@ ${faqBlock([
const howItWorks = () => ({ const howItWorks = () => ({
path: '/how-openshorts-works', path: '/how-openshorts-works',
title: 'How OpenShorts Turns a Long Video Into Clips | OpenShorts', title: 'OpenShorts: How It Works, From Long Video to 9:16 Clips',
description: description:
'The pipeline stage by stage: word-level transcription, scene detection, Gemini moment scoring, face-tracked 9:16 reframing, subtitles, dubbing and publishing.', 'How OpenShorts cuts one long video into 3 to 15 vertical clips: transcript, scene cuts, Gemini scoring, face-tracked reframing, subtitles. Try it free.',
h1: 'How a long video becomes a vertical clip', h1: 'How a long video becomes a vertical clip',
breadcrumb: [{ name: 'How it works' }], breadcrumb: [{ name: 'How it works' }],
tldr: [ tldr: [
@ -463,7 +495,9 @@ every video you process. The free tier exists to show you the output, and the
watermark exists so the output is not the product yet. That is not a scam, it is watermark exists so the output is not the product yet. That is not a scam, it is
the business model, and it is why searching for a hosted tool that is free, the business model, and it is why searching for a hosted tool that is free,
unlimited and unwatermarked at the same time keeps returning nothing: the unlimited and unwatermarked at the same time keeps returning nothing: the
combination cannot pay for itself.</p> combination cannot pay for itself. What a
<a href="/free-ai-clip-generator">free AI clip generator</a> can honestly offer
is one of the three, and which one depends on the edition.</p>
<h2>The structural exception: software you run yourself</h2> <h2>The structural exception: software you run yourself</h2>
${pricingParagraph} ${pricingParagraph}
@ -565,8 +599,9 @@ ${pricingParagraph}
<h2>Other open source clip generators, compared honestly</h2> <h2>Other open source clip generators, compared honestly</h2>
<p class="checked">Checked 2026-08-04 on GitHub. Star counts move; positioning rarely does.</p> <p class="checked">Checked 2026-08-04 on GitHub. Star counts move; positioning rarely does.</p>
<p>OpenShorts is not the only open source project in this space, and pretending <p>OpenShorts is not the only open source project in this space (it is also the
otherwise would not survive one GitHub search. The notable neighbours:</p> <a href="/free-ai-clip-generator">free AI clip generator</a> most of these pages
are about), and pretending otherwise would not survive one GitHub search. The notable neighbours:</p>
<ul> <ul>
<li><strong>AI-Youtube-Shorts-Generator</strong>: the most-starred repo in the category, with a leaner scope built around highlight extraction and cropping.</li> <li><strong>AI-Youtube-Shorts-Generator</strong>: the most-starred repo in the category, with a leaner scope built around highlight extraction and cropping.</li>
<li><strong>supoclip</strong> and <strong>clippyme</strong>: smaller projects covering transcription-driven clipping, the latter also using Gemini for moment selection.</li> <li><strong>supoclip</strong> and <strong>clippyme</strong>: smaller projects covering transcription-driven clipping, the latter also using Gemini for moment selection.</li>
@ -616,9 +651,9 @@ ${sources([
* and active-speaker cutting are capabilities the competitor pages cannot show. */ * and active-speaker cutting are capabilities the competitor pages cannot show. */
const podcastToShorts = () => ({ const podcastToShorts = () => ({
path: '/podcast-to-shorts', path: '/podcast-to-shorts',
title: 'Podcast to Shorts: Both Speakers Stay in Frame | OpenShorts', title: 'Podcast to Shorts With Both Speakers in Frame | OpenShorts',
description: description:
'Turn a podcast into vertical clips without cropping out half the conversation: OpenShorts stacks both speakers and cuts to whoever is talking. Free self-hosted.', 'Paste a podcast episode, get vertical clips with subtitles that keep both speakers on screen. 20 free minutes a month, or self-host it free under MIT.',
h1: 'Turn a podcast into shorts without cropping out half the conversation', h1: 'Turn a podcast into shorts without cropping out half the conversation',
breadcrumb: [{ name: 'Podcast to shorts' }], breadcrumb: [{ name: 'Podcast to shorts' }],
published: '2026-08-04', published: '2026-08-04',
@ -1036,9 +1071,9 @@ ${sources([
const mcpAgentsPage = () => ({ const mcpAgentsPage = () => ({
path: '/mcp', path: '/mcp',
title: 'Clip Video From AI Agents: MCP Server & API | OpenShorts', title: 'OpenShorts MCP Server: Clip Video From Claude or ChatGPT',
description: description:
'OpenShorts ships a built-in MCP server, so Claude, ChatGPT, Cursor or n8n can clip and publish videos for you: REST API with keys and signed webhooks.', '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', h1: 'Clip and publish video from an AI agent',
breadcrumb: [{ name: 'MCP server and API' }], breadcrumb: [{ name: 'MCP server and API' }],
cta: { cta: {
@ -2187,6 +2222,8 @@ export function buildPages() {
mcpAgentsPage(), mcpAgentsPage(),
automateShorts(), automateShorts(),
n8nTemplate(), n8nTemplate(),
...autopilotPages(),
...toolPages(),
] ]
} }
@ -2217,6 +2254,20 @@ export function relatedFor(page, all) {
'/mcp': 'Drive the whole pipeline from Claude, ChatGPT or n8n.', '/mcp': 'Drive the whole pipeline from Claude, ChatGPT or n8n.',
'/automate-shorts-api': 'One POST in, one signed webhook out, no polling.', '/automate-shorts-api': 'One POST in, one signed webhook out, no polling.',
'/n8n-youtube-shorts-automation': 'The importable workflow: channel in, approved shorts out.', '/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.',
'/video-aspect-ratio-converter': '16:9 to 9:16 in your browser: blur, crop or bars.',
}
// A page can name its own neighbours (the tools link to each other, not
// into the comparison ring).
if (page.related) {
return page.related
.map((path) => all.find((p) => p.path === path))
.filter(Boolean)
.map((p) => ({ path: p.path, title: p.h1, blurb: blurb[p.path] || p.description }))
} }
// Walk the ring starting after this page so each page links to a different // Walk the ring starting after this page so each page links to a different
// three. Slicing the same head every time would leave the last pages in the // three. Slicing the same head every time would leave the last pages in the

View file

@ -47,7 +47,8 @@ header.site .wrap{display:flex;align-items:center;justify-content:space-between;
font-size:1.15rem;color:var(--ink);text-transform:lowercase;text-decoration:none} font-size:1.15rem;color:var(--ink);text-transform:lowercase;text-decoration:none}
.brand img{width:26px;height:26px} .brand img{width:26px;height:26px}
.nav{display:flex;gap:1.25rem;font-size:.875rem;text-transform:lowercase} .nav{display:flex;gap:1.25rem;font-size:.875rem;text-transform:lowercase}
.nav a{text-decoration:none;color:var(--muted)} .nav a{text-decoration:none;color:var(--muted);white-space:nowrap}
@media(max-width:48rem){.nav a:not(.keep){display:none}.brand{font-size:1rem}.cta{padding:.45rem .75rem}}
.nav a:hover{color:var(--ink)} .nav a:hover{color:var(--ink)}
.cta{background:var(--brass);color:oklch(17% 0.03 50);padding:.5rem 1rem; .cta{background:var(--brass);color:oklch(17% 0.03 50);padding:.5rem 1rem;
border-radius:8px;font-size:.875rem;font-weight:500;text-decoration:none;white-space:nowrap} border-radius:8px;font-size:.875rem;font-weight:500;text-decoration:none;white-space:nowrap}
@ -114,6 +115,81 @@ td.os{color:var(--ink)}
.cta-box .btn{background:var(--brass);color:oklch(17% 0.03 50);padding:.65rem 1.2rem; .cta-box .btn{background:var(--brass);color:oklch(17% 0.03 50);padding:.65rem 1.2rem;
border-radius:8px;font-size:.9rem;font-weight:500;text-decoration:none;white-space:nowrap} border-radius:8px;font-size:.9rem;font-weight:500;text-decoration:none;white-space:nowrap}
.cta-box .btn:hover{color:oklch(17% 0.03 50);filter:brightness(1.06)} .cta-box .btn:hover{color:oklch(17% 0.03 50);filter:brightness(1.06)}
.lede{font-size:1.05rem;color:var(--ink2);max-width:44rem;margin:0 0 1.5rem}
.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
.tool{background:var(--paper2);border:1px solid var(--rule2);border-radius:14px;padding:1.25rem;margin:0 0 2.5rem}
.tool-row{display:flex;flex-wrap:wrap;gap:.6rem}
.tool input[type=url],.tool input[type=text],.tool textarea,.tool select{background:var(--paper);color:var(--ink);
border:1px solid var(--rule2);border-radius:9px;padding:.75rem .9rem;font:inherit;font-size:1rem;min-width:0}
.tool input[type=url]{flex:1 1 20rem}
.tool textarea{width:100%;resize:vertical;line-height:1.5}
.tool input:focus-visible,.tool textarea:focus-visible,.tool select:focus-visible,.tool button:focus-visible{
outline:2px solid var(--brass);outline-offset:2px}
.btn-primary{background:var(--brass);color:oklch(17% 0.03 50);border:0;border-radius:9px;padding:.75rem 1.2rem;
font:inherit;font-weight:600;font-size:.95rem;cursor:pointer;white-space:nowrap;text-decoration:none;display:inline-block}
.btn-primary:disabled{opacity:.55;cursor:wait}
.btn-ghost,.tool-actions button{background:transparent;color:var(--ink2);border:1px solid var(--rule2);border-radius:8px;
padding:.45rem .8rem;font:inherit;font-size:.85rem;cursor:pointer}
.btn-ghost:hover,.tool-actions button:hover{border-color:var(--brass);color:var(--ink)}
.tool-hint{font-size:.85rem;color:var(--muted);margin:.7rem 0 0}
.tool-status{margin-top:1rem;font-size:.95rem}
.tool-status[data-kind=error]{color:oklch(75% 0.15 25)}
.tool-status[data-kind=busy]{color:var(--muted)}
.tool-status[data-kind=warn]{border:1px solid var(--rule2);border-left:3px solid var(--brass);border-radius:10px;padding:1rem 1.1rem;background:var(--paper)}
.tool-status[data-kind=warn] p{margin:0 0 .7rem}
.tool-meta{margin:1.2rem 0 .6rem}
.tool-meta strong{display:block;color:var(--ink);font-weight:500}
.tool-meta span{font-size:.82rem;color:var(--muted)}
.tool-actions{display:flex;flex-wrap:wrap;gap:.5rem;align-items:center;margin-bottom:.8rem}
.tool-actions label{font-size:.85rem;color:var(--muted);display:flex;gap:.35rem;align-items:center}
.tool-actions select{padding:.45rem .6rem;font-size:.85rem;max-width:14rem}
.transcript{max-height:26rem;overflow:auto;background:var(--paper);border:1px solid var(--rule);border-radius:10px;
padding:.9rem 1rem;font-size:.92rem;line-height:1.55}
.transcript p{margin:0 0 .35rem}
.transcript .ts{font-family:var(--mono);font-size:.75rem;color:var(--brass);text-decoration:none;margin-right:.35rem}
.cta-inline{display:flex;flex-wrap:wrap;gap:.75rem 1rem;align-items:center;justify-content:space-between;
margin-top:1rem;padding-top:1rem;border-top:1px solid var(--rule)}
.cta-inline p{margin:0;font-size:.9rem;color:var(--muted);flex:1 1 18rem}
.modes{display:flex;flex-wrap:wrap;gap:.4rem;margin:0 0 .9rem;border:0;padding:0}
.modes label{border:1px solid var(--rule2);border-radius:999px;padding:.4rem .95rem;font-size:.9rem;cursor:pointer;color:var(--ink2)}
.modes input{position:absolute;opacity:0}
.modes label:has(input:checked){background:var(--brass);color:oklch(17% 0.03 50);border-color:var(--brass)}
.modes label:has(input:focus-visible){outline:2px solid var(--brass);outline-offset:2px}
.field{display:block;margin:0 0 .8rem}
.field span{display:block;font-size:.8rem;color:var(--muted);margin-bottom:.3rem}
.field input{width:100%}
.out{margin-top:1.2rem}
.out-head{display:flex;justify-content:space-between;align-items:center;gap:1rem;font-size:.85rem;color:var(--muted);margin-bottom:.6rem}
.chips{display:flex;flex-wrap:wrap;gap:.4rem}
.chip{background:var(--paper);border:1px solid var(--rule2);color:var(--ink2);border-radius:999px;padding:.3rem .75rem;font:inherit;font-size:.85rem;cursor:pointer}
.chip:hover{border-color:var(--brass)}
.title-list{padding:0;list-style:none;margin:0}
.title-opt{width:100%;display:grid;grid-template-columns:1fr auto;gap:.1rem 1rem;text-align:left;background:var(--paper);
border:1px solid var(--rule);border-radius:9px;padding:.65rem .85rem;margin-bottom:.4rem;font:inherit;color:var(--ink);cursor:pointer}
.title-opt:hover{border-color:var(--brass)}
.title-opt .meta{grid-column:1;font-size:.75rem;color:var(--muted)}
.title-opt .cp{grid-row:1/3;grid-column:2;align-self:center;font-size:.8rem;color:var(--muted)}
.desc-out{min-height:16rem}
.drop{display:block;border:1.5px dashed var(--rule2);border-radius:12px;padding:1.6rem 1rem;text-align:center;cursor:pointer;background:var(--paper)}
.drop[data-over]{border-color:var(--brass)}
.drop strong{display:block;color:var(--ink);font-weight:500}
.drop small{color:var(--muted)}
.opts{display:grid;gap:.9rem;grid-template-columns:1fr;margin:1rem 0}
@media(min-width:40rem){.opts{grid-template-columns:1fr 1fr}}
.opts fieldset{border:0;padding:0;margin:0}
.opts legend{font-size:.8rem;color:var(--muted);margin-bottom:.35rem}
.progress{height:6px;background:var(--paper);border-radius:99px;overflow:hidden;margin-top:1rem}
.progress span{display:block;height:100%;width:0;background:var(--brass);transition:width .2s}
.vc-result{display:grid;gap:1rem;grid-template-columns:1fr;align-items:start;margin-top:1.2rem}
@media(min-width:40rem){.vc-result{grid-template-columns:14rem 1fr}}
.vc-result video{width:100%;max-height:26rem;background:#000;border-radius:10px}
.tools-grid{display:grid;gap:.9rem;grid-template-columns:1fr;margin:1.5rem 0 2.5rem}
@media(min-width:44rem){.tools-grid{grid-template-columns:1fr 1fr 1fr}}
.tools-grid a{display:block;border:1px solid var(--rule2);border-radius:12px;padding:1.1rem 1.2rem;text-decoration:none;background:var(--paper2)}
.tools-grid a:hover{border-color:var(--brass)}
.tools-grid strong{display:block;color:var(--ink);font-weight:500;margin-bottom:.3rem}
.tools-grid span{font-size:.88rem;color:var(--muted)}
[hidden]{display:none!important}
footer.site{border-top:1px solid var(--rule);padding:2.5rem 0;font-size:.85rem;color:var(--muted)} footer.site{border-top:1px solid var(--rule);padding:2.5rem 0;font-size:.85rem;color:var(--muted)}
footer.site a{color:var(--muted)} footer.site a{color:var(--muted)}
footer.site .row{display:flex;flex-wrap:wrap;gap:1.25rem;margin-bottom:1rem} footer.site .row{display:flex;flex-wrap:wrap;gap:1.25rem;margin-bottom:1rem}
@ -173,7 +249,7 @@ const articleNode = (page) => ({
const buildGraph = (page) => { const buildGraph = (page) => {
// Error pages are described as a plain WebPage. Emitting an Article for one // Error pages are described as a plain WebPage. Emitting an Article for one
// would assert an author and a publication date for content nobody wrote. // would assert an author and a publication date for content nobody wrote.
const main = page.noindex const main = page.noindex || page.tool
? { ? {
'@type': 'WebPage', '@type': 'WebPage',
'@id': `${SITE.url}${page.path}#webpage`, '@id': `${SITE.url}${page.path}#webpage`,
@ -182,6 +258,7 @@ const buildGraph = (page) => {
url: `${SITE.url}${page.path}`, url: `${SITE.url}${page.path}`,
inLanguage: 'en-US', inLanguage: 'en-US',
publisher: { '@id': `${SITE.url}/#organization` }, publisher: { '@id': `${SITE.url}/#organization` },
...(page.tool ? { dateModified: page.updated || SITE.updated } : {}),
} }
: articleNode(page) : articleNode(page)
@ -196,6 +273,7 @@ const NAV = `
<a class="brand" href="${SITE.url}/"><img src="/logo-openshorts.png" alt="OpenShorts logo" width="26" height="26">OpenShorts</a> <a class="brand" href="${SITE.url}/"><img src="/logo-openshorts.png" alt="OpenShorts logo" width="26" height="26">OpenShorts</a>
<nav class="nav"> <nav class="nav">
<a href="/free-ai-clip-generator">Clip generator</a> <a href="/free-ai-clip-generator">Clip generator</a>
<a href="/tools" class="keep">Free tools</a>
<a href="/alternatives">Alternatives</a> <a href="/alternatives">Alternatives</a>
<a href="/mcp">MCP &amp; API</a> <a href="/mcp">MCP &amp; API</a>
<a href="${SITE.repo}" rel="noopener">GitHub</a> <a href="${SITE.repo}" rel="noopener">GitHub</a>
@ -221,6 +299,14 @@ const footer = (_related) => `
<a href="/mcp">MCP server and API</a> <a href="/mcp">MCP server and API</a>
<a href="/automate-shorts-api">Automate shorts</a> <a href="/automate-shorts-api">Automate shorts</a>
</div> </div>
<div class="row">
<a href="/tools">Free tools</a>
<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"> <div class="row">
<a href="/opus-clip-pricing">Opus Clip pricing</a> <a href="/opus-clip-pricing">Opus Clip pricing</a>
<a href="/opus-clip-free-alternative">Free Opus Clip alternative</a> <a href="/opus-clip-free-alternative">Free Opus Clip alternative</a>
@ -282,6 +368,38 @@ const ANALYTICS = `
window.__osAnalyticsInit(); window.__osAnalyticsInit();
</script>` </script>`
/* First-touch attribution for visits that start on a static page.
*
* The app snapshots where a visitor came from (src/lib/attribution.js, key
* os_attrib) and posts it at signup, but that code only runs once React
* boots, i.e. on the homepage. A visitor who landed here from Google and then
* clicked through arrived at the app with a same-origin referrer and
* landing_path "/", so every signup was credited to the homepage: 7,481 of
* 7,481 signup_attribution rows in the 30 days to 23-sep-2026. Writing the
* same key, in the same shape, from the page the visit actually started on
* fixes it without touching the app (first touch wins on both sides).
* Independent of the analytics switch: it is first-party localStorage that
* only ever reaches our own API, exactly like the app's copy. */
const ATTRIBUTION = `
<script>
(function () {
try {
var K = "os_attrib";
if (localStorage.getItem(K)) return;
var q = new URLSearchParams(location.search);
var r = document.referrer || "";
if (r.indexOf(location.origin) === 0) r = "";
localStorage.setItem(K, JSON.stringify({
referrer: r,
landing_path: location.pathname + location.search,
utm_source: q.get("utm_source") || "",
utm_medium: q.get("utm_medium") || "",
utm_campaign: q.get("utm_campaign") || ""
}));
} catch (e) { /* private mode */ }
})();
</script>`
/* The body CTA. Until now the only link to the app on these pages was the fixed /* The body CTA. Until now the only link to the app on these pages was the fixed
* nav button, so a reader who finished the article had nothing to click: the * nav button, so a reader who finished the article had nothing to click: the
* pages sit at positions 1.8-4 with a 0.2-1.6% CTR and no path into the * pages sit at positions 1.8-4 with a 0.2-1.6% CTR and no path into the
@ -302,8 +420,9 @@ const DEFAULT_CTA = {
const ctaBlock = (page) => { const ctaBlock = (page) => {
const c = { ...DEFAULT_CTA, ...(page.cta || {}) } const c = { ...DEFAULT_CTA, ...(page.cta || {}) }
const slug = page.path.replace(/^\//, '').replace(/\//g, '-') || 'home' // Pages about Autopilot send readers to the app tab, not the landing page.
const href = `${SITE.url}/` const target = c.href || `${SITE.url}/`
const href = target
return ` return `
<div class="cta-box"> <div class="cta-box">
<div class="copy"> <div class="copy">
@ -318,19 +437,19 @@ const ctaBlock = (page) => {
/* Internal links are rendered as a visible block rather than a nav bar because /* Internal links are rendered as a visible block rather than a nav bar because
* an engine reading the raw HTML has no way to weight a nav differently from * an engine reading the raw HTML has no way to weight a nav differently from
* body copy — a described link is a stronger signal than a bare one. */ * body copy — a described link is a stronger signal than a bare one. */
const relatedBlock = (related) => const relatedBlock = (related, title = 'Related comparisons') =>
!related?.length !related?.length
? '' ? ''
: `<h2>Related comparisons</h2><div class="cluster">${related : `<h2>${esc(title)}</h2><div class="cluster">${related
.map( .map(
(r) => (r) =>
`<a href="${esc(r.path)}"><strong>${esc(r.title)}</strong><span>${esc(r.blurb)}</span></a>` `<a href="${esc(r.path)}"><strong>${esc(r.title)}</strong><span>${esc(r.blurb)}</span></a>`
) )
.join('')}</div>` .join('')}</div>`
export function renderPage(page, related = [], { cta = true } = {}) { export function renderPage(page, related = [], { cta = true, toolScript = '' } = {}) {
const canonical = `${SITE.url}${page.path}` const canonical = `${SITE.url}${page.path}`
const showCta = cta && !page.noindex const showCta = cta && !page.noindex && page.cta !== false
const crumbs = [ const crumbs = [
`<a href="${SITE.url}/">Home</a>`, `<a href="${SITE.url}/">Home</a>`,
...(page.breadcrumb || []).map((c) => ...(page.breadcrumb || []).map((c) =>
@ -351,6 +470,7 @@ ${page.noindex ? '' : `<link rel="canonical" href="${canonical}">\n`}<meta name=
<link rel="icon" type="image/png" href="/logo-openshorts.png"> <link rel="icon" type="image/png" href="/logo-openshorts.png">
<link rel="stylesheet" href="/fonts.css"> <link rel="stylesheet" href="/fonts.css">
${ANALYTICS} ${ANALYTICS}
${page.noindex ? '' : ATTRIBUTION}
<meta property="og:type" content="article"> <meta property="og:type" content="article">
<meta property="og:url" content="${canonical}"> <meta property="og:url" content="${canonical}">
<meta property="og:title" content="${esc(page.title)}"> <meta property="og:title" content="${esc(page.title)}">
@ -369,6 +489,8 @@ ${NAV}
<main><div class="wrap"> <main><div class="wrap">
<div class="crumbs">${crumbs}</div> <div class="crumbs">${crumbs}</div>
<h1>${esc(page.h1)}</h1> <h1>${esc(page.h1)}</h1>
${page.lede ? `<p class="lede">${page.lede}</p>` : ''}
${page.tool ? page.tool.html : ''}
${ ${
// A byline and a publication date are authorship signals, and an error page // A byline and a publication date are authorship signals, and an error page
// is not authored content. Dating the 404 also read as a mistake to anyone // is not authored content. Dating the 404 also read as a mistake to anyone
@ -384,9 +506,10 @@ ${
${page.tldr ? `<div class="tldr"><span class="label">TL;DR</span>${page.tldr.map((p) => `<p>${p}</p>`).join('')}</div>` : ''} ${page.tldr ? `<div class="tldr"><span class="label">TL;DR</span>${page.tldr.map((p) => `<p>${p}</p>`).join('')}</div>` : ''}
${showCta ? ctaBlock(page) : ''} ${showCta ? ctaBlock(page) : ''}
${page.body} ${page.body}
${relatedBlock(related)} ${relatedBlock(related, page.relatedTitle)}
</div></main> </div></main>
${footer(related)} ${footer(related)}
${page.tool && toolScript ? `<script type="module" src="${esc(toolScript)}"></script>` : ''}
</body> </body>
</html>` </html>`
} }

493
dashboard/seo/tools.js Normal file
View file

@ -0,0 +1,493 @@
/* The free tools (/tools) and the two automation pages built around
* Autopilot (/auto-clip, /youtube-automation).
*
* 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
* the raw HTML a crawler reads and it is the first thing a visitor sees; the
* entry (dashboard/tools/*.js, built by Vite) only wires it up.
*
* House rules that apply to every line here (seo-work REGLAS.md): nothing
* invented, every number dated and sourced, no em dashes, no filler copy.
*/
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>`
const webApp = (path, name, description, category = 'MultimediaApplication') => ({
'@type': 'WebApplication',
'@id': `${SITE.url}${path}#app`,
name,
description,
url: `${SITE.url}${path}`,
applicationCategory: category,
operatingSystem: 'Any (runs in the browser)',
browserRequirements: 'Requires JavaScript',
isAccessibleForFree: true,
offers: { '@type': 'Offer', price: '0', priceCurrency: 'USD' },
publisher: { '@id': `${SITE.url}/#organization` },
})
/* ------------------------------------------------------------------------ */
/* /tools */
/* ------------------------------------------------------------------------ */
export const TOOLS = [
{
path: '/youtube-transcript-generator',
name: 'YouTube transcript generator',
blurb: 'Paste a link, get the transcript with timestamps. Copy it or download TXT and SRT.',
},
{
path: '/youtube-tag-generator',
name: 'YouTube tag, title and description generator',
blurb: 'Describe the video in a few lines, get tags, 10 title options or a description.',
},
{
path: '/video-aspect-ratio-converter',
name: 'Video to 9:16 converter',
blurb: 'Turn a 16:9 video vertical with a blurred background, a crop or black bars. Runs in your browser.',
},
]
const toolsHub = () => ({
path: '/tools',
title: 'Free Tools for YouTube and Short-Form Video | OpenShorts',
description:
'Free YouTube tools with no sign-up: transcript generator, tag, title and description generator, and a video to 9:16 converter that runs in your browser.',
h1: 'Free tools for YouTube and short-form video',
lede: 'Three small tools that do one job each, free and without an account. They come from the same team as the OpenShorts clip generator.',
breadcrumb: [{ name: 'Free tools' }],
published: PUBLISHED,
updated: PUBLISHED,
cta: false,
relatedTitle: 'Also on this site',
related: ['/auto-clip', '/youtube-automation', '/free-ai-clip-generator'],
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')}
</div>
<h2>What each tool does, and what it does not</h2>
<p><a href="/youtube-transcript-generator">The transcript generator</a> reads the
captions a video already has on YouTube, either the ones the creator uploaded or
YouTube's automatic ones. It does not run speech recognition itself, so a video
with no captions at all gets an honest "no captions" instead of a guess.</p>
<p><a href="/youtube-tag-generator">The tag, title and description generator</a>
writes from a short brief you type, using Google Gemini. It follows the limits
YouTube documents: titles up to 100 characters, descriptions up to 5,000, tags up
to 500 characters in total.</p>
<p><a href="/video-aspect-ratio-converter">The 9:16 converter</a> works on your
device. The video is never uploaded, which is why it has no queue and no daily
cap. It keeps the whole frame over a blurred copy, crops to fill, or adds black
bars. It does not follow faces: that is what the clip generator is for.</p>
<h2>Where the paid product starts</h2>
<p>If what you want is not one transcript or one converted file but a long video
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>
`,
faq: [],
})
/* ------------------------------------------------------------------------ */
/* /youtube-transcript-generator */
/* ------------------------------------------------------------------------ */
const transcriptTool = `
<section class="tool" id="tool" aria-label="YouTube transcript generator">
<form id="yt-form" class="tool-row" autocomplete="off">
<label for="yt-url" class="sr">YouTube video link</label>
<input id="yt-url" name="url" type="url" inputmode="url" required
placeholder="https://www.youtube.com/watch?v=...">
<button type="submit" class="btn-primary">Get transcript</button>
</form>
<p class="tool-hint">Any public video with captions, including YouTube's auto-generated ones. Watch, youtu.be, Shorts and live links all work.</p>
<div id="yt-status" class="tool-status" role="status" aria-live="polite" hidden></div>
<div id="yt-result" hidden>
<div class="tool-meta"><strong id="yt-title"></strong><span id="yt-sub"></span></div>
<div class="tool-actions">
<select id="yt-lang" aria-label="Caption track"></select>
<label><input type="checkbox" id="yt-ts" checked> timestamps</label>
<button type="button" id="yt-copy">Copy</button>
<button type="button" id="yt-txt">Download TXT</button>
<button type="button" id="yt-srt">Download SRT</button>
</div>
<div id="yt-text" class="transcript" tabindex="0" aria-label="Transcript"></div>
<div class="cta-inline">
<p>Want the best moments of this video as vertical clips with subtitles? OpenShorts cuts it into 3 to 15 shorts. 20 free minutes a month.</p>
<button type="button" id="yt-clip" class="btn-primary">Turn this video into clips</button>
</div>
</div>
</section>`
const EXAMPLES = [
['arj7oStGLkU', 'Tim Urban, "Inside the Mind of a Master Procrastinator" (TED, 14 min)',
'315 caption lines from the English track TED uploaded; the menu offers 50 tracks.'],
['UF8uR6Z6KLc', 'Steve Jobs, 2005 Stanford commencement address (15 min)',
'244 caption lines; 9 tracks in the menu.'],
['8S0FDjFBj8o', 'Will Stephen, "How to sound smart in your TEDx Talk" (6 min)',
'128 caption lines, a good short test.'],
]
const transcriptPage = () => ({
path: '/youtube-transcript-generator',
title: 'YouTube Transcript Generator: Free, TXT and SRT | OpenShorts',
description:
'Paste a YouTube link, get the full transcript with timestamps. Copy it or download TXT or SRT. Free, no sign-up, works with auto-generated captions.',
h1: 'YouTube transcript generator',
lede: 'Paste a link to a YouTube video and get its transcript with timestamps. Copy it, or download it as a TXT or SRT file. Free, no account.',
breadcrumb: [{ name: 'Free tools', path: '/tools' }, { name: 'YouTube transcript generator' }],
published: PUBLISHED,
updated: PUBLISHED,
cta: false,
tool: { entry: 'tool-transcript', html: transcriptTool },
relatedTitle: 'More free tools',
related: ['/youtube-tag-generator', '/video-aspect-ratio-converter', '/youtube-to-shorts-converter'],
body: `
<h2>How it works</h2>
<p>The tool asks YouTube for the captions the video already has. If the creator
uploaded subtitles in the language spoken in the video, you get those, because a
human wrote them. If not, you get YouTube's automatic captions, which are
speech recognition and read like it: no punctuation on older videos, and names
spelled the way they sound. When a video has several tracks, the menu above the
transcript switches between them. Machine translations are not offered, because
they are not what was said.</p>
<p>Timestamps link to that moment of the video. <strong>Copy</strong> takes the
text as shown (with or without timestamps), <strong>TXT</strong> saves the same
thing to a file, and <strong>SRT</strong> gives you a subtitle file you can load
into Premiere, DaVinci Resolve, CapCut or back into YouTube Studio.</p>
<h2>Try it with a real video</h2>
<p>These were checked on 23 September 2026. Click one to run it:</p>
<ul>
${EXAMPLES.map(([id, label, note]) => `<li><button type="button" class="btn-ghost" data-example-url="https://www.youtube.com/watch?v=${id}">Run</button> ${esc(label)}. ${esc(note)}</li>`).join('\n')}
</ul>
<h2>When there is no transcript</h2>
<p>Some videos have no captions at all: music, very new uploads that YouTube has
not processed yet, and channels that turned automatic captions off. Private,
members-only and age-restricted videos cannot be read either. In those cases the
tool says so rather than inventing text. If you need the words anyway, the
<a href="/free-ai-clip-generator">OpenShorts clip generator</a> runs its own
speech recognition with word-level timing and uses it to cut the video into
subtitled vertical clips.</p>
<h2>What people use a transcript for</h2>
<ul>
<li>Quoting a talk or an interview accurately, with the timestamp as the citation.</li>
<li>Turning a video into a blog post, a newsletter or show notes.</li>
<li>Pasting it into ChatGPT or Claude to summarise, find a moment or draft chapters.</li>
<li>Editing: an SRT lines the words up with the timeline in any video editor.</li>
</ul>
${faqBlock([
{
q: 'Is the YouTube transcript generator free?',
a: 'Yes. There is no account and no payment. To keep it fast for everyone it allows 10 transcripts per 10 minutes from the same network.',
},
{
q: 'Does it work on videos with only auto-generated captions?',
a: 'Yes. When the creator has not uploaded subtitles, the tool returns YouTube\'s automatic captions in the language spoken in the video and labels them as auto-generated.',
},
{
q: 'Why does it say a video has no captions?',
a: 'Because YouTube has none for it: no uploaded subtitles and no automatic track. That happens with music, with very recent uploads and when a channel disables automatic captions. Private, members-only and age-restricted videos cannot be read at all.',
},
{
q: 'Can I download the transcript as SRT?',
a: 'Yes. The SRT button saves a subtitle file with one cue per caption line, which video editors and YouTube Studio can import.',
},
{
q: 'Do you store the transcripts?',
a: 'The server keeps the result for up to 24 hours so that the same video is not fetched from YouTube twice, and nothing is tied to you.',
},
])}
`,
faq: [
{ q: 'Is the YouTube transcript generator free?', a: 'Yes. There is no account and no payment. It allows 10 transcripts per 10 minutes from the same network.' },
{ q: 'Does it work on videos with only auto-generated captions?', a: 'Yes. Without uploaded subtitles it returns YouTube\'s automatic captions in the spoken language, labelled as auto-generated.' },
{ q: 'Why does it say a video has no captions?', a: 'Because YouTube has none for it: no uploaded subtitles and no automatic track. Private, members-only and age-restricted videos cannot be read at all.' },
{ q: 'Can I download the transcript as SRT?', a: 'Yes. The SRT button saves a subtitle file that video editors and YouTube Studio can import.' },
],
extraNodes: [
webApp('/youtube-transcript-generator', 'YouTube transcript generator',
'Get the transcript of a YouTube video with timestamps from its existing captions. Copy it or download TXT and SRT.'),
],
})
/* ------------------------------------------------------------------------ */
/* /youtube-tag-generator */
/* ------------------------------------------------------------------------ */
const metadataTool = `
<section class="tool" id="tool" aria-label="YouTube tag, title and description generator">
<form id="md-form">
<fieldset class="modes">
<legend class="sr">What to generate</legend>
<label><input type="radio" name="mode" value="tags" checked> Tags</label>
<label><input type="radio" name="mode" value="titles"> Titles</label>
<label><input type="radio" name="mode" value="description"> Description</label>
</fieldset>
<label class="field" for="md-topic"><span>What is the video about? Who is it for? Paste timestamps if you want chapters.</span>
<textarea id="md-topic" rows="4" maxlength="2000" required
placeholder="Example: I bake sourdough at home with no stand mixer. I show the stretch and folds, the overnight proof in the fridge and how to tell when the loaf is done."></textarea>
</label>
<label class="field" for="md-keyword"><span>Main keyword (optional)</span>
<input id="md-keyword" type="text" maxlength="80" placeholder="sourdough bread">
</label>
<button type="submit" id="md-go" class="btn-primary">Generate tags</button>
</form>
<div id="md-status" class="tool-status" role="status" aria-live="polite" hidden></div>
<div id="md-out" class="out" hidden></div>
<div id="md-cta" class="cta-inline" hidden>
<p>Got the long video done? OpenShorts cuts it into vertical Shorts with subtitles, and its YouTube Studio writes titles from the video itself.</p>
<a id="md-cta-btn" class="btn-primary" href="${SITE.url}/">Clip the video</a>
</div>
</section>`
const SAMPLE_TAGS = ['procrastination', 'Tim Urban', 'TED talk', 'instant gratification monkey', 'panic monster',
'why we procrastinate', 'Tim Urban TED talk', 'procrastination TED talk', 'long term goals', 'no deadline',
'procrastinating', 'how to stop procrastinating', 'gratification monkey', 'Tim Urban procrastination',
'Tim Urbin', 'procrastionation', 'psychology', 'productivity', 'TED']
const SAMPLE_TITLES = [
'Why Procrastination Destroys Goals Without Deadlines',
'How Procrastination Works Inside Your Brain',
'Deadlines Actually Protect You From Procrastination',
'The Kind of Procrastination Panic Cannot Fix',
'Tim Urban on Procrastination',
]
const metadataPage = () => ({
path: '/youtube-tag-generator',
title: 'YouTube Tag, Title and Description Generator | OpenShorts',
description:
'Free YouTube tag generator that also writes titles and descriptions from a short brief. Stays inside YouTube\'s limits: 100-character titles, 500 for tags.',
h1: 'YouTube tag, title and description generator',
lede: 'Describe your video in a few lines and get tags, 10 title options or a full description. Free, no account.',
breadcrumb: [{ name: 'Free tools', path: '/tools' }, { name: 'YouTube tag, title and description generator' }],
published: PUBLISHED,
updated: PUBLISHED,
cta: false,
tool: { entry: 'tool-metadata', html: metadataTool },
relatedTitle: 'More free tools',
related: ['/youtube-transcript-generator', '/video-aspect-ratio-converter', '/youtube-automation'],
body: `
<h2>How to use it</h2>
<ol>
<li>Pick <strong>Tags</strong>, <strong>Titles</strong> or <strong>Description</strong>.</li>
<li>Write two or three sentences about the video: what happens in it, who it is for, anything specific (names, tools, places). Specific briefs get specific output.</li>
<li>Add the keyword you want to rank for, if you have one.</li>
<li>Click a tag to copy it, or copy all of them at once and paste them into the Tags field in YouTube Studio. Titles copy with one click; the description is editable before you copy it.</li>
</ol>
<p>Need the brief? Paste the video into the <a href="/youtube-transcript-generator">transcript generator</a> first and summarise from that.</p>
<h2>A real example</h2>
<p>This is unedited output from the generator on 23 September 2026, for the brief
<em>"A TED talk by Tim Urban about procrastination: the instant gratification
monkey, the panic monster, and why long-term goals with no deadline never get
done"</em> with the keyword <em>procrastination</em>.</p>
<p><strong>Tags</strong> (${SAMPLE_TAGS.join(', ').length} characters, note the two deliberate misspellings):</p>
<p><code>${esc(SAMPLE_TAGS.join(', '))}</code></p>
<p><strong>Five of the ten titles:</strong></p>
<ul>${SAMPLE_TITLES.map((t) => `<li>${esc(t)} <span class="sources">(${t.length} characters)</span></li>`).join('')}</ul>
<p><button type="button" class="btn-ghost" data-example-topic="A TED talk by Tim Urban about procrastination: the instant gratification monkey, the panic monster, and why long-term goals with no deadline never get done." data-example-keyword="procrastination">Load this brief</button></p>
<h2>What it follows, and why</h2>
<ul>
<li><strong>Tags matter less than you think.</strong> YouTube's own help page says tags "play a minimal role in your video's discovery" and are mainly useful when your topic is commonly misspelled. So the generator includes likely misspellings of the names in your brief, and the title and description deserve more of your time.</li>
<li><strong>Length limits.</strong> Titles can be up to 100 characters and descriptions up to 5,000. The tags field takes 500 characters in total, and the tool keeps the list under that and shows the count.</li>
<li><strong>The first lines of a description do the work.</strong> They are what shows before "more", so the generator puts the payoff and the keyword there.</li>
<li><strong>Three hashtags.</strong> YouTube shows up to three hashtags from the description next to the title and ignores every hashtag on a video that has more than 60.</li>
<li><strong>Nothing invented.</strong> The model is told to use only facts from your brief: no made-up numbers, guests or results, and no chapters unless you gave timestamps.</li>
</ul>
${faqBlock([
{
q: 'Is this YouTube tag generator free?',
a: 'Yes, with no account. Each click is one call to Google Gemini on our side, so it allows 12 generations per 10 minutes and 50 a day from the same network.',
},
{
q: 'Do YouTube tags still help SEO?',
a: 'A little. YouTube says tags play a minimal role in discovery and are most useful for commonly misspelled topics. Your title, thumbnail and description matter more.',
},
{
q: 'How long should a YouTube title be?',
a: 'YouTube allows 100 characters. Search results and phones cut long titles, so the generator aims for about 60 and puts the main point first.',
},
{
q: 'Which AI writes the titles and descriptions?',
a: 'Google Gemini, the same model family OpenShorts uses to pick clips and write titles in its YouTube Studio.',
},
{
q: 'Does it work in other languages?',
a: 'Yes. Write the brief in your language and the output comes back in the same language.',
},
])}
${sources([
'<a href="https://support.google.com/youtube/answer/146402" rel="noopener">YouTube Help: Add tags to your videos</a> (tags play a minimal role; useful for misspellings), checked 23 September 2026.',
'<a href="https://support.google.com/youtube/answer/57404" rel="noopener">YouTube Help: Edit video settings</a> (100-character titles, 5,000-character descriptions), checked 23 September 2026.',
'<a href="https://developers.google.com/youtube/v3/docs/videos" rel="noopener">YouTube Data API: videos resource</a> (tags up to 500 characters), checked 23 September 2026.',
'<a href="https://support.google.com/youtube/answer/6390658" rel="noopener">YouTube Help: Use hashtags for YouTube search</a> (up to three shown by the title, more than 60 ignored), checked 23 September 2026.',
])}
`,
faq: [
{ q: 'Is this YouTube tag generator free?', a: 'Yes, with no account. It allows 12 generations per 10 minutes and 50 a day from the same network.' },
{ q: 'Do YouTube tags still help SEO?', a: 'A little. YouTube says tags play a minimal role in discovery and are most useful for commonly misspelled topics.' },
{ q: 'How long should a YouTube title be?', a: 'YouTube allows 100 characters. The generator aims for about 60 and puts the main point first.' },
{ q: 'Which AI writes the titles and descriptions?', a: 'Google Gemini.' },
],
extraNodes: [
webApp('/youtube-tag-generator', 'YouTube tag, title and description generator',
'Generate YouTube tags, title options and a description from a short brief, within YouTube\'s length limits.', 'UtilitiesApplication'),
],
})
/* ------------------------------------------------------------------------ */
/* /video-aspect-ratio-converter */
/* ------------------------------------------------------------------------ */
const verticalTool = `
<section class="tool" id="tool" aria-label="Video to 9:16 converter">
<label class="drop" id="vc-drop" for="vc-file">
<strong>Choose a video or drop it here</strong>
<small id="vc-name">MP4, MOV or WebM. Up to 5 minutes are converted. The file stays on your device.</small>
<input id="vc-file" type="file" accept="video/*,.mp4,.mov,.m4v,.webm,.mkv" class="sr">
</label>
<div class="opts">
<fieldset>
<legend>Fill the vertical frame with</legend>
<div class="modes">
<label><input type="radio" name="vc-fit" value="blur" checked> Blurred background</label>
<label><input type="radio" name="vc-fit" value="crop"> Crop to fill</label>
<label><input type="radio" name="vc-fit" value="bars"> Black bars</label>
</div>
<label class="field" id="vc-pos-wrap" for="vc-pos"><span>Crop position (left to right)</span>
<input id="vc-pos" type="range" min="0" max="100" value="50">
</label>
</fieldset>
<fieldset>
<legend>Output size</legend>
<div class="modes">
<label><input type="radio" name="vc-size" value="1080" checked> 1080x1920</label>
<label><input type="radio" name="vc-size" value="720"> 720x1280</label>
</div>
</fieldset>
</div>
<button type="button" id="vc-go" class="btn-primary" disabled>Convert to 9:16</button>
<div id="vc-progress" class="progress" hidden><span></span></div>
<div id="vc-status" class="tool-status" role="status" aria-live="polite" hidden></div>
<div id="vc-result" class="vc-result" hidden>
<video id="vc-preview" controls playsinline muted></video>
<div>
<p id="vc-info" class="tool-hint"></p>
<p><button type="button" id="vc-download" class="btn-primary">Download</button></p>
<div class="cta-inline">
<p>Is someone talking in it? OpenShorts reframes with face tracking so the speaker stays in the frame, and cuts the long video into clips with subtitles.</p>
<a id="vc-cta-btn" class="btn-primary" href="${SITE.url}/">Try the clip generator</a>
</div>
</div>
</div>
</section>`
const verticalPage = () => ({
path: '/video-aspect-ratio-converter',
title: 'Video Aspect Ratio Converter (16:9 to 9:16) | OpenShorts',
description:
'Convert a video to 9:16 for TikTok, Reels and Shorts in your browser: blurred background, crop or black bars. Free, no upload, no watermark.',
h1: 'Video aspect ratio converter: 16:9 to 9:16 in your browser',
lede: 'Turn a horizontal video into a vertical 9:16 one for TikTok, Instagram Reels and YouTube Shorts. The conversion runs on your device, so nothing is uploaded.',
breadcrumb: [{ name: 'Free tools', path: '/tools' }, { name: 'Video to 9:16 converter' }],
published: PUBLISHED,
updated: PUBLISHED,
cta: false,
tool: { entry: 'tool-vertical', html: verticalTool },
relatedTitle: 'More free tools',
related: ['/youtube-transcript-generator', '/youtube-tag-generator', '/youtube-to-shorts-converter'],
body: `
<h2>The three ways to fill a vertical frame</h2>
<p>A 16:9 video is 1.78 times wider than it is tall; a 9:16 frame is 0.56. Something
has to give, and each option trades a different thing:</p>
<ul>
<li><strong>Blurred background</strong> keeps the whole picture, centred, over a
blurred and darkened copy of itself. Nothing is cut off, but the video only
fills about a third of the screen height. Good for screen recordings, slides and
wide shots.</li>
<li><strong>Crop to fill</strong> uses the full screen and keeps a vertical
slice of the frame, which you can slide left or right. It cuts away about two
thirds of the width, so it only works when the subject stays in one place.</li>
<li><strong>Black bars</strong> is the plain letterbox: the whole picture, with
the rest of the screen left black.</li>
</ul>
<p>The output is 1080x1920 or 720x1280, as MP4 (H.264) in Chrome, Edge and
Safari, or WebM in browsers that cannot encode H.264. Audio is kept.</p>
<h2>Why it runs in your browser</h2>
<p>Your browser already has a hardware video encoder, and the WebCodecs API lets
a page use it. So the file is read, re-framed and encoded on your machine and
never uploaded: no queue, no watermark, no account. The limits are the ones that
keep a browser tab stable: the first 5 minutes of the video and files up to
2 GB. Keep the tab open while it runs.</p>
<h2>When a fixed crop is not enough</h2>
<p>A fixed crop cannot follow a person who moves, and it cannot show two people
talking at the same time. That is what the
<a href="/youtube-to-shorts-converter">OpenShorts YouTube to Shorts converter</a>
does: it tracks faces with MediaPipe so the speaker stays in the frame, can stack
two people talking in a split screen, and cuts the long video into 3 to 15 clips
with subtitles.</p>
${faqBlock([
{
q: 'How do I convert a video to 9:16 for free?',
a: 'Choose the file above, pick blurred background, crop or black bars, and click Convert. The video is processed in your browser and you download a 1080x1920 or 720x1280 file. There is no sign-up and no watermark.',
},
{
q: 'Is my video uploaded anywhere?',
a: 'No. The conversion runs on your device with your browser\'s own video encoder. The file never leaves your computer or phone.',
},
{
q: 'Why is there a 5 minute limit?',
a: 'The finished video is held in the browser\'s memory until you download it, and long 1080p videos can exhaust a tab. Short-form platforms rarely take more than a few minutes anyway.',
},
{
q: 'Which browsers work?',
a: 'Current versions of Chrome, Edge, Safari and Firefox. The tool needs the WebCodecs API; a browser without it shows a message instead of failing silently.',
},
])}
${sources([
'<a href="https://developer.mozilla.org/en-US/docs/Web/API/WebCodecs_API" rel="noopener">MDN: WebCodecs API</a>, the browser encoder this tool uses.',
`<a href="https://github.com/Vanilagy/mediabunny" rel="noopener">Mediabunny</a>, the open source library that reads and writes the video files. Face tracking in the clip generator: the project source at <a href="${SITE.repo}" rel="noopener">github.com/mutonby/openshorts</a>.`,
])}
`,
faq: [
{ q: 'How do I convert a video to 9:16 for free?', a: 'Choose the file, pick blurred background, crop or black bars, and click Convert. It runs in your browser with no sign-up and no watermark.' },
{ q: 'Is my video uploaded anywhere?', a: 'No. The conversion runs on your device with your browser\'s own video encoder.' },
{ q: 'Why is there a 5 minute limit?', a: 'The finished video is held in the browser\'s memory until you download it, and long 1080p videos can exhaust a tab.' },
{ q: 'Which browsers work?', a: 'Current versions of Chrome, Edge, Safari and Firefox. The tool needs the WebCodecs API.' },
],
extraNodes: [
webApp('/video-aspect-ratio-converter', 'Video to 9:16 converter',
'Convert a horizontal video to vertical 9:16 in the browser with a blurred background, a crop or black bars.'),
],
})
export function toolPages() {
return [toolsHub(), transcriptPage(), metadataPage(), verticalPage()]
}

View file

@ -243,6 +243,7 @@ export default function Landing({ onLaunchApp }) {
{billingEnabled && <a href="#pricing" className="hover:text-ink transition-colors">Pricing</a>} {billingEnabled && <a href="#pricing" className="hover:text-ink transition-colors">Pricing</a>}
<a href="#comparison" className="hover:text-ink transition-colors">Comparison</a> <a href="#comparison" className="hover:text-ink transition-colors">Comparison</a>
<a href="#faq" className="hover:text-ink transition-colors">FAQ</a> <a href="#faq" className="hover:text-ink transition-colors">FAQ</a>
<a href="/tools" className="hover:text-ink transition-colors">Free tools</a>
</div> </div>
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<a <a
@ -275,8 +276,12 @@ export default function Landing({ onLaunchApp }) {
turn long videos into viral 9:16 shorts, or generate ugc marketing videos with ai actors. online, in the cloud, zero setup. 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{' '} 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>, <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 autopilot with the{' '} 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{' '}
<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>. <a href="/n8n-youtube-shorts-automation" className="text-ink2 underline underline-offset-4 decoration-rule hover:text-ink hover:decoration-brass transition-colors">n8n workflow</a>.
just want it free? start with the{' '}
<a href="/free-ai-clip-generator" className="text-ink2 underline underline-offset-4 decoration-rule hover:text-ink hover:decoration-brass transition-colors">free ai clip generator</a>.
</p> </p>
{/* The hero CTA is the product itself: paste a link and land in the {/* The hero CTA is the product itself: paste a link and land in the
@ -774,6 +779,12 @@ export default function Landing({ onLaunchApp }) {
<p className="font-display text-3xl md:text-5xl lowercase text-ink tracking-tight mb-10">clip it before it scrolls past.</p> <p className="font-display text-3xl md:text-5xl lowercase text-ink tracking-tight mb-10">clip it before it scrolls past.</p>
<nav aria-label="Guides and comparisons" className="border-t border-rule pt-6 mb-6 flex flex-wrap items-center gap-x-6 gap-y-2 text-sm lowercase text-muted"> <nav aria-label="Guides and comparisons" className="border-t border-rule pt-6 mb-6 flex flex-wrap items-center gap-x-6 gap-y-2 text-sm lowercase text-muted">
<a href="/free-ai-clip-generator" className="hover:text-ink transition-colors">free ai clip generator</a> <a href="/free-ai-clip-generator" className="hover:text-ink transition-colors">free ai clip generator</a>
<a href="/tools" className="hover:text-ink transition-colors">free tools</a>
<a href="/youtube-transcript-generator" className="hover:text-ink transition-colors">youtube transcript generator</a>
<a href="/youtube-tag-generator" className="hover:text-ink transition-colors">youtube tag generator</a>
<a href="/video-aspect-ratio-converter" className="hover:text-ink transition-colors">video to 9:16 converter</a>
<a href="/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="/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="/open-source-video-clipper" className="hover:text-ink transition-colors">open source video clipper</a>
<a href="/podcast-to-shorts" className="hover:text-ink transition-colors">podcast to shorts</a> <a href="/podcast-to-shorts" className="hover:text-ink transition-colors">podcast to shorts</a>

View file

@ -1,4 +1,5 @@
import { allows } from './consent'; import { allows } from './consent';
import { firstTouchProps } from './attribution';
// Lightweight custom-event helper (OpenPanel). // Lightweight custom-event helper (OpenPanel).
// //
@ -32,13 +33,23 @@ import { allows } from './consent';
// Stripe" from "reached Stripe and abandoned"; before 2-ago-2026 the modals // Stripe" from "reached Stripe and abandoned"; before 2-ago-2026 the modals
// emitted only their own *Checkout event and the difference was invisible. // emitted only their own *Checkout event and the difference was invisible.
// Prices ride along as ordinary props (e.g. value_usd) for breakdowns. // Prices ride along as ordinary props (e.g. value_usd) for breakdowns.
// Conversion events carry the visitor's first touch (landing page, referrer,
// campaign). A signup happens after the Google/magic-link redirect, in a new
// OpenPanel session whose entry page is always "/", so without these props
// every signup looked like it came from the homepage and the SEO pages showed
// zero conversions (7,481 of 7,481 signup_attribution rows in the 30 days to
// 23-sep-2026 said landing_path "/").
const FIRST_TOUCH_EVENTS = new Set(['Signup', 'CheckoutStarted', 'Subscribed']);
export function track(event, options) { export function track(event, options) {
try { try {
// `op` is a queueing stub until consent loads op1.js, so a call made before // `op` is a queueing stub until consent loads op1.js, so a call made before
// the visitor accepted would be flushed the moment they did. Check first. // the visitor accepted would be flushed the moment they did. Check first.
if (!allows('analytics')) return; if (!allows('analytics')) return;
if (typeof window !== 'undefined' && typeof window.op === 'function') { if (typeof window !== 'undefined' && typeof window.op === 'function') {
window.op('track', event, (options && options.props) || {}); const props = (options && options.props) || {};
window.op('track', event,
FIRST_TOUCH_EVENTS.has(event) ? { ...firstTouchProps(), ...props } : props);
} }
} catch (_) { } catch (_) {
/* analytics must never throw into the app */ /* analytics must never throw into the app */

View file

@ -38,6 +38,31 @@ export function capture() {
} catch (_) { /* never break boot over analytics */ } } catch (_) { /* never break boot over analytics */ }
} }
/**
* The first-touch snapshot flattened into event props: which page the visit
* started on (the static SEO pages write this same key, see seo/render.js),
* where from, and the campaign. Empty object when nothing was captured.
*/
export function firstTouchProps() {
try {
const raw = read(KEY);
if (!raw) return {};
const d = JSON.parse(raw);
let host = '';
try { host = d.referrer ? new URL(d.referrer).hostname : ''; } catch (_) { /* malformed */ }
const props = {
landing_path: String(d.landing_path || '').split('?')[0] || '/',
referrer_host: host || 'direct',
};
if (d.utm_source) props.utm_source = d.utm_source;
if (d.utm_medium) props.utm_medium = d.utm_medium;
if (d.utm_campaign) props.utm_campaign = d.utm_campaign;
return props;
} catch (_) {
return {};
}
}
/** /**
* Post the snapshot for a freshly signed-up user. Fire-and-forget: the server * Post the snapshot for a freshly signed-up user. Fire-and-forget: the server
* drops it if the account is not brand new or already has a row. * drops it if the account is not brand new or already has a row.

95
dashboard/tools/common.js Normal file
View file

@ -0,0 +1,95 @@
/* Shared helpers for the free tool pages.
*
* These pages are static HTML emitted by vite-plugin-seo.js; the markup of
* each tool is already in the document (so crawlers and no-JS clients see the
* form), and these modules only wire it up. No React, no framework: the
* biggest of them is the video converter, and that weight is mediabunny.
*/
// Same variable the app uses. Empty means same-origin (self-host behind one host).
export const API_URL = (import.meta.env.VITE_API_URL || '').replace(/\/$/, '')
/* OpenPanel events. window.op is the queueing stub the page head defines; it
* only ever flushes when the analytics init passed its host/placeholder guard,
* so on localhost, a fork or a preview build this records nothing. */
export function track(event, props) {
try {
if (typeof window.op === 'function') window.op('track', event, props || {})
} catch (_) { /* analytics must never break a tool */ }
}
export const $ = (id) => document.getElementById(id)
export function el(tag, attrs, ...children) {
const node = document.createElement(tag)
for (const [k, v] of Object.entries(attrs || {})) {
if (v === undefined || v === null || v === false) continue
if (k === 'class') node.className = v
else if (k === 'text') node.textContent = v
else if (k.startsWith('on')) node.addEventListener(k.slice(2), v)
else node.setAttribute(k, v === true ? '' : v)
}
for (const c of children) {
if (c === null || c === undefined || c === false) continue
node.append(c instanceof Node ? c : document.createTextNode(String(c)))
}
return node
}
export function setStatus(node, text, kind) {
node.textContent = text || ''
node.dataset.kind = kind || ''
node.hidden = !text
}
export async function copyText(text, button) {
try {
await navigator.clipboard.writeText(text)
} catch (_) {
// Older browsers / insecure contexts: a hidden textarea still works.
const ta = el('textarea', { style: 'position:fixed;opacity:0' })
ta.value = text
document.body.append(ta)
ta.select()
try { document.execCommand('copy') } catch (_) { /* nothing else to try */ }
ta.remove()
}
if (button) {
const old = button.textContent
button.textContent = 'Copied'
setTimeout(() => { button.textContent = old }, 1400)
}
}
export function downloadBlob(blob, filename) {
const url = URL.createObjectURL(blob)
const a = el('a', { href: url, download: filename })
document.body.append(a)
a.click()
a.remove()
setTimeout(() => URL.revokeObjectURL(url), 10000)
}
export function safeFilename(s, fallback) {
const out = String(s || '').replace(/[\\/:*?"<>|]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 80)
return out || fallback
}
/* Error text from our API's {detail: {code, message}} shape, or a generic line. */
export async function apiError(res) {
try {
const data = await res.json()
const d = data && data.detail
if (d && typeof d === 'object') return { code: d.code || '', message: d.message || '' }
if (typeof d === 'string') return { code: '', message: d }
} catch (_) { /* not JSON */ }
return { code: String(res.status), message: 'Something went wrong. Try again in a moment.' }
}
/* Hand a YouTube link to the app: MediaInput reads os_pending_url on mount,
* so the visitor lands in the clip generator with their video already in. */
export function openInApp(url, tool) {
track('tool_cta_click', { tool })
try { if (url) localStorage.setItem('os_pending_url', url) } catch (_) { /* private mode */ }
window.location.href = '/#app'
}

112
dashboard/tools/metadata.js Normal file
View file

@ -0,0 +1,112 @@
/* YouTube tag, title and description generator (/youtube-tag-generator).
*
* One form, three modes. The brief goes to our API, which makes one Gemini
* text call per click (rate-limited per IP); rendering and copying are local.
*/
import { API_URL, $, el, track, setStatus, copyText, apiError } from './common.js'
const TOOL = 'youtube-metadata'
const form = $('md-form')
const status = $('md-status')
const out = $('md-out')
const submit = $('md-go')
const LABELS = { tags: 'Generate tags', titles: 'Generate titles', description: 'Generate description' }
const mode = () => form.querySelector('input[name="mode"]:checked')?.value || 'tags'
function syncMode() {
submit.textContent = LABELS[mode()]
}
// Deep links: /youtube-tag-generator#titles opens the titles mode.
const fromHash = (window.location.hash || '').replace('#', '')
if (LABELS[fromHash]) {
const radio = form.querySelector(`input[name="mode"][value="${fromHash}"]`)
if (radio) radio.checked = true
}
syncMode()
form.querySelectorAll('input[name="mode"]').forEach((r) => r.addEventListener('change', () => {
syncMode()
history.replaceState(null, '', `#${mode()}`)
}))
function renderTags(data) {
const joined = data.tags.join(', ')
out.replaceChildren(
el('div', { class: 'out-head' },
el('span', { text: `${data.tags.length} tags · ${data.characters} of 500 characters` }),
el('button', { type: 'button', class: 'btn-ghost', onclick: (e) => copyText(joined, e.currentTarget), text: 'Copy all' })),
el('div', { class: 'chips' }, ...data.tags.map((t) =>
el('button', { type: 'button', class: 'chip', title: 'Copy this tag', onclick: (e) => copyText(t, e.currentTarget), text: t }))),
el('p', { class: 'tool-hint', text: 'Paste "Copy all" into the Tags field in YouTube Studio (Details, Show more). Remove any tag that does not describe your video.' }),
)
}
function renderTitles(data) {
out.replaceChildren(
el('div', { class: 'out-head' }, el('span', { text: `${data.titles.length} titles. Click one to copy it.` })),
el('ol', { class: 'title-list' }, ...data.titles.map((t) => el('li', {},
el('button', { type: 'button', class: 'title-opt', onclick: (e) => copyText(t.title, e.currentTarget.querySelector('.cp')) },
el('span', { class: 'tt', text: t.title }),
el('span', { class: 'meta', text: `${t.title.length} chars${t.angle ? ` · ${t.angle}` : ''}` }),
el('span', { class: 'cp', text: 'Copy' }))))),
)
}
function renderDescription(data) {
const ta = el('textarea', { class: 'desc-out', rows: '14', 'aria-label': 'Generated description' })
ta.value = data.description
out.replaceChildren(
el('div', { class: 'out-head' },
el('span', { text: `${data.description.length} of 5,000 characters. Edit it here, then copy.` }),
el('button', { type: 'button', class: 'btn-ghost', onclick: (e) => copyText(ta.value, e.currentTarget), text: 'Copy' })),
ta,
)
}
form.addEventListener('submit', async (e) => {
e.preventDefault()
const m = mode()
const topic = $('md-topic').value.trim()
if (topic.length < 15) {
setStatus(status, 'Describe the video in at least a sentence: what happens in it and who it is for.', 'error')
return
}
submit.disabled = true
setStatus(status, 'Writing...', 'busy')
try {
const res = await fetch(`${API_URL}/api/tools/youtube-metadata`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ mode: m, topic, keyword: $('md-keyword').value.trim() }),
})
if (!res.ok) {
const err = await apiError(res)
track('tool_used', { tool: TOOL, mode: m, ok: false, code: err.code })
setStatus(status, err.message, 'error')
return
}
const data = await res.json()
track('tool_used', { tool: TOOL, mode: m, ok: true })
setStatus(status, '', '')
if (m === 'tags') renderTags(data)
else if (m === 'titles') renderTitles(data)
else renderDescription(data)
out.hidden = false
$('md-cta').hidden = false
} catch (_) {
track('tool_used', { tool: TOOL, mode: m, ok: false, code: 'network' })
setStatus(status, 'Could not reach the generator. Check your connection and try again.', 'error')
} finally {
submit.disabled = false
}
})
document.querySelectorAll('[data-example-topic]').forEach((b) => b.addEventListener('click', () => {
$('md-topic').value = b.dataset.exampleTopic
$('md-keyword').value = b.dataset.exampleKeyword || ''
window.scrollTo({ top: 0, behavior: 'smooth' })
$('md-topic').focus()
}))
$('md-cta-btn')?.addEventListener('click', () => track('tool_cta_click', { tool: TOOL }))

View file

@ -0,0 +1,149 @@
/* YouTube transcript generator (/youtube-transcript-generator).
*
* Asks our API for the captions the video already has on YouTube and renders
* them with timestamps, plus copy / TXT / SRT export. Everything past the
* fetch happens here in the browser.
*/
import { API_URL, $, el, track, setStatus, copyText, downloadBlob, safeFilename, apiError, openInApp } from './common.js'
const TOOL = 'youtube-transcript'
const form = $('yt-form')
const input = $('yt-url')
const status = $('yt-status')
const result = $('yt-result')
const out = $('yt-text')
const langSel = $('yt-lang')
const tsBox = $('yt-ts')
const submit = form.querySelector('button[type="submit"]')
let current = null
let currentUrl = ''
const clock = (s, srt) => {
const ms = Math.round(s * 1000)
const h = Math.floor(ms / 3600000)
const m = Math.floor((ms % 3600000) / 60000)
const sec = Math.floor((ms % 60000) / 1000)
const pad = (n, w = 2) => String(n).padStart(w, '0')
if (srt) return `${pad(h)}:${pad(m)}:${pad(sec)},${pad(ms % 1000, 3)}`
return h ? `${h}:${pad(m)}:${pad(sec)}` : `${m}:${pad(sec)}`
}
const asText = (segs, withTs) =>
segs.map((s) => (withTs ? `[${clock(s.start)}] ${s.text}` : s.text)).join(withTs ? '\n' : ' ')
.replace(/ {2,}/g, ' ')
const asSrt = (segs) =>
segs.map((s, i) => {
const end = s.start + Math.max(s.dur || 0, 0.5)
return `${i + 1}\n${clock(s.start, true)} --> ${clock(end, true)}\n${s.text}\n`
}).join('\n')
function render() {
if (!current) return
const withTs = tsBox.checked
out.replaceChildren()
if (!withTs) {
out.append(el('p', { text: asText(current.segments, false) }))
return
}
const frag = document.createDocumentFragment()
for (const s of current.segments) {
frag.append(el('p', {},
el('a', {
class: 'ts',
href: `https://www.youtube.com/watch?v=${current.video_id}&t=${Math.floor(s.start)}s`,
target: '_blank', rel: 'noopener',
text: clock(s.start),
}),
' ', s.text))
}
out.append(frag)
}
function showNoCaptions(message) {
result.hidden = true
status.replaceChildren(
el('p', {}, el('strong', { text: 'No captions to read. ' }), message || ''),
el('p', { text: 'OpenShorts runs its own speech recognition on the audio, word by word, so it can transcribe this video and cut it into vertical clips with subtitles. 20 free minutes a month, no credit card.' }),
el('button', {
type: 'button', class: 'btn-primary',
onclick: () => openInApp(currentUrl, TOOL),
text: 'Transcribe and clip it with OpenShorts',
}),
)
status.dataset.kind = 'warn'
status.hidden = false
}
async function load(url, lang) {
currentUrl = url
submit.disabled = true
setStatus(status, 'Reading the captions from YouTube...', 'busy')
const t0 = performance.now()
try {
const q = new URLSearchParams({ url })
if (lang) q.set('lang', lang)
const res = await fetch(`${API_URL}/api/tools/youtube-transcript?${q}`)
if (!res.ok) {
const err = await apiError(res)
track('tool_used', { tool: TOOL, ok: false, code: err.code })
if (err.code === 'no_captions') return showNoCaptions(err.message)
setStatus(status, err.message, 'error')
return
}
current = await res.json()
track('tool_used', { tool: TOOL, ok: true, kind: current.kind, cached: !!current.cached,
ms: Math.round(performance.now() - t0) })
$('yt-title').textContent = current.title
const mins = Math.round((current.duration || 0) / 60)
const words = current.segments.reduce((n, s) => n + s.text.split(/\s+/).length, 0)
$('yt-sub').textContent = [
current.channel,
mins ? `${mins} min` : '',
`${words.toLocaleString('en-US')} words`,
current.kind === 'auto' ? 'YouTube auto-generated captions' : 'captions uploaded by the creator',
].filter(Boolean).join(' · ')
langSel.replaceChildren(...current.languages.map((l) => el('option', {
value: l.request,
selected: l.code === current.language && l.kind === current.kind,
text: l.name,
})))
langSel.hidden = current.languages.length < 2
render()
setStatus(status, '', '')
result.hidden = false
} catch (_) {
track('tool_used', { tool: TOOL, ok: false, code: 'network' })
setStatus(status, 'Could not reach the transcript service. Check your connection and try again.', 'error')
} finally {
submit.disabled = false
}
}
form.addEventListener('submit', (e) => {
e.preventDefault()
const url = input.value.trim()
if (!url) return
load(url)
})
langSel.addEventListener('change', () => load(currentUrl, langSel.value))
tsBox.addEventListener('change', render)
$('yt-copy').addEventListener('click', (e) => current && copyText(asText(current.segments, tsBox.checked), e.currentTarget))
$('yt-txt').addEventListener('click', () => {
if (!current) return
downloadBlob(new Blob([asText(current.segments, tsBox.checked)], { type: 'text/plain;charset=utf-8' }),
`${safeFilename(current.title, current.video_id)}.txt`)
})
$('yt-srt').addEventListener('click', () => {
if (!current) return
downloadBlob(new Blob([asSrt(current.segments)], { type: 'application/x-subrip;charset=utf-8' }),
`${safeFilename(current.title, current.video_id)}.srt`)
})
$('yt-clip').addEventListener('click', () => openInApp(currentUrl, TOOL))
// Example buttons in the page copy fill the form and run it.
document.querySelectorAll('[data-example-url]').forEach((b) => b.addEventListener('click', () => {
input.value = b.dataset.exampleUrl
window.scrollTo({ top: 0, behavior: 'smooth' })
load(input.value)
}))

203
dashboard/tools/vertical.js Normal file
View file

@ -0,0 +1,203 @@
/* Video to 9:16 converter (/video-aspect-ratio-converter).
*
* Runs entirely in the visitor's browser: mediabunny demuxes the file, the
* browser's WebCodecs decoder/encoder do the heavy lifting (hardware-
* accelerated where available), and each frame is composed on a canvas. The
* file never leaves the device, so there is no upload, no server cost and
* nothing to rate-limit.
*/
import {
Input, Output, Conversion, BlobSource, BufferTarget, ALL_FORMATS,
Mp4OutputFormat, WebMOutputFormat, QUALITY_HIGH,
getFirstEncodableVideoCodec,
} from 'mediabunny'
import { $, track, setStatus, downloadBlob, safeFilename } from './common.js'
const TOOL = 'video-9-16'
const MAX_SECONDS = 5 * 60
const MAX_BYTES = 2 * 1024 * 1024 * 1024
const fileInput = $('vc-file')
const drop = $('vc-drop')
const status = $('vc-status')
const go = $('vc-go')
const progress = $('vc-progress')
const bar = progress.querySelector('span')
const result = $('vc-result')
const preview = $('vc-preview')
const posWrap = $('vc-pos-wrap')
let file = null
let running = null
const option = (name) => document.querySelector(`input[name="${name}"]:checked`)?.value
function syncOptions() {
posWrap.hidden = option('vc-fit') !== 'crop'
}
document.querySelectorAll('input[name="vc-fit"]').forEach((r) => r.addEventListener('change', syncOptions))
syncOptions()
function pick(f) {
if (!f) return
if (!/^video\//.test(f.type) && !/\.(mp4|mov|m4v|webm|mkv)$/i.test(f.name)) {
setStatus(status, 'That does not look like a video file. MP4, MOV and WebM work best.', 'error')
return
}
if (f.size > MAX_BYTES) {
setStatus(status, 'That file is over 2 GB. Trim it first or use a shorter export.', 'error')
return
}
file = f
$('vc-name').textContent = `${f.name} · ${(f.size / 1048576).toFixed(1)} MB`
go.disabled = false
result.hidden = true
setStatus(status, '', '')
}
fileInput.addEventListener('change', () => pick(fileInput.files[0]))
;['dragenter', 'dragover'].forEach((ev) => drop.addEventListener(ev, (e) => { e.preventDefault(); drop.dataset.over = '1' }))
;['dragleave', 'drop'].forEach((ev) => drop.addEventListener(ev, (e) => { e.preventDefault(); delete drop.dataset.over }))
drop.addEventListener('drop', (e) => pick(e.dataTransfer.files[0]))
const supported = typeof window.VideoEncoder === 'function' && typeof window.VideoDecoder === 'function'
if (!supported) {
setStatus(status, 'This browser cannot encode video on the page (it lacks the WebCodecs API). Current Chrome, Edge, Safari and Firefox can.', 'error')
go.disabled = true
}
/* One frame of output. `fit` is blur (whole frame over a blurred copy of
* itself), crop (fill the frame, cut the sides at `pos`) or bars (whole frame
* on black). The blur is a downscale-then-upscale, not ctx.filter: Safari's
* canvas had no filter support until 18, and this is cheaper everywhere. */
function makeComposer(W, H, fit, pos, srcW, srcH) {
const canvas = new OffscreenCanvas(W, H)
const ctx = canvas.getContext('2d', { alpha: false })
const small = new OffscreenCanvas(27, 48)
const sctx = small.getContext('2d', { alpha: false })
ctx.imageSmoothingQuality = 'high'
let crop = null
if (fit === 'crop' && srcW && srcH) {
const target = W / H
if (srcW / srcH > target) {
const cw = Math.round(srcH * target)
crop = { left: Math.round((srcW - cw) * pos), top: 0, width: cw, height: srcH }
} else {
const ch = Math.round(srcW / target)
crop = { left: 0, top: Math.round((srcH - ch) * 0.5), width: srcW, height: ch }
}
}
return (sample) => {
if (fit === 'crop') {
sample.drawWithFit(ctx, crop ? { fit: 'cover', crop } : { fit: 'cover' })
} else {
if (fit === 'blur') {
sample.drawWithFit(sctx, { fit: 'cover' })
ctx.drawImage(small, 0, 0, W, H)
ctx.fillStyle = 'rgba(0,0,0,0.28)'
ctx.fillRect(0, 0, W, H)
} else {
ctx.fillStyle = '#000'
ctx.fillRect(0, 0, W, H)
}
sample.drawWithFit(ctx, { fit: 'contain' })
}
return canvas
}
}
async function convert() {
if (!file || running) return
const size = option('vc-size') === '720' ? [720, 1280] : [1080, 1920]
const [W, H] = size
const fit = option('vc-fit') || 'blur'
const pos = Number($('vc-pos').value) / 100
go.disabled = true
result.hidden = true
progress.hidden = false
bar.style.width = '0%'
setStatus(status, 'Reading the video...', 'busy')
const t0 = performance.now()
let input
try {
input = new Input({ source: new BlobSource(file), formats: ALL_FORMATS })
const vt = await input.getPrimaryVideoTrack()
if (!vt) throw new Error('This file has no video track.')
if (!(await vt.canDecode())) {
throw new Error(`This browser cannot decode the video in this file (${vt.codec || 'unknown codec'}). Try Chrome or Edge, or export the video as H.264 MP4 first.`)
}
const duration = await input.computeDuration()
const end = Math.min(duration, MAX_SECONDS)
// MP4/H.264 when the browser can encode it (Chrome, Edge, Safari), WebM
// otherwise (Firefox on Linux, Chromium builds without H.264).
let format = new Mp4OutputFormat({ fastStart: 'in-memory' })
let codec = await getFirstEncodableVideoCodec(['avc', 'hevc'], { width: W, height: H })
if (!codec) {
format = new WebMOutputFormat()
codec = await getFirstEncodableVideoCodec(['vp9', 'vp8', 'av1'], { width: W, height: H })
}
if (!codec) throw new Error('This browser cannot encode video on the page. Try a recent Chrome or Edge.')
const output = new Output({ format, target: new BufferTarget() })
const compose = makeComposer(W, H, fit, pos, vt.displayWidth, vt.displayHeight)
const conversion = await Conversion.init({
input,
output,
trim: { start: 0, end },
video: {
codec,
bitrate: QUALITY_HIGH,
forceTranscode: true,
process: compose,
processedWidth: W,
processedHeight: H,
},
showWarnings: false,
})
if (!conversion.isValid) {
const why = conversion.discardedTracks.map((d) => `${d.track.type}: ${d.reason}`).join(', ')
throw new Error(`This file cannot be converted in the browser (${why}).`)
}
const dropped = conversion.discardedTracks.filter((d) => d.track.type === 'audio')
conversion.onProgress = (p) => {
bar.style.width = `${Math.round(p * 100)}%`
setStatus(status, `Converting... ${Math.round(p * 100)}%`, 'busy')
}
running = conversion
await conversion.execute()
const blob = new Blob([output.target.buffer], { type: format.mimeType })
const ext = format instanceof Mp4OutputFormat ? 'mp4' : 'webm'
const url = URL.createObjectURL(blob)
// Show a frame instead of a black box until the visitor presses play.
preview.addEventListener('loadeddata', () => { try { preview.currentTime = Math.min(1, end / 2) } catch (_) { /* ignore */ } }, { once: true })
preview.src = url
const name = `${safeFilename(file.name.replace(/\.[^.]+$/, ''), 'video')}-9x16.${ext}`
$('vc-download').onclick = () => {
track('tool_download', { tool: TOOL })
downloadBlob(blob, name)
}
const secs = ((performance.now() - t0) / 1000).toFixed(1)
$('vc-info').textContent = [
`${W}x${H} ${ext.toUpperCase()}`,
`${(blob.size / 1048576).toFixed(1)} MB`,
`converted in ${secs} s on this device`,
duration > MAX_SECONDS ? `first ${MAX_SECONDS / 60} minutes only` : '',
dropped.length ? 'no audio (this browser could not re-encode it)' : '',
].filter(Boolean).join(' · ')
result.hidden = false
setStatus(status, '', '')
track('tool_used', { tool: TOOL, ok: true, fit, size: String(H), ext,
seconds: Math.round(end), ms: Math.round(performance.now() - t0) })
} catch (e) {
track('tool_used', { tool: TOOL, ok: false, code: String((e && e.name) || 'error').slice(0, 40) })
setStatus(status, (e && e.message) || 'The conversion failed.', 'error')
} finally {
running = null
progress.hidden = true
go.disabled = !file || !supported
try { input && input.dispose && input.dispose() } catch (_) { /* ignore */ }
}
}
go.addEventListener('click', convert)
$('vc-cta-btn')?.addEventListener('click', () => track('tool_cta_click', { tool: TOOL }))

View file

@ -139,8 +139,17 @@ export default function seoPlugin() {
) )
}, },
generateBundle() { generateBundle(_options, bundle) {
// Tool pages load a standalone entry (vite.config.js rollupOptions.input)
// whose file name carries a content hash; look it up here.
const entries = {}
for (const chunk of Object.values(bundle)) {
if (chunk.type === 'chunk' && chunk.isEntry) entries[chunk.name] = `/${chunk.fileName}`
}
for (const page of pages) { for (const page of pages) {
if (page.tool && !entries[page.tool.entry]) {
throw new Error(`[openshorts-seo] no built entry "${page.tool.entry}" for ${page.path}`)
}
this.emitFile({ this.emitFile({
type: 'asset', type: 'asset',
// Flat .html, not a directory with an index. nginx's `try_files $uri/` // Flat .html, not a directory with an index. nginx's `try_files $uri/`
@ -149,7 +158,12 @@ export default function seoPlugin() {
// `try_files $uri.html` (added to nginx.conf) serves these at the // `try_files $uri.html` (added to nginx.conf) serves these at the
// clean path with a 200 and no redirect. // clean path with a 200 and no redirect.
fileName: `${page.path.replace(/^\//, '')}.html`, fileName: `${page.path.replace(/^\//, '')}.html`,
source: substituteAnalyticsEnv(renderPage(page, relatedFor(page, pages)), env), source: substituteAnalyticsEnv(
renderPage(page, relatedFor(page, pages), {
toolScript: page.tool ? entries[page.tool.entry] : '',
}),
env
),
}) })
} }

View file

@ -14,6 +14,20 @@ export default defineConfig({
// into #root and emits the static /alternatives pages, sitemap.xml and // into #root and emits the static /alternatives pages, sitemap.xml and
// llms.txt. See vite-plugin-seo.js. // llms.txt. See vite-plugin-seo.js.
plugins: [react(), seo()], plugins: [react(), seo()],
// The free tools (/youtube-transcript-generator and friends) are static
// pages emitted by seo(); their behaviour ships as small standalone entries
// with no React in them. vite-plugin-seo.js finds each entry's hashed file
// name in the bundle and adds the <script> to its page.
build: {
rollupOptions: {
input: {
main: 'index.html',
'tool-transcript': 'tools/transcript.js',
'tool-metadata': 'tools/metadata.js',
'tool-vertical': 'tools/vertical.js',
},
},
},
server: { server: {
allowedHosts: [ allowedHosts: [
'openshorts.app', 'openshorts.app',

643
free_tools.py Normal file
View file

@ -0,0 +1,643 @@
"""Free public tools behind the static SEO pages (/tools on openshorts.app).
Two endpoints, both anonymous, both deliberately cheap:
* ``GET /api/tools/youtube-transcript`` reads the captions a video **already
has** on YouTube (manual subtitles first, then YouTube's own automatic
track). It never downloads media and never touches the GPU: no Parakeet, no
render. A video without captions gets an honest "no captions" answer and the
page points at the clip generator, which does transcribe.
* ``POST /api/tools/youtube-metadata`` writes titles, a description or tags
for a video from a short brief, with one Gemini text call.
Why yt-dlp and the static proxies. YouTube answers every anonymous request
from a datacenter IP with "Sign in to confirm you're not a bot" (measured from
the prod container on 23-sep-2026: direct = bot check in 0.8 s; the static ISP
pool = full caption list in 1.1 s). So the transcript goes out through the same
flat-rate ``STATIC_PROXY_URLS`` the download uses, anonymous first and with the
account cookies only as the second attempt on a route. It **never** uses the
per-GB ``PROXY_URL``: a free tool must not be able to run up a bandwidth bill.
With no statics configured (self-host) it goes direct.
Cost and abuse guards, all in-process (a restart resets them, which is fine
for limits this coarse): per-IP windows, a global daily cap per tool, a
semaphore on concurrent YouTube lookups, a hard timeout, and a 24 h cache so a
popular video is fetched once.
"""
from __future__ import annotations
import asyncio
import json
import os
import random
import re
import tempfile
import threading
import time
from collections import OrderedDict, defaultdict, deque
from typing import Optional
from urllib.parse import parse_qs, urlparse
from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel
router = APIRouter()
# --------------------------------------------------------------------------- #
# Rate limiting
# --------------------------------------------------------------------------- #
# (window seconds, max hits) per IP, plus one global cap per UTC day.
LIMITS = {
"transcript": {"per_ip": [(600, 10), (86400, 60)], "global_day": 3000},
"metadata": {"per_ip": [(600, 12), (86400, 50)], "global_day": 2000},
}
class RateLimiter:
"""Sliding windows per (tool, ip) and a fixed UTC-day counter per tool."""
def __init__(self, limits, clock=time.time):
self.limits = limits
self.clock = clock
self._hits = defaultdict(deque)
self._day = {}
self._lock = threading.Lock()
def check(self, tool: str, ip: str) -> Optional[str]:
"""Record a hit and return None, or return the reason it is refused
(nothing is recorded then)."""
cfg = self.limits[tool]
now = self.clock()
day = int(now // 86400)
with self._lock:
d, n = self._day.get(tool, (day, 0))
if d != day:
d, n = day, 0
if n >= cfg["global_day"]:
return "global"
hits = self._hits[(tool, ip)]
longest = max(w for w, _ in cfg["per_ip"])
while hits and now - hits[0] > longest:
hits.popleft()
for window, cap in cfg["per_ip"]:
if sum(1 for t in hits if now - t <= window) >= cap:
return "ip"
hits.append(now)
self._day[tool] = (d, n + 1)
# Keep the map from growing without bound on a long-lived process.
if len(self._hits) > 20000:
for key in [k for k, v in self._hits.items() if not v or now - v[-1] > longest]:
del self._hits[key]
return None
_limiter = RateLimiter(LIMITS)
def client_ip(request: Request) -> str:
# Traefik overwrites X-Forwarded-For from untrusted clients and uvicorn
# resolves it into request.client, so this is the real peer address.
return (request.client.host if request.client else "") or "unknown"
def _enforce(tool: str, request: Request):
reason = _limiter.check(tool, client_ip(request))
if reason == "ip":
raise HTTPException(status_code=429, detail={
"code": "rate_limited",
"message": "Too many requests from your network. Try again in a few minutes."})
if reason == "global":
raise HTTPException(status_code=429, detail={
"code": "busy",
"message": "This free tool hit its daily limit. It resets at midnight UTC."})
# --------------------------------------------------------------------------- #
# YouTube transcript
# --------------------------------------------------------------------------- #
_VIDEO_ID = re.compile(r"^[A-Za-z0-9_-]{11}$")
def extract_video_id(raw: str) -> Optional[str]:
"""The 11-character id of one YouTube video, or None.
Accepts watch / youtu.be / shorts / live / embed links and a bare id. The
request that goes out is always rebuilt from the id, so nothing the user
typed (a playlist, another host, a redirect) ever reaches yt-dlp.
"""
s = (raw or "").strip()
if _VIDEO_ID.match(s):
return s
if not re.match(r"^https?://", s, re.I):
s = "https://" + s
try:
u = urlparse(s)
except ValueError:
return None
host = (u.hostname or "").lower()
if host == "youtu.be":
cand = u.path.strip("/").split("/")[0]
return cand if _VIDEO_ID.match(cand) else None
if not (host == "youtube.com" or host.endswith(".youtube.com")
or host == "youtube-nocookie.com" or host.endswith(".youtube-nocookie.com")):
return None
parts = [p for p in u.path.split("/") if p]
if parts and parts[0] in ("watch", "watch_popup"):
cand = (parse_qs(u.query).get("v") or [""])[0]
return cand if _VIDEO_ID.match(cand) else None
if len(parts) >= 2 and parts[0] in ("shorts", "live", "embed", "v", "e"):
return parts[1] if _VIDEO_ID.match(parts[1]) else None
return None
def _base_lang(code: str) -> str:
return (code or "").split("-")[0].lower()
def choose_track(info: dict, lang: Optional[str] = None):
"""Pick the caption track to return: ``(kind, key, languages)``.
kind is "manual" or "auto" (YouTube's speech recognition), key the entry
in ``subtitles`` / ``automatic_captions``, languages what the user can
switch to. Machine translations of the auto track (every other key in
``automatic_captions``) are never offered: they are not a transcript.
Returns ``(None, None, languages)`` when the video has no captions.
"""
manual = {k: v for k, v in (info.get("subtitles") or {}).items()
if k != "live_chat" and v}
auto = info.get("automatic_captions") or {}
video_lang = info.get("language") or ""
orig = [k for k in auto if k.endswith("-orig")]
# Some videos list the ASR track under the plain language code only.
if not orig and video_lang and video_lang in auto:
orig = [video_lang]
# ``request`` is what the page sends back as ``lang`` to switch track:
# the plain code for a human track, ``<code>-orig`` for YouTube's ASR one.
languages = [{"code": k, "kind": "manual", "request": k,
"name": _track_name(manual[k], k)} for k in manual]
for k in orig:
code = k[:-5] if k.endswith("-orig") else k
languages.append({"code": code, "kind": "auto", "request": f"{code}-orig",
"name": _track_name(auto[k], code) + " (auto-generated)"})
video_base = _base_lang(video_lang)
languages.sort(key=lambda l: (_base_lang(l["code"]) != video_base,
_base_lang(l["code"]) != "en", l["kind"] != "manual",
l["name"].lower()))
def auto_key(code):
for k in orig:
if k == f"{code}-orig" or k == code:
return k
return None
if lang and lang.endswith("-orig"):
k = auto_key(lang[:-5])
if k:
return "auto", k, languages
lang = lang[:-5]
if lang:
if lang in manual:
return "manual", lang, languages
k = auto_key(lang)
if k:
return "auto", k, languages
# Default: a human track in the spoken language, then the auto track in
# the spoken language, then any human track (English first), then any auto.
if video_lang:
for k in manual:
if k == video_lang or _base_lang(k) == _base_lang(video_lang):
return "manual", k, languages
if orig:
return "auto", orig[0], languages
if manual:
for k in manual:
if _base_lang(k) == "en":
return "manual", k, languages
return "manual", next(iter(manual)), languages
return None, None, languages
def _track_name(formats, code):
for f in formats or []:
if f.get("name"):
return re.sub(r"\s*\(.*?\)\s*$", "", f["name"]).strip() or code
return code
def parse_json3(data) -> list:
"""YouTube json3 captions -> [{start, dur, text}] in seconds.
Events without segments are window/style markers; ``\\n``-only events are
the line breaks of the rolling auto captions. Both are dropped.
"""
if isinstance(data, (bytes, str)):
data = json.loads(data)
out = []
for ev in data.get("events") or []:
segs = ev.get("segs")
if not segs:
continue
text = "".join(s.get("utf8", "") for s in segs)
text = re.sub(r"\s+", " ", text.replace("\n", " ")).strip()
if not text:
continue
start = (ev.get("tStartMs") or 0) / 1000.0
dur = (ev.get("dDurationMs") or 0) / 1000.0
out.append({"start": round(start, 3), "dur": round(dur, 3), "text": text})
# Auto captions overlap (each line stays on screen until the next one
# ends); clamp so exported SRT cues never collide.
for a, b in zip(out, out[1:]):
if a["start"] + a["dur"] > b["start"]:
a["dur"] = round(max(0.0, b["start"] - a["start"]), 3)
return out
class TranscriptError(Exception):
def __init__(self, code: str, message: str, status: int):
super().__init__(message)
self.code, self.message, self.status = code, message, status
_UNAVAILABLE = re.compile(
r"private video|video unavailable|has been removed|not available|members-only|"
r"confirm your age|age-restricted|copyright|terminated|does not exist|premieres in",
re.I)
_BLOCKED = re.compile(r"not a bot|sign in to confirm|429|too many requests|403|"
r"unable to download|timed out|proxy|connection", re.I)
_TRANSCRIPT_CACHE: "OrderedDict[tuple, tuple]" = OrderedDict()
_CACHE_TTL = 24 * 3600
_CACHE_MAX = 400
_cache_lock = threading.Lock()
_yt_slots = threading.BoundedSemaphore(int(os.environ.get("FREE_TOOLS_YT_CONCURRENCY", "3")))
TRANSCRIPT_TIMEOUT = float(os.environ.get("FREE_TOOLS_YT_TIMEOUT", "45"))
def _cache_get(key):
with _cache_lock:
hit = _TRANSCRIPT_CACHE.get(key)
if not hit:
return None
ts, value = hit
if time.time() - ts > _CACHE_TTL:
del _TRANSCRIPT_CACHE[key]
return None
_TRANSCRIPT_CACHE.move_to_end(key)
return value
def _cache_put(key, value):
with _cache_lock:
_TRANSCRIPT_CACHE[key] = (time.time(), value)
_TRANSCRIPT_CACHE.move_to_end(key)
while len(_TRANSCRIPT_CACHE) > _CACHE_MAX:
_TRANSCRIPT_CACHE.popitem(last=False)
def transcript_routes():
"""Proxies to try, in order. Statics only (rotated); direct when there are
none. Never the per-GB PROXY_URL."""
statics = [p.strip() for p in os.environ.get("STATIC_PROXY_URLS", "").split(",")
if p.strip()]
if statics:
k = random.randrange(len(statics))
statics = statics[k:] + statics[:k]
routes = statics[:3]
if os.environ.get("DIRECT_FIRST", "").strip() == "1":
routes = [None] + routes
return routes
return [None]
class _QuietLogger:
def debug(self, msg): pass
def info(self, msg): pass
def warning(self, msg): pass
def error(self, msg): pass
def fetch_transcript(video_id: str, lang: Optional[str] = None) -> dict:
"""Blocking: resolve the caption track and download it. Raises
TranscriptError with a user-facing message."""
import yt_dlp
url = f"https://www.youtube.com/watch?v={video_id}"
cookies_env = os.environ.get("YOUTUBE_COOKIES")
ck_path = None
errors = []
try:
if cookies_env:
fd, ck_path = tempfile.mkstemp(prefix="tool_ck_", suffix=".txt")
with os.fdopen(fd, "w") as f:
f.write(cookies_env)
for proxy in transcript_routes():
for use_cookies in ([False, True] if ck_path else [False]):
opts = {"skip_download": True, "quiet": True, "no_warnings": True,
"noplaylist": True, "logger": _QuietLogger(),
"socket_timeout": 15,
# Captions only: without this a video whose formats are
# SABR-only fails with "Requested format is not available"
# although its caption list came back fine.
"ignore_no_formats_error": True,
"extractor_args": {"youtube": {"player_client": ["default"]}}}
if proxy:
opts["proxy"] = proxy
if use_cookies:
opts["cookiefile"] = ck_path
try:
with yt_dlp.YoutubeDL(opts) as ydl:
info = ydl.extract_info(url, download=False)
kind, key, languages = choose_track(info, lang)
meta = {
"video_id": video_id,
"title": info.get("title") or "",
"channel": info.get("channel") or info.get("uploader") or "",
"duration": info.get("duration") or 0,
"languages": languages,
}
if not kind and not info.get("formats"):
# A degraded answer: one of the statics returned
# a player response with no formats and no
# captions at all for a TED talk that has 49
# human tracks (23-sep-2026, twice in a row on
# the same IP, the other two fine). That is the
# route, not the video: try the next one.
errors.append("empty player response")
continue
if not kind:
raise TranscriptError(
"no_captions",
"This video has no captions on YouTube, not even automatic ones.",
404)
pool = (info.get("subtitles") if kind == "manual"
else info.get("automatic_captions")) or {}
fmt = next((f for f in pool.get(key, []) if f.get("ext") == "json3"), None)
if not fmt:
raise TranscriptError(
"no_captions",
"YouTube lists captions for this video but does not serve them in a readable format.",
404)
raw = ydl.urlopen(fmt["url"]).read()
segments = parse_json3(raw)
if not segments:
raise TranscriptError(
"no_captions", "The caption track for this video is empty.", 404)
code = key[:-5] if key.endswith("-orig") else key
return {**meta, "language": code, "kind": kind, "segments": segments}
except TranscriptError:
raise
except Exception as e: # noqa: BLE001 — classified below
msg = str(e)
errors.append(msg[:300])
if _UNAVAILABLE.search(msg) and not re.search(r"not a bot", msg, re.I):
raise TranscriptError(
"unavailable",
"YouTube says this video is private, removed, age-restricted or not "
"available, so its captions cannot be read.", 422)
raise TranscriptError(
"youtube_blocked",
"YouTube is not answering our servers right now. Try again in a minute, or open "
"the video on YouTube and use \"Show transcript\" under the description.", 503)
finally:
if ck_path:
try:
os.remove(ck_path)
except OSError:
pass
def _fetch_with_slot(video_id, lang):
if not _yt_slots.acquire(timeout=20):
raise TranscriptError("busy", "The transcript tool is busy. Try again in a few seconds.", 503)
try:
return fetch_transcript(video_id, lang)
finally:
_yt_slots.release()
@router.get("/api/tools/youtube-transcript")
async def youtube_transcript(request: Request, url: str = "", lang: str = ""):
video_id = extract_video_id(url)
if not video_id:
raise HTTPException(status_code=400, detail={
"code": "bad_url",
"message": "Paste the link of one YouTube video (youtube.com/watch?v=..., youtu.be/... or a Shorts link)."})
lang = lang.strip() if re.match(r"^[A-Za-z0-9-]{1,20}$", lang.strip() or "") else None
key = (video_id, lang or "")
cached = _cache_get(key)
if cached and "error" in cached:
e = cached["error"]
raise HTTPException(status_code=e["status"], detail={"code": e["code"], "message": e["message"]})
if cached:
return {**cached, "cached": True}
_enforce("transcript", request)
try:
result = await asyncio.wait_for(
asyncio.to_thread(_fetch_with_slot, video_id, lang), timeout=TRANSCRIPT_TIMEOUT)
except asyncio.TimeoutError:
raise HTTPException(status_code=504, detail={
"code": "timeout", "message": "YouTube took too long to answer. Try again."})
except TranscriptError as e:
if e.code in ("no_captions", "unavailable"):
# Cache the verdict about the video itself (not a blocked route):
# it will not change within the day, and a retry loop on it would
# spend the static pool for nothing.
_cache_put(key, {"error": {"code": e.code, "message": e.message, "status": e.status}})
raise HTTPException(status_code=e.status, detail={"code": e.code, "message": e.message})
_cache_put(key, result)
if not lang:
req = result["language"] + ("-orig" if result["kind"] == "auto" else "")
_cache_put((video_id, req), result)
return {**result, "cached": False}
# --------------------------------------------------------------------------- #
# YouTube title / description / tag generator
# --------------------------------------------------------------------------- #
MODES = ("titles", "description", "tags")
MAX_BRIEF = 2000
class MetadataRequest(BaseModel):
mode: str
topic: str
keyword: Optional[str] = ""
audience: Optional[str] = ""
_COMMON_RULES = """
- Write in the same language as the BRIEF. Never translate it.
- Use only facts present in the BRIEF. Do not invent numbers, results, names, prices, dates or guests.
- No emojis, no ALL CAPS words, no em dashes.
- Plain, specific wording a creator would actually publish. Avoid filler such as "in today's video", "ultimate guide", "you won't believe", "game-changer", "unlock", "dive into".
"""
PROMPTS = {
"titles": """You write YouTube video titles.
BRIEF (what the video is about):
{topic}
{extra}
Write 10 title options, each with a different angle: specific outcome, how-to with a concrete promise, question the viewer already asks, number or list, contrarian take, curiosity gap that the video actually pays off, short and direct.
Rules:
- Hard limit 100 characters (YouTube's maximum). Aim for 60 or fewer: search results and phones cut long titles, so the payoff must come first.
- Put the main keyword early when it reads naturally, but vary the structure: no more than three titles may start with the same word, and never use a "Keyword: ..." colon pattern more than twice.{keyword_rule}
- Never promise something the brief does not support.
{common}
Return JSON: {{"titles": [{{"title": "...", "angle": "2-4 word label for the angle"}}]}}""",
"description": """You write YouTube video descriptions.
BRIEF (what the video is about):
{topic}
{extra}
Write one description, 120 to 250 words, structured like this:
1. First two sentences (under 150 characters together): what the viewer gets from the video, with the main keyword in the first sentence. These are the only lines shown before "more", in search results and under the player.
2. A short paragraph with the specifics from the brief: what is covered, for whom.
3. If the BRIEF contains timestamps, a chapter list in "00:00 Title" format starting at 00:00. If it contains no timestamps, write no chapters and no timestamps at all.
4. One line inviting a specific next step (subscribe, comment with a question about the topic). Put placeholders like [link] where the creator should paste links; never invent URLs.
5. A final line with exactly 3 relevant hashtags (YouTube shows up to three next to the title).{keyword_rule}
{common}
Return JSON: {{"description": "..."}}""",
"tags": """You pick YouTube tags.
BRIEF (what the video is about):
{topic}
{extra}
Return 15 to 25 tags ordered from most to least important:
- the exact main keyword first{keyword_rule_short}
- close variations and long-tail phrasings people type into YouTube search
- common misspellings of names or terms in the brief, if any (YouTube says tags mainly help when the topic is commonly misspelled)
- 2 or 3 broader topic tags
Rules: lowercase unless a proper noun, no hashtags, no duplicates, each tag under 30 characters, and all tags joined with commas must stay under 450 characters (YouTube's limit is 500).
{common}
Return JSON: {{"tags": ["...", "..."]}}""",
}
def build_prompt(mode: str, topic: str, keyword: str = "", audience: str = "") -> str:
extra = f"TARGET AUDIENCE: {audience}\n" if audience else ""
kw_rule = (f"\n- The main keyword is \"{keyword}\": use it naturally, exactly once in the "
f"part that matters most." if keyword else "")
kw_short = f" (\"{keyword}\")" if keyword else ""
return PROMPTS[mode].format(topic=topic, extra=extra, keyword_rule=kw_rule,
keyword_rule_short=kw_short, common=_COMMON_RULES)
def _clean(s: str) -> str:
return re.sub(r"\s*—\s*", ", ", (s or "")).strip()
def shape_result(mode: str, data: dict) -> dict:
"""Validate and tidy the model's JSON into what the page renders."""
if mode == "titles":
items = []
for t in (data.get("titles") or [])[:12]:
if isinstance(t, str):
t = {"title": t, "angle": ""}
title = _clean(str(t.get("title", "")))[:100]
if title:
items.append({"title": title, "angle": _clean(str(t.get("angle", "")))[:40]})
if not items:
raise ValueError("no titles")
return {"titles": items}
if mode == "description":
desc = _clean(str(data.get("description", "")))[:5000]
if not desc:
raise ValueError("no description")
return {"description": desc}
seen, tags, total = set(), [], 0
for t in data.get("tags") or []:
t = re.sub(r"\s+", " ", str(t).replace("#", "").replace(",", " ")).strip()[:60]
if not t or t.lower() in seen:
continue
if total + len(t) + (1 if tags else 0) > 500:
break
seen.add(t.lower())
tags.append(t)
total += len(t) + (1 if len(tags) > 1 else 0)
if not tags:
raise ValueError("no tags")
return {"tags": tags, "characters": len(",".join(tags))}
def _gemini_key():
try:
from cloud import managed_keys
key = managed_keys.gemini_key()
if key:
return key
except Exception:
pass
return os.environ.get("GEMINI_API_KEY", "").strip() or None
METADATA_MODEL = (os.environ.get("FREE_TOOLS_GEMINI_MODEL")
or os.environ.get("GEMINI_MODEL_THUMBNAIL") or "gemini-3.7-flash")
def _thinking_config(types):
try:
return types.ThinkingConfig(thinking_level="low")
except Exception: # older SDK without thinking_level
return None
def _generate(prompt: str) -> dict:
from google import genai
from google.genai import types
client = genai.Client(api_key=_gemini_key())
resp = client.models.generate_content(
model=METADATA_MODEL,
contents=[prompt],
config=types.GenerateContentConfig(
response_mime_type="application/json",
# Thinking tokens count against max_output_tokens on the 3.x
# models; at 2048 with default thinking the description came back
# cut mid-string. Low thinking + a roomier cap keeps it whole and
# the cost per call at a few thousand tokens.
max_output_tokens=6000,
temperature=0.9,
thinking_config=_thinking_config(types),
),
)
text = (resp.text or "").strip()
text = re.sub(r"^```(?:json)?|```$", "", text).strip()
return json.loads(text)
@router.post("/api/tools/youtube-metadata")
async def youtube_metadata(payload: MetadataRequest, request: Request):
mode = (payload.mode or "").strip().lower()
if mode not in MODES:
raise HTTPException(status_code=400, detail={"code": "bad_mode", "message": "Unknown mode."})
topic = (payload.topic or "").strip()
if len(topic) < 15:
raise HTTPException(status_code=400, detail={
"code": "too_short",
"message": "Describe the video in at least a sentence: what happens in it and who it is for."})
topic = topic[:MAX_BRIEF]
keyword = re.sub(r"[\"\n\r{}]", " ", (payload.keyword or "")).strip()[:80]
audience = re.sub(r"[\n\r{}]", " ", (payload.audience or "")).strip()[:120]
if not _gemini_key():
raise HTTPException(status_code=503, detail={
"code": "not_configured", "message": "This tool needs a Gemini API key on the server."})
_enforce("metadata", request)
prompt = build_prompt(mode, topic.replace("{", "(").replace("}", ")"), keyword, audience)
last = None
for _ in range(2):
try:
data = await asyncio.wait_for(asyncio.to_thread(_generate, prompt), timeout=40)
return {"mode": mode, **shape_result(mode, data)}
except asyncio.TimeoutError:
last = "timeout"
break
except Exception as e: # noqa: BLE001 — model/JSON errors retry once
last = str(e)[:200]
print(f"[free_tools] metadata generation failed: {last}")
raise HTTPException(status_code=502, detail={
"code": "generation_failed", "message": "The generator did not answer. Try again."})

178
tests/test_free_tools.py Normal file
View file

@ -0,0 +1,178 @@
"""Free public tools (free_tools.py): URL parsing, caption track choice,
json3 parsing, the rate limiter and the shape of the generator output.
The network paths (yt-dlp, Gemini) are not exercised here; the prod check
runs them for real. What is pinned down is what decides cost and honesty:
nothing but one video id ever reaches yt-dlp, machine translations are never
served as a transcript, and the limiter refuses before any work is done.
"""
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
import free_tools as ft
class TestExtractVideoId:
@pytest.mark.parametrize("url", [
"https://www.youtube.com/watch?v=arj7oStGLkU",
"https://youtube.com/watch?v=arj7oStGLkU&t=42s",
"https://m.youtube.com/watch?v=arj7oStGLkU&list=PL123",
"youtube.com/watch?v=arj7oStGLkU",
"https://youtu.be/arj7oStGLkU?si=abc",
"https://www.youtube.com/shorts/arj7oStGLkU",
"https://www.youtube.com/live/arj7oStGLkU",
"https://www.youtube.com/embed/arj7oStGLkU",
"arj7oStGLkU",
])
def test_single_video_links(self, url):
assert ft.extract_video_id(url) == "arj7oStGLkU"
@pytest.mark.parametrize("url", [
"", "hello", "https://www.youtube.com/playlist?list=PL123",
"https://www.youtube.com/@ted", "https://www.youtube.com/results?search_query=x",
"https://evil.example/watch?v=arj7oStGLkU", "https://youtube.com.evil.io/watch?v=arj7oStGLkU",
"https://www.youtube.com/watch?v=short",
])
def test_everything_else_is_refused(self, url):
assert ft.extract_video_id(url) is None
def _fmt(name="English"):
return [{"ext": "json3", "url": "u", "name": name}]
class TestChooseTrack:
def test_manual_in_spoken_language_wins(self):
info = {"language": "en", "subtitles": {"es": _fmt("Spanish"), "en": _fmt()},
"automatic_captions": {"en-orig": _fmt("English (Original)"), "fr": _fmt()}}
kind, key, langs = ft.choose_track(info)
assert (kind, key) == ("manual", "en")
codes = {(l["code"], l["kind"]) for l in langs}
# auto translations ("fr") are never offered
assert codes == {("es", "manual"), ("en", "manual"), ("en", "auto")}
def test_auto_original_when_no_human_track(self):
info = {"language": "es", "subtitles": {},
"automatic_captions": {"es-orig": _fmt(), "en": _fmt(), "de": _fmt()}}
assert ft.choose_track(info)[:2] == ("auto", "es-orig")
def test_plain_code_auto_track_counts_as_original(self):
info = {"language": "en", "automatic_captions": {"en": _fmt(), "de": _fmt()}}
assert ft.choose_track(info)[:2] == ("auto", "en")
def test_live_chat_is_not_a_caption(self):
info = {"subtitles": {"live_chat": _fmt()}, "automatic_captions": {}}
assert ft.choose_track(info)[:2] == (None, None)
def test_requested_language(self):
info = {"language": "en", "subtitles": {"es": _fmt(), "en": _fmt()},
"automatic_captions": {"en-orig": _fmt()}}
assert ft.choose_track(info, "es")[:2] == ("manual", "es")
assert ft.choose_track(info, "en-orig")[:2] == ("auto", "en-orig")
# a translation that is not a real track falls back to the default
assert ft.choose_track(info, "ja")[:2] == ("manual", "en")
def test_parse_json3_drops_markers_and_clamps_overlaps():
data = {"events": [
{"tStartMs": 0, "dDurationMs": 5000},
{"tStartMs": 100, "dDurationMs": 4000, "segs": [{"utf8": "hello"}, {"utf8": " world"}]},
{"tStartMs": 2000, "dDurationMs": 10, "aAppend": 1, "segs": [{"utf8": "\n"}]},
{"tStartMs": 3000, "dDurationMs": 2500, "segs": [{"utf8": "second\nline"}]},
]}
out = ft.parse_json3(data)
assert out == [
{"start": 0.1, "dur": 2.9, "text": "hello world"},
{"start": 3.0, "dur": 2.5, "text": "second line"},
]
def test_rate_limiter_per_ip_and_global():
now = [1000.0]
lim = ft.RateLimiter({"t": {"per_ip": [(60, 2)], "global_day": 3}}, clock=lambda: now[0])
assert lim.check("t", "a") is None
assert lim.check("t", "a") is None
assert lim.check("t", "a") == "ip"
assert lim.check("t", "b") is None
assert lim.check("t", "c") == "global"
now[0] += 86400
assert lim.check("t", "c") is None
class TestShapeResult:
def test_tags_respect_the_500_character_limit(self):
tags = [f"tag number {i:02d} with padding" for i in range(40)]
out = ft.shape_result("tags", {"tags": tags + ["#Dup", "dup"]})
assert out["characters"] <= 500
assert out["characters"] == len(",".join(out["tags"]))
def test_tags_are_deduped_and_cleaned(self):
out = ft.shape_result("tags", {"tags": ["#Procrastination", "procrastination", "tim urban"]})
assert out["tags"] == ["Procrastination", "tim urban"]
def test_titles_cut_at_100_and_no_em_dash(self):
out = ft.shape_result("titles", {"titles": [{"title": "A — B" + "x" * 200, "angle": "how-to"}]})
t = out["titles"][0]["title"]
assert len(t) == 100 and "—" not in t
def test_empty_output_is_an_error(self):
with pytest.raises(ValueError):
ft.shape_result("description", {"description": ""})
def test_prompt_carries_the_keyword_and_rules():
p = ft.build_prompt("titles", "A talk about procrastination", "procrastination", "students")
assert '"procrastination"' in p and "TARGET AUDIENCE: students" in p
assert "Do not invent" in p
p2 = ft.build_prompt("description", "x" * 30)
assert "write no chapters" in p2
def _client():
app = FastAPI()
app.include_router(ft.router)
return TestClient(app)
def test_transcript_endpoint_rejects_non_video_before_any_work(monkeypatch):
called = []
monkeypatch.setattr(ft, "fetch_transcript", lambda *a: called.append(a))
r = _client().get("/api/tools/youtube-transcript", params={"url": "https://youtube.com/@ted"})
assert r.status_code == 400 and r.json()["detail"]["code"] == "bad_url"
assert not called
def test_transcript_endpoint_caches_and_maps_errors(monkeypatch):
ft._TRANSCRIPT_CACHE.clear()
monkeypatch.setattr(ft, "_limiter", ft.RateLimiter(ft.LIMITS))
calls = []
def fake(video_id, lang):
calls.append(video_id)
if video_id == "AAAAAAAAAAA":
raise ft.TranscriptError("no_captions", "none", 404)
return {"video_id": video_id, "title": "t", "channel": "c", "duration": 10,
"languages": [], "language": "en", "kind": "manual",
"segments": [{"start": 0, "dur": 1, "text": "hi"}]}
monkeypatch.setattr(ft, "fetch_transcript", fake)
c = _client()
r1 = c.get("/api/tools/youtube-transcript", params={"url": "https://youtu.be/arj7oStGLkU"})
r2 = c.get("/api/tools/youtube-transcript", params={"url": "arj7oStGLkU"})
assert r1.status_code == 200 and r1.json()["cached"] is False
assert r2.status_code == 200 and r2.json()["cached"] is True
for _ in range(2):
r = c.get("/api/tools/youtube-transcript", params={"url": "AAAAAAAAAAA"})
assert r.status_code == 404 and r.json()["detail"]["code"] == "no_captions"
assert calls == ["arj7oStGLkU", "AAAAAAAAAAA"]
def test_metadata_endpoint_validates_input(monkeypatch):
monkeypatch.setattr(ft, "_gemini_key", lambda: "k")
c = _client()
assert c.post("/api/tools/youtube-metadata", json={"mode": "x", "topic": "a" * 40}).status_code == 400
assert c.post("/api/tools/youtube-metadata", json={"mode": "tags", "topic": "short"}).status_code == 400
monkeypatch.setattr(ft, "_generate", lambda prompt: {"tags": ["a b", "c"]})
r = c.post("/api/tools/youtube-metadata", json={"mode": "tags", "topic": "A video about sourdough bread at home"})
assert r.status_code == 200 and r.json()["tags"] == ["a b", "c"]