#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""04 v2 音频 ASR 回读验收（花酱 id=219/220）

铁律：先卡「是中文 + 文本完整」，再谈声调；声调 ASR 会正字化，必须人工耳检。
验两批：
  1) probe_trpv1_v2/ —— TRPV1 数字「一」读法候选，额外卡有没有把 1 读成英文 one
  2) vox_chili04_zh/ —— 中文 prompt 版全 23 段，查系统性吞字/英文漂移

用法: python chili04_asr_v2.py           # 两批都验
      python chili04_asr_v2.py --probe   # 只验候选
"""
import glob, os, re, sys

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

PROBE = r"D:/WorkBuddyProd/chili04/probe_trpv1_v2"
VOX = r"D:/WorkBuddyProd/chili04/vox_chili04_zh"
SUBS = r"D:/Download/muse_exchange/chili04_subs.json"


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


def latin_count(t):
    # 允许专名 T R P V（按字母读）和「一」；其余拉丁字母视为可疑漂移
    t2 = re.sub(r"TRPV|T\s*R\s*P\s*V|\b[TRPV]\b", "", t, flags=re.I)
    return sum(c.isascii() and c.isalpha() for c in t2)


def has_english_number(t):
    # 1 读成英文 one 时 ASR 常见输出：one / 万 / 汪 / 温 / 英文词
    return bool(re.search(r"\bone\b|\bOne\b|ONE|万(?![物岁一])|汪[德洋]", t))


def main():
    import json
    from funasr import AutoModel
    sense = AutoModel(model="iic/SenseVoiceSmall", trust_remote_code=True,
                      device="cpu", disable_update=True)
    subs = json.load(open(SUBS, encoding="utf-8"))["subs"]

    files = sorted(glob.glob(os.path.join(PROBE, "*.wav")))
    if "--probe" not in sys.argv:
        files += sorted(glob.glob(os.path.join(VOX, "s*.wav")))

    for p in files:
        r = sense.generate(input=p, cache={}, language="zh", use_itn=True)
        raw = r[0]["text"] if isinstance(r, list) and r else str(r)
        t = clean(raw)
        lang = re.findall(r"<\|(\w+)\|>", raw)
        lat = latin_count(t)
        en_num = has_english_number(t)
        base = os.path.basename(p)

        if "probe" in p:
            want = "长得不一样" if base.startswith("s16") else "受体"
            complete = want in t or ("首体" in t and want == "受体")
            ok = ("zh" in lang and lat <= 3 and complete and not en_num)
            note = "want=%s en_one=%s" % (want, en_num)
        else:
            m = re.match(r"s(\d+)\.wav", base)
            idx = int(m.group(1)) - 1 if m else -1
            ref = subs[idx]["text"] if 0 <= idx < len(subs) else ""
            # 用「汉字覆盖率」粗查吞字：参考句去掉标点后的汉字，ASR 命中比例
            chars = [c for c in ref if "\u4e00" <= c <= "\u9fff"]
            hit = sum(1 for c in chars if c in t) / max(1, len(chars))
            complete = hit >= 0.6
            ok = ("zh" in lang and lat <= 3 and complete and not en_num)
            note = "hit=%.2f en_one=%s ref=%r" % (hit, en_num, ref)

        print("%-24s lang=%-4s latin=%-2d complete=%-5s %-5s %-38s ASR=%r" %
              (base, ",".join(lang[:1]), lat, complete, "OK" if ok else "CHECK", note, t), flush=True)


if __name__ == "__main__":
    main()
