videogen/tools/freegen/assemble.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

718 lines
28 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""assemble.py — clips or stills → 1080x1920 MP4 at $0.
Pipeline
--------
1. Voiceover — Kokoro-82M (Apache-2.0) via kokoro-onnx.
2. Captions — whisper.cpp word timestamps (if installed) or TTS-derived timing.
3. Motion — clip passthrough when a clip exists; Ken Burns (zoompan) fallback
for stills: the first shot zooms in (hook), subsequent shots pan or zoom.
One push-in effect is applied to the punchline/CTA shot.
4. End card — plain text card (product name + URL) using ffmpeg drawtext.
5. Audio mix — optional music bed from a local file + -14 LUFS / -1.5 dBTP loudnorm.
6. Render — single ffmpeg pass, libx264, 1080x1920 9:16.
Usage
-----
source .venv/bin/activate
python assemble.py [--shots SHOTS_JSON] [--out OUT.mp4] [--text "script"]
[--voice VOICE_BLEND] [--music MUSIC.mp3]
[--product-name "Bidstage"] [--product-url "bidstage.app"]
[--test]
SHOTS_JSON example:
[
{"still": "shot1.png", "text": "Tenders closing this week.", "push": false},
{"still": "shot2.png", "text": "Only one bid per slot.", "push": false},
{"still": "shot3.png", "text": "Win your first contract.", "push": true}
]
--test generates a 15 s test video from two stills in test-stills/ (Ken Burns
fallback, Kokoro voiceover, captions, Bidstage end card).
"""
from __future__ import annotations
import argparse
import json
import os
import shutil
import subprocess
import sys
import tempfile
import time
from pathlib import Path
from typing import Any
# ── config ────────────────────────────────────────────────────────────────────
WIDTH, HEIGHT = 1080, 1920
FPS = 30
DEFAULT_VOICE = "af_heart:1.0" # Kokoro voice (Apache-2.0 weights)
DEFAULT_SPEED = 1.0
SAMPLE_RATE = 24000
END_CARD_SECS = 3.0
CAPTION_Y_FRAC = 0.82 # top of caption at 82% of frame height (style guide §4)
CAPTION_FONT_SIZE = 68
HOOK_ZOOM_START = 1.00 # Ken Burns: hook shot starts at 1.0x (fill)
HOOK_ZOOM_END = 1.08 # zooms in slightly over the shot duration
PUSH_ZOOM_START = 1.00
PUSH_ZOOM_END = 1.10
STATIC_SCALE = 1.02 # locked-off shots: minimal overscan so edges don't show
# ── Kokoro TTS ────────────────────────────────────────────────────────────────
def _kokoro():
"""Lazy-init the Kokoro ONNX engine (cached in module scope)."""
if not hasattr(_kokoro, "_engine"):
from kokoro_onnx import Kokoro
model_dir = Path(__file__).parent
# Search common locations for the ONNX model (newest format first)
candidates = [
model_dir / "models" / "kokoro-v1.0.onnx",
Path.home() / ".cache" / "kokoro" / "kokoro-v1.0.onnx",
# VTT project has a local copy (reuse to avoid download)
# assemble.py → freegen/ → tools/ → videogen/ → products/
Path(__file__).resolve().parent.parent.parent.parent
/ "gtm/oxhan-very-turkish-time/work/models/kokoro/kokoro-v1.0.onnx",
]
for c in candidates:
voices_path = c.parent / "voices-v1.0.bin"
if c.exists() and voices_path.exists():
_kokoro._engine = Kokoro(str(c), str(voices_path))
break
else:
# Download model files on first use
_kokoro._engine = _download_kokoro()
return _kokoro._engine
def _download_kokoro():
"""Download Kokoro ONNX model files to .cache/kokoro/ if not already present."""
from kokoro_onnx import Kokoro
import urllib.request
cache = Path.home() / ".cache" / "kokoro"
cache.mkdir(parents=True, exist_ok=True)
model_path = cache / "kokoro-v1.0.onnx"
voices_path = cache / "voices-v1.0.bin"
HF_BASE = "https://huggingface.co/hexgrad/Kokoro-82M/resolve/main/onnx"
files = [
(model_path, f"{HF_BASE}/kokoro-v1.0.onnx"),
(voices_path, f"{HF_BASE}/voices-v1.0.bin"),
]
for dest, url in files:
if not dest.exists():
size_hint = {"kokoro-v1.0.onnx": 310, "voices-v1.0.bin": 80}.get(dest.name, "?")
print(f"[assemble] downloading {dest.name} (~{size_hint} MB)...")
urllib.request.urlretrieve(url, dest)
return Kokoro(str(model_path), str(voices_path))
def _parse_blend(blend_str: str) -> dict[str, float]:
"""'am_eric:0.5,am_liam:0.3' → {'am_eric': 0.5, 'am_liam': 0.3} (normalised)."""
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, blend: str = DEFAULT_VOICE, speed: float = DEFAULT_SPEED,
out_wav: str | Path | None = None) -> tuple[Path, float]:
"""Render text to WAV and return (path, duration_s)."""
import numpy as np
import soundfile as sf
k = _kokoro()
weights = _parse_blend(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=speed, lang="en-us")
if out_wav is None:
fd, out_wav_str = tempfile.mkstemp(suffix=".wav")
os.close(fd)
out_wav = Path(out_wav_str)
else:
out_wav = Path(out_wav)
sf.write(str(out_wav), samples, sr)
duration = len(samples) / sr
return out_wav, duration
# ── Whisper.cpp captions ──────────────────────────────────────────────────────
def _find_whisper() -> str | None:
"""Return path to whisper-cpp binary, or None if not installed."""
for name in ("whisper-cpp", "whisper", "main"):
p = shutil.which(name)
if p:
return p
return None
def _whisper_timestamps(wav_path: Path, text: str | None = None) -> list[dict]:
"""Return word-level timestamps [{word, start, end}] via whisper.cpp, or [] on failure."""
whisper = _find_whisper()
if not whisper:
return []
model_dir = Path.home() / ".cache" / "whisper.cpp"
model_file = model_dir / "ggml-base.en.bin"
if not model_file.exists():
# skip if no model — caption timing falls back to text chunking
return []
try:
result = subprocess.run(
[whisper, "-m", str(model_file), "-f", str(wav_path),
"--output-json", "--word-thold", "0.01", "--max-len", "1"],
capture_output=True, text=True, timeout=120,
)
if result.returncode != 0:
return []
import json as _json
data = _json.loads(result.stdout)
words = []
for seg in data.get("transcription", []):
for tok in seg.get("tokens", []):
if tok.get("word", "").strip():
words.append({
"word": tok["word"].strip(),
"start": tok["timestamps"]["from"] / 1000.0,
"end": tok["timestamps"]["to"] / 1000.0,
})
return words
except Exception:
return []
def _tts_caption_beats(text: str, duration: float) -> list[dict[str, Any]]:
"""Estimate caption beats from text when whisper.cpp is unavailable.
Groups words into ~4-word phrases spread evenly over the duration.
Returns [{text, start, end}].
"""
words = text.split()
phrases: list[list[str]] = []
chunk = 4
for i in range(0, len(words), chunk):
phrases.append(words[i : i + chunk])
if not phrases:
return []
per_phrase = duration / len(phrases)
beats = []
for i, ph in enumerate(phrases):
beats.append({
"text": " ".join(ph),
"start": i * per_phrase,
"end": (i + 1) * per_phrase - 0.05,
})
return beats
def _word_beats_to_phrase_beats(words: list[dict]) -> list[dict[str, Any]]:
"""Group word-level whisper timestamps into 3-4 word caption phrases."""
if not words:
return []
phrases: list[dict[str, Any]] = []
i = 0
while i < len(words):
group = words[i : i + 4]
phrases.append({
"text": " ".join(w["word"] for w in group).strip(),
"start": group[0]["start"],
"end": group[-1]["end"],
})
i += 4
return phrases
# ── Ken Burns (ffmpeg zoompan) ────────────────────────────────────────────────
def _ken_burns_filter(duration: float, zoom_start: float, zoom_end: float,
pan_x: float = 0.5, pan_y: float = 0.5) -> str:
"""zoompan filter string for a still image.
zoom_start/zoom_end: 1.0 = fill the frame, >1 = zoom in.
pan_x/pan_y: 0.0-1.0 horizontal/vertical anchor (0.5 = centre).
"""
n_frames = int(duration * FPS)
# zoom progresses linearly from zoom_start to zoom_end
zoom_expr = f"{zoom_start}+({zoom_end}-{zoom_start})*on/{n_frames}"
# x/y position centres the crop at the anchor point
x_expr = f"iw/2*{pan_x*2}-iw/zoom/2"
y_expr = f"ih/2*{pan_y*2}-ih/zoom/2"
return (
f"scale={WIDTH*2}:{HEIGHT*2}," # over-scale so zoom never shows edges
f"zoompan=z='{zoom_expr}':x='{x_expr}':y='{y_expr}'"
f":d={n_frames}:s={WIDTH}x{HEIGHT}:fps={FPS}"
)
# ── Caption overlay (PIL PNG + ffmpeg overlay) ────────────────────────────────
def _caption_png(text: str, out_path: Path, font_size: int = CAPTION_FONT_SIZE
) -> tuple[Path, int, int]:
"""Render a caption to a TIGHT-bounding-box transparent PNG.
Returns (path, x_center_offset, y_center_offset) so the caller can place
the small PNG correctly via ffmpeg overlay=x:y.
Tight PNGs are ~20–50 KB instead of ~200 KB for full-frame PNGs, making
the overlay pass ~15x faster at 1080x1920.
"""
from PIL import Image, ImageDraw, ImageFont
# Use a system font; fall back to default if not found
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, font_size, index=0)
break
except Exception:
continue
if font is None:
font = ImageFont.load_default()
# lowercase, no end punctuation (style guide §4)
caption_text = text.lower().rstrip(".,;:!?")
# Measure text
tmp = Image.new("RGBA", (1, 1))
d = ImageDraw.Draw(tmp)
bbox = d.textbbox((0, 0), caption_text, font=font)
w_text = bbox[2] - bbox[0]
h_text = bbox[3] - bbox[1]
pad = 8 # small padding around text
# Create tight PNG
img_w = w_text + pad * 2
img_h = h_text + pad * 2
img = Image.new("RGBA", (img_w, img_h), (0, 0, 0, 0))
draw = ImageDraw.Draw(img)
# thin dark outline + soft shadow (style guide: no box)
for dx, dy in [(-1, -1), (-1, 1), (1, -1), (1, 1)]:
draw.text((pad + dx * 2, pad + dy * 2), caption_text,
font=font, fill=(0, 0, 0, 180))
draw.text((pad, pad), caption_text, font=font, fill=(255, 255, 255, 255))
img.save(str(out_path))
# Return the x/y where the top-left of this PNG should sit so it's centred
# at (WIDTH/2, HEIGHT*CAPTION_Y_FRAC).
x_ov = int((WIDTH - img_w) / 2)
y_ov = int(HEIGHT * CAPTION_Y_FRAC - img_h / 2)
return out_path, x_ov, y_ov
# ── End card ──────────────────────────────────────────────────────────────────
def _end_card_png(product_name: str, product_url: str, out_path: Path) -> Path:
"""Plain black end card with product name and URL."""
from PIL import Image, ImageDraw, ImageFont
img = Image.new("RGBA", (WIDTH, HEIGHT), (0, 0, 0, 255))
draw = ImageDraw.Draw(img)
font_big_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_big_candidates:
if Path(fc).exists():
try:
font_big = ImageFont.truetype(fc, 96, index=0)
font_small = ImageFont.truetype(fc, 56, index=0)
break
except Exception:
continue
if font_big is None:
font_big = font_small = ImageFont.load_default()
for text, font, y_frac in [
(product_name, font_big, 0.42),
(product_url, 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, 255))
img.save(str(out_path))
return out_path
# ── ffmpeg helpers ────────────────────────────────────────────────────────────
def _ffmpeg(*args: str) -> None:
cmd = ["ffmpeg", "-y", "-v", "error"] + list(args)
result = subprocess.run(cmd)
if result.returncode != 0:
sys.exit(f"[assemble] ffmpeg failed: {' '.join(cmd[:6])}")
def _sh(cmd: list[str]) -> str:
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
sys.exit(f"[assemble] command failed: {result.stderr[-500:]}")
return result.stdout
# ── main assembly ─────────────────────────────────────────────────────────────
def assemble(
shots: list[dict[str, Any]],
out: str | Path = "output.mp4",
voice_blend: str = DEFAULT_VOICE,
speed: float = DEFAULT_SPEED,
music: str | Path | None = None,
product_name: str = "Menivor",
product_url: str = "menivor.com",
tmpdir: str | Path | None = None,
) -> Path:
"""Assemble shots into a 1080x1920 MP4.
Each shot dict can have:
"still" : path to a PNG/JPG still (required if no "clip")
"clip" : path to a video clip (takes priority over still)
"text" : spoken/captioned text for this shot
"push" : bool — apply push-in Ken Burns on this shot (punchline/CTA)
"duration": float — override auto-duration (seconds)
"""
t0 = time.monotonic()
out = Path(out)
out.parent.mkdir(parents=True, exist_ok=True)
own_tmp = tmpdir is None
if own_tmp:
tmpdir = Path(tempfile.mkdtemp(prefix="freegen_"))
else:
tmpdir = Path(tmpdir)
tmpdir.mkdir(parents=True, exist_ok=True)
try:
return _assemble_inner(shots, out, voice_blend, speed, music,
product_name, product_url, tmpdir, t0)
finally:
if own_tmp:
shutil.rmtree(tmpdir, ignore_errors=True)
def _assemble_inner(shots, out, voice_blend, speed, music,
product_name, product_url, tmpdir, t0):
# ── 1. render voiceovers ───────────────────────────────────────────────────
vo_paths: list[Path] = []
durations: list[float] = []
caption_beats: list[list[dict]] = []
for i, shot in enumerate(shots):
text = shot.get("text", "")
forced_dur = shot.get("duration")
if text:
wav, dur = synthesise(text, blend=voice_blend, speed=speed,
out_wav=tmpdir / f"vo_{i:02d}.wav")
wo = _whisper_timestamps(wav, text)
if wo:
beats = _word_beats_to_phrase_beats(wo)
else:
beats = _tts_caption_beats(text, dur)
else:
wav, dur = tmpdir / f"silence_{i:02d}.wav", float(forced_dur or 2.0)
# write silence
import numpy as np, soundfile as sf
sf.write(str(wav), np.zeros(int(dur * SAMPLE_RATE)), SAMPLE_RATE)
beats = []
if forced_dur:
dur = float(forced_dur)
vo_paths.append(wav)
durations.append(dur + 0.25) # small tail
caption_beats.append(beats)
# ── 2. build video track per shot ─────────────────────────────────────────
seg_paths: list[Path] = []
for i, (shot, dur) in enumerate(zip(shots, durations)):
seg = tmpdir / f"seg_{i:02d}.mp4"
clip_src = shot.get("clip")
still_src = shot.get("still")
is_push = shot.get("push", False)
if clip_src and Path(clip_src).exists():
# passthrough: conform to 1080x1920 30 fps, trim to dur
_ffmpeg(
"-i", str(clip_src),
"-vf", f"scale={WIDTH}:{HEIGHT}:force_original_aspect_ratio=increase,"
f"crop={WIDTH}:{HEIGHT},fps={FPS}",
"-t", str(dur),
"-an",
"-c:v", "libx264", "-crf", "18", "-preset", "fast",
str(seg),
)
elif still_src and Path(still_src).exists():
# Ken Burns motion on still — work at half-resolution for speed,
# then upscale. A 540x960 zoompan is ~4x faster than 1080x1920.
n_frames = int(dur * FPS)
half_w, half_h = WIDTH // 2, HEIGHT // 2
if is_push:
zs, ze = PUSH_ZOOM_START, PUSH_ZOOM_END
elif i == 0:
zs, ze = HOOK_ZOOM_START, HOOK_ZOOM_END
else:
zs = ze = STATIC_SCALE
# scale input to 2x half-res, zoompan at half-res, upscale to full
zoompan = (
f"scale={half_w*2}:{half_h*2}:flags=lanczos,"
f"zoompan=z='{zs}+({ze}-{zs})*on/{n_frames}'"
f":x='iw/2-iw/zoom/2':y='ih/2-ih/zoom/2'"
f":d={n_frames}:s={half_w}x{half_h}:fps={FPS},"
f"scale={WIDTH}:{HEIGHT}:flags=lanczos,"
f"setsar=1"
)
_ffmpeg(
"-loop", "1", "-i", str(still_src),
"-vf", zoompan,
"-t", str(dur),
"-an",
"-c:v", "libx264", "-crf", "18", "-preset", "fast",
str(seg),
)
else:
# placeholder: solid dark frame
_ffmpeg(
"-f", "lavfi", "-i", f"color=c=0x15120F:s={WIDTH}x{HEIGHT}:r={FPS}",
"-t", str(dur),
"-an",
"-c:v", "libx264", "-crf", "18", "-preset", "fast",
str(seg),
)
seg_paths.append(seg)
# ── 3. concatenate video segments ─────────────────────────────────────────
concat_list = tmpdir / "concat.txt"
concat_list.write_text("\n".join(f"file '{p.resolve()}'" for p in seg_paths))
body_video = tmpdir / "body.mp4"
_ffmpeg(
"-f", "concat", "-safe", "0", "-i", str(concat_list),
"-c", "copy",
str(body_video),
)
total_body = sum(durations)
# ── 4. burn captions — tight-PNG overlay (fast on CPU) ───────────────────
# Each caption PNG is only the text bounding box + 8px padding (not a full
# 1080x1920 RGBA frame), so the overlay pass processes far fewer pixels per
# frame. The overlay filter places each small PNG at the correct (x, y).
overlay_inputs: list[str] = []
overlay_filters: list[str] = []
t_offset = 0.0
cap_idx = 0
for i, (beats, dur) in enumerate(zip(caption_beats, durations)):
for beat in beats:
cap_png = tmpdir / f"cap_{cap_idx:04d}.png"
_, x_ov, y_ov = _caption_png(beat["text"], cap_png)
overlay_inputs += ["-loop", "1", "-i", str(cap_png)]
abs_start = t_offset + beat["start"]
abs_end = t_offset + beat["end"]
in_label = cap_idx + 1 # input index (0 = body video)
overlay_filters.append(
f"[v][{in_label}:v]overlay={x_ov}:{y_ov}"
f":enable='between(t,{abs_start:.3f},{abs_end:.3f})'[v]"
)
cap_idx += 1
t_offset += dur
if overlay_filters:
filter_str = "[0:v]copy[v];" + ";".join(overlay_filters)
cap_video = tmpdir / "captioned.mp4"
cap_inputs = ["-i", str(body_video)] + overlay_inputs
_ffmpeg(
*cap_inputs,
"-filter_complex", filter_str,
"-map", "[v]",
# Explicitly cap output to body video duration — more reliable than
# -shortest when combined with infinite -loop 1 PNG inputs.
"-t", f"{total_body:.3f}",
"-an",
"-c:v", "libx264", "-crf", "18", "-preset", "fast",
str(cap_video),
)
else:
cap_video = body_video
# ── 5. end card ───────────────────────────────────────────────────────────
ec_png = tmpdir / "endcard.png"
_end_card_png(product_name, product_url, ec_png)
ec_video = 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.3:color=black",
"-an",
"-c:v", "libx264", "-crf", "18", "-preset", "fast",
str(ec_video),
)
# concatenate body + end card
full_concat = tmpdir / "full_concat.txt"
full_concat.write_text(f"file '{cap_video.resolve()}'\nfile '{ec_video.resolve()}'")
full_video = tmpdir / "full_video.mp4"
_ffmpeg(
"-f", "concat", "-safe", "0", "-i", str(full_concat),
"-c", "copy",
str(full_video),
)
# ── 6. audio mix ──────────────────────────────────────────────────────────
# concatenate voiceovers
vo_concat_list = tmpdir / "vo_concat.txt"
vo_concat_list.write_text("\n".join(f"file '{p.resolve()}'" for p in vo_paths))
vo_full = tmpdir / "vo_full.wav"
_ffmpeg(
"-f", "concat", "-safe", "0", "-i", str(vo_concat_list),
"-ar", "48000", "-ac", "2",
str(vo_full),
)
if music and Path(music).exists():
# music bed ~8 dB under voice; fade out at end
total_secs = total_body + END_CARD_SECS
music_mix = tmpdir / "mix.wav"
_ffmpeg(
"-i", str(vo_full),
"-stream_loop", "-1", "-i", str(music),
"-filter_complex",
f"[1:a]volume=0.25,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(music_mix),
)
audio_src = music_mix
else:
audio_src = vo_full
# silence for the end card
end_silence = tmpdir / "end_silence.wav"
_ffmpeg(
"-f", "lavfi", "-i", f"anullsrc=r=48000:cl=stereo",
"-t", str(END_CARD_SECS),
str(end_silence),
)
audio_concat = tmpdir / "audio_concat.txt"
audio_concat.write_text(f"file '{audio_src.resolve()}'\nfile '{end_silence.resolve()}'")
audio_full = tmpdir / "audio_full.wav"
_ffmpeg(
"-f", "concat", "-safe", "0", "-i", str(audio_concat),
"-ar", "48000", "-ac", "2",
str(audio_full),
)
# loudnorm -14 LUFS / -1.5 dBTP
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 video + audio ──────────────────────────────────────────────────
_ffmpeg(
"-i", str(full_video),
"-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"[assemble] done in {elapsed:.1f} s -> {out} ({size_mb:.1f} MB)")
return out
# ── test ─────────────────────────────────────────────────────────────────────
TEST_SHOTS = [
{
"still": "test-stills/oxhan-hero-phoenix.png",
"text": "Tenders close this week. Only one bid per slot.",
"push": False,
},
{
"still": "test-stills/bidstage-tenders-closing.png",
"text": "Win your first government contract. At zero cost.",
"push": True,
},
]
def run_test(out: str = "test-output/test-15s.mp4") -> Path:
"""Produce a 15 s test video from test stills (Ken Burns fallback)."""
shots = []
for s in TEST_SHOTS:
still = Path(s["still"])
if not still.exists():
print(f"[assemble] test still not found: {still} — using placeholder")
s = {**s, "still": None}
shots.append(s)
return assemble(
shots=shots,
out=out,
product_name="Bidstage",
product_url="bidstage.app",
)
# ── CLI ───────────────────────────────────────────────────────────────────────
def main(argv: list[str] | None = None) -> None:
ap = argparse.ArgumentParser(
description="Assemble stills/clips into a 1080x1920 MP4 at $0.",
)
ap.add_argument("--shots", default=None,
help="JSON file or inline JSON array of shot dicts")
ap.add_argument("--out", "-o", default="output.mp4")
ap.add_argument("--text", default=None, help="single-shot: spoken text")
ap.add_argument("--still", default=None, help="single-shot: still image path")
ap.add_argument("--clip", default=None, help="single-shot: video clip path")
ap.add_argument("--voice", default=DEFAULT_VOICE, dest="voice")
ap.add_argument("--speed", type=float, default=DEFAULT_SPEED)
ap.add_argument("--music", default=None, help="music bed audio file")
ap.add_argument("--product-name", default="Menivor", dest="product_name")
ap.add_argument("--product-url", default="menivor.com", dest="product_url")
ap.add_argument("--test", action="store_true", help="render 15 s test video from test stills")
a = ap.parse_args(argv)
if a.test:
run_test()
return
if a.shots:
src = a.shots.strip()
if src.startswith("[") or src.startswith("{"):
shots = json.loads(src)
else:
shots = json.loads(Path(src).read_text())
elif a.still or a.clip:
shots = [{"still": a.still, "clip": a.clip, "text": a.text or ""}]
else:
ap.error("provide --shots or --still/--clip, or use --test")
assemble(
shots=shots,
out=a.out,
voice_blend=a.voice,
speed=a.speed,
music=a.music,
product_name=a.product_name,
product_url=a.product_url,
)
if __name__ == "__main__":
main()