#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""EP03 Short 1 旁白自检（wb id=381）：读音 + 停顿。
验：燕(yān)、一四零二、五个字/帝不知所终、这五字；停顿只在逗号处、无中间断句。
方法：整段 SenseVoice 识字（同音正字化不算错），能量分段看超长间隙定位异常停顿。
ASR 只作初筛；最终以花酱词级时间戳 + 刚耳检为准。"""
import json, 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)
from ep03_fix10_asr_probe import blocks, load

VOXDIR = os.path.join(HERE, "ep03_short1_vox")
OUT = os.path.join(HERE, "ep03_short1_asr_report.json")
SEEDS = [42, 43, 44, 45]

# 关键读音/文字检查：同音集（ASR 正字化不算错）
# 燕 yān：ASR 可能写「燕/宴/晏/厌」同音，都是 yān 一声对；「燕」在「燕王」按词义必 yān
CHECKS = {
    "yan_wang": ["燕王", "宴王", "晏王", "厌王", " yan王"],
    "yisi": ["一四零二", "一四0二", "一四〇二", "1402", "一四零二年", "一四零二年夏"],
    "five": ["五个字", "5个字", "五字"],
    "buzhizhong": ["帝不知所终", "不知所终"],
    "zhewuzi": ["这五字", "这5字", "这五个字"],
}

EXPECT_TEXT = (
    "公元一四零二年夏天，南京宫城起火。先说清楚，不是北京那座紫禁城。"
    "那时候，北京的紫禁城还没盖起来。火灭之后，燕王朱棣派人从灰烬里扒出残骸，"
    "说：这是皇帝，这是皇后。八天以后，以天子之礼下葬。按说案子该结了。"
    "可《明史》写到这儿，只用了五个字：帝不知所终。那具尸体，是胜利者派人「取」出来的。"
    "葬仪是真的，葬的是谁，没有旁证。建文帝到底去哪儿了？长视频从这五字的缝开始拆。"
)


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


def has_any(text, words):
    n = norm(text)
    return any(norm(w) in n for w in words)


def main():
    from funasr import AutoModel
    asr = AutoModel(model="iic/SenseVoiceSmall", hub="ms", disable_update=True)
    import soundfile as sf
    tmp = os.path.join(HERE, "_short1_asr_seg.wav")
    report = {"scope": "EP03 Short 1 旁白自检（wb id=381）",
              "expect_text": EXPECT_TEXT, "checks": CHECKS, "takes": {}}
    for seed in SEEDS:
        p = os.path.join(VOXDIR, "ep03_short1_s%d.wav" % seed)
        if not os.path.exists(p):
            continue
        x, sr = load(p)
        dur = len(x) / sr
        # 整段识字
        sf.write(tmp, x, sr)
        r = asr.generate(input=tmp)
        txt = r[0]["text"] if r else ""
        full = txt.split("|>")[-1]
        # 能量分段：看停顿分布（>0.45s 记为长停顿，正常句内逗号 0.15-0.5s）
        segs, gaps = blocks(x, sr, thr_db=-32.0)
        long_gaps = [g for g in gaps if g["dur"] >= 0.45]
        # 关键词命中
        hit = {k: has_any(full, words) for k, words in CHECKS.items()}
        # 四字污染（不应出现）
        four_bad = ("四个字" in norm(full)) or ("四字" in norm(full))
        row = {
            "file": os.path.basename(p), "duration_s": round(dur, 3),
            "asr_text": full, "asr_norm": norm(full),
            "checks_hit": hit, "four_bad": four_bad,
            "n_blocks": len(segs), "n_gaps": len(gaps),
            "long_gaps": long_gaps,
            "coverage_chars": len(norm(full)),
        }
        report["takes"]["s%d" % seed] = row
        print("\n=== s%d dur=%.2fs blocks=%d gaps=%d long>=0.45=%d ===" %
              (seed, dur, len(segs), len(gaps), len(long_gaps)), flush=True)
        print("ASR:", full, flush=True)
        print("HIT:", hit, "four_bad:", four_bad, "chars:", len(norm(full)), flush=True)
        print("LONG GAPS:", [(g["after_block"], g["s"], g["dur"]) for g in long_gaps], flush=True)
    json.dump(report, open(OUT, "w", encoding="utf-8"), ensure_ascii=False, indent=2)
    print("\nREPORT", OUT, flush=True)


if __name__ == "__main__":
    main()
