thucdangvan020999's picture
Initial upload: releases, checkpoints, code, docs
a1fe2e2 verified
Raw History Blame Contribute Delete
7.59 kB
"""Waveform augmentation, applied per sample inside the data-loader workers.
Order: speed -> reverb -> channel EQ -> gain -> additive noise -> babble -> noise floor -> clipping.
Every step has a probability, so a share of the training data stays clean.
"""
from __future__ import annotations
from dataclasses import dataclass, field
import numpy as np
from scipy.signal import butter, fftconvolve, sosfilt
from vitakws.data import audio
@dataclass
class AugmentConfig:
enabled: bool = True
speed_prob: float = 0.3
speed_range: tuple[float, float] = (0.9, 1.1)
gain_db: tuple[float, float] = (-12.0, 6.0)
rir_prob: float = 0.3
noise_prob: float = 0.8
snr_db: tuple[float, float] = (0.0, 25.0)
# Faint noise under every clip so digital silence never becomes a cue.
floor_dbfs: tuple[float, float] = (-70.0, -50.0)
clip_prob: float = 0.05
clip_range: tuple[float, float] = (0.3, 0.8)
noise_dirs: list[str] = field(default_factory=list)
rir_dirs: list[str] = field(default_factory=list)
babble_prob: float = 0.0
babble_snr_db: tuple[float, float] = (5.0, 20.0)
eq_prob: float = 0.0
eq_highpass_hz: tuple[float, float] = (80.0, 400.0)
eq_lowpass_hz: tuple[float, float] = (3000.0, 7500.0)
def speed_perturb(wave: np.ndarray, factor: float, sample_rate: int) -> np.ndarray:
"""Play ``factor`` times faster (changes pitch too, like Kaldi speed perturbation)."""
if abs(factor - 1.0) < 1e-3:
return wave
return audio.resample(wave, int(round(sample_rate * factor)), sample_rate)
def fit_length(wave: np.ndarray, length: int, rng: np.random.Generator | None = None) -> np.ndarray:
"""Crop or zero-pad to ``length``; random position when ``rng`` is given."""
n = len(wave)
if n == length:
return wave
if n > length:
start = int(rng.integers(0, n - length + 1)) if rng is not None else (n - length) // 2
return wave[start : start + length]
out = np.zeros(length, dtype=np.float32)
start = int(rng.integers(0, length - n + 1)) if rng is not None else (length - n) // 2
out[start : start + n] = wave
return out
def add_reverb(wave: np.ndarray, rir: np.ndarray) -> np.ndarray:
"""Convolve with a room impulse response, keeping length, alignment and level."""
if len(rir) == 0 or not np.any(rir):
return wave
peak = int(np.argmax(np.abs(rir)))
out = fftconvolve(wave, rir)[peak : peak + len(wave)]
before, after = audio.rms(wave), audio.rms(out)
if after > 0:
out = out * (before / after)
return out.astype(np.float32)
def mix_at_snr(wave: np.ndarray, noise: np.ndarray, snr_db: float) -> np.ndarray:
"""Add ``noise`` scaled so that speech-to-noise ratio is ``snr_db``.
When the clip is silent (nothing to measure against) the noise is added as is.
"""
signal_rms, noise_rms = audio.rms(wave), audio.rms(noise)
if noise_rms <= 0:
return wave
if signal_rms <= 1e-6:
return (wave + noise).astype(np.float32)
scale = signal_rms / (noise_rms * 10.0 ** (snr_db / 20.0))
return (wave + noise * scale).astype(np.float32)
def coloured_noise(length: int, rng: np.random.Generator, tilt: float) -> np.ndarray:
"""Unit-RMS noise with spectrum ~ 1/f**tilt (0 white, 1 pink, 2 brown)."""
spectrum = np.fft.rfft(rng.standard_normal(length))
freqs = np.arange(len(spectrum), dtype=np.float64)
freqs[0] = 1.0
noise = np.fft.irfft(spectrum / freqs ** (tilt / 2.0), n=length)
return (noise / max(np.sqrt(np.mean(noise**2)), 1e-12)).astype(np.float32)
def band_limit(
wave: np.ndarray,
sample_rate: int,
rng: np.random.Generator,
highpass_hz: tuple[float, float],
lowpass_hz: tuple[float, float],
) -> np.ndarray:
"""Random high-pass and/or low-pass, like a phone or a cheap microphone."""
nyq = sample_rate / 2.0
choice = rng.random()
if choice < 0.67: # high-pass (alone or with low-pass)
fc = float(rng.uniform(*highpass_hz))
wave = sosfilt(butter(int(rng.integers(1, 5)), fc / nyq, "highpass", output="sos"), wave)
if choice > 0.33: # low-pass (alone or with high-pass)
fc = min(float(rng.uniform(*lowpass_hz)), nyq * 0.95)
wave = sosfilt(butter(int(rng.integers(2, 7)), fc / nyq, "lowpass", output="sos"), wave)
return np.asarray(wave, dtype=np.float32)
class Augmenter:
def __init__(
self,
cfg: AugmentConfig,
sample_rate: int,
noise_files: list[str] | None = None,
babble_files: list[str] | None = None,
):
self.cfg = cfg
self.sample_rate = sample_rate
self.noise_files = list(noise_files or [])
self.babble_files = list(babble_files or [])
for d in cfg.noise_dirs:
self.noise_files += [str(p) for p in audio.list_audio(d)]
self.rir_files: list[str] = []
for d in cfg.rir_dirs:
self.rir_files += [str(p) for p in audio.list_audio(d)]
def random_speed(self, rng: np.random.Generator) -> float:
if not self.cfg.enabled or rng.random() >= self.cfg.speed_prob:
return 1.0
return float(rng.uniform(*self.cfg.speed_range))
def _noise_clip(
self, length: int, rng: np.random.Generator, files: list[str] | None = None
) -> np.ndarray:
files = self.noise_files if files is None else files
if not files:
return coloured_noise(length, rng, tilt=float(rng.uniform(0.0, 2.0)))
path = files[int(rng.integers(len(files)))]
sr, frames = audio.info(path)
need = length / self.sample_rate
start = float(rng.uniform(0.0, max(0.0, frames / sr - need)))
clip = audio.load(path, self.sample_rate, start=start, duration=need)
if len(clip) < length:
clip = np.tile(clip, int(np.ceil(length / max(len(clip), 1))))[:length]
return clip[:length]
def __call__(self, wave: np.ndarray, rng: np.random.Generator, is_background: bool = False):
"""Augment one fixed-length training window."""
cfg = self.cfg
length = len(wave)
if cfg.enabled:
if self.rir_files and rng.random() < cfg.rir_prob:
rir = audio.load(
self.rir_files[int(rng.integers(len(self.rir_files)))], self.sample_rate
)
wave = add_reverb(wave, rir)
if rng.random() < cfg.eq_prob:
wave = band_limit(wave, self.sample_rate, rng, cfg.eq_highpass_hz, cfg.eq_lowpass_hz)
wave = wave * 10.0 ** (float(rng.uniform(*cfg.gain_db)) / 20.0)
# Background clips are already noise; mixing more adds nothing.
if not is_background and rng.random() < cfg.noise_prob:
wave = mix_at_snr(
wave, self._noise_clip(length, rng), float(rng.uniform(*cfg.snr_db))
)
if not is_background and self.babble_files and rng.random() < cfg.babble_prob:
babble = self._noise_clip(length, rng, self.babble_files)
wave = mix_at_snr(wave, babble, float(rng.uniform(*cfg.babble_snr_db)))
floor = 10.0 ** (float(rng.uniform(*cfg.floor_dbfs)) / 20.0)
wave = wave + floor * coloured_noise(length, rng, tilt=float(rng.uniform(0.0, 1.5)))
if cfg.enabled and rng.random() < cfg.clip_prob:
limit = float(rng.uniform(*cfg.clip_range)) * max(float(np.abs(wave).max()), 1e-6)
wave = np.clip(wave, -limit, limit)
return np.clip(wave, -1.0, 1.0).astype(np.float32)