File size: 1,740 Bytes
f730521
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Random fixed-length crops of the built dialogues: stereo audio (caller, agent) and
one label per 80 ms frame. Used by both trainers."""
import json
from pathlib import Path

import numpy as np
import torch
from torch.utils.data import IterableDataset, get_worker_info

from duplex.spec import FRAME, read_wav


class Crops(IterableDataset):
    def __init__(self, root, split, crop_frames, seed=0, limit=None):
        self.root, self.crop, self.seed, self.limit = Path(root), crop_frames, seed, limit
        self.items = json.loads((self.root / f"index_{split}.json").read_text())
        assert self.items, f"no dialogues in split {split}"

    def __iter__(self):
        info = get_worker_info()
        rng = np.random.default_rng([self.seed, info.id if info else 0])
        length = np.array([it["n_frames"] for it in self.items], dtype=np.float64)
        p = length / length.sum()
        count = 0
        while self.limit is None or count < self.limit:
            it = self.items[int(rng.choice(len(self.items), p=p))]
            start = int(rng.integers(0, max(1, it["n_frames"] - self.crop + 1)))
            wav, _ = read_wav(self.root / "audio" / f"{it['id']}.wav", start * FRAME, self.crop * FRAME)
            labels = np.load(self.root / "labels" / f"{it['id']}.npy")[start:start + self.crop].astype(np.int64)
            if wav.shape[0] < self.crop * FRAME:      # dialogue shorter than the crop: pad, and ignore padded frames
                wav = np.pad(wav, ((0, self.crop * FRAME - wav.shape[0]), (0, 0)))
                labels = np.pad(labels, (0, self.crop - len(labels)), constant_values=-100)
            yield torch.from_numpy(np.ascontiguousarray(wav.T)), torch.from_numpy(labels)
            count += 1