#!/usr/bin/env python3
"""Reads script.md and renders meeting.m4a / meeting.mp3 with macOS `say` (three voices) and ffmpeg.
Reproducible on any Mac with the Samantha, Daniel and Moira voices installed."""
import re, subprocess, tempfile, pathlib
HERE = pathlib.Path(__file__).parent
VOICES = {"Ana": "Samantha", "Rui": "Daniel", "Marta": "Moira"}
RATES = {"Ana": 178, "Rui": 168, "Marta": 172}
lines = [l for l in (HERE / "script.md").read_text().splitlines() if re.match(r"^(Ana|Rui|Marta): ", l)]
tmp = pathlib.Path(tempfile.mkdtemp())
parts = []
for i, l in enumerate(lines):
    who, text = l.split(": ", 1)
    aiff = tmp / f"{i:03d}.aiff"
    subprocess.run(["say", "-v", VOICES[who], "-r", str(RATES[who]), "-o", str(aiff), text], check=True)
    parts.append(aiff)
concat = tmp / "list.txt"
gap = tmp / "gap.wav"
subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-f", "lavfi", "-i", "anullsrc=r=22050:cl=mono", "-t", "0.45", str(gap)], check=True)
concat.write_text("".join(f"file '{p}'\nfile '{gap}'\n" for p in parts))
subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-f", "concat", "-safe", "0", "-i", str(concat), "-ar", "22050", "-ac", "1", "-c:a", "aac", "-b:a", "64k", str(HERE / "meeting.m4a")], check=True)
subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-i", str(HERE / "meeting.m4a"), "-c:a", "libmp3lame", "-b:a", "64k", str(HERE / "meeting.mp3")], check=True)
print("wrote meeting.m4a and meeting.mp3 from", len(lines), "lines")
