Files
Athena-Deck/integrations/parakeet-redux/compare.py
T

57 lines
4.4 KiB
Python

"""Isolated CPU-only ASR comparison. Requires explicit --go. Never reads private chats."""
import argparse,contextlib,io,json,os,pathlib,re,signal,socket,subprocess,time,urllib.request,wave
p=argparse.ArgumentParser();p.add_argument('--go',action='store_true');p.add_argument('--state-root',default='/var/lib/deck');p.add_argument('--cases',required=True);p.add_argument('--output',required=True);a=p.parse_args()
if not a.go:raise SystemExit('Prepared only. Add --go after user authorization.')
root=pathlib.Path(a.state_root);out=pathlib.Path(a.output);out.mkdir(parents=True,exist_ok=True)
cases=json.loads(pathlib.Path(a.cases).read_text());version='v0.6.1';pr=root/'parakeet-runtime'/version
runtime=json.loads((root/'runtime/state.json').read_text());llama=root/'runtime'/runtime['active']/'build/bin/llama-server'
entries=[]
for path in (root/'models').glob('*/entry.json'):
d=json.loads(path.read_text())
if d.get('repo')=='ggml-org/Qwen3-ASR-0.6B-GGUF':entries.append((d['file'],path.parent/'model.gguf'))
qmodel=next(path for name,path in entries if name=='Qwen3-ASR-0.6B-Q8_0.gguf');proj=next(path for name,path in entries if name=='mmproj-Qwen3-ASR-0.6B-Q8_0.gguf')
def wer(reference,hypothesis):
def words(s):return re.findall(r'\w+',s.casefold())
r,h=words(reference),words(hypothesis);row=list(range(len(h)+1))
for i,x in enumerate(r,1):
nxt=[i]
for j,y in enumerate(h,1):nxt.append(min(nxt[-1]+1,row[j]+1,row[j-1]+(x!=y)))
row=nxt
return row[-1]/max(1,len(r))
def request(url,audio):
boundary='athena-synthetic-comparison'
body=(f'--{boundary}\r\nContent-Disposition: form-data; name="model"\r\n\r\ndeck-stt\r\n--{boundary}\r\nContent-Disposition: form-data; name="language"\r\n\r\nde\r\n--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="synthetic.wav"\r\nContent-Type: audio/wav\r\n\r\n').encode()+audio+f'\r\n--{boundary}--\r\n'.encode()
with urllib.request.urlopen(urllib.request.Request(url+'/v1/audio/transcriptions',data=body,headers={'Content-Type':'multipart/form-data; boundary='+boundary}),timeout=280) as resp:return json.load(resp)['text'].split('<asr_text>')[-1].replace('<|endoftext|>','').strip()
results=[]
for engine in ('qwen','redux'):
with socket.socket() as s:s.bind(('127.0.0.1',0));port=s.getsockname()[1]
args=([str(llama),'--model',str(qmodel),'--mmproj',str(proj),'--no-mmproj-offload','--n-gpu-layers','0','--ctx-size','4096','--threads','2','--parallel','1','--host','127.0.0.1','--port',str(port),'--no-ui','--fit','off','--alias','deck-stt'] if engine=='qwen' else [str(pr/'runtime'/('parakeet-'+version+'-bin-linux-cpu-x64')/'parakeet-server'),'--model',str(pr/'redux-packed.gguf'),'--host','127.0.0.1','--port',str(port),'--threads','2','--concurrency','1'])
start=time.monotonic();proc=subprocess.Popen(args,env=dict(os.environ,CUDA_VISIBLE_DEVICES='',OMP_NUM_THREADS='2'),stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,start_new_session=True)
try:
url=f'http://127.0.0.1:{port}'
while True:
if proc.poll() is not None:raise RuntimeError(engine+' startup failed')
if time.monotonic()-start>120:raise RuntimeError(engine+' startup timeout')
try:
with urllib.request.urlopen(url+'/health',timeout=1) as resp:
if resp.status==200:break
except OSError:time.sleep(.2)
load=time.monotonic()-start
for case in cases:
source=pathlib.Path(a.cases).parent/case['file']
# Converts only the explicitly listed synthetic files; no library scans.
pcm=subprocess.check_output(['ffmpeg','-nostdin','-v','error','-i',str(source),'-ac','1','-ar','16000','-f','s16le','pipe:1'],stderr=subprocess.DEVNULL)
buffer=io.BytesIO()
with wave.open(buffer,'wb') as w:w.setnchannels(1);w.setsampwidth(2);w.setframerate(16000);w.writeframes(pcm)
audio=buffer.getvalue();duration=len(pcm)/32000
for repetition in (1,2):
t=time.monotonic();text=request(url,audio);elapsed=time.monotonic()-t
row=dict(engine=engine,case=case['name'],repetition=repetition,startup_seconds=round(load,3),seconds=round(elapsed,3),audio_seconds=round(duration,3),rtf=round(elapsed/duration,4),wer=round(wer(case['expected'],text),4),text=text)
results.append(row);(out/'results.json').write_text(json.dumps(results,indent=2));print(json.dumps({k:v for k,v in row.items() if k!='text'}),flush=True)
finally:
if proc.poll() is None:
os.killpg(proc.pid,signal.SIGTERM)
try:proc.wait(timeout=10)
except subprocess.TimeoutExpired:os.killpg(proc.pid,signal.SIGKILL);proc.wait()
(out/'complete').write_text('Synthetic comparison complete\n')