Download stream_ref.py from Reza2kn/Shenava-Rizeh-v1.5-tract-streaming: direct link, hf CLI and curl.
- Browser
- Download file 2.19 kB
-
https://huggingface.co/Reza2kn/Shenava-Rizeh-v1.5-tract-streaming/resolve/main/stream_ref.py
- Command line
-
hf download hf://Reza2kn/Shenava-Rizeh-v1.5-tract-streaming/stream_ref.py
-
curl -L -o stream_ref.py https://huggingface.co/Reza2kn/Shenava-Rizeh-v1.5-tract-streaming/resolve/main/stream_ref.py
2.19 kB
| """Reference streaming decode with onnxruntime over the exported streaming encoder (greedy, English block masked). | |
| Dumps per-chunk features + expected tokens so other runtimes (tract, CoreML) can be checked bit-for-bit-ish. | |
| usage: stream_ref.py model_dir wav outprefix""" | |
| import sys,json,numpy as np,soundfile as sf,onnxruntime as ort,torch | |
| import os;sys.path.insert(0,os.path.dirname(os.path.abspath(__file__))) | |
| from fbank_torch import fbank | |
| d,wav,outp=sys.argv[1:4] | |
| so=ort.SessionOptions();so.intra_op_num_threads=4 | |
| enc=ort.InferenceSession(f'{d}/encoder.onnx',so);dec=ort.InferenceSession(f'{d}/decoder.onnx',so);joi=ort.InferenceSession(f'{d}/joiner.onnx',so) | |
| meta=enc.get_modelmeta().custom_metadata_map;T=int(meta['T']);CH=int(meta['decode_chunk_len']) | |
| x,sr=sf.read(wav,dtype='float32');x=x.mean(1) if x.ndim>1 else x | |
| x=np.concatenate([x,np.zeros(int(0.8*sr),np.float32)]) # tail padding like sherpa | |
| F=fbank(torch.from_numpy(x)).numpy().astype(np.float32) | |
| n=max(1,(len(F)-T)//CH+1) | |
| states={i.name:np.zeros([s if isinstance(s,int) else 1 for s in i.shape],dtype=np.int64 if 'int64' in i.type else np.float32) for i in enc.get_inputs()[1:]} | |
| allowed=np.r_[0:32,1056:2080];mask=np.full(2080,-1e9,np.float32);mask[allowed]=0 | |
| ctx=[0,0];toks=[];dout=dec.run(None,{'y':np.array([ctx],np.int64)})[0];chunks=[] | |
| for c in range(n): | |
| xc=F[c*CH:c*CH+T];xc=np.pad(xc,((0,T-len(xc)),(0,0)));chunks.append(xc) | |
| o=enc.run(None,{'x':xc[None],**states});eo=o[0][0] | |
| for name,v in zip([q.name for q in enc.get_outputs()[1:]],o[1:]): states[name[4:]]=v | |
| for t in range(len(eo)): | |
| lg=joi.run(None,{'encoder_out':eo[t:t+1],'decoder_out':dout})[0][0]+mask;k=int(lg.argmax()) | |
| if k!=0: | |
| toks.append(k);ctx=[ctx[-1],k];dout=dec.run(None,{'y':np.array([ctx],np.int64)})[0] | |
| pieces=[l.rstrip('\n').rsplit(' ',1)[0] for l in open(f'{d}/tokens.txt',encoding='utf-8')] | |
| txt=''.join(pieces[i] for i in toks).replace('▁',' ').strip() | |
| np.stack(chunks).astype('<f4').tofile(outp+'.chunks.f32');json.dump({'T':T,'chunk':CH,'n':n,'tokens':toks,'text':txt,'state_inputs':[[i.name,i.shape,i.type] for i in enc.get_inputs()]},open(outp+'.json','w'),ensure_ascii=False) | |
| print(n,'chunks',txt) | |