thecollabagepatch commited on
Commit
6b456c1
·
1 Parent(s): b1bc032

save buttons bro

Browse files
Files changed (1) hide show
  1. utils.py +90 -0
utils.py CHANGED
@@ -237,3 +237,93 @@ def wav_bytes_base64(x: np.ndarray, sr: int) -> tuple[str, int, int]:
237
  buf.seek(0)
238
  b64 = base64.b64encode(buf.read()).decode("utf-8")
239
  return b64, int(x.shape[0]), int(x.shape[1])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
237
  buf.seek(0)
238
  b64 = base64.b64encode(buf.read()).decode("utf-8")
239
  return b64, int(x.shape[0]), int(x.shape[1])
240
+
241
+ def _ratio(out_sr: int, in_sr: int) -> tuple[int, int]:
242
+ g = gcd(int(out_sr), int(in_sr))
243
+ return int(out_sr) // g, int(in_sr) // g
244
+
245
+ class StreamingResampler:
246
+ """
247
+ Stateful streaming resampler.
248
+ Prefers soxr (best), then libsamplerate; final fallback is block resample_poly.
249
+ Always pass float32 arrays shaped (S, C).
250
+ """
251
+ def __init__(self, in_sr: int, out_sr: int, channels: int = 2, quality: str = "VHQ"):
252
+ self.in_sr = int(in_sr)
253
+ self.out_sr = int(out_sr)
254
+ self.channels = int(channels)
255
+ self.quality = quality
256
+ self._backend = None
257
+
258
+ # Try soxr first
259
+ try:
260
+ import soxr # pip install soxr
261
+ self._backend = "soxr"
262
+ # dtype float32 keeps things consistent with the rest of your code
263
+ self._rs = soxr.Resampler(
264
+ self.in_sr,
265
+ self.out_sr,
266
+ channels=self.channels,
267
+ dtype="float32",
268
+ quality=self.quality, # "Q", "HQ", "VHQ"
269
+ )
270
+ except Exception:
271
+ # Try libsamplerate
272
+ try:
273
+ import samplerate # pip install samplerate
274
+ self._backend = "samplerate"
275
+ # sinc_best == highest quality; you can choose 'sinc_medium' for speed
276
+ self._rs = samplerate.Resampler(converter_type="sinc_best", channels=self.channels)
277
+ except Exception:
278
+ # Last resort: block resample (not truly streaming)
279
+ from scipy.signal import resample_poly
280
+ self._backend = "scipy"
281
+ self._resample_poly = resample_poly
282
+ self._L, self._M = _ratio(self.out_sr, self.in_sr)
283
+ # Keep a tiny tail to help transitions (still not perfect vs true streaming)
284
+ self._hist = np.zeros((0, self.channels), dtype=np.float32)
285
+
286
+ def process(self, x: np.ndarray, final: bool = False) -> np.ndarray:
287
+ """Feed a chunk (S, C) and get resampled chunk (S', C). Keep calling in order."""
288
+ if x.size == 0 and not final:
289
+ # nothing to do
290
+ return np.zeros((0, self.channels), dtype=np.float32)
291
+
292
+ if self._backend == "soxr":
293
+ return self._rs.process(x, final=final)
294
+
295
+ elif self._backend == "samplerate":
296
+ import samplerate
297
+ ratio = float(self.out_sr) / float(self.in_sr)
298
+ # end_of_input=True flushes tail on the last call
299
+ y = self._rs.process(x, ratio, end_of_input=final)
300
+ # libsamplerate returns (S', C)
301
+ return y.astype(np.float32, copy=False)
302
+
303
+ # --- scipy fallback (block, not truly streaming) ---
304
+ # We concatenate a short history to reduce block edge artifacts
305
+ x_ext = x if self._hist.size == 0 else np.vstack([self._hist, x])
306
+ y = self._resample_poly(x_ext, up=self._L, down=self._M, axis=0).astype(np.float32, copy=False)
307
+
308
+ # Heuristic: drop the portion corresponding roughly to the history to avoid duplicate content
309
+ # (Not perfect, but helps a lot when chunks are reasonably sized.)
310
+ drop = int(round(self._hist.shape[0] * self.out_sr / self.in_sr))
311
+ y = y[drop:] if drop < y.shape[0] else np.zeros((0, self.channels), dtype=np.float32)
312
+
313
+ # Keep a small input tail for the next call (say ~ 4 ms at in_sr)
314
+ tail_samples = max(int(0.004 * self.in_sr), 1)
315
+ self._hist = x[-tail_samples:] if x.shape[0] >= tail_samples else x.copy()
316
+ if final:
317
+ self._hist = np.zeros((0, self.channels), dtype=np.float32)
318
+ return y
319
+
320
+ def flush(self) -> np.ndarray:
321
+ """Drain converter tail (call at stop)."""
322
+ if self._backend == "soxr":
323
+ return self._rs.process(np.zeros((0, self.channels), dtype=np.float32), final=True)
324
+ elif self._backend == "samplerate":
325
+ ratio = float(self.out_sr) / float(self.in_sr)
326
+ return self._rs.process(np.zeros((0, self.channels), dtype=np.float32), ratio, end_of_input=True)
327
+ else:
328
+ # nothing meaningful to flush in scipy fallback
329
+ return np.zeros((0, self.channels), dtype=np.float32)