#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
TRPV1 读法候选探针（s04 / s16 成对，保证两段读法一致）

铁律：SEED_TEXT / prompt 参数一律从正式脚本 import，绝不手写。
候选必须先 ASR 回读卡「是中文 + 文本完整」，再验声调；声调 ASR 验不了，需人工耳检。
"""
import os, sys, time

from moon03_tts import MODEL_DIR, SEED_WAV, SEED_TEXT, SEED, CFG, STEPS

try:
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
    pass

OUT = r"D:/WorkBuddyProd/chili04/probe_trpv1"
os.makedirs(OUT, exist_ok=True)

# (候选名, seed, s04 写法, s16 写法)
CANDS = [
    ("orig42", 42, "TRPV1 的受体。", "鸟的 TRPV1 长得不一样，"),
    ("orig100", 100, "TRPV1 的受体。", "鸟的 TRPV1 长得不一样，"),
    ("spaced42", 42, "T R P V 1 的受体。", "鸟的 T R P V 1 长得不一样，"),
    ("spaced100", 100, "T R P V 1 的受体。", "鸟的 T R P V 1 长得不一样，"),
]


def main():
    import numpy as np
    import soundfile as sf
    import torch
    from voxcpm import VoxCPM

    model = VoxCPM.from_pretrained(MODEL_DIR, load_denoiser=False, device="cpu", optimize=False)
    sr = model.tts_model.sample_rate
    assert sr == 48000
    for name, seed, t4, t16 in CANDS:
        for seg, text in ((4, t4), (16, t16)):
            path = os.path.join(OUT, "%s_s%02d.wav" % (name, seg))
            if os.path.exists(path) and os.path.getsize(path) > 10000:
                print("%s s%02d SKIP" % (name, seg), flush=True)
                continue
            torch.manual_seed(seed)
            t = time.time()
            wav = model.generate(text=text,
                                 prompt_wav_path=SEED_WAV, prompt_text=SEED_TEXT,
                                 reference_wav_path=SEED_WAV,
                                 cfg_value=CFG, inference_timesteps=STEPS)
            wav = np.asarray(wav, dtype=np.float32).reshape(-1)
            sf.write(path, wav, sr)
            print("%s s%02d OK dur=%.2fs cost=%.0fs text=%s" %
                  (name, seg, len(wav) / sr, time.time() - t, text), flush=True)


if __name__ == "__main__":
    main()
