#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
tree_water 02暖男声线读英文 试音两段 ASR 回读验收
用法: python tree_water_en_asr.py
铁律（02 s17 探针翻车实证）：先卡「是英文 + 文本完整 + 无中文」，再谈音质；
02 中文底子读英文是首次，最怕蹦中文/英文乱码，ASE 疑似点一律人工耳检，不自判放行。
"""
import os, re, sys

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

HERE = os.path.dirname(os.path.abspath(__file__))
EXCHANGE = r"D:/Download/muse_exchange"

# 与 tree_water_en_probe.py 的 SEGS 对齐（英文原文）
REF = {
    "SEG01": "Picture the tallest living thing on Earth. A coast redwood in California, a hundred and fifteen meters tall. Taller than a thirty-five-story building.",
    "SEG09": "It pulls it. From the top. The engine is the leaf. Every leaf is losing water all the time. Sunlight hits the leaf, water evaporates off its surface thats transpiration.",
}
FILES = {
    "SEG01": os.path.join(EXCHANGE, "tree_water_en_SEG01_02voice_enseed.wav"),
    "SEG09": os.path.join(EXCHANGE, "tree_water_en_SEG09_02voice_enseed.wav"),
}


def clean(raw):
    t = re.sub(r"<\|[^|>]*\|>", "", raw).strip()
    return t


def norm(t):
    return re.sub(r"[^a-z0-9 ]", "", t.lower()).split()


def main():
    from funasr import AutoModel
    sense = AutoModel(model="iic/SenseVoiceSmall", trust_remote_code=True,
                      device="cpu", disable_update=True)
    bad = []
    for key in ("SEG01", "SEG09"):
        p = FILES[key]
        # 不强制 language，让 SenseVoice 自己判（验语言是否英文）
        r = sense.generate(input=p, cache={}, language="auto", use_itn=True)
        raw = r[0]["text"] if isinstance(r, list) and r else str(r)
        t = clean(raw)
        langs = re.findall(r"<\|(\w+)\|>", raw)
        zh = len(re.findall(r"[\u4e00-\u9fff]", t))
        asr_words = norm(t)
        ref_words = norm(REF[key])
        # 逐词命中率（顺序无关，集合）
        hit = sum(1 for w in ref_words if w in asr_words) / max(1, len(ref_words))
        ok = ("en" in langs) and zh == 0 and hit >= 0.5 and len(asr_words) >= 8
        if not ok:
            bad.append(key)
        print("%s lang=%s zh_chars=%d hit=%.2f words=%d %s" %
              (key, ",".join(langs), zh, hit, len(asr_words), "OK" if ok else "CHECK"), flush=True)
        print("  ASR=%r" % t, flush=True)
        print("  REF=%r" % REF[key], flush=True)
    print("SUMMARY total=2 bad=%d %s" % (len(bad), bad), flush=True)


if __name__ == "__main__":
    main()
