#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""05 s12「分/芬/纷」声调 F0 自检（花酱 id=245：刚说 v2 还是四声）

背景：刚在 05 v2 听到「水分子」的「分」仍是四声（基频 147Hz→98Hz 下降）。
我用的同音字「芬」版（sci05_s12_fen_fen.wav）没生效，需用 F0 轨迹判定：
  一声 fēn  → F0 高平（末段降幅 <15%）
  四声 fèn  → F0 明显下降（降幅 >=25%）
测法：取每个候选音频中「分子/芬子/纷子」那个字所在时窗（该字前的停顿后 ~0.35s），
      逐帧自相关 F0，看走向；同时打印全段 F0 供人工核对。
输出：F0 摘要 + 逐帧表
"""
import os, sys
import numpy as np
import soundfile as sf

CAND_DIR = r"D:/WorkBuddyProd/sci05/probe_s12s13"
CANDS = ["s12_original", "s12_fen_fen", "s12_fen_纷", "s12_final"]
EXTRA = r"D:/WorkBuddyProd/sci05/vox/s12.wav"   # 正式版


def f0_track(wav, sr, frame=0.05, hop=0.01, fmin=60, fmax=450):
    n, h = int(frame * sr), int(hop * sr)
    w = np.hanning(n)
    times, f0s = [], []
    for i in range(0, len(wav) - n, h):
        seg = wav[i:i + n]
        r = np.sqrt(np.mean(seg ** 2))
        if r < 0.01:
            times.append(i / sr); f0s.append(np.nan); continue
        ac = np.correlate(seg, seg, mode="full")[n - 1:]
        ac = ac / (ac[0] + 1e-9)
        lo, hi = int(sr / fmax), int(sr / fmin)
        if hi >= len(ac):
            times.append(i / sr); f0s.append(np.nan); continue
        k = lo + int(np.argmax(ac[lo:hi]))
        times.append(i / sr); f0s.append(sr / k if ac[k] > 0.3 else np.nan)
    return np.array(times), np.array(f0s)


def analyze(path, label):
    wav, sr = sf.read(path, dtype="float32")
    if wav.ndim > 1:
        wav = wav.mean(axis=1)
    t, f0 = f0_track(wav, sr)
    v = np.isfinite(f0)
    if v.sum() < 5:
        print("%-16s 无有效 F0" % label); return
    # 找最后一个连续有声段（句末字）
    voiced = f0[v]
    tmax = t[v][-1]
    seg = (t >= max(0, tmax - 0.45)) & v
    tail = f0[seg]
    tail = tail[np.isfinite(tail)]
    if len(tail) < 3:
        print("%-16s 尾部样本不足" % label); return
    hi = np.percentile(tail, 90); lo = np.percentile(tail, 10)
    drop = (hi - lo) / hi * 100.0
    kind = "一声(平)" if drop < 15 else ("四声(降)" if drop >= 25 else "不确定")
    print("%-16s 尾段F0 %.0f→%.0f 降幅%.0f%%  判定=%s" %
          (label, hi, lo, drop, kind))
    print("                 尾段F0序列: " + " ".join("%.0f" % x for x in tail))


if __name__ == "__main__":
    print("=== 05 s12 声调 F0 自检 ===")
    for c in CANDS:
        p = os.path.join(CAND_DIR, c + ".wav")
        if os.path.exists(p):
            analyze(p, c)
    if os.path.exists(EXTRA):
        analyze(EXTRA, "正式版s12.wav")
