Local video editor for coding agents: 42 FFmpeg tools with a machine-readable contract and an MCP server, for Claude Code, Cursor and Codex. Cut, captions, reframe, loudness, platform exports. No cloud, no API keys.
Python agent-skillsai-agentsaudio-processingcaptionsclaude-codecodexcoding-agentcursorffmpegloudness-normalizationmcpmcp-servermodel-context-protocolpythonsubtitlestranscodingvideovideo-editingvideo-processingwhisper
Release 0.6.0: graphics templates, brand.json, HTML delivery report (#7)
kajisho587f1bc6abed7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d0752f4..e4c99ff 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,12 @@# Changelog+## 0.6.0++- `graphics.py` (new): motion-graphics templates with no image assets — lower-third (slide in/out), title card, chapter chip, progress bar, countdown, corner bug — coloured from brand.json.+- `brand.json` support: fonts, colours, logo (position/scale/opacity), safe margin, caption defaults. `caption.py --brand`, `overlay.py --brand --logo`, `graphics.py --brand`, and a `"brand"` key in `render.py` projects (plus a `graphics` stage and `{"logo": true}` overlays).+- `report.py` (new): single-file HTML delivery report with before/after contact sheets, media facts, loudness, compliance table and the commands run.+- Tests: 46 end-to-end cases.+## 0.5.0- `render.py` (new): declarative edits from one `project.json` (clips → join → silence → fit → captions → overlays → audio → loudness → export → check). `--init` writes a starter, `--dry-run` prints every command, `--stop-after` for iterating.diff --git a/README.md b/README.mdindex 9490aea..fe23db0 100644--- a/README.md+++ b/README.md@@ -18,6 +18,9 @@ npx ffmpeg-skill- **Lossless when possible** — cuts and joins use stream copy by default; re-encoding only happens when it must (frame-accurate cuts, filters, format changes).- **Cut & join** segments with `mm:ss` / `hh:mm:ss.ms` times.- **Declarative edits** — describe the whole edit in a `project.json` (clips, transitions, captions, overlays, music, loudness, export, check) and re-render after every tweak.+- **Brand kit** — one `brand.json` (fonts, colours, logo, safe margins, caption style) applied by captions, overlays, graphics and projects.+- **Motion graphics without assets** — lower-thirds, title cards, chapter chips, progress bars, countdowns and corner bugs drawn by FFmpeg.+- **HTML delivery report** — before/after contact sheets, media facts, loudness, compliance and the commands run, in one file.- **Scene detection and highlight picks** — find cuts and loud moments, get a 60-second digest proposal as a cut list.- **Delivery checks** — PASS/FAIL against YouTube, Shorts, Reels, TikTok, X, LinkedIn, broadcast and podcast specs, with the fix for each failure.- **Multicam** — align any number of cameras and recorders by audio (with drift correction) and cut between them from a switch list.@@ -96,6 +99,8 @@ More examples: [examples/README.md](examples/README.md). To see everything run e| `probe.py` | Duration, fps (+ VFR detection), resolution, codecs, bit depth, HDR format incl. Dolby Vision, colour space, rotation, audio channels as JSON; `--analyze` flags Log footage || `cut.py` | In/out or multi-segment cuts, lossless `-c copy` first, re-encode fallback, `--accurate` for frame-exact || `render.py` | Render a whole edit from `project.json`; `--init`, `--dry-run`, `--stop-after` |+| `graphics.py` | Lower-third, title, chapter, progress, countdown, bug templates (brand colours) |+| `report.py` | Single-file HTML delivery report with sheets, facts, loudness, compliance, commands || `scenes.py` | Scene changes, audio peaks, highlight proposals and per-scene sheet || `check.py` | Pre-delivery compliance per platform (duration, aspect, codec, colour, loudness, size) || `multicam.py` | Align cameras/recorders by audio and switch between them from a time list |diff --git a/SKILL.md b/SKILL.mdindex ae96749..a472ea8 100644--- a/SKILL.md+++ b/SKILL.md@@ -1,6 +1,6 @@---name: ffmpeg-skill-description: Professional video editing with local FFmpeg — declarative project rendering, scene detection and highlight picks, delivery compliance checks, cut, silence removal, transitions, multicam, captions (animated/karaoke timed to speech), fit to duration/aspect, audio sync with drift correction, HDR/HLG/Dolby Vision to SDR, LUTs, audio clean-up and ducking, loudness, overlays, platform exports, frame inspection and a real-footage verification kit; Python stdlib scripts, no cloud or API keys.+description: Professional video editing with local FFmpeg — declarative project rendering, brand kits, motion-graphics templates (lower-thirds, titles, countdowns), HTML delivery reports, scene detection and highlight picks, delivery compliance checks, cut, silence removal, transitions, multicam, captions (animated/karaoke timed to speech), fit to duration/aspect, audio sync with drift correction, HDR/HLG/Dolby Vision to SDR, LUTs, audio clean-up and ducking, loudness, overlays, platform exports, frame inspection and a real-footage verification kit; Python stdlib scripts, no cloud or API keys.---# ffmpeg-skill@@ -72,6 +72,9 @@ path on stdout, and defaults the output name to `<input>_<operation>.<ext>`.| "make a 60 s highlight from this hour", "find the good bits" | `scenes.py long.mp4 --highlights 6 --target 60 --edl picks.txt` → `cut.py --segments` || "is this OK to upload?", "check it meets the Reels spec" | `check.py final.mp4 --platform reels` || "set it up so I can tweak and re-render", "several changes to the same edit" | `render.py --init project.json`, edit, `render.py project.json` |+| "add a lower third with my name", "title card", "countdown intro", "progress bar" | `graphics.py input.mp4 --template lower-third --name "..." --title "..." --start 2 --end 8` |+| "use our brand fonts/colours/logo" | pass `--brand brand.json` to caption/overlay/graphics, or `"brand"` in project.json |+| "send me a summary of what you did" | `report.py --before raw.mov --after final.mp4 --platform youtube -o report.html` || "three cameras, cut between them" | `multicam.py camA.mp4 camB.mp4 camC.mp4 --switch "0-20:0,20-40:1,40-60:2"` || "it's an iPhone Dolby Vision clip and players show it wrong" | `color.py clip.mov --to-sdr` or `color.py clip.mov --strip-dovi` (keep HDR, drop the DV layer) || "does it look like Log / S-Log / flat footage?" | `probe.py clip.mp4 --analyze` (`looks_like_log`) then `color.py --lut` |@@ -149,7 +152,7 @@ render.py --init project.json # starter filerender.py project.json [--fast] [--dry-run] [--stop-after STAGE] [--work DIR --keep]```Stages: clips (cut, optional speed) → join (transition) → silence → fit →-captions → overlays → audio → loudness → export → check. Keys mirror the+captions → graphics → overlays → audio → loudness → export → check. Keys mirror theCLI flags of each script (see the docstring). Use it whenever an edit hasmore than two steps or the user is likely to ask for changes: edit the JSON,re-render, and the result is reproducible. `--dry-run --json` prints the@@ -173,6 +176,35 @@ check.py INPUT --platform youtube|shorts|reels|tiktok|x|linkedin|broadcast|podcaPASS/WARN/FAIL per check with the script that fixes it. Run it as the finalstep before reporting a deliverable; fix FAILs, mention WARNs.+### graphics.py — motion-graphics templates+```+graphics.py INPUT --template lower-third|title|chapter|progress|countdown|bug [--name] [--title] [--subtitle]+ [--from N] [--start S] [--end E] [--position CORNER] [--brand brand.json] [--primary RRGGBB] [--scale 1.0] [-o OUT]+```+Drawn with drawbox/drawtext/overlay — no PNG assets needed. Sizes scale with+the frame's short side; colours, font and safe margin come from `--brand`.+Lower-third slides in over 0.4 s and out over 0.3 s; title/chapter/bug fade.++### brand.json — one file for fonts, colours, logo, margins+```json+{"font": "Noto Sans CJK JP", "font_file": "fonts/NotoSansCJK-Bold.ttc",+ "colors": {"primary": "FF6A00", "text": "FFFFFF", "outline": "000000", "background": "0B1D2A"},+ "logo": "logo.png", "logo_position": "top-right", "logo_scale": 160, "logo_opacity": 0.9,+ "safe_margin": 48, "caption": {"size": 28, "position": "bottom", "animate": "pop", "karaoke": true, "bold": true}}+```+`caption.py --brand`, `overlay.py --brand --logo`, `graphics.py --brand`, and+`"brand": "brand.json"` in a render project. Explicit flags still win. When a+user mentions brand guidelines, colours, "our font" or a logo, ask for or+write a brand.json once and reuse it across every output.++### report.py — HTML delivery report+```+report.py --after FINAL [--before SOURCE] [--platform youtube] [--commands cmds.txt] [--notes notes.md] [--title T] [--no-sheets] [-o report.html]+```+One self-contained HTML: before/after facts and contact sheets, loudness,+compliance table with fixes, commands. Produce it for any multi-step job and+hand the path to the user together with the numbers.+### multicam.py — align several cameras and switch between them```multicam.py REF CAM2 [CAM3 ...] [--switch "START-END:CAM,..."] | [--auto N] [--audio IDX] [--fix-drift]diff --git a/examples/README.md b/examples/README.mdindex c8624c3..de0d58b 100644--- a/examples/README.md+++ b/examples/README.md@@ -109,6 +109,26 @@ python3 $S/render.py project.json --fast # previewpython3 $S/render.py project.json # final```+### "Add a lower third / title / countdown"+```bash+python3 $S/graphics.py talk.mp4 --template lower-third --name "Ada Lovelace" --title "Analyst" --start 2 --end 8 --brand brand.json+python3 $S/graphics.py talk.mp4 --template title --title "Episode 12" --subtitle "The math of video" --start 0 --end 4+python3 $S/graphics.py intro.mp4 --template countdown --from 5 --start 1 --end 6+python3 $S/graphics.py talk.mp4 --template progress+```++### "Use our brand"+```bash+cp examples/brand.json ./brand.json # edit fonts, colours, logo+python3 $S/caption.py talk.mp4 --text cues.txt --brand brand.json+python3 $S/overlay.py talk.mp4 --logo --brand brand.json+```++### "Give me a report of what you did"+```bash+python3 $S/report.py --before raw.mov --after final.mp4 --platform youtube --commands commands.txt -o report.html+```+### "Make a 60 second highlight from an hour"```bashpython3 $S/scenes.py event.mp4 --highlights 6 --target 60 --edl picks.txt --sheet scenes.pngdiff --git a/examples/brand.json b/examples/brand.jsonnew file mode 100644index 0000000..9229828--- /dev/null+++ b/examples/brand.json@@ -0,0 +1,28 @@+{+ "font": "DejaVu Sans",+ "font_file": null,+ "colors": {+ "primary": "FF6A00",+ "text": "FFFFFF",+ "outline": "000000",+ "background": "0B1D2A",+ "accent": "1E6F8E"+ },+ "logo": "logo.png",+ "logo_position": "top-right",+ "logo_scale": 160,+ "logo_opacity": 0.9,+ "safe_margin": 48,+ "caption": {+ "size": 28,+ "position": "bottom",+ "animate": "pop",+ "karaoke": true,+ "bold": true,+ "outline": 2+ },+ "loudness": {+ "lufs": -14,+ "tp": -1+ }+}\ No newline at end of filediff --git a/package.json b/package.jsonindex d021118..fe11c68 100644--- a/package.json+++ b/package.json@@ -1,7 +1,7 @@{"name": "ffmpeg-skill",- "version": "0.5.0",- "description": "Agent Skill that lets coding agents (Claude Code, Cursor, Codex) do professional video editing with local FFmpeg: declarative project rendering, scene detection, delivery checks, cut, silence removal, transitions, multicam, captions, sync with drift correction, HDR to SDR, LUTs, audio clean-up and ducking, loudness, platform exports. No API keys, no cloud, no dependencies.",+ "version": "0.6.0",+ "description": "Agent Skill that lets coding agents (Claude Code, Cursor, Codex) do professional video editing with local FFmpeg: declarative project rendering, brand kits, motion-graphics templates, HTML delivery reports, scene detection, delivery checks, cut, silence removal, transitions, multicam, captions, sync with drift correction, HDR to SDR, LUTs, audio clean-up and ducking, loudness, platform exports. No API keys, no cloud, no dependencies.","keywords": ["ffmpeg", "video", "agent-skill", "claude-code", "cursor", "codex", "skill", "video-editing"],"license": "MIT","author": "kajisho5",diff --git a/scripts/_common.py b/scripts/_common.pyindex 18d112e..fb154e2 100755--- a/scripts/_common.py+++ b/scripts/_common.py@@ -417,6 +417,55 @@ def analyze_levels(path: str, seconds: float = 20.0) -> Dict[str, Any]:}+BRAND_DEFAULTS: Dict[str, Any] = {+ "font": "DejaVu Sans",+ "font_file": None,+ "colors": {"primary": "FFD200", "text": "FFFFFF", "outline": "000000", "background": "101418", "accent": "1E6F8E"},+ "logo": None,+ "logo_position": "top-right",+ "logo_scale": 160,+ "logo_opacity": 0.9,+ "safe_margin": 48,+ "caption": {"size": 26, "position": "bottom", "animate": "pop", "karaoke": False, "bold": True, "outline": 2},+ "loudness": {"lufs": -14, "tp": -1},+}+++def load_brand(path: Optional[str]) -> Dict[str, Any]:+ """Load brand.json (fonts, colours, logo, safe margins, caption defaults); missing keys fall back to defaults."""+ import copy+ brand = copy.deepcopy(BRAND_DEFAULTS)+ if not path:+ return brand+ if not os.path.exists(path):+ die(f"brand file not found: {path}")+ try:+ data = json.loads(Path(path).read_text(encoding="utf-8"))+ except ValueError as exc:+ die(f"brand file is not valid JSON: {exc}")+ base = Path(path).resolve().parent+ for k, v in data.items():+ if isinstance(v, dict) and isinstance(brand.get(k), dict):+ brand[k].update(v)+ else:+ brand[k] = v+ for key in ("logo", "font_file"):+ if brand.get(key) and not os.path.isabs(brand[key]):+ brand[key] = str(base / brand[key])+ brand["_path"] = str(path)+ return brand+++def color_hex(value: str) -> str:+ """Normalise '#ffd200' / 'ffd200' / '0xFFD200' to 'FFD200'."""+ v = str(value).strip().lstrip("#")+ if v.lower().startswith("0x"):+ v = v[2:]+ if len(v) != 6:+ die(f"colour must be RRGGBB, got '{value}'")+ return v.upper()++def print_json(obj: Any) -> None:sys.stdout.write(json.dumps(obj, indent=2, ensure_ascii=False) + "\n")diff --git a/scripts/caption.py b/scripts/caption.pyindex f6bd9cf..9b01549 100755--- a/scripts/caption.py+++ b/scripts/caption.py@@ -20,9 +20,10 @@ import argparseimport osimport reimport sys+from pathlib import Pathfrom typing import List, Tuple-from _common import video_args, add_common, apply_common, emit, aac_args, cfr_args, default_output, die, escape_filter_path, ffmpeg_base, fmt_srt_time, info, parse_time, probe, run, x264_args+from _common import color_hex, load_brand, video_args, add_common, apply_common, emit, aac_args, cfr_args, default_output, die, escape_filter_path, ffmpeg_base, fmt_srt_time, info, parse_time, probe, run, x264_argsALIGN = {"bottom": 2, "top": 8, "center": 5, "bottom-left": 1, "bottom-right": 3, "top-left": 7, "top-right": 9}@@ -220,21 +221,22 @@ def main() -> int:src.add_argument("--auto-seconds", type=float, default=3.0, help="duration for cues without timing (default 3)")src.add_argument("--gap", type=float, default=0.0, help="gap after auto-timed cues in seconds")sty = ap.add_argument_group("style (SRT only)")- sty.add_argument("--font", default="DejaVu Sans", help="font family, e.g. 'Noto Sans CJK JP' for Japanese")+ sty.add_argument("--brand", help="brand.json: font, colours, caption size/position/animation defaults")+ sty.add_argument("--font", default=None, help="font family, e.g. 'Noto Sans CJK JP' for Japanese (default DejaVu Sans or brand font)")sty.add_argument("--fonts-dir", help="directory with extra .ttf/.otf files")- sty.add_argument("--size", type=int, default=24, help="font size in ASS points (relative to a 288p script height, scales automatically)")- sty.add_argument("--color", default="FFFFFF", help="text colour RRGGBB (default FFFFFF)")- sty.add_argument("--outline-color", default="000000", help="outline colour RRGGBB")- sty.add_argument("--outline", type=float, default=2.0, help="outline width (default 2)")+ sty.add_argument("--size", type=int, default=None, help="font size in ASS points (relative to a 288p script height, scales automatically)")+ sty.add_argument("--color", default=None, help="text colour RRGGBB (default FFFFFF or brand text colour)")+ sty.add_argument("--outline-color", default=None, help="outline colour RRGGBB")+ sty.add_argument("--outline", type=float, default=None, help="outline width (default 2)")sty.add_argument("--shadow", type=float, default=0.0, help="shadow depth (default 0)")sty.add_argument("--bold", action="store_true")- sty.add_argument("--position", choices=sorted(ALIGN), default="bottom", help="on-screen placement (default bottom)")+ sty.add_argument("--position", choices=sorted(ALIGN), default=None, help="on-screen placement (default bottom)")sty.add_argument("--margin", type=int, default=30, help="vertical margin from the edge (default 30)")sty.add_argument("--box", action="store_true", help="draw an opaque box behind text instead of an outline")anim = ap.add_argument_group("animation (generates ASS; needs --text or --srt input)")- anim.add_argument("--animate", choices=["none", "fade", "pop", "slide"], default="none", help="per-cue entrance animation")+ anim.add_argument("--animate", choices=["none", "fade", "pop", "slide"], default=None, help="per-cue entrance animation (default none, or brand caption.animate)")anim.add_argument("--karaoke", action="store_true", help="word-by-word highlight (fills from --color to --highlight-color across each cue)")- anim.add_argument("--highlight-color", default="FFD200", help="karaoke fill colour RRGGBB (default FFD200)")+ anim.add_argument("--highlight-color", default=None, help="karaoke fill colour RRGGBB (default FFD200 or brand primary)")anim.add_argument("--karaoke-timing", choices=["even", "energy"], default="energy",help="how words are timed inside a cue: 'energy' follows the speech loudness in the audio (default), 'even' splits time equally")anim.add_argument("--write-ass", help="where to save the generated ASS (default: next to the output)")@@ -245,6 +247,22 @@ def main() -> int:args = ap.parse_args()apply_common(args)+ brand = load_brand(args.brand)+ bc, bcap = brand["colors"], brand["caption"]+ args.font = args.font or brand.get("font") or "DejaVu Sans"+ args.size = args.size if args.size is not None else (bcap.get("size", 24) if args.brand else 24)+ args.color = color_hex(args.color or bc.get("text", "FFFFFF"))+ args.outline_color = color_hex(args.outline_color or bc.get("outline", "000000"))+ args.outline = args.outline if args.outline is not None else (float(bcap.get("outline", 2)) if args.brand else 2.0)+ args.position = args.position or (bcap.get("position", "bottom") if args.brand else "bottom")+ args.animate = args.animate or (bcap.get("animate", "none") if args.brand else "none")+ args.highlight_color = color_hex(args.highlight_color or bc.get("primary", "FFD200"))+ if args.brand and bcap.get("bold") and not args.bold:+ args.bold = True+ if args.brand and bcap.get("karaoke") and not args.karaoke:+ args.karaoke = True+ if args.brand and brand.get("font_file") and not args.fonts_dir:+ args.fonts_dir = str(Path(brand["font_file"]).parent)if not (args.srt or args.ass or args.text):die("give one of --srt, --ass or --text")diff --git a/scripts/graphics.py b/scripts/graphics.pynew file mode 100755index 0000000..e03976c--- /dev/null+++ b/scripts/graphics.py@@ -0,0 +1,166 @@+#!/usr/bin/env python3+"""Motion-graphics templates rendered with drawbox/drawtext expressions —+no After Effects, no image assets, brand colours from brand.json.++Templates:+ lower-third name + title bar sliding in from the left (--name, --title)+ title centred title card with optional subtitle, fade in/out (--title, --subtitle)+ chapter small chip in a corner (--title), e.g. "Part 2 — Setup"+ progress thin progress bar along the bottom that fills over the clip (or --start/--end)+ countdown big numbers counting down from --from to 0 (--start/--end define the window)+ bug persistent text bug (--title) in a corner, e.g. "@handle" or "LIVE"++Examples:+ python3 graphics.py talk.mp4 --template lower-third --name "Ada Lovelace" --title "Analyst" --start 2 --end 8+ python3 graphics.py talk.mp4 --template title --title "Episode 12" --subtitle "The math of video" --start 0 --end 4+ python3 graphics.py talk.mp4 --template progress --brand brand.json+ python3 graphics.py intro.mp4 --template countdown --from 5 --start 1 --end 6+ python3 graphics.py clip.mp4 --template chapter --title "Part 2 — Setup" --position top-left --start 0 --end 5+"""+import argparse+import sys+from typing import List, Optional++from _common import aac_args, add_common, apply_common, cfr_args, color_hex, default_output, die, emit, escape_drawtext, escape_filter_path, ffmpeg_base, info, load_brand, parse_time, probe, run, video_args++TEMPLATES = ["lower-third", "title", "chapter", "progress", "countdown", "bug"]+++def ff_color(hex_rgb: str, alpha: float = 1.0) -> str:+ return f"0x{color_hex(hex_rgb)}@{alpha:g}"+++def font_opts(brand: dict, font: Optional[str], font_file: Optional[str]) -> str:+ if font_file or brand.get("font_file"):+ return f"fontfile={escape_filter_path(font_file or brand['font_file'])}"+ return f"font='{font or brand.get('font', 'DejaVu Sans')}'"+++def main() -> int:+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("input")+ ap.add_argument("-o", "--output", help="output file (default: <name>_gfx.<ext>)")+ ap.add_argument("--template", choices=TEMPLATES, required=True)+ ap.add_argument("--brand", help="brand.json for colours, font, safe margin")+ ap.add_argument("--name", help="lower-third: name line")+ ap.add_argument("--title", help="title / chapter / bug text, or lower-third second line")+ ap.add_argument("--subtitle", help="title: smaller second line")+ ap.add_argument("--from", dest="count_from", type=int, default=5, help="countdown start number (default 5)")+ ap.add_argument("--start", help="show from (default 0)")+ ap.add_argument("--end", help="hide after (default end of clip)")+ ap.add_argument("--position", choices=["top-left", "top-right", "bottom-left", "bottom-right"], default=None, help="corner for chapter/bug (default bottom-left / top-right)")+ ap.add_argument("--primary", help="override brand primary colour RRGGBB")+ ap.add_argument("--text-color", help="override text colour RRGGBB")+ ap.add_argument("--font")+ ap.add_argument("--font-file")+ ap.add_argument("--scale", type=float, default=1.0, help="size multiplier (default 1)")+ ap.add_argument("--crf", type=int, default=18)+ ap.add_argument("--preset", default="medium")+ add_common(ap)+ args = ap.parse_args()+ apply_common(args)++ brand = load_brand(args.brand)+ primary = color_hex(args.primary or brand["colors"]["primary"])+ text_c = color_hex(args.text_color or brand["colors"]["text"])+ bg = color_hex(brand["colors"].get("background", "101418"))+ margin = int(brand.get("safe_margin", 48))+ fo = font_opts(brand, args.font, args.font_file)++ meta = probe(args.input)+ if not meta.get("video"):+ die("input has no video stream")+ W, H = meta["video"]["width"], meta["video"]["height"]+ if meta["video"].get("rotation") in (90, -90, 270, -270):+ W, H = H, W+ dur = meta.get("duration") or 0.0+ s = parse_time(args.start) if args.start else 0.0+ e = parse_time(args.end) if args.end else dur+ if e <= s:+ die("--end must be after --start")+ en = f"enable='between(t,{s:.3f},{e:.3f})'"+ base = min(W, H) * args.scale # scale everything from the short side+ filters: List[str] = []+ fade_a = f"if(lt(t,{s:.3f}+0.3),(t-{s:.3f})/0.3,if(gt(t,{e:.3f}-0.3),({e:.3f}-t)/0.3,1))"++ extra_inputs: List[str] = []+ fc: List[str] = [] # filter_complex chains (used by templates that need animated boxes)+ if args.template == "lower-third":+ if not args.name:+ die("lower-third needs --name")+ h1 = int(base * 0.055)+ h2 = int(base * 0.038)+ pad = int(base * 0.02)+ bar_h = h1 + (h2 + pad if args.title else 0) + pad * 2+ bar_w = int(base * 0.62)+ y0 = H - margin - bar_h+ # slide in from the left over 0.4 s, slide out over 0.3 s (overlay evaluates x per frame)+ x_expr = f"if(lt(t,{s:.3f}+0.4),-{bar_w}+({bar_w}+{margin})*((t-{s:.3f})/0.4),if(gt(t,{e:.3f}-0.3),{margin}-({bar_w}+{margin})*(1-({e:.3f}-t)/0.3),{margin}))"+ fc.append(f"color=c=0x{bg}@0.85:s={bar_w}x{bar_h}:r={meta['video'].get('fps') or 30:g},format=rgba[bar]")+ fc.append(f"color=c=0x{primary}:s={int(base * 0.012)}x{bar_h}:r={meta['video'].get('fps') or 30:g},format=rgba[acc]")+ fc.append(f"[0:v][bar]overlay=x='{x_expr}':y={y0}:{en}:eof_action=pass[v1]")+ fc.append(f"[v1][acc]overlay=x='{x_expr}':y={y0}:{en}:eof_action=pass[v2]")+ tx = f"({x_expr})+{int(base * 0.035)}"+ chain = f"drawtext=text='{escape_drawtext(args.name)}':{fo}:fontsize={h1}:fontcolor={ff_color(text_c)}:x='{tx}':y={y0 + pad}:{en}"+ if args.title:+ chain += f",drawtext=text='{escape_drawtext(args.title)}':{fo}:fontsize={h2}:fontcolor={ff_color(primary)}:x='{tx}':y={y0 + pad + h1 + pad // 2}:{en}"+ fc.append(f"[v2]{chain}[vout]")++ elif args.template == "title":+ if not args.title:+ die("title needs --title")+ h1 = int(base * 0.11)+ h2 = int(base * 0.045)+ filters.append(f"drawbox=x=0:y=0:w=iw:h=ih:color={ff_color(bg, 0.55)}:t=fill:{en}")+ filters.append(f"drawtext=text='{escape_drawtext(args.title)}':{fo}:fontsize={h1}:fontcolor={ff_color(text_c)}:x=(w-text_w)/2:y=(h-text_h)/2-{h2 if args.subtitle else 0}:alpha='{fade_a}':{en}")+ filters.append(f"drawbox=x=(iw-{int(base * 0.12)})/2:y=(ih)/2+{h1 // 2 + (0 if args.subtitle else 0)}:w={int(base * 0.12)}:h={max(2, int(base * 0.006))}:color={ff_color(primary)}:t=fill:{en}")+ if args.subtitle:+ filters.append(f"drawtext=text='{escape_drawtext(args.subtitle)}':{fo}:fontsize={h2}:fontcolor={ff_color(primary)}:x=(w-text_w)/2:y=(h-text_h)/2+{h1 // 2 + int(base * 0.03)}:alpha='{fade_a}':{en}")++ elif args.template in ("chapter", "bug"):+ if not args.title:+ die(f"{args.template} needs --title")+ pos = args.position or ("bottom-left" if args.template == "chapter" else "top-right")+ fs = int(base * (0.04 if args.template == "chapter" else 0.032))+ padx, pady = int(fs * 0.6), int(fs * 0.35)+ xe = f"{margin}" if "left" in pos else f"w-text_w-{margin}"+ ye = f"{margin}" if "top" in pos else f"h-text_h-{margin}"+ box_color = ff_color(primary if args.template == "chapter" else bg, 0.9 if args.template == "chapter" else 0.7)+ txt_color = ff_color(bg if args.template == "chapter" else text_c)+ filters.append(f"drawtext=text='{escape_drawtext(args.title)}':{fo}:fontsize={fs}:fontcolor={txt_color}:x={xe}:y={ye}:box=1:boxcolor={box_color}:boxborderw={pady}|{padx}:alpha='{fade_a}':{en}")++ elif args.template == "progress":+ h = max(3, int(base * 0.008))+ fps = meta['video'].get('fps') or 30+ fc.append(f"color=c=0x{primary}:s={W}x{h}:r={fps:g},format=rgba[pb]")+ fc.append(f"[0:v]drawbox=x=0:y=ih-{h}:w=iw:h={h}:color={ff_color(bg, 0.5)}:t=fill:{en}[v1]")+ fc.append(f"[v1][pb]overlay=x='-w+w*min(1,max(0,(t-{s:.3f})/{e - s:.3f}))':y={H - h}:{en}:eof_action=pass[vout]")++ elif args.template == "countdown":+ n = args.count_from+ seg = (e - s) / (n + 1)+ fs = int(base * 0.32)+ for k in range(n, -1, -1):+ ks = s + (n - k) * seg+ ke = ks + seg+ pulse = f"1-0.15*min(1,(t-{ks:.3f})/{seg * 0.5:.3f})"+ filters.append(f"drawtext=text='{k}':{fo}:fontsize={fs}:fontcolor={ff_color(primary)}:borderw={max(2, fs // 40)}:bordercolor={ff_color(bg)}:x=(w-text_w)/2:y=(h-text_h)/2:alpha='{pulse}':enable='between(t,{ks:.3f},{ke:.3f})'")++ output = args.output or default_output(args.input, "gfx")+ cmd = ffmpeg_base() + ["-i", args.input]+ if fc:+ cmd += ["-filter_complex", ";".join(fc), "-map", "[vout]", "-map", "0:a:0?"]+ else:+ cmd += ["-vf", ",".join(filters), "-map", "0:v:0", "-map", "0:a:0?"]+ cmd += video_args(meta, args.crf, args.preset) + cfr_args(meta)+ cmd += aac_args() if meta.get("audio") else ["-an"]+ cmd.append(output)+ run(cmd)+ r = probe(output)+ info(f"wrote {output} ({r['duration']:.3f}s, {args.template})")+ emit(output, template=args.template)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/overlay.py b/scripts/overlay.pyindex 7c53d52..b5bf0bf 100755--- a/scripts/overlay.py+++ b/scripts/overlay.py@@ -15,7 +15,7 @@ import argparseimport sysfrom typing import List, Optional-from _common import video_args, add_common, apply_common, emit, aac_args, cfr_args, default_output, die, escape_drawtext, escape_filter_path, ffmpeg_base, info, parse_time, probe, run, x264_args+from _common import load_brand, video_args, add_common, apply_common, emit, aac_args, cfr_args, default_output, die, escape_drawtext, escape_filter_path, ffmpeg_base, info, parse_time, probe, run, x264_argsPOS = {"top-left": ("{m}", "{m}"),@@ -76,9 +76,11 @@ def main() -> int:ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)ap.add_argument("input")ap.add_argument("-o", "--output", help="output file (default: <name>_overlay.<ext>)")- src = ap.add_mutually_exclusive_group(required=True)+ src = ap.add_mutually_exclusive_group()src.add_argument("--image", help="PNG/JPG (alpha respected) to composite")src.add_argument("--text", help="text to draw (drawtext)")+ src.add_argument("--logo", action="store_true", help="composite the brand logo from --brand (position/scale/opacity from brand.json)")+ ap.add_argument("--brand", help="brand.json (logo, font, colours, safe margin)")ap.add_argument("--position", default="top-right", help="named position or X,Y (default top-right)")ap.add_argument("--margin", type=int, default=24, help="margin from the edges in px (default 24)")ap.add_argument("--start", help="show from this time (default: whole video)")@@ -104,6 +106,26 @@ def main() -> int:args = ap.parse_args()apply_common(args)+ brand = load_brand(args.brand)+ if args.logo:+ if not brand.get("logo"):+ die("--logo needs a brand.json with a 'logo' entry")+ args.image = brand["logo"]+ if args.position == ap.get_default("position"):+ args.position = brand.get("logo_position", "top-right")+ if not args.scale and not args.scale_percent:+ args.scale = int(brand.get("logo_scale", 160))+ if args.opacity == 1.0:+ args.opacity = float(brand.get("logo_opacity", 1.0))+ if not (args.image or args.text):+ die("give --image, --text or --logo")+ if args.brand:+ if args.margin == ap.get_default("margin"):+ args.margin = int(brand.get("safe_margin", args.margin))+ if args.font == ap.get_default("font"):+ args.font = brand.get("font", args.font)+ if not args.font_file and brand.get("font_file"):+ args.font_file = brand["font_file"]meta = probe(args.input)if not meta.get("video"):die("input has no video stream")diff --git a/scripts/render.py b/scripts/render.pyindex ff9c62e..d179045 100755--- a/scripts/render.py+++ b/scripts/render.py@@ -15,8 +15,13 @@ Project format (all keys optional except clips):"transition": {"type": "fade", "duration": 0.5},"silence": {"threshold": -38, "min_silence": 0.8},"captions": {"text": "cues.txt", "srt": null, "animate": "pop", "karaoke": true, "font": "Noto Sans CJK JP", "size": 28, "position": "bottom"},+ "brand": "brand.json",+ "graphics": [+ {"template": "title", "title": "Episode 12", "subtitle": "The math of video", "start": 0, "end": 4},+ {"template": "lower-third", "name": "Ada Lovelace", "title": "Analyst", "start": 5, "end": 11}+ ],"overlays": [- {"image": "logo.png", "position": "top-right", "scale": 160, "opacity": 0.9},+ {"logo": true},{"text": "Episode 12", "position": "bottom", "start": 1, "end": 5, "fade": 0.3, "box": true}],"audio": {"voice": true, "music": "bed.mp3", "music_volume": -16, "duck": true, "fade_out": 2},@@ -27,7 +32,9 @@ Project format (all keys optional except clips):}Stages run in this order: clips (cut) → join → silence → fit → captions →-overlays → audio → loudness → export → check. Missing stages are skipped.+graphics → overlays → audio → loudness → export → check. Missing stages are+skipped. "brand" points caption/graphics/overlay at a brand.json (fonts,+colours, logo, safe margin); {"logo": true} in overlays places the brand logo.Examples:python3 render.py --init project.json # write a commented starter project@@ -53,7 +60,9 @@ TEMPLATE = {"clips": [{"src": "REPLACE_ME.mp4", "in": "0:00", "out": "0:30"}],"transition": {"type": "fade", "duration": 0.5},"silence": None,+ "brand": None,"captions": None,+ "graphics": [],"overlays": [],"audio": None,"loudness": {"lufs": -14, "tp": -1},@@ -89,7 +98,7 @@ def main() -> int:ap.add_argument("--init", metavar="FILE", help="write a starter project file and exit")ap.add_argument("--work", help="work directory for intermediates (default: <output>_work)")ap.add_argument("--keep", action="store_true", help="keep intermediates (default: kept only when --work is given)")- ap.add_argument("--stop-after", choices=["clips", "join", "silence", "fit", "captions", "overlays", "audio", "loudness", "export"], help="stop after this stage (for iterating)")+ ap.add_argument("--stop-after", choices=["clips", "join", "silence", "fit", "captions", "graphics", "overlays", "audio", "loudness", "export"], help="stop after this stage (for iterating)")add_common(ap)args = ap.parse_args()apply_common(args)@@ -119,6 +128,7 @@ def main() -> int:work.mkdir(parents=True, exist_ok=True)frame = proj.get("frame") or {}trans = proj.get("transition") or {}+ brand_args: List[str] = ["--brand", rel(proj["brand"])] if proj.get("brand") else []stages_done: List[str] = []# ---- clips@@ -222,18 +232,37 @@ def main() -> int:for k, flag in (("karaoke", "--karaoke"), ("bold", "--bold"), ("box", "--box")):if cap.get(k):argv.append(flag)- sh("caption.py", *argv)+ sh("caption.py", *(argv + brand_args))current = nxtstages_done.append("captions")if args.stop_after == "captions":emit(current, stages=stages_done)return 0+ # ---- graphics+ for i, g in enumerate(proj.get("graphics") or []):+ nxt = str(work / f"graphics{i:02d}.mp4")+ if not g.get("template"):+ die(f"graphics[{i}] needs a template")+ argv = [current, "-o", nxt, "--template", g["template"]]+ for k, flag in (("name", "--name"), ("title", "--title"), ("subtitle", "--subtitle"), ("start", "--start"), ("end", "--end"), ("position", "--position"), ("from", "--from"), ("scale", "--scale"), ("primary", "--primary"), ("text_color", "--text-color")):+ if g.get(k) is not None:+ argv += [flag, str(g[k])]+ sh("graphics.py", *(argv + brand_args))+ current = nxt+ if "graphics" not in stages_done:+ stages_done.append("graphics")+ if args.stop_after == "graphics":+ emit(current, stages=stages_done)+ return 0+# ---- overlaysfor i, ov in enumerate(proj.get("overlays") or []):nxt = str(work / f"overlay{i:02d}.mp4")argv = [current, "-o", nxt]- if ov.get("image"):+ if ov.get("logo"):+ argv.append("--logo")+ elif ov.get("image"):argv += ["--image", rel(ov["image"])]elif ov.get("text"):argv += ["--text", ov["text"]]@@ -244,7 +273,7 @@ def main() -> int:argv += [flag, str(ov[k])]if ov.get("box"):argv.append("--box")- sh("overlay.py", *argv)+ sh("overlay.py", *(argv + brand_args))current = nxtif "overlays" not in stages_done:stages_done.append("overlays")diff --git a/scripts/report.py b/scripts/report.pynew file mode 100755index 0000000..f15e72e--- /dev/null+++ b/scripts/report.py@@ -0,0 +1,162 @@+#!/usr/bin/env python3+"""Build a single-file HTML delivery report: what went in, what came out,+before/after contact sheets, loudness, compliance and the exact commands.+The agent hands this to the user instead of a wall of text.++Examples:+ python3 report.py --before raw.mov --after final.mp4 -o report.html+ python3 report.py --after final.mp4 --platform reels --title "Episode 12 — Reels cut" -o report.html+ python3 report.py --before raw.mov --after final.mp4 --commands commands.txt --notes notes.md+"""+import argparse+import base64+import html+import json+import os+import subprocess+import sys+import tempfile+from pathlib import Path+from typing import Any, Dict, List, Optional++from _common import add_common, apply_common, die, emit, info, probe++HERE = Path(__file__).resolve().parent+++def sheet_b64(path: str, tiles: str = "4x2", width: int = 1200) -> Optional[str]:+ with tempfile.TemporaryDirectory(prefix="ffskill_report_") as tmp:+ png = os.path.join(tmp, "sheet.png")+ proc = subprocess.run([sys.executable, str(HERE / "look.py"), path, "--tiles", tiles, "--width", str(width), "-o", png],+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)+ if proc.returncode != 0 or not os.path.exists(png):+ return None+ return base64.b64encode(Path(png).read_bytes()).decode("ascii")+++def loudness(path: str) -> Dict[str, Any]:+ proc = subprocess.run([sys.executable, str(HERE / "loudness.py"), path, "--measure-only"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)+ try:+ d = json.loads(proc.stdout)+ return {"lufs": round(float(d["input_i"]), 1), "tp": round(float(d["input_tp"]), 1), "lra": round(float(d["input_lra"]), 1)}+ except (ValueError, KeyError):+ return {}+++def check(path: str, platform: str) -> Optional[Dict[str, Any]]:+ proc = subprocess.run([sys.executable, str(HERE / "check.py"), path, "--platform", platform, "--json"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)+ try:+ return json.loads(proc.stdout)+ except ValueError:+ return None+++def fmt_dur(sec: Optional[float]) -> str:+ if not sec:+ return "?"+ m, s = divmod(sec, 60)+ h, m = divmod(int(m), 60)+ return f"{h}:{m:02d}:{s:05.2f}" if h else f"{m}:{s:05.2f}"+++def media_rows(meta: Dict[str, Any], ld: Dict[str, Any]) -> List[List[str]]:+ v, a = meta.get("video") or {}, meta.get("audio") or {}+ rows = [+ ["Duration", fmt_dur(meta.get("duration"))],+ ["Size", f"{(meta.get('size_bytes') or 0) / 1024 / 1024:.1f} MB"],+ ["Video", f"{v.get('codec')} {v.get('width')}×{v.get('height')} @ {v.get('fps')} fps, {v.get('pix_fmt')}" if v else "none"],+ ["Colour", (f"{v.get('color_primaries')}/{v.get('color_transfer')}" + (f" — {v.get('hdr_format')}" if v.get("hdr") else " (SDR)")) if v else "—"],+ ["Frame rate", ("variable (suspected)" if v.get("variable_frame_rate_suspected") else "constant") if v else "—"],+ ["Audio", f"{a.get('codec')} {a.get('channels')} ch {a.get('sample_rate')} Hz" if a else "none"],+ ]+ if ld:+ rows.append(["Loudness", f"{ld['lufs']} LUFS, TP {ld['tp']} dBTP, LRA {ld['lra']} LU"])+ return rows+++def main() -> int:+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("--after", required=True, help="the deliverable")+ ap.add_argument("--before", help="the source (optional)")+ ap.add_argument("-o", "--output", help="report path (default: <after>_report.html)")+ ap.add_argument("--title", help="report title")+ ap.add_argument("--platform", help="run check.py for this platform and include the table")+ ap.add_argument("--commands", help="text file with the commands that were run (one per line)")+ ap.add_argument("--notes", help="text/markdown file with notes to include verbatim")+ ap.add_argument("--no-sheets", action="store_true", help="skip contact sheets (faster, smaller)")+ add_common(ap)+ args = ap.parse_args()+ apply_common(args)++ after = probe(args.after)+ before = probe(args.before) if args.before else None+ ld_after = loudness(args.after) if after.get("audio") else {}+ ld_before = loudness(args.before) if before and before.get("audio") else {}+ chk = check(args.after, args.platform) if args.platform else None+ sheets = {}+ if not args.no_sheets:+ if before and before.get("video"):+ sheets["before"] = sheet_b64(args.before)+ if after.get("video"):+ sheets["after"] = sheet_b64(args.after)+ commands = Path(args.commands).read_text(encoding="utf-8").splitlines() if args.commands else []+ notes = Path(args.notes).read_text(encoding="utf-8") if args.notes else ""+ title = args.title or f"Delivery report — {Path(args.after).name}"+ output = args.output or str(Path(args.after).with_name(Path(args.after).stem + "_report.html"))++ def table(rows: List[List[str]]) -> str:+ return "<table>" + "".join(f"<tr><th>{html.escape(k)}</th><td>{html.escape(str(v))}</td></tr>" for k, v in rows) + "</table>"++ parts: List[str] = []+ parts.append(f"<h1>{html.escape(title)}</h1>")+ parts.append(f"<p class='meta'>{html.escape(os.path.abspath(args.after))}</p>")+ cols = []+ if before:+ cols.append(f"<div class='col'><h2>Before</h2><p class='file'>{html.escape(Path(args.before).name)}</p>{table(media_rows(before, ld_before))}"+ + (f"<img src='data:image/png;base64,{sheets['before']}' alt='before contact sheet'>" if sheets.get("before") else "") + "</div>")+ cols.append(f"<div class='col'><h2>After</h2><p class='file'>{html.escape(Path(args.after).name)}</p>{table(media_rows(after, ld_after))}"+ + (f"<img src='data:image/png;base64,{sheets['after']}' alt='after contact sheet'>" if sheets.get("after") else "") + "</div>")+ parts.append("<div class='cols'>" + "".join(cols) + "</div>")+ if chk:+ rows = "".join(+ f"<tr class='{r['status'].lower()}'><td class='st'>{r['status']}</td><td>{html.escape(r['check'])}</td><td>{html.escape(str(r['value']))}</td><td>{html.escape(str(r['expected']))}</td><td>{html.escape(r.get('fix') or '') if r['status'] != 'PASS' else ''}</td></tr>"+ for r in chk["checks"])+ verdict = "READY" if chk.get("ok") else f"{chk.get('failed')} FAIL"+ parts.append(f"<h2>Compliance — {html.escape(args.platform)} <span class='verdict {'ok' if chk.get('ok') else 'bad'}'>{verdict}</span></h2>"+ f"<table class='checks'><tr><th></th><th>check</th><th>value</th><th>expected</th><th>fix</th></tr>{rows}</table>")+ if notes:+ parts.append("<h2>Notes</h2><pre class='notes'>" + html.escape(notes) + "</pre>")+ if commands:+ parts.append("<h2>Commands</h2><pre class='cmd'>" + html.escape("\n".join(commands)) + "</pre>")+ parts.append("<p class='foot'>Generated by ffmpeg-skill · local FFmpeg, no cloud.</p>")++ css = """+ :root{--bg:#F4F6F8;--paper:#fff;--ink:#161B21;--ink2:#4B5661;--line:#D8DEE4;--ok:#2C8A5B;--warn:#C48519;--bad:#B4362F;--accent:#1E6F8E}+ @media (prefers-color-scheme:dark){:root{--bg:#111518;--paper:#191E23;--ink:#E8ECEF;--ink2:#AEB6BE;--line:#2A3138;--ok:#5CC38C;--warn:#E3A63C;--bad:#F07A73;--accent:#5FB2D4}}+ body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.6 system-ui,-apple-system,"Segoe UI",Roboto,"Noto Sans JP",sans-serif}+ .wrap{max-width:1100px;margin:0 auto;padding:32px 20px 60px}+ h1{font-size:26px;margin:0 0 4px}h2{font-size:18px;margin:28px 0 10px}+ .meta{color:var(--ink2);font-size:13px;margin:0 0 20px;word-break:break-all}+ .cols{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:16px}+ .col{background:var(--paper);border:1px solid var(--line);border-radius:6px;padding:14px 16px}+ .col h2{margin-top:0}.file{color:var(--ink2);font-size:13px;margin:0 0 8px}+ table{border-collapse:collapse;width:100%;font-size:14px}th,td{text-align:left;padding:6px 8px;border-bottom:1px solid var(--line);vertical-align:top}+ th{color:var(--ink2);font-weight:500;width:34%}+ img{max-width:100%;border-radius:4px;margin-top:12px;border:1px solid var(--line)}+ .checks{background:var(--paper);border:1px solid var(--line);border-radius:6px;overflow:hidden}.checks th{width:auto}+ .st{font-weight:700;font-family:ui-monospace,Menlo,monospace}tr.pass .st{color:var(--ok)}tr.warn .st{color:var(--warn)}tr.fail .st{color:var(--bad)}+ .verdict{font-size:13px;padding:2px 8px;border-radius:3px;margin-left:8px;vertical-align:middle}.verdict.ok{background:var(--ok);color:#fff}.verdict.bad{background:var(--bad);color:#fff}+ pre{background:var(--paper);border:1px solid var(--line);border-radius:6px;padding:12px 14px;overflow-x:auto;font-size:12.5px;line-height:1.5}+ .foot{color:var(--ink2);font-size:12px;margin-top:36px;border-top:1px solid var(--line);padding-top:10px}+ """+ doc = f"<!doctype html><html><head><meta charset='utf-8'><meta name='viewport' content='width=device-width,initial-scale=1'><title>{html.escape(title)}</title><style>{css}</style></head><body><div class='wrap'>{''.join(parts)}</div></body></html>"+ Path(output).write_text(doc, encoding="utf-8")+ info(f"wrote {output} ({os.path.getsize(output) / 1024:.0f} KB)")+ emit(None, report=output, check=chk)+ if not args.json:+ print(output)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/test_all.py b/tests/test_all.pyindex 7421698..3e59e36 100644--- a/tests/test_all.py+++ b/tests/test_all.py@@ -637,6 +637,64 @@ class FFmpegSkillTests(unittest.TestCase):m = probe(str(out))["video"]self.assertEqual((m["width"], m["height"]), (640, 360))+ # ---------------------------------------------------------------- v0.6: graphics / brand / report+ def test_graphics_templates(self):+ brand = OUT / "brand.json"+ brand.write_text(json.dumps({"font": "DejaVu Sans", "colors": {"primary": "FF6A00", "text": "FFFFFF", "background": "0B1D2A"},+ "logo": "logo.png", "logo_position": "top-right", "logo_scale": 140, "safe_margin": 40,+ "caption": {"size": 28, "position": "bottom", "animate": "pop", "karaoke": True, "bold": True}}), encoding="utf-8")+ cases = {+ "lower-third": ["--name", "Ada Lovelace", "--title", "Analyst", "--start", "1", "--end", "6"],+ "title": ["--title", "Episode 12", "--subtitle", "The math of video", "--start", "0", "--end", "4"],+ "chapter": ["--title", "Part 2", "--start", "0", "--end", "5"],+ "progress": [],+ "countdown": ["--from", "3", "--start", "1", "--end", "5"],+ "bug": ["--title", "@handle"],+ }+ for name, argv in cases.items():+ out = OUT / f"gfx_{name}.mp4"+ proc = script("graphics.py", self.src, "--template", name, "--brand", brand, "--fast", "-o", out, *argv)+ self.assertClose(probe(str(out))["duration"], 12.0, 0.2, name)+ self.assertTrue("FF6A00" in proc.stderr or "0B1D2A" in proc.stderr, f"{name} uses the brand colours")+ # animated templates must actually move: lower-third frame mid-slide differs from settled frame+ script("look.py", OUT / "gfx_lower-third.mp4", "--at", "1.15", "--at", "3", "--no-timecode", "-o", OUT / "lt")+ a, b = (OUT / "lt_1.150s.png").read_bytes(), (OUT / "lt_3.000s.png").read_bytes()+ self.assertNotEqual(a[200:4000], b[200:4000])+ script("graphics.py", self.src, "--template", "lower-third", expect_fail=True)++ def test_brand_defaults_apply_to_caption_and_logo(self):+ brand = OUT / "brand.json"+ if not brand.exists():+ self.test_graphics_templates()+ ass = OUT / "brand.ass"+ script("caption.py", self.src, "--text", self.cues, "--brand", brand, "--write-ass", ass, "--fast", "-o", OUT / "brand_cap.mp4")+ style = [l for l in ass.read_text(encoding="utf-8-sig").splitlines() if l.startswith("Style:")][0]+ self.assertIn("&H00006AFF", style, "primary FF6A00 becomes the karaoke fill (BGR)")+ self.assertIn(",70,", style, "size 28 scaled to 720p")+ self.assertIn("\\kf", ass.read_text(encoding="utf-8-sig"), "brand enables karaoke")+ proc = script("overlay.py", self.src, "--logo", "--brand", brand, "--fast", "-o", OUT / "brand_logo.mp4")+ self.assertIn("scale=140:-1", proc.stderr)+ self.assertIn("overlay=W-w-40:40", proc.stderr)+ script("overlay.py", self.src, "--logo", expect_fail=True)++ def test_report_html(self):+ reels = OUT / "export_reels.mp4"+ if not reels.exists():+ script("export.py", self.src, "--preset", "reels", "--fit", "crop", "-o", reels)+ cmds = OUT / "cmds.txt"+ cmds.write_text("python3 export.py source.mp4 --preset reels\n")+ out = OUT / "report.html"+ data = json.loads(script("report.py", "--before", self.src, "--after", reels, "--platform", "reels", "--commands", cmds, "--title", "Test delivery", "-o", out, "--json").stdout)+ self.assertEqual(data["report"], str(out))+ html_text = out.read_text(encoding="utf-8")+ self.assertIn("Test delivery", html_text)+ self.assertEqual(html_text.count("data:image/png;base64"), 2, "before and after contact sheets")+ self.assertIn("export.py source.mp4 --preset reels", html_text)+ self.assertIn("class='verdict", html_text)+ self.assertIn("1080×1920", html_text)+ script("report.py", "--after", reels, "--no-sheets", "-o", OUT / "report2.html")+ self.assertLess((OUT / "report2.html").stat().st_size, 40000)+# ---------------------------------------------------------------- helpdef test_every_script_has_help(self):for name in sorted(p.name for p in SCRIPTS.glob("*.py") if not p.name.startswith("_")):