# clip-forge

Adopt this skill: https://proskills.md/skills/other/lowdevco-clip-forge

Page: https://proskills.md/skills/other/lowdevco-clip-forge
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: SKILL.md
size: 17431
sha: 66a0c2bc47ea5ef6dac1c470e19a66206b2cc121
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/SKILL.md

````text
---
name: clip-forge
description: Turn a long YouTube video, podcast, gameplay recording, match or tutorial into ready-to-post, fully edited vertical Shorts / Reels / TikToks. Finds the most viral moments (from the transcript for talk, from action, sound and scoreboard or kill-feed changes for gameplay and sport), shows a scored table for approval, then renders 1080x1920 clips with a real edit - colour grade, punch-in zooms, slow motion, sound effects, speaker tracking, an animated headline and word-by-word captions (English and Malayalam). Use whenever the user gives a YouTube link or a video file and wants shorts, reels, clips, highlights, "viral parts", "best moments", "cut this into short videos" or "edit this clip", even if they do not name this skill. Also use when a message starts with /clip-gameplay, /clip-podcast, /clip-sports, /clip-tutorial, /clip-video or /clip-edit.
---

# ClipForge

Long video in, a handful of finished vertical clips out. ClipForge is built
by lowdevco.

The bar is a clip that looks like an experienced editor made it: the picture
fills the frame, the colour has punch, the picture and sound react on the
moments that matter, and the headline and captions are designed and timed.
A plain cut with a label on top is not the goal.

## At a glance

| Step | You do | Output | Stop for the user? |
|---|---|---|---|
| 0. Mode | Settle the kind of video, read its reference | `references/<mode>.md` in mind | Only if the mode is unclear |
| 1. Check | `check_setup.py` | `mode`, `todo`, `speech_to_text` | Before installing anything on their PC |
| 2. Get | `fetch.py`, the .bat route, or a file already here | `<workdir>/<video>.mp4` (+ subtitles) | Videos over ~90 min: whole or a section? |
| 3. Find | Tools from the mode reference | Candidate moments | No |
| 4. Score | Score, table, ask | Approved clip numbers | **Always.** Never render before the answer |
| 5. Edit | Plan → render → quality check | `<workdir>/shorts/*.mp4` | No |
| 6. Post copy | Title, caption, hashtags | `<workdir>/shorts/posts.md` | No |
| 7. Hand over | Deliver files, list clips, offer changes | The reply | It ends the turn |

Working conventions:

- All scripts live in `scripts/` next to this file. Call them with the
  absolute path to that folder.
- One work folder per video (`<workdir>`); finished clips go in
  `<workdir>/shorts`.
- Anything that takes more than a minute or two (speech-to-text, scouting,
  rendering) runs in the background, and you tell the user roughly how long.

## Ground rules

1. **Rights.** Only work on videos the user owns or may reuse. If they are
   clipping someone else's channel, say once that re-uploading needs the
   owner's permission, then carry on.
2. **Approval before rendering.** Rendering is the slow part and their taste
   decides. Show the scored table and wait.
3. **Never invent.** Hooks, callouts, kill counts, scores and quotes come from
   what you saw in frames or read in the transcript. Never make up a channel
   handle; ask for it once.
4. **Honest scores.** Three good moments get three high scores, not twelve
   85s. Say when you judged from still frames only.
5. **Check your own work.** Look at frames of every rendered clip before
   showing it (step 5c).
6. **Restraint.** Three well-placed beats in 30 s feel edited; ten feel like
   a filter.

## 0. Mode

The kind of video decides how moments are found, framed and captioned. Read
the one reference file for the mode before step 3, and follow it.

| Command | Mode | Reference | Use for |
|---|---|---|---|
| `/clip-gameplay <link>` | gameplay | `references/gameplay.md` | Game recordings and streams, with or without a facecam |
| `/clip-podcast <link>` | podcast | `references/podcast.md` | Podcasts, interviews, talking head: the moment is in the words |
| `/clip-sports <link>` | sports | `references/sports.md` | Matches and broadcasts: goals, wickets, points, finishes |
| `/clip-tutorial <link>` | tutorial | `references/tutorial.md` | How-to, lessons, coding, screen recordings: one complete idea per clip |
| `/clip-video <link>` | video | `references/video.md` | Everything else: vlogs, reviews, events, travel, reactions |
| `/clip-edit <file or link>` | edit | `references/edit.md` | The user already has the clip or the times and wants only the edit; replaces steps 3 and 4 |

- A command at the start of the message (or the kind of video named in
  words) settles the mode. Do not second-guess it.
- With no command, decide from the title, channel and a contact sheet
  (`peek.py --at` with five times spread over the video). Still unclear: ask
  in one line.
- Anything after the link is a request to honour, for example
  `/clip-gameplay <link> top 3, neon captions, watermark @myname`.

## 1. Check the machine

```
python scripts/check_setup.py
```

Read `mode`, `todo` and `speech_to_text`. Install what `todo` lists (they are
copy-paste commands; ask before installing on the user's own PC).

| Result | Meaning |
|---|---|
| `mode: local` | YouTube is reachable (Claude Code on the user's own PC). The whole pipeline runs from just a link |
| `mode: cloud` | YouTube is blocked (Claude chat / cloud sessions). The download happens on the user's computer; everything after runs here. Do not retry through other tools or mirrors: the block is at the network level |
| `speech_to_text: false` | No transcript can be made here unless the video has subtitles. Podcast mode needs one; say so before starting |

## 2. Get the video

**A. Local mode, link given**

```
python scripts/fetch.py "<url>" --out <workdir>
```

It prints the video path and any subtitle files. For videos over ~90 minutes
ask whether they want the whole thing or a section (`--section 600-3000`).

**B. Cloud mode, link given**

Say plainly, in one or two sentences, that this chat cannot download from
YouTube itself and the download takes one step on their PC. Then:

1. Send them `assets/pc/get_video.bat` (once; they keep it in a folder of
   their choice, e.g. a project folder connected to the chat).
2. They double-click it and paste the link. It saves the video, subtitles
   and info file into an `inbox` folder next to the .bat. Default is 720p to
   keep the file small; `get_video.bat <url> 1080` gives sharper crops.
3. If computer-folder tools are available (names containing
   `remote-devices`), list the `inbox` folder, copy the `.mp4` and every
   `.json3` / `.vtt` beside it into the workspace, and continue. Those tools
   usually cap one file at about 400 MB: if the video is bigger, ask them to
   re-run the .bat at 480, or to say which part of the video matters.
4. With no such tools, ask them to attach the video and subtitle file (small
   files only), or to run this skill in Claude Code on the PC where route A
   works end to end.

**C. A video file is already here** (attached, or in a connected folder):
use it directly. A subtitle file with the same name beside it is picked up
automatically.

## 3. Find the moments

Follow the reference file for the mode. The tools it draws on:

| Tool | What it gives |
|---|---|
| `transcribe.py <video> --out <workdir> [--lang en\|ml\|auto] [--model small]` | Word-timed transcript: subtitle file → faster-whisper → sherpa-onnx. Exit code 3 = no transcript possible |
| `scout.py <video> --out <workdir> [--top 12] [--len 30] [--kind sports] [--roi x,y,w,h]` | The stretches with the most sound and motion, ranked, each with an 8-frame filmstrip in `<workdir>/scout/`, plus `end.jpg` for the last 45 s. `--roi` is the kill-feed or scoreboard box: every change there is counted and timed |
| `track.py <video> --clips <workdir>/clips.json --write` | Who is on screen and who is talking in each clip; writes a suggested layout, face positions and a speaker-following crop path into `clips.json` |
| `analyze_audio.py <video> --out <workdir>` | Single loud instants (a laugh, a shout) with their lift in dB |
| `peek.py <video> --at 754,760 --out x.jpg` | Frames at exact times |
| `peek.py <video> --range 998-1032 --n 8 --out x.jpg` | A filmstrip of one stretch, start to finish |
| `peek.py <video> --at 600 --grid --out x.jpg` | One frame with a pixel grid, for reading the box of a facecam, kill feed or scoreboard |
| `peek.py <video> --at 600,640 --crop x,y,w,h --out x.jpg` | One region enlarged, for reading a score or other small on-screen text |

Transcripts:

- `exact_word_timing: false` means word timings are estimated inside each
  line. Captions still work; the highlight is a little less tight.
- Speech-to-text is roughly real time with `small` on 2 CPUs. Run it in the
  background and tell the user. Do not go below `small` for Malayalam, and
  say Malayalam captions will need a read-through.
- When it finishes, read `<workdir>/transcript.txt` in full (compact
  `[mm:ss] text`; the JSON is for the renderer).

Scouting: `scout.py` takes about two minutes for a 17-minute 1080p video. Its
`action` number is a rank inside that one video: it says where to look first,
not how good the moment is. Open the filmstrips and judge with your own eyes.

## 4. Score and get approval

Aim for 8–12 candidates on a long video (fewer if it is short), each 20–60 s;
action moments can be as short as 12 s. No overlaps.

Score each out of 100:

| Part | Points | What earns them |
|---|---|---|
| Hook | 30 | First 3 seconds make a stranger stop: a claim, a question, or action already under way |
| Payoff | 25 | It delivers: the answer, the punchline, the kill, the fail |
| Stands alone | 20 | Makes sense without the rest of the video |
| Emotion | 15 | Surprise, laughter, tension, awe, or strong disagreement |
| Pace | 10 | No dead stretch; the length fits the content |

Show the table, best first:

| # | Time | Len | Score | Hook line (on screen) | Why it works |
|---|---|---|---|---|---|
| 1 | 12:34–13:10 | 36s | 88 | He quit a ₹40 lakh job for this | Bold claim up front, clean ending |

Then, in the same message, ask:

- which numbers to render (offer "top 5");
- the channel handle for the watermark, if not known;
- whether they want a different look from the mode's default edit.

**Stop here until they answer.**

The hook line is the 3–8 word headline shown for the first 3.5 seconds. Put
`*stars*` around the one or two words that carry it; they take the accent
colour. Create curiosity without lying about the clip. Use the speaker's
language (Malayalam hook for a Malayalam clip).

## 5. Edit

Read `references/editing.md` now. It is the editing standard; this section
is the short version.

### 5a. Plan each clip

For every approved clip decide five things, then write `<workdir>/clips.json`:

| Decide | Key | Rule of thumb |
|---|---|---|
| Framing | `layout` | Fill the screen: `center` or `speaker` first, `blur` last |
| Treatment | `edit` | From the mode reference, unless the user named a look |
| Headline | `hook` | 3–8 words, one or two `*starred*` words, true to the clip |
| Beats | `beats` | The 2–3 moments the picture reacts to; exact times beat `auto` |
| Ending | `end`, `outro` | End on the payoff, never in an end card or menu |

```json
{"clips": [
  {"id": 1, "start": 754.2, "end": 790.6, "hook": "He quit a *₹40 lakh* job",
   "slug": "quit-job", "layout": "auto", "edit": "story", "tighten": true},
  {"id": 4, "start": 2210, "end": 2236, "hook": "1 HP. *Four enemies.*",
   "layout": "center", "edit": "hype", "captions": false,
   "beats": ["auto", {"t": 2229.4, "fx": ["punch", "flash"], "text": "Clutch"},
             {"t": 2231.0, "fx": "slowmo", "len": 1.2}]}
]}
```

**Edits**

| Edit | Best for | What it does |
|---|---|---|
| `hype` | Gameplay, sports, anything fast | Vivid grade, slow push-in, punch + shake + flash with a bass thump on each beat, condensed all-caps headline, progress bar |
| `premium` | General video (default) | Punchy grade, slow push-in, punch-in with a soft thump on each beat, bold headline |
| `story` | Podcasts, interviews, talking head | Soft grade, zoom cuts on sentence changes, animated captions |
| `clean` | Business, tutorials, serious topics | Soft grade and animated text only |
| `raw` | When the user wants it untouched | Plain cut, boxed headline, static captions |

**Beats** are the moments the picture reacts to. Leave `"beats"` out to have
them found from the sound, or list your own: `t` in source seconds, `fx` of
`punch`, `shake`, `flash`, `slowmo`, optional `text` for a one-to-three word
callout. Slow motion at most once per clip, on the payoff.

**Layouts**

| Layout | Result |
|---|---|
| `speaker` | 9:16 crop centred on the detected face; follows `"focus_path"` from `track.py` when present |
| `auto` | `speaker` if a clear face is found, otherwise `blur` |
| `center` | 9:16 crop that fills the screen; `"focus_x": 0–1` slides it, `"focus_path"` moves it over time |
| `stack` | Two speakers, one above the other; face positions come from `track.py` or `"faces"` |
| `split` | Facecam on top, game below; needs `"facecam": [x, y, w, h]` |
| `blur` | Whole width kept in the middle, blurred copy above and below; `"zoom": 1.0–2.5` enlarges the sharp picture. Last resort: it leaves the picture small |

**Looks**, for every clip on the command line or per clip in `clips.json`:

| Option | Per-clip key | What it does |
|---|---|---|
| `--edit hype\|premium\|story\|clean\|raw` | `"edit"` | The editing treatment |
| `--style bold\|clean\|neon\|fire` | `"style"` | Caption look and accent colour. `bold`: white capitals, yellow accent (default). `clean`: smaller sentence case, pale blue. `neon`: green accent, purple outline. `fire`: largest, orange accent |
| `--outro "Follow for more"` | `"outro"` | Tag that pops over the last 1.6 s |
| `--watermark "@name"` | `"watermark"` | Small see-through channel tag for the whole clip |
| `--progress` | `"progress"` | Thin bar along the top that fills as the clip plays |

### 5b. Render

```
python scripts/render.py <video> --clips <workdir>/clips.json --out <workdir>/shorts [--edit hype] [--style fire] [--outro "Follow for more"] [--watermark "@name"]
```

- It prints one JSON line per clip: `ok`, `file`, `layout`, `edit`,
  `seconds`, and `beats` with the times the effects landed.
- A full render takes about 1.5× the clip's length per clip on an ordinary
  PC. Say how long, and run it in the background.
- When framing or a beat time is a guess, run `--preview` first: small fast
  drafts (`*_preview.mp4`) to check before the full render.
- Re-render one clip with `--only <id>`.

### 5c. Quality check

Pull frames from each clip and look at them before showing anything:

```
ffmpeg -y -loglevel error -ss 2 -i <clip.mp4> -frames:v 1 <workdir>/check_01.jpg
```

Check the headline (2 s), one beat, and the last second. Every clip must pass:

| Check | Fix if it fails |
|---|---|
| The subject is in frame, nothing important cropped off | `layout`, `focus_x`, `zoom` or `facecam` |
| The frame is full, not a small picture floating in blur | `center` / `speaker`, or `blur` with `"zoom": 1.6`+ and `"hook_hold": true` |
| The hook is readable and true to the clip | Rewrite `hook` |
| Captions do not sit on a face or on the part of the game that matters | `layout` or `"captions": false` for voiceless gameplay |
| Beats land on the actual moment, not near it | Exact `t` in `beats` |
| The clip ends on the payoff, not in an end card or menu | Move `end`; check with `peek.py --range` |
| Caption words are right (names, terms) | Fix `transcript.json`, re-render |

Re-render just the failing clip with `--only <id>`.

## 6. Post copy

For each rendered clip, in the clip's language:

- **Title**: under 60 characters, the hook rephrased, no clickbait the clip
  does not pay off.
- **Caption**: 1–2 lines plus a question or call to action.
- **Hashtags**: 3–5, one broad, the rest specific to the topic or game.

Save them as `<workdir>/shorts/posts.md` and show them in the reply.

## 7. Hand over

- **Local mode**: say where the `shorts` folder is.
- **Cloud mode**: send each `.mp4` and `posts.md` as files. If the video came
  from a connected folder on their computer, also save the clips into a
  `shorts` folder beside the `inbox`.

Finish with one line per clip (number, length, hook) and offer changes: a
different start or end, another layout or caption style, a new hook line, or
more clips from the remaining candidates.

## Things that go wrong

| Symptom | Cause and fix |
|---|---|
| Download fails in local mode with a sign-in or bot message | Update yt-dlp (`python -m pip install -U yt-dlp`) and retry once. Still failing: ask the user to download it another way and use route C |
| `transcribe.py` exits 3 with "could not find module ... dll" | The speech engine is installed but cannot load. `check_setup.py` prints the fix (on Windows, the Visual C++ runtime). A machine problem, not a silent video: say so |
| Captions are wrong words | The transcript is wrong, not the renderer. Fix the words in `transcript.json` for that range and re-render, or re-run `transcribe.py` with a bigger `--model` |
| Face crop follows the wrong person | `track.py` guesses the speaker from mouth movement. Switch that clip to `stack`, or `center` with a `focus_x` |
| The edit feels like too much | Drop to `premium` or `clean`, or give a short explicit `beats` list instead of `auto` |
| `ass` filter missing | ffmpeg was built without libass; `check_setup` says how to install a full build |
````

## File: README.md
size: 12738
sha: fcfe38bb118a919a58a5e521f5b88fdb8e9959d8
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/README.md

```text
<div align="center">

<img src="docs/logo.svg" width="120" alt="ClipForge" />

<h1>ClipForge</h1>

<p><strong>Paste a link. Pick your favourites. Get Shorts that look edited.</strong></p>

<p>
  ClipForge is a skill for Claude. You give it a YouTube link or a video file.<br />
  It finds the best moments, shows you a scored shortlist, and turns the ones<br />
  you choose into finished vertical clips for YouTube Shorts, Instagram Reels<br />
  and TikTok.
</p>

<p>
  The clips come out edited, not just cut: the picture fills the screen, the<br />
  colour is graded, the camera punches in on the big moments, and the headline<br />
  and captions are animated.
</p>

<p>Created by <a href="https://github.com/lowdevco">lowdevco</a></p>

<hr />

<h2>What you type</h2>

<table align="center">
  <thead>
    <tr>
      <th align="center">Command</th>
      <th align="center">Best for</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td align="center"><code>/clip-gameplay</code></td>
      <td align="center">Game recordings and streams</td>
    </tr>
    <tr>
      <td align="center"><code>/clip-podcast</code></td>
      <td align="center">Podcasts, interviews, talking to camera</td>
    </tr>
    <tr>
      <td align="center"><code>/clip-sports</code></td>
      <td align="center">Matches and broadcasts</td>
    </tr>
    <tr>
      <td align="center"><code>/clip-tutorial</code></td>
      <td align="center">How-to videos, lessons, screen recordings</td>
    </tr>
    <tr>
      <td align="center"><code>/clip-video</code></td>
      <td align="center">Everything else: vlogs, reviews, events</td>
    </tr>
    <tr>
      <td align="center"><code>/clip-edit</code></td>
      <td align="center">A clip you have already cut</td>
    </tr>
  </tbody>
</table>

<p>Add what you want after the command:</p>

<pre><code>/clip-gameplay &lt;link&gt; top 3, neon captions, watermark @myname</code></pre>

<p><em>No command? Just ask for shorts. ClipForge works out what kind of video it is.</em></p>

<hr />

<h2>What happens next</h2>

<table align="center">
  <thead>
    <tr>
      <th align="center">Step</th>
      <th align="center">What ClipForge does</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td align="center"><strong>1</strong></td>
      <td align="center">Gets the video</td>
    </tr>
    <tr>
      <td align="center"><strong>2</strong></td>
      <td align="center">Finds 8 to 12 moments and scores each one out of 100</td>
    </tr>
    <tr>
      <td align="center"><strong>3</strong></td>
      <td align="center">Shows you the list and waits. Nothing is rendered until you choose</td>
    </tr>
    <tr>
      <td align="center"><strong>4</strong></td>
      <td align="center">Edits and renders your picks</td>
    </tr>
    <tr>
      <td align="center"><strong>5</strong></td>
      <td align="center">Writes a title, caption and hashtags for each clip</td>
    </tr>
  </tbody>
</table>

<hr />

<h2>Install</h2>

<h3>Claude Code</h3>

<p>Paste this as a message in Claude Code:</p>

<pre><code>Install the ClipForge skill from https://github.com/lowdevco/Clip-Forge</code></pre>

<p>
  Claude downloads the repository and runs the installer, asking before it<br />
  runs commands. Then start a new session.
</p>

<details>
  <summary>Or do it by hand</summary>
  <br />
  <pre><code>git clone https://github.com/lowdevco/Clip-Forge</code></pre>
  <pre><code>python Clip-Forge/tools/build.py --install</code></pre>
</details>

<h3>Claude chat (claude.ai and the desktop app)</h3>

<table align="center">
  <thead>
    <tr>
      <th align="center">Step</th>
      <th align="center">What to do</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td align="center"><strong>1</strong></td>
      <td align="center">Download <code>clip-forge.zip</code> from the <a href="https://github.com/lowdevco/Clip-Forge/releases/latest">latest release</a></td>
    </tr>
    <tr>
      <td align="center"><strong>2</strong></td>
      <td align="center">In Claude, open <strong>Settings</strong>, find <strong>Skills</strong>, and upload the zip</td>
    </tr>
    <tr>
      <td align="center"><strong>3</strong></td>
      <td align="center">On the same page, make sure code execution and file creation is switched on</td>
    </tr>
  </tbody>
</table>

<hr />

<h2>How to use it</h2>

<h3>In Claude Code</h3>

<p>Claude Code downloads the video for you, so the link is all it needs.</p>

<table align="center">
  <thead>
    <tr>
      <th align="center">Step</th>
      <th align="center">What to do</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td align="center"><strong>1</strong></td>
      <td align="center">Type a command with your YouTube link, for example <code>/clip-podcast https://youtu.be/...</code></td>
    </tr>
    <tr>
      <td align="center"><strong>2</strong></td>
      <td align="center">Wait for the scored list, then answer with your picks, for example <code>top 3</code></td>
    </tr>
    <tr>
      <td align="center"><strong>3</strong></td>
      <td align="center">Find the finished clips in the <code>shorts</code> folder Claude tells you about</td>
    </tr>
  </tbody>
</table>

<h3>In Claude chat</h3>

<p>Claude chat cannot download from YouTube, so you give it the video file.</p>

<table align="center">
  <thead>
    <tr>
      <th align="center">Step</th>
      <th align="center">What to do</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td align="center"><strong>1</strong></td>
      <td align="center">Open <a href="https://vidssave.com">vidssave.com</a>, paste the YouTube link, and download the video as MP4. 720p is enough</td>
    </tr>
    <tr>
      <td align="center"><strong>2</strong></td>
      <td align="center">Attach the file to a new chat (up to 500 MB) and type a command, for example <code>/clip-podcast</code></td>
    </tr>
    <tr>
      <td align="center"><strong>3</strong></td>
      <td align="center">Wait for the scored list, then answer with your picks, for example <code>top 3</code></td>
    </tr>
    <tr>
      <td align="center"><strong>4</strong></td>
      <td align="center">Download the finished clips Claude sends back</td>
    </tr>
  </tbody>
</table>

<hr />

<h2>Edit styles</h2>

<p>Say the name of a style to use it. Each command has a sensible default.</p>

<table align="center">
  <thead>
    <tr>
      <th align="center">Style</th>
      <th align="center">Good for</th>
      <th align="center">The look</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td align="center"><code>hype</code></td>
      <td align="center">Gameplay, sports</td>
      <td align="center">Vivid colour, zoom hits with shake and flash, a bass thump on big moments, bold all-caps headline, progress bar</td>
    </tr>
    <tr>
      <td align="center"><code>premium</code></td>
      <td align="center">Most videos (the default)</td>
      <td align="center">Punchy colour, a slow push-in, zoom hits with a soft thump</td>
    </tr>
    <tr>
      <td align="center"><code>story</code></td>
      <td align="center">Podcasts, talking to camera</td>
      <td align="center">Soft colour, zoom cuts between sentences, animated captions</td>
    </tr>
    <tr>
      <td align="center"><code>clean</code></td>
      <td align="center">Business, tutorials</td>
      <td align="center">Soft colour and animated text, nothing else</td>
    </tr>
    <tr>
      <td align="center"><code>raw</code></td>
      <td align="center">When you want it untouched</td>
      <td align="center">A plain cut with a simple headline</td>
    </tr>
  </tbody>
</table>

<hr />

<h2>What the editor can do</h2>

<table align="center">
  <thead>
    <tr>
      <th align="center">Feature</th>
      <th align="center">Details</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td align="center"><strong>Framing</strong></td>
      <td align="center">Full screen, follow the speaker, two speakers stacked, facecam on top, or blurred background</td>
    </tr>
    <tr>
      <td align="center"><strong>Speaker tracking</strong></td>
      <td align="center">Spots camera cuts, finds the faces in each shot, and keeps the person talking in frame</td>
    </tr>
    <tr>
      <td align="center"><strong>Big moments</strong></td>
      <td align="center">Zoom hit, shake, flash or slow motion, plus a pop-up word such as "GOAL" or "CLUTCH"</td>
    </tr>
    <tr>
      <td align="center"><strong>Headline</strong></td>
      <td align="center">Animated, with your key words in an accent colour</td>
    </tr>
    <tr>
      <td align="center"><strong>Captions</strong></td>
      <td align="center">Word by word, in four looks: <code>bold</code>, <code>clean</code>, <code>neon</code>, <code>fire</code>. English and Malayalam</td>
    </tr>
    <tr>
      <td align="center"><strong>Sound</strong></td>
      <td align="center">Volume evened out, with thump, whoosh and pop effects made by the skill itself</td>
    </tr>
    <tr>
      <td align="center"><strong>Finishing touches</strong></td>
      <td align="center">Outro tag, channel watermark, progress bar, silences trimmed</td>
    </tr>
    <tr>
      <td align="center"><strong>Safe area</strong></td>
      <td align="center">Text stays clear of the app buttons on Shorts, Reels and TikTok</td>
    </tr>
  </tbody>
</table>

<hr />

<h2>What Claude Code needs on your computer</h2>

<p>
  In Claude Code the tools run on your own machine. Claude chat runs them in<br />
  its own workspace, so this section does not apply there.
</p>

<table align="center">
  <thead>
    <tr>
      <th align="center">Needed</th>
      <th align="center">How to get it</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td align="center"><strong>Python 3.9 or newer</strong></td>
      <td align="center"><a href="https://www.python.org/downloads/">python.org</a></td>
    </tr>
    <tr>
      <td align="center"><strong>ffmpeg, full build</strong></td>
      <td align="center">Windows: <code>winget install Gyan.FFmpeg</code></td>
    </tr>
    <tr>
      <td align="center"><strong>Python packages</strong></td>
      <td align="center"><code>pip install opencv-python numpy yt-dlp faster-whisper</code></td>
    </tr>
    <tr>
      <td align="center"><strong>Visual C++ runtime (Windows only)</strong></td>
      <td align="center">Needed for turning speech into text</td>
    </tr>
  </tbody>
</table>

<p><em>Not sure what you have? Claude checks on first use and tells you what to install. You can also run <code>python scripts/check_setup.py</code> yourself.</em></p>

<hr />

<h2>What is in this repository</h2>

<table align="center">
  <thead>
    <tr>
      <th align="center">Path</th>
      <th align="center">What it is</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td align="center"><code>SKILL.md</code></td>
      <td align="center">The instructions Claude follows</td>
    </tr>
    <tr>
      <td align="center"><code>references/</code></td>
      <td align="center">A guide for each kind of video, plus a guide to editing</td>
    </tr>
    <tr>
      <td align="center"><code>commands/</code></td>
      <td align="center">The name and description of each command</td>
    </tr>
    <tr>
      <td align="center"><code>scripts/</code></td>
      <td align="center">The tools that download, transcribe, analyse, track and render</td>
    </tr>
    <tr>
      <td align="center"><code>assets/</code></td>
      <td align="center">Fonts, face-detection models and a Windows download helper</td>
    </tr>
    <tr>
      <td align="center"><code>tools/build.py</code></td>
      <td align="center">Builds the zip files and installs the skill</td>
    </tr>
    <tr>
      <td align="center"><code>tools/selftest.py</code></td>
      <td align="center">Checks the whole skill without rendering any video</td>
    </tr>
  </tbody>
</table>

<hr />

<h2>Good to know</h2>

<p>Speaker tracking is an estimate based on mouth movement. It can pick the wrong person, so look at the preview.</p>

<p>For kill feeds and scoreboards, ClipForge detects that something changed. Claude then reads the frame to see what.</p>

<p>The edits follow what editors usually do. They make a clip look finished. Nobody can promise views.</p>

<hr />

<h2>Credits and licence</h2>

<p>Created by <a href="https://github.com/lowdevco">lowdevco</a></p>

<p>Released under the <a href="LICENSE">MIT License</a>, copyright &copy; 2026 lowdevco.</p>

<p>
  <small>
    Some bundled files keep their own licences: the Poppins, Anton and Noto Sans<br />
    Malayalam fonts (SIL Open Font License, texts in <code>assets/fonts/</code>), the YuNet<br />
    face-detection models from OpenCV Zoo (MIT), and OpenCV's Haar cascade (its<br />
    licence is stated inside the file).
  </small>
</p>

</div>
```

## File: scripts/analyze_audio.py
size: 3378
sha: 8a808ced53dc01c2212306d3f7ac337b0a2d8691
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/scripts/analyze_audio.py

```text
#!/usr/bin/env python3
"""Find the loud, exciting moments in a video's audio (shouts, laughter,
explosions, crowd noise). This is the main signal for gameplay, where the
best moments are often not in the words at all.

Usage: python analyze_audio.py VIDEO --out WORKDIR [--top 25]

Writes WORKDIR/audio_peaks.json and prints a table:
  time | lift (dB above the surrounding minute) | how long the burst lasts
"""
import argparse
import json
import os
import subprocess

import numpy as np

SR = 8000
WIN = 0.5

def ts(t):
    t = int(t)
    return f"{t // 3600}:{t % 3600 // 60:02d}:{t % 60:02d}" if t >= 3600 \
        else f"{t // 60:02d}:{t % 60:02d}"

def loudness(video):
    """Return (db, lift, seconds): loudness per 0.5 s window, and how far each
    window rises above the median of the minute around it."""
    raw = subprocess.run(
        ["ffmpeg", "-loglevel", "error", "-i", video, "-vn", "-ac", "1",
         "-ar", str(SR), "-f", "s16le", "-"],
        capture_output=True, check=True).stdout
    pcm = np.frombuffer(raw, dtype=np.int16).astype(np.float32) / 32768
    n = int(SR * WIN)
    frames = pcm[:len(pcm) // n * n].reshape(-1, n)
    db = 20 * np.log10(np.sqrt((frames ** 2).mean(axis=1)) + 1e-6)

    # Smooth to 1.5 s, then compare with the median of the surrounding minute.
    k = 3
    smooth = np.convolve(db, np.ones(k) / k, mode="same")
    half = int(30 / WIN)
    base = np.array([np.median(smooth[max(0, i - half):i + half + 1])
                     for i in range(len(smooth))])
    return db, smooth - base, len(pcm) / SR

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("video")
    ap.add_argument("--out", required=True)
    ap.add_argument("--top", type=int, default=25)
    ap.add_argument("--min-gap", type=float, default=20,
                    help="seconds between reported peaks")
    args = ap.parse_args()
    os.makedirs(args.out, exist_ok=True)

    db, lift, seconds = loudness(args.video)

    order = np.argsort(-lift)
    peaks, gap = [], int(args.min_gap / WIN)
    for i in order:
        if lift[i] < 4:
            break
        if any(abs(i - p) < gap for p in peaks):
            continue
        peaks.append(int(i))
        if len(peaks) >= args.top:
            break

    rows = []
    for i in sorted(peaks):
        a = b = i
        while a > 0 and lift[a - 1] > lift[i] / 2:
            a -= 1
        while b < len(lift) - 1 and lift[b + 1] > lift[i] / 2:
            b += 1
        rows.append({"t": round(i * WIN, 1), "time": ts(i * WIN),
                     "lift_db": round(float(lift[i]), 1),
                     "burst_start": round(a * WIN, 1),
                     "burst_end": round((b + 1) * WIN, 1)})

    quiet = float(np.percentile(db, 10))
    result = {"duration": round(seconds, 1),
              "median_db": round(float(np.median(db)), 1),
              "quiet_floor_db": round(quiet, 1), "peaks": rows}
    with open(os.path.join(args.out, "audio_peaks.json"), "w") as fh:
        json.dump(result, fh, indent=1)

    print(f"duration {ts(result['duration'])}, {len(rows)} peaks "
          f"(strongest first is NOT the order below; sorted by time)")
    print("time     lift_dB  burst")
    for r in rows:
        print(f"{r['time']:>8} {r['lift_db']:>7}  "
              f"{ts(r['burst_start'])}-{ts(r['burst_end'])}")

if __name__ == "__main__":
    main()
```

## File: scripts/check_setup.py
size: 5552
sha: a58ac32adacdf6cfc9fa4e10c4c8b45ffc180b20
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/scripts/check_setup.py

```text
#!/usr/bin/env python3
"""Report what this machine can do, as JSON. Run this first.

Usage: python check_setup.py
"""
import importlib.util
import json
import os
import platform
import shutil
import subprocess
import sys
import urllib.request

def has_module(name):
    return importlib.util.find_spec(name) is not None

def loads(name):
    """Really import the module in a child process. A package can be installed
    and still fail to load (missing DLL), which find_spec does not notice.
    Returns (ok, last line of the error)."""
    if not has_module(name):
        return False, "not installed"
    try:
        res = subprocess.run([sys.executable, "-c", f"import {name}"],
                             capture_output=True, text=True, timeout=120)
    except Exception as exc:  # noqa: BLE001
        return False, repr(exc)
    if res.returncode == 0:
        return True, None
    tail = (res.stderr.strip().splitlines() or ["import failed"])[-1]
    return False, tail[:300]

def reachable(url):
    try:
        req = urllib.request.Request(url, method="HEAD",
                                     headers={"User-Agent": "Mozilla/5.0"})
        urllib.request.urlopen(req, timeout=8)
        return True
    except Exception as exc:  # noqa: BLE001
        code = getattr(exc, "code", None)
        # 4xx/5xx from the site itself still means the network path is open,
        # but a proxy refusal shows up as a tunnel/URL error with no code.
        return code is not None and code not in (403, 407)

def ffmpeg_filters():
    try:
        out = subprocess.run(["ffmpeg", "-hide_banner", "-filters"],
                             capture_output=True, text=True, timeout=20).stdout
    except Exception:  # noqa: BLE001
        return []
    return [f for f in ("ass", "loudnorm", "boxblur") if f" {f} " in out]

def main():
    fw_ok, fw_err = loads("faster_whisper")
    so_ok, so_err = loads("sherpa_onnx")
    info = {
        "os": platform.system(),
        "python": sys.version.split()[0],
        "ffmpeg": bool(shutil.which("ffmpeg")),
        "ffprobe": bool(shutil.which("ffprobe")),
        "ffmpeg_filters": ffmpeg_filters(),
        "yt_dlp": bool(shutil.which("yt-dlp")) or has_module("yt_dlp"),
        "opencv": has_module("cv2"),
        "numpy": has_module("numpy"),
        "faster_whisper": fw_ok,
        "sherpa_onnx": so_ok,
        "speech_to_text": fw_ok or so_ok,
        "js_runtime": bool(shutil.which("deno") or shutil.which("node")),
        "youtube_reachable": reachable("https://www.youtube.com/"),
        "huggingface_reachable": reachable("https://huggingface.co/"),
        "github_reachable": reachable("https://github.com/"),
    }
    info["mode"] = "local" if info["youtube_reachable"] else "cloud"
    # yunet = good face tracking; haar = basic; none = no speaker framing
    info["face_detector"] = "none"
    if info["opencv"]:
        try:
            res = subprocess.run(
                [sys.executable, "-c", "import faces; print(faces.kind())"],
                capture_output=True, text=True, timeout=120,
                cwd=os.path.dirname(os.path.abspath(__file__)))
            info["face_detector"] = (res.stdout.strip().splitlines() or ["none"])[-1]
        except Exception:  # noqa: BLE001
            pass

    todo = []
    pip = f"{sys.executable} -m pip install"
    if platform.system() == "Linux":
        pip += " --break-system-packages"
    if not info["ffmpeg"] or not info["ffprobe"]:
        todo.append("Install ffmpeg (Windows: winget install Gyan.FFmpeg ; "
                    "macOS: brew install ffmpeg ; Linux: apt install ffmpeg)")
    elif "ass" not in info["ffmpeg_filters"]:
        todo.append("This ffmpeg has no libass (no burned captions). "
                    "Install a full build (Windows: winget install Gyan.FFmpeg).")
    if not info["opencv"] or not info["numpy"]:
        todo.append(f"{pip} opencv-python-headless numpy")
    if info["youtube_reachable"] and not info["yt_dlp"]:
        todo.append(f"{pip} -U yt-dlp")
    errors = {k: v for k, v in (("faster_whisper", fw_err), ("sherpa_onnx", so_err))
              if v and v != "not installed"}
    if errors:
        info["speech_to_text_errors"] = errors
    if not info["speech_to_text"] and errors:
        if platform.system() == "Windows":
            todo.append("Speech-to-text is installed but cannot load (missing "
                        "Windows runtime). Run: winget install -e --id "
                        "Microsoft.VCRedist.2015+.x64   then check again.")
        else:
            todo.append("Speech-to-text is installed but cannot load; see "
                        f"speech_to_text_errors. Try: {pip} --force-reinstall "
                        "faster-whisper")
    elif not info["speech_to_text"]:
        if info["huggingface_reachable"]:
            todo.append(f"{pip} faster-whisper   (speech-to-text, best quality)")
        elif info["github_reachable"]:
            todo.append(f"{pip} sherpa-onnx   (speech-to-text that works without "
                        "Hugging Face access)")
    if info["youtube_reachable"] and info["yt_dlp"] and not info["js_runtime"]:
        info["note"] = ("yt-dlp has no JavaScript runtime, so some YouTube "
                        "formats may be missing. Downloads usually still work; "
                        "if one fails, install Deno (Windows: winget install "
                        "DenoLand.Deno).")
    info["todo"] = todo
    print(json.dumps(info, indent=2))

if __name__ == "__main__":
    main()
```

## File: scripts/faces.py
size: 3440
sha: 4c2effa42e24ca2966a776d4a68d50c26080773d
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/scripts/faces.py

```text
#!/usr/bin/env python3
"""Face detection shared by render.py and track.py.

Uses YuNet (assets/face_detection_yunet_*.onnx, from OpenCV Zoo, MIT
licence) when this OpenCV build has cv2.FaceDetectorYN, and falls back to the
older Haar cascade otherwise. YuNet copes with side-on faces, glasses and
small faces far better, and also gives the mouth position.
"""
import os

HERE = os.path.dirname(os.path.abspath(__file__))
ASSETS = os.path.join(HERE, "..", "assets")
YUNET = os.path.join(ASSETS, "face_detection_yunet_2023mar.onnx")
YUNET_2026 = os.path.join(ASSETS, "face_detection_yunet_2026may.onnx")

_state = {"kind": None, "det": None}

def _load():
    if _state["kind"] is not None:
        return
    import cv2
    # OpenCV 5 prefers the 2026 export (dynamic input size); OpenCV 4 needs
    # the 2023 one. Try the better match first, then the other.
    models = [YUNET_2026, YUNET] if cv2.__version__.startswith("5") \
        else [YUNET, YUNET_2026]
    for model in models:
        if not (hasattr(cv2, "FaceDetectorYN") and os.path.exists(model)):
            continue
        try:
            _state["det"] = cv2.FaceDetectorYN.create(model, "", (320, 320),
                                                      0.6, 0.3, 50)
            _state["kind"] = "yunet"
            return
        except Exception:  # noqa: BLE001
            pass
    for xml in (os.path.join(getattr(getattr(cv2, "data", None), "haarcascades", ""),
                             "haarcascade_frontalface_default.xml"),
                os.path.join(ASSETS, "haarcascade_frontalface_default.xml")):
        if os.path.exists(xml):
            c = cv2.CascadeClassifier(xml)
            if not c.empty():
                _state["det"], _state["kind"] = c, "haar"
                return
    _state["kind"] = "none"

def kind():
    _load()
    return _state["kind"]

def detect(frame, max_w=640):
    """Faces in one BGR frame, largest first. Each is a dict in source pixels:
    x, y, w, h, score, mouth (x, y) and eyes (x, y); mouth and eyes are
    estimated from the box when the detector does not give landmarks."""
    import cv2
    _load()
    if _state["kind"] == "none":
        return []
    H, W = frame.shape[:2]
    scale = min(max_w / W, 1.0)
    img = cv2.resize(frame, (int(W * scale), int(H * scale))) if scale < 1 else frame
    out = []
    if _state["kind"] == "yunet":
        det = _state["det"]
        det.setInputSize((img.shape[1], img.shape[0]))
        _, found = det.detect(img)
        for r in (found if found is not None else []):
            x, y, w, h = (float(v) / scale for v in r[:4])
            pts = [float(v) / scale for v in r[4:14]]
            out.append({"x": x, "y": y, "w": w, "h": h, "score": float(r[14]),
                        "eyes": ((pts[0] + pts[2]) / 2, (pts[1] + pts[3]) / 2),
                        "mouth": ((pts[6] + pts[8]) / 2, (pts[7] + pts[9]) / 2)})
    else:
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        for (x, y, w, h) in _state["det"].detectMultiScale(gray, 1.1, 6,
                                                            minSize=(36, 36)):
            x, y, w, h = (float(v) / scale for v in (x, y, w, h))
            out.append({"x": x, "y": y, "w": w, "h": h, "score": 0.5,
                        "eyes": (x + w / 2, y + h * 0.38),
                        "mouth": (x + w / 2, y + h * 0.78)})
    out.sort(key=lambda f: -f["w"] * f["h"])
    return out
```

## File: scripts/fetch.py
size: 3148
sha: a2fad009ae2286894a9b6cb9a10ddaae90dd148a
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/scripts/fetch.py

```text
#!/usr/bin/env python3
"""Download a YouTube video (mp4) plus its subtitles with yt-dlp.

Usage:
  python fetch.py URL --out WORKDIR [--max-height 1080] [--section 600-1500]

Prints JSON: {"video": path, "subs": [paths], "title", "duration", "channel"}.
Only works where YouTube is reachable (see check_setup.py -> "mode": "local").
"""
import argparse
import glob
import json
import os
import shutil
import subprocess
import sys

def ytdlp_cmd():
    exe = shutil.which("yt-dlp")
    if exe:
        return [exe]
    try:
        import yt_dlp  # noqa: F401
        return [sys.executable, "-m", "yt_dlp"]
    except ImportError:
        sys.exit("yt-dlp is not installed. Run: python -m pip install -U yt-dlp")

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("url")
    ap.add_argument("--out", required=True)
    ap.add_argument("--max-height", type=int, default=1080)
    ap.add_argument("--section", help="only download START-END, in seconds "
                    "or hh:mm:ss, e.g. 600-1500")
    ap.add_argument("--langs", default="en.*,ml.*",
                    help="subtitle languages to try (yt-dlp --sub-langs)")
    args = ap.parse_args()

    os.makedirs(args.out, exist_ok=True)
    h = args.max_height
    cmd = ytdlp_cmd() + [
        "--no-playlist", "--restrict-filenames",
        "-f", f"bv*[height<={h}]+ba/b[height<={h}]/b",
        "-S", "vcodec:h264,res,acodec:m4a",
        "--merge-output-format", "mp4",
        "--write-subs", "--write-auto-subs",
        "--sub-langs", args.langs + ",-live_chat",
        "--sub-format", "json3/vtt/best",
        "--write-info-json",
        "-o", os.path.join(args.out, "%(id)s.%(ext)s"),
    ]
    if args.section:
        cmd += ["--download-sections", f"*{args.section}"]
    cmd.append(args.url)

    proc = subprocess.run(cmd)
    videos = sorted(glob.glob(os.path.join(args.out, "*.mp4")),
                    key=os.path.getmtime)
    if not videos:
        # Subtitle errors (HTTP 429) can abort the run; retry video only.
        retry = [c for c in cmd if c not in ("--write-subs", "--write-auto-subs")]
        proc = subprocess.run(retry)
        videos = sorted(glob.glob(os.path.join(args.out, "*.mp4")),
                        key=os.path.getmtime)
    if not videos:
        sys.exit(f"Download failed (yt-dlp exit code {proc.returncode}). "
                 "If the error mentions sign-in or bot checks, update yt-dlp "
                 "(python -m pip install -U yt-dlp) and try again.")

    video = videos[-1]
    stem = os.path.splitext(video)[0]
    subs = sorted(glob.glob(stem + ".*.json3") + glob.glob(stem + ".*.vtt")
                  + glob.glob(stem + ".*.srt"))
    meta = {}
    info_path = stem + ".info.json"
    if os.path.exists(info_path):
        with open(info_path, encoding="utf-8") as fh:
            info = json.load(fh)
        meta = {k: info.get(k) for k in ("title", "duration", "channel",
                                         "language", "webpage_url")}
    print(json.dumps({"video": video, "subs": subs, **meta}, indent=2,
                     ensure_ascii=False))

if __name__ == "__main__":
    main()
```

## File: scripts/peek.py
size: 3965
sha: bfbee4017105141db284b7ca9780f772d8f98d37
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/scripts/peek.py

```text
#!/usr/bin/env python3
"""Save a contact sheet of frames so you can LOOK at moments before choosing
them (is something actually happening? is there a facecam, and where?).

Usage:
  python peek.py VIDEO --at 75,312.5,1040 --out WORKDIR/peek.jpg [--grid]
  python peek.py VIDEO --range 998-1032 --n 8 --out WORKDIR/strip.jpg

  python peek.py VIDEO --at 600,640 --crop 1500,40,400,200 --out WORKDIR/hud.jpg

--range takes N evenly spaced frames from START-END (seconds): a filmstrip
that shows how one moment plays out from start to finish.
--crop shows only one region of the frame, enlarged, so small on-screen text
(a scoreboard, a kill feed, a timer) can be read.
--grid draws 10% guide lines with pixel labels on each frame; use it to read
off a facecam box [x, y, w, h] in source pixels for the "split" layout.
"""
import argparse

import cv2
import numpy as np

def spread(start, end, n):
    """N times evenly spaced inside start-end, away from the very edges."""
    n = max(int(n), 1)
    return [start + (end - start) * (i + 0.5) / n for i in range(n)]

def make_sheet(video, times, out, grid=False, cols=3, tile_w=None, crop=None):
    cap = cv2.VideoCapture(video)
    tiles = []
    for t in times:
        cap.set(cv2.CAP_PROP_POS_MSEC, t * 1000)
        ok, frame = cap.read()
        if not ok:
            continue
        if crop:
            x, y, w, h = crop
            frame = frame[y:y + h, x:x + w]
            if frame.size == 0:
                continue
        H, W = frame.shape[:2]
        if grid:
            for i in range(1, 10):
                x, y = W * i // 10, H * i // 10
                cv2.line(frame, (x, 0), (x, H), (0, 255, 255), 2)
                cv2.line(frame, (0, y), (W, y), (0, 255, 255), 2)
                cv2.putText(frame, str(x), (x + 4, 28), 0, 0.9, (0, 0, 0), 5)
                cv2.putText(frame, str(x), (x + 4, 28), 0, 0.9, (0, 255, 255), 2)
                cv2.putText(frame, str(y), (4, y - 6), 0, 0.9, (0, 0, 0), 5)
                cv2.putText(frame, str(y), (4, y - 6), 0, 0.9, (0, 255, 255), 2)
        tw = tile_w or (960 if grid else 640)
        tile = cv2.resize(frame, (tw, int(H * tw / W)))
        label = f"{int(t) // 60:02d}:{t % 60:04.1f}  ({W}x{H})"
        cv2.putText(tile, label, (10, tile.shape[0] - 14), 0, 0.8, (0, 0, 0), 5)
        cv2.putText(tile, label, (10, tile.shape[0] - 14), 0, 0.8,
                    (255, 255, 255), 2)
        tiles.append(tile)
    cap.release()
    if not tiles:
        return None
    cols = 1 if grid else min(cols, len(tiles))
    blank = np.zeros_like(tiles[0])
    while len(tiles) % cols:
        tiles.append(blank)
    rows = [np.hstack(tiles[i:i + cols]) for i in range(0, len(tiles), cols)]
    cv2.imwrite(out, np.vstack(rows), [cv2.IMWRITE_JPEG_QUALITY, 82])
    return out

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("video")
    ap.add_argument("--at", help="comma-separated seconds")
    ap.add_argument("--range", dest="span", help="START-END in seconds")
    ap.add_argument("--n", type=int, default=8, help="frames for --range")
    ap.add_argument("--out", required=True)
    ap.add_argument("--grid", action="store_true")
    ap.add_argument("--cols", type=int)
    ap.add_argument("--crop", help="x,y,w,h in source pixels: show only this "
                    "region, enlarged (read a scoreboard, kill feed or HUD)")
    args = ap.parse_args()
    crop = [int(v) for v in args.crop.split(",")] if args.crop else None

    if args.span:
        a, b = (float(x) for x in args.span.split("-", 1))
        times, cols = spread(a, b, args.n), args.cols or 4
    elif args.at:
        times, cols = [float(x) for x in args.at.split(",")], args.cols or 3
    else:
        raise SystemExit("give --at or --range")
    if not make_sheet(args.video, times, args.out, args.grid, cols, crop=crop):
        raise SystemExit("no frames could be read")
    print(args.out)

if __name__ == "__main__":
    main()
```

## File: scripts/render.py
size: 35773
sha: a8c150a87bfe42832dd339fc80be08e31a1a5e80
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/scripts/render.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/lowdevco/clip-forge/blob/HEAD/scripts/render.py

## File: scripts/scout.py
size: 8649
sha: 8456a3829d121c368d9d3cfaa573addf39807911
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/scripts/scout.py

```text
#!/usr/bin/env python3
"""Rank the stretches of a video where the most is happening, and save a
filmstrip of each so you can look at them. Built for gameplay and other
videos where the best moments are in the action, not the words.

Usage: python scout.py VIDEO --out WORKDIR [--top 12] [--len 30]
                       [--kind action|sports] [--roi x,y,w,h]

--roi names the part of the frame that holds the kill feed or the scoreboard
(read the box off `peek.py --grid`). Changes there are counted as events and
raise the rank of the windows that contain them.
--kind sports ranks by sustained crowd and commentator noise first.

For every window of --len seconds it measures
  loud    how far the sound rises above its surroundings (shouts, gunfire,
          explosions, laughter)
  motion  how much the picture changes (fights, chases, fast cuts)
and ranks the windows by the two together. The "action" score (0-100) is a
rank inside this one video: it says where to look first, not how good the
moment is. Judge the moment from the filmstrip.

Writes WORKDIR/scout.json and WORKDIR/scout/NN.jpg (8 frames per window, in
order), plus WORKDIR/scout/end.jpg for the last 45 seconds, because results
screens, wins and fails usually sit at the very end.
"""
import argparse
import json
import os
import subprocess

import numpy as np

from analyze_audio import WIN, loudness, ts
from peek import make_sheet, spread

FPS = 4            # frames per second sampled for motion
MW, MH = 160, 90   # motion is measured on a tiny grey copy

def motion(video):
    """Mean absolute change between sampled frames, one value per 0.5 s."""
    proc = subprocess.Popen(
        ["ffmpeg", "-loglevel", "error", "-i", video, "-an",
         "-vf", f"fps={FPS},scale={MW}:{MH},format=gray", "-f", "rawvideo", "-"],
        stdout=subprocess.PIPE)
    vals, prev, size = [], None, MW * MH
    while True:
        buf = proc.stdout.read(size)
        if len(buf) < size:
            break
        frame = np.frombuffer(buf, dtype=np.uint8).astype(np.int16)
        vals.append(0.0 if prev is None else float(np.abs(frame - prev).mean()))
        prev = frame
    proc.wait()
    vals = np.array(vals, dtype=np.float32)
    if not len(vals):
        return vals
    # A hard cut changes every pixel once; cap it so cuts do not outweigh
    # sustained movement.
    vals = np.minimum(vals, np.percentile(vals, 95))
    per = int(FPS * WIN)
    return vals[:len(vals) // per * per].reshape(-1, per).mean(axis=1)

def roi_changes(video, roi):
    """Times (seconds) when one region of the frame changes: a new line in a
    kill feed, a scoreboard ticking over, a banner appearing. This is what
    highlight tools for games and sport rely on most."""
    x, y, w, h = roi
    sw = min(w, 160) // 2 * 2
    sh = max(int(h * sw / w) // 2 * 2, 2)
    proc = subprocess.Popen(
        ["ffmpeg", "-loglevel", "error", "-i", video, "-an",
         "-vf", f"fps=2,crop={w}:{h}:{x}:{y},scale={sw}:{sh},format=gray",
         "-f", "rawvideo", "-"], stdout=subprocess.PIPE)
    diffs, prev, size = [], None, sw * sh
    while True:
        buf = proc.stdout.read(size)
        if len(buf) < size:
            break
        frame = np.frombuffer(buf, dtype=np.uint8).astype(np.int16)
        diffs.append(0.0 if prev is None else float(np.abs(frame - prev).mean()))
        prev = frame
    proc.wait()
    d = np.array(diffs, dtype=np.float32)
    if len(d) < 4:
        return []
    med = float(np.median(d))
    thr = max(med + 4 * float(np.median(np.abs(d - med))), med * 2, 4.0)
    times = []
    for i in np.where(d > thr)[0]:
        t = i / 2
        if not times or t - times[-1] >= 2.0:
            times.append(float(t))
    return times

def zscore(x):
    sd = float(x.std())
    return (x - x.mean()) / sd if sd > 1e-6 else np.zeros_like(x)

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("video")
    ap.add_argument("--out", required=True)
    ap.add_argument("--top", type=int, default=12)
    ap.add_argument("--len", dest="length", type=float, default=30,
                    help="window length in seconds")
    ap.add_argument("--kind", choices=("action", "sports"), default="action",
                    help="sports weighs sustained crowd and commentator noise "
                         "above picture motion")
    ap.add_argument("--roi", help="x,y,w,h in source pixels of the kill feed "
                    "or scoreboard; changes there count as events")
    ap.add_argument("--no-strips", action="store_true")
    args = ap.parse_args()
    os.makedirs(args.out, exist_ok=True)
    roi = [int(v) for v in args.roi.split(",")] if args.roi else None

    db, lift, seconds = loudness(args.video)
    mot = motion(args.video)
    n = min(len(db), len(mot)) if len(mot) else len(db)
    db, lift = db[:n], lift[:n]
    mot = mot[:n] if len(mot) else np.zeros(n, dtype=np.float32)

    win = max(int(args.length / WIN), 4)
    if n <= win:
        raise SystemExit("video is shorter than one window; lower --len")
    step = int(2 / WIN)
    above = np.maximum(lift, 0)                  # rises above the local minute
    hot = np.maximum(db - np.median(db), 0)      # louder than the whole video
    starts = np.arange(0, n - win + 1, step)
    a = np.array([above[s:s + win].mean() for s in starts])
    h = np.array([hot[s:s + win].mean() for s in starts])
    m = np.array([mot[s:s + win].mean() for s in starts])
    wa, wh, wm = (0.25, 0.55, 0.20) if args.kind == "sports" else (0.35, 0.25, 0.40)
    score = wa * zscore(a) + wh * zscore(h) + wm * zscore(m)
    events = roi_changes(args.video, roi) if roi else []
    ev = np.zeros(n, dtype=np.float32)
    for t in events:
        if int(t / WIN) < n:
            ev[int(t / WIN)] += 1
    r = np.array([ev[s:s + win].sum() for s in starts])
    if roi and r.max() > 0:
        score = 0.65 * score + 0.35 * zscore(r)
    rank = score.argsort().argsort() / max(len(score) - 1, 1) * 100
    m_rank = m.argsort().argsort() / max(len(m) - 1, 1) * 100
    a_rank = (a + h).argsort().argsort() / max(len(a) - 1, 1) * 100

    picked = []
    for i in np.argsort(-score):
        s = int(starts[i])
        if any(abs(s - p) < win + int(4 / WIN) for p in picked):
            continue
        picked.append(s)
        if len(picked) >= args.top:
            break

    strips = os.path.join(args.out, "scout")
    if not args.no_strips:
        os.makedirs(strips, exist_ok=True)
    index = {int(s): i for i, s in enumerate(starts)}
    rows = []
    for num, s in enumerate(sorted(picked, key=lambda p: -score[index[p]]), 1):
        i = index[s]
        t0, t1 = s * WIN, (s + win) * WIN
        peak = (s + int(np.argmax(lift[s:s + win]))) * WIN
        row = {"n": num, "start": round(t0, 1), "end": round(t1, 1),
               "window": f"{ts(t0)}-{ts(t1)}", "action": int(round(rank[i])),
               "loud": int(round(a_rank[i])), "motion": int(round(m_rank[i])),
               "loudest_at": ts(peak), "loudest_t": round(peak, 1)}
        if roi:
            row["roi_events"] = [round(t, 1) for t in events if t0 <= t < t1]
        if not args.no_strips:
            path = os.path.join(strips, f"{num:02d}.jpg")
            if make_sheet(args.video, spread(t0, t1, 8), path, cols=4,
                          tile_w=480):
                row["strip"] = path
        rows.append(row)

    result = {"duration": round(seconds, 1), "window_seconds": args.length,
              "kind": args.kind, "windows": rows}
    if roi:
        result["roi"] = roi
        result["roi_events"] = [round(t, 1) for t in events]
    if not args.no_strips and seconds > 50:
        end = os.path.join(strips, "end.jpg")
        if make_sheet(args.video, spread(seconds - 45, seconds - 1, 8), end,
                      cols=4, tile_w=480):
            result["ending_strip"] = end
    with open(os.path.join(args.out, "scout.json"), "w", encoding="utf-8") as fh:
        json.dump(result, fh, indent=1)

    print(f"duration {ts(seconds)}, {len(rows)} windows of {args.length:g}s, "
          "strongest first")
    print(" #  window        action  loud  motion  loudest at"
          + ("  region changes" if roi else ""))
    for r in rows:
        print(f"{r['n']:>2}  {r['window']:<12} {r['action']:>6} {r['loud']:>5} "
              f"{r['motion']:>7}  {r['loudest_at']}"
              + (f"       {len(r['roi_events'])}" if roi else ""))
    if roi:
        print(f"region {roi}: {len(events)} changes in the whole video")
    if not args.no_strips:
        print(f"filmstrips: {strips} (NN.jpg per window, end.jpg = last 45 s)")

if __name__ == "__main__":
    main()
```

## File: scripts/sfx.py
size: 2355
sha: 4f05c669a7c33bf5d6b185b3821a884fff40f137
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/scripts/sfx.py

```text
#!/usr/bin/env python3
"""Make the small sound effects the renderer mixes in. They are synthesised
here, so the skill ships no audio files and has no licensing questions.

  boom    low thump for an impact or a punch-in zoom
  whoosh  airy sweep for a title or a transition
  pop     short blip for a callout

Usage: python sfx.py OUTDIR   (writes boom.wav, whoosh.wav, pop.wav)
"""
import os
import sys
import wave

import numpy as np

SR = 48000

def _save(path, x):
    x = np.tanh(np.asarray(x, dtype=np.float64) * 1.2)      # soft clip
    x = x / (np.abs(x).max() + 1e-9) * 0.89
    pcm = (x * 32767).astype("<i2")
    with wave.open(path, "wb") as w:
        w.setnchannels(1)
        w.setsampwidth(2)
        w.setframerate(SR)
        w.writeframes(pcm.tobytes())

def _band_noise(n, lo, hi, rng):
    spec = np.fft.rfft(rng.standard_normal(n))
    freq = np.fft.rfftfreq(n, 1 / SR)
    spec[(freq < lo) | (freq > hi)] = 0
    out = np.fft.irfft(spec, n)
    return out / (np.abs(out).max() + 1e-9)

def boom():
    n = int(SR * 0.75)
    t = np.arange(n) / SR
    freq = 38 + 62 * np.exp(-t * 14)                 # 100 Hz falling to 38 Hz
    body = np.sin(2 * np.pi * np.cumsum(freq) / SR) * np.exp(-t * 5.5)
    rng = np.random.default_rng(7)
    click = _band_noise(n, 80, 900, rng) * np.exp(-t * 70) * 0.5
    fade = np.minimum(1, (n - np.arange(n)) / (SR * 0.05))
    return (body + click) * fade

def whoosh():
    n = int(SR * 0.6)
    t = np.arange(n) / SR
    rng = np.random.default_rng(11)
    air = _band_noise(n, 500, 7000, rng)
    low = _band_noise(n, 150, 900, rng)
    peak = 0.62                                       # swell, then fall away
    env = np.where(t / 0.6 < peak, (t / 0.6 / peak) ** 2.2,
                   ((1 - t / 0.6) / (1 - peak)) ** 1.6)
    return (air * 0.8 + low * 0.5) * env

def pop():
    n = int(SR * 0.09)
    t = np.arange(n) / SR
    freq = 520 + 600 * np.exp(-t * 60)
    return np.sin(2 * np.pi * np.cumsum(freq) / SR) * np.exp(-t * 45)

def write_all(outdir):
    os.makedirs(outdir, exist_ok=True)
    paths = {}
    for name, fn in (("boom", boom), ("whoosh", whoosh), ("pop", pop)):
        paths[name] = os.path.join(outdir, f"{name}.wav")
        _save(paths[name], fn())
    return paths

if __name__ == "__main__":
    print(write_all(sys.argv[1] if len(sys.argv) > 1 else "."))
```

## File: scripts/track.py
size: 12542
sha: 152528f41da580b8933f134e58b927b398ea27f8
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/scripts/track.py

```text
#!/usr/bin/env python3
"""Find the people in each clip and who is speaking when, so the renderer can
frame them: follow the active speaker, or stack two speakers.

Usage: python track.py VIDEO --clips WORKDIR/clips.json [--only 1,3] [--write]

For each clip it
  1. finds the camera cuts, so every shot is handled on its own (a position
     from before a cut means nothing after it);
  2. detects faces (YuNet) about six times a second and groups them into
     people by position within the shot;
  3. scores how much each person's mouth area moves compared with the rest
     of their face while there is sound, and takes the one whose mouth moves
     most as the speaker.

Prints one JSON line per clip:
  shots       each shot's time span and the people in it: face centre
              (cx, cy as 0-1), size, and share of the talking in that shot
  suggest     speaker | stack | blur, with the reason
  focus_path  [[source seconds, cx], ...] crop positions: a new one at every
              camera cut and whenever the speaker changes
  no_face     share of the clip where no face was found

--write stores "focus_path" and, where it applies, "faces" back into
clips.json, and sets the layout where it is "auto" or missing.

This is a heuristic, not a trained active-speaker model. It is usually right
for people facing the camera, and can be fooled by laughing, eating, a hand
near the mouth, or an off-screen voice. Render with --preview and look at a
few frames before trusting it on a new show.
"""
import argparse
import json
import subprocess
import sys

import cv2
import numpy as np

import faces as facelib

SAMPLE_HZ = 6
MIN_TURN = 1.5          # seconds a speaker must hold before the crop moves

def audio_activity(video, start, dur, times):
    """For each sample time: is there sound above the clip's quiet floor?"""
    raw = subprocess.run(
        ["ffmpeg", "-loglevel", "error", "-ss", f"{start:.3f}", "-t", f"{dur:.3f}",
         "-i", video, "-vn", "-ac", "1", "-ar", "8000", "-f", "s16le", "-"],
        capture_output=True).stdout
    pcm = np.frombuffer(raw, dtype=np.int16).astype(np.float32) / 32768
    n = 1600                                      # 0.2 s windows
    if len(pcm) < n * 5:
        return np.ones(len(times), dtype=bool)
    fr = pcm[:len(pcm) // n * n].reshape(-1, n)
    db = 20 * np.log10(np.sqrt((fr ** 2).mean(axis=1)) + 1e-6)
    loud = db > np.percentile(db, 15) + 8
    idx = np.clip(((np.array(times) - start) / 0.2).astype(int), 0, len(loud) - 1)
    return loud[idx]

def region(gray, cx, cy, w, h):
    H, W = gray.shape
    x0, x1 = int(max(cx - w / 2, 0)), int(min(cx + w / 2, W))
    y0, y1 = int(max(cy - h / 2, 0)), int(min(cy + h / 2, H))
    if x1 - x0 < 6 or y1 - y0 < 6:
        return None
    return cv2.resize(gray[y0:y1, x0:x1], (32, 20)).astype(np.float32)

def scan(video, start, end):
    """Read the clip once. Returns (samples, cuts): samples are
    (time, shot number, [face dicts with cx, cy, h, motion]); cuts are the
    times a new shot begins."""
    cap = cv2.VideoCapture(video)
    fps = cap.get(cv2.CAP_PROP_FPS) or 30
    step = max(int(round(fps / SAMPLE_HZ)), 3)
    cap.set(cv2.CAP_PROP_POS_MSEC, start * 1000)
    samples, cuts, recent = [], [start], []
    shot, k, held, prev_small, since_cut = 0, 0, None, None, 0
    while True:
        ok, frame = cap.read()
        t = start + k / fps
        if not ok or t > end:
            break
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        small = cv2.resize(gray, (64, 36)).astype(np.float32)
        if prev_small is not None:
            d = float(np.abs(small - prev_small).mean())
            base = float(np.median(recent)) if recent else 1.0
            # A cut changes the whole picture at once, far beyond the motion
            # of the frames before it.
            if d > 9 and d > 5 * max(base, 0.8) and since_cut > fps * 0.4:
                shot += 1
                cuts.append(round(t, 3))
                held, since_cut = None, 0
            recent = (recent + [d])[-20:]
        prev_small = small
        since_cut += 1
        phase = k % step
        if phase == 0:
            H, W = gray.shape
            held = (t, gray, [f for f in facelib.detect(frame, max_w=960)[:5]
                              if f["h"] / H >= 0.05], shot)
        elif phase == 2 and held is not None and held[3] == shot:
            t0, g0, found, _ = held
            H, W = g0.shape
            row = []
            for f in found:
                mx, my = f["mouth"]
                ex, ey = f["eyes"]
                m0 = region(g0, mx, my + f["h"] * 0.06, f["w"] * 0.55, f["h"] * 0.34)
                m1 = region(gray, mx, my + f["h"] * 0.06, f["w"] * 0.55, f["h"] * 0.34)
                e0 = region(g0, ex, ey, f["w"] * 0.7, f["h"] * 0.25)
                e1 = region(gray, ex, ey, f["w"] * 0.7, f["h"] * 0.25)
                motion = 0.0
                if not (m0 is None or m1 is None or e0 is None or e1 is None):
                    # Mouth movement beyond what the whole head is doing.
                    motion = float(max(np.abs(m1 - m0).mean()
                                       - np.abs(e1 - e0).mean(), 0))
                row.append({"cx": (f["x"] + f["w"] / 2) / W,
                            "cy": (f["y"] + f["h"] / 2) / H,
                            "h": f["h"] / H, "motion": motion})
            samples.append((t0, shot, row))
            held = None
        k += 1
    cap.release()
    return samples, cuts

def track_shot(rows, active):
    """rows: [(t, faces)] of one shot. Returns (people, speaker index per
    sample or -1). People are grouped by horizontal position."""
    people = []
    assign = []
    for _, found in rows:
        mine = {}
        for f in found:
            for i, p in enumerate(people):
                if abs(np.median(p["cx"][-30:]) - f["cx"]) < 0.10:
                    break
            else:
                people.append({"cx": [], "cy": [], "h": []})
                i = len(people) - 1
            if i in mine:
                continue
            p = people[i]
            p["cx"].append(f["cx"])
            p["cy"].append(f["cy"])
            p["h"].append(f["h"])
            mine[i] = f["motion"]
        assign.append(mine)
    n = len(rows)
    keep = [i for i, p in enumerate(people) if len(p["cx"]) >= max(2, n * 0.2)]
    if not keep:
        return [], [-1] * n
    motion = np.zeros((len(keep), n), dtype=np.float32)
    seen = np.zeros((len(keep), n), dtype=bool)
    for j, mine in enumerate(assign):
        for a, i in enumerate(keep):
            if i in mine:
                motion[a, j], seen[a, j] = mine[i], True
    w = max(int(SAMPLE_HZ * 0.9), 1)
    kern = np.ones(w) / w
    smooth = np.array([np.convolve(motion[a], kern, mode="same")
                       for a in range(len(keep))])
    speaker, cur = [], int(np.argmax(seen.sum(axis=1)))
    for j in range(n):
        if active[j] and smooth[:, j].max() > 0:
            best = int(np.argmax(smooth[:, j]))
            if smooth[best, j] > smooth[cur, j] * 1.3:
                cur = best
        speaker.append(cur)
    min_run = int(SAMPLE_HZ * MIN_TURN)
    j = 0
    while j < n:                                   # drop very short turns
        e = j
        while e < n and speaker[e] == speaker[j]:
            e += 1
        if e - j < min_run and j > 0:
            speaker[j:e] = [speaker[j - 1]] * (e - j)
        elif e - j < min_run and e < n:
            # A blip at the start of the shot: open on whoever speaks next,
            # so the crop does not jump a moment after the cut.
            speaker[j:e] = [speaker[e]] * (e - j)
            continue
        j = e
    act = np.array(active, dtype=bool)
    talk = np.bincount(np.array(speaker)[act], minlength=len(keep)) \
        if act.any() else np.zeros(len(keep))
    share = talk / max(talk.sum(), 1)
    out = [{"cx": round(float(np.median(people[i]["cx"])), 3),
            "cy": round(float(np.median(people[i]["cy"])), 3),
            "h": round(float(np.median(people[i]["h"])), 3),
            "talk_share": round(float(share[a]), 2)}
           for a, i in enumerate(keep)]
    return out, speaker

def summarise(video, clip):
    start, end = float(clip["start"]), float(clip["end"])
    samples, cuts = scan(video, start, end)
    if not samples:
        return {"id": clip.get("id"), "shots": [], "focus_path": [],
                "suggest": "blur", "why": "clip could not be read"}
    times = [s[0] for s in samples]
    active = audio_activity(video, start, end - start, times)
    counts = np.array([len(s[2]) for s in samples])
    shots, path = [], []
    bounds = cuts + [end]
    for sid in range(len(cuts)):
        idx = [j for j, s in enumerate(samples) if s[1] == sid]
        t0, t1 = bounds[sid], bounds[sid + 1]
        if not idx:
            # Too short to sample: keep the framing of the shot before.
            continue
        rows = [(samples[j][0], samples[j][2]) for j in idx]
        people, speaker = track_shot(rows, [bool(active[j]) for j in idx])
        shots.append({"start": round(t0, 2), "end": round(t1, 2), "people": people})
        if not people:
            path.append([round(t0, 2), 0.5])       # nobody found: centre
            continue
        last = None
        for (t, _), sp in zip(rows, speaker):
            if sp != last:
                path.append([round(t0 if last is None else t, 2),
                             people[sp]["cx"]])
                last = sp
    path = path[:60]

    dur = max(end - start, 0.1)
    no_face = float((counts == 0).mean())
    together = float((counts >= 2).mean())
    crowd = float((counts >= 3).mean())
    longest = max(shots, key=lambda s: s["end"] - s["start"]) if shots else None
    faces = None
    if no_face > 0.5:
        suggest, why = "blur", "no face found in most of the clip"
    elif together < 0.25:
        suggest, why = "speaker", ("one person on screen at a time; the path "
                                   "follows them through the camera cuts")
    elif crowd >= 0.25:
        suggest, why = "speaker", ("three or more people share the shot; stack "
                                   "shows only two, so the path cuts between them")
    elif longest and len(longest["people"]) == 2 and \
            (longest["end"] - longest["start"]) / dur >= 0.7:
        two = sorted(longest["people"], key=lambda p: p["cx"])
        faces = [[p["cx"], p["cy"]] for p in two]
        if min(p["talk_share"] for p in two) >= 0.25 or \
                sum(p["talk_share"] for p in two) == 0:
            suggest, why = "stack", "two people share one steady shot and both talk"
        else:
            suggest, why = "speaker", "two people share the shot, one does the talking"
    else:
        suggest, why = "speaker", ("two people share some shots, and the camera "
                                   "cuts too often for a steady stack")
    return {"id": clip.get("id"), "suggest": suggest, "why": why,
            "detector": facelib.kind(), "cuts": len(cuts) - 1,
            "no_face": round(no_face, 2), "shots": shots, "faces": faces,
            "focus_path": path}

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("video")
    ap.add_argument("--clips", required=True)
    ap.add_argument("--only", help="comma-separated clip ids")
    ap.add_argument("--write", action="store_true",
                    help="store the results back into clips.json")
    args = ap.parse_args()
    if facelib.kind() == "none":
        sys.exit("no face detector available (OpenCV model files missing)")
    with open(args.clips, encoding="utf-8") as fh:
        data = json.load(fh)
    wanted = {int(x) for x in args.only.split(",")} if args.only else None
    for clip in data["clips"]:
        if wanted and int(clip.get("id", 0)) not in wanted:
            continue
        r = summarise(args.video, clip)
        print(json.dumps(r, ensure_ascii=False), flush=True)
        if args.write:
            clip.pop("faces", None)
            if r["focus_path"]:
                clip["focus_path"] = r["focus_path"]
                clip["focus_mode"] = "cut"
            if r.get("faces"):
                clip["faces"] = r["faces"]
            if clip.get("layout", "auto") == "auto":
                clip["layout"] = r["suggest"]
    if args.write:
        with open(args.clips, "w", encoding="utf-8") as fh:
            json.dump(data, fh, indent=1, ensure_ascii=False)

if __name__ == "__main__":
    main()
```

## File: scripts/transcribe.py
size: 12067
sha: 65a26c8238a4fb2a00a461e9b07121ea5d286af4
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/scripts/transcribe.py

```text
#!/usr/bin/env python3
"""Build a word-timed transcript for a video.

Usage:
  python transcribe.py VIDEO --out WORKDIR [--subs FILE] [--lang en|ml|auto]
                       [--engine auto|subs|faster-whisper|sherpa] [--model small]

Order tried in "auto": subtitle file (--subs, or one sitting next to the video)
-> faster-whisper -> sherpa-onnx (models come from GitHub, so it also works
where Hugging Face is blocked).

Writes WORKDIR/transcript.json  {"language","source","words":[{"s","e","w"}],
                                 "segments":[{"start","end","text"}]}
and    WORKDIR/transcript.txt   compact "[mm:ss] text" lines for reading.
Exit code 3 means no transcript could be made (use audio-only mode).
"""
import argparse
import glob
import html
import json
import os
import re
import subprocess
import sys
import tarfile
import urllib.request

CACHE = os.path.join(os.path.expanduser("~"), ".cache", "clip-forge")
GH = "https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/"

# ---------- helpers ----------------------------------------------------------
def spread_words(text, start, end):
    """Give each word in a timed line a share of its time, by length."""
    toks = text.split()
    if not toks or end <= start:
        return []
    total = sum(len(t) + 1 for t in toks)
    out, t = [], start
    for tok in toks:
        d = (end - start) * (len(tok) + 1) / total
        out.append({"s": round(t, 3), "e": round(t + d, 3), "w": tok})
        t += d
    return out

def words_to_segments(words, max_len=9.0, gap=0.8):
    segs, cur = [], []
    for w in words:
        if cur and (w["s"] - cur[-1]["e"] > gap
                    or w["e"] - cur[0]["s"] > max_len
                    or cur[-1]["w"][-1:] in ".?!"):
            segs.append(cur)
            cur = []
        cur.append(w)
    if cur:
        segs.append(cur)
    return [{"start": s[0]["s"], "end": s[-1]["e"],
             "text": " ".join(x["w"] for x in s)} for s in segs]

def ts(t):
    t = int(t)
    return f"{t // 3600}:{t % 3600 // 60:02d}:{t % 60:02d}" if t >= 3600 \
        else f"{t // 60:02d}:{t % 60:02d}"

# ---------- subtitle parsers -------------------------------------------------
def parse_json3(path):
    with open(path, encoding="utf-8") as fh:
        data = json.load(fh)
    words = []
    for ev in data.get("events", []):
        segs = [s for s in ev.get("segs", []) if s.get("utf8", "").strip()]
        if not segs:
            continue
        t0 = ev.get("tStartMs", 0) / 1000
        t1 = t0 + ev.get("dDurationMs", 0) / 1000
        timed = len(segs) > 1 or "tOffsetMs" in segs[0]
        if timed:  # auto captions: one seg per word, each with its own offset
            starts = [t0 + s.get("tOffsetMs", 0) / 1000 for s in segs]
            for i, s in enumerate(segs):
                end = starts[i + 1] if i + 1 < len(segs) else min(t1, starts[i] + 1.2)
                words += spread_words(s["utf8"].strip(), starts[i],
                                      max(end, starts[i] + 0.05))
        else:
            words += spread_words(segs[0]["utf8"].replace("\n", " "), t0, t1)
    return words

TIME = re.compile(r"(?:(\d+):)?(\d{1,2}):(\d{2})[.,](\d{3})")

def _sec(m):
    return int(m.group(1) or 0) * 3600 + int(m.group(2)) * 60 + int(m.group(3)) \
        + int(m.group(4)) / 1000

def parse_vtt_srt(path):
    with open(path, encoding="utf-8-sig") as fh:
        blocks = re.split(r"\n\s*\n", fh.read().replace("\r", ""))
    words, last_text = [], None
    for block in blocks:
        lines = [ln for ln in block.split("\n") if ln.strip()]
        idx = next((i for i, ln in enumerate(lines) if "-->" in ln), None)
        if idx is None:
            continue
        times = list(TIME.finditer(lines[idx]))
        if len(times) < 2:
            continue
        start, end = _sec(times[0]), _sec(times[1])
        text = " ".join(lines[idx + 1:])
        text = html.unescape(re.sub(r"<[^>]+>", "", text)).strip()
        # YouTube auto .vtt repeats the previous line in each rolling cue.
        if last_text and text.startswith(last_text):
            text = text[len(last_text):].strip()
        elif text == last_text:
            text = ""
        if text:
            words += spread_words(text, start, end)
            last_text = " ".join(lines[idx + 1:]).strip()
            last_text = html.unescape(re.sub(r"<[^>]+>", "", last_text))
    return words

def find_subs(video, lang):
    stem = os.path.splitext(video)[0]
    found = glob.glob(stem + ".*.json3") + glob.glob(stem + ".*.vtt") \
        + glob.glob(stem + ".*.srt") + glob.glob(stem + ".srt") \
        + glob.glob(stem + ".vtt")
    if not found:
        return None

    def rank(p):
        name = os.path.basename(p).lower()
        code = name[len(os.path.basename(stem)) + 1:].split(".")[0]
        score = 0
        if lang not in ("auto", None) and code.startswith(lang):
            score -= 10
        if code.endswith("-orig"):
            score -= 5          # original-language auto captions
        if name.endswith(".json3"):
            score -= 2          # carries per-word timing
        score += len(code)      # prefer "en" over "en-xx-yy" translations
        return score
    return sorted(found, key=rank)[0]

def from_subs(path):
    words = parse_json3(path) if path.endswith(".json3") else parse_vtt_srt(path)
    return words, f"subtitles:{os.path.basename(path)}"

# ---------- speech-to-text engines ------------------------------------------
def extract_wav(video, out):
    wav = os.path.join(out, "audio16k.wav")
    if not os.path.exists(wav):
        subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-i", video,
                        "-vn", "-ac", "1", "-ar", "16000", wav], check=True)
    return wav

def with_faster_whisper(video, out, lang, model):
    from faster_whisper import WhisperModel
    wav = extract_wav(video, out)
    wm = WhisperModel(model, device="auto", compute_type="auto")
    segments, info = wm.transcribe(
        wav, language=None if lang == "auto" else lang,
        word_timestamps=True, vad_filter=True)
    words = []
    for seg in segments:
        for w in seg.words or []:
            if w.word.strip():
                words.append({"s": round(w.start, 3), "e": round(w.end, 3),
                              "w": w.word.strip()})
        print(f"  ...{ts(seg.end)}", end="\r", file=sys.stderr)
    return words, f"faster-whisper:{model}", info.language

def _download(url, dest):
    os.makedirs(os.path.dirname(dest), exist_ok=True)
    if not os.path.exists(dest):
        print(f"downloading {os.path.basename(dest)} ...", file=sys.stderr)
        urllib.request.urlretrieve(url, dest + ".part")
        os.replace(dest + ".part", dest)
    return dest

def with_sherpa(video, out, lang, model):
    import wave

    import numpy as np
    import sherpa_onnx

    name = f"sherpa-onnx-whisper-{model}"
    mdir = os.path.join(CACHE, name)
    if not os.path.isdir(mdir):
        tar = _download(GH + name + ".tar.bz2",
                        os.path.join(CACHE, name + ".tar.bz2"))
        with tarfile.open(tar) as tf:
            try:
                tf.extractall(CACHE, filter="data")
            except TypeError:  # Python < 3.12
                tf.extractall(CACHE)
        os.remove(tar)
    vad_path = _download(GH + "silero_vad.onnx",
                         os.path.join(CACHE, "silero_vad.onnx"))
    rec = sherpa_onnx.OfflineRecognizer.from_whisper(
        encoder=os.path.join(mdir, f"{model}-encoder.int8.onnx"),
        decoder=os.path.join(mdir, f"{model}-decoder.int8.onnx"),
        tokens=os.path.join(mdir, f"{model}-tokens.txt"),
        language="" if lang == "auto" else lang, task="transcribe",
        num_threads=max(1, (os.cpu_count() or 2)))
    cfg = sherpa_onnx.VadModelConfig()
    cfg.silero_vad.model = vad_path
    cfg.silero_vad.min_silence_duration = 0.25
    cfg.silero_vad.max_speech_duration = 12
    cfg.sample_rate = 16000
    vad = sherpa_onnx.VoiceActivityDetector(cfg, buffer_size_in_seconds=60)

    wav = extract_wav(video, out)
    words = []

    def drain():
        while not vad.empty():
            seg = vad.front
            start = seg.start / 16000
            samples = np.array(seg.samples, dtype=np.float32)
            vad.pop()
            stream = rec.create_stream()
            stream.accept_waveform(16000, samples)
            rec.decode_stream(stream)
            text = stream.result.text.strip()
            if text:
                words.extend(spread_words(text, start,
                                          start + len(samples) / 16000))
            print(f"  ...{ts(start)}", end="\r", file=sys.stderr)

    win = cfg.silero_vad.window_size
    with wave.open(wav) as wf:
        while True:
            raw = wf.readframes(win * 200)
            if not raw:
                break
            pcm = np.frombuffer(raw, dtype=np.int16).astype(np.float32) / 32768
            for i in range(0, len(pcm) - win + 1, win):
                vad.accept_waveform(pcm[i:i + win])
            drain()
    vad.flush()
    drain()
    return words, f"sherpa-whisper:{model}", lang

# ---------- main -------------------------------------------------------------
def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("video")
    ap.add_argument("--out", required=True)
    ap.add_argument("--subs")
    ap.add_argument("--lang", default="auto")
    ap.add_argument("--engine", default="auto",
                    choices=["auto", "subs", "faster-whisper", "sherpa"])
    ap.add_argument("--model", default="small",
                    help="whisper size: tiny, base, small, medium (bigger = "
                         "slower and more accurate; use small+ for Malayalam)")
    args = ap.parse_args()
    os.makedirs(args.out, exist_ok=True)

    words, source, language = [], None, args.lang
    errors = []
    if args.engine in ("auto", "subs"):
        subs = args.subs or find_subs(args.video, args.lang)
        if subs:
            words, source = from_subs(subs)
    if not words and args.engine in ("auto", "faster-whisper"):
        try:
            words, source, language = with_faster_whisper(
                args.video, args.out, args.lang, args.model)
        except Exception as exc:  # noqa: BLE001
            errors.append(f"faster-whisper: {exc!r}")
    if not words and args.engine in ("auto", "sherpa"):
        try:
            words, source, language = with_sherpa(
                args.video, args.out, args.lang, args.model)
        except Exception as exc:  # noqa: BLE001
            errors.append(f"sherpa-onnx: {exc!r}")

    if not words:
        print(json.dumps({"ok": False, "errors": errors,
                          "hint": "No subtitles and no working speech-to-text "
                                  "engine. Continue in audio-only mode, or "
                                  "install an engine (see check_setup.py)."},
                         indent=2))
        sys.exit(3)

    words.sort(key=lambda w: w["s"])
    segments = words_to_segments(words)
    if any("ഀ" <= ch <= "ൿ" for w in words[:400] for ch in w["w"]):
        language = "ml"
    with open(os.path.join(args.out, "transcript.json"), "w",
              encoding="utf-8") as fh:
        json.dump({"language": language, "source": source, "words": words,
                   "segments": segments}, fh, ensure_ascii=False)
    with open(os.path.join(args.out, "transcript.txt"), "w",
              encoding="utf-8") as fh:
        for seg in segments:
            fh.write(f"[{ts(seg['start'])}] {seg['text']}\n")
    print(json.dumps({"ok": True, "source": source, "language": language,
                      "words": len(words), "segments": len(segments),
                      "exact_word_timing": "json3" in (source or "")
                      or "faster-whisper" in (source or ""),
                      "transcript_txt": os.path.join(args.out, "transcript.txt")},
                     indent=2))

if __name__ == "__main__":
    main()
```

## File: references/edit.md
size: 2183
sha: c5bb4df0fec3ffdee709efb26d02d5766cffeb7e
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/references/edit.md

```text
# Edit mode

The user already has the clip (or knows the exact times) and wants the
edit: `/clip-edit <file or link> [what they want]`. There is no search for
moments and no scored table.

## Steps

1. Get the video as in step 2 of the main instructions. A short file the
   user attached is used as it is.
2. Work out the span:
   - A finished short clip: the whole file is the clip (`start` 0, `end` =
     its length).
   - Times given ("from 12:30 to 13:05"): use them.
   - A long video and no times: ask which part, or offer to switch to one
     of the finding modes.
3. Look at it: `peek.py --range <start>-<end> --n 12`. Note what kind of
   footage it is, where the subject sits, whether anyone talks, and where
   the key moment falls.
4. If someone talks, run `transcribe.py` for captions. If there are people
   in a wide shot, run `track.py`.
5. Read `references/editing.md` and write `clips.json` with a real edit
   plan: layout, edit preset, hook with `*accent*` words, beats on the
   moments you saw, a callout or two where the picture supports it.
6. If the source is already vertical (9:16), use `"layout": "center"`; it
   passes through at full frame.
7. Say in two or three lines what you plan (edit, layout, beats, headline),
   then render. A plan the user can read in ten seconds does not need an
   approval stop unless they asked for one. Use `--preview` first when the
   framing is a guess.
8. Check frames, hand over the file, and offer changes: another edit
   preset, different beats, a new headline, a caption style.

## Reading what the user asked for

| They say | Do |
|---|---|
| "make it pop", "hype", "like a gaming montage" | `"edit": "hype"`, style `fire` or `neon` |
| "clean", "professional", "for LinkedIn" | `"edit": "clean"`, style `clean`, no outro |
| "podcast style", "like the big podcast clips" | `"edit": "story"`, `stack` or `speaker` via `track.py`, style `bold` |
| "just captions" | `"edit": "clean"`, `"grade": "none"`, no hook |
| "no captions", "no text" | `"captions": false`, omit `hook` |
| "slow-mo on the …" | a `slowmo` beat at that moment |
| "add my handle" | `--watermark "@theirs"` (ask for it if not given) |
```

## File: references/editing.md
size: 6068
sha: 927c321eeb2d15f750cb92cfd6f1cc061d1c76db
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/references/editing.md

````text
# Editing: making a clip look made, not cut

A raw cut with a label on top reads as low effort. What separates a clip an
experienced editor made is a handful of deliberate choices: the frame is
full, the colour has punch, the picture moves on the moments that matter, the
sound backs those moments up, and the text is designed and timed. `render.py`
does the mechanics; your job is the choices. Read this before writing
`clips.json`.

## Pick the edit

`"edit"` on a clip (or `--edit` for all) sets the whole treatment:

| Edit | Use for | What it does |
|---|---|---|
| `hype` | Gameplay, sports, anything fast | Vivid grade, slow push-in, punch + shake + flash with a bass thump on each beat, condensed all-caps headline, progress bar |
| `premium` | General video, calmer gameplay | Punchy grade, slow push-in, punch-in with a soft thump on each beat, bold headline |
| `story` | Podcasts, interviews, talking head | Soft grade, zoom cuts on sentence changes, animated captions, a whoosh under the headline |
| `clean` | Business, tutorials, serious topics | Soft grade and animated text only; no zooms, no sound effects |
| `raw` | When the user wants it untouched | Plain cut, boxed headline, static captions |

Default is `premium`. If the user names a look ("hype edit", "keep it
clean"), that settles it.

## Beats: where the picture reacts

A beat is a moment the edit should land on: the shot, the goal, the
punchline, the reveal. On a beat the picture punches in (and in `hype`,
shakes and flashes) with a thump underneath.

- `"beats": "auto"` (the default in `hype` and `premium`) finds the hardest
  jumps in the sound: at most one per ~7 s, none under the headline. Good
  enough for most action clips.
- When you can see or read the exact moment, say so. It is always better
  than auto:

```json
"beats": ["auto",
  {"t": 1028.2, "fx": ["flash", "punch"], "text": "#1 Winner"},
  {"t": 771.5, "fx": "slowmo", "len": 1.2}]
```

`t` is in source-video seconds, like `start` and `end`. `"auto"` inside the
list keeps the found beats and adds yours.

| fx | Effect | Use it for |
|---|---|---|
| `punch` | Quick zoom in that settles back | Any hit, kill, goal, punchline |
| `shake` | Short camera shake | Explosions, heavy impacts, a clutch |
| `flash` | Brief white flash | A result screen, a cut to the payoff |
| `slowmo` | Half speed for `len` seconds | The one best moment of the clip, once |

`"text"` on a beat pops a callout word on screen for about a second
("CLUTCH", "1 HP", "GOAL"). Rules for callouts:

- Only what the frames or the transcript show. Never invent a kill count.
- One to three words. At most two or three callouts per clip.
- Slow motion at most once per clip, on the payoff. More than that reads as
  padding.

Restraint matters. Three well-placed beats in 30 seconds feel edited; ten
feel like a filter.

## Headline

The `hook` is the headline for the first 3.5 seconds.

- 3–8 words. Put `*stars*` around the one or two words that carry it; they
  take the accent colour: `"He quit a *40 lakh* job"`.
- It must be true to the clip. Curiosity, not a lie.
- `"hook_hold": true` keeps it up for the whole clip. Use that with the
  `blur` layout, where the band above the picture would otherwise sit empty.
- `stack` layout: keep the hook to one short line; it sits over the top
  speaker.

## Captions

- Talk needs captions; most viewers watch without sound at first. Gameplay
  with no voice needs none (`"captions": false`).
- Styles: `bold` (default), `clean` (calm content), `neon` and `fire`
  (gameplay, hype).
- The transcript is the caption. If a name or term is wrong, fix it in
  `transcript.json` and re-render with `--only`.

## Framing

Fill the screen. A small picture floating in blur is the clearest sign of a
low-effort clip.

- `center` or `speaker` first. `blur` only when the edges really matter, and
  then with `"zoom": 1.6` or more and `"hook_hold": true`.
- Two people in one wide shot: run `track.py`, then `stack` (both on screen)
  or `speaker` with the `focus_path` it writes (cuts to whoever is talking).
- Check a frame of every clip. A cropped-off face or a caption over the
  action undoes everything else.

## Closing and branding

- `"outro": "Follow for more"` (or `--outro`) pops a tag over the last
  1.6 s. Skip it when the clip ends on a strong line or image; let that be
  the ending.
- `--watermark "@name"` adds a small, see-through channel tag. Ask for the
  handle once; never invent one.
- `--progress` shows a thin bar along the top (on by default in `hype`).
- End the clip on the payoff. Check the last two seconds with
  `peek.py --range`: source videos often end with the creator's own end
  card, and a clip that runs into it looks careless.

## Where text can go

The apps cover parts of the frame with their own buttons and captions. The
renderer keeps its text inside the free area, roughly x 60–890 and
y 290–1250 of the 1080x1920 frame (the bottom third and the right edge
belong to the app). Nothing to do unless you override positions: just know
that the lower third of the picture will be partly hidden, so the subject
should not live there.

## What is evidence and what is craft

Be straight with the user if they ask what "works":

- Supported by platform guidance: state the point within the first 3
  seconds, use captions or on-screen text, use sound, keep it vertical and
  sharp. Clips of roughly 20–35 s are a safe default length.
- Craft, not proof: how often to zoom, which sound effect, loop endings.
  These follow editing convention. They make a clip feel finished; nobody
  can promise they raise views.

## After the render

1. Look at a frame from the headline, from one beat, and from the last
   second of each clip.
2. If a `--preview` pass would have caught it (framing, a callout at the
   wrong time), use `--preview` next time before the full render.
3. If the session has an `effects` skill and the clip is a talking head,
   offer it as an extra step on the finished file. It is a separate skill;
   do not assume it is installed.
````

## File: references/gameplay.md
size: 3783
sha: f21b5ffc4237748638698b2f77956dfbcfc7fd2b
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/references/gameplay.md

````text
# Gameplay mode

The moment is in the action and the reaction, not in a transcript. A good
gameplay Short shows a situation, then something happens: a multi-kill, a
clutch, a fail, a win screen, a jump scare.

## Find the moments

1. Look at one mid-game frame with a grid:
   `peek.py <video> --at <t> --grid --out <workdir>/grid.jpg`. Note where
   the kill feed (or score, or event log) sits and whether there is a
   facecam. Read the kill-feed box as `x,y,w,h` in source pixels.
2. Run scout, with the kill-feed box if the game has one:

   ```
   python scripts/scout.py <video> --out <workdir> --roi x,y,w,h
   ```

   It ranks the busiest stretches by sound and motion and saves a filmstrip
   of each in `<workdir>/scout/`. With `--roi`, every change in the kill
   feed counts as an event: windows with several are multi-kills and
   fights, and the exact times are in `scout.json` under `roi_events`.
3. Open every filmstrip, and `end.jpg`. Read them like a comic strip:
   - **Keep** stretches where the frames show a fight, a chase, a result
     screen, or a kill feed filling up.
   - **Drop** menus, loading screens, the lobby, looting, long drives, and
     stretches that are loud only because of music.
   - **The ending** almost always holds the win or the death. If `end.jpg`
     shows a result screen, the last fight before it is a candidate even if
     scout ranked it low.
4. Read what the game tells you on screen: the kill feed and kill counter,
   the health bar (low health = tension), the players-alive counter, banners
   such as "double kill" or "winner". `peek.py --crop x,y,w,h` enlarges a
   region so small text is readable. Use these for the hook, the callouts
   and the score, and only claim what the frames show.
5. For each stretch you keep, set exact times. Begin 8–20 s before the peak
   so the viewer sees the situation, and end 2–4 s after the result lands.
   Check the last seconds with `peek.py --range`: do not run into the
   creator's own end card or a menu.
6. `analyze_audio.py` helps when the video has a commentator or streamer:
   its peaks are their shouts and laughs. In a video that is gunfire from
   start to finish it adds little; trust scout and the frames.

## Facecam and commentary

- **Facecam?** If yes, get its box from the grid frame for the `split`
  layout.
- **Does anyone talk?** If there is a streamer or commentator, run
  `transcribe.py` and use captions. If the sound is only the game and music,
  skip transcription and set `"captions": false` on every clip.

## Framing

| Situation | Layout |
|---|---|
| Facecam present | `split` with the `facecam` box: face on top, game below |
| No facecam, action in the middle (most shooters, racing) | `center`. Fills the whole screen, which is what gameplay Shorts need |
| Action off to one side | `center` with `"focus_x"` (0.3 = left of middle, 0.7 = right) |
| The edges are the story (a scoreboard, a minimap) | `blur` with `"zoom": 1.6–2.0` and `"hook_hold": true` |

Default to `center`. A small picture floating in blur looks low-effort on a
phone.

## Edit

Read `references/editing.md`. For gameplay:

- `"edit": "hype"`, caption style `fire` or `neon`.
- Leave `"beats"` unset for automatic beats on the loudest hits, or give
  your own where you can see the exact moment. Add `"auto"` to the list to
  keep both.
- Callouts from what the screen shows: "SQUAD WIPE", "1 HP", "#1 WINNER".
- `slowmo` once, on the best kill or the winning moment.
- `"tighten": false` always. A quiet second before the action is the
  tension.
- Hooks are short and concrete: "1 HP. *Four enemies.*", "Last circle,
  *no cover*", "He never saw the *grenade*".

## Post copy

Name the game in the first hashtag. Titles state what happens, not how
amazing it is.
````

## File: references/podcast.md
size: 4358
sha: e245e0e6239e358ac80bf7d2e4e2c01af7d4bf6e
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/references/podcast.md

````text
# Podcast mode

Podcasts, interviews and talking-head videos. The moment is in the words, so
the transcript is the main tool and it is required. If `check_setup.py` shows
`speech_to_text: false` and the video has no subtitles, stop and tell the
user what to install; do not fall back to guessing from audio.

## Find the moments

1. Run `transcribe.py`, then read `<workdir>/transcript.txt` in full.
2. Look for passages that work with zero context:
   - a bold or contrarian claim
   - a number that surprises
   - a confession or a story with a turn
   - a clear how-to in three steps or fewer
   - a punchline
3. Start the clip on the sentence that hooks, not on the question that led
   to it. End on the payoff, not a trailing "so yeah". A clip that needs the
   host's question to make sense should include it only if it is short.
4. Run `analyze_audio.py` as a second opinion: its peaks are laughter and
   raised voices. A passage you liked that also has a peak is a strong
   candidate; a peak with no good passage around it is not one.
5. Snap `start` and `end` to word boundaries from `transcript.json` so a clip
   never opens or closes mid-word. Leave 0.15 s of air on each side.

## Framing: follow the speaker

After the user approves clips and you have written `clips.json` (with
`"layout": "auto"`), run the tracker:

```
python scripts/track.py <video> --clips <workdir>/clips.json --write
```

For each clip it finds the camera cuts, tracks the people inside each shot,
estimates who is talking when, and writes back a suggested layout and a
`focus_path`: a crop position for every shot and every change of speaker.
Read its output (`cuts`, `no_face`, and the people in each shot):

| It reports | Layout to use |
|---|---|
| One person on screen at a time (single camera, or an edit that cuts between cameras) | `speaker`. The path keeps the crop on them through camera changes |
| Two people in one steady shot, both talk in the clip | `stack`: both on screen, one above the other, captions on the seam. The safest choice for a conversation |
| Two people in one shot, one does the talking | `speaker` with the path: the crop sits on the talker and cuts across when the other answers |
| Three or more people in a wide shot | `speaker` with the path. `stack` shows only two people, so it would drop someone |
| No faces (screen share, slides) | `blur` with `"zoom": 1.0–1.3` |

The tracker is a heuristic: it compares mouth movement between faces. It is
usually right for people facing the camera and can be fooled by laughter,
eating, or a voice from off screen. Before the full render, run
`render.py --preview` and look at eight to ten frames spread across each
clip, not just the start: an empty frame (bare wall, half a chair) means the
crop is pointing at nobody. If the crop is wrong in a steady two-person
shot, switch that clip to `stack`, which needs no guess about who is
talking.

Two more things to read off its output:

- **`cuts`** – if the source already cuts between cameras every few seconds
  (say more than one cut per five seconds), it has its own rhythm. Set
  `"zoomcuts": false` on the clip so the `story` edit does not add zoom
  changes on top.
- **What sits above the faces** – the headline's default spot is the top of
  the frame. If something that matters is there (a prop, a name card, a
  picture on a headband), move the headline with `"hook_y"`, for example
  `940` to place it on the chest above the captions.

## Edit

Read `references/editing.md`. For talk:

- `"edit": "story"`: zoom cuts on sentence changes give a single-camera
  shot the rhythm of a multi-camera edit. Use `clean` for serious or
  business content.
- `"tighten": true`: removes silences longer than 0.7 s.
- Captions on, always. Style `bold`; `clean` for calm content.
- Beats are optional in talk. One `punch` on the punchline or the key
  number, with a callout of that number, is plenty.
- Hook line in the speaker's language, with `*stars*` on the key words. For
  Malayalam, write the hook in Malayalam script and tell the user the
  captions need a read-through.
- If the captions show a wrong name or term, fix the words in
  `transcript.json` for that time range and re-render with `--only`.

## Post copy

The title is the claim in the clip, rephrased. Tag the guest's name and the
topic rather than generic tags.
````

## File: references/sports.md
size: 3314
sha: 6fcbf0faeb6d730f23ba72c45cc7879a1dbb640b
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/references/sports.md

````text
# Sports mode

Match footage and broadcasts: football, cricket, basketball, esports
broadcasts with a caster, fights, racing. The moment is a scoring play, a
save, a wicket, a knockout, a finish. Two signals find almost all of them:
the crowd and commentator getting loud and staying loud, and the scoreboard
changing.

## Find the moments

1. Look at one frame with a grid to locate the scoreboard:
   `peek.py <video> --at <a time during play> --grid --out <workdir>/grid.jpg`.
   Read its box as `x,y,w,h` in source pixels. Skip this if there is no
   on-screen score.
2. Run scout in sports mode, with the scoreboard box if you have one:

   ```
   python scripts/scout.py <video> --out <workdir> --kind sports --len 40 --roi x,y,w,h
   ```

   `--kind sports` ranks by sustained loudness (a roar lasts; a whistle does
   not). `region changes` counts how often the scoreboard changed in each
   window, and `scout.json` lists every change time under `roi_events`.
3. A scoreboard change means something happened shortly **before** it:
   usually 5–25 s earlier, since graphics update after the play. For each
   change, look back with `peek.py --range <t-30>-<t+5> --n 10`.
4. Read the score before and after to know what happened:
   `peek.py <video> --at <before>,<after> --crop x,y,w,h --out <workdir>/score.jpg`.
   Use the real score in the hook and the callout.
5. Open the scout filmstrips for the loud windows with no score change:
   near misses, saves, fouls and celebrations live there.
6. Broadcasts replay the best moments. If a filmstrip shows the same play
   twice, cut the clip from the live play and stop before the replay, or
   use the replay angle on its own if it shows the play better.
7. Run `transcribe.py` only if the commentary is worth captioning. For most
   sports clips the picture and a headline are enough; captions of fast
   commentary clutter the frame.

## Timing

- Start with the build-up: 6–12 s before the scoring moment, at the pass,
  run-up or delivery that begins it.
- End on the celebration or the reaction, 3–5 s after, before the replay.
- 15–35 s is typical.

## Framing

| Shot | Layout |
|---|---|
| Wide broadcast camera, play moves across the field | `blur` with `"zoom": 1.6–1.9` and `"hook_hold": true`. A tight crop would lose the ball |
| Play stays in one area (penalty, free throw, a wicket, a ring) | `center`, with `"focus_x"` on the area |
| Play moves steadily one way and you can see where | `center` with a `"focus_path"` of two or three points and `"focus_mode": "pan"` |
| Close-up reaction or celebration | `center` or `speaker` |

For a `focus_path`, read the subject's position off a filmstrip: 0 is the
left edge of the source frame, 1 the right edge. A few points are enough;
do not try to track the ball frame by frame.

## Edit

- `"edit": "hype"`.
- One beat on the scoring moment with `["punch", "flash"]` and a callout
  with the real result: "GOAL", "2–1", "OUT", "KO".
- `slowmo` once, on the moment of contact, if the picture is clear enough.
- Hooks state the stakes: "90th minute. *One chance.*", "Needs *6 off 1*".

## Rights

Broadcast sport is almost always owned by a league or broadcaster and is
taken down quickly. Say this once if the footage is clearly a broadcast,
then carry on with what the user asked.
````

## File: references/tutorial.md
size: 2435
sha: e158be54a748d6ee58e156c229ef7e4c17d728af
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/references/tutorial.md

```text
# Tutorial mode

How-to and educational videos: coding, software walkthroughs, lessons,
explainers, cooking, repairs, reviews with a clear lesson. The clip that
works is **one idea, complete**: a single tip, fix or result that a viewer
can use without seeing the rest.

## Find the moments

1. Run `transcribe.py` and read `transcript.txt` in full. The transcript is
   required here; if it cannot be made, say what to install.
2. Mark every passage that is a complete unit:
   - one tip or shortcut, stated and shown
   - a mistake and its fix
   - a before and after
   - a surprising fact with its reason
   - a result worth showing first ("this is what we are building")
3. Drop passages that depend on earlier steps ("as we saw", "now go back to
   the file we made"), and setup with no payoff.
4. Lead with the result. If the passage builds up to something visible,
   start the clip a few seconds before the result appears, or pick the
   sentence that states the benefit ("this one setting halves your build
   time") as the opening line.
5. Check what is on screen with `peek.py --range`: the words and the picture
   must match. A tip explained over an unrelated screen does not clip well.

## Framing

| Shot | Layout |
|---|---|
| Screen recording with small text | `blur` with `"zoom": 1.5–2.2` and `"hook_hold": true`. Choose the zoom so the part being discussed is readable on a phone, and check a frame |
| Screen recording, action in one area | `center` with `"focus_x"` on that area |
| Screen plus a facecam corner | `split` with the facecam box: face on top, screen below |
| Presenter to camera | `auto` |
| Hands, a workbench, a pan on a stove | `center` |

Text on a shared screen is the hardest thing to keep readable in 9:16. If no
zoom makes it readable, say so and frame on the presenter instead.

## Edit

- `"edit": "clean"` by default; `story` if it is a presenter talking and a
  livelier feel suits the channel.
- `"tighten": true`: tutorials have long pauses while things load or type.
- Captions on, style `clean`.
- At most one beat, on the result, with a short callout ("FIXED", "3x
  faster") only when the screen shows it.
- Hooks promise the one thing: "Stop writing *for loops* for this",
  "The *one setting* that fixes blurry exports".

## Post copy

Title = the tip. Put the tool or topic name in the first hashtag. A caption
that restates the steps in one line helps people save the clip.
```

## File: references/video.md
size: 2420
sha: 9383873c56e004200fc46d2c5b25e8243da14836
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/references/video.md

```text
# Video mode (general)

For everything without its own mode: vlogs, reviews, events, travel,
reactions, product demos, music and dance. Moments can come from the words,
the pictures, or both, so use both tools and let the video tell you which
matters more. (Gameplay, podcasts, sport and tutorials each have their own
mode and guide; use those when they fit.)

## Find the moments

1. Run `transcribe.py` and `scout.py`. Read `transcript.txt` in full and open
   the scout filmstrips.
2. Decide which carries this video:
   - **Words lead** (review, vlog to camera, reaction): pick passages from
     the transcript as in podcast mode: a claim, a result, a verdict, a
     punchline. Use the filmstrips to check that something worth watching is
     on screen while it is said.
   - **Pictures lead** (events, travel, anything with little talk): pick
     from the scout filmstrips as in gameplay mode: a reveal, a fall, a
     before-and-after, a crowd reaction. Use the transcript only for
     captions.
   - If transcription is not possible (exit code 3, or nobody speaks), carry
     on with pictures only and `"captions": false`.
3. Strong general-video moments: a reveal or result shown early, a
   before/after, a verdict, a reaction, a mistake.
4. Set times so the clip opens on the interesting thing itself. For a
   reveal, start 5–10 s before it; for a verdict, start on its first
   sentence.

## Framing

Check a filmstrip of each candidate (`peek.py --range`), then:

| Shot | Layout |
|---|---|
| A person talking to camera | `auto`, or run `track.py` if the shot changes or there are two people |
| One clear subject in the middle | `center` |
| Subject off to one side, or moving | `center` with `"focus_x"`, or a short `"focus_path"` with `"focus_mode": "pan"` |
| Wide scenery, a group, text on screen | `blur` with `"zoom": 1.5–1.9` and `"hook_hold": true` |

Prefer a layout that fills the screen. Fall back to `blur` when a clip mixes
shots that no single crop serves.

## Edit

Read `references/editing.md`.

- `"edit": "premium"` by default; `story` when a person talking carries the
  clip; `hype` for events and fast action; `clean` for calm content.
- `"tighten": true` when the clip is mostly talk; `false` when the pictures
  or the natural sound carry it.
- One or two beats on the reveal or the reaction, with a callout only when
  it adds something the picture does not already say.
```

## File: assets/face_detection_yunet_2023mar.onnx
size: 232589
sha: f9beb3044f3791affe1c2f0932af31927e2e4705
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/assets/face_detection_yunet_2023mar.onnx

Content is not inlined in the catalog. Read the upstream file: https://github.com/lowdevco/clip-forge/blob/HEAD/assets/face_detection_yunet_2023mar.onnx

## File: assets/face_detection_yunet_2026may.onnx
size: 229738
sha: a9399977f019b8121894aa42f87ecd467c7b271d
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/assets/face_detection_yunet_2026may.onnx

Content is not inlined in the catalog. Read the upstream file: https://github.com/lowdevco/clip-forge/blob/HEAD/assets/face_detection_yunet_2026may.onnx

## File: assets/fonts/Anton-Regular.ttf
size: 170812
sha: 4d65707db9d8663ccfa99cd28cd3a4e0025be178
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/assets/fonts/Anton-Regular.ttf

Content is not inlined in the catalog. Read the upstream file: https://github.com/lowdevco/clip-forge/blob/HEAD/assets/fonts/Anton-Regular.ttf

## File: assets/fonts/NotoSansMalayalam-Bold.ttf
size: 118480
sha: 7891b09bfbe33dfa17ccf65bde3b499e46a2d520
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/assets/fonts/NotoSansMalayalam-Bold.ttf

Content is not inlined in the catalog. Read the upstream file: https://github.com/lowdevco/clip-forge/blob/HEAD/assets/fonts/NotoSansMalayalam-Bold.ttf

## File: assets/fonts/OFL-Anton.txt
size: 4391
sha: efd0dd80c2deafa962d86926d1f445a9aa7407c4
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/assets/fonts/OFL-Anton.txt

```text
Copyright 2020 The Anton Project Authors (https://github.com/googlefonts/AntonFont.git)

This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL

-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------

PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.

The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded, 
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.

DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.

"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).

"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).

"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.

"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.

PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:

1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.

2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.

3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.

4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.

5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.

TERMINATION
This license becomes null and void if any of the above conditions are
not met.

DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
```

## File: assets/fonts/OFL-NotoSansMalayalam.txt
size: 4385
sha: 3fe274f292a1b917ed33839f1046bc9a238f4c17
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/assets/fonts/OFL-NotoSansMalayalam.txt

```text
Copyright 2022 The Noto Project Authors (https://github.com/notofonts/malayalam)

This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://scripts.sil.org/OFL

-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------

PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.

The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded, 
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.

DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.

"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).

"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).

"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.

"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.

PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:

1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.

2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.

3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.

4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.

5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.

TERMINATION
This license becomes null and void if any of the above conditions are
not met.

DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
```

## File: assets/fonts/OFL-Poppins.txt
size: 4385
sha: 76df3b565672e3248a5715339d092d4cb6c75019
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/assets/fonts/OFL-Poppins.txt

```text
Copyright 2020 The Poppins Project Authors (https://github.com/itfoundry/Poppins)

This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL

-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------

PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.

The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded, 
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.

DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.

"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).

"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).

"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.

"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.

PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:

1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.

2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.

3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.

4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.

5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.

TERMINATION
This license becomes null and void if any of the above conditions are
not met.

DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
```

## File: assets/fonts/Poppins-ExtraBold.ttf
size: 154836
sha: 167667d203d98f5b27c3ff58d486eea9c5287fe4
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/assets/fonts/Poppins-ExtraBold.ttf

Content is not inlined in the catalog. Read the upstream file: https://github.com/lowdevco/clip-forge/blob/HEAD/assets/fonts/Poppins-ExtraBold.ttf

## File: assets/haarcascade_frontalface_default.xml
size: 930127
sha: cbd1aa89e927d8d54b49fe666bf17244c3c46a7b
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/assets/haarcascade_frontalface_default.xml

Content is not inlined in the catalog. Read the upstream file: https://github.com/lowdevco/clip-forge/blob/HEAD/assets/haarcascade_frontalface_default.xml

## File: assets/pc/get_video.bat
size: 1696
sha: 4efb3ab3528d50e2842df6d9c900dab335a19955
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/assets/pc/get_video.bat

```text
@echo off
setlocal
rem Downloads a YouTube video + subtitles into the "inbox" folder next to this
rem file, so Claude (chat) can pick it up through the connected folder.
rem Usage: double-click and paste the link, or:  get_video.bat URL [height]

rem yt-dlp can be a program on PATH (winget) or a Python package (pip).
set "YTDLP="
where yt-dlp >nul 2>nul && set "YTDLP=yt-dlp"
if not defined YTDLP (
  python -m yt_dlp --version >nul 2>nul && set "YTDLP=python -m yt_dlp"
)
if not defined YTDLP (
  py -m yt_dlp --version >nul 2>nul && set "YTDLP=py -m yt_dlp"
)
if not defined YTDLP (
  echo yt-dlp is not installed. Run one of these once, then start again:
  echo     winget install yt-dlp.yt-dlp
  echo     python -m pip install -U yt-dlp
  pause & exit /b 1
)
where ffmpeg >nul 2>nul
if errorlevel 1 (
  echo ffmpeg is not installed. Run this once, then start again:
  echo     winget install Gyan.FFmpeg
  pause & exit /b 1
)

set "URL=%~1"
if "%URL%"=="" set /p "URL=Paste the YouTube link: "
set "H=%~2"
if "%H%"=="" set "H=720"

set "OUT=%~dp0inbox"
if not exist "%OUT%" mkdir "%OUT%"

%YTDLP% --no-playlist --restrict-filenames ^
  -f "bv*[height<=%H%]+ba/b[height<=%H%]/b" -S "vcodec:h264,res,acodec:m4a" ^
  --merge-output-format mp4 ^
  --write-subs --write-auto-subs --sub-langs "en.*,ml.*,-live_chat" ^
  --sub-format "json3/vtt/best" --write-info-json ^
  -o "%OUT%\%%(id)s.%%(ext)s" "%URL%"
if errorlevel 1 (
  echo.
  echo The download reported an error. If a video file is in the inbox it may
  echo still be usable; otherwise update yt-dlp and try again.
)

echo.
echo Done. Files are in: %OUT%
echo Now tell Claude: "the video is in the inbox folder, make the shorts".
pause
```

## File: .gitattributes
size: 147
sha: 5312fae2a2b4dedea9e4e1093ed8af3b22793b6b
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/.gitattributes

```text
# Auto detect text files and perform LF normalization
* text=auto
# Windows batch files need CRLF line endings to run reliably
*.bat text eol=crlf
```

## File: .gitignore
size: 171
sha: 728fcbcf46d66ba9d8a5a5947b7ae20abd3d749a
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/.gitignore

```text
__pycache__/
*.pyc
# videos and per-video work folders never belong in the repo
inbox/
work/
shorts/
_work/
*.mp4
*.mkv
*.webm
*.wav
# packaged builds
dist/
*.skill
*.zip
```

## File: commands/clip-edit.md
size: 730
sha: d4f19e7ba269c86235b36c8a31f6e244217528aa
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/commands/clip-edit.md

```text
---
name: clip-edit
description: Give an existing clip, or an exact time range of a video, a finished short-form edit without searching for moments. Reframes to vertical 1080x1920, adds colour grade, punch-in zooms and slow-motion on the key moments, sound effects, an animated headline, word-by-word captions, a channel watermark and an outro. Use when the user runs /clip-edit, or already has a clip or timestamps and asks to edit it, make it pop, add captions, polish it or make it look professional.
---

**Mode is fixed: edit.** The user already has the clip or the times. Do not
search for moments or show a scored table. Read `references/edit.md` and
follow it in place of steps 3 and 4 below; the rest applies as written.
```

## File: commands/clip-gameplay.md
size: 704
sha: 800e0056a3089b380e35f033499f48b3717dc692
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/commands/clip-gameplay.md

```text
---
name: clip-gameplay
description: Cut a gameplay video or stream into vertical Shorts / Reels / TikToks. Finds the best action moments (fights, clutches, wins, fails) from sound, motion and the frames, shows a scored table for approval, then renders 1080x1920 clips with a hook headline, facecam split or full-screen framing, and captions when someone talks. Use when the user runs /clip-gameplay, or gives a YouTube link or video file of a game and wants shorts, highlights or best moments.
---

**Mode is fixed: gameplay.** The user chose this command, so do not work out
what kind of video it is. Read `references/gameplay.md` before step 3 and
follow it. Everything else below applies as written.
```

## File: commands/clip-podcast.md
size: 716
sha: 8edee7039c34865923527905b2a7589c8d488f31
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/commands/clip-podcast.md

```text
---
name: clip-podcast
description: Cut a podcast, interview or talking-head video into vertical Shorts / Reels / TikToks. Finds the strongest self-contained passages from the transcript, shows a scored table for approval, then renders 1080x1920 clips cropped onto the speaker with word-by-word captions (English and Malayalam), a hook headline and silences trimmed. Use when the user runs /clip-podcast, or gives a YouTube link or video file of a podcast or interview and wants shorts, clips or viral parts.
---

**Mode is fixed: podcast.** The user chose this command, so do not work out
what kind of video it is. Read `references/podcast.md` before step 3 and
follow it. Everything else below applies as written.
```

## File: commands/clip-sports.md
size: 742
sha: 48e0f93bc131f480e479953382f61daa747c04e3
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/commands/clip-sports.md

```text
---
name: clip-sports
description: Cut sports footage or a match broadcast into vertical Shorts / Reels / TikToks. Finds goals, wickets, points, saves and finishes from crowd and commentator noise and from scoreboard changes, shows a scored table for approval, then renders edited 1080x1920 clips with a headline, punch-in and slow-motion on the key moment, and the real score as a callout. Use when the user runs /clip-sports, or gives a YouTube link or video file of a match, game or race and wants highlights, shorts or best moments.
---

**Mode is fixed: sports.** The user chose this command, so do not work out
what kind of video it is. Read `references/sports.md` before step 3 and
follow it. Everything else below applies as written.
```

## File: commands/clip-tutorial.md
size: 710
sha: 671be89f7687a38500b483e7fd9e1753eb1d6f60
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/commands/clip-tutorial.md

```text
---
name: clip-tutorial
description: Cut a tutorial, lesson, walkthrough or explainer into vertical Shorts / Reels / TikToks. Finds complete single ideas (one tip, one fix, one result) from the transcript, shows a scored table for approval, then renders clean 1080x1920 clips with readable screen framing, captions and silences trimmed. Use when the user runs /clip-tutorial, or gives a YouTube link or video file of a how-to, course, coding or screen-recording video and wants shorts, tips or clips.
---

**Mode is fixed: tutorial.** The user chose this command, so do not work out
what kind of video it is. Read `references/tutorial.md` before step 3 and
follow it. Everything else below applies as written.
```

## File: commands/clip-video.md
size: 698
sha: 32508e0ae7d15f7a4ad59cc56dca4f5ef49429b6
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/commands/clip-video.md

```text
---
name: clip-video
description: Cut any long video (vlog, tutorial, review, event, sports, travel) into vertical Shorts / Reels / TikToks. Finds the best moments from both the transcript and the pictures, shows a scored table for approval, then renders 1080x1920 clips with captions, a hook headline and loudness-normalised audio. Use when the user runs /clip-video, or gives a YouTube link or video file that is neither a podcast nor gameplay and wants shorts, clips or highlights.
---

**Mode is fixed: video (general).** The user chose this command, so do not
work out what kind of video it is. Read `references/video.md` before step 3
and follow it. Everything else below applies as written.
```

## File: docs/logo.svg
size: 390
sha: b26eb9636f7d4548f5a5ea08eb37c58f23ba7579
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/docs/logo.svg

```text
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 120" width="120" height="120" role="img" aria-label="ClipForge logo">
  <title>ClipForge</title>
  <!-- a 9:16 clip with a play cut out of it -->
  <rect x="31" y="8" width="58" height="104" rx="16" fill="#FF4D2E"/>
  <path d="M52 43 L75 60 L52 77 Z" fill="#FFFFFF" stroke="#FFFFFF" stroke-width="4" stroke-linejoin="round"/>
</svg>
```

## File: LICENSE
size: 1065
sha: 13d7ac71badb883efa82f16dced88f7ac921eb8e
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/LICENSE

```text
MIT License

Copyright (c) 2026 lowdevco

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```

## File: tools/build.py
size: 3595
sha: 61d664647735afaa644a842b922c7870315ef9fc
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/tools/build.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/lowdevco/clip-forge/blob/HEAD/tools/build.py

## File: tools/selftest.py
size: 7042
sha: 67b1ead35bd637d1123ae79a49ef85acf47cc8b8
upstream: https://github.com/lowdevco/clip-forge/blob/HEAD/tools/selftest.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/lowdevco/clip-forge/blob/HEAD/tools/selftest.py
