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

gen_captions.pyskills/reel-builder/scripts/

#!/usr/bin/env python3
"""Styled burn-in captions: rounded cards, custom font, per-word emphasis.

`render_reel.py --srt` burns plain libass text. libass BorderStyle=3 draws a
hard rectangle with no corner radius, so the rounded-box look modern IG/TikTok
captions use cannot be produced that way. This renders each phrase as an image
card and overlays the cards on the video.

Two stages, deliberately. Whisper mishears proper nouns and numbers ("70.3" ->
"17.3", "borrowed" -> "Boren"), so the text is surfaced for correction BEFORE
anything is burned in:

  1. review   words.json  -> phrases.json   (edit text, timings, emphasis)
  2. burn     phrases.json + video -> captioned video

Emphasis is explicit, not guessed: set "emphasis": [i, ...] on a phrase to
italicise the i-th word of that phrase.

Animation (`burn --animate`), timed to each word as it is spoken:
  none       one static card per phrase (default)
  highlight  the whole phrase shows; the spoken word sits on an accent pill
  reveal     words appear as they are spoken; the newest sits on the pill
Every state of a phrase has the same card geometry, so nothing jitters as the
highlight moves. Word timings come from `review` ("word_times"); if you change
a phrase's word count while fixing it, that phrase's timing is split by word
length instead, and burn says which phrases it estimated.

Width: burn measures each phrase's card with its own font, size and padding
and splits any wider than --max-width of the frame (default MAX_CARD_WIDTH,
clear of every platform's right rail) at the most balanced word boundary,
keeping per-word timing and emphasis.

Input is WORD-LEVEL timestamps, not a segment SRT — phrase chunking needs word
boundaries. Whisper's continuation tokens ("100" + "%", "4" + ".5,") are joined
into one word on load. Produce them with:
  mlx_whisper take.wav --word-timestamps True --output-format json

Usage:
  gen_captions.py review words.json --out work/captions/phrases.json
  gen_captions.py burn work/captions/phrases.json --video work/master.mp4 \\
      --out work/master_captioned.mp4 [--animate highlight]
  gen_captions.py srt work/captions/phrases.json --out work/captions.srt
      (the reviewed text as a sidecar, for platforms that take uploaded captions)
"""

import argparse
import json
import re
import shutil
import subprocess
import sys
from pathlib import Path

MAX_WORDS = 4  # phrase length cap; 2-4 words is the readable range
MAX_GAP = 0.6  # a pause longer than this starts a new phrase
BOX_RADIUS = 18
PAD_X, PAD_Y = 34, 18
SPACE_RATIO = 0.28  # inter-word gap as a fraction of point size
ANIMATIONS = ("none", "highlight", "reveal")
TAIL_PUNCT = "-'’,"  # unspaced, these join the word before ("N" + "-square")
# Widest caption card as a fraction of frame width. Centred, 0.70 ends at 0.85,
# left of the strictest right rail in safe_zones.ZONES (0.86).
MAX_CARD_WIDTH = 0.70
WORD_PAD_X, WORD_PAD_Y = 12, 6  # pill padding around every word when animated
WORD_RADIUS = 12
# Used when ImageMagick has no font registered under the requested name — a
# Homebrew ImageMagick does not index the macOS system fonts, so the default
# "Helvetica-Bold" fails there with "unable to read font".
FONT_FALLBACKS = {
    "regular": [
        "/System/Library/Fonts/Supplemental/Arial Bold.ttf",
        "/Library/Fonts/Arial Bold.ttf",
        "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
    ],
    "italic": [
        "/System/Library/Fonts/Supplemental/Arial Bold Italic.ttf",
        "/Library/Fonts/Arial Bold Italic.ttf",
        "/usr/share/fonts/truetype/dejavu/DejaVuSans-BoldOblique.ttf",
    ],
}


def need(exe, why):
    path = shutil.which(exe)
    if not path:
        sys.exit(f"{exe} not found — {why}")
    return path


def run(cmd, label):
    r = subprocess.run(cmd, capture_output=True, text=True)
    if r.returncode != 0:
        sys.exit(f"{label} failed:\n{' '.join(str(c) for c in cmd)[:300]}\n{r.stderr[-700:]}")
    return r


# ---------- stage 1: words -> phrases ----------


def load_words(path):
    """Accept whisper's nested JSON or a flat [{word,start,end}] list."""
    data = json.loads(Path(path).read_text())
    if isinstance(data, list):
        words = data
    elif "words" in data:
        words = data["words"]
    elif "segments" in data:
        words = [w for s in data["segments"] for w in s.get("words", [])]
    else:
        sys.exit(
            "Unrecognised words JSON. Expected a flat list, {'words': …}, "
            "or whisper's {'segments': [{'words': …}]}."
        )
    raws = [(w.get("word") or w.get("text") or "") for w in words]
    # Whisper marks a new word with a leading space; a token without one
    # continues the previous word ("100" + "%", "4" + ".5,", "N" + "-square").
    # A flat list already stripped of spaces only merges the unambiguous cases.
    spaced = any(r[:1].isspace() for r in raws)
    out = []
    for w, raw in zip(words, raws):
        text = raw.strip()
        if not text:
            continue
        try:
            start, end = float(w["start"]), float(w["end"])
        except (KeyError, TypeError, ValueError):
            sys.exit(
                f"Word entry missing usable start/end: {w}. Transcribe with --word-timestamps True."
            )
        if out and continues(raw, text, spaced, out[-1]["text"]):
            out[-1]["text"] += text
            out[-1]["end"] = end
            continue
        out.append({"text": text, "start": start, "end": end})
    if not out:
        sys.exit("No words found — was this transcribed with word timestamps?")
    return out


def continues(raw, text, spaced, prev):
    """Is this token the tail of the previous word rather than a word?

    Only the unambiguous cases: "%" after a number; a decimal tail (".5",
    ".5,") after a number; and, where Whisper's spacing shows the token is
    unspaced, a hyphen, apostrophe or comma tail. ".NET" and "rate .5" stay
    separate words."""
    if spaced and raw[:1].isspace():
        return False
    after_number = prev[-1:].isdigit()
    if text == "%" or text.startswith("%"):
        return after_number
    if text[0] == ".":
        return after_number and text[1:2].isdigit()
    return spaced and text[0] in TAIL_PUNCT


def chunk(words, max_words, max_gap):
    phrases, cur = [], []
    for w in words:
        if cur:
            gap = w["start"] - cur[-1]["end"]
            ends_clause = re.search(r"[.,!?;:]$", cur[-1]["text"])
            if len(cur) >= max_words or gap > max_gap or ends_clause:
                phrases.append(cur)
                cur = []
        cur.append(w)
    if cur:
        phrases.append(cur)
    return [
        {
            "text": " ".join(w["text"] for w in p),
            "words": [w["text"] for w in p],
            "start": round(p[0]["start"], 3),
            "end": round(p[-1]["end"], 3),
            "word_times": [[round(w["start"], 3), round(w["end"], 3)] for w in p],
            "emphasis": [],
        }
        for p in phrases
    ]


def has_word_times(phrase):
    times = phrase.get("word_times")
    return bool(times) and len(times) == len(phrase["words"])


def word_windows(phrase):
    """[(start, end)] per word: the span during which that word is the current one.

    Each window runs from the word's start to the next word's start, so the
    highlight never blinks off in the gap between words. Without usable
    word_times (the review edit changed the word count) the phrase span is split
    in proportion to word length.
    """
    words = phrase["words"]
    start, end = float(phrase["start"]), float(phrase["end"])
    if has_word_times(phrase):
        starts = [float(t[0]) for t in phrase["word_times"]]
    else:
        weights = [max(1, len(w)) for w in words]
        total, t, starts = sum(weights), start, []
        for w in weights:
            starts.append(t)
            t += (end - start) * w / total
    starts[0] = start
    for i in range(1, len(starts)):  # clamp: monotonic, inside the phrase
        starts[i] = min(max(starts[i], starts[i - 1]), end)
    ends = starts[1:] + [end]
    return [(round(a, 3), round(b, 3)) for a, b in zip(starts, ends)]


def card_states(phrase, animate):
    """[(active_word, visible_words, start, end)] — one card per state."""
    n = len(phrase["words"])
    if animate == "none":
        return [(None, n, float(phrase["start"]), float(phrase["end"]))]
    states = []
    for i, (a, b) in enumerate(word_windows(phrase)):
        if b <= a:
            continue  # a zero-length window shows nothing
        states.append((i, n if animate == "highlight" else i + 1, a, b))
    return states


def srt_time(t):
    ms = int(round(max(0.0, float(t)) * 1000))
    h, ms = divmod(ms, 3_600_000)
    m, ms = divmod(ms, 60_000)
    sec, ms = divmod(ms, 1000)
    return f"{h:02d}:{m:02d}:{sec:02d},{ms:03d}"


def to_srt(phrases):
    """The reviewed phrases as SRT: one cue per phrase, the edited text."""
    cues = []
    for n, p in enumerate(phrases, 1):
        text = " ".join(p.get("words") or [p.get("text", "")]).strip()
        cues.append(f"{n}\n{srt_time(p['start'])} --> {srt_time(p['end'])}\n{text}\n")
    return "\n".join(cues)


# ---------- stage 2: phrases -> cards -> burned video ----------


def known_fonts(magick):
    """Font names ImageMagick has registered (`magick -list font`)."""
    r = run([magick, "-list", "font"], "list fonts")
    return {
        line.split(":", 1)[1].strip()
        for line in r.stdout.splitlines()
        if line.strip().startswith("Font:")
    }


def resolve_font(name, kind, known, is_file=lambda p: Path(p).is_file()):
    """(font to pass to ImageMagick, warning or None).

    A path that exists, or a name ImageMagick knows, is used as given. Anything
    else falls back to the first installed font in FONT_FALLBACKS[kind].
    """
    if is_file(name) or name in known:
        return name, None
    for candidate in FONT_FALLBACKS[kind]:
        if is_file(candidate):
            return candidate, (
                f"font {name!r} is not registered with ImageMagick — using {candidate}"
            )
    sys.exit(
        f"font {name!r} is not registered with ImageMagick and no fallback "
        f"font is installed — pass --font /path/to/Bold.ttf and "
        f"--font-italic /path/to/BoldItalic.ttf"
    )


def render_card(phrase, opts, dst, active=None, visible=None):
    """One card per phrase, or per animation state when `active` is set.

    `active` puts that word on the accent pill; words at index >= `visible`
    render fully transparent so the card keeps its final size.

    Built from per-word `label:` renders appended with transparent spacers,
    because ImageMagick's pango delegate errors with "no decode delegate" in
    the common Homebrew IM7 build even though `-list format` advertises it.
    That rules out inline markup, so emphasis needs a separate font file.
    """
    magick = need("magick", "install ImageMagick (brew install imagemagick)")
    s = opts.get("_scale", 1.0)
    pad_x, pad_y = round(PAD_X * s), round(PAD_Y * s)
    radius = round(BOX_RADIUS * s)
    animated = active is not None
    visible = len(phrase["words"]) if visible is None else visible
    wpx, wpy = round(WORD_PAD_X * s), round(WORD_PAD_Y * s)
    gap = int(opts["size"] * SPACE_RATIO)
    if animated:  # word padding already separates the words
        gap = max(1, gap - 2 * wpx)
    parts, tmps = [], []
    spacer = dst.parent / f".sp_{dst.stem}.png"
    run([magick, "-size", f"{gap}x1", "xc:none", str(spacer)], "spacer")
    tmps.append(spacer)

    for i, word in enumerate(phrase["words"]):
        emph = i in phrase.get("emphasis", [])
        font = opts["font_italic"] if emph else opts["font"]
        colour = opts["fg"] if i == active else (opts["accent"] if emph else opts["fg"])
        wp = dst.parent / f".w{i}_{dst.stem}.png"
        run(
            [
                magick,
                "-background",
                "none",
                "-fill",
                colour,
                "-font",
                font,
                "-pointsize",
                str(opts["size"]),
                f"label:{word}",
                str(wp),
            ],
            f"word {word!r}",
        )
        tmps.append(wp)
        if animated:
            # identical padding on every word keeps every state the same size
            if i == active:
                r = run([magick, str(wp), "-format", "%w %h", "info:"], "measure word")
                ww, wh = (int(n) for n in r.stdout.split())
                pw, ph = ww + 2 * wpx, wh + 2 * wpy
                rad = round(WORD_RADIUS * s)
                run(
                    [
                        magick,
                        "-size",
                        f"{pw}x{ph}",
                        "xc:none",
                        "-fill",
                        opts["active_box"],
                        "-draw",
                        f"roundrectangle 0,0 {pw - 1},{ph - 1} {rad},{rad}",
                        str(wp),
                        "-gravity",
                        "center",
                        "-composite",
                        str(wp),
                    ],
                    "word pill",
                )
            else:
                run(
                    [magick, str(wp), "-bordercolor", "none", "-border", f"{wpx}x{wpy}", str(wp)],
                    "word padding",
                )
            if i >= visible:
                run(
                    [
                        magick,
                        str(wp),
                        "-alpha",
                        "set",
                        "-channel",
                        "A",
                        "-evaluate",
                        "set",
                        "0",
                        "+channel",
                        str(wp),
                    ],
                    "hide word",
                )
        if parts:
            parts.append(str(spacer))
        parts.append(str(wp))

    text_img = dst.parent / f".txt_{dst.stem}.png"
    run(
        [magick] + parts + ["-background", "none", "-gravity", "center", "+append", str(text_img)],
        "append words",
    )
    tmps.append(text_img)

    r = run([magick, str(text_img), "-format", "%w %h", "info:"], "measure")
    tw, th = (int(n) for n in r.stdout.split())
    bw, bh = tw + pad_x * 2, th + pad_y * 2
    run(
        [
            magick,
            "-size",
            f"{bw}x{bh}",
            "xc:none",
            "-fill",
            opts["box"],
            "-draw",
            f"roundrectangle 0,0 {bw - 1},{bh - 1} {radius},{radius}",
            str(text_img),
            "-gravity",
            "center",
            "-composite",
            str(dst),
        ],
        "compose card",
    )
    for t in tmps:
        t.unlink(missing_ok=True)
    return dst


def split_phrase(p):
    """Two phrases split at the word boundary that balances their length,
    keeping per-word timing and emphasis."""
    words = p["words"]
    cut = min(
        range(1, len(words)), key=lambda i: abs(len(" ".join(words[:i])) - len(" ".join(words[i:])))
    )
    # the phrase's own clamped windows: the halves keep its outer bounds and
    # meet where the second half's first word becomes current, so the caption
    # never blinks off between them
    windows = word_windows(p)
    mid = windows[cut][0]
    halves = []
    for lo, hi, a, b in ((0, cut, p["start"], mid), (cut, len(words), mid, p["end"])):
        part = {
            "text": " ".join(words[lo:hi]),
            "words": words[lo:hi],
            "start": round(float(a), 3),
            "end": round(float(b), 3),
            "emphasis": [i - lo for i in p.get("emphasis", []) if lo <= i < hi],
        }
        if has_word_times(p):
            part["word_times"] = [list(w) for w in windows[lo:hi]]
        halves.append(part)
    return halves


def fit_width(phrases, opts, frame_w, max_frac, measure_dir):
    """Split every phrase whose rendered card is wider than max_frac of the
    frame, measured with the burn's own font, size and padding."""
    if not max_frac:
        return phrases, 0
    animated = opts.get("animate", "none") != "none"
    out, splits = [], 0
    queue = list(phrases)
    while queue:
        p = queue.pop(0)
        probe = measure_dir / ".measure.png"
        render_card(p, opts, probe, active=0 if animated else None)
        magick = need("magick", "install ImageMagick (brew install imagemagick)")
        width = int(run([magick, str(probe), "-format", "%w", "info:"], "measure card").stdout)
        probe.unlink(missing_ok=True)
        if width > max_frac * frame_w and len(p["words"]) > 1:
            queue[:0] = split_phrase(p)
            splits += 1
            continue
        if width > max_frac * frame_w:
            print(
                f"  one word is wider than {max_frac:.2f} of the frame: {p['text']!r} — "
                f"lower --size",
                file=sys.stderr,
            )
        out.append(p)
    return out, splits


def video_width(path):
    from ffsafe import probe_field

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


def burn(phrases, video, out, opts):
    need("ffmpeg", "install ffmpeg (brew install ffmpeg)")
    # Card geometry is authored at 1080 wide and scaled to the real frame, so
    # a 4K master gets proportionally sized captions instead of half-size ones.
    scale = video_width(video) / 1080.0
    opts = {**opts, "size": max(8, round(opts["size"] * scale)), "_scale": scale}
    print(
        f"  frame is {round(1080 * scale)}px wide -> caption scale "
        f"{scale:.2f}x (point size {opts['size']})",
        flush=True,
    )
    cards_dir = out.parent / f"{out.stem}_cards"
    cards_dir.mkdir(parents=True, exist_ok=True)
    phrases, splits = fit_width(
        phrases, opts, round(1080 * scale), opts.get("max_width"), cards_dir
    )
    if splits:
        print(
            f"  split {splits} phrase(s) wider than {opts['max_width']:.2f} of the frame "
            f"(the platforms' right rail)",
            file=sys.stderr,
        )

    animate = opts.get("animate", "none")
    estimated = [n for n, p in enumerate(phrases) if animate != "none" and not has_word_times(p)]
    if estimated:
        print(
            f"  {len(estimated)} phrase(s) have no per-word timing matching their "
            f"words (edited word count, or an older phrases.json) — split by word "
            f"length: {', '.join(str(n) for n in estimated[:12])}",
            file=sys.stderr,
        )

    cards = []  # (path, start, end)
    for n, p in enumerate(phrases):
        for k, (active, visible, a, b) in enumerate(card_states(p, animate)):
            dst = cards_dir / (
                f"card_{n:04d}.png" if animate == "none" else f"card_{n:04d}_{k}.png"
            )
            render_card(p, opts, dst, active=active, visible=visible)
            cards.append((dst, a, b))
        print(f"  card {n + 1}/{len(phrases)}: {p['text'][:48]}", flush=True)

    # Build one filtergraph. Every card is an input; overlay is gated on
    # enable=between(t,start,end) so only the current card is visible. Animated
    # states end where the next begins, so the right edge is exclusive (lt) to
    # avoid two states sharing the boundary frame.
    cmd = ["ffmpeg", "-y", "-v", "error", "-i", str(video)]
    for dst, _, _ in cards:
        cmd += ["-i", str(dst)]
    chain, prev = [], "[0:v]"
    for i, (_, a, b) in enumerate(cards, start=1):
        label = f"[v{i}]"
        gate = (
            f"between(t,{a:.3f},{b:.3f})" if animate == "none" else f"gte(t,{a:.3f})*lt(t,{b:.3f})"
        )
        chain.append(
            f"{prev}[{i}:v]overlay=x=(W-w)/2:y=H*{opts['position']}-h/2:enable='{gate}'{label}"
        )
        prev = label
    cmd += [
        "-filter_complex",
        ";".join(chain),
        "-map",
        prev,
        "-map",
        "0:a?",
        "-c:a",
        "copy",
        "-c:v",
        "libx264",
        "-preset",
        "slow",
        "-crf",
        str(opts["crf"]),
        "-pix_fmt",
        "yuv420p",
        "-movflags",
        "+faststart",
        str(out),
    ]
    run(cmd, "burn captions")
    return cards_dir, caption_zone_report([c for c, _, _ in cards], video, opts["position"])


def caption_zone_report(cards, video, position):
    """Which platform UI zones the burned caption band falls under (safe_zones.py)."""
    from ffsafe import probe_field
    from safe_zones import check_all

    magick = need("magick", "install ImageMagick (brew install imagemagick)")
    w, h = probe_field(video, "stream=width"), probe_field(video, "stream=height")
    if not cards or w is None or h is None:
        return None
    sizes = [
        tuple(
            int(n)
            for n in run(
                [magick, str(c), "-format", "%w %h", "info:"], "measure card"
            ).stdout.split()
        )
        for c in cards
    ]
    cw, ch = max(s[0] for s in sizes), max(s[1] for s in sizes)
    band = (round(position - ch / 2 / int(h), 3), round(position + ch / 2 / int(h), 3))
    hits = check_all(band, cw / int(w))
    for platform, zones in hits.items():
        if zones:
            print(
                f"  WARNING: captions at {band[0]:.2f}-{band[1]:.2f} of the height sit under "
                f"{platform}'s {', '.join(zones)} UI (approximate zones) — move --position "
                "or check with safe_zones.py preview",
                file=sys.stderr,
            )
    return {"band": band, "width": round(cw / int(w), 3), "overlaps": hits}


def main():
    ap = argparse.ArgumentParser()
    sub = ap.add_subparsers(dest="cmd", required=True)

    r = sub.add_parser("review", help="words.json -> editable phrases.json")
    r.add_argument("words_json")
    r.add_argument("--out", default="work/captions/phrases.json")
    r.add_argument("--max-words", type=int, default=MAX_WORDS)
    r.add_argument("--max-gap", type=float, default=MAX_GAP)

    sr = sub.add_parser("srt", help="phrases.json -> .srt sidecar")
    sr.add_argument("phrases_json")
    sr.add_argument("--out", default="work/captions.srt")

    b = sub.add_parser("burn", help="phrases.json + video -> captioned video")
    b.add_argument("phrases_json")
    b.add_argument("--video", required=True)
    b.add_argument("--out", required=True)
    b.add_argument("--font", default="Helvetica-Bold")
    b.add_argument(
        "--font-italic",
        default="Helvetica-BoldOblique",
        help="Used for emphasised words; pango markup is not "
        "available, so emphasis needs its own font file/name",
    )
    b.add_argument(
        "--size",
        type=int,
        default=54,
        help="Point size authored at 1080 wide; scaled to the "
        "actual frame, so 4K gets proportional captions",
    )
    b.add_argument("--fg", default="white")
    b.add_argument("--accent", default="#F26B21")
    b.add_argument("--box", default="#0F1D2BE6", help="Card fill, RGBA hex")
    b.add_argument(
        "--crf",
        type=int,
        default=16,
        help="x264 quality for the re-encode, lower is better "
        "(default 16). Match the master you are burning onto "
        "— burning at a higher CRF silently discards its "
        "quality.",
    )
    b.add_argument(
        "--animate",
        choices=ANIMATIONS,
        default="none",
        help="Per-word animation: highlight the spoken word, or "
        "reveal words as they are spoken (default none)",
    )
    b.add_argument(
        "--active-box",
        default=None,
        help="Pill colour behind the current word when animated (default: --accent)",
    )
    b.add_argument(
        "--max-width",
        type=float,
        default=MAX_CARD_WIDTH,
        help="widest card as a fraction of frame width; wider phrases split at "
        "a word boundary (default 0.70 clears every platform's right rail; "
        "0 disables)",
    )
    b.add_argument(
        "--position",
        type=float,
        default=0.72,
        help="Card centre as a fraction of frame height. Default "
        "0.72 is lower-third — deliberately off the face.",
    )
    args = ap.parse_args()

    if args.cmd == "srt":
        phrases = json.loads(Path(args.phrases_json).read_text())
        if not phrases:
            sys.exit("No phrases in that file — nothing to write.")
        out = Path(args.out)
        out.parent.mkdir(parents=True, exist_ok=True)
        out.write_text(to_srt(phrases))
        print(json.dumps({"cues": len(phrases), "output": str(out)}))
        return

    if args.cmd == "review":
        phrases = chunk(load_words(args.words_json), args.max_words, args.max_gap)
        out = Path(args.out)
        out.parent.mkdir(parents=True, exist_ok=True)
        out.write_text(json.dumps(phrases, indent=2))
        print(f"{len(phrases)} phrases -> {out}\n")
        for p in phrases[:8]:
            print(f"  {p['start']:6.2f}  {p['text']}")
        if len(phrases) > 8:
            print(f"  … {len(phrases) - 8} more")
        print(
            "\nREAD THIS BEFORE BURNING. Whisper mishears proper nouns and "
            'numbers — fix the text now, and set "emphasis": [i] on a '
            "phrase to italicise its i-th word.",
            file=sys.stderr,
        )
        return

    phrases = json.loads(Path(args.phrases_json).read_text())
    if not phrases:
        sys.exit("No phrases in that file — nothing to burn.")
    out = Path(args.out)
    out.parent.mkdir(parents=True, exist_ok=True)
    magick = need("magick", "install ImageMagick (brew install imagemagick)")
    known = known_fonts(magick)
    font, warn = resolve_font(args.font, "regular", known)
    font_italic, warn_i = resolve_font(args.font_italic, "italic", known)
    for w in (warn, warn_i):
        if w:
            print(f"  {w}", file=sys.stderr)
    opts = {
        "font": font,
        "font_italic": font_italic,
        "size": args.size,
        "fg": args.fg,
        "accent": args.accent,
        "box": args.box,
        "position": args.position,
        "crf": args.crf,
        "animate": args.animate,
        "active_box": args.active_box or args.accent,
        "max_width": args.max_width,
    }
    cards_dir, zones = burn(phrases, args.video, out, opts)
    print(
        json.dumps(
            {
                "phrases": len(phrases),
                "animate": args.animate,
                "cards": str(cards_dir),
                "output": str(out),
                "position": args.position,
                "font": font,
                "font_italic": font_italic,
                "safe_zones": zones,
            },
            indent=2,
        )
    )


if __name__ == "__main__":
    main()

skills

tile.json