#!/usr/bin/env python3
"""Cantonese voiceover with Gemini 3.8 Flash TTS: one take per line, checked, then joined.

    export PROJECT_ID=your-project        # Vertex AI enabled; `gcloud auth login` done
    export VOICE_ID=voice_...             # optional: reuse a designed voice; omitted -> one is created
    python3 make_voiceover.py             # -> out/line*.wav, out/narration.wav

Needs: python3 + requests, ffmpeg/ffprobe on PATH.
"""
import base64, io, json, os, re, subprocess, tempfile, time, wave
import requests

PROJECT = os.environ["PROJECT_ID"]
API = f"https://aiplatform.googleapis.com/v1beta1/projects/{PROJECT}/locations/global"
TOKEN = subprocess.check_output(["gcloud", "auth", "print-access-token"], text=True).strip()
HDR = {"Authorization": f"Bearer {TOKEN}"}
OUT = "out"; GAP = 0.4; MAX_TAKES = 4
PRICE_PER_M = {"text_in": 1.00, "audio_out": 18.00}   # USD per 1M tokens from 2027-01-01 (half that through 2026)

# --- the voice: accent, age and timbre live here, not in the style ---------------------------
VOICE_PROMPT = ("三十多岁的香港男工程师，讲地道香港粤语口语，句中夹杂的英文术语带明显港式口音"
                "（唔系标准英美音），声音清晰、自信，似科技发布会旁白。")

# --- the script: text is read verbatim; style is one short phrase per line --------------------
BASE = "Hong Kong Cantonese, tech keynote narrator, steady pace, crisp endings"
LINES = [  # (text in traditional Cantonese characters, mood, must appear in transcript, must not appear)
    ("混元 4 喺 TPU v7 度 cold start，淨係 compile 就要 95 分鐘；cache 一 invalidate 咗，就要由頭嚟過。",
     "heavy and urgent", [r"95", r"分[鐘钟]"], []),
    ("Bottleneck 唔喺 compiler 度，係個 graph 畀人放大咗。", "calm and assured", [r"(?i)compiler", r"(?i)graph"], []),
    ("Loop 改用 for i，constant 改做 parameter，compile 出嚟嘅嘢喺唔同 rank 之間 share。",
     "confident and upbeat", [r"(?i)constant", r"(?i)parameter"], []),
    ("Cold start，直接壓到得返十四分鐘！", "energetic, pleasantly surprised", [r"14|十四", r"分[鐘钟]"],
     [r"秒", r"1\.4"]),                                             # misreadings we actually heard
    ("每日嘅優化實驗由 12 組變 80 組，i-te-rate 快咗好多！", "rising excitement, strong finish", [r"12|十二", r"80|八十"], []),
]


def post(path, body, timeout=180):
    r = requests.post(f"{API}/{path}", headers=HDR, json=body, timeout=timeout)
    r.raise_for_status()
    return r.json()


def create_voice():
    j = post("voices", {"store": True, "voice": {
        "type": "VOICE_TYPE_PROMPTED", "displayName": "hk-engineer", "gender": "male",
        "languageCode": "yue-HK", "prompted": {"input": VOICE_PROMPT}}}, timeout=120)
    print("created voice", j["id"], "- export VOICE_ID to reuse it")
    return j["id"]


def synth(text, style, voice):
    j = post("publishers/google/models/gemini-3.8-flash-tts:generateContent", {
        "contents": [{"role": "user", "parts": [{"text": text, "speechMetadata": {"style": style}}]}],
        "generationConfig": {"responseModalities": ["AUDIO"],
                             "speechConfig": {"languageCode": "yue-HK", "voiceConfig": {"voice": voice}}}})
    wav = base64.b64decode(j["candidates"][0]["content"]["parts"][0]["inlineData"]["data"])  # complete WAV
    return wav, j.get("usageMetadata", {})


def ffmpeg(*args, data=None):
    return subprocess.run(["ffmpeg", "-nostdin", "-v", "error", "-y", *args], input=data,
                          capture_output=True, check=True).stdout


def trim(wav):  # cut leading/trailing silence, short fades against clicks
    edge = "silenceremove=start_periods=1:start_threshold=-42dB"
    with tempfile.NamedTemporaryFile(suffix=".wav") as f:   # a file, not a pipe, so the WAV header gets real sizes
        ffmpeg("-i", "pipe:0", "-af", f"{edge},areverse,{edge},areverse,afade=t=in:d=0.01,areverse,"
               "afade=t=in:d=0.04,areverse", f.name, data=wav)
        return open(f.name, "rb").read()


def duration(wav):
    w = wave.open(io.BytesIO(wav)); return w.getnframes() / w.getframerate()


def longest_pause(wav):
    log = subprocess.run(["ffmpeg", "-nostdin", "-i", "pipe:0", "-af", "silencedetect=n=-38dB:d=0.12", "-f", "null", "-"],
                         input=wav, capture_output=True).stderr.decode()
    st = [float(x) for x in re.findall(r"silence_start: ([\d.]+)", log)]
    en = [float(x) for x in re.findall(r"silence_end: ([\d.]+)", log)]
    return max([b - a for a, b in zip(st, en)] or [0.0])


def ask(model, prompt, wav):
    body = {"contents": [{"role": "user", "parts": [
        {"text": prompt}, {"inlineData": {"mimeType": "audio/wav", "data": base64.b64encode(wav).decode()}}]}]}
    for attempt in range(3):         # now and then a response comes back with no text
        j = post(f"publishers/google/models/{model}:generateContent", body)
        parts = (j.get("candidates") or [{}])[0].get("content", {}).get("parts", [])
        text = "".join(p.get("text", "") for p in parts).strip()
        if text:
            return text
        time.sleep(2 * (attempt + 1))
    return ""                        # an empty transcript fails the check, so the line is generated again


def check(text, wav, must, forbid):
    """Return a list of problems; empty means the take passes."""
    problems, dur = [], duration(wav)
    units = (len(re.findall(r"[\u4e00-\u9fff]", text)) + len(re.findall(r"[A-Za-z]+(?:-[A-Za-z]+)*", text))
             + len(re.findall(r"\d+", text)))                      # Chinese characters + English words + numbers
    if dur > 1.5 + 0.3 * units:     # normal takes ran 0.23-0.29 s/unit; takes that read the directions ran 3-12x
        problems.append(f"too long ({dur:.1f}s)")
    pause = longest_pause(wav)
    if pause > 0.6:                                                 # 0.86 s read as a break; commas give ~0.3 s
        problems.append(f"pause {pause:.2f}s")
    for model in ("gemini-3.5-flash", "gemini-3.7-flash"):          # two transcribers must both agree
        heard = ask(model, "逐字转写这段粤语音频，数字用阿拉伯数字，只输出转写。", wav)
        miss = [m for m in must if not re.search(m, heard)] + [f for f in forbid if re.search(f, heard)]
        if miss:
            problems.append(f"{model} heard {heard!r} (check {miss})")
    js = ask("gemini-3.5-flash", '判断音频里每个中文字是粤语还是普通话发音（英文词忽略）。'
             '只输出 JSON：{"cantonese_pct": 0-100}', wav)
    m = re.search(r"\{.*\}", js, re.S)
    pct = json.loads(m.group(0)).get("cantonese_pct", 0) if m else 0
    if pct < 90:
        problems.append(f"Mandarin drift (cantonese_pct={pct})")
    return problems


def main():
    os.makedirs(OUT, exist_ok=True)
    voice = os.environ.get("VOICE_ID") or create_voice()
    tokens = {"text_in": 0, "audio_out": 0}
    takes = []
    for i, (text, mood, must, forbid) in enumerate(LINES, 1):
        for n in range(1, MAX_TAKES + 1):
            wav, usage = synth(text, f"{BASE}, {mood}", voice)
            tokens["text_in"] += usage.get("promptTokenCount", 0)
            tokens["audio_out"] += usage.get("candidatesTokenCount", 0)
            wav = trim(wav)
            problems = check(text, wav, must, forbid)
            print(f"line {i} take {n}: {duration(wav):.2f}s", "OK" if not problems else problems)
            if not problems:
                break
        else:
            raise SystemExit(f"line {i}: no clean take in {MAX_TAKES} tries; listen to out/line{i}.wav")
        path = f"{OUT}/line{i}.wav"
        open(path, "wb").write(wav); takes.append(path)
    gap = f"{OUT}/gap.wav"
    ffmpeg("-f", "lavfi", "-i", "anullsrc=r=24000:cl=mono", "-t", str(GAP), gap)
    with open(f"{OUT}/list.txt", "w") as f:
        f.write("".join(f"file '{os.path.abspath(p)}'\nfile '{os.path.abspath(gap)}'\n" for p in takes[:-1])
                + f"file '{os.path.abspath(takes[-1])}'\n")
    ffmpeg("-f", "concat", "-safe", "0", "-i", f"{OUT}/list.txt", "-ar", "24000", "-ac", "1", f"{OUT}/narration.wav")
    cost = sum(tokens[k] * PRICE_PER_M[k] / 1e6 for k in tokens)
    print(f"narration: {OUT}/narration.wav  tokens {tokens}  TTS cost ${cost:.4f} (list price from 2027; "
          f"half through 2026; transcription calls billed separately)")


if __name__ == "__main__":
    main()
