-
Notifications
You must be signed in to change notification settings - Fork 0
/
gcommand_loader.py
142 lines (119 loc) · 4.76 KB
/
gcommand_loader.py
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
import os
import os.path
import soundfile as sf
import librosa
import numpy as np
import torch
import torch.utils.data as data
AUDIO_EXTENSIONS = [
'.wav', '.WAV',
]
def is_audio_file(filename):
return any(filename.endswith(extension) for extension in AUDIO_EXTENSIONS)
def find_classes(dir):
classes = [d for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d))]
classes.sort()
class_to_idx = {classes[i]: i for i in range(len(classes))}
return classes, class_to_idx
def make_dataset(dir, class_to_idx):
spects = []
dir = os.path.expanduser(dir)
for target in sorted(os.listdir(dir)):
d = os.path.join(dir, target)
if not os.path.isdir(d):
continue
for root, _, fnames in sorted(os.walk(d)):
for fname in sorted(fnames):
if is_audio_file(fname):
path = os.path.join(root, fname)
item = (path, class_to_idx[target])
spects.append(item)
return spects
def spect_loader(path, window_size, window_stride, window, normalize, max_len=101):
y, sr = sf.read(path)
# n_fft = 4096
n_fft = int(sr * window_size)
win_length = n_fft
hop_length = int(sr * window_stride)
# STFT
D = librosa.stft(y, n_fft=n_fft, hop_length=hop_length,
win_length=win_length, window=window)
spect, phase = librosa.magphase(D)
# S = log(S+1)
spect = np.log1p(spect)
# make all spects with the same dims
# TODO: change that in the future
if spect.shape[1] < max_len:
pad = np.zeros((spect.shape[0], max_len - spect.shape[1]))
spect = np.hstack((spect, pad))
elif spect.shape[1] > max_len:
spect = spect[:, :max_len]
spect = np.resize(spect, (1, spect.shape[0], spect.shape[1]))
spect = torch.FloatTensor(spect)
# z-score normalization
if normalize:
mean = spect.mean()
std = spect.std()
if std != 0:
spect.add_(-mean)
spect.div_(std)
return spect
class GCommandLoader(data.Dataset):
"""A google command data set loader where the wavs are arranged in this way: ::
root/one/xxx.wav
root/one/xxy.wav
root/one/xxz.wav
root/head/123.wav
root/head/nsdf3.wav
root/head/asd932_.wav
Args:
root (string): Root directory path.
transform (callable, optional): A function/transform that takes in an PIL image
and returns a transformed version. E.g, ``transforms.RandomCrop``
target_transform (callable, optional): A function/transform that takes in the
target and transforms it.
window_size: window size for the stft, default value is .02
window_stride: window stride for the stft, default value is .01
window_type: typye of window to extract the stft, default value is 'hamming'
normalize: boolean, whether or not to normalize the spect to have zero mean and one std
max_len: the maximum length of frames to use
Attributes:
classes (list): List of the class names.
class_to_idx (dict): Dict with items (class_name, class_index).
spects (list): List of (spects path, class_index) tuples
STFT parameter: window_size, window_stride, window_type, normalize
"""
def __init__(self, root, transform=None, target_transform=None, window_size=.02,
window_stride=.01, window_type='hamming', normalize=True, max_len=101):
classes, class_to_idx = find_classes(root)
spects = make_dataset(root, class_to_idx)
if len(spects) == 0:
raise (RuntimeError("Found 0 sound files in subfolders of: " + root + "Supported audio file extensions are: " + ",".join(AUDIO_EXTENSIONS)))
self.root = root
self.spects = spects
self.classes = classes
self.class_to_idx = class_to_idx
self.transform = transform
self.target_transform = target_transform
self.loader = spect_loader
self.window_size = window_size
self.window_stride = window_stride
self.window_type = window_type
self.normalize = normalize
self.max_len = max_len
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
tuple: (spect, target) where target is class_index of the target class.
"""
path, target = self.spects[index]
spect = self.loader(path, self.window_size, self.window_stride, self.window_type, self.normalize, self.max_len)
if self.transform is not None:
spect = self.transform(spect)
if self.target_transform is not None:
target = self.target_transform(target)
return spect, target
def __len__(self):
return len(self.spects)