#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
EP03 fix6 三段 ASR 读音验收（接 wb id=307 第1步）

用 SenseVoiceSmall 转写 p04/p61/p107 三段，对照预期文本，标出读音锁词：
  梅殷 méi yīn / 私谥 sī shì / 惠宗 huì zōng
按纪律：ASR 只标疑似点，最终以花酱验 + 刚耳检为准；同音正字化不算读错。
"""
import json, os, sys, time
import re

HERE = os.path.dirname(os.path.abspath(__file__))
VOXDIR = os.path.join(HERE, "ep03_vox_fix6")
REPORT_JSON = os.path.join(HERE, "ep03_fix6_asr_report.json")
REPORT_MD = os.path.join(HERE, "ep03_fix6_asr_report.md")

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

# 预期文本（与 ep03_fix6_tts.py 一致）
EXPECT = {
    "p04":  "按说，故事到这儿该结束了。人死了，葬了。可新君即位，比下葬还早四天。",
    "p61":  "庙号和谥号更晚。神宗是建文旧臣梅殷的私谥，成祖不认；南明弘光元年，朝廷直接追上惠宗，谥让皇帝；清朝乾隆元年，又追谥恭闵惠皇帝。这就是《明史》称他「恭闵帝」的来历。距离那场火，已经三百多年。",
    "p107": "下期预告：回到《如果历史拐了个弯》。",
}
# 读音锁：目标词 -> (拼音, 常见 ASR 同音/近音误写)
PRON = {
    "梅殷": ("méi yīn", ["梅音", "梅因", "美音", "煤殷", "梅荫"]),
    "私谥": ("sī shì", ["私事", "四是", "司事", "私是", "厮是"]),
    "惠宗": ("huì zōng", ["慧宗", "会宗", "惠踪", "惠综"]),
}


def norm(s):
    s = re.sub(r"[\s，。；、：！？「」『』《》（）()\[\]【】,.;:!?\"'—\-]", "", s)
    return s


def main():
    from funasr import AutoModel
    t0 = time.time()
    asr = AutoModel(model="iic/SenseVoiceSmall", trust_remote_code=True,
                    device="cpu", disable_update=True)
    print("ASR_MODEL_OK %.1fs" % (time.time() - t0), flush=True)

    report = {"scope": "ep03 fix6 三段读音验收", "engine": "SenseVoiceSmall",
              "disclaimer": "ASR只标疑似点，最终以花酱验+刚耳检为准；同音正字化不算读错",
              "segments": [], "pron_flags": []}
    for key in ("p04", "p61", "p107"):
        wav = os.path.join(VOXDIR, "ep03_vox_fix6_%s.wav" % key)
        if not os.path.exists(wav):
            print("MISSING", wav, flush=True)
            continue
        r = asr.generate(input=wav, cache={}, language="zh", use_itn=True)
        text = r[0]["text"] if isinstance(r, list) and r else str(r)
        text = re.sub(r"<[^>]+>", "", text).strip()
        exp = EXPECT[key]
        nit_e, nit_a = norm(exp), norm(text)
        # 读音锁词：目标词是否在 ASR 里命中；常见误写是否出现
        flags = []
        for word, (py, wrongs) in PRON.items():
            if word not in exp:
                continue
            hit = word in text
            wh = [w for w in wrongs if w in text]
            flags.append({"word": word, "pinyin": py, "asr_hit": hit,
                          "asr_wrong_variants": wh,
                          "verdict": "疑似需耳检" if (not hit and wh) else
                                     ("未命中目标词(未必错)" if not hit else "目标词命中")})
        rec = {"seg": key, "expect": exp, "asr": text,
               "exact_match": nit_e == nit_a, "pron_flags": flags}
        report["segments"].append(rec)
        for fl in flags:
            fl2 = dict(fl)
            fl2["seg"] = key
            report["pron_flags"].append(fl2)
        print("%s exact=%s | ASR=%s" % (key, rec["exact_match"], text), flush=True)
        for fl in flags:
            print("   [%s] %s %s asr_hit=%s wrong=%s" %
                  (key, fl["word"], fl["pinyin"], fl["asr_hit"], fl["asr_wrong_variants"]), flush=True)

    with open(REPORT_JSON, "w", encoding="utf-8") as f:
        json.dump(report, f, ensure_ascii=False, indent=2)

    lines = ["# EP03 fix6 三段 ASR 读音验收", "",
             "> ASR 只标疑似点，最终以花酱验 + 刚耳检为准；同音正字化不算读错。", "",
             "配方：VoxCPM2 / seed42 / cfg2.0 / steps10 / 48k / voice_ref_eq48_ep04.wav", "",
             "## 读音锁重点", ""]
    for fl in report["pron_flags"]:
        lines.append("- **%s** `%s`（%s）：%s%s" % (
            fl["seg"], fl["word"], fl["pinyin"], fl["verdict"],
            "；ASR 误写=%s" % fl["asr_wrong_variants"] if fl["asr_wrong_variants"] else ""))
    lines += ["", "## 逐段对照", ""]
    for s in report["segments"]:
        lines += ["### %s（exact=%s）" % (s["seg"], s["exact_match"]), "",
                  "**预期**：%s" % s["expect"], "",
                  "**ASR** ：%s" % s["asr"], ""]
    with open(REPORT_MD, "w", encoding="utf-8") as f:
        f.write("\n".join(lines) + "\n")
    print("DONE segments=%d flags=%d" %
          (len(report["segments"]), len(report["pron_flags"])), flush=True)


if __name__ == "__main__":
    main()
