augmentation.py 7.68 KB
Newer Older
Anthony Larcher's avatar
Anthony Larcher committed
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# coding: utf-8 -*-
#
# This file is part of SIDEKIT.
#
# SIDEKIT is a python package for speaker verification.
# Home page: http://www-lium.univ-lemans.fr/sidekit/
#
# SIDEKIT is a python package for speaker verification.
# Home page: http://www-lium.univ-lemans.fr/sidekit/
#
# SIDEKIT is free software: you can redistribute it and/or modify
# it under the terms of the GNU LLesser General Public License as
# published by the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# SIDEKIT is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with SIDEKIT.  If not, see <http://www.gnu.org/licenses/>.

"""
Copyright 2014-2020 Anthony Larcher
"""

import collections
import numpy
import pandas
import random
import soundfile
import threading
import pyroomacoustics


Noise = collections.namedtuple('Noise', 'type file duration')


def normalize(wav):
    """

    :param wav:
    :return:
    """
    return wav / (numpy.sqrt(numpy.mean(wav ** 2)) + 1e-8)


def crop(signal, duration):
    """

    :return:
    """
    start =random.randint(0, signal.shape[0] - duration)
    chunk = signal[start: start + duration]

    return chunk


class AddNoise(object):
    """

    """

    def __init__(self, noise_db_csv, snr_min, snr_max, noise_root_path):
        """

        """
        self.snr_min = snr_min
        self.snr_max = snr_max
        self.noise_root_path = noise_root_path

        df = pandas.read_csv(noise_db_csv)
        self.noises = []
        for index, row in df.iterrows():
            self.noises.append(Noise(type=row["type"], file=row["file_id"], duration=row["duration"]))

    def __call__(self, original, sample_rate):
        """

        :param original:
        :param sample_rate:
        :return:
        """
        original_duration = len(original) / sample_rate

        # accumulate enough noise to cover duration of original waveform
        noises = []
        left = original_duration
        while left > 0:

            # select noise file at random
            file = random.choice(self.noises)
            noise_signal, fs = soundfile.read(self.noise_root_path + "/" + file.file_id + ".wav")
            # Load noise from file
            duration = noise_signal.shape[0] / fs

            # if noise file is longer than what is needed, crop it
            if duration > left:
                noise = crop(noise_signal, duration)
                left = 0

            # otherwise, take the whole file
            else:
                noise = noise_signal
                left -= duration

            # Todo Downsample if needed
            # if sample_rate > fs:
            #

            noise = normalize(noise)
            noises.append(noise)

        # concatenate
        noise = numpy.vstack(noises)

        # select SNR at random
        snr = (self.snr_max - self.snr_min) * numpy.random.random_sample() + self.snr_min
        alpha = numpy.exp(-numpy.log(10) * snr / 20)

        return normalize(original) + alpha * noise


class AddReverb(object):
    """Simulate indoor reverberation

    Parameters
    ----------
    depth : (float, float), optional
        Minimum and maximum values for room depth (in meters).
        Defaults to (2.0, 10.0).
    width : (float, float), optional
        Minimum and maximum values for room width (in meters).
        Defaults to (1.0, 10.0).
    height : (float, float), optional
        Minimum and maximum values for room heigth (in meters).
        Defaults to (2.0, 5.0).
    absorption : (float, float), optional
        Minimum and maximum values of walls absorption coefficient.
        Defaults to (0.2, 0.9).
    noise : str or list of str, optional
        `pyannote.database` collection(s) used for adding noise.
        Defaults to "MUSAN.Collection.BackgroundNoise"
    snr : (float, float), optional
        Minimum and maximum values of signal-to-noise ratio.
        Defaults to (5.0, 15.0)

    """

    def __init__(
        self,
        depth=(2.0, 10.0),
        width=(1.0, 10.0),
        height=(2.0, 5.0),
        absorption=(0.2, 0.9),
        noise=None,
        snr=(5.0, 15.0)
    ):

        super().__init__()
        self.depth = depth
        self.width = width
        self.height = height
        self.absorption = absorption
        self.max_order_ = 17

        self.noise = noise
        self.snr = snr
        self.noise_ = noise

        self.n_rooms_ = 128
        self.new_rooms_prob_ = 0.001
        self.main_lock_ = threading.Lock()
        self.rooms_ = collections.deque(maxlen=self.n_rooms_)
        self.room_lock_ = [threading.Lock() for _ in range(self.n_rooms_)]

    @staticmethod
    def random(m, M):
        """

        :param m:
        :param M:
        :return:
        """
        return (M - m) * numpy.random.random_sample() + m

    def new_room(self, sample_rate: int):
        """

        :param sample_rate:
        :return:
        """
        # generate a room at random
        depth = self.random(*self.depth)
        width = self.random(*self.width)
        height = self.random(*self.height)
        absorption = self.random(*self.absorption)
        room = pyroomacoustics.ShoeBox(
            [depth, width, height],
            fs=sample_rate,
            absorption=absorption,
            max_order=self.max_order_,
        )

        # play the original audio chunk at a random location
        original = [
            self.random(0, depth),
            self.random(0, width),
            self.random(0, height),
        ]
        room.add_source(original)

        # play the noise audio chunk at a random location
        noise = [self.random(0, depth), self.random(0, width), self.random(0, height)]
        room.add_source(noise)

        # place the microphone at a random location
        microphone = [
            self.random(0, depth),
            self.random(0, width),
            self.random(0, height),
        ]
        room.add_microphone_array(
            pyroomacoustics.MicrophoneArray(numpy.c_[microphone, microphone], sample_rate)
        )

        room.compute_rir()

        return room

    def __call__(self, original: numpy.ndarray, sample_rate):

        with self.main_lock_:

            # initialize rooms (with 2 sources and 1 microphone)
            while len(self.rooms_) < self.n_rooms_:
                room = self.new_room(sample_rate)
                self.rooms_.append(room)

            # create new room with probability new_rooms_prob_
            if numpy.random.rand() > 1.0 - self.new_rooms_prob_:
                room = self.new_room(sample_rate)
                self.rooms_.append(room)

            # choose one room at random
            index = numpy.random.choice(self.n_rooms_)

        # lock chosen room to ensure room.sources are not updated concurrently
        with self.room_lock_[index]:

            room = self.rooms_[index]

            # play normalized original audio chunk at source #1
            n_samples = len(original)
            original = normalize(original).squeeze()
            room.sources[0].add_signal(original)

            # generate noise with random SNR
            noise = self.noise_(n_samples, sample_rate).squeeze()
            snr = self.random(*self.snr)
            alpha = numpy.exp(-numpy.log(10) * snr / 20)
            noise *= alpha

            # play noise at source #2
            room.sources[1].add_signal(noise)

            # simulate room and return microphone signal
            room.simulate()
            return room.mic_array.signals[0, :n_samples, numpy.newaxis]