File size: 1,972 Bytes
928abc1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
"""Standalone streaming transcriber for the ExecuTorch (XNNPACK) export. pip install executorch sentencepiece soundfile scipy numpy
   python run_executorch.py audio.wav [encoder.int8.pte | encoder.pte]"""
import math, os, sys, time
import numpy as np, sentencepiece as spm, soundfile as sf, torch
from executorch.runtime import Runtime
from scipy.signal import resample_poly
H = os.path.dirname(os.path.abspath(__file__)); CH = 10240
rt = Runtime.get(); enc = rt.load_program(f"{H}/{sys.argv[2] if len(sys.argv) > 2 else 'encoder.int8.pte'}").load_method("forward")
jnt = rt.load_program(f"{H}/joint.pte").load_method("forward"); sp = spm.SentencePieceProcessor(model_file=f"{H}/tokenizer.model")
meta = enc.metadata; ins = [meta.input_tensor_meta(i) for i in range(meta.num_inputs())]
w, sr = sf.read(sys.argv[1], dtype="float32", always_2d=True); w = w.mean(1)
if sr != 16000: g = math.gcd(16000, sr); w = resample_poly(w, 16000 // g, sr // g).astype("float32")
x = np.pad(w, (0, (-len(w)) % CH + CH))[None]; t0 = time.time(); fr = []
st = [torch.zeros(tuple(ins[1].sizes())), torch.tensor(0, dtype=torch.int64), *[torch.zeros(tuple(m.sizes())) for m in ins[3:]]]  # all caches and the frame counter start at zero
for i in range(0, x.shape[1], CH):
    o = enc.execute([torch.from_numpy(x[:, i:i + CH]), *st]); fr.append(o[0][0].numpy()); st = list(o[2:])  # outputs 2.. are the new caches, fed back unchanged
f = np.concatenate(fr); ids, T, y2, y1, sym = [], 0, 0, 0, 0
while T < len(f):
    lg = jnt.execute([torch.from_numpy(f[T:T + 1]), torch.tensor([y2]), torch.tensor([y1])])[0][0].numpy()
    tok, dur = int(lg[:-5].argmax()), int(lg[-5:].argmax()); emit = tok != 0; sym = sym + 1 if emit and dur == 0 else 0
    if not emit or sym >= 5: dur = max(dur, 1)
    if dur > 0: sym = 0
    if emit: ids.append(tok - 1); y2, y1 = y1, tok
    T += dur
print(sp.decode(ids)); print(f"[{len(w)/16000:.1f} s audio, real-time factor {(time.time()-t0)/(len(w)/16000):.3f}]")