File size: 8,397 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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
"""Fixed-window dataset and the kind-balanced sampler."""

from __future__ import annotations

from collections import Counter

import numpy as np
import torch
from torch.utils.data import Dataset, WeightedRandomSampler

from vitakws.data import audio
from vitakws.data.augment import Augmenter, fit_length, speed_perturb
from vitakws.data.manifest import KEYWORD_KIND, Item, LabelMap

# Seconds of audio kept after the keyword ends. Training randomises it so the
# model fires anywhere in this range; evaluation uses the middle.
TRAIL_RANGE = (0.05, 0.40)
TRAIL_EVAL = 0.20


def place_keyword(
    wave: np.ndarray,
    kw_end: int,
    window: int,
    trail: int,
) -> np.ndarray:
    """Cut a window that ends ``trail`` samples after the keyword, zero-padding outside the clip.

    Aligning on the keyword end mirrors streaming use: the detector sees the
    keyword slide in from the right and must fire shortly after it finishes.
    Whatever follows in the clip (a command spoken right after) stays in the window.
    """
    end = kw_end + trail
    start = end - window
    out = np.zeros(window, dtype=np.float32)
    src_lo, src_hi = max(start, 0), min(end, len(wave))
    if src_hi > src_lo:
        out[src_lo - start : src_hi - start] = wave[src_lo:src_hi]
    return out


class KwsDataset(Dataset):
    """Returns (waveform [window], class index, item index)."""

    def __init__(
        self,
        items: list[Item],
        label_map: LabelMap,
        sample_rate: int,
        window_seconds: float,
        augmenter: Augmenter | None = None,
        train: bool = False,
        seed: int = 0,
        align_short_negatives: float = 0.0,
        context_files: list[str] | None = None,
        context_prob: float = 0.0,
        context_gap_s: tuple[float, float] = (0.0, 0.3),
        context_gain_db: tuple[float, float] = (-10.0, 3.0),
        trail_range: tuple[float, float] = TRAIL_RANGE,
    ):
        self.items = items
        self.label_map = label_map
        self.sample_rate = sample_rate
        self.window = int(round(window_seconds * sample_rate))
        self.augmenter = augmenter
        self.train = train
        self.seed = seed
        self.align_short_negatives = align_short_negatives
        self.context_files = context_files or []
        self.context_prob = context_prob
        self.context_gap_s = context_gap_s
        self.context_gain_db = context_gain_db
        # A negative lower bound also trains on keywords cut before their end (fire earlier).
        self.trail_range = tuple(trail_range)
        self.targets = [label_map.index(i.label) for i in items]
        self._rng: np.random.Generator | None = None

    def __len__(self) -> int:
        return len(self.items)

    def _rng_for(self, index: int) -> np.random.Generator:
        if not self.train:
            return np.random.default_rng([self.seed, index])
        if self._rng is None:
            info = torch.utils.data.get_worker_info()
            # torch reseeds every worker each epoch, so this differs per worker and epoch.
            base = info.seed if info is not None else int(torch.randint(0, 2**31, (1,)))
            self._rng = np.random.default_rng([self.seed, base])
        return self._rng

    def _load_keyword(self, item: Item, rng: np.random.Generator) -> np.ndarray:
        sr = self.sample_rate
        wave = audio.load(item.audio, sr)
        kw_end = len(wave) if item.kw_end is None else int(round(item.kw_end * sr))
        if self.train and self.augmenter is not None:
            factor = self.augmenter.random_speed(rng)
            if factor != 1.0:
                wave = speed_perturb(wave, factor, sr)
                kw_end = int(round(kw_end / factor))
        trail = rng.uniform(*self.trail_range) if self.train else TRAIL_EVAL
        kw_end = min(kw_end, len(wave))
        out = place_keyword(wave, kw_end, self.window, int(round(trail * sr)))
        if self.train and self.context_files and rng.random() < self.context_prob:
            self._add_context(out, wave, kw_end, int(round(trail * sr)), rng)
        return out

    def _add_context(self, out: np.ndarray, wave: np.ndarray, kw_end: int, trail: int,
                     rng: np.random.Generator) -> None:
        """Put other speech in the zero padding before the clip starts, in place."""
        sr = self.sample_rate
        lead = self.window - (kw_end + trail) - int(round(rng.uniform(*self.context_gap_s) * sr))
        if lead < int(0.15 * sr):
            return
        path = self.context_files[int(rng.integers(len(self.context_files)))]
        file_sr, frames = audio.info(path)
        total = frames / file_sr
        start = float(rng.uniform(0.0, max(total - lead / sr, 0.0)))
        ctx = audio.load(path, sr, start=start, duration=min(lead / sr, total))[:lead]
        ref = np.sqrt(np.mean(wave**2) + 1e-10)
        rms = np.sqrt(np.mean(ctx**2) + 1e-10)
        if rms < 1e-4:
            return
        ctx = ctx * (ref / rms) * 10 ** (rng.uniform(*self.context_gain_db) / 20)
        out[lead - len(ctx) : lead] += ctx.astype(np.float32)

    def _load_negative(self, item: Item, rng: np.random.Generator) -> np.ndarray:
        sr = self.sample_rate
        file_sr, frames = audio.info(item.audio)
        total = frames / file_sr
        factor = self.augmenter.random_speed(rng) if self.train and self.augmenter else 1.0
        need = self.window / sr * factor
        if total > need:
            start = float(rng.uniform(0.0, total - need)) if self.train else (total - need) / 2.0
            wave = audio.load(item.audio, sr, start=start, duration=need)
        else:
            wave = audio.load(item.audio, sr)
        wave = speed_perturb(wave, factor, sr)
        # A near-miss phrase sliding through the detector passes the exact position
        # keyword clips are trained at (ending just before the window's right edge).
        # Placing short negatives there too stops position from telling the classes apart.
        if len(wave) < self.window and self.align_short_negatives > 0:
            if not self.train:
                return place_keyword(wave, len(wave), self.window, int(round(TRAIL_EVAL * sr)))
            if rng.random() < self.align_short_negatives:
                trail = int(round(rng.uniform(*self.trail_range) * sr))
                return place_keyword(wave, len(wave), self.window, trail)
        return fit_length(wave, self.window, rng if self.train else None)

    def __getitem__(self, index: int):
        item = self.items[index]
        rng = self._rng_for(index)
        if item.kind == KEYWORD_KIND:
            wave = self._load_keyword(item, rng)
        else:
            wave = self._load_negative(item, rng)
        if self.augmenter is not None:
            wave = self.augmenter(wave, rng, is_background=item.kind == "background")
        return torch.from_numpy(wave), self.targets[index], index


def balanced_sampler(
    items: list[Item],
    kind_ratios: dict[str, float],
    num_samples: int,
    window_seconds: float,
    max_windows: float = 50.0,
    generator: torch.Generator | None = None,
) -> WeightedRandomSampler:
    """Draw kinds at fixed ratios regardless of how many files each kind has.

    Inside a kind, a file is weighted by how many windows it holds (capped), so
    an hour-long negative recording is not sampled as rarely as a one-second clip.
    An optional per-item ``sample_weight`` manifest field scales that weight.
    """
    present = Counter(i.kind for i in items)
    ratios = {k: v for k, v in kind_ratios.items() if v > 0 and present.get(k, 0) > 0}
    if not ratios:
        raise ValueError(
            f"kind_ratios {kind_ratios} selects nothing; kinds in the data: {dict(present)}"
        )
    total_ratio = sum(ratios.values())
    raw = np.array(
        [
            min(max(i.duration / window_seconds, 1.0), max_windows)
            * float(i.extra.get("sample_weight", 1.0))
            if i.kind in ratios
            else 0.0
            for i in items
        ]
    )
    weights = np.zeros(len(items))
    for kind, ratio in ratios.items():
        mask = np.array([i.kind == kind for i in items])
        weights[mask] = raw[mask] / raw[mask].sum() * ratio / total_ratio
    return WeightedRandomSampler(
        torch.from_numpy(weights), num_samples=num_samples, replacement=True, generator=generator
    )