#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""EP03 fix9 第1步自验：
1) 全部 6 take 整段 SenseVoice 转写：p62 新词读对、p67 文字完整；
2) p67 三 take 能量分段 + 逐段 ASR 探针，定位「钧州人」「杨行祥」所在段，
   报告两处之间的停顿间隙——判断「钧州人」后是否有意外停顿、
   「杨行祥」后是否有应有停顿。
ASR 只作疑似标记；最终以花酱 ASR 词级时间戳 + 刚耳检为准。"""
import json, os, re, sys, time

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

HERE = os.path.dirname(os.path.abspath(__file__))
VOXDIR = os.path.join(HERE, "ep03_vox_fix9")
OUT = os.path.join(HERE, "ep03_fix9_asr_report.json")
SEEDS = [42, 43, 44]
EXPECT = {
    "p62": "为什么要花这么长时间，才肯把一个做过四年皇帝的人，重新写回时间里？因为承认他在位，就等于承认永乐登基之前，中间隔着一个合法的侄子。这是一件让朱棣的子孙一直睡不安稳的事。",
    "p67": "正统五年，一四四零年，出过一件能写进正史的事。有个僧人从云南走到广西，自称建文皇帝。思恩知府上报朝廷，一审问，判定他是钧州人杨行祥，年纪已经九十多，下狱四个月后死去，同谋的十二个僧人被发配辽东。",
}

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

def load(path, sr=48000):
    import soundfile as sf
    x, s = sf.read(path)
    if x.ndim > 1:
        x = x.mean(axis=1)
    if s != sr:
        import librosa
        x = librosa.resample(x, orig_sr=s, target_sr=sr)
    return x.astype("float32"), sr

def blocks(x, sr, thr_ratio=0.06, hop_ms=20, min_gap_ms=60, min_block_ms=100):
    import numpy as np
    hop = int(sr * hop_ms / 1000)
    rms = np.array([np.sqrt(np.mean(x[i*hop:(i+1)*hop]**2)+1e-12) for i in range(len(x)//hop)])
    thr = max(1e-4, thr_ratio*float(rms.max()))
    voiced = rms >= thr
    bs, i = [], 0
    while i < len(voiced):
        if voiced[i]:
            j = i
            while j < len(voiced) and voiced[j]:
                j += 1
            bs.append([i, j]); i = j
        else:
            i += 1
    mg = []
    for b in bs:
        if mg and (b[0]-mg[-1][1])*hop_ms < min_gap_ms:
            mg[-1][1] = b[1]
        else:
            mg.append(b)
    return [{"i": k, "s": round(a*hop/sr, 3), "e": round(b*hop/sr, 3)}
            for k, (a, b) in enumerate(mg) if (b-a)*hop_ms >= min_block_ms]

def probe(asr, x, sr, b):
    import soundfile as sf
    cl = x[int(b["s"]*sr):int(b["e"]*sr)]
    if len(cl) < int(0.1*sr):
        return ""
    tmp = os.path.join(HERE, "_fix9_probe.wav")
    sf.write(tmp, cl, sr)
    try:
        r = asr.generate(input=tmp, cache={}, language="zh", use_itn=True)
        txt = r[0]["text"] if isinstance(r, list) and r else str(r)
        return re.sub(r"<[^>]+>", "", txt).strip()
    except Exception:
        return ""

def main():
    t0 = time.time()
    from funasr import AutoModel
    asr = AutoModel(model="iic/SenseVoiceSmall", trust_remote_code=True,
                    device="cpu", disable_update=True)
    print("ASR_MODEL_OK %.1fs" % (time.time()-t0), flush=True)
    rep = {"scope": "EP03 fix9 第1步自验", "engine": "SenseVoiceSmall + 能量分段探针",
           "disclaimer": "ASR只标疑似，最终以花酱ASR词级时间戳+刚耳检为准", "takes": []}
    for key in ("p62", "p67"):
        for seed in SEEDS:
            name = "ep03_fix9_%s_s%d.wav" % (key, seed)
            path = os.path.join(VOXDIR, name)
            if not os.path.exists(path):
                print("MISSING", name, flush=True); continue
            r = asr.generate(input=path, cache={}, language="zh", use_itn=True)
            txt = r[0]["text"] if isinstance(r, list) and r else str(r)
            txt = re.sub(r"<[^>]+>", "", txt).strip()
            rec = {"seg": key, "seed": seed, "file": name, "asr": txt,
                   "norm_match": norm(txt) == norm(EXPECT[key]),
                   "dur_s": round(len(load(path)[0])/48000, 3)}
            checks = {}
            if key == "p62":
                checks["新词_睡不安稳"] = "睡不安稳" in txt
                checks["旧词_不好睡_absent"] = "不好睡" not in txt
            rec["checks"] = checks
            # p67 停顿探针：能量分段→逐段识字→找含「钧州人」「杨行祥」的段
            if key == "p67":
                x, sr = load(path)
                segs = blocks(x, sr)
                hits = {"junzhou": [], "yangxingxiang": []}
                probe_texts = {}
                for b in segs:
                    tt = probe(asr, x, sr, b)
                    probe_texts[b["i"]] = tt
                    if "钧州" in tt or "均州" in tt:
                        hits["junzhou"].append(b["i"])
                    if "杨行祥" in tt or "羊行祥" in tt or "扬行祥" in tt:
                        hits["yangxingxiang"].append(b["i"])
                rec["energy_blocks"] = len(segs)
                rec["probe_hits"] = hits
                rec["probe_texts"] = probe_texts
                # 停顿分析：钧州人 与 杨行祥 若在同一能量段（无内部间隙）→一口气读完；
                # 若分属相邻段且间隙 >150ms →「钧州人」后有意外停顿（错）
                jz = hits["junzhou"][0] if hits["junzhou"] else None
                yx = hits["yangxingxiang"][0] if hits["yangxingxiang"] else None
                gap_ms = None
                if jz is not None and yx is not None and yx == jz+1:
                    gap_ms = int(round((segs[yx]["s"]-segs[jz]["e"])*1000))
                rec["pause_between_junzhou_yang"] = {
                    "junzhou_block": jz, "yang_block": yx, "gap_ms": gap_ms,
                    "verdict": ("同段连读(可能正确)" if jz==yx else
                                "分段间隙%dms(疑钧州人后错停)" % gap_ms if gap_ms else "定位不足")}
            rep["takes"].append(rec)
            print("%s s%d dur=%.2f norm=%s checks=%s pause=%s | %s" %
                  (key, seed, rec["dur_s"], rec["norm_match"], checks,
                   rec.get("pause_between_junzhou_yang", {}).get("verdict", "-"),
                   txt[:50]), flush=True)
            json.dump(rep, open(OUT, "w", encoding="utf-8"), ensure_ascii=False, indent=2)
    print("DONE %.1f min takes=%d" % ((time.time()-t0)/60, len(rep["takes"])), flush=True)

if __name__ == "__main__":
    main()
