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

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
import json
import subprocess
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import plan_schema  # noqa: E402  — owner of cut_plan.json reads and writes
from provenance import file_fp  # noqa: E402


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 = plan_schema.load_or_exit(args.plan)
    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())
    # hand-authored plans omit total_duration; derive it as render_reel.py does
    planned = plan.get("total_duration") or sum(float(s["duration"]) for s in plan["segments"])
    drift = rendered - planned

    # 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,
        "video_fp": file_fp(args.video),
        "planned_duration": planned,
        "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']} (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()

skills

tile.json