import json, subprocess
import numpy as np
from scipy.io import wavfile
A="/var/aiadultvideo/output/aiadult/"
SR=16000
def wav_of(mp4,dst):
    subprocess.run(["ffmpeg","-y","-v","error","-i",mp4,"-vn","-ac","1","-ar",str(SR),"-c:a","pcm_s16le",dst],check=True)
    sr,x=wavfile.read(dst); return x.astype(np.float64)
def env(x,hop=160):
    n=(len(x)-hop)//hop
    r=np.sqrt((x[:n*hop].reshape(n,hop)**2).mean(1)+1e-12)
    return 20*np.log10(r/32768.0)
def analyze(tag,mp4):
    x=wav_of(mp4,A+"voice_ref/"+tag+".wav")
    e=env(x)
    noise=float(np.percentile(e,10)); peak=float(np.percentile(e,99))
    thr=noise+6.0
    v=e>thr
    segs=[]; i=0; n=len(v)
    while i<n:
        if not v[i]: i+=1; continue
        j=i
        while j+1<n and v[j+1]: j+=1
        if (j-i)*0.01>=0.05: segs.append((round(i*0.01,2),round(j*0.01,2),round((j-i)*0.01,2)))
        i=j+1
    # syllable nuclei: peaks in smoothed envelope
    k=np.ones(5)/5.0; es=np.convolve(e,k,mode="same")
    peaks=[]
    for i2 in range(2,len(es)-2):
        if es[i2]>thr+3 and es[i2]>=es[i2-1] and es[i2]>es[i2+1] and es[i2]>=es[i2-2] and es[i2]>=es[i2+2]:
            if not peaks or (i2-peaks[-1])*0.01>=0.09: peaks.append(i2)
    return {"tag":tag,"noise_db":round(noise,1),"peak_db":round(peak,1),"thr_db":round(thr,1),
            "segments":[{"start":a,"end":b,"dur":d} for a,b,d in segs],
            "total_voiced_sec":round(float(v.sum())*0.01,2),
            "nuclei_count":len(peaks),
            "nuclei_times":[round(p*0.01,2) for p in peaks]}
out={}
for tag,mp4 in (("S06b_v5",A+"ep01_delivery/S06b_v5.mp4"),
                ("S02_v3_calib_2syl",A+"ep01_delivery/S02_v3.mp4"),
                ("S01_v15_calib",A+"ep01_delivery/S01_v15.mp4")):
    out[tag]=analyze(tag,mp4)
    print(tag,json.dumps(out[tag],ensure_ascii=False),flush=True)
json.dump(out,open(A+"voice_ref/syllable_check.json","w"),ensure_ascii=False,indent=1)
print("SYL_DONE",flush=True)
