videogen/tools/freegen/build_ep04_free.py
caelum0x d56639a594
Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

760 lines
31 KiB
Python

"""build_ep04_free.py — EP04 'The Judges', $0 production.
Pipeline: FLUX.1-schnell 4-bit stills (mflux) + Kokoro multi-voice VO + ffmpeg assembly.
Output: ~/products/gtm/oxhan-very-turkish-time/final/oxhan-vtt-ep04-the-judges-free.mp4
Usage:
cd ~/products/videogen/tools/freegen
source .venv/bin/activate
python build_ep04_free.py [--stills-only] [--assemble-only]
"""
from __future__ import annotations
import argparse
import json
import os
import shutil
import subprocess
import sys
import tempfile
import time
from pathlib import Path
# ── paths ──────────────────────────────────────────────────────────────────────
FREEGEN = Path(__file__).parent
VTT = Path.home() / "products/gtm/oxhan-very-turkish-time"
STILLS_DIR = VTT / "stills"
SHEET_DIR = VTT / "sheet/v2"
BRAND_DIR = VTT / "brand"
FINAL_DIR = VTT / "final"
OUT_MP4 = FINAL_DIR / "oxhan-vtt-ep04-the-judges-free.mp4"
DRYRUN_MP4 = FINAL_DIR / "oxhan-vtt-ep04-the-judges-dryrun.mp4"
sys.path.insert(0, str(FREEGEN))
# ── constants ──────────────────────────────────────────────────────────────────
WIDTH, HEIGHT = 1080, 1920
FPS = 30
SAMPLE_RATE = 24000
END_CARD_SECS = 3.0
CAPTION_Y_FRAC = 0.83
CAPTION_FONT_SIZE = 64
HOOK_ZOOM_START, HOOK_ZOOM_END = 1.00, 1.07
PUSH_ZOOM_START, PUSH_ZOOM_END = 1.00, 1.10
STATIC_SCALE = 1.02
LINE_GAP = 0.3 # seconds of silence between spoken lines in the same segment
SHOT_TAIL = 0.2 # seconds of silence after the last line in a segment
# ── character voices (from cast.yaml) ─────────────────────────────────────────
VOICES: dict[str, dict] = {
"H": {"blend": "am_eric:0.50,am_liam:0.30,am_onyx:0.20", "speed": 1.15},
"O": {"blend": "am_liam:0.5,am_echo:0.5", "speed": 0.94},
"J1": {"blend": "bm_george:0.7,am_onyx:0.3", "speed": 0.95},
"J2": {"blend": "af_nicole:0.5,bf_emma:0.5", "speed": 1.00},
"J3": {"blend": "af_heart:1.0", "speed": 1.00},
}
# ── lines (text, caption, speaker) ────────────────────────────────────────────
# (speaker, tts_text, caption_text)
LINES: dict[str, tuple[str, str, str]] = {
"j2a": ("J2", "Where are you from?",
"where are you from"),
"h2": ("H", "Guess!",
"guess"),
"j3a": ("J3", "Italian?",
"italian"),
"h3": ("H", "Close.",
"close"),
"j2b": ("J2", "Spanish? You're forty minutes late.",
"spanish? you're forty minutes late"),
"h4": ("H", "In my country, that's early.",
"in my country, that's early"),
"h5": ("H", "Turkish!",
"turkish"),
"o2": ("O", "He can't sing. It was the tea.",
"he can't sing. it was the tea"),
"h6": ("H", "You met me at a very Turkish time in my life. Get yours at Oxhan Atelier dot com.",
"you met me at a very turkish time in my life. get yours at oxhanatelier.com"),
}
# ── edit sequence ──────────────────────────────────────────────────────────────
# (still_id, line_ids, push_in, forced_dur)
EDIT_SEQUENCE = [
("s0", ["j2a"], False, None), # judges wide: "where are you from?"
("s1", ["h2"], False, None), # hero: "guess"
("s0", ["j3a"], False, None), # judges wide: "italian?"
("s1", ["h3"], False, None), # hero: "close"
("s0", ["j2b"], False, None), # judges wide: "spanish..."
("s1", ["h4", "h5"], False, None), # hero: "in my country... Turkish!"
("s4", [], False, 2.2), # buzzer still: silent reaction
("s2", ["o2"], False, None), # oxhan in wings: deadpan tea line
("s1", ["h6"], True, None), # hero payoff + push-in: CTA
]
# ── still prompts ──────────────────────────────────────────────────────────────
HERO_SHEET = str(SHEET_DIR / "ep03b-sheet-hero.png")
OXHAN_SHEET = str(SHEET_DIR / "ep03b-sheet-oxhan.png")
PRINT_REF = str(BRAND_DIR / "sweatshirt/print-phoenix-owner.png")
LOOK = (
"Look: a mid-2000s pre-rendered video game cinematic cutscene (PlayStation 2 / early PlayStation 3 era CGI): "
"smooth, slightly waxy skin shading, clumped polygonal hair strands, cinematic rim light, soft bloom on lights, "
"gentle compression softness. Clearly CGI, not photoreal, not anime, not cartoon."
)
SET_DESC = (
"Set: an original TV talent-show studio (no real show, no logos, no brand names): glossy black stage floor, "
"one hard white spotlight on the performer, light purple-blue haze, rows of warm bulbs, and facing the stage "
"a long glossy judges' desk with one big round GOLD buzzer in front of the judge on the right."
)
JUDGES_DESC = (
"Three original judges (not resembling any real person): "
"LEFT judge — a man about 60 with swept silver hair, a trimmed grey beard, black-rimmed glasses and a dark "
"velvet blazer, stern; "
"CENTRE judge — a woman about 45 with a sharp black bob, red lipstick, a white blazer and a gold wristwatch, strict; "
"RIGHT judge — a woman about 35 with voluminous curly auburn hair, gold hoop earrings and an emerald dress, warm."
)
HERO_DESC = (
"HERO: Turkish man, late 20s, tanned olive skin, messy swept-back black hair with strands falling forward, "
"strong brows, light stubble, smug confident grin, black fingerless leather gloves, silver rings, "
"a black tespih (prayer beads) wrapped on his left wrist, black trousers."
)
OXHAN_DESC = (
"OXHAN: Turkish man, about 30, tanned skin, short neat near-black hair, straight brows, light stubble, "
"calm deadpan expression, slim build, black trousers, BARE hands: no gloves, no rings, no prayer beads."
)
SWEAT = (
"a relaxed oversized BLACK crewneck sweatshirt; centred on the chest is a dark-red (#7A0F14) "
"flame-feathered phoenix rising behind two lines of bone-white swash serif text reading exactly "
"'You met me at a very' / 'Turkish time in my life.'; reproduce that print faithfully and legibly."
)
NOTEXT = "No other text, no logos, no watermark, no captions."
STILL_PROMPTS: dict[str, dict] = {
"s0": {
"dst": STILLS_DIR / "e4-s0.png",
"seed": 400,
"steps": 4,
"prompt": (
f"Vertical 9:16 medium-wide shot from the stage looking at the judges' desk, cinematic cutscene still. "
f"{SET_DESC} {JUDGES_DESC} All three sit side by side behind the desk, faces clearly visible and lit, "
f"looking toward camera with sceptical expressions; name plates are blank. "
f"The reference image is ONLY for the rendering style; none of these judges is that man. {LOOK} {NOTEXT}"
),
},
"s1": {
"dst": STILLS_DIR / "e4-s1.png",
"seed": 401,
"steps": 4,
"prompt": (
f"Vertical 9:16 medium shot, waist-up, cinematic cutscene still. {SET_DESC} "
f"HERO (exactly the man in the first reference image) stands centre stage in the hard white spotlight "
f"facing the camera (the judges' point of view), smug grin, one gloved hand open in a confident gesture "
f"at waist height; the chest print fully visible, unobstructed and legible, centred; his face in the "
f"upper third. {HERO_DESC} He wears {SWEAT} {LOOK} {NOTEXT}"
),
},
"s2": {
"dst": STILLS_DIR / "e4-s2.png",
"seed": 402,
"steps": 4,
"prompt": (
f"Vertical 9:16 medium close-up, chest-up, cinematic cutscene still. "
f"OXHAN (exactly the man in the first reference image) stands in the dim side wings of the "
f"talent-show stage, half behind a heavy dark-red curtain edge, looking toward the stage with a "
f"completely deadpan face, one hand raised slightly as if warning someone. "
f"Spill of the stage spotlight and purple haze behind him. "
f"The upper chest print with both text lines is visible and legible. "
f"{OXHAN_DESC} He wears {SWEAT} {LOOK} {NOTEXT}"
),
},
"s3": {
"dst": STILLS_DIR / "e4-s3.png",
"seed": 403,
"steps": 4,
"prompt": (
f"Vertical 9:16 medium-wide shot, cinematic cutscene still. "
f"OXHAN (exactly the man in the first reference image, bare hands) stands at the glossy judges' desk "
f"holding a round brass tea tray by its single rigid arched brass handle (no chains), and places a "
f"tulip-shaped glass of red tea on a small white saucer in front of each judge; the judges look surprised. "
f"His chest print is visible and legible. {OXHAN_DESC} He wears {SWEAT} {LOOK} {NOTEXT}"
),
},
"s4": {
"dst": STILLS_DIR / "e4-s4.png",
"seed": 404,
"steps": 4,
"prompt": (
f"Vertical 9:16 medium close-up, cinematic cutscene still: the RIGHT judge "
f"(woman about 35, voluminous curly auburn hair, gold hoop earrings, emerald dress) sits at the "
f"glossy judges' desk, eyes closed in bliss, a tulip-shaped glass of red tea on a white saucer "
f"near her lips; her other open palm is slamming down on the big round GOLD buzzer; "
f"gold confetti bursting and raining down from above; studio bulbs and purple haze behind. {LOOK} {NOTEXT}"
),
},
}
# ── helpers ────────────────────────────────────────────────────────────────────
def _ffmpeg(*args: str, check: bool = True) -> None:
cmd = ["ffmpeg", "-y", "-v", "error"] + list(args)
r = subprocess.run(cmd)
if check and r.returncode != 0:
sys.exit(f"[ep04] ffmpeg failed: {' '.join(cmd[:8])}")
def _free_gb() -> float:
return shutil.disk_usage("/").free / (1024 ** 3)
def _parse_blend(blend_str: str) -> dict[str, float]:
parts: dict[str, float] = {}
for item in blend_str.split(","):
name, _, w = item.strip().partition(":")
parts[name.strip()] = float(w.strip() or "1")
total = sum(parts.values())
return {k: v / total for k, v in parts.items()}
def _synthesise(text: str, voice_key: str, out_wav: Path) -> float:
"""Render text with a character voice, return duration in seconds."""
import numpy as np
import soundfile as sf
from kokoro_onnx import Kokoro
cache = Path.home() / ".cache/kokoro"
model_path = cache / "kokoro-v1.0.onnx"
voices_path = cache / "voices-v1.0.bin"
if not model_path.exists() or not voices_path.exists():
import urllib.request
cache.mkdir(parents=True, exist_ok=True)
HF_BASE = "https://huggingface.co/hexgrad/Kokoro-82M/resolve/main/onnx"
for dest, url in [(model_path, f"{HF_BASE}/kokoro-v1.0.onnx"), (voices_path, f"{HF_BASE}/voices-v1.0.bin")]:
if not dest.exists():
print(f"[ep04] downloading {dest.name}...")
urllib.request.urlretrieve(url, dest)
if not hasattr(_synthesise, "_engine"):
_synthesise._engine = Kokoro(str(model_path), str(voices_path))
k = _synthesise._engine
v = VOICES[voice_key]
weights = _parse_blend(v["blend"])
voice_style = sum(k.get_voice_style(name) * w for name, w in weights.items())
samples, sr = k.create(text, voice=voice_style, speed=v["speed"], lang="en-us")
sf.write(str(out_wav), samples, sr)
return len(samples) / sr
def _caption_png(text: str, out_path: Path) -> Path:
from PIL import Image, ImageDraw, ImageFont
img = Image.new("RGBA", (WIDTH, HEIGHT), (0, 0, 0, 0))
draw = ImageDraw.Draw(img)
font_candidates = [
"/System/Library/Fonts/Helvetica.ttc",
"/System/Library/Fonts/Arial.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
]
font = None
for fc in font_candidates:
if Path(fc).exists():
try:
font = ImageFont.truetype(fc, CAPTION_FONT_SIZE, index=0)
break
except Exception:
continue
if font is None:
font = ImageFont.load_default()
caption_text = text.lower().rstrip(".,;:!?")
# wrap long captions
words = caption_text.split()
lines_out = []
current = []
for word in words:
current.append(word)
test_line = " ".join(current)
if draw.textlength(test_line, font=font) > WIDTH * 0.88:
if len(current) > 1:
lines_out.append(" ".join(current[:-1]))
current = [word]
else:
lines_out.append(test_line)
current = []
if current:
lines_out.append(" ".join(current))
line_height = CAPTION_FONT_SIZE + 8
total_height = len(lines_out) * line_height
y_start = int(HEIGHT * CAPTION_Y_FRAC) - total_height + line_height
for i, line in enumerate(lines_out):
w_text = draw.textlength(line, font=font)
x = (WIDTH - w_text) / 2
y = y_start + i * line_height
# shadow
for dx, dy in [(-1, -1), (-1, 1), (1, -1), (1, 1)]:
draw.text((x + dx * 2, y + dy * 2), line, font=font, fill=(0, 0, 0, 180))
draw.text((x, y), line, font=font, fill=(255, 255, 255, 255))
img.save(str(out_path))
return out_path
def _end_card_png(out_path: Path) -> Path:
from PIL import Image, ImageDraw, ImageFont
img = Image.new("RGB", (WIDTH, HEIGHT), (0, 0, 0))
draw = ImageDraw.Draw(img)
font_candidates = [
"/System/Library/Fonts/Helvetica.ttc",
"/System/Library/Fonts/Arial.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
]
font_big = font_small = None
for fc in font_candidates:
if Path(fc).exists():
try:
font_big = ImageFont.truetype(fc, 88, index=0)
font_small = ImageFont.truetype(fc, 52, index=0)
break
except Exception:
continue
if font_big is None:
font_big = font_small = ImageFont.load_default()
for text, font, y_frac in [
("oxhan atelier", font_big, 0.42),
("oxhanatelier.com", font_small, 0.52),
]:
w = draw.textlength(text, font=font)
draw.text(((WIDTH - w) / 2, int(HEIGHT * y_frac)), text, font=font, fill=(255, 255, 255))
img.save(str(out_path))
return out_path
def _zoompan_filter(n_frames: int, zoom_start: float, zoom_end: float) -> str:
return (
f"scale={WIDTH * 2}:{HEIGHT * 2}:flags=lanczos,"
f"zoompan=z='{zoom_start}+({zoom_end}-{zoom_start})*on/{n_frames}'"
f":x='iw/2-iw/zoom/2':y='ih/2-ih/zoom/2'"
f":d={n_frames}:s={WIDTH}x{HEIGHT}:fps={FPS},"
f"setsar=1"
)
# ── still generation ───────────────────────────────────────────────────────────
def generate_stills(skip_existing: bool = True) -> dict[str, Path]:
"""Generate all EP04 stills. Returns {id: path}."""
from stills import generate_still
STILLS_DIR.mkdir(parents=True, exist_ok=True)
paths: dict[str, Path] = {}
for sid, spec in STILL_PROMPTS.items():
dst = Path(spec["dst"])
if skip_existing and dst.exists():
print(f"[ep04] still {sid}: already exists, skipping ({dst})")
paths[sid] = dst
continue
print(f"\n[ep04] generating still {sid}...")
t0 = time.monotonic()
path = generate_still(
prompt=spec["prompt"],
out=dst,
seed=spec.get("seed"),
steps=spec.get("steps", 4),
)
elapsed = time.monotonic() - t0
print(f"[ep04] still {sid} done in {elapsed:.1f}s -> {path}")
paths[sid] = path
return paths
# ── video assembly ─────────────────────────────────────────────────────────────
def assemble_video(stills: dict[str, Path], out: Path = OUT_MP4) -> Path:
"""Assemble the final video from stills + multi-voice VO."""
out.parent.mkdir(parents=True, exist_ok=True)
tmpdir = Path(tempfile.mkdtemp(prefix="ep04_free_"))
t0 = time.monotonic()
try:
return _assemble_inner(stills, out, tmpdir, t0)
finally:
shutil.rmtree(tmpdir, ignore_errors=True)
def _assemble_inner(stills: dict[str, Path], out: Path, tmpdir: Path, t0: float) -> Path:
# ── 1. render per-line voiceovers ─────────────────────────────────────────
print("[ep04] rendering voice lines...")
line_wavs: dict[str, Path] = {}
line_durs: dict[str, float] = {}
for lid, (speaker, tts_text, caption_text) in LINES.items():
wav_path = tmpdir / f"vo_{lid}.wav"
print(f" {lid} ({speaker}): {tts_text[:60]}")
dur = _synthesise(tts_text, speaker, wav_path)
line_wavs[lid] = wav_path
line_durs[lid] = dur
print(f" -> {dur:.2f}s")
# ── 2. build video segments ───────────────────────────────────────────────
print("[ep04] building video segments...")
seg_paths: list[Path] = []
seg_audio_paths: list[Path] = []
seg_durs: list[float] = []
seg_cap_beats: list[list[dict]] = [] # [{text, start, end}]
for seg_idx, (still_id, line_ids, push_in, forced_dur) in enumerate(EDIT_SEQUENCE):
still_path = stills.get(still_id)
if still_path is None or not still_path.exists():
print(f"[ep04] WARNING: still {still_id} not found, using placeholder")
still_path = None
# compute segment duration and audio
if forced_dur is not None:
seg_dur = float(forced_dur)
seg_wav = tmpdir / f"seg{seg_idx:02d}_silence.wav"
_write_silence(seg_wav, seg_dur)
beats: list[dict] = []
elif line_ids:
# concatenate line wavs with gaps
parts: list[Path] = []
beat_list: list[dict] = []
cursor = 0.0
for i, lid in enumerate(line_ids):
parts.append(line_wavs[lid])
_, _, cap_text = LINES[lid]
line_dur = line_durs[lid]
# split caption into ~4-word phrases
words = cap_text.split()
phrase_len = max(1, len(words))
# for short lines show whole caption
beat_list.append({
"text": cap_text,
"start": cursor + 0.05,
"end": cursor + line_dur - 0.05,
})
cursor += line_dur
if i < len(line_ids) - 1:
cursor += LINE_GAP
# add tail silence
total_vo = cursor + SHOT_TAIL
seg_dur = total_vo
# concatenate wavs with gap silence
seg_wav = tmpdir / f"seg{seg_idx:02d}_audio.wav"
_concat_wavs_with_gaps(parts, line_durs, line_ids, seg_wav, LINE_GAP, SHOT_TAIL)
beats = beat_list
else:
seg_dur = 2.0
seg_wav = tmpdir / f"seg{seg_idx:02d}_silence.wav"
_write_silence(seg_wav, seg_dur)
beats = []
# build video for this segment
seg_vid = tmpdir / f"seg{seg_idx:02d}_video.mp4"
n_frames = max(1, int(seg_dur * FPS))
if still_path:
if push_in:
zs, ze = PUSH_ZOOM_START, PUSH_ZOOM_END
elif seg_idx == 0:
zs, ze = HOOK_ZOOM_START, HOOK_ZOOM_END
else:
zs = ze = STATIC_SCALE
zoompan = _zoompan_filter(n_frames, zs, ze)
_ffmpeg(
"-loop", "1", "-i", str(still_path),
"-vf", zoompan,
"-t", str(seg_dur),
"-an", "-c:v", "libx264", "-crf", "18", "-preset", "fast",
str(seg_vid),
)
else:
_ffmpeg(
"-f", "lavfi", "-i", f"color=c=0x15120F:s={WIDTH}x{HEIGHT}:r={FPS}",
"-t", str(seg_dur),
"-an", "-c:v", "libx264", "-crf", "18", "-preset", "fast",
str(seg_vid),
)
seg_paths.append(seg_vid)
seg_audio_paths.append(seg_wav)
seg_durs.append(seg_dur)
seg_cap_beats.append(beats)
# ── 3. concatenate body video ─────────────────────────────────────────────
concat_list = tmpdir / "concat.txt"
concat_list.write_text("\n".join(f"file '{p.resolve()}'" for p in seg_paths))
body_vid = tmpdir / "body.mp4"
_ffmpeg("-f", "concat", "-safe", "0", "-i", str(concat_list), "-c", "copy", str(body_vid))
total_body = sum(seg_durs)
print(f"[ep04] body video: {total_body:.2f}s")
# ── 4. burn captions ──────────────────────────────────────────────────────
cap_png_paths: list[tuple[Path, float, float]] = []
t_offset = 0.0
for beats, dur in zip(seg_cap_beats, seg_durs):
for beat in beats:
abs_start = t_offset + beat["start"]
abs_end = min(t_offset + beat["end"], total_body - 0.05)
if abs_end > abs_start:
cap_png_paths.append((beat["text"], abs_start, abs_end))
t_offset += dur
if cap_png_paths:
cap_inputs: list[str] = ["-i", str(body_vid)]
filter_parts = ["[0:v]copy[v]"]
for ci, (cap_text, abs_start, abs_end) in enumerate(cap_png_paths):
cap_png = tmpdir / f"cap_{ci:04d}.png"
_caption_png(str(cap_text), cap_png)
cap_inputs += ["-loop", "1", "-i", str(cap_png)]
stream = ci + 1
filter_parts.append(
f"[v][{stream}:v]overlay=0:0:enable='between(t,{abs_start:.3f},{abs_end:.3f})'[v]"
)
filter_str = ";".join(filter_parts)
captioned_vid = tmpdir / "captioned.mp4"
_ffmpeg(
*cap_inputs,
"-filter_complex", filter_str,
"-map", "[v]", "-an",
"-c:v", "libx264", "-crf", "18", "-preset", "fast",
str(captioned_vid),
)
else:
captioned_vid = body_vid
# ── 5. end card ───────────────────────────────────────────────────────────
ec_png = tmpdir / "endcard.png"
_end_card_png(ec_png)
ec_vid = tmpdir / "endcard.mp4"
_ffmpeg(
"-loop", "1", "-i", str(ec_png),
"-t", str(END_CARD_SECS),
"-vf", f"scale={WIDTH}:{HEIGHT},fps={FPS},fade=in:st=0:d=0.4:color=black",
"-an", "-c:v", "libx264", "-crf", "18", "-preset", "fast",
str(ec_vid),
)
full_concat = tmpdir / "full_concat.txt"
full_concat.write_text(f"file '{captioned_vid.resolve()}'\nfile '{ec_vid.resolve()}'")
full_vid = tmpdir / "full_video.mp4"
_ffmpeg("-f", "concat", "-safe", "0", "-i", str(full_concat), "-c", "copy", str(full_vid))
# ── 6. concatenate audio ──────────────────────────────────────────────────
vo_list = tmpdir / "vo_concat.txt"
vo_list.write_text("\n".join(f"file '{p.resolve()}'" for p in seg_audio_paths))
vo_full = tmpdir / "vo_full.wav"
_ffmpeg("-f", "concat", "-safe", "0", "-i", str(vo_list), "-ar", "48000", "-ac", "2", str(vo_full))
# generate music bed: multi-harmonic sine bass (original, owned, no external samples)
# aevalsrc: fundamental at 90 Hz + harmonics, ~8 dB under the voice (~0.22 amplitude)
music_bed = tmpdir / "music_bed.wav"
total_secs = total_body + END_CARD_SECS
_ffmpeg(
"-f", "lavfi",
"-i", (
"aevalsrc=0.10*sin(2*PI*t*90)+0.06*sin(2*PI*t*180)"
"+0.04*sin(2*PI*t*270)+0.03*sin(2*PI*t*45)"
":s=48000"
),
"-t", str(total_secs + 2),
"-ar", "48000", "-ac", "2",
str(music_bed),
)
# mix VO + music bed
audio_mix = tmpdir / "audio_mix.wav"
_ffmpeg(
"-i", str(vo_full),
"-stream_loop", "-1", "-i", str(music_bed),
"-filter_complex",
(
f"[1:a]volume=0.22,afade=out:st={total_secs - 1.5}:d=1.5[bed];"
f"[0:a][bed]amix=inputs=2:duration=first:normalize=0[mix]"
),
"-map", "[mix]",
"-ar", "48000", "-ac", "2",
str(audio_mix),
)
# silence for end card
end_silence = tmpdir / "end_silence.wav"
_ffmpeg(
"-f", "lavfi", "-i", "anullsrc=r=48000:cl=stereo",
"-t", str(END_CARD_SECS), str(end_silence),
)
audio_cat = tmpdir / "audio_cat.txt"
audio_cat.write_text(f"file '{audio_mix.resolve()}'\nfile '{end_silence.resolve()}'")
audio_full = tmpdir / "audio_full.wav"
_ffmpeg("-f", "concat", "-safe", "0", "-i", str(audio_cat), "-ar", "48000", "-ac", "2", str(audio_full))
# loudnorm
audio_norm = tmpdir / "audio_norm.wav"
_ffmpeg("-i", str(audio_full), "-af", "loudnorm=I=-14:TP=-1.5:LRA=7", "-ar", "48000", str(audio_norm))
# ── 7. mux ────────────────────────────────────────────────────────────────
_ffmpeg(
"-i", str(full_vid), "-i", str(audio_norm),
"-c:v", "copy", "-c:a", "aac", "-b:a", "192k",
"-shortest", str(out),
)
elapsed = time.monotonic() - t0
size_mb = out.stat().st_size / (1024 * 1024)
print(f"\n[ep04] done in {elapsed:.1f}s -> {out} ({size_mb:.1f} MB)")
return out
def _write_silence(wav_path: Path, duration: float) -> None:
import numpy as np
import soundfile as sf
samples = int(duration * SAMPLE_RATE)
sf.write(str(wav_path), [0.0] * samples, SAMPLE_RATE)
def _concat_wavs_with_gaps(
parts: list[Path],
line_durs: dict[str, float],
line_ids: list[str],
out_wav: Path,
gap_sec: float,
tail_sec: float,
) -> None:
"""Concatenate multiple wav files with silence gaps, write to out_wav."""
import numpy as np
import soundfile as sf
all_samples: list[np.ndarray] = []
gap_samples = int(gap_sec * SAMPLE_RATE)
tail_samples = int(tail_sec * SAMPLE_RATE)
for i, (part_path, lid) in enumerate(zip(parts, line_ids)):
data, sr = sf.read(str(part_path))
# resample to SAMPLE_RATE if needed
if sr != SAMPLE_RATE:
# simple: just use as-is (kokoro returns 24000)
pass
all_samples.append(data)
if i < len(parts) - 1:
all_samples.append(np.zeros(gap_samples, dtype=data.dtype if data.ndim == 1 else float))
all_samples.append(np.zeros(tail_samples, dtype=float))
combined = np.concatenate(all_samples)
# Detect actual kokoro output rate
_, sr_actual = sf.read(str(parts[0]))
sf.write(str(out_wav), combined, sr_actual)
# ── frame extraction ───────────────────────────────────────────────────────────
def extract_frames(video_path: Path, out_dir: Path, n: int = 5) -> list[Path]:
"""Extract n evenly spaced frames from a video for visual verification."""
out_dir.mkdir(parents=True, exist_ok=True)
# get duration
r = subprocess.run(
["ffprobe", "-v", "error", "-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1", str(video_path)],
capture_output=True, text=True,
)
try:
dur = float(r.stdout.strip())
except Exception:
dur = 20.0
frame_paths: list[Path] = []
for i in range(n):
t = dur * (i + 0.5) / n
frame_path = out_dir / f"frame_{i + 1:02d}_{t:.1f}s.png"
subprocess.run(
["ffmpeg", "-y", "-v", "error", "-ss", str(t),
"-i", str(video_path), "-vframes", "1", str(frame_path)],
check=False,
)
if frame_path.exists():
frame_paths.append(frame_path)
return frame_paths
# ── CLI ────────────────────────────────────────────────────────────────────────
def main() -> None:
ap = argparse.ArgumentParser(description="Build EP04 'The Judges' video at $0.")
ap.add_argument("--stills-only", action="store_true", help="Generate stills only, don't assemble")
ap.add_argument("--assemble-only", action="store_true", help="Assemble only (skip still gen)")
ap.add_argument("--regen-still", default=None, metavar="ID", help="Regenerate a specific still (e.g. s0)")
ap.add_argument("--out", default=str(OUT_MP4), help="Output path")
a = ap.parse_args()
out_path = Path(a.out)
print(f"[ep04] disk free: {_free_gb():.1f} GB")
print(f"[ep04] output: {out_path}")
# Archive old dry run
if DRYRUN_MP4.exists():
pass # already archived
elif OUT_MP4.exists():
print(f"[ep04] archiving dry run to {DRYRUN_MP4.name}")
shutil.move(str(OUT_MP4), str(DRYRUN_MP4))
stills: dict[str, Path] = {}
if not a.assemble_only:
# Regenerate a specific still
skip_existing = True
if a.regen_still:
for sid in a.regen_still.split(","):
sid = sid.strip()
if sid in STILL_PROMPTS:
dst = Path(STILL_PROMPTS[sid]["dst"])
if dst.exists():
dst.unlink()
print(f"[ep04] will regenerate {sid}")
else:
print(f"[ep04] unknown still id: {sid}")
stills = generate_stills(skip_existing=skip_existing)
else:
# Load existing stills
for sid, spec in STILL_PROMPTS.items():
dst = Path(spec["dst"])
if dst.exists():
stills[sid] = dst
else:
print(f"[ep04] WARNING: still {sid} not found at {dst}")
if a.stills_only:
print(f"[ep04] stills-only mode, done. Stills: {list(stills.keys())}")
return
# Assemble
video = assemble_video(stills, out=out_path)
# Extract frames for verification
frames_dir = out_path.parent / "ep04_frames"
frames = extract_frames(video, frames_dir)
print(f"[ep04] extracted {len(frames)} frames:")
for f in frames:
print(f" {f}")
print(f"\n[ep04] DONE")
print(f" video : {video}")
print(f" size : {video.stat().st_size // (1024*1024)} MB")
if __name__ == "__main__":
main()