#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""树喝水全16段 ASR 回读验收：逐段卡「英文 + 无中文 + 文本完整」，疑似点人工耳检。"""
import os, re, sys
try:
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
    pass
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
EXCHANGE = r"D:/Download/muse_exchange"

def load_segs():
    txt = open(os.path.join(EXCHANGE, "tree_water_narration_en_v1.txt"), encoding="utf-8").read()
    parts = re.split(r"--- SEG (\d+)[^\n]*---\s*", txt)
    return {int(parts[i]): parts[i + 1].strip() for i in range(1, len(parts), 2)}

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)
    segs = load_segs()
    bad = []
    for idx in range(1, 17):
        p = os.path.join(EXCHANGE, "tree_water_en_SEG%02d_02voice_enseed.wav" % idx)
        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 = re.sub(r"<\|[^|>]*\|>", "", raw).strip()
        langs = re.findall(r"<\|(\w+)\|>", raw)
        zh = len(re.findall(r"[\u4e00-\u9fff]", t))
        aw, rw = norm(t), norm(segs[idx])
        hit = sum(1 for w in rw if w in aw) / max(1, len(rw))
        # 专业词疑似点：读音注里的词，ASR 拼错即标
        asr_words = set(aw)
        mark = [w for w in ("xylem", "transpiration", "cohesion", "tension", "hyperion",
                            "dixon", "joly", "evaporates", "molecule", "hydrogen")
                if w in rw and w not in asr_words]
        ok = ("en" in langs) and zh == 0 and hit >= 0.5 and len(aw) >= 6
        if not ok or mark:
            bad.append(idx)
        print("SEG%02d lang=%s zh=%d hit=%.2f %s%s" %
              (idx, ",".join(langs[:1]), zh, hit, "OK" if ok else "CHECK",
               (" suspect_px=" + ",".join(mark)) if mark else ""), flush=True)
        if not ok:
            print("  ASR=%r" % t, flush=True)
    print("SUMMARY total=16 bad=%d %s" % (len(bad), bad), flush=True)

if __name__ == "__main__":
    main()
