SayedShaun commited on
Commit
8aeadc7
·
verified ·
1 Parent(s): 1c6663a

Lightweight loader: numpy features, stdlib WAV + downloader; only onnxruntime and numpy required

Browse files
Files changed (1) hide show
  1. asr.py +178 -43
asr.py CHANGED
@@ -1,14 +1,25 @@
1
  # SPDX-License-Identifier: Apache-2.0 (loader code; the model weights are CC BY-SA 4.0, see LICENSE)
2
- """Bangla Zipformer transducer (ONNX) - self-contained inference, no torch / icefall needed.
3
 
4
- pip install huggingface_hub onnxruntime numpy soundfile soxr kaldi-native-fbank
 
5
 
6
  from asr import BanglaASR
7
- asr = BanglaASR.from_pretrained("SayedShaun/bangla-zipformer-onnx", precision="int8")
8
  print(asr.transcribe("audio.wav")) # beam search (default)
9
  print(asr.transcribe("audio.wav", decoding="greedy")) # faster
 
 
 
 
 
 
 
10
  """
11
  import os
 
 
 
12
  from typing import List, Tuple, Union
13
 
14
  import numpy as np
@@ -18,46 +29,112 @@ MAX_CHUNK_S = 20.0 # the model was trained on utterances up to 20 s
18
  SEARCH_S = 3.0 # look this far back from a 20 s boundary for the quietest point to cut at
19
  MIN_S = 1.0 # shorter clips are padded with silence up to this length
20
  PRECISIONS = ("fp32", "fp16", "int8")
 
 
21
 
 
 
22
 
23
- def _fbank(samples: np.ndarray) -> np.ndarray:
24
- """80-dim kaldi fbank, identical settings to training (lhotse Fbank): (T, 80) float32."""
25
- import kaldi_native_fbank as knf
26
-
27
- o = knf.FbankOptions()
28
- o.frame_opts.samp_freq = SAMPLE_RATE
29
- o.frame_opts.dither = 0.0
30
- o.frame_opts.snip_edges = False
31
- o.frame_opts.window_type = "povey"
32
- o.frame_opts.remove_dc_offset = True
33
- o.frame_opts.preemph_coeff = 0.97
34
- o.mel_opts.num_bins = 80
35
- o.mel_opts.low_freq = 20.0
36
- o.mel_opts.high_freq = -400.0
37
- o.energy_floor = 1e-10
38
- o.use_energy = False
39
- f = knf.OnlineFbank(o)
40
- f.accept_waveform(SAMPLE_RATE, samples.astype(np.float32).tolist())
41
- f.input_finished()
42
- return np.stack([f.get_frame(i) for i in range(f.num_frames_ready)]).astype(np.float32)
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
- def _load_audio(audio: Union[str, os.PathLike, Tuple[np.ndarray, int]]) -> np.ndarray:
46
- """File path (wav/flac/ogg/...) or (samples, sample_rate) -> mono float32 at 16 kHz."""
47
- import soundfile as sf
48
 
 
 
49
  if isinstance(audio, tuple):
50
  x, sr = audio
51
  else:
52
- x, sr = sf.read(str(audio), dtype="float32", always_2d=False)
 
 
 
 
 
 
 
 
53
  x = np.asarray(x, dtype=np.float32)
54
  if x.ndim == 2:
55
  x = x.mean(axis=1)
56
- if sr != SAMPLE_RATE:
57
- import soxr
58
-
59
- x = soxr.resample(x, sr, SAMPLE_RATE)
60
- return x
61
 
62
 
63
  def _split(x: np.ndarray) -> List[np.ndarray]:
@@ -78,6 +155,55 @@ def _split(x: np.ndarray) -> List[np.ndarray]:
78
  return out
79
 
80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  class BanglaASR:
82
  def __init__(self, model_dir: str, precision: str = "int8", num_threads: int = 4, beam: int = 4):
83
  import onnxruntime as ort
@@ -104,16 +230,10 @@ class BanglaASR:
104
  self.tokens[int(idx)] = tok
105
 
106
  @classmethod
107
- def from_pretrained(cls, repo_id: str = "SayedShaun/bangla-zipformer-onnx", precision: str = "int8",
108
- num_threads: int = 4, beam: int = 4, token: str = None, revision: str = None) -> "BanglaASR":
109
- """repo_id: a Hugging Face repo name (downloads only the chosen precision) or a local folder."""
110
- if os.path.isdir(repo_id):
111
- path = repo_id
112
- else:
113
- from huggingface_hub import snapshot_download
114
-
115
- path = snapshot_download(repo_id, allow_patterns=[f"{precision}/*", "tokens.txt"], token=token, revision=revision)
116
- return cls(path, precision, num_threads, beam)
117
 
118
  def _greedy(self, enc: np.ndarray) -> List[int]:
119
  """Greedy transducer search (one symbol per frame), enc: (T, joiner_dim)."""
@@ -177,5 +297,20 @@ class BanglaASR:
177
  x_name, l_name = (i.name for i in self.encoder.get_inputs())
178
  enc, _ = self.encoder.run(None, {x_name: feats, l_name: np.array([feats.shape[1]], dtype=np.int64)})
179
  ids = self._greedy(enc[0]) if decoding == "greedy" else self._beam_search(enc[0], self.beam)
180
- pieces.append("".join(self.tokens[i] for i in ids).replace("▁", " ").strip())
181
  return " ".join(p for p in pieces if p)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # SPDX-License-Identifier: Apache-2.0 (loader code; the model weights are CC BY-SA 4.0, see LICENSE)
2
+ """Bangla Zipformer transducer (ONNX) - a single-file, minimal-dependency loader.
3
 
4
+ pip install onnxruntime numpy
5
+ curl -LO https://huggingface.co/SayedShaun/bangla-zipformer-onnx/resolve/main/asr.py
6
 
7
  from asr import BanglaASR
8
+ asr = BanglaASR.from_pretrained("SayedShaun/bangla-zipformer-onnx", precision="int8") # fp32 | fp16 | int8
9
  print(asr.transcribe("audio.wav")) # beam search (default)
10
  print(asr.transcribe("audio.wav", decoding="greedy")) # faster
11
+
12
+ or from a shell: python asr.py audio.wav [--precision int8] [--decoding greedy]
13
+
14
+ Required: onnxruntime, numpy. Everything else is optional: `soundfile` (FLAC / OGG / MP3 input; plain 16-bit WAV
15
+ works without it), `soxr` (higher-quality resampling for non-16 kHz audio), `huggingface_hub` (used for downloads
16
+ when installed; otherwise a built-in downloader fetches the files). Features are computed in numpy (Kaldi-compatible
17
+ 80-dim fbank, matching the training features to ~0.003 in log-mel).
18
  """
19
  import os
20
+ import sys
21
+ import urllib.request
22
+ import wave
23
  from typing import List, Tuple, Union
24
 
25
  import numpy as np
 
29
  SEARCH_S = 3.0 # look this far back from a 20 s boundary for the quietest point to cut at
30
  MIN_S = 1.0 # shorter clips are padded with silence up to this length
31
  PRECISIONS = ("fp32", "fp16", "int8")
32
+ DEFAULT_REPO = "SayedShaun/bangla-zipformer-onnx"
33
+ ONNX_NAMES = ("encoder", "decoder", "joiner")
34
 
35
+ # ---------------------------------------------------------------- features (numpy, Kaldi-compatible fbank)
36
+ _EPS = float(np.finfo(np.float32).eps) # Kaldi floors mel energies at float32 epsilon
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
+ def _mel_filterbank(n_fft=512, num_bins=80, low=20.0, high=7600.0, sr=SAMPLE_RATE):
40
+ """Kaldi-style triangular mel filters over the first n_fft/2 FFT bins: (num_bins, n_fft/2)."""
41
+ mel = lambda f: 1127.0 * np.log1p(f / 700.0)
42
+ mel_low, mel_high = mel(low), mel(high)
43
+ delta = (mel_high - mel_low) / (num_bins + 1)
44
+ left = mel_low + np.arange(num_bins)[:, None] * delta
45
+ center = left + delta
46
+ right = center + delta
47
+ m = mel(np.arange(n_fft // 2) * (sr / n_fft))[None, :]
48
+ up = (m - left) / (center - left)
49
+ down = (right - m) / (right - center)
50
+ return np.maximum(0.0, np.minimum(up, down))
51
+
52
+
53
+ _FB = _mel_filterbank()
54
+ # Each triangular filter touches only a few FFT bins. Applying them as 80 small slices (no BLAS) avoids a matmul whose
55
+ # multi-threaded BLAS call would compete with onnxruntime's own threads (measured: 1.35x slower overall).
56
+ _BANDS = [(int(np.nonzero(r)[0][0]), int(np.nonzero(r)[0][-1]) + 1, r[np.nonzero(r)[0][0]: np.nonzero(r)[0][-1] + 1].copy()) for r in _FB]
57
+ _WIN = (0.5 - 0.5 * np.cos(2 * np.pi * np.arange(400) / 399)) ** 0.85 # "povey" window
58
+
59
+
60
+ def _fbank(x: np.ndarray) -> np.ndarray:
61
+ """80-dim Kaldi-compatible log-mel features: 25 ms frames, 10 ms shift, no dither, snip_edges=False.
62
+ x: float samples in [-1, 1] at 16 kHz. Returns (T, 80) float32."""
63
+ x = np.asarray(x, dtype=np.float64)
64
+ n, shift, flen = len(x), 160, 400
65
+ frames = (n + shift // 2) // shift
66
+ start = np.arange(frames) * shift + shift // 2 - flen // 2
67
+ idx = start[:, None] + np.arange(flen)[None, :]
68
+ idx = np.where(idx < 0, -idx - 1, idx) # reflect at the start
69
+ idx = np.where(idx >= n, 2 * n - 1 - idx, idx) # reflect at the end
70
+ f = x[idx]
71
+ f -= f.mean(axis=1, keepdims=True) # remove DC offset
72
+ pre = f.copy()
73
+ f[:, 1:] = pre[:, 1:] - 0.97 * pre[:, :-1] # pre-emphasis from the raw previous sample
74
+ f[:, 0] = pre[:, 0] * (1.0 - 0.97) # first sample: x0 - 0.97 * x0
75
+ f *= _WIN
76
+ spec = np.fft.rfft(f, n=512, axis=1)[:, :256]
77
+ power = spec.real ** 2 + spec.imag ** 2
78
+ mel = np.empty((power.shape[0], len(_BANDS)))
79
+ for j, (lo, hi, w) in enumerate(_BANDS):
80
+ mel[:, j] = (power[:, lo:hi] * w).sum(axis=1) # plain numpy, no BLAS call
81
+ return np.log(np.maximum(mel, _EPS)).astype(np.float32)
82
+
83
+
84
+ # ---------------------------------------------------------------- audio input
85
+ def _read_wav(path) -> Tuple[np.ndarray, int]:
86
+ """Plain PCM WAV via the standard library (8/16/24/32-bit)."""
87
+ with wave.open(str(path), "rb") as w:
88
+ sr, ch, width, n = w.getframerate(), w.getnchannels(), w.getsampwidth(), w.getnframes()
89
+ raw = w.readframes(n)
90
+ if width == 2:
91
+ x = np.frombuffer(raw, dtype="<i2").astype(np.float32) / 32768.0
92
+ elif width == 1:
93
+ x = (np.frombuffer(raw, dtype=np.uint8).astype(np.float32) - 128.0) / 128.0
94
+ elif width == 3:
95
+ b = np.frombuffer(raw, dtype=np.uint8).reshape(-1, 3).astype(np.int32)
96
+ x = (((b[:, 0] | (b[:, 1] << 8) | (b[:, 2] << 16)) << 8) >> 8).astype(np.float32) / 8388608.0
97
+ elif width == 4:
98
+ x = np.frombuffer(raw, dtype="<i4").astype(np.float32) / 2147483648.0
99
+ else:
100
+ raise ValueError(f"unsupported WAV sample width: {width} bytes")
101
+ return (x.reshape(-1, ch).mean(axis=1) if ch > 1 else x), sr
102
+
103
+
104
+ def _resample(x: np.ndarray, sr: int) -> np.ndarray:
105
+ if sr == SAMPLE_RATE:
106
+ return x
107
+ try:
108
+ import soxr
109
+
110
+ return soxr.resample(x, sr, SAMPLE_RATE)
111
+ except ImportError: # numpy fallback: band-limited FFT resampling (fine for speech)
112
+ n_out = int(round(len(x) * SAMPLE_RATE / sr))
113
+ spec = np.fft.rfft(x)
114
+ out = np.zeros(n_out // 2 + 1, dtype=spec.dtype)
115
+ k = min(len(out), len(spec))
116
+ out[:k] = spec[:k]
117
+ return (np.fft.irfft(out, n_out) * (n_out / len(x))).astype(np.float32)
118
 
 
 
 
119
 
120
+ def _load_audio(audio: Union[str, os.PathLike, Tuple[np.ndarray, int]]) -> np.ndarray:
121
+ """Path to an audio file, or (samples, sample_rate) -> mono float32 at 16 kHz."""
122
  if isinstance(audio, tuple):
123
  x, sr = audio
124
  else:
125
+ try:
126
+ x, sr = _read_wav(audio)
127
+ except (wave.Error, EOFError): # not a plain PCM WAV (FLAC, OGG, MP3, float WAV, ...)
128
+ try:
129
+ import soundfile as sf
130
+ except ImportError:
131
+ raise RuntimeError("This is not a plain PCM WAV file. Install `soundfile` (pip install soundfile) "
132
+ "to read FLAC / OGG / MP3 / float WAV, or convert it to 16-bit WAV.") from None
133
+ x, sr = sf.read(str(audio), dtype="float32", always_2d=False)
134
  x = np.asarray(x, dtype=np.float32)
135
  if x.ndim == 2:
136
  x = x.mean(axis=1)
137
+ return _resample(x, sr)
 
 
 
 
138
 
139
 
140
  def _split(x: np.ndarray) -> List[np.ndarray]:
 
155
  return out
156
 
157
 
158
+ # ---------------------------------------------------------------- model download
159
+ def _cache_dir() -> str:
160
+ return os.environ.get("BANGLA_ASR_CACHE") or os.path.join(os.path.expanduser("~"), ".cache", "bangla-zipformer")
161
+
162
+
163
+ def _fetch(repo_id: str, filename: str, token: str = None, revision: str = "main") -> str:
164
+ """Download one file of a public (or token-authorised) Hugging Face repo with the standard library; cached."""
165
+ dest = os.path.join(_cache_dir(), repo_id.replace("/", "--"), revision, filename)
166
+ if os.path.exists(dest) and os.path.getsize(dest) > 0:
167
+ return dest
168
+ os.makedirs(os.path.dirname(dest), exist_ok=True)
169
+ req = urllib.request.Request(f"https://huggingface.co/{repo_id}/resolve/{revision}/{filename}")
170
+ if token:
171
+ req.add_header("Authorization", f"Bearer {token}")
172
+ tmp = dest + ".part"
173
+ with urllib.request.urlopen(req) as r, open(tmp, "wb") as f:
174
+ total = int(r.headers.get("Content-Length", 0))
175
+ if total > 5_000_000:
176
+ print(f"downloading {filename} ({total / 1e6:.0f} MB) ...", file=sys.stderr)
177
+ got = 0
178
+ while True:
179
+ chunk = r.read(1 << 20)
180
+ if not chunk:
181
+ break
182
+ f.write(chunk)
183
+ got += len(chunk)
184
+ if total and got != total:
185
+ os.remove(tmp)
186
+ raise IOError(f"incomplete download of {filename}: {got} of {total} bytes")
187
+ os.replace(tmp, dest)
188
+ return dest
189
+
190
+
191
+ def _model_dir(repo_id: str, precision: str, token: str = None, revision: str = None) -> str:
192
+ """Local folder holding `<precision>/{encoder,decoder,joiner}.onnx` and `tokens.txt`."""
193
+ if os.path.isdir(repo_id):
194
+ return repo_id
195
+ try: # preferred when installed: huggingface_hub's cache, auth and resume handling
196
+ from huggingface_hub import snapshot_download
197
+
198
+ return snapshot_download(repo_id, allow_patterns=[f"{precision}/*", "tokens.txt"], token=token, revision=revision)
199
+ except ImportError:
200
+ pass
201
+ paths = [_fetch(repo_id, f"{precision}/{n}.onnx", token, revision or "main") for n in ONNX_NAMES]
202
+ _fetch(repo_id, "tokens.txt", token, revision or "main")
203
+ return os.path.dirname(os.path.dirname(paths[0]))
204
+
205
+
206
+ # ---------------------------------------------------------------- the model
207
  class BanglaASR:
208
  def __init__(self, model_dir: str, precision: str = "int8", num_threads: int = 4, beam: int = 4):
209
  import onnxruntime as ort
 
230
  self.tokens[int(idx)] = tok
231
 
232
  @classmethod
233
+ def from_pretrained(cls, repo_id: str = DEFAULT_REPO, precision: str = "int8", num_threads: int = 4,
234
+ beam: int = 4, token: str = None, revision: str = None) -> "BanglaASR":
235
+ """repo_id: a Hugging Face repo name (downloads only the chosen precision, ~70-250 MB) or a local folder."""
236
+ return cls(_model_dir(repo_id, precision, token, revision), precision, num_threads, beam)
 
 
 
 
 
 
237
 
238
  def _greedy(self, enc: np.ndarray) -> List[int]:
239
  """Greedy transducer search (one symbol per frame), enc: (T, joiner_dim)."""
 
297
  x_name, l_name = (i.name for i in self.encoder.get_inputs())
298
  enc, _ = self.encoder.run(None, {x_name: feats, l_name: np.array([feats.shape[1]], dtype=np.int64)})
299
  ids = self._greedy(enc[0]) if decoding == "greedy" else self._beam_search(enc[0], self.beam)
300
+ pieces.append("".join(self.tokens[i] for i in ids).replace("\u2581", " ").strip())
301
  return " ".join(p for p in pieces if p)
302
+
303
+
304
+ if __name__ == "__main__":
305
+ import argparse
306
+
307
+ ap = argparse.ArgumentParser(description="Transcribe Bangla audio with the ONNX Zipformer.")
308
+ ap.add_argument("audio", nargs="+")
309
+ ap.add_argument("--repo", default=DEFAULT_REPO, help="Hugging Face repo name or local folder")
310
+ ap.add_argument("--precision", default="int8", choices=PRECISIONS)
311
+ ap.add_argument("--decoding", default="beam", choices=("beam", "greedy"))
312
+ ap.add_argument("--threads", type=int, default=4)
313
+ a = ap.parse_args()
314
+ model = BanglaASR.from_pretrained(a.repo, precision=a.precision, num_threads=a.threads)
315
+ for f in a.audio:
316
+ print(model.transcribe(f, decoding=a.decoding))