CtrlK
BlogDocsLog inGet started
Tessl Logo

gamussa/reels-producer-skill

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

94

2.36x
Quality

97%

Does it follow best practices?

Impact

85%

2.36x

Average score across 3 eval scenarios

SecuritybySnyk

Low

Low-risk findings worth noting

Overview
Quality
Evals
Security
Files

check_cuts.pyskills/reel-builder/scripts/

#!/usr/bin/env python3
"""QC a rendered reel before showing it to the human.

Checks every cut boundary in the plan:
  - black/near-black frames at a cut (bad trim or empty source region)
  - frozen cut (frame before == frame after -> the "cut" is invisible,
    usually two segments from the same clip region)
  - duration drift between plan and rendered file

Produces:
  - contact sheet PNG: frame pairs (last frame of seg N | first of seg N+1)
    for visual inspection by the agent BEFORE the human sees the preview
  - report JSON with per-cut verdicts

Usage: check_cuts.py plan/cut_plan.json preview/draft_v1.mp4 \
           --out work/qc_v1  (writes qc_v1.png + qc_v1.json)
"""
import argparse, json, subprocess, sys
from pathlib import Path


def run(cmd):
    r = subprocess.run(cmd, capture_output=True, text=True)
    if r.returncode != 0:
        sys.exit(f"ffmpeg failed:\n{r.stderr[-600:]}")
    return r


def frame_stats(video, t, out_png):
    """Grab frame at t; return (mean_luma, saved_path)."""
    run(["ffmpeg", "-y", "-v", "error", "-ss", f"{max(0, t):.3f}", "-i", str(video),
         "-frames:v", "1", "-vf", "scale=270:480", str(out_png)])
    r = subprocess.run(
        ["ffmpeg", "-i", str(out_png), "-vf", "signalstats,metadata=print",
         "-f", "null", "-"], capture_output=True, text=True)
    mean = None
    for line in r.stderr.splitlines():
        if "YAVG" in line:
            mean = float(line.split("=")[-1])
    return mean if mean is not None else -1


# A black frame is always wrong. A frozen cut is a QUESTION: two frames across
# a clean cut on smooth-gimbal or POV footage are legitimately similar, and
# reporting that at the same severity as a real defect trains the reader to
# ignore the whole report.
HARD = ("BLACK_FRAME",)


def severity(verdict):
    """'defect' for something always wrong, 'review' for something to look at."""
    if verdict == "ok":
        return "ok"
    return "defect" if any(h in verdict for h in HARD) else "review"


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("plan")
    ap.add_argument("video")
    ap.add_argument("--out", default="work/qc")
    ap.add_argument("--black-thresh", type=float, default=16.0,
                    help="mean luma below this = black frame")
    ap.add_argument("--frozen-psnr", type=float, default=45.0,
                    help="PSNR across a cut above which the two frames are "
                         "called frozen (default 45). Smooth-gimbal and POV "
                         "footage reads high here on perfectly good cuts — "
                         "raise it rather than distrusting the report.")
    args = ap.parse_args()

    plan = json.loads(Path(args.plan).read_text())
    outbase = Path(args.out)
    outbase.parent.mkdir(parents=True, exist_ok=True)
    tmp = outbase.parent / "_qc_frames"
    tmp.mkdir(exist_ok=True)

    # rendered duration vs plan
    r = subprocess.run(["ffprobe", "-v", "quiet", "-show_entries", "format=duration",
                        "-of", "csv=p=0", args.video], capture_output=True, text=True)
    rendered = float(r.stdout.strip())
    drift = rendered - plan["total_duration"]

    # cut times = cumulative segment durations
    cuts, t = [], 0.0
    for seg in plan["segments"][:-1]:
        t += seg["duration"]
        cuts.append(round(t, 3))

    issues, pairs = [], []
    eps = 1 / 30 / 2  # half a frame
    for i, ct in enumerate(cuts):
        before = tmp / f"cut{i:02d}_before.png"
        after = tmp / f"cut{i:02d}_after.png"
        luma_b = frame_stats(args.video, ct - eps - 1/30, before)
        luma_a = frame_stats(args.video, ct + eps, after)
        verdict = "ok"
        if luma_b < args.black_thresh or luma_a < args.black_thresh:
            verdict = "BLACK_FRAME"
        pairs.append((before, after))
        # frozen-cut check: pixel difference between the two frames
        d = subprocess.run(
            ["ffmpeg", "-i", str(before), "-i", str(after),
             "-lavfi", "psnr", "-f", "null", "-"],
            capture_output=True, text=True)
        psnr = None
        for line in d.stderr.splitlines():
            if "average:" in line:
                try:
                    psnr = float(line.split("average:")[1].split()[0])
                except ValueError:
                    psnr = 99.0  # 'inf' -> identical
        if psnr is None or psnr > args.frozen_psnr:
            verdict = "FROZEN_CUT" if verdict == "ok" else verdict + "+FROZEN"
        issues.append({"cut": i, "time": ct, "luma_before": round(luma_b, 1),
                       "luma_after": round(luma_a, 1),
                       "psnr_across_cut": psnr, "verdict": verdict,
                       "severity": severity(verdict)})

    # contact sheet: stack all pairs into a grid (2 cols per cut)
    inputs, filters = [], []
    for i, (b, a) in enumerate(pairs):
        inputs += ["-i", str(b), "-i", str(a)]
        filters.append(f"[{2*i}][{2*i+1}]hstack[row{i}]")
    if pairs:
        graph = ";".join(filters)
        if len(pairs) > 1:
            graph += ";" + "".join(f"[row{i}]" for i in range(len(pairs))) + \
                     f"vstack=inputs={len(pairs)}[sheet]"
            outmap = "[sheet]"
        else:
            outmap = "[row0]"
        run(["ffmpeg", "-y", "-v", "error"] + inputs +
            ["-filter_complex", graph, "-map", outmap,
             "-frames:v", "1", f"{outbase}.png"])

    report = {"video": args.video, "planned_duration": plan["total_duration"],
              "rendered_duration": round(rendered, 2), "drift_s": round(drift, 2),
              "cuts": issues,
              "problems": [c for c in issues if c["verdict"] != "ok"],
              "defects": [c for c in issues if c["severity"] == "defect"],
              "review": [c for c in issues if c["severity"] == "review"]}
    Path(f"{outbase}.json").write_text(json.dumps(report, indent=2))

    defects, review = report["defects"], report["review"]
    print(f"QC: {len(cuts)} cuts checked, {len(defects)} defect(s), "
          f"{len(review)} to review, duration drift {drift:+.2f}s")
    for c in defects:
        print(f"  DEFECT  cut {c['cut']} @ {c['time']}s: {c['verdict']}")
    for c in review:
        print(f"  review  cut {c['cut']} @ {c['time']}s: {c['verdict']} "
              f"(psnr {c['psnr_across_cut']})")
    if review and not defects:
        print("\nNothing here is necessarily wrong. Frozen-cut flags fire on "
              "legitimately low-motion cuts — gimbal and POV footage especially "
              f"— so look at the sheet before acting. Raise --frozen-psnr above "
              f"{args.frozen_psnr} if this footage flags constantly.")
    print(f"Contact sheet: {outbase}.png  Report: {outbase}.json")
    if abs(drift) > 0.5:
        print(f"WARNING: rendered duration off by {drift:+.2f}s vs plan")


if __name__ == "__main__":
    main()

.mcp.json

tile.json