-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_utils.py
154 lines (122 loc) · 4.76 KB
/
data_utils.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
import copy
import os
import pickle
from typing import Dict, Optional, Tuple
import librosa
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import yaml
from scipy.signal import lfilter
from models import AdaInVC
from generate_masking_threshold import generate_th, generate_th
class PreEmphasis(torch.nn.Module):
def __init__(self, coef: float = 0.97):
super().__init__()
self.coef = coef
# make kernel
# In pytorch, the convolution operation uses cross-correlation. So, filter is flipped.
self.register_buffer(
'flipped_filter', torch.FloatTensor([-self.coef, 1.]).unsqueeze(0).unsqueeze(0).cuda()
)
def forward(self, input: torch.tensor) -> torch.tensor:
assert len(input.size()) == 3, 'The number of dimensions of input tensor must be 3!'
# reflect padding to match lengths of in/out
input = F.pad(input, (1, 0), 'reflect')
return F.conv1d(input, self.flipped_filter)
class InversePreEmphasis(torch.nn.Module):
"""
Implement Inverse Pre-emphasis by using RNN to boost up inference speed.
"""
def __init__(self, coef: float = 0.97):
super().__init__()
self.coef = coef
self.rnn = torch.nn.RNN(1, 1, 1, bias=False, batch_first=True)
# use originally on that time
self.rnn.weight_ih_l0.data.fill_(1)
# multiply coefficient on previous output
self.rnn.weight_hh_l0.data.fill_(self.coef)
def forward(self, input: torch.tensor) -> torch.tensor:
x, _ = self.rnn(input.transpose(1, 2))
return x.transpose(1, 2)
class Transform(object):
'''
Return: PSD
'''
def __init__(
self,
sample_rate: int,
preemph: float,
n_fft: int,
hop_length: int,
win_length: int,
n_mels: int,
ref_db: float,
max_db: float,
top_db: float,
):
self.scale = 8. / 3.
self.n_fft = n_fft
self.hop_length = hop_length
self.win_length = win_length
def __call__(self, x, psd_max_ori):
device = x.device
win = torch.stft(input=x, n_fft=self.n_fft, hop_length=self.hop_length, win_length=self.win_length,
window=torch.hann_window(self.win_length).cuda(), center=True, pad_mode='reflect',
normalized=False, onesided=True, return_complex=False)
mag = torch.sqrt(win.pow(2).sum(-1) + (1e-9))
z = self.scale * torch.abs(mag / self.win_length)
psd = torch.square(z)
PSD = torch.pow(torch.tensor([10.]), 9.6).to(device) / torch.reshape(psd_max_ori, [-1, 1, 1]) * psd
PSD = PSD.squeeze().T
PSD = 10 * torch.log10(PSD)
return PSD
def normalize_tensor(mel: torch.Tensor, attr: Dict) -> np.array:
mean, std = attr["mean"], attr["std"]
mel = torch.div(torch.sub(mel, torch.from_numpy(mean).cuda()), torch.from_numpy(std).cuda())
return mel
def wav2mel_tensor(
wav: torch.Tensor,
sample_rate: int,
preemph: float,
n_fft: int,
hop_length: int,
win_length: int,
n_mels: int,
ref_db: float,
max_db: float,
top_db: float,
attr: Dict,
):
preemp = PreEmphasis(coef=preemph)
wav = wav.unsqueeze(0).unsqueeze(0)
preemp_wav = preemp(wav).squeeze(0).squeeze(0)
linear = torch.stft(input=preemp_wav, n_fft=n_fft, hop_length=hop_length, win_length=win_length,
window=torch.hann_window(win_length).cuda(), center=True, pad_mode='reflect',
normalized=False, onesided=True, return_complex=False)
mag = torch.sqrt(linear.pow(2).sum(-1) + (1e-9))
mel_basis = torch.from_numpy(librosa.filters.mel(sr=sample_rate, n_fft=n_fft, n_mels=n_mels)).cuda()
mel = torch.matmul(mel_basis, mag)
mel = torch.tensor([20]).cuda() * torch.log10(torch.maximum(torch.tensor([1e-5]).cuda(), mel))
mel = torch.clip((mel - ref_db + max_db) / max_db, 1e-8, 1)
mel = mel.T
mel = normalize_tensor(mel, attr)
return mel.T.unsqueeze(0).cuda()
def file2wav_mask(
audio_path: str,
sample_rate: int,
preemph: float,
n_fft: int,
hop_length: int,
win_length: int,
n_mels: int,
ref_db: float,
max_db: float,
top_db: float,
) -> Tuple[np.array, np.array, np.array]:
wav, _ = librosa.load(audio_path, sr=sample_rate)
wav, _ = librosa.effects.trim(wav, top_db=top_db)
wav = np.clip(wav, -1, 1)
theta_xs, psd_max = generate_th(wav, sample_rate=sample_rate, n_fft=n_fft, hop_length=hop_length, win_length=win_length)
return wav, theta_xs, psd_max