-
Notifications
You must be signed in to change notification settings - Fork 0
/
preprocess.py
203 lines (157 loc) · 6.68 KB
/
preprocess.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
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
199
200
201
202
203
import librosa
import numpy as np
import os
import pickle
class Loader:
# loader is responsible for loading the audio file
def __init__(self, sample_rate, duration, mono):
self.sample_rate = sample_rate
self.duration = duration
self.mono = mono
def load(self, file_path):
signal = librosa.load(file_path,
sr=self.sample_rate,
duration=self.duration,
mono=self.mono)[0]
return signal
class Padder:
# Padder is responsible to apply padding to an array
def __init__(self, mode="constant"):
self.mode = mode
def left_pad(self, array, num_missing_items):
padded_array = np.pad(array,
(num_missing_items, 0),
mode=self.mode)
return padded_array
def right_pad(self, array, num_missing_items):
padded_array = np.pad(array,
(0, num_missing_items),
mode=self.mode)
return padded_array
class LogSpectrogramExtractor:
# LogSpectrogramExtractor extracts log spectrogram (in dB) from a time series signal
def __init__(self, frame_size, hop_length):
self.frame_rate = frame_size
self.hop_length = hop_length
def extract(self, signal):
stft = librosa.stft(signal,
n_fft=self.frame_rate,
hop_length=self.hop_length)[:-1]
spectrogram = np.abs(stft)
log_spectrogram = librosa.amplitude_to_db(spectrogram)
return log_spectrogram
class MinMaxNormaliser:
# MinMaxNormaliser applies min max normalisation to an array
def __init__(self, min_val, max_val):
self.min = min_val
self.max = max_val
def normalise(self, array):
norm_array = (array - array.min()) / (array.max() - array.min())
norm_array = norm_array * (self.max - self.min) + self.min
return norm_array
def denormalise(self, norm_array, original_min, original_max):
array = (norm_array - self.min) / (self.max - self.min)
array = array * (original_max - original_min) + original_min
return array
class Saver:
# Saver is responsible to save features, and the min max values
def __init__(self, feature_save_dir, min_max_values_save_dir):
self.feature_save_dir = feature_save_dir
self.min_max_values_save_dir = min_max_values_save_dir
def save_feature(self, feature, file_path):
save_path = self._generate_save_path(file_path)
# if not (os.path.exists(save_path)):
# os.mkdir(save_path)
with open('save_path', 'wb') as f:
np.save(f, feature, allow_pickle=True)
print("npy file created")
return save_path
# def save_min_max_values(self, min_max_values):
# save_path = os.path.join(self.min_max_values_save_dir, "min_max_values.pkl")
# self._save(min_max_values, save_path)
def save_min_max_values(self, min_max_values):
save_path = os.path.join(self.min_max_values_save_dir, "min_max_values.pkl")
self._save(min_max_values, save_path)
@staticmethod
def _save(data, save_path):
with open(save_path, "wb") as f:
pickle.dump(data, f)
def _generate_save_path(self, file_path):
file_name = os.path.split(file_path)[1]
save_path = os.path.join(self.feature_save_dir, file_name + ".npy")
return save_path
class PreprocessingPipeline:
"""
PreprocessingPipeline processes audio files in a directory,
applying the following to each file
1 - load a file
2 - pad the signal (if necessary)
3 - extracting log spectrogram from signal
4 - normalise spectrogram
5 - save the normalised signal
storing all the min max values for all the log spectrogram
"""
def __init__(self):
self.padder = None
self.extractor = None
self.normaliser = None
self.saver = None
self.min_max_values = {}
self._loader = None
self._num_expected_samples = None
@property
def loader(self):
return self._loader
@loader.setter
def loader(self, loader):
self._loader = loader
self._num_expected_samples = int(self.loader.sample_rate * self.loader.duration)
def process(self, audio_files_directory):
for root, _, files in os.walk(audio_files_directory):
for file in files:
file_path = os.path.join(root, file)
self._process_file(file_path)
print(f"Processed file {file_path}")
self.saver.save_min_max_values(self.min_max_values)
def _process_file(self, file_path):
signal = self.loader.load(file_path)
if self._is_padding_necessary(signal):
signal = self._apply_padding(signal)
feature = self.extractor.extract(signal)
norm_feature = self.normaliser.normalise(feature)
save_path = self.saver.save_feature(norm_feature, file_path)
self._store_min_max_value(save_path, feature.min(), feature.max())
def _is_padding_necessary(self, signal):
if len(signal) < self._num_expected_samples:
return True
return False
def _apply_padding(self, signal):
num_missing_samples = self._num_expected_samples - len(signal)
padded_signal = self.padder.right_pad(signal, num_missing_samples)
return padded_signal
def _store_min_max_value(self, save_path, min_val, max_val):
self.min_max_values[save_path] = {
"min": min_val,
"max": max_val
}
if __name__ == "__main__":
FRAME_SIZE = 512
HOP_LENGTH = 256
DURATION = 0.74 # In seconds
SAMPLE_RATE = 22050
MONO = True
SPECTROGRAM_SAVE_DIR = "data/spectrograms/"
MIN_MAX_VALUES_SAVE_DIR = "data/"
FILES_DIR = "data/audio/"
loader = Loader(SAMPLE_RATE, DURATION, MONO)
padder = Padder()
log_spectrogram_extractor = LogSpectrogramExtractor(FRAME_SIZE, HOP_LENGTH)
min_max_normaliser = MinMaxNormaliser(0, 1)
saver = Saver(SPECTROGRAM_SAVE_DIR, MIN_MAX_VALUES_SAVE_DIR)
preprocessing_pipeline = PreprocessingPipeline()
preprocessing_pipeline.loader = loader
preprocessing_pipeline.padder = padder
preprocessing_pipeline.extractor = log_spectrogram_extractor
preprocessing_pipeline.normaliser = min_max_normaliser
preprocessing_pipeline.saver = saver
preprocessing_pipeline.process(FILES_DIR)