# -*- coding: utf-8 -*-
"""probe_wb_env.py - VoxCPM2 环境对照探针（只读诊断，不改任何配置）

用法: D:\voxcpm\.venv\Scripts\python.exe <本文件路径>
全程打点 + faulthandler 每90s落栈；挂死也能看出卡在哪一行。
最长 8 分钟自动退出。结果追加写本目录 probe_result.txt。
"""
import os, sys, time, socket, threading, faulthandler

HERE = os.path.dirname(os.path.abspath(__file__))
# === FIX: DSH sandbox blocks tempfile creation in system TEMP / venv __pycache__.
# Redirect numba cache + python tempfile to the writable workspace BEFORE any import.
os.environ["TMP"] = HERE
os.environ["TEMP"] = HERE
os.environ["NUMBA_CACHE_DIR"] = os.path.join(HERE, "numba_cache")
os.makedirs(os.environ["NUMBA_CACHE_DIR"], exist_ok=True)
LOG = os.path.join(HERE, "probe_result.txt")
_lf = open(LOG, "a", encoding="utf-8")
def log(m):
    _lf.write("[%s] %s\n" % (time.strftime("%H:%M:%S"), m)); _lf.flush()

faulthandler.dump_traceback_later(90, repeat=True, file=_lf)   # 每90s落全部线程栈
threading.Timer(480, lambda: (log("HARD EXIT 480s"), os._exit(3))).start()

log("=== probe start pid=%d host=%s py=%s ===" % (os.getpid(), socket.gethostname(), sys.version.split()[0]))
for k in ("OMP_NUM_THREADS","MKL_NUM_THREADS","KMP_BLOCKTIME","KMP_AFFINITY","MKL_DYNAMIC","OMP_DYNAMIC","VOXCPM_MPS_DTYPE"):
    if os.environ.get(k):
        log("env %s=%s" % (k, os.environ[k]))

import torch, numpy as np, soundfile as sf
log("torch %s threads=%d capability=%s" % (torch.__version__, torch.get_num_threads(), torch.backends.cpu.get_cpu_capability()))

a = torch.randn(1800, 1800); b = torch.randn(1800, 1800)
t = time.time(); c = a @ b
log("STEP1 fp32 matmul 1800: %.2fs" % (time.time() - t))

MODEL = r"D:\voxcpm\models\models\OpenBMB--VoxCPM2\snapshots\master"
SEED_WAV = r"D:/Download/muse_exchange/_vox_design/candidates/a_identity.wav"
SEED_TEXT = ("Okay, so let me get this straight. You wake up, you open your phone, "
             "and before you even get out of bed, you have already seen three different "
             "versions of today. Is that right? That sounds exhausting, honestly.")
from voxcpm import VoxCPM
t = time.time()
model = VoxCPM.from_pretrained(MODEL, load_denoiser=False, device="cpu", optimize=False)
m = model.tts_model
log("STEP2 loaded %.1fs dtype=%s threads_after=%d" % (time.time() - t, m.config.dtype, torch.get_num_threads()))

torch.manual_seed(42)
t = time.time()
wav = model.generate(text="大家好，我是栖迟。",
                     prompt_wav_path=SEED_WAV, prompt_text=SEED_TEXT,
                     reference_wav_path=SEED_WAV,
                     cfg_value=2.0, inference_timesteps=10)
wav = np.asarray(wav, dtype=np.float32).reshape(-1)
out = os.path.join(HERE, "probe_out.wav")
sf.write(out, wav, 48000)
log("STEP3 generate DONE %.1fs audio=%.2fs -> %s" % (time.time() - t, len(wav)/48000.0, out))
log("=== probe OK ===")
os._exit(0)
