File size: 7,592 Bytes
a1fe2e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
"""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)