mosi77/5
0
1import torch
2import torch.utils.data
3from librosa.filters import mel as librosa_mel_fn
4
5
6def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
7 return torch.log(torch.clamp(x, min=clip_val) * C)
8
9
10def dynamic_range_decompression_torch(x, C=1):
11 return torch.exp(x) / C
12
13
14def spectral_normalize_torch(magnitudes):
15 return dynamic_range_compression_torch(magnitudes)
16
17
18def spectral_de_normalize_torch(magnitudes):
19 return dynamic_range_decompression_torch(magnitudes)
20
21
22mel_basis = {}
23hann_window = {}
24
25
26def spectrogram_torch(y, n_fft, hop_size, win_size, center=False):
27 global hann_window
28 dtype_device = str(y.dtype) + "_" + str(y.device)
29 wnsize_dtype_device = str(win_size) + "_" + dtype_device
30 if wnsize_dtype_device not in hann_window:
31 hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(
32 dtype=y.dtype, device=y.device
33 )
34
35 y = torch.nn.functional.pad(
36 y.unsqueeze(1),
37 (int((n_fft - hop_size) / 2), int((n_fft - hop_size) / 2)),
38 mode="reflect",
39 )
40 y = y.squeeze(1)
41
42 spec = torch.stft(
43 y,
44 n_fft,
45 hop_length=hop_size,
46 win_length=win_size,
47 window=hann_window[wnsize_dtype_device],
48 center=center,
49 pad_mode="reflect",
50 normalized=False,
51 onesided=True,
52 return_complex=True,
53 )
54
55 spec = torch.sqrt(spec.real.pow(2) + spec.imag.pow(2) + 1e-6)
56
57 return spec
58
59
60def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax):
61 global mel_basis
62 dtype_device = str(spec.dtype) + "_" + str(spec.device)
63 fmax_dtype_device = str(fmax) + "_" + dtype_device
64 if fmax_dtype_device not in mel_basis:
65 mel = librosa_mel_fn(
66 sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax
67 )
68 mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(
69 dtype=spec.dtype, device=spec.device
70 )
71
72 melspec = torch.matmul(mel_basis[fmax_dtype_device], spec)
73 melspec = spectral_normalize_torch(melspec)
74 return melspec
75
76
77def mel_spectrogram_torch(
78 y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False
79):
80 spec = spectrogram_torch(y, n_fft, hop_size, win_size, center)
81
82 melspec = spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax)
83
84 return melspec
85 