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

shortlist.pyskills/reel-builder/scripts/

#!/usr/bin/env python3
"""The producer's shortlist: candidate shorts from a long recording, chosen for
complete ideas, not chopped to a duration.

Workflow (references/shortlist-and-hooks.md):
  source recording -> build (candidate pool) -> the agent writes the shortlist
  -> check -> preview -> the USER selects -> promote -> hooks.py -> the normal
  pipeline with its gates.

This script does the deterministic half:
  build    pool of sentence-aligned windows (shorts_from_long.candidates) with
           context/qualifier flags, plus the source's provenance
  check    every shortlist entry is complete, its range sits on word
           boundaries, and its transcript is the recorded words — the script
           writes "transcript" itself so it can never be paraphrased
  preview  a rough low-res clip of an entry's range, for comparing candidates
  select   records the USER's pick (status "selected", with their note)
  promote  turns a selected entry into a reel project: an excerpt of the
           source re-encoded at near-lossless quality (that range plus
           handles: up to HEAD_MAX before the first word and TAIL_MAX into
           the pause after the last, never taking a neighbouring word), a
           provenance file with the handles and "speech_end", its transcript
           re-timed to the excerpt, and a brief pre-filled from the entry

The judgment half — viewer, why it matters, opening / central point / payoff,
the context that must stay, whether it is worth making — is the agent's, and
the selection is the user's. Never run `select` for the user.

plan/shortlist.json (schema_version 1): {"schema_version", "source": {"video":
fingerprint, "words": path, "words_sha256"}, "pool": [...], "shortlist": [entry]}
entry: {"id", "start", "end", "transcript", "viewer", "why_it_matters",
"opening", "central_point", "payoff", "keep_context": [..], "worth": str,
"status": "shortlisted"|"selected"|"rejected", "note", "preview"}

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

Usage:
  shortlist.py build talk.mp4 talk.words.json --out plan/shortlist.json [--min 20 --max 90]
  shortlist.py check plan/shortlist.json
  shortlist.py preview plan/shortlist.json s3
  shortlist.py select plan/shortlist.json s3 --note "user: this one, it lands"
  shortlist.py promote plan/shortlist.json s3 --project ../easy-runs-s3 \
      [--captions yes|no] [--aspect 9:16] [--resolution 1080]

Commands may run in parallel (several previews at once): each applies its own
change to a fresh read of the shortlist under a lock and replaces the file
atomically. preview and promote refuse a source video whose fingerprint no
longer matches the one recorded at build.
  shortlist.py migrate --project ../easy-runs-s3     (owner upgrade of an older provenance record)
"""

import argparse
import contextlib
import fcntl
import json
import os
import re
import subprocess
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from gen_captions import load_words  # noqa: E402
from provenance import file_fp, fp_matches, sha256_file  # noqa: E402
from shorts_from_long import candidates  # noqa: E402

SCHEMA_VERSION = 1
REQUIRED = ("viewer", "why_it_matters", "opening", "central_point", "payoff", "worth")
STATUSES = ("shortlisted", "selected", "rejected")
EPS = 0.02
PREVIEW_W = 540
EXCERPT_CRF = "12"
# Handles around a promoted excerpt, so it never starts or ends on the edge of a
# word: a short head before the first word, and a tail into the pause after the
# last one, stopping HANDLE_GUARD short of the next word.
HEAD_MAX, TAIL_MAX, HANDLE_GUARD = 0.3, 1.2, 0.08
# raw/excerpt.provenance.json, written only by promote (references/state-schema.md)
PROVENANCE_SCHEMA = 2


class Refused(Exception):
    pass


def norm(t):
    return re.sub(r"[^a-z0-9']+", "", t.lower())


def words_in(words, start, end):
    return [w for w in words if w["start"] >= start - EPS and w["end"] <= end + EPS]


def handles(words, start, end, duration):
    """(head, tail) seconds of room around [start, end] without taking a word."""
    before = [w["end"] for w in words if w["start"] < start - EPS and w["end"] <= start + EPS]
    after = [w["start"] for w in words if w["end"] > end + EPS and w["start"] >= end - EPS]
    prev_end = max(before) if before else 0.0
    next_start = min(after) if after else duration
    head = min(HEAD_MAX, start - prev_end - (HANDLE_GUARD if before else 0.0))
    tail = min(TAIL_MAX, next_start - end - (HANDLE_GUARD if after else 0.0))
    return round(max(0.0, head), 3), round(max(0.0, tail), 3)


def media_duration(path):
    r = subprocess.run(
        ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(path)],
        capture_output=True,
        text=True,
    )
    try:
        return float(r.stdout.strip())
    except ValueError:
        raise Refused(f"cannot read the duration of {path} — is it a video file?")


def on_boundaries(words, start, end):
    starts = any(abs(w["start"] - start) <= EPS for w in words)
    ends = any(abs(w["end"] - end) <= EPS for w in words)
    return starts and ends


def check_entries(doc, words):
    """(errors, warnings); fills each entry's transcript and duration from the words."""
    errors, warnings, ids = [], [], set()
    for n, e in enumerate(doc.get("shortlist", []), 1):
        tag = e.get("id") or f"entry {n}"
        if not e.get("id"):
            errors.append(f"{tag}: needs an id")
        elif e["id"] in ids:
            errors.append(f"{tag}: duplicate id")
        ids.add(e.get("id"))
        try:
            start, end = float(e["start"]), float(e["end"])
        except (KeyError, TypeError, ValueError):
            errors.append(f"{tag}: start/end must be numbers")
            continue
        if end <= start:
            errors.append(f"{tag}: end must be after start")
            continue
        if not on_boundaries(words, start, end):
            errors.append(
                f"{tag}: {start}-{end}s does not start and end on word boundaries — "
                "snap it to the transcript so no word is cut"
            )
            continue
        e["transcript"] = " ".join(w["text"] for w in words_in(words, start, end))
        e["duration"] = round(end - start, 2)
        status = e.get("status", "shortlisted")
        if status not in STATUSES:
            errors.append(f"{tag}: status must be one of {', '.join(STATUSES)}")
        if status == "rejected":
            if not (e.get("note") or "").strip():
                errors.append(f'{tag}: say why it was rejected ("note")')
            continue
        for f in REQUIRED:
            if not (isinstance(e.get(f), str) and e[f].strip()):
                errors.append(f"{tag}: {f} is empty")
        if not isinstance(e.get("keep_context"), list):
            errors.append(f"{tag}: keep_context must be a list (empty when nothing must stay)")
        if not e.get("preview"):
            warnings.append(f"{tag}: no rough preview yet (shortlist.py preview)")
    return errors, warnings


@contextlib.contextmanager
def locked(path):
    """Exclusive lock on <shortlist>.lock: concurrent commands (parallel
    previews) serialize their read-modify-write instead of overwriting each
    other's entries. Slow work (encoding) runs outside it."""
    lock = Path(f"{path}.lock")
    with open(lock, "w") as fh:
        fcntl.flock(fh, fcntl.LOCK_EX)
        try:
            yield
        finally:
            fcntl.flock(fh, fcntl.LOCK_UN)


def save(path, doc):
    """Atomic replace: a reader never sees a half-written shortlist, and a
    failed write leaves no temporary file behind."""
    tmp = Path(f"{path}.tmp.{os.getpid()}")
    try:
        tmp.write_text(json.dumps(doc, indent=2) + "\n")
        tmp.replace(path)
    finally:
        tmp.unlink(missing_ok=True)


def update(path, mutate):
    """Re-read under the lock, apply this command's change, write atomically."""
    with locked(path):
        doc = load(path)
        result = mutate(doc)
        save(path, doc)
    return result


def load(path):
    doc = json.loads(Path(path).read_text())
    if doc.get("schema_version") != SCHEMA_VERSION:
        raise Refused(f"{path}: schema_version must be {SCHEMA_VERSION}")
    return doc


def source_words(doc):
    src = doc.get("source") or {}
    wpath = src.get("words")
    if not wpath or not Path(wpath).is_file():
        raise Refused(f"transcript {wpath!r} is missing")
    if sha256_file(wpath) != src.get("words_sha256"):
        raise Refused(f"{wpath} changed since the shortlist was built — rebuild it")
    return load_words(wpath)


def entry(doc, entry_id):
    for e in doc.get("shortlist", []):
        if e.get("id") == entry_id:
            return e
    raise Refused(f"no shortlist entry {entry_id!r}")


def ffmpeg(cmd, label):
    try:
        r = subprocess.run(["ffmpeg", "-y", "-v", "error", *cmd], capture_output=True, text=True)
    except FileNotFoundError:
        raise Refused("ffmpeg not found — install it (brew install ffmpeg)") from None
    if r.returncode != 0:
        raise Refused(f"{label} failed: {r.stderr[-400:]}")


def build(video, words_path, out, min_s, max_s):
    words = load_words(words_path)
    pool = candidates(words, min_s, max_s)
    doc = {
        "schema_version": SCHEMA_VERSION,
        "source": {
            "video": file_fp(video),
            "words": str(words_path),
            "words_sha256": sha256_file(words_path),
        },
        "pool": [{"pool_id": f"p{n}", **c} for n, c in enumerate(pool, 1)],
        "shortlist": [],
    }
    Path(out).parent.mkdir(parents=True, exist_ok=True)
    with locked(out):  # a rebuild never races a locked update
        save(out, doc)
    return doc


def cut_from(doc, e):
    """What a preview of entry e is cut from: its range and the source video."""
    return (e["start"], e["end"], doc["source"].get("video"))


def attach_preview(fresh, entry_id, snapshot, out):
    """Record a preview on the CURRENT shortlist, only if the entry and source
    it was cut from are unchanged (the shortlist may have moved while encoding)."""
    current = entry(fresh, entry_id)
    if cut_from(fresh, current) != snapshot:
        raise Refused(f"{entry_id} or its source changed while previewing — run preview again")
    current["preview"] = str(out)


def record_selection(fresh, entry_id, snapshot, note):
    """Record the user's pick on the CURRENT shortlist, only for the entry they
    were shown: same range, same source, and still valid there."""
    current = entry(fresh, entry_id)
    if cut_from(fresh, current) != snapshot:
        raise Refused(
            f"{entry_id} or its source changed since it was shown — check it and ask the user again"
        )
    errors, _ = check_entries(fresh, source_words(fresh))
    mine = [x for x in errors if x.startswith(f"{entry_id}:")]
    if mine:
        raise Refused(mine[0])
    current["status"], current["note"] = "selected", note


def source_video(doc):
    """The recorded source, only while it is the file the shortlist was built
    from: a replaced file would get the approved ranges cut from other footage."""
    fp = doc["source"].get("video") or {}
    video = fp.get("path")
    if not video or not Path(video).is_file():
        raise Refused(f"source video {video!r} is missing")
    if not fp_matches(fp):
        raise Refused(
            f"{video} changed since the shortlist was built — rebuild it "
            f"(shortlist.py build) before previewing or promoting"
        )
    return video


def preview(doc, e, outdir="work/shortlist"):
    video = source_video(doc)
    out = Path(outdir) / f"{e['id']}.mp4"
    out.parent.mkdir(parents=True, exist_ok=True)
    ffmpeg(
        [
            "-ss",
            f"{e['start']}",
            "-to",
            f"{e['end']}",
            "-i",
            video,
            "-vf",
            f"scale={PREVIEW_W}:-2",
            "-c:v",
            "libx264",
            "-preset",
            "veryfast",
            "-crf",
            "28",
            "-c:a",
            "aac",
            "-b:a",
            "96k",
            str(out),
        ],
        "preview",
    )
    return out


def promote(doc, e, project, words, captions=None, aspect="9:16", resolution="1080"):
    """A reel project for a selected entry: excerpt + provenance + transcript + brief."""
    if e.get("status") != "selected":
        raise Refused(
            f"{e['id']} is {e.get('status', 'shortlisted')!r} — only an entry the "
            "user selected can be promoted"
        )
    video = source_video(doc)
    proj = Path(project)
    if (proj / "state.json").exists():
        raise Refused(f"{proj} is already a reel project")
    proj.mkdir(parents=True, exist_ok=True)
    init = [
        sys.executable,
        str(Path(__file__).with_name("pipeline.py")),
        "init",
        "--mode",
        "talking-head",
        "--target-duration",
        f"{e['duration']:g}",
        "--aspect",
        aspect,
        "--resolution",
        resolution,
    ]
    if captions:
        init += ["--captions", captions]
    r = subprocess.run(init, cwd=proj, capture_output=True, text=True)
    if r.returncode != 0:
        raise Refused(f"pipeline init failed: {r.stderr[-300:]}")
    head, tail = handles(words, e["start"], e["end"], media_duration(video))
    x0, x1 = round(e["start"] - head, 3), round(e["end"] + tail, 3)
    excerpt = proj / "raw" / "excerpt.mp4"
    ffmpeg(
        [
            "-ss",
            f"{x0}",
            "-to",
            f"{x1}",
            "-i",
            video,
            "-c:v",
            "libx264",
            "-preset",
            "slow",
            "-crf",
            EXCERPT_CRF,
            "-pix_fmt",
            "yuv420p",
            "-c:a",
            "aac",
            "-b:a",
            "320k",
            str(excerpt),
        ],
        "excerpt",
    )
    (proj / "raw" / "excerpt.provenance.json").write_text(
        json.dumps(
            {
                "schema_version": PROVENANCE_SCHEMA,
                "source": doc["source"]["video"],
                "start": e["start"],
                "end": e["end"],
                "excerpt_start": x0,
                "excerpt_end": x1,
                "handles": {"head": head, "tail": tail},
                "speech_end": round(e["end"] - x0, 3),
                "shortlist_id": e["id"],
                "transcript": e["transcript"],
            },
            indent=2,
        )
        + "\n"
    )
    shifted = [
        {"word": w["text"], "start": round(w["start"] - x0, 3), "end": round(w["end"] - x0, 3)}
        for w in words_in(words, e["start"], e["end"])
    ]
    (proj / "work" / "excerpt.words.json").write_text(json.dumps(shifted, indent=1) + "\n")
    (proj / "plan" / "brief.json").write_text(
        json.dumps(
            {
                "schema_version": 1,
                "viewer": e["viewer"],
                "need": e["why_it_matters"],
                "promise": e["central_point"],
                "evidence": [f"recorded excerpt {e['start']}-{e['end']}s"],
                "response": "",
                "platform": "",
                "structure": "",
                "duration": {"target": e["duration"], "basis": "the complete idea's own length"},
            },
            indent=2,
        )
        + "\n"
    )
    return proj


def migrate(project):
    """Owner migration of raw/excerpt.provenance.json to PROVENANCE_SCHEMA.

    A version 1 record (no schema_version) describes an excerpt cut exactly at
    start-end, so the upgrade is exact: zero handles, excerpt_start = start,
    speech_end = end - start. Only the record is rewritten; the media is not
    touched. Re-promote the entry into a new project for real handles.
    """
    path = Path(project) / "raw" / "excerpt.provenance.json"
    rec = json.loads(path.read_text())
    version = rec.get("schema_version", 1)
    if version == PROVENANCE_SCHEMA:
        return {"migrated": False, "schema_version": version}
    if version != 1:
        raise Refused(
            f"{path} is schema_version {version}, newer than this shortlist.py "
            f"reads — update the skill"
        )
    start, end = float(rec["start"]), float(rec["end"])
    rec.update(
        {
            "schema_version": PROVENANCE_SCHEMA,
            "excerpt_start": start,
            "excerpt_end": end,
            "handles": {"head": 0.0, "tail": 0.0},
            "speech_end": round(end - start, 3),
        }
    )
    tmp = path.with_name(path.name + ".tmp")
    tmp.write_text(json.dumps(rec, indent=2) + "\n")
    tmp.replace(path)
    return {"migrated": True, "schema_version": PROVENANCE_SCHEMA, "from": 1}


def main():
    ap = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
    )
    sub = ap.add_subparsers(dest="cmd", required=True)
    b = sub.add_parser("build")
    b.add_argument("video")
    b.add_argument("words")
    b.add_argument("--out", default="plan/shortlist.json")
    b.add_argument("--min", type=float, default=20)
    b.add_argument("--max", type=float, default=90)
    c = sub.add_parser("check")
    c.add_argument("shortlist")
    for name in ("preview", "select", "promote"):
        p = sub.add_parser(name)
        p.add_argument("shortlist")
        p.add_argument("id")
        if name == "select":
            p.add_argument("--note", required=True, help="the user's words for the pick")
        if name == "promote":
            p.add_argument("--project", required=True)
            p.add_argument(
                "--captions",
                choices=("yes", "no"),
                help="the user's Step 1 answer, recorded at init",
            )
            p.add_argument("--aspect", choices=("9:16", "16:9", "1:1"), default="9:16")
            p.add_argument("--resolution", choices=("1080", "4k"), default="1080")
    m = sub.add_parser("migrate", help="upgrade a promoted project's excerpt provenance record")
    m.add_argument("--project", required=True)
    a = ap.parse_args()

    try:
        if a.cmd == "migrate":
            print(json.dumps({"ok": True, **migrate(a.project)}))
            return
        if a.cmd == "build":
            doc = build(a.video, a.words, a.out, a.min, a.max)
            print(
                json.dumps(
                    {
                        "ok": True,
                        "out": a.out,
                        "pool": len(doc["pool"]),
                        "unflagged": sum(1 for p in doc["pool"] if not p["flags"]),
                    }
                )
            )
            return
        if a.cmd == "check":
            # validate the same snapshot it writes: everything under the lock
            def validate_and_record(fresh):
                return check_entries(fresh, source_words(fresh)) + (
                    len(fresh.get("shortlist", [])),
                )

            errors, warnings, entries = update(a.shortlist, validate_and_record)
            print(
                json.dumps(
                    {"ok": not errors, "errors": errors, "warnings": warnings, "entries": entries}
                )
            )
            for err in errors:
                print(f"shortlist.py check: {err}", file=sys.stderr)
            sys.exit(1 if errors else 0)
        doc = load(a.shortlist)
        words = source_words(doc)
        errors, warnings = check_entries(doc, words)
        e = entry(doc, a.id)
        if a.cmd == "preview":
            # comparing candidates comes before writing them up: only this range must be valid
            mine = [x for x in errors if x.startswith(f"{e['id']}:") and "boundar" in x]
            if mine or "transcript" not in e:
                raise Refused(mine[0] if mine else f"{e['id']}: invalid range — run check")
            out = preview(doc, e)  # the slow part, outside the lock
            snapshot = cut_from(doc, e)
            update(a.shortlist, lambda fresh: attach_preview(fresh, a.id, snapshot, out))
            result = {"preview": str(out)}
        elif errors:
            raise Refused("shortlist invalid — run check: " + errors[0])
        elif a.cmd == "select":
            update(
                a.shortlist, lambda fresh: record_selection(fresh, a.id, cut_from(doc, e), a.note)
            )
            result = {"selected": e["id"]}
        else:
            result = {
                "project": str(
                    promote(doc, e, a.project, words, a.captions, a.aspect, a.resolution)
                )
            }
        print(json.dumps({"ok": True, **result}))
    except (Refused, OSError, json.JSONDecodeError, KeyError) as err:
        print(json.dumps({"ok": False, "error": str(err)}))
        print(f"shortlist.py {a.cmd} failed: {err}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()

skills

tile.json