File size: 25,057 Bytes
0b2d8e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
"""
Module: transforms.py
Authors: Christian Bergler, Hendrik Schroeter
GNU General Public License v3.0
Institution: Friedrich-Alexander-University Erlangen-Nuremberg, Department of Computer Science, Pattern Recognition Lab
Last Access: 27.12.2022
"""

import io
import os
import sys
import math
import resampy
import numpy as np
import scipy.fftpack
import soundfile as sf

import torch
import torch.nn.functional as F

from typing import List
from multiprocessing import Lock
from utils.FileIO import AsyncFileReader, AsyncFileWriter

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

""" Load audio file  """
def load_audio_file(file_name, sr=None, mono=True):
    y, sr_orig = sf.read(file_name, always_2d=True, dtype="float32")
    if mono and y.ndim == 2 and y.shape[1] > 1:
        y = np.mean(y, axis=1, keepdims=True)
    if sr is not None and sr != sr_orig:
        y = resampy.resample(y, sr_orig, sr, axis=0, filter="kaiser_best")
    return torch.from_numpy(y).float().t()

"""Composes several transforms to one."""
class Compose(object):

    def __init__(self, *transforms):
        if len(transforms) == 1 and isinstance(transforms[0], list):
            self.transforms = transforms[0]
        else:
            self.transforms = transforms

    def __call__(self, x):
        for t in self.transforms:
            x = t(x)
        return x

"""Unsqueezes the given tensor at dim=0."""
class SqueezeDim0(object):

    def __call__(self, x):
        return x.squeeze(dim=0)


"""Unsqueezes the given tensor at dim=0."""
class UnsqueezeDim0(object):

    def __call__(self, x):
        return x.unsqueeze(dim=0)


"""Converts a given numpy array to torch.FloatTensor."""
class ToFloatTensor(object):

    def __call__(self, x):
        if isinstance(x, np.ndarray):
            return torch.from_numpy(x).float()
        elif isinstance(x, torch.Tensor):
            return x.float()
        else:
            raise ValueError("Unknown input array type: {}".format(type(x)))

"""Converts a given numpy array to torch.FloatTensor."""
class ToFloatNumpy(object):

    def __call__(self, x):
        if isinstance(x, np.ndarray):
            return x.astype("float32")
        elif isinstance(x, torch.Tensor):
            return x.float().numpy()
        else:
            raise ValueError("Unknown input array type: {}".format(type(x)))

"""Pre-Emphasize in order to raise higher frequencies and lower low frequencies."""
class PreEmphasize(object):
    def __init__(self, factor=0.97):
        self.factor = factor

    def __call__(self, y):
        if y.dim() != 2:
            raise ValueError(
                "PreEmphasize expects a 2 dimensional signal of size (c, n), "
                "but got size: {}.".format(y.size())
            )
        return torch.cat(
            (y[:, 0].unsqueeze(dim=-1), y[:, 1:] - self.factor * y[:, :-1]), dim=-1
        )

"""Converts a given audio to a spectrogram."""
class Spectrogram(object):


    def __init__(self, n_fft, hop_length, center=True):
        self.n_fft = n_fft
        self.hop_length = hop_length
        self.center = center
        self.window = torch.hann_window(self.n_fft)

    def __call__(self, y):
        if y.dim() != 2:
            raise ValueError(
                "Spectrogram expects a 2 dimensional signal of size (c, n), "
                "but got size: {}.".format(y.size())
            )
        S = torch.stft(
            input=y,
            n_fft=self.n_fft,
            hop_length=self.hop_length,
            window=self.window,
            center=self.center,
            onesided=True,
            return_complex=False
        ).transpose(1, 2)
        S /= self.window.pow(2).sum().sqrt()
        S = S.pow(2).sum(-1)
        return S


"""Converts a given audio to a spectrogram, cache and store the spectrograms."""
class CachedSpectrogram(object):
    version = 4

    def __init__(
        self, cache_dir, spec_transform, file_reader=None, file_writer=None, **meta
    ):
        os.makedirs(cache_dir, exist_ok=True)
        self.cache_dir = cache_dir
        if file_reader is not None:
            self.reader = file_reader
        else:
            self.reader = AsyncFileReader(n_readers=1)
        self.transform = spec_transform
        self.meta = meta
        if file_writer is not None:
            self.writer = file_writer
        else:
            self.writer = AsyncFileWriter(write_fn=self._write_fn, n_writers=1)

    def get_cached_name(self, file_name):
        cached_spec_n = os.path.splitext(os.path.basename(file_name))[0] + ".spec"
        dir_structure = os.path.dirname(file_name).replace(r"/", "_") + "_"
        cached_spec_n = dir_structure + cached_spec_n
        if not os.path.isabs(cached_spec_n):
            cached_spec_n = os.path.join(self.cache_dir, cached_spec_n)
        return cached_spec_n

    def __call__(self, fn):
        cached_spec_n = self.get_cached_name(fn)
        if not os.path.isfile(cached_spec_n):
            return self._compute_and_cache(fn)
        try:
            data = self.reader(cached_spec_n)
            spec_dict = torch.load(io.BytesIO(data), map_location="cpu")
        except (EOFError, RuntimeError):
            return self._compute_and_cache(fn)
        if not (
            "v" in spec_dict
            and spec_dict["v"] == self.version
            and "data" in spec_dict
            and spec_dict["data"].dim() == 3
        ):
            return self._compute_and_cache(fn)
        for key, value in self.meta.items():
            if not (key in spec_dict and spec_dict[key] == value):
                return self._compute_and_cache(fn)
        return spec_dict["data"]

    def _compute_and_cache(self, fn):
        try:
            audio_data = self.reader(fn)
            spec = self.transform(io.BytesIO(audio_data))
        except Exception:
            spec = self.transform(fn)
        self.writer(self.get_cached_name(fn), spec)
        return spec

    def _write_fn(self, fn, data):
        spec_dict = {"v": self.version, "data": data}
        for key, value in self.meta.items():
            spec_dict[key] = value
        torch.save(spec_dict, fn)


"""Normalize a spectrogram by subtracting mean and dividing by std."""
class MeanStdNormalize(object):

    def __call__(self, spectrogram, ret_dict=None):
        mean = spectrogram.mean()
        spectrogram.sub_(mean)
        std = spectrogram.std()
        spectrogram.div_(std)
        if ret_dict is not None:
            ret_dict["mean"] = mean
            ret_dict["std"] = std
        return spectrogram

"""dB-Normalize db scale to 0..1"""
class Normalize(object):

    def __init__(self, min_level_db=-100, ref_level_db=20):
        self.min_level_db = min_level_db
        self.ref_level_db = ref_level_db

    def __call__(self, spec):
        return torch.clamp(
            (spec - self.ref_level_db - self.min_level_db) / -self.min_level_db, 0, 1
        )

"""Normalize min/max scale to 0..1"""
class MinMaxNormalize(object):

    def __call__(self, spectrogram):
        spectrogram -= spectrogram.min()
        if spectrogram.max().item() == 0.0:
            return spectrogram
        spectrogram /= spectrogram.max()
        return spectrogram

"""Turns a spectrogram from the power/amplitude scale to the decibel scale.

Code from https://github.com/pytorch/audio/blob/5787787edc/torchaudio/transforms.py

BSD 2-Clause License

Copyright (c) 2017 Facebook Inc. (Soumith Chintala), 
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Access Data: 12.09.2018, Last Access Date: 21.12.2021

Changes: Modified by Christian Bergler and Hendrik Schroeter (12.09.2018)
"""
class Amp2Db(object):

    def __init__(self, min_level_db=None, stype="power"):
        self.stype = stype
        self.multiplier = 10. if stype == "power" else 20.
        if min_level_db is None:
            self.min_level = None
        else:
            min_level_db = -min_level_db if min_level_db > 0 else min_level_db
            self.min_level = torch.tensor(
                np.exp(min_level_db / self.multiplier * np.log(10))
            )

    def __call__(self, spec):
        if self.min_level is not None:
            spec_ = torch.max(spec, self.min_level)
        else:
            spec_ = spec
        spec_db = self.multiplier * torch.log10(spec_)
        return spec_db

"""Compress a spectrogram using torch.log1p(spec * compression_factor)."""
class SPECLOG1P(object):

    def __init__(self, compression_factor=1):
        self.compression_factor = compression_factor

    def __call__(self, spectrogram):
        return torch.log1p(spectrogram * self.compression_factor)

"""Compress a spectrogram using torch.log1p(spec * compression_factor)."""
class SPECEXPM1(object):

    def __init__(self, decompression_factor=1):
        self.decompression_factor = decompression_factor

    def __call__(self, spectrogram):
        return torch.expm1(spectrogram) / self.decompression_factor

"""Scaling spectrogram dimension (time/frequency) by a given factor."""
def _scale(spectrogram: torch.Tensor, shift_factor: float, dim: int):
    in_dim = spectrogram.dim()
    if in_dim < 3:
        raise ValueError(
            "Expected spectrogram with size (c t f) or (n c t f)"
            ", but got {}".format(spectrogram.size())
        )
    if in_dim == 3:
        spectrogram.unsqueeze_(dim=0)
    size = list(spectrogram.shape)[2:]
    dim -= 1
    size[dim] = int(round(size[dim] * shift_factor))
    spectrogram = F.interpolate(spectrogram, size=size, mode="nearest")
    if in_dim == 3:
        spectrogram.squeeze_(dim=0)
    return spectrogram


"""Randomly shifts the pitch of a spectrogram by a factor of 2**Uniform(log2(from), log2(to))."""
class RandomPitchSift(object):

    def __init__(self, from_=0.5, to_=1.5):
        self.from_ = math.log2(from_)
        self.to_ = math.log2(to_)

    def __call__(self, spectrogram: torch.Tensor):
        factor = 2 ** torch.empty((1,)).uniform_(self.from_, self.to_).item()
        median = spectrogram.median()
        size = list(spectrogram.shape)
        scaled = _scale(spectrogram, factor, dim=2)
        if factor > 1:
            out = scaled[:, :, : size[2]]
        else:
            out = torch.full(size, fill_value=median, dtype=spectrogram.dtype)
            new_f_bins = int(round(size[2] * factor))
            out[:, :, 0:new_f_bins] = scaled
        return out

"""Randomly stretches the time of a spectrogram by a factor of 2**Uniform(log2(from), log2(to))."""
class RandomTimeStretch(object):

    def __init__(self, from_=0.5, to_=2):
        self.from_ = math.log2(from_)
        self.to_ = math.log2(to_)

    def __call__(self, spectrogram: torch.Tensor):
        factor = 2 ** torch.empty((1,)).uniform_(self.from_, self.to_).item()
        return _scale(spectrogram, factor, dim=1)

"""Randomly scaling (uniform distributed) the amplitude based on a given input spectrogram (intensity augmenation)."""
class RandomAmplitude(object):
    def __init__(self, increase_db=3, decrease_db=None):
        self.inc_db = increase_db
        if decrease_db is None:
            decrease_db = -increase_db
        elif decrease_db > 0:
            decrease_db *= -1
        self.dec_db = decrease_db

    def __call__(self, spec):
        db_change = torch.randint(
            self.dec_db, self.inc_db, size=(1,), dtype=torch.float
        )
        return spec.mul(10 ** (db_change / 10))

""" 
Randomly adds a given noise file to the given spectrogram by considering a randomly selected
(uniform distributed) SNR of min = -3 dB and max = 12 dB. The noise file could also be intensity, pitch, and/or time
augmented. If a noise file is longer/shorter than the given spectrogram it will be subsampled/self-concatenated. 
The spectrogram is expected to be a power spectrogram, which is **not** logarithmically compressed.
"""
class RandomAddNoise(object):

    def __init__(
        self,
        noise_files: List[str],
        spectrogram_transform,
        transform,
        min_length=0,
        min_snr=12,
        max_snr=-3,
        return_original=False,
    ):
        if not noise_files:
            raise ValueError("No noise files found")
        self.noise_files = noise_files
        self.t_spectrogram = spectrogram_transform
        self.noise_file_locks = {file: Lock() for file in noise_files}
        self.transform = transform
        self.min_length = min_length
        self.t_pad = PaddedSubsequenceSampler(sequence_length=min_length, dim=1)
        self.min_snr = min_snr if min_snr > max_snr else max_snr
        self.max_snr = max_snr if min_snr > max_snr else min_snr
        self.return_original = return_original

    def __call__(self, spectrogram):
        if len(self.noise_files) == 1:
            idx = 0
        else:
            idx = torch.randint(
                0, len(self.noise_files) - 1, size=(1,), dtype=torch.long
            ).item()
        noise_file = self.noise_files[idx]

        try:
            if not self.noise_file_locks[noise_file].acquire(timeout=10):
                print("Warning: Could not acquire lock for {}".format(noise_file))
                return spectrogram
            noise_spec = self.t_spectrogram(noise_file)
        except Exception:
            import traceback

            print(traceback.format_exc())
            return spectrogram
        finally:
            self.noise_file_locks[noise_file].release()

        noise_spec = self.t_pad._maybe_sample_subsequence(
            noise_spec, spectrogram.size(1) * 2
        )
        noise_spec = self.transform(noise_spec)

        if self.min_length > 0:
            spectrogram = self.t_pad._maybe_pad(spectrogram)

        if spectrogram.size(1) > noise_spec.size(1):
            n_repeat = int(math.ceil(spectrogram.size(1) / noise_spec.size(1)))
            noise_spec = noise_spec.repeat(1, n_repeat, 1)
        if spectrogram.size(1) < noise_spec.size(1):
            high = noise_spec.size(1) - spectrogram.size(1)
            start = torch.randint(0, high, size=(1,), dtype=torch.long)
            end = start + spectrogram.size(1)
            noise_spec_part = noise_spec[:, start:end]
        else:
            noise_spec_part = noise_spec

        snr = torch.randint(self.max_snr, self.min_snr, size=(1,), dtype=torch.float)
        signal_power = spectrogram.sum()
        noise_power = noise_spec_part.sum()

        K = (signal_power / noise_power) * 10 ** (-snr / 10)
        spectrogram_aug = spectrogram + noise_spec_part * K

        if self.return_original:
            return spectrogram_aug, spectrogram
        return spectrogram_aug

"""Samples a subsequence along one axis and pads if necessary."""
class PaddedSubsequenceSampler(object):

    def __init__(self, sequence_length: int, dim: int = 0, random=True):
        assert isinstance(sequence_length, int)
        assert isinstance(dim, int)
        self.sequence_length = sequence_length
        self.dim = dim
        if random:
            self._sampler = lambda x: torch.randint(
                0, x, size=(1,), dtype=torch.long
            ).item()
        else:
            self._sampler = lambda x: x // 2

    def _maybe_sample_subsequence(self, spectrogram, sequence_length=None):
        if sequence_length is None:
            sequence_length = self.sequence_length
        sample_length = spectrogram.shape[self.dim]
        if sample_length > sequence_length:
            start = self._sampler(sample_length - sequence_length)
            end = start + sequence_length
            indices = torch.arange(start, end, dtype=torch.long)
            return torch.index_select(spectrogram, self.dim, indices)
        return spectrogram

    def _maybe_pad(self, spectrogram, sequence_length=None):
        if sequence_length is None:
            sequence_length = self.sequence_length
        sample_length = spectrogram.shape[self.dim]
        if sample_length < sequence_length:
            start = self._sampler(sequence_length - sample_length)
            end = start + sample_length

            shape = list(spectrogram.shape)
            shape[self.dim] = sequence_length
            padded_spectrogram = torch.zeros(shape, dtype=spectrogram.dtype)

            if self.dim == 0:
                padded_spectrogram[start:end] = spectrogram
            elif self.dim == 1:
                padded_spectrogram[:, start:end] = spectrogram
            elif self.dim == 2:
                padded_spectrogram[:, :, start:end] = spectrogram
            elif self.dim == 3:
                padded_spectrogram[:, :, :, start:end] = spectrogram
            return padded_spectrogram
        return spectrogram

    def __call__(self, spectrogram):
        spectrogram = self._maybe_pad(spectrogram)
        spectrogram = self._maybe_sample_subsequence(spectrogram)
        return spectrogram

"""Frequency compression of a given frequency range into a chosen number of frequency bins."""
class Interpolate(object):
    def __init__(self, n_freqs, sr=None, f_min=0, f_max=None):
        self.n_freqs = n_freqs
        self.sr = sr
        self.f_min = f_min
        self.f_max = f_max

    def __call__(self, spec):
        n_fft = (spec.size(2) - 1) * 2

        if self.sr is not None and n_fft is not None:
            min_bin = int(max(0, math.floor(n_fft * self.f_min / self.sr)))
            max_bin = int(min(n_fft - 1, math.ceil(n_fft * self.f_max / self.sr)))
            spec = spec[:, :, min_bin:max_bin]

        spec.unsqueeze_(dim=0)
        spec = F.interpolate(spec, size=(spec.size(2), self.n_freqs), mode="nearest")
        return spec.squeeze(dim=0)

"""Convert hertz to mel."""
def _hz2mel(f):
    return 2595 * np.log10(1 + f / 700)

"""Convert mel to hertz."""
def _mel2hz(mel):
    return 700 * (10 ** (mel / 2595) - 1)

"""
Create melbank.

Code from https://github.com/pytorch/audio/blob/5787787edc/torchaudio/transforms.py

BSD 2-Clause License

Copyright (c) 2017 Facebook Inc. (Soumith Chintala), 
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Access Data: 12.09.2018, Last Access Date: 21.12.2021
Changes: Modified by Christian Bergler and Hendrik Schroeter (12.09.2018)
"""
def _melbank(sr, n_fft, n_mels=128, f_min=0.0, f_max=None, inverse=False):
    m_min = 0. if f_min == 0 else _hz2mel(f_min)
    m_max = _hz2mel(f_max if f_max is not None else sr // 2)

    m_pts = torch.linspace(m_min, m_max, n_mels + 2)
    f_pts = _mel2hz(m_pts)

    bins = torch.floor(((n_fft - 1) * 2 + 1) * f_pts / sr).long()

    fb = torch.zeros(n_mels, n_fft)
    for m in range(1, n_mels + 1):
        f_m_minus = bins[m - 1].item()
        f_m = bins[m].item()
        f_m_plus = bins[m + 1].item()

        if f_m_minus != f_m:
            fb[m - 1, f_m_minus:f_m] = (torch.arange(f_m_minus, f_m) - f_m_minus).float() / (
                f_m - f_m_minus
            )
        if f_m != f_m_plus:
            fb[m - 1, f_m:f_m_plus] = (f_m_plus - torch.arange(f_m, f_m_plus)).float() / (
                f_m_plus - f_m
            )

    if not inverse:
        return fb.t()
    else:
        return fb


"""
This turns a normal STFT into a MEL Frequency STFT, using a conversion matrix.  This uses triangular filter banks.

Code from https://github.com/pytorch/audio/blob/5787787edc/torchaudio/transforms.py

BSD 2-Clause License

Copyright (c) 2017 Facebook Inc. (Soumith Chintala), 
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Access Data: 12.09.2018, Last Access Date: 21.12.2021
Changes: Modified by Christian Bergler and Hendrik Schroeter (12.09.2018)
"""
class F2M(object):


    def __init__(
        self, sr: int = 16000, n_mels: int = 40, f_min: int = 0, f_max: int = None
    ):
        self.sr = sr
        self.n_mels = n_mels
        self.f_min = f_min
        self.f_max = f_max if f_max is not None else sr // 2
        if self.f_max > self.sr // 2:
            raise ValueError("f_max > sr // 2")

    def __call__(self, spec_f: torch.Tensor):
        n_fft = spec_f.size(2)

        fb = _melbank(self.sr, n_fft, self.n_mels, self.f_min, self.f_max)

        spec_m = torch.matmul(
            spec_f, fb
        )
        return spec_m


"""
Converts a normal STFT into a MEL Frequency STFT, using a conversion
matrix. This uses triangular filter banks.
"""
class M2F(object):

    def __init__(
        self, sr: int = 16000, n_fft: int = 1024, f_min: int = 0, f_max: int = None
    ):
        self.sr = sr
        self.n_fft = n_fft // 2 + 1
        self.f_min = f_min
        self.f_max = f_max if f_max is not None else sr // 2
        if self.f_max > self.sr // 2:
            raise ValueError("f_max > sr // 2")

    def __call__(self, spec_m: torch.Tensor):
        n_mels = spec_m.size(2)

        fb = _melbank(self.sr, self.n_fft, n_mels, self.f_min, self.f_max, inverse=True)

        spec_f = torch.matmul(
            spec_m, fb
        )
        return spec_f

"""
Converts MEL Frequency to MFCC.
"""
class M2MFCC(object):

    def __init__(self, n_mfcc : int = 32):
        self.n_mfcc = n_mfcc

    def __call__(self, spec_m):
        device = spec_m.device
        spec_m = 10 * torch.log10(spec_m)
        spec_m[spec_m == float('-inf')] = 0
        if isinstance(spec_m, torch.Tensor):
            spec_m = spec_m.cpu().numpy()
        mfcc = scipy.fftpack.dct(spec_m, axis=-1)
        mfcc = mfcc[:, :, 1:self.n_mfcc+1]
        return torch.from_numpy(mfcc).to(device)