import sys,asyncio,time,os,json,gc,wave
from pathlib import Path
from unittest.mock import patch
sys.path.insert(0,'/tmp/jarvis-pr8-perf-audit/apps/desktop/pipecat/src')
from jarvis_voice_runtime.parakeet import create_recognizer,ParakeetSegmentedSTT
import sherpa_onnx
ROOT=Path('/home/abstergo/Documents/Jarvis-pocket-migration/packages/jarvis-native-voice/resources/parakeet')
config=Path('/tmp/jarvis-pr8-perf-results/no-spin.conf');config.write_text('SessionConfig.session.intra_op.allow_spinning=0\nSessionConfig.session.inter_op.allow_spinning=0\n')
orig=sherpa_onnx.OfflineRecognizer.from_transducer;rows=[]
async def main():
 for threads,spin in [(4,True),(4,False),(2,False),(1,False)]:
  def factory(**kw):kw['num_threads']=threads;kw['provider']='cpu' if spin else 'cpu:'+str(config);return orig(**kw)
  z=time.perf_counter()
  with patch.object(sherpa_onnx.OfflineRecognizer,'from_transducer',factory):rec=create_recognizer(ROOT)
  load=(time.perf_counter()-z)*1000
  tests=[]
  for name,path in [('short',ROOT/'test_wavs/en-english.wav'),('report',Path('/tmp/jarvis-pr8-perf-results/typical-0.wav'))]:
   with wave.open(str(path),'rb') as w:sr=w.getframerate();pcm=w.readframes(w.getnframes())
   for trial in range(3):
    service=ParakeetSegmentedSTT(rec,'',sample_rate=sr);z=time.perf_counter();a=time.process_time();frames=[f async for f in service.run_stt(pcm)];tests.append({'text':name,'trial':trial,'wallMs':(time.perf_counter()-z)*1000,'cpuMs':(time.process_time()-a)*1000,'transcript':[f.text for f in frames]})
  idle=[]
  for i in range(2):
   a=time.process_time();await asyncio.sleep(2);idle.append(time.process_time()-a)
  row={'threads':threads,'spin':spin,'loadMs':load,'tests':tests,'idleCpuSecondsPer2s':idle};rows.append(row);print(json.dumps(row),flush=True);Path('/tmp/jarvis-pr8-perf-results/stt-threads.json').write_text(json.dumps(rows,indent=2))
  del service,rec;gc.collect()
asyncio.run(main())
