-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtool.py
191 lines (150 loc) · 6.81 KB
/
tool.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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import torch
import torchaudio
import random
import itertools
import numpy as np
from tools.mix import mix
import os
import logging
initialized_logger = {}
def normalize_wav(waveform):
waveform = waveform - torch.mean(waveform)
waveform = waveform / (torch.max(torch.abs(waveform)) + 1e-8)
return waveform * 0.5
def pad_wav(waveform, segment_length):
waveform_length = len(waveform)
if segment_length is None or waveform_length == segment_length:
return waveform
elif waveform_length > segment_length:
return waveform[:segment_length]
else:
pad_wav = torch.zeros(segment_length - waveform_length).to(waveform.device)
waveform = torch.cat([waveform, pad_wav])
return waveform
def _pad_spec(fbank, target_length=1024):
batch, n_frames, channels = fbank.shape
p = target_length - n_frames
if p > 0:
pad = torch.zeros(batch, p, channels).to(fbank.device)
fbank = torch.cat([fbank, pad], 1)
elif p < 0:
fbank = fbank[:, :target_length, :]
if channels % 2 != 0:
fbank = fbank[:, :, :-1]
return fbank
def read_wav_file(filename, segment_length):
waveform, sr = torchaudio.load(filename) # Faster!!!
waveform = torchaudio.functional.resample(waveform, orig_freq=sr, new_freq=16000)[0]
try:
waveform = normalize_wav(waveform)
except:
print ("Exception normalizing:", filename)
waveform = torch.ones(160000)
waveform = pad_wav(waveform, segment_length).unsqueeze(0)
waveform = waveform / torch.max(torch.abs(waveform))
waveform = 0.5 * waveform
return waveform
def get_mel_from_wav(audio, _stft):
audio = torch.nan_to_num(torch.clip(audio, -1, 1))
audio = torch.autograd.Variable(audio, requires_grad=False)
melspec, log_magnitudes_stft, energy = _stft.mel_spectrogram(audio)
return melspec, log_magnitudes_stft, energy
def wav_to_fbank(paths, target_length=1024, fn_STFT=None):
assert fn_STFT is not None
waveform = torch.cat([read_wav_file(path, target_length * 160) for path in paths], 0) # hop size is 160
fbank, log_magnitudes_stft, energy = get_mel_from_wav(waveform, fn_STFT)
fbank = fbank.transpose(1, 2)
log_magnitudes_stft = log_magnitudes_stft.transpose(1, 2)
fbank, log_magnitudes_stft = _pad_spec(fbank, target_length), _pad_spec(
log_magnitudes_stft, target_length
)
return fbank, log_magnitudes_stft, waveform
def batch_read_wav(paths, target_length_seconds=10, target_sr=24000):
# waveform = torch.cat([read_wav_file(path, target_length * 160) for path in paths], 0) # hop size is 160
target_length = target_length_seconds * 24000
waves = []
for path in paths:
wave, sr = torchaudio.load(path)
# waveform = torchaudio.functional.resample(waveform, orig_freq=sr, new_freq=24000)[0]
wav = torchaudio.transforms.Resample(sr, target_sr)(wave)
lenth = wav.shape[1]
if lenth < target_length_seconds * 24000:
pad_wav = torch.zeros(target_length - lenth).to(wav.device).unsqueeze(0)
wav = torch.cat([wav, pad_wav], dim=1)
elif lenth > target_length:
wav = wav[:, :target_length]
waves.append(wav.unsqueeze(0))
waveforms = torch.cat([vec for vec in waves], 0)
return waveforms
def uncapitalize(s):
if s:
return s[:1].lower() + s[1:]
else:
return ""
def mix_wavs_and_captions(path1, path2, caption1, caption2, target_length=1024):
sound1 = read_wav_file(path1, target_length * 160)[0].numpy()
sound2 = read_wav_file(path2, target_length * 160)[0].numpy()
mixed_sound = mix(sound1, sound2, 0.5, 16000).reshape(1, -1)
mixed_caption = "{} and {}".format(caption1, uncapitalize(caption2))
return mixed_sound, mixed_caption
def augment(paths, texts, num_items=4, target_length=1024):
mixed_sounds, mixed_captions = [], []
combinations = list(itertools.combinations(list(range(len(texts))), 2))
random.shuffle(combinations)
if len(combinations) < num_items:
selected_combinations = combinations
else:
selected_combinations = combinations[:num_items]
for (i, j) in selected_combinations:
new_sound, new_caption = mix_wavs_and_captions(paths[i], paths[j], texts[i], texts[j], target_length)
mixed_sounds.append(new_sound)
mixed_captions.append(new_caption)
waveform = torch.tensor(np.concatenate(mixed_sounds, 0))
waveform = waveform / torch.max(torch.abs(waveform))
waveform = 0.5 * waveform
return waveform, mixed_captions
def augment_wav_to_fbank(paths, texts, num_items=4, target_length=1024, fn_STFT=None):
assert fn_STFT is not None
waveform, captions = augment(paths, texts)
fbank, log_magnitudes_stft, energy = get_mel_from_wav(waveform, fn_STFT)
fbank = fbank.transpose(1, 2)
log_magnitudes_stft = log_magnitudes_stft.transpose(1, 2)
fbank, log_magnitudes_stft = _pad_spec(fbank, target_length), _pad_spec(
log_magnitudes_stft, target_length
)
return fbank, log_magnitudes_stft, waveform, captions
def get_encode_text(name, root):
if not isinstance(name, list):
name = [name]
emd = []
mask = []
for each in name:
path = os.path.join(root, each+'.pth')
path_mask = os.path.join(root, each+'_mask.pth')
encoder_hidden_states = torch.load(path, map_location='cpu')
emd.append(encoder_hidden_states)
attention_mask = torch.load(path_mask, map_location='cpu') ## bool tensor
mask.append(attention_mask)
padded_maskS = []
padded_emdS = []
max_length = max([tensor.shape[0] for tensor in mask])
for i in range(len(name)):
padding = max_length - mask[i].shape[0]
padded_emd = torch.cat([emd[i], torch.zeros((padding,) + emd[i].shape[1:])], dim=0)
padded_emdS.append(padded_emd)
padded_mask = torch.cat([mask[i], torch.zeros((padding,) + mask[i].shape[1:])], dim=0)
padded_maskS.append(padded_mask)
batch_encoder_hidden_states = torch.cat([tensor.unsqueeze(0) for tensor in padded_emdS], dim=0)
batch_attention_mask = torch.cat([tensor.unsqueeze(0) for tensor in padded_maskS], dim=0)
boolean_encoder_mask = (batch_attention_mask == 1)
return batch_encoder_hidden_states, boolean_encoder_mask
def get_latent(name, root):
if not isinstance(name, list):
name = [name]
latent = []
for each in name:
path = os.path.join(root, each+'.pth')
encoder_hidden_states = torch.load(path, map_location='cpu')
latent.append(encoder_hidden_states)
batch_latent = torch.cat([tensor.unsqueeze(0) for tensor in latent], dim=0)
return batch_latent