Write talking-head scripts and produce Instagram reels and YouTube shorts
96%
Does it follow best practices?
Impact
98%
1.07xAverage score across 8 eval scenarios
Low
Low-risk findings worth noting
#!/usr/bin/env python3
"""Talk layout: a recorded talk excerpt composed into a 9:16 layout clip.
A stage camera shoots wide: two speakers small in frame, the slide on a screen
nobody can read. Center-cropping that to 9:16 loses both the slide and one
speaker. This stacks the parts a viewer needs, top to bottom:
series label + headline (plain line, accent line in italic)
slide panel the talk's slide video at the matching moment (optional)
name plates left and right speaker, over the camera panel
camera panel a fixed crop of the wide shot (both speakers), optionally graded
Positions are fixed constants chosen to clear the TikTok / IG Reels / Shorts
UI (safe_zones.ZONES): nothing important in the top band, the right rail or
the bottom band; captions burned later at --position 0.70 sit over the camera
panel, inside every zone.
The output is an ordinary clip. It becomes the single segment of a
talking-head cut_plan.json, so render, captions, QC, the gates and export run
unchanged (references/long-form.md, "Talk layout").
plan/layout.json (schema_version 2; owner: this script; docs/adr/0005). Every
command reads the spec through migrate(): a version 1 spec (version 2 without
"end_card") is upgraded and rewritten on read; `talk_layout.py migrate` runs
the same upgrade on its own.
{"schema_version": 2,
"camera": {"file": "raw/excerpt.mp4", "crop": [x, y, w, h], "grade": "none"},
"slides": {"file": "/path/slides_track.mp4", "start": 281.6}, # optional
"headline": {"plain": "Don't forget how to be a", "accent": "software engineer"},
"label": "THE MISSING PROTOCOL · CURRENT 2026 SF", # optional
"names": {"left": "Sean Falconer", "right": "Viktor Gamov @gamussa"}, # optional
"style": {"fonts": {"serif", "serif_italic", "sans", "sans_bold"},
"colors": {"text", "muted", "accent", "bg_top", "bg_bottom"}}, # optional
"end_card": {"text": "Follow @gamussa", "sub": "Full talk: link in bio",
"seconds": 1.5}, # optional, v2
"out": "work/layout/talk.mp4"}
camera.crop pixels of the camera file: both speakers, head to knee at least
camera.grade a render_reel.py grade name, applied to the camera only — the
graphics are never graded
end_card holds the last frame of both panels for `seconds` after the
excerpt, under a card (text + optional sub) over the camera
panel, so a short whose speaker keeps talking ends on a
deliberate beat instead of a cut. The clip is that much
longer; the talk audio is silent under it (the cut plan's
"vo" is padded by render_reel.py).
slides.start seconds into the slides file at the excerpt's t=0: the
excerpt's source start (raw/excerpt.provenance.json
"excerpt_start") minus the slide video's own offset into the talk
Two ways to make the layout clip from the same spec:
build ImageMagick still graphics + ffmpeg composite, with the talk's
audio. Needs only the tools captions already need.
hyperframes writes a Hyperframes project (assets/hyperframes-talk): the
camera crop and slide segment as browser-safe H.264 (dense
keyframes), the fonts, and index.html with an animated
headline and panels. Then `npm --prefix <project> ci` and
render_hyperframes.py [--docker] render it; the clip is silent,
so the cut plan carries the talk audio as "vo".
Usage:
talk_layout.py check plan/layout.json
talk_layout.py migrate plan/layout.json (owner upgrade of an older spec)
talk_layout.py build plan/layout.json [--resolution 1080|4k]
talk_layout.py hyperframes plan/layout.json --project work/motion/talk
Exit codes: 0 ok; 1 invalid spec or failed step. JSON on stdout; on failure
the same error, with what to do, also goes to stderr.
"""
import argparse
import hashlib
import html
import json
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from gen_captions import FONT_FALLBACKS, known_fonts, resolve_font # noqa: E402
from provenance import file_fp, fp_matches, sha256_file, write_render_record # noqa: E402
from render_reel import GRADES # noqa: E402
SCHEMA_VERSION = 2
BASE_W, BASE_H = 1080, 1920
SIZES = {"1080": (1080, 1920), "4k": (2160, 3840)}
FPS = 30
# Layout at 1080x1920; 4K scales every number by 2. Boxes are (x, y, w, h).
MARGIN = 40
LABEL_Y, LABEL_PT = 150, 30
PLAIN_Y, PLAIN_PT = 192, 76
ACCENT_Y, ACCENT_PT = 272, 92
SLIDE_BOX = (40, 410, 1000, 562) # even sizes: H.264 needs them
CAM_BOX = (40, 1052, 1000, 790)
CAM_BOX_NO_SLIDES = (40, 470, 1000, 1372)
NAME_PT, NAME_ABOVE = 30, 64
RIGHT_NAME_EDGE = 920 # right plate ends left of the platforms' right rail
RADIUS = 22
SHADOW_BLUR, SHADOW_ALPHA = 14, "96"
FRAME_ALPHA = "3C"
DEFAULT_COLORS = {
"text": "#F5F5F7",
"muted": "#B0B4C4",
"accent": "#E8633A",
"bg_top": "#101426",
"bg_bottom": "#1E142E",
}
FONT_KINDS = {
"serif": "regular",
"serif_italic": "italic",
"sans": "regular",
"sans_bold": "regular",
}
HEX = re.compile(r"^#[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?$")
ASSETS = Path(__file__).resolve().parent.parent / "assets"
HF_TEMPLATE = ASSETS / "hyperframes-talk" / "index.html"
HF_STARTER = ASSETS / "hyperframes-motion" # its package.json + lock pin Hyperframes and GSAP
# Headline type in the HTML layout: the largest size up to the 1080 base whose
# estimated width (characters x average glyph width in em) fits the 1000 px
# column. Conservative for the serif; check the rendered frame.
PLAIN_EM, ACCENT_EM = 0.43, 0.45
MEDIA_CRF = "16"
CARD_SECONDS = (0.5, 5.0) # an end card shorter reads as a glitch, longer as dead air
CARD_TEXT_PT, CARD_SUB_PT = 64, 34
CARD_DIM = "#000000A6" # over the held camera frame, so the card reads
CARD_FADE = 0.35
class Refused(Exception):
pass
def run(cmd, label):
r = subprocess.run([str(c) for c in cmd], capture_output=True, text=True)
if r.returncode != 0:
raise Refused(f"{label} failed: {r.stderr.strip()[-600:]}")
return r
def probe(path):
"""(width, height, duration, has_audio) of a video file."""
r = run(
[
"ffprobe",
"-v",
"error",
"-show_entries",
"stream=codec_type,width,height:format=duration",
"-of",
"json",
path,
],
f"ffprobe {path}",
)
d = json.loads(r.stdout)
video = next((s for s in d.get("streams", []) if s.get("codec_type") == "video"), None)
if video is None:
raise Refused(f"{path} has no video stream")
has_audio = any(s.get("codec_type") == "audio" for s in d["streams"])
return int(video["width"]), int(video["height"]), float(d["format"]["duration"]), has_audio
def is_num(v):
return isinstance(v, (int, float)) and not isinstance(v, bool)
# Every field the spec may carry: (section, key) -> (required, type test, what it must be).
FIELDS = {
("camera", "file"): (True, lambda v: isinstance(v, str) and v, "a path string"),
("camera", "crop"): (
True,
lambda v: (
isinstance(v, list)
and len(v) == 4
and all(isinstance(x, int) and not isinstance(x, bool) and x >= 0 for x in v)
and v[2] > 0
and v[3] > 0
),
"[x, y, w, h] in whole pixels",
),
("camera", "grade"): (
False,
lambda v: isinstance(v, str) and v in GRADES,
f"one of {sorted(GRADES)}",
),
("slides", "file"): (True, lambda v: isinstance(v, str) and v, "a path string"),
("slides", "start"): (
True,
lambda v: is_num(v) and v >= 0,
"seconds >= 0 into the slides file",
),
("headline", "plain"): (True, lambda v: isinstance(v, str) and v.strip(), "a non-empty string"),
("headline", "accent"): (False, lambda v: isinstance(v, str), "a string"),
("end_card", "text"): (True, lambda v: isinstance(v, str) and v.strip(), "a non-empty string"),
("end_card", "sub"): (False, lambda v: isinstance(v, str), "a string"),
("end_card", "seconds"): (
True,
lambda v: is_num(v) and CARD_SECONDS[0] <= v <= CARD_SECONDS[1],
f"seconds between {CARD_SECONDS[0]} and {CARD_SECONDS[1]}",
),
("names", "left"): (False, lambda v: isinstance(v, str), "a string"),
("names", "right"): (False, lambda v: isinstance(v, str), "a string"),
}
SECTIONS = {
"camera": True,
"headline": True,
"slides": False,
"names": False,
"style": False,
"end_card": False,
}
def validate(spec, probe=probe):
"""Errors in a layout spec, [] when it can be built. Types are checked
before any value is used, so a malformed spec is named, never crashed on."""
if not isinstance(spec, dict):
return ["the layout spec must be a JSON object — see the talk_layout.py header"]
version = spec.get("schema_version")
if version != SCHEMA_VERSION:
return [f"schema_version must be {SCHEMA_VERSION}; a newer spec needs a newer skill"]
errors = [
f"{name} must be an object — see the talk_layout.py header"
for name, required in SECTIONS.items()
if (required or name in spec) and not isinstance(spec.get(name), dict)
]
if errors:
return errors
for (section, key), (required, ok, what) in FIELDS.items():
if section not in spec:
continue
if key not in spec[section]:
if required:
errors.append(f"{section}.{key} is required: {what}")
elif not ok(spec[section][key]):
errors.append(f"{section}.{key} must be {what}")
known = {
"names": {"left", "right"},
"headline": {"plain", "accent"},
"end_card": {"text", "sub", "seconds"},
}
for section, keys in known.items():
extra = sorted(set(spec.get(section, {})) - keys)
if extra:
errors.append(f"{section} has unknown keys {extra}; allowed: {sorted(keys)}")
if "label" in spec and not isinstance(spec["label"], str):
errors.append("label must be a string")
if not (isinstance(spec.get("out"), str) and spec["out"].endswith(".mp4")):
errors.append("out must be an .mp4 path string")
style = spec.get("style", {})
for sub in ("fonts", "colors"):
if sub in style and not isinstance(style[sub], dict):
errors.append(f"style.{sub} must be an object")
for k, v in (style.get("fonts") if isinstance(style.get("fonts"), dict) else {}).items():
if k not in FONT_KINDS or not isinstance(v, str):
errors.append(
f"style.fonts.{k} must be a font file path or ImageMagick font name, "
f"key one of {sorted(FONT_KINDS)}"
)
for k, v in (style.get("colors") if isinstance(style.get("colors"), dict) else {}).items():
if k not in DEFAULT_COLORS or not isinstance(v, str) or not HEX.match(v):
errors.append(f"style.colors.{k} must be one of {sorted(DEFAULT_COLORS)} as #RRGGBB")
if errors:
return errors
cam = spec["camera"]
if not Path(cam["file"]).is_file():
return [f"camera.file {cam['file']!r} is missing"]
w, h, _, _ = probe(cam["file"])
x, y, cw, ch = cam["crop"]
if x + cw > w or y + ch > h:
errors.append(f"camera.crop {cam['crop']} runs outside the {w}x{h} camera frame")
if "slides" in spec and not Path(spec["slides"]["file"]).is_file():
errors.append(f"slides.file {spec['slides']['file']!r} is missing")
return errors
def esc(text):
"""Text for an ImageMagick -annotate / label: argument, taken literally."""
t = str(text).replace("\\", "\\\\").replace("%", "%%")
return "\\" + t if t.startswith("@") else t
def text_width(magick, font, pt, text):
r = run(
[magick, "-font", font, "-pointsize", pt, f"label:{esc(text)}", "-format", "%w", "info:"],
"measure text",
)
return int(r.stdout.strip() or 0)
def fit_pt(magick, font, pt, text, max_w, floor=30):
"""Largest point size <= pt at which text fits max_w pixels."""
while pt > floor and text_width(magick, font, pt, text) > max_w:
pt -= 2
return pt
def resolve_fonts(magick, wanted):
known = known_fonts(magick)
fonts, warnings = {}, []
for key, kind in FONT_KINDS.items():
name = wanted.get(key) or FONT_FALLBACKS[kind][-1]
font, warn = resolve_font(name, kind, known)
if warn and wanted.get(key):
raise Refused(
f"style.fonts.{key} {name!r} is neither a font file nor an ImageMagick "
f"font — fix it, or remove the key to use the installed fallback"
)
fonts[key] = font
return fonts, warnings
def boxes(spec, s):
def sc(b):
return tuple(round(v * s) for v in b)
if spec.get("slides"):
return sc(SLIDE_BOX), sc(CAM_BOX)
return None, sc(CAM_BOX_NO_SLIDES)
def background(spec, magick, size, out):
"""The still layer: gradient, panel shadows and frames, text. Returns warnings."""
W, H = size
s = W / BASE_W
colors = {**DEFAULT_COLORS, **((spec.get("style") or {}).get("colors") or {})}
fonts, warnings = resolve_fonts(magick, (spec.get("style") or {}).get("fonts") or {})
slide, cam = boxes(spec, s)
panels = [b for b in (slide, cam) if b]
r = round(RADIUS * s)
shadow = ["(", "-size", f"{W}x{H}", "xc:none", "-fill", f"#000000{SHADOW_ALPHA}"]
for x, y, w, h in panels:
shadow += [
"-draw",
f"roundrectangle {x + 6 * s},{y + 12 * s} {x + w + 6 * s},{y + h + 12 * s} {r},{r}",
]
shadow += ["-blur", f"0x{SHADOW_BLUR * s}", ")", "-composite"]
frames = [
"-fill",
"none",
"-stroke",
f"#FFFFFF{FRAME_ALPHA}",
"-strokewidth",
str(round(2 * s)),
]
for x, y, w, h in panels:
frames += [
"-draw",
f"roundrectangle {x - 2 * s},{y - 2 * s} {x + w + 1 * s},{y + h + 1 * s} {r + 2 * s},{r + 2 * s}",
]
frames += ["-stroke", "none"]
head = spec["headline"]
max_w = W - 2 * MARGIN * s
text = ["-gravity", "NorthWest"]
m = round(MARGIN * s)
if spec.get("label"):
text += [
"-font",
fonts["sans"],
"-pointsize",
str(round(LABEL_PT * s)),
"-fill",
colors["muted"],
"-annotate",
f"+{m}+{round(LABEL_Y * s)}",
esc(spec["label"]),
]
pt = fit_pt(magick, fonts["serif"], round(PLAIN_PT * s), head["plain"], max_w)
text += [
"-font",
fonts["serif"],
"-pointsize",
str(pt),
"-fill",
colors["text"],
"-annotate",
f"+{m}+{round(PLAIN_Y * s)}",
esc(head["plain"]),
]
if head.get("accent"):
pt = fit_pt(magick, fonts["serif_italic"], round(ACCENT_PT * s), head["accent"], max_w)
text += [
"-font",
fonts["serif_italic"],
"-pointsize",
str(pt),
"-fill",
colors["accent"],
"-annotate",
f"+{m}+{round(ACCENT_Y * s)}",
esc(head["accent"]),
]
names = spec.get("names") or {}
cx, cy, cw, _ = cam
npt, ny = round(NAME_PT * s), cy - round(NAME_ABOVE * s)
if names.get("left"):
text += [
"-font",
fonts["sans_bold"],
"-pointsize",
str(npt),
"-fill",
colors["text"],
"-annotate",
f"+{cx + round(8 * s)}+{ny}",
esc(names["left"]),
]
text += [
"-fill",
colors["accent"],
"-draw",
f"rectangle {cx + 8 * s},{cy - 22 * s} {cx + 68 * s},{cy - 18 * s}",
]
if names.get("right"):
tw = text_width(magick, fonts["sans_bold"], npt, names["right"])
text += [
"-font",
fonts["sans_bold"],
"-pointsize",
str(npt),
"-fill",
colors["text"],
"-annotate",
f"+{round(RIGHT_NAME_EDGE * s) - tw}+{ny}",
esc(names["right"]),
]
run(
[
magick,
"-size",
f"{W}x{H}",
f"gradient:{colors['bg_top']}-{colors['bg_bottom']}",
*shadow,
*frames,
*text,
"-alpha",
"off",
out,
],
"background",
)
return warnings
def mask(magick, w, h, r, out):
run(
[
magick,
"-size",
f"{w}x{h}",
"xc:black",
"-fill",
"white",
"-draw",
f"roundrectangle 0,0 {w - 1},{h - 1} {r},{r}",
out,
],
"panel mask",
)
INPUTS_SCHEMA = 2 # 2 adds "fonts"
def inputs_record_path(out):
return Path(f"{out}.inputs.json")
def read_spec(spec_path):
"""(spec, sha256) from ONE read of the file: the spec that renders is the
one the record's hash certifies."""
raw = Path(spec_path).read_bytes()
return json.loads(raw), hashlib.sha256(raw).hexdigest()
def inputs_snapshot(spec_path, spec, spec_sha=None):
"""The spec hash and every input fingerprint, taken BEFORE any input is read.
spec_sha is the hash of the bytes `spec` was parsed from (read_spec)."""
return {
"spec_sha256": spec_sha or sha256_file(spec_path),
"camera": file_fp(spec["camera"]["file"]),
"slides": file_fp(spec["slides"]["file"]) if spec.get("slides") else None,
"fonts": spec_font_files(spec),
}
def confirm_unchanged(spec_path, spec, before):
"""Refuse when an input or the spec changed while it was being read: the
clip would then mix old and new inputs, and a record would vouch for it."""
if inputs_snapshot(spec_path, spec) != before:
raise Refused(
"an input or the layout spec changed while the layout was being built — run it again"
)
def write_inputs_record(spec_path, spec, engine, snapshot):
"""What a layout clip is built from, written BEFORE the clip renders and
from a snapshot taken before any input was read: the clip is current only
if it is newer than this record and every input still matches
(layout_status). Both engines write it, so pipeline.py judges them alike."""
rec = {"schema_version": INPUTS_SCHEMA, "engine": engine, "spec": str(spec_path), **snapshot}
path = inputs_record_path(spec["out"])
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(rec, indent=2) + "\n")
def spec_font_files(spec):
"""{key: fingerprint} for every style.fonts entry that is a font FILE (an
ImageMagick font name has no file to fingerprint)."""
fonts = (spec.get("style") or {}).get("fonts") or {}
return {k: file_fp(v) for k, v in sorted(fonts.items()) if Path(v).is_file()}
def layout_status(spec_path, resolution="1080"):
"""(state, detail) of the layout clip: ready (not built, or the spec is not
usable yet), stale (an input, the spec or the frame size changed since it was
built), or done. Read-only: an older spec is reported, never rewritten here."""
try:
spec = json.loads(Path(spec_path).read_text())
except (OSError, json.JSONDecodeError) as err:
return "ready", f"{spec_path} unreadable ({err}) — run talk_layout.py check"
if not isinstance(spec, dict) or spec.get("schema_version") != SCHEMA_VERSION:
return "ready", (
f"{spec_path} is not a schema_version {SCHEMA_VERSION} spec — run "
f"talk_layout.py check (it upgrades an older one)"
)
try:
errors = validate(spec)
except Refused as err: # the camera exists but ffprobe cannot read it
errors = [f"camera.file cannot be read ({err}) — replace it, then rebuild the layout"]
out = Path(spec["out"]) if isinstance(spec.get("out"), str) else None
if errors: # a clip built from inputs that are now missing or invalid is stale, never done
return ("stale" if out and out.exists() else "ready"), f"{spec_path}: {errors[0]}"
assert out is not None # validate() requires a string out
if not out.exists():
return "ready", f"no layout clip at {out} yet"
try:
rec = json.loads(inputs_record_path(out).read_text())
except (OSError, json.JSONDecodeError):
return "stale", f"{out} has no inputs record — rebuild it with talk_layout.py"
if not isinstance(rec, dict) or rec.get("schema_version") != INPUTS_SCHEMA:
return "stale", f"{inputs_record_path(out)} is an unknown version — rebuild the layout"
if rec.get("spec_sha256") != sha256_file(spec_path):
return "stale", f"{spec_path} changed since {out} was built"
# every input the spec names must be in the record and still match it
for key in ("camera", "slides"):
fp = rec.get(key)
if key not in spec:
if fp is not None:
return "stale", f"{out} was built with {key}, the spec has none — rebuild it"
continue
# file_fp() records str(Path(file)), so compare the same normal form
if not isinstance(fp, dict) or fp.get("path") != str(Path(spec[key]["file"])):
return (
"stale",
f"{inputs_record_path(out)} does not record {key} {spec[key]['file']} — rebuild",
)
if not fp_matches(fp):
return "stale", f"{key} {fp['path']} is missing or changed since {out} was built"
# the fonts the spec names: same set, each still matching
recorded = rec.get("fonts")
wanted = (spec.get("style") or {}).get("fonts") or {}
if not isinstance(recorded, dict) or set(recorded) != {
k for k, v in wanted.items() if Path(v).is_file() or k in recorded
}:
return "stale", f"the spec's fonts differ from the ones {out} was built with — rebuild it"
for key, fp in recorded.items():
if (
not isinstance(fp, dict)
or key not in wanted
or fp.get("path") != str(Path(wanted[key]))
):
return (
"stale",
f"font {key} in the record is not the spec's {wanted.get(key)!r} — rebuild",
)
if not fp_matches(fp):
return "stale", f"font {key} is missing or changed since {out} was built"
if out.stat().st_mtime_ns < inputs_record_path(out).stat().st_mtime_ns:
return "stale", f"{out} predates its inputs record — render it again"
try:
w, h, _, _ = probe(out)
except Refused as err:
return "stale", f"{out} is unreadable ({err}) — rebuild it"
if (w, h) != SIZES[resolution]:
return "stale", f"{out} is {w}x{h}, the project is {resolution} — rebuild at that size"
return "done", f"layout clip {out}"
def hold_seconds(spec):
return float((spec.get("end_card") or {}).get("seconds", 0.0))
def card_png(spec, magick, size, s, out):
"""The end card at camera-panel size: a dimmed rounded panel, text over sub."""
w, h = size
colors = {**DEFAULT_COLORS, **((spec.get("style") or {}).get("colors") or {})}
fonts, _ = resolve_fonts(magick, (spec.get("style") or {}).get("fonts") or {})
card, r = spec["end_card"], round(RADIUS * s)
text_pt = fit_pt(
magick, fonts["serif_italic"], round(CARD_TEXT_PT * s), card["text"], w - 80 * s
)
cmd = [
magick,
"-size",
f"{w}x{h}",
"xc:none",
"-fill",
CARD_DIM,
"-draw",
f"roundrectangle 0,0 {w - 1},{h - 1} {r},{r}",
"-gravity",
"center",
"-font",
fonts["serif_italic"],
"-pointsize",
str(text_pt),
"-fill",
colors["accent"],
"-annotate",
f"+0-{round(30 * s)}" if card.get("sub") else "+0+0",
esc(card["text"]),
]
if card.get("sub"):
sub_pt = fit_pt(magick, fonts["sans"], round(CARD_SUB_PT * s), card["sub"], w - 80 * s)
cmd += [
"-font",
fonts["sans"],
"-pointsize",
str(sub_pt),
"-fill",
colors["text"],
"-annotate",
f"+0+{round(48 * s)}",
esc(card["sub"]),
]
run([*cmd, out], "end card")
def build(spec_path, resolution="1080"):
migrate(spec_path)
spec, spec_sha = read_spec(spec_path)
errors = validate(spec)
if errors:
raise Refused(errors[0])
magick = shutil.which("magick")
if not magick:
raise Refused("ImageMagick not found — install it (brew install imagemagick)")
W, H = SIZES[resolution]
s = W / BASE_W
cam_spec, slides = spec["camera"], spec.get("slides")
_, _, dur, has_audio = probe(cam_spec["file"])
if not has_audio:
raise Refused(f"{cam_spec['file']} has no audio — the talk's voice is the spine")
hold = hold_seconds(spec)
total = dur + hold
slide_box, cam_box = boxes(spec, s)
out = Path(spec["out"])
out.parent.mkdir(parents=True, exist_ok=True)
snapshot = inputs_snapshot(spec_path, spec, spec_sha)
write_inputs_record(spec_path, spec, "build", snapshot)
tmp_out = out.with_name(out.stem + ".tmp" + out.suffix)
with tempfile.TemporaryDirectory() as td:
td = Path(td)
warnings = background(spec, magick, (W, H), td / "bg.png")
r = round(RADIUS * s)
mask(magick, cam_box[2], cam_box[3], r, td / "cam_mask.png")
kx, ky, kw, kh = cam_spec["crop"]
grade = GRADES.get(cam_spec.get("grade", "none"))
cam_chain = f"crop={kw}:{kh}:{kx}:{ky},scale={cam_box[2]}:{cam_box[3]}:flags=lanczos"
if grade:
cam_chain += f",{grade}"
inputs = [
"-loop",
"1",
"-framerate",
str(FPS),
"-i",
td / "bg.png",
"-i",
cam_spec["file"],
"-loop",
"1",
"-i",
td / "cam_mask.png",
]
fc = (
f"[1:v]fps={FPS},{cam_chain},tpad=stop_mode=clone:stop_duration={hold:.3f},"
f"format=rgba[c0];[2:v]format=gray[cm];[c0][cm]alphamerge[cam];"
)
base = "[0:v]"
if slides:
assert slide_box is not None # boxes() returns a slide box whenever slides are set
mask(magick, slide_box[2], slide_box[3], r, td / "slide_mask.png")
# read only the speech's span of slides: tpad then holds its last frame under the card
inputs += [
"-ss",
f"{slides['start']:.3f}",
"-t",
f"{dur:.3f}",
"-i",
slides["file"],
"-loop",
"1",
"-i",
td / "slide_mask.png",
]
fc += (
f"[3:v]fps={FPS},scale={slide_box[2]}:{slide_box[3]}:flags=lanczos,"
f"tpad=stop_mode=clone:stop_duration={total:.3f},format=rgba[s0];"
f"[4:v]format=gray[sm];[s0][sm]alphamerge[sl];"
f"[0:v][sl]overlay={slide_box[0]}:{slide_box[1]}[b];"
)
base = "[b]"
if hold:
card_png(spec, magick, (cam_box[2], cam_box[3]), s, td / "card.png")
n = len([a for a in inputs if a == "-i"])
inputs += ["-loop", "1", "-framerate", str(FPS), "-i", td / "card.png"]
fc += (
f"{base}[cam]overlay={cam_box[0]}:{cam_box[1]}[p];"
f"[{n}:v]format=rgba,fade=t=in:st={dur:.3f}:d={CARD_FADE}:alpha=1[card];"
f"[p][card]overlay={cam_box[0]}:{cam_box[1]}:enable='gte(t,{dur:.3f})',"
f"format=yuv420p,setsar=1[v]"
)
else:
fc += f"{base}[cam]overlay={cam_box[0]}:{cam_box[1]},format=yuv420p,setsar=1[v]"
run(
[
"ffmpeg",
"-v",
"error",
"-y",
*inputs,
"-filter_complex",
fc,
"-map",
"[v]",
"-map",
"1:a:0",
"-af",
"apad",
"-t",
f"{total:.3f}",
"-c:v",
"libx264",
"-preset",
"slow",
"-crf",
"14",
"-pix_fmt",
"yuv420p",
"-c:a",
"aac",
"-b:a",
"320k",
"-ar",
"48000",
"-movflags",
"+faststart",
tmp_out,
],
"compose layout",
)
try:
confirm_unchanged(spec_path, spec, snapshot)
except Refused:
tmp_out.unlink(missing_ok=True)
inputs_record_path(out).unlink(missing_ok=True)
raise
w, h, got, _ = probe(tmp_out)
if (w, h) != (W, H) or abs(got - total) > 0.1:
tmp_out.unlink(missing_ok=True)
raise Refused(
f"layout render is {w}x{h} {got:.2f}s, expected {W}x{H} {total:.2f}s — discarded"
)
tmp_out.replace(out)
write_render_record(
out,
spec_path,
inputs={"camera": cam_spec["file"], "slides": slides["file"] if slides else None},
settings={
"engine": "talk_layout",
"resolution": resolution,
"crop": cam_spec["crop"],
"grade": cam_spec.get("grade", "none"),
"slides_start": slides["start"] if slides else None,
"end_card": hold,
},
)
return {
"out": str(out),
"duration": round(got, 3),
"speech_part": round(dur, 3),
"size": f"{W}x{H}",
"warnings": warnings,
}
def font_files(wanted):
"""Font FILES for @font-face: a named font must exist; an unset key takes the
first installed fallback."""
out = {}
for key, kind in FONT_KINDS.items():
name = wanted.get(key)
if name:
if not Path(name).is_file():
raise Refused(
f"style.fonts.{key} {name!r} is not a font file — fix the path, "
f"or remove the key to use the installed fallback"
)
out[key] = Path(name)
continue
found = next((Path(c) for c in FONT_FALLBACKS[kind] if Path(c).is_file()), None)
if found is None:
raise Refused(f"no font file for {key} — set style.fonts.{key} to a .ttf/.otf path")
out[key] = found
return out
def html_px(text, base, em):
return max(30, min(base, int(1000 / max(1.0, len(text) * em))))
def encode_panel(src, start, dur, total, vf, out):
"""`dur` seconds of panel source (the speech), then its last frame held to
`total` (the end card). A source that ends sooner than `dur` holds too; a
source that runs on past `dur` is cut there, so nothing moves under the card."""
run(
[
"ffmpeg",
"-v",
"error",
"-y",
"-ss",
f"{start:.3f}",
"-t",
f"{dur:.3f}",
"-i",
src,
"-vf",
f"{vf},fps={FPS},tpad=stop_mode=clone:stop_duration={total:.3f},format=yuv420p",
"-t",
f"{total:.3f}",
"-an",
"-c:v",
"libx264",
"-preset",
"medium",
"-crf",
MEDIA_CRF,
"-g",
str(FPS),
"-keyint_min",
str(FPS),
"-movflags",
"+faststart",
out,
],
f"encode {Path(out).name}",
)
def hyperframes_project(spec_path, project):
"""Write a Hyperframes talk-layout project; returns what to run next."""
migrate(spec_path)
spec, spec_sha = read_spec(spec_path)
errors = validate(spec)
if errors:
raise Refused(errors[0])
project = Path(project)
cam_spec, slides = spec["camera"], spec.get("slides")
_, _, dur, has_audio = probe(cam_spec["file"])
if not has_audio:
raise Refused(f"{cam_spec['file']} has no audio — the talk's voice is the spine")
hold = hold_seconds(spec)
total = dur + hold
snapshot = inputs_snapshot(spec_path, spec, spec_sha)
slide_box, cam_box = boxes(spec, 1.0)
(project / "media").mkdir(parents=True, exist_ok=True)
(project / "fonts").mkdir(exist_ok=True)
for name in ("package.json", "package-lock.json"):
shutil.copyfile(HF_STARTER / name, project / name)
kx, ky, kw, kh = cam_spec["crop"]
grade = GRADES.get(cam_spec.get("grade", "none"))
cam_vf = f"crop={kw}:{kh}:{kx}:{ky},scale={cam_box[2]}:{cam_box[3]}:flags=lanczos"
encode_panel(
cam_spec["file"],
0.0,
dur,
total,
cam_vf + (f",{grade}" if grade else ""),
project / "media" / "camera.mp4",
)
if slides:
assert slide_box is not None # boxes() returns a slide box whenever slides are set
encode_panel(
slides["file"],
slides["start"],
dur,
total,
f"scale={slide_box[2]}:{slide_box[3]}:flags=lanczos",
project / "media" / "slides.mp4",
)
fonts = {}
for key, path in font_files((spec.get("style") or {}).get("fonts") or {}).items():
dst = project / "fonts" / f"{key}{path.suffix.lower()}"
shutil.copyfile(path, dst)
fonts[key] = f"fonts/{dst.name}"
colors = {**DEFAULT_COLORS, **((spec.get("style") or {}).get("colors") or {})}
head, names = spec["headline"], spec.get("names") or {}
sb = slide_box or (0, 0, 0, 0)
values = {
"font_serif": fonts["serif"],
"font_serif_italic": fonts["serif_italic"],
"font_sans": fonts["sans"],
"font_sans_bold": fonts["sans_bold"],
**colors,
"duration": f"{total:.3f}",
"card_start": f"{dur:.3f}",
"card_seconds": f"{hold:.3f}",
"card_text": html.escape((spec.get("end_card") or {}).get("text", "")),
"card_sub": html.escape((spec.get("end_card") or {}).get("sub", "")),
"label": html.escape(spec.get("label") or ""),
"plain": html.escape(head["plain"]),
"accent_text": html.escape(head.get("accent") or ""),
"plain_px": html_px(head["plain"], PLAIN_PT, PLAIN_EM),
"accent_px": html_px(head.get("accent") or "", ACCENT_PT, ACCENT_EM),
"slide_x": sb[0],
"slide_y": sb[1],
"slide_w": sb[2],
"slide_h": sb[3],
"slide_display": "block" if slides else "none",
"cam_x": cam_box[0],
"cam_y": cam_box[1],
"cam_w": cam_box[2],
"cam_h": cam_box[3],
"name_y": cam_box[1] - NAME_ABOVE,
"rule_y": cam_box[1] - 22,
"name_left_x": cam_box[0] + 8,
"name_right_inset": BASE_W - RIGHT_NAME_EDGE,
"name_left": html.escape(names.get("left") or ""),
"name_right": html.escape(names.get("right") or ""),
"rule_display": "block" if names.get("left") else "none",
}
page = HF_TEMPLATE.read_text()
for key, value in values.items():
page = page.replace("{{" + key + "}}", str(value))
left = sorted(set(re.findall(r"\{\{(\w+)\}\}", page)))
if left:
raise Refused(
f"template keys left unfilled: {left} — update talk_layout.py with the template"
)
if not slides: # no slide video: drop the element so Hyperframes never loads it
page = re.sub(r'\s*<video id="slides-video".*?</video>', "", page, flags=re.S)
if not hold: # no end card: drop it and its animation
page = re.sub(r'\s*<div id="card".*?</div>\s*</div>', "", page, flags=re.S)
page = re.sub(r'\s*tl\.fromTo\("#card".*?\);', "", page, flags=re.S)
(project / "index.html").write_text(page)
confirm_unchanged(spec_path, spec, snapshot)
write_inputs_record(spec_path, spec, "hyperframes", snapshot)
return {
"project": str(project),
"duration": round(total, 3),
"speech_part": round(dur, 3),
"out": spec["out"],
"next": [
f"npm --prefix {project} ci --no-audit --no-fund",
f"render_hyperframes.py {project} --out {spec['out']} [--docker]",
],
}
def migrate(spec_path):
"""Owner upgrade of a layout spec to SCHEMA_VERSION. Version 1 is version 2
without "end_card", so the upgrade only restamps it; a v1 spec carrying
end_card is not a v1 spec and is refused."""
path = Path(spec_path)
spec = json.loads(path.read_text())
if not isinstance(spec, dict) or spec.get("schema_version") != 1:
# current, newer or malformed: nothing to upgrade; validate() names what is wrong
return {
"migrated": False,
"schema_version": spec.get("schema_version") if isinstance(spec, dict) else None,
}
if "end_card" in spec:
raise Refused("a version 1 spec cannot carry end_card — fix the spec by hand")
spec["schema_version"] = SCHEMA_VERSION
tmp = path.with_name(path.name + ".tmp")
tmp.write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n")
tmp.replace(path)
return {"migrated": True, "schema_version": SCHEMA_VERSION, "from": 1}
def main(argv=None):
ap = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
sub = ap.add_subparsers(dest="cmd", required=True)
c = sub.add_parser("check")
c.add_argument("spec")
b = sub.add_parser("build")
b.add_argument("spec")
b.add_argument("--resolution", choices=sorted(SIZES), default="1080")
m = sub.add_parser("migrate")
m.add_argument("spec")
h = sub.add_parser("hyperframes")
h.add_argument("spec")
h.add_argument("--project", required=True, help="directory for the Hyperframes project")
a = ap.parse_args(argv)
try:
if a.cmd == "check":
migrated = migrate(a.spec)
errors = validate(json.loads(Path(a.spec).read_text()))
print(
json.dumps(
{"ok": not errors, "errors": errors, "migrated_from": migrated.get("from")}
)
)
for err in errors:
print(
f"talk_layout.py check: {err} — fix it in {a.spec} and rerun", file=sys.stderr
)
return 0 if not errors else 1
if a.cmd == "migrate":
result = migrate(a.spec)
if result["schema_version"] != SCHEMA_VERSION:
raise Refused(
f"cannot upgrade schema_version {result['schema_version']!r}: only 1 "
f"upgrades to {SCHEMA_VERSION}, and the spec must be a JSON object"
)
print(json.dumps({"ok": True, **result}))
return 0
if a.cmd == "hyperframes":
print(json.dumps({"ok": True, **hyperframes_project(a.spec, a.project)}))
return 0
print(json.dumps({"ok": True, **build(a.spec, a.resolution)}))
return 0
except (Refused, OSError, json.JSONDecodeError) as err:
print(json.dumps({"ok": False, "error": str(err)}))
print(
f"talk_layout.py {a.cmd} failed: {err}\n"
f"Fix the spec or the named input, then rerun: talk_layout.py check {a.spec}",
file=sys.stderr,
)
return 1
if __name__ == "__main__":
sys.exit(main()).tessl-plugin
skills
reel-builder
assets
references
scripts
yap-writer