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

qa_render.pyskills/reel-builder/scripts/

#!/usr/bin/env python3
"""Every-frame QA of a rendered reel — catch what a cut-boundary check cannot.

check_cuts.py looks at the two frames either side of each planned cut. This
looks at EVERY frame, so it finds what happens inside a segment:

  - black frames            a gap, a bad trim, an empty source region (defect)
  - white frames            an unplanned flash, a blown exposure (review)
  - frozen spans            12+ frames with no change: a stalled Ken Burns, a
                            Hyperframes seek freeze, a hold that reads as a
                            hang (review)
  - pops                    a single-frame jump in an otherwise smooth stretch:
                            a dropped frame, a mid-segment cut nobody planned
                            (review)
  - mid-reel audio silences a VO join that dropped out (review)

Planned effects are not flagged: a black or white run of at most FX_FRAMES that
touches a planned cut is a `transitions.py` dip or flash, a frame-to-frame
jump at a planned cut is the cut, and the plan's closing picture fade
(`fade_out` with `video`) may end on black. Without a plan every cut reads as a pop, so
pass the plan whenever there is one.

It also measures each segment in numbers — median luma, 10th/90th percentile
luma, saturation, motion — which is what references/look-match.md compares
against a reference reel.

Writes <out>.json and contact sheets <out>_sheets/sheet_NNN.png (60 frames
each, 10 x 6, row-major; frame F is cell F % 60 of sheet F // 60). Every flag in
the report names its sheet and cell, so open only those.

Exit codes: 0 = no defect, 1 = at least one defect, 2 = could not analyse
(ffmpeg/ffprobe missing or failed, unreadable plan).

Usage:
  qa_render.py work/master.mp4 --plan plan/cut_plan.json --out work/qa_master
  qa_render.py reference.mp4 --out work/qa_reference      # measure a reference
  qa_render.py work/master.mp4 --planned 130-134,1131-1137
"""

import argparse
import json
import shutil
import statistics
import subprocess
import sys
import tempfile
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
from render_reel import end_fade  # noqa: E402

ANALYSIS_W, ANALYSIS_H = 180, 320  # per-frame stats are taken at this size
BLACK_YAVG = 20.0  # tv-range black is 16
WHITE_YAVG = 230.0  # tv-range white is 235
FROZEN_DIFF = 0.02  # mean abs luma change per frame; a static hold measures ~0.002,
# a 10 s Ken Burns push at 10 % never drops below ~0.05
FROZEN_MIN = 12  # frames; shorter freezes do not read as a hang
POP_RATIO = 3.0  # a jump this many times the local median ...
POP_FLOOR = 1.0  # ... plus this, in luma levels, is a pop
POP_WINDOW = 8  # frames either side for the local median
CUT_SLACK = 3  # frames either side of a planned cut treated as the cut
FX_FRAMES = 6  # longest black/white run accepted as a planned dip/flash
SILENCE_DB = -45
SILENCE_MIN = 0.3  # seconds
EDGE_S = 0.2  # silence this close to either end is a lead-in/out, not a gap
SHEET_COLS, SHEET_ROWS = 10, 6
SHEET_TILE = (108, 192)
STAT_KEYS = ("YAVG", "YLOW", "YHIGH", "SATAVG")


class AnalysisError(Exception):
    pass


def run(cmd):
    try:
        r = subprocess.run(cmd, capture_output=True, text=True)
    except FileNotFoundError:
        raise AnalysisError(f"{cmd[0]} not found — install ffmpeg (brew install ffmpeg)") from None
    if r.returncode != 0:
        raise AnalysisError(f"{cmd[0]} failed:\n{r.stderr[-600:]}")
    return r


def probe(video):
    r = run(
        [
            "ffprobe",
            "-v",
            "error",
            "-show_entries",
            "stream=codec_type,width,height,r_frame_rate:format=duration",
            "-of",
            "json",
            str(video),
        ]
    )
    info = json.loads(r.stdout)
    v = next((s for s in info["streams"] if s["codec_type"] == "video"), None)
    if v is None:
        raise AnalysisError(f"{video} has no video stream")
    num, den = (int(x) for x in v["r_frame_rate"].split("/"))
    return {
        "width": v["width"],
        "height": v["height"],
        "fps": num / den,
        "duration": float(info["format"]["duration"]),
        "has_audio": any(s["codec_type"] == "audio" for s in info["streams"]),
    }


def parse_metadata(text):
    """ffmpeg `metadata=print` output -> list of {key: value} per frame, in order."""
    frames = []
    for line in text.splitlines():
        if line.startswith("frame:"):
            frames.append({})
        elif "=" in line and frames:
            key, _, val = line.rpartition("=")
            short = key.rsplit(".", 1)[-1]
            if short in STAT_KEYS:
                frames[-1][short] = float(val)
    return frames


def frame_stats(video, workdir):
    """Per-frame signal stats, and per-pair luma difference (diff[i] = |f[i+1] - f[i]|)."""
    s_txt, d_txt = workdir / "stats.txt", workdir / "diff.txt"
    graph = (
        f"[0:v]scale={ANALYSIS_W}:{ANALYSIS_H},split[a][b];"
        f"[a]signalstats,metadata=print:file={s_txt}[o1];"
        f"[b]format=gray,tblend=all_mode=difference,signalstats,"
        f"metadata=print:file={d_txt}[o2]"
    )
    run(
        [
            "ffmpeg",
            "-v",
            "error",
            "-i",
            str(video),
            "-filter_complex",
            graph,
            "-map",
            "[o1]",
            "-f",
            "null",
            "-",
            "-map",
            "[o2]",
            "-f",
            "null",
            "-",
        ]
    )
    stats = parse_metadata(s_txt.read_text())
    diff = [f["YAVG"] for f in parse_metadata(d_txt.read_text())]
    return stats, diff


def runs(flags):
    """Indices where flags is true -> [(first, last)] inclusive runs."""
    out, start = [], None
    for i, f in enumerate(flags):
        if f and start is None:
            start = i
        elif not f and start is not None:
            out.append((start, i - 1))
            start = None
    if start is not None:
        out.append((start, len(flags) - 1))
    return out


def near_cut(first, last, cuts):
    return any(first - CUT_SLACK <= c <= last + CUT_SLACK for c in cuts)


def parse_ranges(spec):
    out = []
    for part in filter(None, (p.strip() for p in (spec or "").split(","))):
        a, _, b = part.partition("-")
        out.append((int(a), int(b or a)))
    return out


def plan_cuts(plan, fps):
    """Frame index of the first frame of every segment after the first."""
    cuts, t = [], 0.0
    for seg in plan["segments"][:-1]:
        t += float(seg["duration"])
        cuts.append(round(t * fps))
    return cuts


def plan_fades(plan, fps):
    """Frame range of the plan's closing picture fade ("fade_out": {"video":
    true}), which ends on black by design: planned, never a black defect."""
    total = plan.get("total_duration") or sum(float(s["duration"]) for s in plan["segments"])
    st, d, video = end_fade(plan, total)
    if not (video and d > 0):
        return []
    return [(round(st * fps), round(total * fps))]


def where(frame):
    return {
        "frame": frame,
        "sheet": frame // (SHEET_COLS * SHEET_ROWS),
        "cell": frame % (SHEET_COLS * SHEET_ROWS),
    }


def detect(stats, diff, fps, cuts=(), planned=(), fades=()):
    """Return (defects, review) lists. Pure: no I/O, so tests drive it directly.

    `fades` are closing picture fades: black is expected only INSIDE one, so a
    black run is exempt only when it lies wholly within a fade range."""

    def is_planned(a, b):
        return any(pa <= b and a <= pb for pa, pb in planned)

    def in_fade(a, b):
        return any(fa <= a and b <= fb for fa, fb in fades)

    defects, review = [], []
    luma = [f.get("YAVG", 0.0) for f in stats]

    for kind, flags in (
        ("black", [y < BLACK_YAVG for y in luma]),
        ("white", [y > WHITE_YAVG for y in luma]),
    ):
        for a, b in runs(flags):
            length = b - a + 1
            if (
                is_planned(a, b)
                or (length <= FX_FRAMES and near_cut(a, b, cuts))
                or (kind == "black" and in_fade(a, b))
            ):
                continue
            item = {
                **where(a),
                "kind": kind,
                "last_frame": b,
                "frames": length,
                "time": round(a / fps, 3),
            }
            (defects if kind == "black" else review).append(item)

    for a, b in runs([d < FROZEN_DIFF for d in diff]):
        held = b - a + 2  # n small diffs span n + 1 identical frames
        if held >= FROZEN_MIN and not is_planned(a, b + 1):
            review.append(
                {
                    **where(a),
                    "kind": "frozen",
                    "last_frame": b + 1,
                    "frames": held,
                    "time": round(a / fps, 3),
                }
            )

    for i, d in enumerate(diff):
        lo, hi = max(0, i - POP_WINDOW), min(len(diff), i + POP_WINDOW + 1)
        local = statistics.median(diff[lo:hi])
        frame = i + 1  # the frame that jumped
        if (
            d > POP_RATIO * local + POP_FLOOR
            and not near_cut(frame, frame, cuts)
            and not is_planned(frame, frame)
        ):
            review.append(
                {
                    **where(frame),
                    "kind": "pop",
                    "jump": round(d, 2),
                    "local_median": round(local, 2),
                    "time": round(frame / fps, 3),
                }
            )

    review.sort(key=lambda r: r["frame"])
    return defects, review


def segment_stats(stats, diff, bounds):
    """Median look numbers per [a, b) frame range."""
    out = []
    for i, (a, b) in enumerate(bounds):
        chunk = stats[a:b]
        if not chunk:
            continue
        row = {"segment": i, "first_frame": a, "last_frame": b - 1}
        for key in STAT_KEYS:
            vals = [f[key] for f in chunk if key in f]
            row[key.lower()] = round(statistics.median(vals), 2) if vals else None
        motion = diff[a : max(a, b - 1)]
        row["motion"] = round(statistics.median(motion), 3) if motion else None
        out.append(row)
    return out


def silences(video, duration):
    r = run(
        [
            "ffmpeg",
            "-v",
            "info",
            "-i",
            str(video),
            "-map",
            "0:a:0",
            "-af",
            f"silencedetect=n={SILENCE_DB}dB:d={SILENCE_MIN}",
            "-f",
            "null",
            "-",
        ]
    )
    gaps, start = [], None
    for line in r.stderr.splitlines():
        if "silence_start:" in line:
            start = float(line.split("silence_start:")[1].split()[0])
        elif "silence_end:" in line and start is not None:
            end = float(line.split("silence_end:")[1].split()[0])
            if start > EDGE_S and end < duration - EDGE_S:
                gaps.append({"kind": "silence", "start": round(start, 3), "end": round(end, 3)})
            start = None
    return gaps


def write_sheets(video, sheet_dir):
    sheet_dir.mkdir(parents=True, exist_ok=True)
    w, h = SHEET_TILE
    run(
        [
            "ffmpeg",
            "-y",
            "-v",
            "error",
            "-i",
            str(video),
            "-vf",
            f"scale={w}:{h},tile={SHEET_COLS}x{SHEET_ROWS}",
            "-fps_mode",
            "passthrough",
            "-start_number",
            "0",
            str(sheet_dir / "sheet_%03d.png"),
        ]
    )


def main():
    ap = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
    )
    ap.add_argument("video")
    ap.add_argument("--plan", help="cut_plan.json: exempts planned cuts and reports per segment")
    ap.add_argument("--planned", help="extra planned frame ranges, e.g. 130-134,600-606")
    ap.add_argument("--out", default="work/qa")
    ap.add_argument("--no-sheets", action="store_true", help="skip contact sheets")
    a = ap.parse_args()

    out = Path(a.out)
    out.parent.mkdir(parents=True, exist_ok=True)
    try:
        info = probe(a.video)
        plan = plan_schema.load(a.plan) if a.plan else None
        cuts = plan_cuts(plan, info["fps"]) if plan else []
        with tempfile.TemporaryDirectory() as td:
            stats, diff = frame_stats(a.video, Path(td))
        planned = parse_ranges(a.planned)
        fades = plan_fades(plan, info["fps"]) if plan else []
        defects, review = detect(stats, diff, info["fps"], cuts, planned, fades)
        if info["has_audio"]:
            review += silences(a.video, info["duration"])
        edges = [0] + cuts + [len(stats)]
        segments = segment_stats(stats, diff, list(zip(edges, edges[1:])))
        sheet_dir = Path(f"{out}_sheets")
        if not a.no_sheets:
            if sheet_dir.exists():
                shutil.rmtree(sheet_dir)
            write_sheets(a.video, sheet_dir)
    except (AnalysisError, OSError, ValueError, KeyError, plan_schema.PlanError) as e:
        print(f"qa_render: {e}", file=sys.stderr)
        sys.exit(2)

    report = {
        "video": a.video,
        "video_fp": file_fp(a.video),
        **info,
        "frames": len(stats),
        "defects": defects,
        "review": review,
        "segments": segments,
        "sheets": None if a.no_sheets else str(sheet_dir),
    }
    Path(f"{out}.json").write_text(json.dumps(report, indent=2))

    print(
        f"{len(stats)} frames @ {info['fps']:g} fps, {info['width']}x{info['height']}: "
        f"{len(defects)} defect(s), {len(review)} to review -> {out}.json"
    )
    for item in defects + review:
        sev = "DEFECT" if item in defects else "review"
        loc = (
            f"frame {item['frame']} (sheet {item['sheet']:03d} cell {item['cell']})"
            if "frame" in item
            else f"{item['start']}-{item['end']}s"
        )
        extra = f", {item['frames']} frames" if "frames" in item else ""
        print(f"  {sev:6} {item['kind']:8} {loc}{extra}")
    sys.exit(1 if defects else 0)


if __name__ == "__main__":
    main()

skills

tile.json