CtrlK
BlogDocsLog inGet started
Tessl Logo
PluginPublic

gamussa/reels-producer-skill

Write talking-head scripts and produce Instagram reels and YouTube shorts

1.07x
Quality

96%

Does it follow best practices?

Impact

98%

1.07x

Average score across 8 eval scenarios

SecuritybySnyk

Low

Low-risk findings worth noting

Overview
Quality
Evals
Security
Files

hooks.pyskills/reel-builder/scripts/

#!/usr/bin/env python3
"""Three opening concepts per reel, compared as rendered openings before the
full edit is polished.

Each variant combines a first line, the footage under it, and on-screen text.
They are creative alternatives to put in front of the user, not a claim that
one performs better. Nothing here is a performance prediction.

A first line is one of two kinds, and the difference is enforced:
  recorded  words actually spoken: start/end in the transcript, and the text
            must equal those words exactly (check refuses a paraphrase)
  pickup    a suggested line the speaker has NOT recorded; the preview plays
            silence under it with a "PICKUP — not recorded" label, so it can
            never pass for source material

plan/hooks.json (schema_version 1):
  {"schema_version": 1, "words": "work/excerpt.words.json", "audio": "raw/excerpt.mp4",
   "variants": [
     {"id": "A", "first_line": {"kind": "recorded", "text": "...", "start": 0.4, "end": 2.1},
      "footage": {"clip": "work/mezz/excerpt.mp4", "in": 0.4},
      "on_screen_text": "EASY RUNS AREN'T EASY", "rationale": "..."},
     ... exactly three ...],
   "previews": {"A": <fingerprint>, ...},        written by preview
   "chosen": {"id": "B", "why": "..."}}          written by choose — the USER's pick

  init     write a three-variant template
  check    shape, recorded-line fidelity, footage exists (exit 1 on any error)
  preview  render the first --seconds of each variant (work/hooks/hook_<id>.mp4),
           a back-to-back compare.mp4 and a compare.png sheet
  choose   record the user's pick and their reason; refuses until the previews
           are current. Never run it for the user.

Exit codes: 0 ok; 1 invalid or refused. JSON on stdout.

Usage:
  hooks.py init --words work/excerpt.words.json --audio raw/excerpt.mp4
  hooks.py check
  hooks.py preview --seconds 3
  hooks.py choose B --why "user: the watch face makes the claim visible"
"""

import argparse
import json
import re
import subprocess
import sys
import tempfile
import textwrap
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from gen_captions import load_words, known_fonts, need, render_card, resolve_font  # noqa: E402
from provenance import file_fp, fp_matches  # noqa: E402

SCHEMA_VERSION = 1
HOOKS = Path("plan/hooks.json")
OUTDIR = Path("work/hooks")
W, H = 540, 960
EPS = 0.02
TEXT_Y, LABEL_Y = 0.22, 0.62
WRAP = 22


class Refused(Exception):
    pass


def norm_words(text):
    return [t for t in (re.sub(r"[^a-z0-9']+", "", w.lower()) for w in text.split()) if t]


def template(words, audio):
    blank = {
        "first_line": {"kind": "recorded", "text": "", "start": None, "end": None},
        "footage": {"clip": "", "in": 0.0},
        "on_screen_text": "",
        "rationale": "",
    }
    return {
        "schema_version": SCHEMA_VERSION,
        "words": words,
        "audio": audio,
        "variants": [{"id": i, **json.loads(json.dumps(blank))} for i in "ABC"],
        "previews": {},
        "chosen": None,
    }


def validate(doc):
    """Errors that make the variants unusable; empty list means valid."""
    errors = []
    if doc.get("schema_version") != SCHEMA_VERSION:
        return [f"schema_version must be {SCHEMA_VERSION}"]
    try:
        words = load_words(doc["words"])
    except (KeyError, OSError, SystemExit) as e:
        return [f"cannot read the transcript {doc.get('words')!r}: {e}"]
    variants = doc.get("variants") or []
    if len(variants) != 3 or len({v.get("id") for v in variants}) != 3:
        errors.append("exactly three variants with distinct ids")
    for v in variants:
        tag = f"variant {v.get('id')}"
        fl = v.get("first_line") or {}
        text = (fl.get("text") or "").strip()
        if not text:
            errors.append(f"{tag}: first_line.text is empty")
        if fl.get("kind") == "recorded":
            s, e = fl.get("start"), fl.get("end")
            if not isinstance(s, (int, float)) or not isinstance(e, (int, float)) or e <= s:
                errors.append(f"{tag}: a recorded line needs start < end from the transcript")
            else:
                spoken = [w for w in words if w["start"] >= s - EPS and w["end"] <= e + EPS]
                if norm_words(text) != norm_words(" ".join(w["text"] for w in spoken)):
                    errors.append(
                        f"{tag}: recorded line does not match the transcript at "
                        f"{s}-{e}s (it says: {' '.join(w['text'] for w in spoken)!r}) — "
                        "use the words as spoken, or mark it a pickup"
                    )
        elif fl.get("kind") == "pickup":
            if fl.get("start") is not None or fl.get("end") is not None:
                errors.append(f"{tag}: a pickup line has no source timing — it was not recorded")
        else:
            errors.append(f"{tag}: first_line.kind must be 'recorded' or 'pickup'")
        foot = v.get("footage") or {}
        if not foot.get("clip") or not Path(foot["clip"]).is_file():
            errors.append(f"{tag}: footage clip {foot.get('clip')!r} not found")
        if not isinstance(foot.get("in", 0), (int, float)) or foot.get("in", 0) < 0:
            errors.append(f"{tag}: footage.in must be seconds >= 0")
        if not isinstance(v.get("on_screen_text", ""), str):
            errors.append(f"{tag}: on_screen_text must be a string (empty for none)")
        if not (v.get("rationale") or "").strip():
            errors.append(f"{tag}: say what this opening tries (rationale)")
    return errors


def run(cmd, label):
    r = subprocess.run(cmd, capture_output=True, text=True)
    if r.returncode != 0:
        raise Refused(f"{label} failed: {r.stderr[-400:]}")


def card_opts():
    magick = need("magick", "install ImageMagick (brew install imagemagick)")
    known = known_fonts(magick)
    font, _ = resolve_font("Helvetica-Bold", "regular", known)
    italic, _ = resolve_font("Helvetica-BoldOblique", "italic", known)
    return {
        "font": font,
        "font_italic": italic,
        "size": 30,
        "fg": "white",
        "accent": "#F26B21",
        "box": "#0F1D2BE6",
        "_scale": W / 1080,
    }


def cards(text, opts, tmp, tag, box=None):
    """One card PNG per wrapped line; returns paths top to bottom."""
    out = []
    for i, line in enumerate(textwrap.wrap(text, WRAP)):
        dst = tmp / f"{tag}_{i}.png"
        render_card(
            {"words": line.split(), "emphasis": []}, dict(opts, box=box or opts["box"]), dst
        )
        out.append(dst)
    return out


def render_variant(doc, v, seconds, opts, tmp):
    fl, foot = v["first_line"], v["footage"]
    dst = OUTDIR / f"hook_{v['id']}.mp4"
    inputs = ["-ss", f"{foot.get('in', 0)}", "-t", f"{seconds}", "-i", foot["clip"]]
    if fl["kind"] == "recorded":
        inputs += ["-ss", f"{fl['start']}", "-t", f"{seconds}", "-i", doc["audio"]]
        audio = "[1:a]apad,atrim=0:{s}[a]".format(s=seconds)
    else:
        inputs += ["-f", "lavfi", "-t", f"{seconds}", "-i", "anullsrc=r=48000:cl=stereo"]
        audio = "[1:a]anull[a]"
    overlays = [(p, TEXT_Y) for p in cards(v.get("on_screen_text") or "", opts, tmp, f"t{v['id']}")]
    if fl["kind"] == "pickup":
        overlays += [
            (p, LABEL_Y)
            for p in cards(
                f"PICKUP, not recorded: {fl['text']}", opts, tmp, f"p{v['id']}", box="#7A1C1CE6"
            )
        ]
    graph = [f"[0:v]scale={W}:{H}:force_original_aspect_ratio=increase,crop={W}:{H},setsar=1[v0]"]
    prev, row = "[v0]", {}
    for k, (png, y) in enumerate(overlays, start=2):
        inputs += ["-i", str(png)]
        n = row.get(y, 0)
        row[y] = n + 1
        graph.append(f"{prev}[{k}:v]overlay=x=(W-w)/2:y=H*{y}+{n}*h*1.15[v{k}]")
        prev = f"[v{k}]"
    graph.append(audio)
    run(
        [
            "ffmpeg",
            "-y",
            "-v",
            "error",
            *inputs,
            "-filter_complex",
            ";".join(graph),
            "-map",
            prev,
            "-map",
            "[a]",
            "-t",
            f"{seconds}",
            "-r",
            "30",
            "-c:v",
            "libx264",
            "-preset",
            "veryfast",
            "-crf",
            "24",
            "-pix_fmt",
            "yuv420p",
            "-c:a",
            "aac",
            "-ar",
            "48000",
            "-ac",
            "2",
            str(dst),
        ],
        f"variant {v['id']}",
    )
    return dst


def compare(paths, opts, tmp):
    """compare.mp4 plays the openings back to back, each labelled; compare.png side by side."""
    labelled = []
    for p in paths:
        vid = p.stem.split("_")[-1]
        lab = cards(f"Opening {vid}", opts, tmp, f"l{vid}")[0]
        out = tmp / f"lab_{vid}.mp4"
        run(
            [
                "ffmpeg",
                "-y",
                "-v",
                "error",
                "-i",
                str(p),
                "-i",
                str(lab),
                "-filter_complex",
                "[0:v][1:v]overlay=x=(W-w)/2:y=H*0.04[v]",
                "-map",
                "[v]",
                "-map",
                "0:a",
                "-c:v",
                "libx264",
                "-preset",
                "veryfast",
                "-crf",
                "24",
                "-c:a",
                "aac",
                str(out),
            ],
            f"label {vid}",
        )
        labelled.append(out)
    lst = tmp / "list.txt"
    lst.write_text("".join(f"file '{p}'\n" for p in labelled))
    run(
        [
            "ffmpeg",
            "-y",
            "-v",
            "error",
            "-f",
            "concat",
            "-safe",
            "0",
            "-i",
            str(lst),
            "-c",
            "copy",
            str(OUTDIR / "compare.mp4"),
        ],
        "compare video",
    )
    ins = []
    for p in labelled:
        ins += ["-ss", "1.0", "-i", str(p)]
    run(
        [
            "ffmpeg",
            "-y",
            "-v",
            "error",
            *ins,
            "-filter_complex",
            "".join(f"[{i}:v]" for i in range(len(labelled))) + f"hstack={len(labelled)}",
            "-frames:v",
            "1",
            str(OUTDIR / "compare.png"),
        ],
        "compare sheet",
    )


def main():
    ap = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
    )
    sub = ap.add_subparsers(dest="cmd", required=True)
    i = sub.add_parser("init")
    i.add_argument("--words", required=True)
    i.add_argument("--audio", required=True)
    sub.add_parser("check")
    p = sub.add_parser("preview")
    p.add_argument("--seconds", type=float, default=3.0)
    c = sub.add_parser("choose")
    c.add_argument("id")
    c.add_argument("--why", required=True, help="the user's reason, in their words")
    a = ap.parse_args()

    try:
        if a.cmd == "init":
            if HOOKS.exists():
                raise Refused(f"{HOOKS} exists — edit it")
            HOOKS.parent.mkdir(parents=True, exist_ok=True)
            HOOKS.write_text(json.dumps(template(a.words, a.audio), indent=2) + "\n")
            print(json.dumps({"ok": True, "out": str(HOOKS)}))
            return
        doc = json.loads(HOOKS.read_text())
        errors = validate(doc)
        if a.cmd == "check":
            print(json.dumps({"ok": not errors, "errors": errors}))
            sys.exit(1 if errors else 0)
        if errors:
            raise Refused("hooks invalid — run check: " + errors[0])
        if a.cmd == "preview":
            if not 0.5 <= a.seconds <= 10:
                raise Refused("--seconds is the opening only: 0.5-10")
            OUTDIR.mkdir(parents=True, exist_ok=True)
            opts = card_opts()
            with tempfile.TemporaryDirectory() as td:
                paths = [render_variant(doc, v, a.seconds, opts, Path(td)) for v in doc["variants"]]
                compare(paths, opts, Path(td))
            doc["previews"] = {v["id"]: file_fp(p) for v, p in zip(doc["variants"], paths)}
            result = {"previews": [str(p) for p in paths], "compare": str(OUTDIR / "compare.mp4")}
        else:
            if a.id not in {v["id"] for v in doc["variants"]}:
                raise Refused(f"no variant {a.id!r}")
            pv = doc.get("previews") or {}
            if len(pv) != 3 or not all(fp_matches(x) for x in pv.values()):
                raise Refused(
                    "the previews are missing or out of date — render and show them "
                    "before recording a choice"
                )
            doc["chosen"] = {"id": a.id, "why": a.why}
            result = {"chosen": a.id}
        HOOKS.write_text(json.dumps(doc, indent=2) + "\n")
        print(json.dumps({"ok": True, **result}))
    except (Refused, OSError, json.JSONDecodeError) as err:
        print(json.dumps({"ok": False, "error": str(err)}))
        sys.exit(1)


if __name__ == "__main__":
    main()

skills

tile.json