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

export_variants.pyskills/reel-builder/scripts/

#!/usr/bin/env python3
"""Export platform variants from the master render.

Vertical masters (9:16) go to the short-form platforms:
  tiktok    - CRF 19, loudness -14 LUFS
  ig_reels  - CRF 18, loudness -14 LUFS (IG recompresses hard; feed it quality)
  yt_shorts - CRF 18, loudness -14 LUFS, BT.709 tags explicit
  linkedin  - CRF 18, loudness -14 LUFS (also written for 16:9 masters)

A square master (1:1) goes to the same three: each accepts 1:1 as-is (see
check_export.py PLATFORMS). A landscape master (16:9) is not a reel. Those
targets are skipped and a single `youtube` variant is written instead —
exporting a 16:9 cut as a Short would letterbox it into a vertical frame.
DELIVERABLES is the one table of what each aspect produces; pipeline.py reads
it to know when exporting is complete.

Writes <outdir>/manifest.json: the master's fingerprint and each file written,
so a re-rendered master makes the exports stale (references/state-schema.md).

Also grabs a thumbnail JPEG at --thumb-at seconds, and — when a Gemini API
key is present (GEMINI_API_KEY / GOOGLE_AI_API_KEY / GOOGLE_API_KEY) — asks
stylize_thumbnail.py for sport-magazine variants (modern + 80s) so the human
can pick a cover from all three. Styled thumbs are a bonus: any failure there
warns and continues, never blocks the export.

Usage: export_variants.py work/master.mp4 --outdir exports/ --thumb-at 1.5 \
           [--thumb-text "HOOK LINE"] [--no-stylize]
"""

import argparse
import json
import os
import subprocess
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from ffsafe import loudnorm_filter, measure_loudness, probe_field  # noqa: E402
from provenance import file_fp  # noqa: E402

VERTICAL = {
    "tiktok": {"crf": "19"},
    "ig_reels": {"crf": "18"},
    "yt_shorts": {"crf": "18"},
    "linkedin": {"crf": "18"},  # LinkedIn plays 9:16, 1:1 and 16:9 natively
}
LANDSCAPE = {"youtube": {"crf": "18"}, "linkedin": {"crf": "18"}}
DELIVERABLES = {"9:16": VERTICAL, "1:1": VERTICAL, "16:9": LANDSCAPE}
# Output-level -color_primaries/-color_trc are ignored when the decoded frames
# carry "unknown" (measured on ffmpeg 8.x: exports came out bt709/unknown/unknown);
# stamping the frames themselves is what makes the tags stick.
TAG_BT709 = "setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709"
SHAPES = {"9:16": "vertical", "1:1": "square", "16:9": "landscape"}
MANIFEST_SCHEMA = 1


def master_dims(path):
    w, h = probe_field(path, "stream=width"), probe_field(path, "stream=height")
    if w is None or h is None:
        sys.exit(f"Cannot read dimensions from {path} — is it a video file ffprobe can open?")
    return int(w), int(h)


def aspect_of(w, h):
    return "9:16" if h > w else ("1:1" if h == w else "16:9")


def deliverable_names(aspect):
    """Export file stems for a project aspect — the contract pipeline.py checks."""
    return list(DELIVERABLES[aspect])


def platforms_for(w, h):
    """Short-form targets for vertical and square masters; youtube for landscape."""
    a = aspect_of(w, h)
    return DELIVERABLES[a], SHAPES[a]


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


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("master")
    ap.add_argument("--outdir", default="exports")
    ap.add_argument("--thumb-at", type=float, default=1.5)
    ap.add_argument(
        "--captioned",
        metavar="MASTER",
        help="Captioned master (gen_captions.py burn): also writes "
        "<platform>_captioned.mp4, so both clean and captioned ship",
    )
    ap.add_argument(
        "--srt", help="Caption sidecar (gen_captions.py srt), copied to <outdir>/captions.srt"
    )
    ap.add_argument(
        "--thumb-text", help="Cover headline for the stylized thumbnails (magazine-cover mode)"
    )
    ap.add_argument(
        "--no-stylize",
        action="store_true",
        help="Skip Nano Banana thumbnail styling even if an API key is present",
    )
    args = ap.parse_args()

    outdir = Path(args.outdir)
    outdir.mkdir(parents=True, exist_ok=True)

    w, h = master_dims(args.master)
    platforms, shape = platforms_for(w, h)
    print(f"Master is {w}x{h} ({shape}) -> {', '.join(platforms)}\n", flush=True)

    # write to .tmp.mp4 and rename on success so a partial export can never
    # be mistaken for a deliverable
    # One analysis pass on the master, reused for every platform: the
    # second pass then applies a single linear gain instead of loudnorm's
    # dynamic mode, which audibly pumps on speech.
    measured = measure_loudness(args.master)
    if measured is None:
        print(
            "WARNING: loudness analysis pass failed — falling back to "
            "single-pass loudnorm, which can pump on speech",
            file=sys.stderr,
        )
    for name, cfg in platforms.items():
        dst = outdir / f"{name}.mp4"
        tmp = outdir / f"{name}.tmp.mp4"
        print(f"Exporting {name}...", flush=True)
        run(
            [
                "ffmpeg",
                "-y",
                "-i",
                args.master,
                "-c:v",
                "libx264",
                "-preset",
                "medium",
                "-crf",
                cfg["crf"],
                "-profile:v",
                "high",
                "-level",
                "4.1",
                "-pix_fmt",
                "yuv420p",
                "-vf",
                TAG_BT709,
                "-colorspace",
                "bt709",
                "-color_primaries",
                "bt709",
                "-color_trc",
                "bt709",
                "-c:a",
                "aac",
                "-b:a",
                "192k",
                "-ar",
                "48000",
                "-af",
                loudnorm_filter(-14, -1.0, 11, measured),
                "-movflags",
                "+faststart",
                str(tmp),
            ],
            name,
        )
        tmp.rename(dst)

    # Read every deliverable back against its platform. Encoding to a spec
    # and meeting it are different claims; only the second is worth reporting.
    check = Path(__file__).resolve().parent / "check_export.py"
    written = [str(outdir / f"{name}.mp4") for name in platforms]
    if args.captioned:
        for name, cfg in platforms.items():
            dst, tmp = outdir / f"{name}_captioned.mp4", outdir / f"{name}_captioned.tmp.mp4"
            print(f"Exporting {name} (captioned)...", flush=True)
            run(
                [
                    "ffmpeg",
                    "-y",
                    "-i",
                    args.captioned,
                    "-c:v",
                    "libx264",
                    "-preset",
                    "medium",
                    "-crf",
                    cfg["crf"],
                    "-profile:v",
                    "high",
                    "-level",
                    "4.1",
                    "-pix_fmt",
                    "yuv420p",
                    "-vf",
                    TAG_BT709,
                    "-colorspace",
                    "bt709",
                    "-color_primaries",
                    "bt709",
                    "-color_trc",
                    "bt709",
                    "-c:a",
                    "aac",
                    "-b:a",
                    "192k",
                    "-ar",
                    "48000",
                    "-af",
                    loudnorm_filter(-14, -1.0, 11, measured),
                    "-movflags",
                    "+faststart",
                    str(tmp),
                ],
                f"{name} captioned",
            )
            tmp.rename(dst)
            written.append(str(dst))
    sidecar = None
    if args.srt:
        sidecar = outdir / "captions.srt"
        sidecar.write_text(Path(args.srt).read_text())
    r = subprocess.run([sys.executable, str(check), *written], capture_output=True, text=True)
    print("\n" + r.stdout.rstrip())
    if r.returncode != 0:
        print(
            "A deliverable above FAILs its platform check. Format rows are safe "
            "to fix and re-export; judgement rows change the content — put "
            "those to the human before shipping.",
            file=sys.stderr,
        )

    manifest = outdir / "manifest.json"
    manifest.write_text(
        json.dumps(
            {
                "schema_version": MANIFEST_SCHEMA,
                "master": file_fp(args.master),
                "shape": shape,
                "captioned": file_fp(args.captioned) if args.captioned else None,
                "sidecar": file_fp(sidecar) if sidecar else None,
                "outputs": [file_fp(x) for x in written],
            },
            indent=2,
        )
    )

    thumb = outdir / "thumbnail.jpg"
    thumb_tmp = outdir / "thumbnail.tmp.jpg"
    run(
        [
            "ffmpeg",
            "-y",
            "-ss",
            str(args.thumb_at),
            "-i",
            args.master,
            "-frames:v",
            "1",
            "-q:v",
            "2",
            str(thumb_tmp),
        ],
        "thumbnail",
    )
    thumb_tmp.rename(thumb)

    # optional: sport-magazine styled variants of the same frame
    has_key = any(
        os.environ.get(v) for v in ("GEMINI_API_KEY", "GOOGLE_AI_API_KEY", "GOOGLE_API_KEY")
    )
    if args.no_stylize:
        pass
    elif not has_key:
        print("(no Gemini API key — skipping stylized thumbnails; plain frame grab only)")
    else:
        cmd = [
            sys.executable,
            str(Path(__file__).parent / "stylize_thumbnail.py"),
            str(thumb),
            "--style",
            "all",
            "--outdir",
            str(outdir),
        ]
        if args.thumb_text:
            cmd += ["--text", args.thumb_text]
        r = subprocess.run(cmd)
        if r.returncode != 0:
            print(
                "WARNING: thumbnail styling failed — continuing with the plain frame grab",
                file=sys.stderr,
            )

    print(f"\nDeliverables in {outdir}/:")
    for f in sorted(outdir.iterdir()):
        print(f"  {f.name} ({f.stat().st_size / 1e6:.1f} MB)")
    print(
        "\nThe music is baked into these files. If the track is trending "
        "audio, add it from the platform's in-app library on upload instead "
        "— baked audio risks a mute or a takedown, and it does not get the "
        "reach that using the in-app track does. Post-schedulers cannot add "
        "in-app music, so a scheduled post has to accept the baked version."
    )


if __name__ == "__main__":
    main()

skills

tile.json