# Speech-only duration of each TTS file: ffprobe total minus leading/trailing silence (ffmpeg silencedetect -45 dB, 0.05 s).
import json, re, subprocess, glob, os, statistics as st
def dur(p): return float(subprocess.check_output(['ffprobe','-v','error','-show_entries','format=duration','-of','csv=p=0',p]).decode())
def speech(p):
    tot = dur(p)
    e = subprocess.run(['ffmpeg','-hide_banner','-nostats','-i',p,'-af','silencedetect=n=-45dB:d=0.05','-f','null','-'],capture_output=True,text=True).stderr
    starts = [float(x) for x in re.findall(r'silence_start: ([\d.]+)', e)]
    ends = [float(x) for x in re.findall(r'silence_end: ([\d.]+)', e)]
    lead = ends[0] if starts and starts[0] < 0.01 and ends else 0.0
    trail = tot - starts[-1] if starts and (len(starts) > len(ends) or ends[-1] >= tot - 0.01) and starts[-1] > lead else 0.0
    return tot, tot - lead - trail
d = json.load(open('hooks-analysed.json'))
# control: 31 words said at -r 155 should be about 12.0 s if the setting means words per minute
rows = []
for rate in (155, 120, 190):
    for r in d:
        f = 'wav/r%d_%s_%02d.wav' % (rate, r['fill'], r['i'])
        if not os.path.exists(f): continue
        tot, sp = speech(f)
        rows.append(dict(rate=rate, fill=r['fill'], i=r['i'], text=r['text'], w=r['w'], pred=r['w']/rate*60, total=tot, speech=sp))
json.dump(rows, open('tts-rows.json','w'))
for rate in (155,120,190):
    rr = [x for x in rows if x['rate']==rate]
    ratio = [x['speech']/x['pred'] for x in rr]
    wpm = [x['w']/x['speech']*60 for x in rr]
    err = [x['speech']-x['pred'] for x in rr]
    print('say -r %d: n=%d  measured/predicted median %.2f (min %.2f max %.2f); measured words/min median %.0f (min %.0f max %.0f); speech-pred diff median %.2f s, min %.2f max %.2f' % (rate, len(rr), st.median(ratio), min(ratio), max(ratio), st.median(wpm), min(wpm), max(wpm), st.median(err), min(err), max(err)))
rr = [x for x in rows if x['rate']==155]
print('at -r 155, total file (with lead/trail silence) minus speech: median %.2f s' % st.median([x['total']-x['speech'] for x in rr]))
print('lines within +-0.5 s of prediction at -r 155: %d of %d' % (sum(abs(x['speech']-x['pred'])<=0.5 for x in rr), len(rr)))
print('speech-only seconds at -r155, min/median/max %.2f/%.2f/%.2f' % (min(x['speech'] for x in rr), st.median([x['speech'] for x in rr]), max(x['speech'] for x in rr)))
for x in sorted(rr, key=lambda x: x['speech']-x['pred'])[:2]+sorted(rr, key=lambda x: x['speech']-x['pred'])[-2:]: print(' ', x['w'], 'pred %.2f measured %.2f' % (x['pred'], x['speech']), x['text'])
# by number of words: short (<=8) vs long (>=11)
for lab, f in (('<=8 words', lambda x: x['w']<=8), ('9-10 words', lambda x: 9<=x['w']<=10), ('>=11 words', lambda x: x['w']>=11)):
    g = [x for x in rr if f(x)]; print(lab, 'n=%d median measured/pred %.2f median wpm %.0f' % (len(g), st.median([x['speech']/x['pred'] for x in g]), st.median([x['w']/x['speech']*60 for x in g])))
