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

verify_cut.pyskills/reel-builder/scripts/

#!/usr/bin/env python3
"""Prove a finished cut still says what the plan said it would.

check_cuts.py looks at pictures — black frames, frozen cuts, duration drift.
It cannot tell you that a join ate a word, which is the failure mode every
audio-driven edit in this pipeline can produce: tighten_vo.py trims to a
margin, trim_words.py cuts on word boundaries, and a few frames either way
clips a consonant. The output plays fine and is subtly wrong.

So: re-transcribe the FINISHED file and diff it against the words the plan
expected to survive. A cut that clipped a word fails here instead of shipping.

Reports SKIPPED rather than PASS when no transcription backend is installed —
an unverifiable check must never read as a passing one.

The idea (and the "re-transcribe the output and diff" trick) is borrowed from
yap-editor by Jens Heitmann, MIT licensed.

Usage:
  verify_cut.py work/master.mp4 --words work/take.words.json --cuts work/cuts.json
  verify_cut.py work/master.mp4 --expect "the words that should be there"
"""

import argparse
import json
import re
import shutil
import subprocess
import sys
import tempfile
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  # noqa: E402

MATCH_FLOOR = 0.95  # below this the cut lost or gained real words


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


def result(name, status, detail=""):
    print(f"  {name:18} {status}{f'  ({detail})' if detail else ''}")
    return status


def write_report(out, video, body):
    if out:
        Path(out).parent.mkdir(parents=True, exist_ok=True)
        Path(out).write_text(
            json.dumps({"video": str(video), "video_fp": file_fp(video), **body}, indent=2)
        )


def expected_words(words, keeps):
    """Words from the source transcript that fall inside the kept ranges."""
    out = []
    for w in words:
        for a, b in keeps:
            if w["start"] >= a - 1e-6 and w["end"] <= b + 1e-6:
                out.append(w["text"])
                break
    return out


def transcribe(path):
    """Word list from the finished file, or None if no backend is installed."""
    exe = shutil.which("mlx_whisper") or shutil.which("whisper")
    if not exe:
        return None
    with tempfile.TemporaryDirectory() as td:
        r = subprocess.run(
            [exe, str(path), "--output-format", "json", "--output-dir", td],
            capture_output=True,
            text=True,
        )
        if r.returncode != 0:
            print(f"  transcription failed:\n{r.stderr[-400:]}", file=sys.stderr)
            return None
        got = list(Path(td).glob("*.json"))
        if not got:
            return None
        data = json.loads(got[0].read_text())
    segs = data.get("segments") or []
    text = " ".join(s.get("text", "") for s in segs)
    return [t for t in (norm(x) for x in text.split()) if t]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("video")
    ap.add_argument("--words", help="Word-level transcript of the SOURCE take")
    ap.add_argument("--cuts", help="Cut list from tighten_vo/trim_words --emit-cuts")
    ap.add_argument("--expect", help="Expected text directly, instead of words+cuts")
    ap.add_argument(
        "--out",
        help="Also write the result (PASS/FAIL/SKIPPED) to this JSON "
        "file — pipeline.py reads it to gate the master",
    )
    ap.add_argument(
        "--floor",
        type=float,
        default=MATCH_FLOOR,
        help=f"Similarity below which the cut fails (default {MATCH_FLOOR})",
    )
    args = ap.parse_args()

    video = Path(args.video)
    if not video.exists():
        sys.exit(f"Not found: {video}")

    if args.expect:
        want = [t for t in (norm(x) for x in args.expect.split()) if t]
    elif args.words and args.cuts:
        cuts = json.loads(Path(args.cuts).read_text())
        keeps = [tuple(k) for k in cuts.get("keep", [])]
        if not keeps:
            sys.exit(f"{args.cuts} records no keep ranges.")
        want = [norm(w) for w in expected_words(load_words(args.words), keeps)]
        want = [w for w in want if w]
    else:
        sys.exit("Pass --words with --cuts, or --expect.")

    print(f"Join integrity — {video.name}")
    got = transcribe(video)
    if got is None:
        result("Join integrity", "SKIPPED", "no transcription backend (pip install mlx-whisper)")
        write_report(args.out, video, {"status": "SKIPPED"})
        print(
            "\nSKIPPED is not PASS. The cut is unverified: a join may have "
            "clipped a word and nothing here would know.",
            file=sys.stderr,
        )
        return

    import difflib

    ratio = difflib.SequenceMatcher(a=want, b=got).ratio()
    sm = difflib.SequenceMatcher(a=want, b=got)
    missing, extra = [], []
    for tag, i1, i2, j1, j2 in sm.get_opcodes():
        if tag in ("delete", "replace"):
            missing += want[i1:i2]
        if tag in ("insert", "replace"):
            extra += got[j1:j2]

    status = "PASS" if ratio >= args.floor else "FAIL"
    result("Join integrity", status, f"{ratio:.1%} of {len(want)} expected words")
    if missing:
        print(f"    missing: {' '.join(missing[:12])}{' …' if len(missing) > 12 else ''}")
    if extra:
        print(f"    extra:   {' '.join(extra[:12])}{' …' if len(extra) > 12 else ''}")
    body = {
        "status": status,
        "similarity": round(ratio, 4),
        "expected": len(want),
        "transcribed": len(got),
        "missing": missing[:40],
        "extra": extra[:40],
    }
    print(json.dumps({"video": str(video), **body}, indent=2))
    write_report(args.out, video, body)
    if status == "FAIL":
        print(
            "\nA word went missing at a join. Raise --margin on tighten_vo, "
            "or --breath on trim_words, and re-cut.",
            file=sys.stderr,
        )
        sys.exit(1)


if __name__ == "__main__":
    main()

skills

tile.json