#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
科学线 05/06/07 音频 ASR 回读验收（通用版，参数化自 chili04_asr_v2.py）

用法: python sci_asr.py 05
铁律：先卡「是中文 + 文本完整」，再谈声调；声调 ASR 会正字化，必须人工耳检。
"""
import glob
import json
import os
import re
import sys

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

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from sci_cfg import ep_paths, EPS

EP = sys.argv[1]
P = ep_paths(EP)


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


def latin_count(t):
    return sum(c.isascii() and c.isalpha() for c in t)


def has_english_number(t):
    return bool(re.search(r"\bone\b|\bOne\b|ONE|万(?![物岁一])|汪[德洋]", t))


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

    files = sorted(glob.glob(os.path.join(P["vox"], "s*.wav")))
    bad = []
    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)
        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 ""
        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)
        if not ok:
            bad.append(base)
        print("%-12s lang=%-4s latin=%-2d complete=%-5s %-5s hit=%.2f en_one=%-5s ASR=%r" %
              (base, ",".join(lang[:1]), lat, complete, "OK" if ok else "CHECK",
               hit, en_num, t), flush=True)
    print("SUMMARY ep=%s total=%d bad=%d %s" % (EP, len(files), len(bad), bad))
    json.dump({"ep": EP, "total": len(files), "bad": bad},
              open(os.path.join(os.path.dirname(P["report"]), "sci%s_asr_report.json" % EP),
                   "w", encoding="utf-8"), ensure_ascii=False, indent=2)


if __name__ == "__main__":
    main()
