# -*- coding: utf-8 -*-
"""为 fix10 停顿探针找合适的绝对能量门限：统计候选 wav 的 10ms RMS 与静音段。"""
import os, sys, numpy as np, soundfile as sf

HERE = os.path.dirname(os.path.abspath(__file__))
D = os.path.join(HERE, "ep03_vox_fix10")
FILES = ["ep03_fix10_full_s46.wav", "ep03_fix10_tail_s42.wav", "ep03_fix10_tail_s44.wav"]

for fn in FILES:
    x, sr = sf.read(os.path.join(D, fn))
    if x.ndim > 1:
        x = x.mean(axis=1)
    x = x.astype("float32")
    hop = int(sr * 0.01)
    rms = np.array([np.sqrt(np.mean(x[i*hop:(i+1)*hop]**2) + 1e-12)
                    for i in range(len(x)//hop)])
    db = 20*np.log10(rms+1e-12)
    print("\n", fn, "dur=%.2f" % (len(x)/sr),
          "peak=%.4f" % np.abs(x).max(),
          "rms_p10/p50/p90=%.1f/%.1f/%.1f dB" % tuple(np.percentile(db, [10,50,90])))
    for t in [-25, -28, -30, -32, -35, -38, -40, -45]:
        voiced = db > t
        # 合并 <100ms 的微断
        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] < 10:
                mg[-1][1] = b[1]
            else:
                mg.append(b)
        gaps = [(mg[k+1][0]-mg[k][1])*0.01 for k in range(len(mg)-1)]
        big = [g for g in gaps if g >= 0.2]
        print("  thr=%d dB: blocks=%d gaps>=0.2s=%s" %
              (t, len(mg), [round(g, 2) for g in big]))
