"""Segment a Slavin recording into phrases by RMS pauses. Save segments to JSON."""
import numpy as np, librosa, json, sys
def segment(path, min_pause=0.18, thr_pct=20, thr_mult=1.5):
    y, sr = librosa.load(path, sr=22050, mono=True)
    hop = int(0.02*sr)
    rms = librosa.feature.rms(y=y, frame_length=1024, hop_length=hop)[0]
    times = librosa.frames_to_time(np.arange(len(rms)), sr=sr, hop_length=hop)
    thr = np.percentile(rms, thr_pct) * thr_mult
    silent = rms < thr
    pauses=[]; i=0
    while i < len(silent):
        if silent[i]:
            j=i
            while j < len(silent) and silent[j]: j+=1
            dur=(j-i)*0.02
            if dur>=min_pause: pauses.append((float(times[i]), float(times[j-1]), float(dur)))
            i=j
        else: i+=1
    # phrases = gaps between pauses
    segs=[]; prev_end=0.0
    for (s,e,d) in pauses:
        if s-prev_end > 0.3:  # a real phrase (not just a blip)
            segs.append((prev_end, s))
        prev_end=e
    dur_total = len(y)/sr
    if dur_total-prev_end > 0.3: segs.append((prev_end, dur_total))
    return segs, pauses, dur_total
if __name__=='__main__':
    path = sys.argv[1]
    segs, pauses, total = segment(path)
    print(f"{path}: duration {total:.1f}s, pauses>=0.18s: {len(pauses)}, phrases: {len(segs)}")
    long_pauses = [p for p in pauses if p[2]>=1.0]
    print(f"long pauses (>=1s): {len(long_pauses)}")
    for s,e,d in long_pauses[:15]: print(f"  long pause {s:8.2f}-{e:8.2f} dur {d:.2f}")
    # phrase duration distribution
    durs=[b-a for a,b in segs]
    print(f"phrase durations: median {np.median(durs):.2f}s, mean {np.mean(durs):.2f}s, min {np.min(durs):.2f}, max {np.max(durs):.2f}")
    out={"path":path,"duration":total,"segments":segs,"pauses":pauses}
    json.dump(out, open(path.replace(".mp3","-segments.json"),"w"))
    print("saved", path.replace(".mp3","-segments.json"))
