-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnorm_wav.py
166 lines (137 loc) · 6 KB
/
norm_wav.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
from scipy.io.wavfile import read, write
import torchaudio
import torch
from librosa.util import normalize
from librosa.filters import mel as librosa_mel_fn
import numpy as np
import librosa
import argparse
import librosa.display
from tqdm import tqdm
import os
import soundfile as sf
import matplotlib.pyplot as plt
import parser
import glob
#%matplotlib inline
MAX_WAV_VALUE = 32768.0
def load_wav(full_path):
sampling_rate, data = read(full_path)
return data, sampling_rate
def dynamic_range_compression(x, C=1, clip_val=1e-5):
return np.log(np.clip(x, a_min=clip_val, a_max=None) * C)
def dynamic_range_decompression(x, C=1):
return np.exp(x) / C
def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
return torch.log(torch.clamp(x, min=clip_val) * C)
def dynamic_range_decompression_torch(x, C=1):
return torch.exp(x) / C
def spectral_normalize_torch(magnitudes):
output = dynamic_range_compression_torch(magnitudes)
return output
def spectral_de_normalize_torch(magnitudes):
output = dynamic_range_decompression_torch(magnitudes)
return output
mel_basis = {}
hann_window = {}
def mel_spectrogram(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False):
if torch.min(y) < -1.:
print('min value is ', torch.min(y))
if torch.max(y) > 1.:
print('max value is ', torch.max(y))
global mel_basis, hann_window
if fmax not in mel_basis:
mel = librosa_mel_fn(sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax)
mel_basis[str(fmax)+'_'+str(y.device)] = torch.from_numpy(mel).float().to(y.device)
hann_window[str(y.device)] = torch.hann_window(win_size).to(y.device)
y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect')
y = y.squeeze(1)
spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[str(y.device)],
center=center, pad_mode='reflect', normalized=False, onesided=True,return_complex=False)
spec = torch.sqrt(spec.pow(2).sum(-1)+(1e-9))
spec = torch.matmul(mel_basis[str(fmax)+'_'+str(y.device)], spec)
spec = spectral_normalize_torch(spec)
return spec
def extract_and_save_mel(data_path, save_path, wav_files):
for file_name in tqdm(wav_files[:]):
try:
wav, sr = librosa.load(os.path.join(data_path, file_name), sr=16000)
except:
print("error file",os.path.join(data_path, file_name))
continue
wav = np.clip(wav, -1, 1)
x = torch.FloatTensor(wav)
# print(len(x))
x = mel_spectrogram(x.unsqueeze(0), n_fft=1024, num_mels=80, sampling_rate=16000,
hop_size=256, win_size=1024, fmin=0, fmax=8000)
#print("x.shape",x.shape)
spec = x.cpu().numpy()[0]
#print("spec.shape",spec.shape)
wav = wav * MAX_WAV_VALUE
wav = wav.astype('int16')
write(os.path.join(save_path, "wav", file_name), 16000, wav)
np.save(os.path.join(save_path, "mel", file_name.replace(".wav", ".npy")), spec)
def extract_and_save_spk_emb(data_path, save_path, wav_files,speaker):
for file_name in tqdm(wav_files[:]):
try:
wav, sr = librosa.load(os.path.join(data_path, file_name), sr=16000)
except:
print("error file",os.path.join(data_path, file_name))
continue
spk_emb=speaker.extract_embedding(os.path.join(data_path, file_name))
np.save(os.path.join(save_path, "spkemb", file_name.replace(".wav", ".npy")), spk_emb)
def stft(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=True):
if torch.min(y) < -1.:
print('min value is ', torch.min(y))
if torch.max(y) > 1.:
print('max value is ', torch.max(y))
hann_window[str(y.device)] = torch.hann_window(win_size).to(y.device)
spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[str(y.device)],
center=center, pad_mode='reflect', normalized=False, onesided=False,return_complex=True)
return spec
def extract_and_save_stft(data_path, save_path, wav_files):
for file_name in tqdm(wav_files[:]):
try:
wav, sr = librosa.load(os.path.join(data_path, file_name), sr=16000)
except:
print("error file",os.path.join(data_path, file_name))
continue
wav = np.clip(wav, -1, 1)
x = torch.FloatTensor(wav)
# print(len(x))
spec = stft(x.unsqueeze(0), n_fft=512, num_mels=80, sampling_rate=16000,
hop_size=256, win_size=512, fmin=0, fmax=8000, center=True)
#print("x.shape",x.shape)
#spec = x.cpu().numpy()[0]
#print("spec.shape",spec.shape)
spec = spec.cpu().numpy()
np.save(os.path.join(save_path, "stft_512", file_name.replace(".wav", ".npy")), spec)
def save_wav(data_path, save_path, wav_files, prefix = None):
for file_name in tqdm(wav_files[:]):
try:
wav, sr = librosa.load(os.path.join(data_path, file_name), sr=16000)
except:
print("error file",os.path.join(data_path, file_name))
continue
wav = wav - np.mean(wav)
wav = wav / np.max(np.abs(wav))
#wav = np.clip(wav, -1, 1)
#wav = wav * MAX_WAV_VALUE
#wav = wav.astype('int16')
if prefix == None:
write(os.path.join(save_path, file_name), 16000, wav)
else:
write(os.path.join(save_path, prefix + file_name), 16000, wav)
# main function
if __name__ == "__main__":
# input parser
parser = argparse.ArgumentParser()
parser.add_argument('--data_path', type=str, default="/input_dir")
parser.add_argument('--save_path', type=str, default="/output_dir_mel")
args = parser.parse_args()
data_path = args.data_path
save_path = args.save_path
if not os.path.exists(save_path):
os.makedirs(save_path)
wav_files = os.listdir(data_path)
save_wav(data_path, save_path, wav_files)