# Control for the speech-length measure + calibrated prediction + effect of punctuation inside a line (same voice, same rate).
import json, re, subprocess, statistics as st, importlib.util, sys
spec = importlib.util.spec_from_file_location('m', 'measure.py')
src = open('measure.py').read().split("d = json.load")[0]
exec(src)
# CONTROL: 0.5 s silence + 3.00 s tone + 0.5 s silence must read as 3.00 s speech
subprocess.run(['ffmpeg','-y','-v','error','-f','lavfi','-i','anullsrc=r=22050:cl=mono','-f','lavfi','-i','sine=f=440:r=22050:d=3','-f','lavfi','-i','anullsrc=r=22050:cl=mono','-filter_complex','[0]atrim=duration=0.5[a];[2]atrim=duration=0.5[c];[a][1][c]concat=n=3:v=0:a=1','control-3s.wav'],check=True)
t, s = speech('control-3s.wav'); print('CONTROL tone 3.00 s with 0.5 s silence each side: total %.2f speech %.2f -> %s' % (t, s, 'OK' if abs(s-3.0) < 0.1 else 'FAILED'))
rows = [r for r in json.load(open('tts-rows.json')) if r['rate']==155]
W = sum(r['w'] for r in rows); S = sum(r['speech'] for r in rows)
wpm = W/S*60; print('pooled voice pace at say -r 155: %d words / %.1f s = %.0f wpm' % (W, S, wpm))
err = [r['speech'] - r['w']/wpm*60 for r in rows]
print('calibrated prediction error (measured - words/pooled wpm), s: median %.2f, min %.2f, max %.2f, within +-0.5 s: %d of %d, within +-0.3 s: %d' % (st.median(err), min(err), max(err), sum(abs(e)<=0.5 for e in err), len(err), sum(abs(e)<=0.3 for e in err)))
inner = lambda t: bool(re.search(r'[.,:;?!]\s', t))
a = [r for r in rows if not inner(r['text'])]; b = [r for r in rows if inner(r['text'])]
for lab, g in (('no punctuation inside the line', a), ('punctuation inside the line', b)):
    print('%s: n=%d median seconds per word %.3f, median wpm %.0f' % (lab, len(g), st.median([r['speech']/r['w'] for r in g]), st.median([r['w']/r['speech']*60 for r in g])))
# same word count, with vs without: 9-word lines
for w in (8,9,10):
    ga=[r['speech'] for r in a if r['w']==w]; gb=[r['speech'] for r in b if r['w']==w]
    print('%d-word lines: no punct n=%d median %.2f s | with punct n=%d median %.2f s' % (w, len(ga), st.median(ga) if ga else float('nan'), len(gb), st.median(gb) if gb else float('nan')))
# the 30 default-fill lines at three say rates: seconds for the median line
for rate in (120,155,190):
    g=[r['speech'] for r in json.load(open('tts-rows.json')) if r['rate']==rate]
    print('say -r %d, 30 default lines: median speech %.2f s, max %.2f s' % (rate, st.median(g), max(g)))
