# Edit Clone: Claude-д өгөх setup файл

## Худалдан авагчид

Энэ файлыг Claude-д нэг удаа өгөхөд Claude хэрэгтэй бүх зүйлийг өөрөө суулгана. Дараа нь таалагдсан видеоныхоо
линкийг өгөхөд Claude тэр edit-ийн бүтэц, хэмнэл, өнгө, хөдөлгөөнийг уншаад таны текст, лого, зургаар ижил маягийн
видео хийнэ.

**Юу хэрэгтэй вэ**

- Claude Pro эсвэл түүнээс дээш эрх. Free эрх дээр Claude Code ажиллахгүй.
- Claude Code: Claude Desktop app-ийн **Code** хэсэг (Local сонгоно) эсвэл terminal. Энгийн чат дээр энэ файл
  ажиллахгүй, учир нь чат таны компьютер дээр программ суулгаж чадахгүй.
- Windows 10/11 эсвэл macOS, интернэт, 3 GB орчим сул зай.

**Яаж эхлэх вэ**

1. Claude Desktop app-аа нээгээд **Code** хэсэгт орж, ажлын хавтас сонгоно. Жишээ нь Documents дотор "videos" нэртэй
   хавтас үүсгээд түүнийгээ сонгоорой.
2. Энэ файлыг чирч оруулаад "Энэ файлыг уншаад setup хий" гэж бичнэ.
3. Claude юу суулгахаа жагсааж хэлээд зөвшөөрөл асууна. Зөвшөөрөөрэй. Windows "Do you want to allow" гэж асуувал Yes
   дарна. Setup 15-30 минут үргэлжилнэ.
4. Дууссаны дараа `/edit-clone <линк>` гэж бичээд Claude-ийн асуултад хариулна.

**Анхаарах зүйл**

- Бусдын бичлэг, дуу, лого, текстийг хуулахгүй. Зөвхөн хэв маяг, хэмнэлийг нь авна.
- Видео бүтээхэд Claude-ийн хэрэглээний хязгаар их зарцуулагдана. Pro эрх дээр нэг видео хийх явцад хязгаарт хүрч,
  хэдэн цаг хүлээх тохиолдол гардаг.

---

# For Claude: install the `edit-clone` skill

The user handed you this file to set up a skill that remakes the style of a reference video edit with the user's
own content, built with HyperFrames (HTML to video, by HeyGen, Apache-2.0). Do exactly what this section lists,
nothing else. Talk to the user in their language (Mongolian when they write Mongolian); keep tool names in English.

Every step checks first and skips what is already there, so running this file again is safe.

## 1. Tell the user the plan and get one OK

List in the user's language what you will do, then ask once and wait for yes:

- Install only what is missing: Node.js 22+, Python 3.10+, FFmpeg (system installs, may ask for permission).
- Install the HyperFrames skills and its headless browser (`npx hyperframes skills`, `npx hyperframes browser ensure`),
  and turn off HyperFrames usage telemetry.
- Create `~/.claude/skills/edit-clone/` with three files from this document, and a Python environment inside it with
  numpy, pillow, librosa and yt-dlp.
- Run a self-test.

## 2. Find what is missing

Detect the OS. Run each check; note what fails or is too old.

| Need | Check | Windows (PowerShell) | macOS |
|---|---|---|---|
| Node.js 22+ | `node --version` | `winget install -e --id OpenJS.NodeJS.LTS --accept-source-agreements --accept-package-agreements` | `brew install node` |
| Python 3.10+ | Windows: `py -3 --version`; macOS: `python3 --version` | `winget install -e --id Python.Python.3.12 --accept-source-agreements --accept-package-agreements` | `brew install python` |
| FFmpeg | `ffmpeg -version` and `ffprobe -version` | `winget install -e --id Gyan.FFmpeg --accept-source-agreements --accept-package-agreements` | `brew install ffmpeg` |

- **Windows:** run installs and checks with the PowerShell tool. Do not use `python` there: on a fresh Windows it
  opens the Microsoft Store. Use `py`.
- **Windows PATH:** a program installed during this session is not on this session's PATH. Prefix each check after
  an install with
  `$env:Path = [Environment]::GetEnvironmentVariable('Path','Machine') + ';' + [Environment]::GetEnvironmentVariable('Path','User');`.
  If you installed anything with winget, finish the remaining steps, then tell the user to quit Claude completely
  and open it again before the first video (HyperFrames and the skill run ffmpeg and node from PATH).
- **macOS without Homebrew** (`brew --version` fails): it needs the user's password, so you cannot run it. Give the
  user this line to paste into Terminal, wait for them, then continue:
  `/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"`
- **Linux:** use the distro's packages (`node` 22+ from NodeSource if the distro's is older, `python3 python3-venv`,
  `ffmpeg`).
- Judge a check by what it prints (a version number), not by its exit code: PowerShell can report a failure for a
  native command that worked.
- A failed install: show the error to the user in plain words and stop. Do not work around a missing tool.

## 3. HyperFrames

```
npx --yes hyperframes skills
npx --yes hyperframes browser ensure
npx --yes hyperframes telemetry disable
npx --yes hyperframes doctor
```

In `doctor`'s output, Node, FFmpeg and Chrome (the headless browser) must be ✓. A ✗ on an optional item (Kokoro
TTS, Docker, and the like) is fine, even when the last line says some checks failed. If a required one fails, show
it to the user and fix it before going on.

## 4. Write the skill

`SKILL_DIR` = `~/.claude/skills/edit-clone` (Windows: `%USERPROFILE%\.claude\skills\edit-clone`). Its three files are
in the **Files** section at the end of this document: `SKILL.md`, `tools/requirements.txt`, `tools/read.py`. Each
is everything between its `~~~~` fence lines and must land byte for byte. Do not change, shorten or "improve" them.

- **You know this document's path** (the user attached or dragged the file): extract the files with a script, not
  by retyping. Write the script below to a temp file `extract.py` and run it with `py -3` (Windows) or `python3`:
  `<python> extract.py "<this document>" "<SKILL_DIR>"`. It must print three `wrote` lines.
- **You only have the text** (the user pasted it): write each file with the Write tool, exactly as it stands.

```python
import io, os, re, sys

doc, dest = sys.argv[1], sys.argv[2]
text = io.open(doc, encoding="utf-8").read().replace("\r\n", "\n")
files = re.findall(r"^## ([\w./-]+)\n\n~~~~\w*\n(.*?)\n~~~~$", text, re.S | re.M)
for name, body in files:
    path = os.path.join(dest, *name.split("/"))
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with io.open(path, "w", encoding="utf-8", newline="\n") as h:
        h.write(body + "\n")
    print("wrote", path)
if len(files) != 3:
    sys.exit("expected 3 files, found %d" % len(files))
```

Then the Python environment, inside `SKILL_DIR`:

- Windows: `py -3 -m venv "$env:USERPROFILE\.claude\skills\edit-clone\.venv"`, then
  `& "$env:USERPROFILE\.claude\skills\edit-clone\.venv\Scripts\python.exe" -m pip install -r "$env:USERPROFILE\.claude\skills\edit-clone\tools\requirements.txt"`
- macOS/Linux: `python3 -m venv ~/.claude/skills/edit-clone/.venv`, then
  `~/.claude/skills/edit-clone/.venv/bin/python -m pip install -r ~/.claude/skills/edit-clone/tools/requirements.txt`
- If pip fails, run the same command once more (a first run can time out). If it fails again with a long-path error
  on Windows, the user enables long paths once in a PowerShell opened as administrator, then you run pip again:
  `New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem" -Name LongPathsEnabled -Value 1 -PropertyType DWORD -Force`

## 5. Self-test

Run, with the venv's Python: `<venv python> <SKILL_DIR>/tools/read.py --selftest <a temp folder>`.
It makes a 3-second test clip, reads it, and must print `SELFTEST OK`. On `SELFTEST FAIL` or a crash, extract the
files again (a copying slip is the usual cause) and run it again. Then delete the temp folder.

## 6. Hand over

Tell the user, in their language. In Mongolian, use this text:

> Setup дууслаа. Ингэж ашиглана:
> 1. Таалагдсан видеоныхоо линкийг хуулна (Instagram, TikTok, YouTube).
> 2. `/edit-clone <линк>` гэж бичнэ. "Энэ видео шиг edit хий" гээд линкээ өгсөн ч болно.
> 3. Claude таны текст, лого, зураг, дууг асууна.
> 4. Эхлээд хурдан draft гаргаж үзүүлээд, дараа нь бүрэн чанартай MP4 гаргана.
>
> `/edit-clone` гарч ирэхгүй бол `/reload-skills` гэж бичээрэй, эсвэл app-аа хаагаад дахин нээгээрэй.

If anything was installed with winget, add that they must quit Claude completely and reopen it first.

---

# Files

## SKILL.md

~~~~markdown
---
name: edit-clone
description: Remake the style of a reference video edit (Instagram Reel, TikTok, YouTube) with the user's own content, built in HyperFrames. Downloads the reference, reads its cuts, pacing, beat sync, palette, type and motion, writes a short recipe, then builds, checks and renders a new video that moves and feels the same. Use when the user gives a video link or file and says "make it like this", "ene video shig hii", "энэ видео шиг хий", "дуурай", "ийм edit хий", "/edit-clone".
---

# Edit clone

Take a reference edit, read how it is put together, and make a new video in the same style that carries the user's
own words, brand, pictures and music. The style is copied; the reference's content never is.

**Paths.** `SKILL_DIR` = this skill's folder (`~/.claude/skills/edit-clone`; Windows
`%USERPROFILE%\.claude\skills\edit-clone`). `PY` = `SKILL_DIR/.venv/bin/python` (macOS/Linux) or
`SKILL_DIR\.venv\Scripts\python.exe` (Windows). `READ` = `SKILL_DIR/tools/read.py`. Run them by absolute path.

**Talk** to the user in their language (Mongolian when they write Mongolian), tool names in English.

## 0. Start

- Quick check: `ffmpeg -version` and `PY -c "import librosa, yt_dlp"`. If one fails, tell the user to run the setup
  file again. Do not work around it.
- Make the work folder `edits/<short-name>/` in the current folder and run every command below from inside it. It
  holds `ref/` (the reference and its reading), `RECIPE.md`, and the HyperFrames project.
- Ask once, all together, only what the user has not already given. In Mongolian:

  > Видеогоо хийхэд дараах зүйлс хэрэгтэй. Байхгүйг нь алгасаарай:
  > 1. Видео дээр гарах текст эсвэл гол санаа
  > 2. Брэндийн өнгө, лого (файлаа чирч оруулна)
  > 3. Өөрийн зураг, бичлэг (файл эсвэл хавтас)
  > 4. Дуу: өөрийн дуу, бичлэг, эсвэл дуугүй (дууг Instagram дээр нийтлэхдээ нэмж болно)
  > 5. Хэмжээ: 9:16 (Reels, TikTok), 1:1 эсвэл 16:9. Хэлэхгүй бол 9:16.

## 1. Get the reference

- `PY -m yt_dlp -f "bv*+ba/b" --merge-output-format mp4 -o ref/master.mp4 <url>`.
  YouTube: add `--js-runtimes node`. A failed download: first `PY -m pip install -U "yt-dlp[default]"` and retry.
- Instagram often refuses logged-out downloads. Only with the user's OK, add `--cookies-from-browser firefox`
  (Firefox installed and logged in), and say that logged-in downloading can trip Instagram's automation checks on
  their account. Otherwise ask the user to save the video and give you the file.
- A file from the user works the same. A screen recording is fine for style, weaker for timing.
- Never upscale or re-encode the reference.

## 2. Read it

1. `PY READ ref/master.mp4 --out ref`. It writes `read.json` (summary first: size, fps,
   length, cuts, shot lengths, tempo, `cuts_on_beat`, palette, flashes; then every cut, shot and beat),
   `sheet.jpg` (frames at even times) and `shots.jpg` (one frame per shot, numbered, with its time).
2. Look at `shots.jpg` and `sheet.jpg`. They show the structure; most edits need nothing more.
3. For a move that matters (a title entrance, a transition), look at up to 4 short stretches frame by frame:
   `ffmpeg -v error -ss <t0> -t 1.2 -i ref/master.mp4 -vf "fps=15,scale=240:-2,tile=6x3" -frames:v 1 ref/move-<t0>.jpg`
   (18 frames over 1.2 s; count the frames a move takes, 1 frame = 1/15 s here).
4. The numbers can mislead: a one-frame glitch or a whip reads as a cut; the tempo can read double or half;
   `cuts_on_beat` is meaningless when the reference has no music. Trust what you see in the frames over a number.

## 3. RECIPE.md

Write `RECIPE.md` from what you read. Mark each line [seen] (in a frame), [measured] (read.json) or
[guess]. Keep it to one page:

```markdown
# Recipe: <reference name>
Format: <WxH>, <fps> fps, <length> s [measured]
Structure: <section> <t0-t1> ... (hook, build, payoff, end card) [seen]
Pacing: <cuts> cuts, shot median <s> s (shortest <s>, longest <s>); tempo <bpm>; cuts on beat <share> [measured]
Look: background <hex>, palette <hexes>; grain / glow / blur / gradients [seen]
Type: <serif | sans | display>, <weight>, <case>, size <% of frame height>, placement, how words enter [seen]
Motion: entrances and exits (slide / scale / fade / mask / type-on), feel -> ease (table below), camera (push-in,
  shake, parallax) [seen / guess]
Transitions: hard cut <n>, whip <n>, flash <n>, zoom-through <n>, other [seen: count them in shots.jpg and the
  frame stretches; `white_flashes` counts only white flashes shorter than 0.2 s]
Sound: music / voice / sound effects; where hits land [measured + heard in the frames' timing]
Swap: <their element> -> <the user's element>, one line each
```

- **Nothing to swap in** (no logo, no pictures): replace that element with type or simple shapes in the user's
  colours, or drop the shot and keep the pacing.
- **A different frame shape** (a 16:9 reference, a 9:16 delivery): recompose every scene for the new frame (stack
  side-by-side parts, keep type at the same share of the frame width); never crop or letterbox the design. Write
  this in the recipe.

Feel to GSAP ease: snappy, lands hard -> `power3.out` or `expo.out`; smooth glide -> `sine.inOut` or
`power2.inOut`; overshoots and settles -> `back.out(1.7)`; wobbles -> `elastic.out(1, 0.4)`; speeds into a cut ->
`power2.in` or `expo.in`; constant speed -> `none`.

Show the user the recipe in 5-8 plain lines and go on unless they object.

## 4. Build with HyperFrames

- Copy the user's files into the work folder first. With the user's music: `PY READ <music file> --out music`
  gives its beats. Without music, keep the reference's tempo and beat times so a track at that tempo can be added in
  the app; say so at the end.
- Invoke `/hyperframes` as a **fresh creation**. Give it: the user's content, `RECIPE.md` (absolute path), the size,
  and a suggested route:
  - cuts on the beat and the user has music -> `/music-to-video`
  - under ~10 s, no voice, motion is the message -> `/motion-graphics`
  - the user's own talking footage with captions -> `/embedded-captions`; with designed info cards ->
    `/talking-head-recut`
  - anything else -> `/general-video`
- Tell it the direction is fixed: match the recipe's structure, pacing, look and motion; no alternative directions.
  Answer its intake questions from the recipe and the user's answers; ask the user only what is still missing.
  After `init`, `BRIEF.md` must carry `Style reference: <path>/RECIPE.md` under `## Notes` and the recipe's
  must-haves under `## Customizations`.
- Cuts: place them on the beats with about the same share on the beat as the reference; same shot lengths. Fewer
  words means fewer shots, not slower ones. Never stretch a move to fill time.
- Fonts: open fonts that cover the user's script (for Mongolian check Ө and Ү: Inter, Montserrat, Roboto,
  Noto Sans). Build any app or website UI as live HTML, never as a screenshot of a real app.

## 5. Check (at most 2 rounds)

1. `npx hyperframes check` passes; `npx hyperframes snapshot --at <a time in each section>`; look at the frames.
2. Draft render (inside the project): `npx hyperframes render --quality draft --workers 2`.
3. `PY READ <draft.mp4> --out check/round1`, then compare with the reference's `read.json`:
   length within 10 %, shot median within 25 %, cuts on beat within 0.2 (when both have music). Put
   `check/round1/shots.jpg` beside `ref/shots.jpg` and look for the biggest difference in look or motion.
4. Fix the biggest difference, render again. After round 2, stop and tell the user what still differs.

## 6. Render and hand over

- Final: `npx hyperframes render --quality delivery --workers 2`. Each worker is a separate Chrome (~256 MB); keep
  2 on a computer with less than 8 GB free memory.
- Give the user the MP4 path, 3-4 lines on what matches the reference, and what differs.

## Rules

- **Copy the style, not the assets.** Never put the reference's footage, music, logos, people, words or watermark in
  the new video. Music: the user's own or licensed track, or a trending track added in the app when posting.
- A downloaded reference is for study only; it stays in `ref/` and is never published.
- Every frame must come from the timeline (no `Math.random`, `Date.now`, `requestAnimationFrame`); `/hyperframes-core`
  has the rules.
~~~~

## tools/requirements.txt

~~~~text
numpy
pillow
librosa
yt-dlp[default]
~~~~

## tools/read.py

~~~~python
# -*- coding: utf-8 -*-
"""Read a reference edit: size, length, cuts, shot lengths, beats, cuts on the beat, palette, flashes.

    python read.py <video.mp4 | music.mp3> [--out DIR]

Writes into DIR (default: a folder named after the file, next to it):
  read.json   everything measured (summary first)
  sheet.jpg   frames at even times, labelled with seconds
  shots.jpg   one frame from the middle of every shot, labelled #shot and seconds
A file with no picture (music, voice-over) gets read.json with its beat grid only.

A cut is a frame whose change from the previous frame jumps (ffmpeg scdet's score above 10), at least 3 frames
after the previous cut. A white flash is a jump up in brightness that falls back within 0.2 s (a white card that
stays longer is a shot, not a flash). Beats and onsets come from librosa; the tempo can read double or half the felt tempo.
"""
from __future__ import annotations

import argparse
import io
import json
import os
import subprocess
import tempfile

import numpy as np

# librosa's numba cache lands next to the package by default; a long Windows path breaks it.
os.environ.setdefault("NUMBA_CACHE_DIR", os.path.join(tempfile.gettempdir(), "edit-clone-numba"))

FONTS = [
    r"C:\Windows\Fonts\arialbd.ttf",
    "/System/Library/Fonts/Supplemental/Arial Bold.ttf",
    "/Library/Fonts/Arial Bold.ttf",
    "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
]


def font(size):
    from PIL import ImageFont

    for path in FONTS:
        if os.path.exists(path):
            return ImageFont.truetype(path, size)
    try:
        return ImageFont.load_default(size=size)
    except TypeError:  # Pillow < 10.1
        return ImageFont.load_default()


def probe(path):
    out = subprocess.run(
        ["ffprobe", "-v", "error", "-show_streams", "-show_format", "-of", "json", path],
        capture_output=True, check=True, text=True,
    ).stdout
    return json.loads(out)


def even(x):
    return max(2, int(round(x / 2.0)) * 2)


def decode(path, width, height, pix):
    chans = {"gray": 1, "rgb24": 3}[pix]
    raw = subprocess.run(
        ["ffmpeg", "-v", "error", "-i", path, "-an", "-vf", "scale=%d:%d:flags=area" % (width, height),
         "-f", "rawvideo", "-pix_fmt", pix, "-"],
        capture_output=True, check=True,
    ).stdout
    frames = np.frombuffer(raw, np.uint8)
    n = frames.size // (width * height * chans)
    shape = (n, height, width) if chans == 1 else (n, height, width, chans)
    return frames[: n * width * height * chans].reshape(shape)


def palette(rgb, k=6):
    """Most common colours: pixels binned to 8 levels per channel, each bin reported as its mean colour."""
    px = rgb.reshape(-1, 3).astype(np.int32)
    bins = (px[:, 0] // 32) * 64 + (px[:, 1] // 32) * 8 + px[:, 2] // 32
    counts = np.bincount(bins, minlength=512)
    out = []
    for b in np.argsort(-counts)[:k]:
        if counts[b] == 0:
            break
        mean = px[bins == b].mean(axis=0)
        out.append({"hex": "#%02x%02x%02x" % tuple(int(v) for v in mean), "share": round(counts[b] / len(px), 3)})
    return out


def audio(path, folder):
    import librosa

    wav = os.path.join(folder, "_a22.wav")
    done = subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", path, "-vn", "-ac", "1", "-ar", "22050", wav],
                          capture_output=True)
    empty = {"tempo": None, "beats": [], "onsets": []}
    if done.returncode != 0 or not os.path.exists(wav):  # no audio stream
        return empty
    y, sr = librosa.load(wav, sr=22050)
    os.remove(wav)
    if y.size == 0 or float(np.abs(y).max()) < 1e-4:
        return empty
    tempo, beats = librosa.beat.beat_track(y=y, sr=sr, units="time")
    onsets = librosa.onset.onset_detect(y=y, sr=sr, units="time")
    return {
        "tempo": round(float(np.atleast_1d(tempo)[0]), 1),
        "beats": [round(float(t), 3) for t in beats],
        "onsets": [round(float(t), 3) for t in onsets],
    }


def on_grid(times, grid, fps):
    """Share of times within 2 frames of a grid point (a beat or an onset)."""
    if not times or not grid:
        return None
    g = np.asarray(grid)
    return round(float(np.mean([np.abs(g - t).min() <= 2.0 / fps + 1e-6 for t in times])), 2)


def label(img, text):
    from PIL import ImageDraw

    draw = ImageDraw.Draw(img)
    f = font(max(12, img.width // 12))
    box = draw.textbbox((0, 0), text, font=f)
    draw.rectangle((0, 0, box[2] + 8, box[3] + 6), fill=(0, 0, 0))
    draw.text((4, 2), text, fill=(255, 255, 0), font=f)
    return img


def grab(path, indices, width, height):
    """Frames by index in one decode pass."""
    from PIL import Image

    wanted = sorted(set(indices))
    expr = "+".join("eq(n\\,%d)" % i for i in wanted)
    raw = subprocess.run(
        ["ffmpeg", "-v", "error", "-i", path, "-an", "-vf",
         "select='%s',scale=%d:%d:flags=lanczos" % (expr, width, height), "-vsync", "0",
         "-f", "rawvideo", "-pix_fmt", "rgb24", "-"],
        capture_output=True, check=True,
    ).stdout
    size = width * height * 3
    return {i: Image.frombytes("RGB", (width, height), raw[k * size:(k + 1) * size])
            for k, i in enumerate(wanted) if (k + 1) * size <= len(raw)}


def contact(tiles, cols, out):
    from PIL import Image

    rows = (len(tiles) + cols - 1) // cols
    w, h = tiles[0].size
    canvas = Image.new("RGB", (cols * w + (cols - 1) * 4, rows * h + (rows - 1) * 4), (40, 40, 40))
    for i, tile in enumerate(tiles):
        canvas.paste(tile, ((i % cols) * (w + 4), (i // cols) * (h + 4)))
    canvas.save(out, quality=86)


def read(path, folder):
    os.makedirs(folder, exist_ok=True)
    meta = probe(path)
    video = next((s for s in meta["streams"] if s["codec_type"] == "video"), None)
    if video is None:  # music or voice-over: the beat grid only
        aud = audio(path, folder)
        result = {"summary": {"file": os.path.basename(path), "tempo": aud["tempo"], "beats": len(aud["beats"]),
                              "onsets": len(aud["onsets"])}, **aud}
        with io.open(os.path.join(folder, "read.json"), "w", encoding="utf-8") as h:
            json.dump(result, h, ensure_ascii=False, indent=1)
        print(json.dumps(result["summary"], ensure_ascii=False))
        print("wrote", folder)
        return
    W, H = int(video["width"]), int(video["height"])
    num, den = (int(x) for x in video["avg_frame_rate"].split("/"))
    fps = num / den

    luma = decode(path, 320, even(320 * H / W), "gray")
    rgb = decode(path, 96, even(96 * H / W), "rgb24")
    n = min(len(luma), len(rgb))
    luma, rgb = luma[:n], rgb[:n]
    mad = np.zeros(n, np.float32)
    for i in range(1, n):
        mad[i] = np.abs(luma[i].astype(np.int16) - luma[i - 1]).mean()
    mafd = mad * 100.0 / 255.0
    scd = np.zeros(n, np.float32)
    scd[1:] = np.minimum(mafd[1:], np.abs(np.diff(mafd)))
    cuts = []
    for i in range(1, n):
        if scd[i] > 10 and (not cuts or i - cuts[-1] >= 3):
            cuts.append(i)
    mean_luma = luma.reshape(n, -1).mean(axis=1)
    rises = np.where(np.diff(mean_luma) > 60)[0] + 1
    back = max(2, int(round(0.2 * fps)))
    flashes = sum(1 for i in rises if i + 1 < n and mean_luma[i + 1:i + 1 + back].min() < mean_luma[i] - 60)

    bounds = [0] + cuts + [n]
    shots = []
    for a, b in zip(bounds[:-1], bounds[1:]):
        mid = (a + b) // 2
        shots.append({"n": len(shots) + 1, "start": round(a / fps, 3), "dur": round((b - a) / fps, 3),
                      "mid": round(mid / fps, 3),
                      "busy": round(float(mad[a + 1:b].mean()) if b - a > 1 else 0.0, 2),
                      "palette": palette(rgb[mid], k=4)})

    aud = audio(path, folder)
    cut_times = [round(c / fps, 3) for c in cuts]
    durs = np.array([s["dur"] for s in shots])
    summary = {
        "file": os.path.basename(path), "size": "%dx%d" % (W, H), "fps": round(fps, 3),
        "seconds": round(n / fps, 2), "cuts": len(cuts), "shots": len(shots),
        "shot_median_s": round(float(np.median(durs)), 2),
        "shot_shortest_s": round(float(durs.min()), 2), "shot_longest_s": round(float(durs.max()), 2),
        "busy_median": round(float(np.median(mad[1:])), 2) if n > 1 else 0.0,
        "white_flashes": flashes, "black_frames": int(np.sum(mean_luma < 8)),
        "tempo": aud["tempo"],
        "cuts_on_beat": on_grid(cut_times, aud["beats"], fps),
        "cuts_on_onset": on_grid(cut_times, aud["onsets"], fps),
        "palette": palette(rgb[:: max(1, n // 40)], k=6),
    }
    result = {"summary": summary, "cuts": cut_times, "shots": shots, **aud}
    with io.open(os.path.join(folder, "read.json"), "w", encoding="utf-8") as h:
        json.dump(result, h, ensure_ascii=False, indent=1)

    portrait = H > W
    tile_w, cols, count = (180, 8, 32) if portrait else (300, 6, 36)
    tile_h = even(tile_w * H / W)
    sheet_idx = [int((i + 0.5) * n / count) for i in range(count)]
    shown = shots if len(shots) <= 48 else [shots[int(i * len(shots) / 48)] for i in range(48)]
    shot_idx = [min(n - 1, int(round(s["mid"] * fps))) for s in shown]
    frames = grab(path, sheet_idx + shot_idx, tile_w, tile_h)
    contact([label(frames[i].copy(), "%.2fs" % (i / fps)) for i in sheet_idx if i in frames], cols,
            os.path.join(folder, "sheet.jpg"))
    contact([label(frames[i].copy(), "#%d %.2fs" % (s["n"], s["mid"])) for s, i in zip(shown, shot_idx)
             if i in frames], cols, os.path.join(folder, "shots.jpg"))
    print(json.dumps(summary, ensure_ascii=False))
    print("wrote", folder)


def selftest(folder):
    """Make a 3 s clip (white, black, grey; a click every 0.5 s) and check that it reads back right."""
    os.makedirs(folder, exist_ok=True)
    clip = os.path.join(folder, "selftest.mp4")
    subprocess.run(
        ["ffmpeg", "-v", "error", "-y",
         "-f", "lavfi", "-i", "color=c=white:s=640x360:r=30:d=1",
         "-f", "lavfi", "-i", "color=c=black:s=640x360:r=30:d=1",
         "-f", "lavfi", "-i", "color=c=gray:s=640x360:r=30:d=1",
         "-f", "lavfi", "-i", "aevalsrc=0.8*sin(2*PI*1000*t)*lt(mod(t\\,0.5)\\,0.03):s=44100:d=3",
         "-filter_complex", "[0:v][1:v][2:v]concat=n=3:v=1:a=0[v]", "-map", "[v]", "-map", "3:a",
         "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", clip],
        check=True,
    )
    read(clip, os.path.join(folder, "selftest"))
    with io.open(os.path.join(folder, "selftest", "read.json"), encoding="utf-8") as h:
        got = json.load(h)
    s = got["summary"]
    problems = []
    if [round(c, 1) for c in got["cuts"]] != [1.0, 2.0]:
        problems.append("cuts %s, expected [1.0, 2.0]" % got["cuts"])
    if not s["tempo"] or min(abs(s["tempo"] - t) for t in (60, 120, 240)) > 6:
        problems.append("tempo %s, expected 120 (or 60 / 240)" % s["tempo"])
    for name in ("sheet.jpg", "shots.jpg"):
        if not os.path.exists(os.path.join(folder, "selftest", name)):
            problems.append(name + " missing")
    print("SELFTEST FAIL: " + "; ".join(problems) if problems else "SELFTEST OK")
    return not problems


def main():
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("file", nargs="?")
    ap.add_argument("--out", default="", help="output folder (default: <file name> next to the file)")
    ap.add_argument("--selftest", metavar="DIR", help="make a test clip in DIR, read it, print SELFTEST OK or FAIL")
    a = ap.parse_args()
    if a.selftest:
        raise SystemExit(0 if selftest(os.path.abspath(a.selftest)) else 1)
    if not a.file:
        ap.error("give a video or audio file")
    path = os.path.abspath(a.file)
    read(path, os.path.abspath(a.out) if a.out else os.path.splitext(path)[0])


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