#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""fix7「燕王」声调精确复核：能量分段→逐段 ASR 探针→严格定位含「燕王」的段→yin F0。
修正上一版探针误命中「检验」的 bug：关键词必须「燕/烟/淹/焉」紧邻「王」，或句首单「燕」。
"""
import os, re, sys, json
import numpy as np, soundfile as sf, librosa

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_fix7")
SR = 48000

def voiced_segments(x, sr, thr_db=-34.0, min_ms=90, gap_ms=160):
    hop = int(sr * 0.01)
    n = len(x) // hop
    e = x[:n*hop].reshape(n, hop)
    db = 20*np.log10(np.sqrt((e**2).mean(axis=1))+1e-12)
    on = db > thr_db
    segs, i = [], 0
    while i < n:
        if not on[i]:
            i += 1; continue
        j, last = i, i
        while j < n:
            if on[j]: last = j
            if j - last > gap_ms//10: break
            j += 1
        if (last-i+1)*10 >= min_ms:
            segs.append((i*0.01, (last+1)*0.01))
        i = j+1
    return segs

def is_yanwang(t):
    """严格判定探针文本是否含『燕王』音节（ASR 常写成 燕/烟/淹/焉/宴/艳 + 王）。"""
    t = t.replace(" ", "")
    return bool(re.search(r"[燕烟淹焉宴艳彦]王", t))

def f0_window(x, sr, a, b):
    seg = x[int(a*sr):int(b*sr)]
    if len(seg) < sr*0.05:
        return None
    # 只取前 55%：覆盖「燕」起音到「王」之前，避开后字
    seg = seg[:int(len(seg)*0.55)]
    f0 = librosa.yin(seg, fmin=70, fmax=320, sr=sr, frame_length=2048, hop_length=128)
    n = len(f0)
    rms = np.array([np.sqrt((seg[i*128:(i+1)*128]**2).mean()+1e-12) for i in range(n)])
    db = 20*np.log10(rms+1e-12)
    m = db > -42.0
    v = f0[m]
    if len(v) < 4:
        return None
    # 野点剔除
    good=[v[0]]
    for q in v[1:]:
        if abs(q-good[-1]) <= 55: good.append(q)
    v=np.array(good)
    if len(v) < 4: return None
    k=max(2,len(v)//3)
    head=float(np.median(v[:k])); tail=float(np.median(v[-k:]))
    return {"n":len(v),"head":round(head,1),"tail":round(tail,1),
            "delta":round(tail-head,1),"med":round(float(np.median(v)),1)}

def main():
    from funasr import AutoModel
    asr = AutoModel(model="iic/SenseVoiceSmall", trust_remote_code=True,
                    device="cpu", disable_update=True)
    out={"scope":"fix7 燕王声调精确复核","takes":[]}
    for key in ("p38","p40"):
        for seed in (42,43,44,45):
            path=os.path.join(VOXDIR,"ep03_fix7_%s_s%d.wav"%(key,seed))
            x,sr=sf.read(path)
            if x.ndim>1: x=x.mean(axis=1)
            segs=voiced_segments(x,sr)
            probes=[]
            hit=None
            tmp=os.path.join(HERE,"_probe2.wav")
            for a,b in segs:
                clip=x[int(a*sr):int(b*sr)]
                sf.write(tmp,clip,sr)
                r=asr.generate(input=tmp,cache={},language="zh",use_itn=True)
                tt=re.sub(r"<[^>]+>","",(r[0]["text"] if r else "")).strip()
                probes.append({"seg":[round(a,2),round(b,2)],"text":tt})
                if is_yanwang(tt):
                    hit=(a,b,tt); break
            f0=f0_window(x,sr,hit[0],hit[1]) if hit else None
            rec={"seg":key,"seed":seed,"hit":(hit[2] if hit else None),
                 "hit_seg":([round(hit[0],2),round(hit[1],2)] if hit else None),
                 "f0":f0,"probes":probes}
            out["takes"].append(rec)
            verdict="?"
            if f0: verdict="一声yān(平)" if f0["delta"]>-12 else ("四声yàn(降)" if f0["delta"]<-18 else "边界")
            print("%s s%d hit=%r f0=%s -> %s"%(key,seed,rec["hit"],f0,verdict),flush=True)
            json.dump(out,open(os.path.join(HERE,"ep03_fix7_tone_report.json"),"w",encoding="utf-8"),ensure_ascii=False,indent=2)
    print("DONE",flush=True)

if __name__=="__main__":
    main()
