Run this model with HF Jobs

Run moonbox-dev/voice-isolator-TensorRT on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs to fine-tune https://huggingface.co/moonbox-dev/voice-isolator-TensorRT. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/moonbox-dev/voice-isolator-TensorRT on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
jennyxue's picture
fp16 build of Inworld Voice Isolator
c7eeb65 verified
Raw History Blame Contribute Delete
4.26 kB
"""Inworld Voice Isolator (offline, 48 kHz) with ONNX Runtime: numpy STFT / iSTFT and chunking around one graph.
from pipeline import VoiceIsolator
iso = VoiceIsolator("fp16") # a folder holding model.onnx (+ model.onnx.data)
voice = iso.isolate(audio) # float32 mono at 48 kHz -> float32 mono at 48 kHz
The graph maps the noisy spectrum to the change the network makes to it:
spec [1, 1025, T, 2] real / imaginary parts of the STFT (n_fft 2048, hop 480, periodic Hann, centred)
change [1, 1025, T, 2] the complex correction (mask delta x spectrum + bounded residual)
and the output is the input plus the iSTFT of the change, exactly as inworld-voice-isolation's
VoiceIsolatorNetwork.forward. Clips longer than 8 s run in 8 s windows overlapping by 2 s with a linear crossfade
(VoiceIsolatorNetwork.enhance). Only numpy and onnxruntime are needed.
"""
from __future__ import annotations
from pathlib import Path
import numpy as np
SR = 48000
N_FFT = 2048
HOP = 480
CHUNK_SECONDS = 8.0
OVERLAP_SECONDS = 2.0
WINDOW = (0.5 - 0.5 * np.cos(2 * np.pi * np.arange(N_FFT) / N_FFT)).astype(np.float32) # torch.hann_window
def stft(x: np.ndarray) -> np.ndarray:
"""torch.stft(x, 2048, 480, window, center=True, return_complex=True) of one clip: [1025, T] complex64."""
pad = N_FFT // 2
x = np.pad(x.astype(np.float32), pad, mode="reflect" if len(x) > pad else "constant")
t = 1 + (len(x) - N_FFT) // HOP
idx = np.arange(N_FFT)[None, :] + HOP * np.arange(t)[:, None]
return np.fft.rfft(x[idx] * WINDOW, axis=-1).T.astype(np.complex64)
def istft(spec: np.ndarray, length: int) -> np.ndarray:
"""torch.istft(spec, 2048, 480, window, center=True, length=length): overlap-add over the squared window."""
frames = np.fft.irfft(spec.T, n=N_FFT, axis=-1).astype(np.float32) * WINDOW
t = frames.shape[0]
n = N_FFT + HOP * (t - 1)
y = np.zeros(n, np.float32)
env = np.zeros(n, np.float32)
w2 = WINDOW * WINDOW
for i in range(t):
y[i * HOP:i * HOP + N_FFT] += frames[i]
env[i * HOP:i * HOP + N_FFT] += w2
start = N_FFT // 2
y = y[start:start + length] / np.maximum(env[start:start + length], 1e-11)
return np.pad(y, (0, length - len(y))) if len(y) < length else y
class VoiceIsolator:
def __init__(self, model_dir: str | Path, providers=None, session_options=None):
import onnxruntime as ort
path = Path(model_dir)
path = path / "model.onnx" if path.is_dir() else path
self.session = ort.InferenceSession(str(path), session_options,
providers=providers or ["CPUExecutionProvider"])
def forward(self, audio: np.ndarray) -> np.ndarray:
"""One window: audio [N] -> isolated voice [N]."""
spec = stft(audio)
ri = np.stack([spec.real, spec.imag], -1)[None].astype(np.float32)
change = self.session.run(None, {"spec": ri})[0][0]
return audio + istft(change[..., 0] + 1j * change[..., 1], len(audio))
def isolate(self, audio: np.ndarray) -> np.ndarray:
"""Any length: 8 s windows overlapping by 2 s, linear crossfades (the original's enhance)."""
audio = np.asarray(audio, np.float32).reshape(-1)
chunk = int(CHUNK_SECONDS * SR)
overlap = min(int(OVERLAP_SECONDS * SR), chunk // 2)
n = len(audio)
if n <= chunk:
return self.forward(audio)
out = np.zeros(n, np.float32)
weight = np.zeros(n, np.float32)
starts = list(range(0, n - chunk, chunk - overlap)) + [n - chunk]
for k, start in enumerate(starts):
end = start + chunk
w = np.ones(chunk, np.float32)
if k > 0:
fade_in = starts[k - 1] + chunk - overlap - start
w[:fade_in] = 0.0
if overlap > 0:
w[fade_in:fade_in + overlap] = np.linspace(0.0, 1.0, overlap, dtype=np.float32)
if overlap > 0 and end < n:
w[-overlap:] = np.linspace(1.0, 0.0, overlap, dtype=np.float32)
out[start:end] += self.forward(audio[start:end]) * w
weight[start:end] += w
return out / np.maximum(weight, 1e-6)