Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
prophesier
GitHub Repository: prophesier/diff-svc
Path: blob/main/modules/nsf_hifigan/nvSTFT.py
695 views
1
import math
2
import os
3
os.environ["LRU_CACHE_CAPACITY"] = "3"
4
import random
5
import torch
6
import torch.utils.data
7
import numpy as np
8
import librosa
9
from librosa.util import normalize
10
from librosa.filters import mel as librosa_mel_fn
11
from scipy.io.wavfile import read
12
import soundfile as sf
13
14
def load_wav_to_torch(full_path, target_sr=None, return_empty_on_exception=False):
15
sampling_rate = None
16
try:
17
data, sampling_rate = sf.read(full_path, always_2d=True)# than soundfile.
18
except Exception as ex:
19
print(f"'{full_path}' failed to load.\nException:")
20
print(ex)
21
if return_empty_on_exception:
22
return [], sampling_rate or target_sr or 48000
23
else:
24
raise Exception(ex)
25
26
if len(data.shape) > 1:
27
data = data[:, 0]
28
assert len(data) > 2# check duration of audio file is > 2 samples (because otherwise the slice operation was on the wrong dimension)
29
30
if np.issubdtype(data.dtype, np.integer): # if audio data is type int
31
max_mag = -np.iinfo(data.dtype).min # maximum magnitude = min possible value of intXX
32
else: # if audio data is type fp32
33
max_mag = max(np.amax(data), -np.amin(data))
34
max_mag = (2**31)+1 if max_mag > (2**15) else ((2**15)+1 if max_mag > 1.01 else 1.0) # data should be either 16-bit INT, 32-bit INT or [-1 to 1] float32
35
36
data = torch.FloatTensor(data.astype(np.float32))/max_mag
37
38
if (torch.isinf(data) | torch.isnan(data)).any() and return_empty_on_exception:# resample will crash with inf/NaN inputs. return_empty_on_exception will return empty arr instead of except
39
return [], sampling_rate or target_sr or 48000
40
if target_sr is not None and sampling_rate != target_sr:
41
data = torch.from_numpy(librosa.core.resample(data.numpy(), orig_sr=sampling_rate, target_sr=target_sr))
42
sampling_rate = target_sr
43
44
return data, sampling_rate
45
46
def dynamic_range_compression(x, C=1, clip_val=1e-5):
47
return np.log(np.clip(x, a_min=clip_val, a_max=None) * C)
48
49
def dynamic_range_decompression(x, C=1):
50
return np.exp(x) / C
51
52
def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
53
return torch.log(torch.clamp(x, min=clip_val) * C)
54
55
def dynamic_range_decompression_torch(x, C=1):
56
return torch.exp(x) / C
57
58
class STFT():
59
def __init__(self, sr=22050, n_mels=80, n_fft=1024, win_size=1024, hop_length=256, fmin=20, fmax=11025, clip_val=1e-5):
60
self.target_sr = sr
61
62
self.n_mels = n_mels
63
self.n_fft = n_fft
64
self.win_size = win_size
65
self.hop_length = hop_length
66
self.fmin = fmin
67
self.fmax = fmax
68
self.clip_val = clip_val
69
self.mel_basis = {}
70
self.hann_window = {}
71
72
def get_mel(self, y, center=False):
73
sampling_rate = self.target_sr
74
n_mels = self.n_mels
75
n_fft = self.n_fft
76
win_size = self.win_size
77
hop_length = self.hop_length
78
fmin = self.fmin
79
fmax = self.fmax
80
clip_val = self.clip_val
81
82
if torch.min(y) < -1.:
83
print('min value is ', torch.min(y))
84
if torch.max(y) > 1.:
85
print('max value is ', torch.max(y))
86
87
if fmax not in self.mel_basis:
88
mel = librosa_mel_fn(sr=sampling_rate, n_fft=n_fft, n_mels=n_mels, fmin=fmin, fmax=fmax)
89
self.mel_basis[str(fmax)+'_'+str(y.device)] = torch.from_numpy(mel).float().to(y.device)
90
self.hann_window[str(y.device)] = torch.hann_window(self.win_size).to(y.device)
91
92
y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_length)/2), int((n_fft-hop_length)/2)), mode='reflect')
93
y = y.squeeze(1)
94
95
spec = torch.stft(y, n_fft, hop_length=hop_length, win_length=win_size, window=self.hann_window[str(y.device)],
96
center=center, pad_mode='reflect', normalized=False, onesided=True)
97
# print(111,spec)
98
spec = torch.sqrt(spec.pow(2).sum(-1)+(1e-9))
99
# print(222,spec)
100
spec = torch.matmul(self.mel_basis[str(fmax)+'_'+str(y.device)], spec)
101
# print(333,spec)
102
spec = dynamic_range_compression_torch(spec, clip_val=clip_val)
103
# print(444,spec)
104
return spec
105
106
def __call__(self, audiopath):
107
audio, sr = load_wav_to_torch(audiopath, target_sr=self.target_sr)
108
spect = self.get_mel(audio.unsqueeze(0)).squeeze(0)
109
return spect
110
111
stft = STFT()
112