DoNotSelect commited on
Commit
597103f
·
1 Parent(s): 3807078
.gitattributes CHANGED
@@ -32,3 +32,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
32
  *.zip filter=lfs diff=lfs merge=lfs -text
33
  *.zst filter=lfs diff=lfs merge=lfs -text
34
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
32
  *.zip filter=lfs diff=lfs merge=lfs -text
33
  *.zst filter=lfs diff=lfs merge=lfs -text
34
  *tfevents* filter=lfs diff=lfs merge=lfs -text
35
+ *.wav filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ /.idea/vcs.xml
2
+ /hubert/put_hubert_ckpt_here
3
+ /.idea/inspectionProfiles/Project_Default.xml
4
+ /.idea/inspectionProfiles/profiles_settings.xml
5
+ /.idea/modules.xml
6
+ /.idea/.gitignore
7
+ /.idea/so-vits-svc-3.0-app.iml
8
+ /.idea/AI-minato_aqua.iml
9
+ /.idea/misc.xml
app.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import os
3
+
4
+ import gradio as gr
5
+ import librosa
6
+ import numpy as np
7
+ import soundfile
8
+ import torch
9
+ from inference.infer_tool import Svc
10
+ import logging
11
+ logging.getLogger("numba").setLevel(logging.WARNING)
12
+
13
+ model_path = "logs/48k/aqua.pth"
14
+ config_path = "configs/config.json"
15
+
16
+ svc_model = Svc(model_path, config_path)
17
+
18
+
19
+ def vc_fn(input_audio, vc_transform, term):
20
+ if not term:
21
+ return "请阅读并同意《AI阿夸模型使用协议》", None
22
+ if input_audio is None:
23
+ return "请上传音频", None
24
+ sampling_rate, audio = input_audio
25
+ duration = audio.shape[0] / sampling_rate
26
+ if duration > 30:
27
+ return "请上传小于30s的音频,长音频的转换请在本地进行", None
28
+ audio = (audio / np.iinfo(audio.dtype).max).astype(np.float32)
29
+ if len(audio.shape) > 1:
30
+ audio = librosa.to_mono(audio.transpose(1, 0))
31
+ if sampling_rate != 24000:
32
+ audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=24000)
33
+ print(audio.shape)
34
+ out_wav_path = io.BytesIO()
35
+ soundfile.write(out_wav_path, audio, 24000, format="wav")
36
+ out_wav_path.seek(0)
37
+
38
+ # sid = sid_map[sid]
39
+ sid = "aqua"
40
+ out_audio, out_sr = svc_model.infer(sid, vc_transform, out_wav_path)
41
+ _audio = out_audio.cpu().numpy()
42
+ return "Success", (48000, _audio)
43
+
44
+
45
+ inputs = [
46
+ gr.inputs.Audio(source="upload"),
47
+ gr.inputs.Number(default=0),
48
+ gr.Checkbox(label="您已阅读并同意《AI阿夸模型使用协议》")
49
+ ]
50
+
51
+ outputs = [
52
+ "text",
53
+ gr.outputs.Audio(type="numpy")
54
+ ]
55
+
56
+ example = [
57
+ ["./raw/大手拉小手.wav", 0, False]
58
+ ]
59
+
60
+ des = """
61
+ ## 在使用此模型前请阅读[AI阿夸模型使用协议](https://huggingface.co/spaces/DoNotSelect/AI-minato_aqua/blob/main/terms.md)
62
+ """
63
+
64
+ demo = gr.Interface(
65
+ fn=vc_fn,
66
+ inputs=inputs,
67
+ outputs=outputs,
68
+ layout="horizontal",
69
+ theme="huggingface",
70
+ description=des,
71
+ examples=example,
72
+ cache_examples=True
73
+ )
74
+
75
+ if __name__ == "__main__":
76
+ demo.launch()
attentions.py ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import math
3
+ import numpy as np
4
+ import torch
5
+ from torch import nn
6
+ from torch.nn import functional as F
7
+
8
+ import commons
9
+ import modules
10
+ from modules import LayerNorm
11
+
12
+
13
+ class Encoder(nn.Module):
14
+ def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., window_size=4, **kwargs):
15
+ super().__init__()
16
+ self.hidden_channels = hidden_channels
17
+ self.filter_channels = filter_channels
18
+ self.n_heads = n_heads
19
+ self.n_layers = n_layers
20
+ self.kernel_size = kernel_size
21
+ self.p_dropout = p_dropout
22
+ self.window_size = window_size
23
+
24
+ self.drop = nn.Dropout(p_dropout)
25
+ self.attn_layers = nn.ModuleList()
26
+ self.norm_layers_1 = nn.ModuleList()
27
+ self.ffn_layers = nn.ModuleList()
28
+ self.norm_layers_2 = nn.ModuleList()
29
+ for i in range(self.n_layers):
30
+ self.attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, window_size=window_size))
31
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
32
+ self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout))
33
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
34
+
35
+ def forward(self, x, x_mask):
36
+ attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
37
+ x = x * x_mask
38
+ for i in range(self.n_layers):
39
+ y = self.attn_layers[i](x, x, attn_mask)
40
+ y = self.drop(y)
41
+ x = self.norm_layers_1[i](x + y)
42
+
43
+ y = self.ffn_layers[i](x, x_mask)
44
+ y = self.drop(y)
45
+ x = self.norm_layers_2[i](x + y)
46
+ x = x * x_mask
47
+ return x
48
+
49
+
50
+ class Decoder(nn.Module):
51
+ def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., proximal_bias=False, proximal_init=True, **kwargs):
52
+ super().__init__()
53
+ self.hidden_channels = hidden_channels
54
+ self.filter_channels = filter_channels
55
+ self.n_heads = n_heads
56
+ self.n_layers = n_layers
57
+ self.kernel_size = kernel_size
58
+ self.p_dropout = p_dropout
59
+ self.proximal_bias = proximal_bias
60
+ self.proximal_init = proximal_init
61
+
62
+ self.drop = nn.Dropout(p_dropout)
63
+ self.self_attn_layers = nn.ModuleList()
64
+ self.norm_layers_0 = nn.ModuleList()
65
+ self.encdec_attn_layers = nn.ModuleList()
66
+ self.norm_layers_1 = nn.ModuleList()
67
+ self.ffn_layers = nn.ModuleList()
68
+ self.norm_layers_2 = nn.ModuleList()
69
+ for i in range(self.n_layers):
70
+ self.self_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, proximal_bias=proximal_bias, proximal_init=proximal_init))
71
+ self.norm_layers_0.append(LayerNorm(hidden_channels))
72
+ self.encdec_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout))
73
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
74
+ self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout, causal=True))
75
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
76
+
77
+ def forward(self, x, x_mask, h, h_mask):
78
+ """
79
+ x: decoder input
80
+ h: encoder output
81
+ """
82
+ self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype)
83
+ encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
84
+ x = x * x_mask
85
+ for i in range(self.n_layers):
86
+ y = self.self_attn_layers[i](x, x, self_attn_mask)
87
+ y = self.drop(y)
88
+ x = self.norm_layers_0[i](x + y)
89
+
90
+ y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
91
+ y = self.drop(y)
92
+ x = self.norm_layers_1[i](x + y)
93
+
94
+ y = self.ffn_layers[i](x, x_mask)
95
+ y = self.drop(y)
96
+ x = self.norm_layers_2[i](x + y)
97
+ x = x * x_mask
98
+ return x
99
+
100
+
101
+ class MultiHeadAttention(nn.Module):
102
+ def __init__(self, channels, out_channels, n_heads, p_dropout=0., window_size=None, heads_share=True, block_length=None, proximal_bias=False, proximal_init=False):
103
+ super().__init__()
104
+ assert channels % n_heads == 0
105
+
106
+ self.channels = channels
107
+ self.out_channels = out_channels
108
+ self.n_heads = n_heads
109
+ self.p_dropout = p_dropout
110
+ self.window_size = window_size
111
+ self.heads_share = heads_share
112
+ self.block_length = block_length
113
+ self.proximal_bias = proximal_bias
114
+ self.proximal_init = proximal_init
115
+ self.attn = None
116
+
117
+ self.k_channels = channels // n_heads
118
+ self.conv_q = nn.Conv1d(channels, channels, 1)
119
+ self.conv_k = nn.Conv1d(channels, channels, 1)
120
+ self.conv_v = nn.Conv1d(channels, channels, 1)
121
+ self.conv_o = nn.Conv1d(channels, out_channels, 1)
122
+ self.drop = nn.Dropout(p_dropout)
123
+
124
+ if window_size is not None:
125
+ n_heads_rel = 1 if heads_share else n_heads
126
+ rel_stddev = self.k_channels**-0.5
127
+ self.emb_rel_k = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
128
+ self.emb_rel_v = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
129
+
130
+ nn.init.xavier_uniform_(self.conv_q.weight)
131
+ nn.init.xavier_uniform_(self.conv_k.weight)
132
+ nn.init.xavier_uniform_(self.conv_v.weight)
133
+ if proximal_init:
134
+ with torch.no_grad():
135
+ self.conv_k.weight.copy_(self.conv_q.weight)
136
+ self.conv_k.bias.copy_(self.conv_q.bias)
137
+
138
+ def forward(self, x, c, attn_mask=None):
139
+ q = self.conv_q(x)
140
+ k = self.conv_k(c)
141
+ v = self.conv_v(c)
142
+
143
+ x, self.attn = self.attention(q, k, v, mask=attn_mask)
144
+
145
+ x = self.conv_o(x)
146
+ return x
147
+
148
+ def attention(self, query, key, value, mask=None):
149
+ # reshape [b, d, t] -> [b, n_h, t, d_k]
150
+ b, d, t_s, t_t = (*key.size(), query.size(2))
151
+ query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
152
+ key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
153
+ value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
154
+
155
+ scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
156
+ if self.window_size is not None:
157
+ assert t_s == t_t, "Relative attention is only available for self-attention."
158
+ key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
159
+ rel_logits = self._matmul_with_relative_keys(query /math.sqrt(self.k_channels), key_relative_embeddings)
160
+ scores_local = self._relative_position_to_absolute_position(rel_logits)
161
+ scores = scores + scores_local
162
+ if self.proximal_bias:
163
+ assert t_s == t_t, "Proximal bias is only available for self-attention."
164
+ scores = scores + self._attention_bias_proximal(t_s).to(device=scores.device, dtype=scores.dtype)
165
+ if mask is not None:
166
+ scores = scores.masked_fill(mask == 0, -1e4)
167
+ if self.block_length is not None:
168
+ assert t_s == t_t, "Local attention is only available for self-attention."
169
+ block_mask = torch.ones_like(scores).triu(-self.block_length).tril(self.block_length)
170
+ scores = scores.masked_fill(block_mask == 0, -1e4)
171
+ p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
172
+ p_attn = self.drop(p_attn)
173
+ output = torch.matmul(p_attn, value)
174
+ if self.window_size is not None:
175
+ relative_weights = self._absolute_position_to_relative_position(p_attn)
176
+ value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, t_s)
177
+ output = output + self._matmul_with_relative_values(relative_weights, value_relative_embeddings)
178
+ output = output.transpose(2, 3).contiguous().view(b, d, t_t) # [b, n_h, t_t, d_k] -> [b, d, t_t]
179
+ return output, p_attn
180
+
181
+ def _matmul_with_relative_values(self, x, y):
182
+ """
183
+ x: [b, h, l, m]
184
+ y: [h or 1, m, d]
185
+ ret: [b, h, l, d]
186
+ """
187
+ ret = torch.matmul(x, y.unsqueeze(0))
188
+ return ret
189
+
190
+ def _matmul_with_relative_keys(self, x, y):
191
+ """
192
+ x: [b, h, l, d]
193
+ y: [h or 1, m, d]
194
+ ret: [b, h, l, m]
195
+ """
196
+ ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
197
+ return ret
198
+
199
+ def _get_relative_embeddings(self, relative_embeddings, length):
200
+ max_relative_position = 2 * self.window_size + 1
201
+ # Pad first before slice to avoid using cond ops.
202
+ pad_length = max(length - (self.window_size + 1), 0)
203
+ slice_start_position = max((self.window_size + 1) - length, 0)
204
+ slice_end_position = slice_start_position + 2 * length - 1
205
+ if pad_length > 0:
206
+ padded_relative_embeddings = F.pad(
207
+ relative_embeddings,
208
+ commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]))
209
+ else:
210
+ padded_relative_embeddings = relative_embeddings
211
+ used_relative_embeddings = padded_relative_embeddings[:,slice_start_position:slice_end_position]
212
+ return used_relative_embeddings
213
+
214
+ def _relative_position_to_absolute_position(self, x):
215
+ """
216
+ x: [b, h, l, 2*l-1]
217
+ ret: [b, h, l, l]
218
+ """
219
+ batch, heads, length, _ = x.size()
220
+ # Concat columns of pad to shift from relative to absolute indexing.
221
+ x = F.pad(x, commons.convert_pad_shape([[0,0],[0,0],[0,0],[0,1]]))
222
+
223
+ # Concat extra elements so to add up to shape (len+1, 2*len-1).
224
+ x_flat = x.view([batch, heads, length * 2 * length])
225
+ x_flat = F.pad(x_flat, commons.convert_pad_shape([[0,0],[0,0],[0,length-1]]))
226
+
227
+ # Reshape and slice out the padded elements.
228
+ x_final = x_flat.view([batch, heads, length+1, 2*length-1])[:, :, :length, length-1:]
229
+ return x_final
230
+
231
+ def _absolute_position_to_relative_position(self, x):
232
+ """
233
+ x: [b, h, l, l]
234
+ ret: [b, h, l, 2*l-1]
235
+ """
236
+ batch, heads, length, _ = x.size()
237
+ # padd along column
238
+ x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length-1]]))
239
+ x_flat = x.view([batch, heads, length**2 + length*(length -1)])
240
+ # add 0's in the beginning that will skew the elements after reshape
241
+ x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
242
+ x_final = x_flat.view([batch, heads, length, 2*length])[:,:,:,1:]
243
+ return x_final
244
+
245
+ def _attention_bias_proximal(self, length):
246
+ """Bias for self-attention to encourage attention to close positions.
247
+ Args:
248
+ length: an integer scalar.
249
+ Returns:
250
+ a Tensor with shape [1, 1, length, length]
251
+ """
252
+ r = torch.arange(length, dtype=torch.float32)
253
+ diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
254
+ return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
255
+
256
+
257
+ class FFN(nn.Module):
258
+ def __init__(self, in_channels, out_channels, filter_channels, kernel_size, p_dropout=0., activation=None, causal=False):
259
+ super().__init__()
260
+ self.in_channels = in_channels
261
+ self.out_channels = out_channels
262
+ self.filter_channels = filter_channels
263
+ self.kernel_size = kernel_size
264
+ self.p_dropout = p_dropout
265
+ self.activation = activation
266
+ self.causal = causal
267
+
268
+ if causal:
269
+ self.padding = self._causal_padding
270
+ else:
271
+ self.padding = self._same_padding
272
+
273
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
274
+ self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
275
+ self.drop = nn.Dropout(p_dropout)
276
+
277
+ def forward(self, x, x_mask):
278
+ x = self.conv_1(self.padding(x * x_mask))
279
+ if self.activation == "gelu":
280
+ x = x * torch.sigmoid(1.702 * x)
281
+ else:
282
+ x = torch.relu(x)
283
+ x = self.drop(x)
284
+ x = self.conv_2(self.padding(x * x_mask))
285
+ return x * x_mask
286
+
287
+ def _causal_padding(self, x):
288
+ if self.kernel_size == 1:
289
+ return x
290
+ pad_l = self.kernel_size - 1
291
+ pad_r = 0
292
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
293
+ x = F.pad(x, commons.convert_pad_shape(padding))
294
+ return x
295
+
296
+ def _same_padding(self, x):
297
+ if self.kernel_size == 1:
298
+ return x
299
+ pad_l = (self.kernel_size - 1) // 2
300
+ pad_r = self.kernel_size // 2
301
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
302
+ x = F.pad(x, commons.convert_pad_shape(padding))
303
+ return x
commons.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import numpy as np
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+ def slice_pitch_segments(x, ids_str, segment_size=4):
8
+ ret = torch.zeros_like(x[:, :segment_size])
9
+ for i in range(x.size(0)):
10
+ idx_str = ids_str[i]
11
+ idx_end = idx_str + segment_size
12
+ ret[i] = x[i, idx_str:idx_end]
13
+ return ret
14
+
15
+ def rand_slice_segments_with_pitch(x, pitch, x_lengths=None, segment_size=4):
16
+ b, d, t = x.size()
17
+ if x_lengths is None:
18
+ x_lengths = t
19
+ ids_str_max = x_lengths - segment_size + 1
20
+ ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)
21
+ ret = slice_segments(x, ids_str, segment_size)
22
+ ret_pitch = slice_pitch_segments(pitch, ids_str, segment_size)
23
+ return ret, ret_pitch, ids_str
24
+
25
+ def init_weights(m, mean=0.0, std=0.01):
26
+ classname = m.__class__.__name__
27
+ if classname.find("Conv") != -1:
28
+ m.weight.data.normal_(mean, std)
29
+
30
+
31
+ def get_padding(kernel_size, dilation=1):
32
+ return int((kernel_size*dilation - dilation)/2)
33
+
34
+
35
+ def convert_pad_shape(pad_shape):
36
+ l = pad_shape[::-1]
37
+ pad_shape = [item for sublist in l for item in sublist]
38
+ return pad_shape
39
+
40
+
41
+ def intersperse(lst, item):
42
+ result = [item] * (len(lst) * 2 + 1)
43
+ result[1::2] = lst
44
+ return result
45
+
46
+
47
+ def kl_divergence(m_p, logs_p, m_q, logs_q):
48
+ """KL(P||Q)"""
49
+ kl = (logs_q - logs_p) - 0.5
50
+ kl += 0.5 * (torch.exp(2. * logs_p) + ((m_p - m_q)**2)) * torch.exp(-2. * logs_q)
51
+ return kl
52
+
53
+
54
+ def rand_gumbel(shape):
55
+ """Sample from the Gumbel distribution, protect from overflows."""
56
+ uniform_samples = torch.rand(shape) * 0.99998 + 0.00001
57
+ return -torch.log(-torch.log(uniform_samples))
58
+
59
+
60
+ def rand_gumbel_like(x):
61
+ g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device)
62
+ return g
63
+
64
+
65
+ def slice_segments(x, ids_str, segment_size=4):
66
+ ret = torch.zeros_like(x[:, :, :segment_size])
67
+ for i in range(x.size(0)):
68
+ idx_str = ids_str[i]
69
+ idx_end = idx_str + segment_size
70
+ ret[i] = x[i, :, idx_str:idx_end]
71
+ return ret
72
+
73
+
74
+ def rand_slice_segments(x, x_lengths=None, segment_size=4):
75
+ b, d, t = x.size()
76
+ if x_lengths is None:
77
+ x_lengths = t
78
+ ids_str_max = x_lengths - segment_size + 1
79
+ ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)
80
+ ret = slice_segments(x, ids_str, segment_size)
81
+ return ret, ids_str
82
+
83
+
84
+ def rand_spec_segments(x, x_lengths=None, segment_size=4):
85
+ b, d, t = x.size()
86
+ if x_lengths is None:
87
+ x_lengths = t
88
+ ids_str_max = x_lengths - segment_size
89
+ ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)
90
+ ret = slice_segments(x, ids_str, segment_size)
91
+ return ret, ids_str
92
+
93
+
94
+ def get_timing_signal_1d(
95
+ length, channels, min_timescale=1.0, max_timescale=1.0e4):
96
+ position = torch.arange(length, dtype=torch.float)
97
+ num_timescales = channels // 2
98
+ log_timescale_increment = (
99
+ math.log(float(max_timescale) / float(min_timescale)) /
100
+ (num_timescales - 1))
101
+ inv_timescales = min_timescale * torch.exp(
102
+ torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment)
103
+ scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)
104
+ signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)
105
+ signal = F.pad(signal, [0, 0, 0, channels % 2])
106
+ signal = signal.view(1, channels, length)
107
+ return signal
108
+
109
+
110
+ def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):
111
+ b, channels, length = x.size()
112
+ signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
113
+ return x + signal.to(dtype=x.dtype, device=x.device)
114
+
115
+
116
+ def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):
117
+ b, channels, length = x.size()
118
+ signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
119
+ return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)
120
+
121
+
122
+ def subsequent_mask(length):
123
+ mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
124
+ return mask
125
+
126
+
127
+ @torch.jit.script
128
+ def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
129
+ n_channels_int = n_channels[0]
130
+ in_act = input_a + input_b
131
+ t_act = torch.tanh(in_act[:, :n_channels_int, :])
132
+ s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
133
+ acts = t_act * s_act
134
+ return acts
135
+
136
+
137
+ def convert_pad_shape(pad_shape):
138
+ l = pad_shape[::-1]
139
+ pad_shape = [item for sublist in l for item in sublist]
140
+ return pad_shape
141
+
142
+
143
+ def shift_1d(x):
144
+ x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
145
+ return x
146
+
147
+
148
+ def sequence_mask(length, max_length=None):
149
+ if max_length is None:
150
+ max_length = length.max()
151
+ x = torch.arange(max_length, dtype=length.dtype, device=length.device)
152
+ return x.unsqueeze(0) < length.unsqueeze(1)
153
+
154
+
155
+ def generate_path(duration, mask):
156
+ """
157
+ duration: [b, 1, t_x]
158
+ mask: [b, 1, t_y, t_x]
159
+ """
160
+ device = duration.device
161
+
162
+ b, _, t_y, t_x = mask.shape
163
+ cum_duration = torch.cumsum(duration, -1)
164
+
165
+ cum_duration_flat = cum_duration.view(b * t_x)
166
+ path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
167
+ path = path.view(b, t_x, t_y)
168
+ path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
169
+ path = path.unsqueeze(1).transpose(2,3) * mask
170
+ return path
171
+
172
+
173
+ def clip_grad_value_(parameters, clip_value, norm_type=2):
174
+ if isinstance(parameters, torch.Tensor):
175
+ parameters = [parameters]
176
+ parameters = list(filter(lambda p: p.grad is not None, parameters))
177
+ norm_type = float(norm_type)
178
+ if clip_value is not None:
179
+ clip_value = float(clip_value)
180
+
181
+ total_norm = 0
182
+ for p in parameters:
183
+ param_norm = p.grad.data.norm(norm_type)
184
+ total_norm += param_norm.item() ** norm_type
185
+ if clip_value is not None:
186
+ p.grad.data.clamp_(min=-clip_value, max=clip_value)
187
+ total_norm = total_norm ** (1. / norm_type)
188
+ return total_norm
configs/config.json ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "train": {
3
+ "log_interval": 200,
4
+ "eval_interval": 1000,
5
+ "seed": 1234,
6
+ "epochs": 10000,
7
+ "learning_rate": 0.0002,
8
+ "betas": [
9
+ 0.8,
10
+ 0.99
11
+ ],
12
+ "eps": 1e-09,
13
+ "batch_size": 12,
14
+ "fp16_run": false,
15
+ "lr_decay": 0.999875,
16
+ "segment_size": 17920,
17
+ "init_lr_ratio": 1,
18
+ "warmup_epochs": 0,
19
+ "c_mel": 45,
20
+ "c_kl": 1.0,
21
+ "use_sr": true,
22
+ "max_speclen": 384,
23
+ "port": "8001"
24
+ },
25
+ "data": {
26
+ "training_files": "filelists/train.txt",
27
+ "validation_files": "filelists/val.txt",
28
+ "max_wav_value": 32768.0,
29
+ "sampling_rate": 48000,
30
+ "filter_length": 1280,
31
+ "hop_length": 320,
32
+ "win_length": 1280,
33
+ "n_mel_channels": 80,
34
+ "mel_fmin": 0.0,
35
+ "mel_fmax": null
36
+ },
37
+ "model": {
38
+ "inter_channels": 192,
39
+ "hidden_channels": 192,
40
+ "filter_channels": 768,
41
+ "n_heads": 2,
42
+ "n_layers": 6,
43
+ "kernel_size": 3,
44
+ "p_dropout": 0.1,
45
+ "resblock": "1",
46
+ "resblock_kernel_sizes": [
47
+ 3,
48
+ 7,
49
+ 11
50
+ ],
51
+ "resblock_dilation_sizes": [
52
+ [
53
+ 1,
54
+ 3,
55
+ 5
56
+ ],
57
+ [
58
+ 1,
59
+ 3,
60
+ 5
61
+ ],
62
+ [
63
+ 1,
64
+ 3,
65
+ 5
66
+ ]
67
+ ],
68
+ "upsample_rates": [
69
+ 10,
70
+ 8,
71
+ 2,
72
+ 2
73
+ ],
74
+ "upsample_initial_channel": 512,
75
+ "upsample_kernel_sizes": [
76
+ 16,
77
+ 16,
78
+ 4,
79
+ 4
80
+ ],
81
+ "n_layers_q": 3,
82
+ "use_spectral_norm": false,
83
+ "gin_channels": 256,
84
+ "ssl_dim": 256,
85
+ "n_speakers": 2
86
+ },
87
+ "spk": {
88
+ "aqua": 0
89
+ }
90
+ }
data_utils.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import os
3
+ import random
4
+ import numpy as np
5
+ import torch
6
+ import torch.utils.data
7
+
8
+ import commons
9
+ from mel_processing import spectrogram_torch, spec_to_mel_torch
10
+ from utils import load_wav_to_torch, load_filepaths_and_text, transform
11
+
12
+ # import h5py
13
+
14
+
15
+ """Multi speaker version"""
16
+
17
+
18
+ class TextAudioSpeakerLoader(torch.utils.data.Dataset):
19
+ """
20
+ 1) loads audio, speaker_id, text pairs
21
+ 2) normalizes text and converts them to sequences of integers
22
+ 3) computes spectrograms from audio files.
23
+ """
24
+
25
+ def __init__(self, audiopaths, hparams):
26
+ self.audiopaths = load_filepaths_and_text(audiopaths)
27
+ self.max_wav_value = hparams.data.max_wav_value
28
+ self.sampling_rate = hparams.data.sampling_rate
29
+ self.filter_length = hparams.data.filter_length
30
+ self.hop_length = hparams.data.hop_length
31
+ self.win_length = hparams.data.win_length
32
+ self.sampling_rate = hparams.data.sampling_rate
33
+ self.use_sr = hparams.train.use_sr
34
+ self.spec_len = hparams.train.max_speclen
35
+ self.spk_map = hparams.spk
36
+
37
+ random.seed(1234)
38
+ random.shuffle(self.audiopaths)
39
+
40
+ def get_audio(self, filename):
41
+ audio, sampling_rate = load_wav_to_torch(filename)
42
+ if sampling_rate != self.sampling_rate:
43
+ raise ValueError("{} SR doesn't match target {} SR".format(
44
+ sampling_rate, self.sampling_rate))
45
+ audio_norm = audio / self.max_wav_value
46
+ audio_norm = audio_norm.unsqueeze(0)
47
+ spec_filename = filename.replace(".wav", ".spec.pt")
48
+ if os.path.exists(spec_filename):
49
+ spec = torch.load(spec_filename)
50
+ else:
51
+ spec = spectrogram_torch(audio_norm, self.filter_length,
52
+ self.sampling_rate, self.hop_length, self.win_length,
53
+ center=False)
54
+ spec = torch.squeeze(spec, 0)
55
+ torch.save(spec, spec_filename)
56
+
57
+ spk = filename.split(os.sep)[-2]
58
+ spk = torch.LongTensor([self.spk_map[spk]])
59
+
60
+ c = torch.load(filename + ".soft.pt").squeeze(0)
61
+ c = torch.repeat_interleave(c, repeats=3, dim=1)
62
+
63
+ f0 = np.load(filename + ".f0.npy")
64
+ f0 = torch.FloatTensor(f0)
65
+ lmin = min(c.size(-1), spec.size(-1), f0.shape[0])
66
+ assert abs(c.size(-1) - spec.size(-1)) < 4, (c.size(-1), spec.size(-1), f0.shape, filename)
67
+ assert abs(lmin - spec.size(-1)) < 4, (c.size(-1), spec.size(-1), f0.shape)
68
+ assert abs(lmin - c.size(-1)) < 4, (c.size(-1), spec.size(-1), f0.shape)
69
+ spec, c, f0 = spec[:, :lmin], c[:, :lmin], f0[:lmin]
70
+ audio_norm = audio_norm[:, :lmin * self.hop_length]
71
+ _spec, _c, _audio_norm, _f0 = spec, c, audio_norm, f0
72
+ while spec.size(-1) < self.spec_len:
73
+ spec = torch.cat((spec, _spec), -1)
74
+ c = torch.cat((c, _c), -1)
75
+ f0 = torch.cat((f0, _f0), -1)
76
+ audio_norm = torch.cat((audio_norm, _audio_norm), -1)
77
+ start = random.randint(0, spec.size(-1) - self.spec_len)
78
+ end = start + self.spec_len
79
+ spec = spec[:, start:end]
80
+ c = c[:, start:end]
81
+ f0 = f0[start:end]
82
+ audio_norm = audio_norm[:, start * self.hop_length:end * self.hop_length]
83
+
84
+ return c, f0, spec, audio_norm, spk
85
+
86
+ def __getitem__(self, index):
87
+ return self.get_audio(self.audiopaths[index][0])
88
+
89
+ def __len__(self):
90
+ return len(self.audiopaths)
91
+
92
+
93
+ class EvalDataLoader(torch.utils.data.Dataset):
94
+ """
95
+ 1) loads audio, speaker_id, text pairs
96
+ 2) normalizes text and converts them to sequences of integers
97
+ 3) computes spectrograms from audio files.
98
+ """
99
+
100
+ def __init__(self, audiopaths, hparams):
101
+ self.audiopaths = load_filepaths_and_text(audiopaths)
102
+ self.max_wav_value = hparams.data.max_wav_value
103
+ self.sampling_rate = hparams.data.sampling_rate
104
+ self.filter_length = hparams.data.filter_length
105
+ self.hop_length = hparams.data.hop_length
106
+ self.win_length = hparams.data.win_length
107
+ self.sampling_rate = hparams.data.sampling_rate
108
+ self.use_sr = hparams.train.use_sr
109
+ self.audiopaths = self.audiopaths[:5]
110
+ self.spk_map = hparams.spk
111
+
112
+
113
+ def get_audio(self, filename):
114
+ audio, sampling_rate = load_wav_to_torch(filename)
115
+ if sampling_rate != self.sampling_rate:
116
+ raise ValueError("{} SR doesn't match target {} SR".format(
117
+ sampling_rate, self.sampling_rate))
118
+ audio_norm = audio / self.max_wav_value
119
+ audio_norm = audio_norm.unsqueeze(0)
120
+ spec_filename = filename.replace(".wav", ".spec.pt")
121
+ if os.path.exists(spec_filename):
122
+ spec = torch.load(spec_filename)
123
+ else:
124
+ spec = spectrogram_torch(audio_norm, self.filter_length,
125
+ self.sampling_rate, self.hop_length, self.win_length,
126
+ center=False)
127
+ spec = torch.squeeze(spec, 0)
128
+ torch.save(spec, spec_filename)
129
+
130
+ spk = filename.split(os.sep)[-2]
131
+ spk = torch.LongTensor([self.spk_map[spk]])
132
+
133
+ c = torch.load(filename + ".soft.pt").squeeze(0)
134
+
135
+ c = torch.repeat_interleave(c, repeats=3, dim=1)
136
+
137
+ f0 = np.load(filename + ".f0.npy")
138
+ f0 = torch.FloatTensor(f0)
139
+ lmin = min(c.size(-1), spec.size(-1), f0.shape[0])
140
+ assert abs(c.size(-1) - spec.size(-1)) < 4, (c.size(-1), spec.size(-1), f0.shape)
141
+ assert abs(f0.shape[0] - spec.shape[-1]) < 4, (c.size(-1), spec.size(-1), f0.shape)
142
+ spec, c, f0 = spec[:, :lmin], c[:, :lmin], f0[:lmin]
143
+ audio_norm = audio_norm[:, :lmin * self.hop_length]
144
+
145
+ return c, f0, spec, audio_norm, spk
146
+
147
+ def __getitem__(self, index):
148
+ return self.get_audio(self.audiopaths[index][0])
149
+
150
+ def __len__(self):
151
+ return len(self.audiopaths)
152
+
flask_api.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import logging
3
+
4
+ import soundfile
5
+ import torch
6
+ import torchaudio
7
+ from flask import Flask, request, send_file
8
+ from flask_cors import CORS
9
+
10
+ from inference.infer_tool import Svc, RealTimeVC
11
+
12
+ app = Flask(__name__)
13
+
14
+ CORS(app)
15
+
16
+ logging.getLogger('numba').setLevel(logging.WARNING)
17
+
18
+
19
+ @app.route("/voiceChangeModel", methods=["POST"])
20
+ def voice_change_model():
21
+ request_form = request.form
22
+ wave_file = request.files.get("sample", None)
23
+ # 变调信息
24
+ f_pitch_change = float(request_form.get("fPitchChange", 0))
25
+ # DAW所需的采样率
26
+ daw_sample = int(float(request_form.get("sampleRate", 0)))
27
+ speaker_id = int(float(request_form.get("sSpeakId", 0)))
28
+ # http获得wav文件并转换
29
+ input_wav_path = io.BytesIO(wave_file.read())
30
+
31
+ # 模型推理
32
+ if raw_infer:
33
+ out_audio, out_sr = svc_model.infer(speaker_id, f_pitch_change, input_wav_path)
34
+ tar_audio = torchaudio.functional.resample(out_audio, svc_model.target_sample, daw_sample)
35
+ else:
36
+ out_audio = svc.process(svc_model, speaker_id, f_pitch_change, input_wav_path)
37
+ tar_audio = torchaudio.functional.resample(torch.from_numpy(out_audio), svc_model.target_sample, daw_sample)
38
+ # 返回音频
39
+ out_wav_path = io.BytesIO()
40
+ soundfile.write(out_wav_path, tar_audio.cpu().numpy(), daw_sample, format="wav")
41
+ out_wav_path.seek(0)
42
+ return send_file(out_wav_path, download_name="temp.wav", as_attachment=True)
43
+
44
+
45
+ if __name__ == '__main__':
46
+ # 启用则为直接切片合成,False为交叉淡化方式
47
+ # vst插件调整0.3-0.5s切片时间可以降低延迟,直接切片方法会有连接处爆音、交叉淡化会有轻微重叠声音
48
+ # 自行选择能接受的方法,或将vst最大切片时间调整为1s,此处设为Ture,延迟大音质稳定一些
49
+ raw_infer = True
50
+ # 每个模型和config是唯一对应的
51
+ model_name = "logs/48k/G_174000-Copy1.pth"
52
+ config_name = "configs/config.json"
53
+ svc_model = Svc(model_name, config_name)
54
+ svc = RealTimeVC()
55
+ # 此处与vst插件对应,不建议更改
56
+ app.run(port=6842, host="0.0.0.0", debug=False, threaded=False)
hubert/__init__.py ADDED
File without changes
hubert/hubert-soft-0d54a1f4.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e82e7d079df05fe3aa535f6f7d42d309bdae1d2a53324e2b2386c56721f4f649
3
+ size 378435957
hubert/hubert_model.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import random
3
+ from typing import Optional, Tuple
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.nn.functional as t_func
8
+ from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
9
+
10
+
11
+ class Hubert(nn.Module):
12
+ def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
13
+ super().__init__()
14
+ self._mask = mask
15
+ self.feature_extractor = FeatureExtractor()
16
+ self.feature_projection = FeatureProjection()
17
+ self.positional_embedding = PositionalConvEmbedding()
18
+ self.norm = nn.LayerNorm(768)
19
+ self.dropout = nn.Dropout(0.1)
20
+ self.encoder = TransformerEncoder(
21
+ nn.TransformerEncoderLayer(
22
+ 768, 12, 3072, activation="gelu", batch_first=True
23
+ ),
24
+ 12,
25
+ )
26
+ self.proj = nn.Linear(768, 256)
27
+
28
+ self.masked_spec_embed = nn.Parameter(torch.FloatTensor(768).uniform_())
29
+ self.label_embedding = nn.Embedding(num_label_embeddings, 256)
30
+
31
+ def mask(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
32
+ mask = None
33
+ if self.training and self._mask:
34
+ mask = _compute_mask((x.size(0), x.size(1)), 0.8, 10, x.device, 2)
35
+ x[mask] = self.masked_spec_embed.to(x.dtype)
36
+ return x, mask
37
+
38
+ def encode(
39
+ self, x: torch.Tensor, layer: Optional[int] = None
40
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
41
+ x = self.feature_extractor(x)
42
+ x = self.feature_projection(x.transpose(1, 2))
43
+ x, mask = self.mask(x)
44
+ x = x + self.positional_embedding(x)
45
+ x = self.dropout(self.norm(x))
46
+ x = self.encoder(x, output_layer=layer)
47
+ return x, mask
48
+
49
+ def logits(self, x: torch.Tensor) -> torch.Tensor:
50
+ logits = torch.cosine_similarity(
51
+ x.unsqueeze(2),
52
+ self.label_embedding.weight.unsqueeze(0).unsqueeze(0),
53
+ dim=-1,
54
+ )
55
+ return logits / 0.1
56
+
57
+ def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
58
+ x, mask = self.encode(x)
59
+ x = self.proj(x)
60
+ logits = self.logits(x)
61
+ return logits, mask
62
+
63
+
64
+ class HubertSoft(Hubert):
65
+ def __init__(self):
66
+ super().__init__()
67
+
68
+ @torch.inference_mode()
69
+ def units(self, wav: torch.Tensor) -> torch.Tensor:
70
+ wav = t_func.pad(wav, ((400 - 320) // 2, (400 - 320) // 2))
71
+ x, _ = self.encode(wav)
72
+ return self.proj(x)
73
+
74
+
75
+ class FeatureExtractor(nn.Module):
76
+ def __init__(self):
77
+ super().__init__()
78
+ self.conv0 = nn.Conv1d(1, 512, 10, 5, bias=False)
79
+ self.norm0 = nn.GroupNorm(512, 512)
80
+ self.conv1 = nn.Conv1d(512, 512, 3, 2, bias=False)
81
+ self.conv2 = nn.Conv1d(512, 512, 3, 2, bias=False)
82
+ self.conv3 = nn.Conv1d(512, 512, 3, 2, bias=False)
83
+ self.conv4 = nn.Conv1d(512, 512, 3, 2, bias=False)
84
+ self.conv5 = nn.Conv1d(512, 512, 2, 2, bias=False)
85
+ self.conv6 = nn.Conv1d(512, 512, 2, 2, bias=False)
86
+
87
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
88
+ x = t_func.gelu(self.norm0(self.conv0(x)))
89
+ x = t_func.gelu(self.conv1(x))
90
+ x = t_func.gelu(self.conv2(x))
91
+ x = t_func.gelu(self.conv3(x))
92
+ x = t_func.gelu(self.conv4(x))
93
+ x = t_func.gelu(self.conv5(x))
94
+ x = t_func.gelu(self.conv6(x))
95
+ return x
96
+
97
+
98
+ class FeatureProjection(nn.Module):
99
+ def __init__(self):
100
+ super().__init__()
101
+ self.norm = nn.LayerNorm(512)
102
+ self.projection = nn.Linear(512, 768)
103
+ self.dropout = nn.Dropout(0.1)
104
+
105
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
106
+ x = self.norm(x)
107
+ x = self.projection(x)
108
+ x = self.dropout(x)
109
+ return x
110
+
111
+
112
+ class PositionalConvEmbedding(nn.Module):
113
+ def __init__(self):
114
+ super().__init__()
115
+ self.conv = nn.Conv1d(
116
+ 768,
117
+ 768,
118
+ kernel_size=128,
119
+ padding=128 // 2,
120
+ groups=16,
121
+ )
122
+ self.conv = nn.utils.weight_norm(self.conv, name="weight", dim=2)
123
+
124
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
125
+ x = self.conv(x.transpose(1, 2))
126
+ x = t_func.gelu(x[:, :, :-1])
127
+ return x.transpose(1, 2)
128
+
129
+
130
+ class TransformerEncoder(nn.Module):
131
+ def __init__(
132
+ self, encoder_layer: nn.TransformerEncoderLayer, num_layers: int
133
+ ) -> None:
134
+ super(TransformerEncoder, self).__init__()
135
+ self.layers = nn.ModuleList(
136
+ [copy.deepcopy(encoder_layer) for _ in range(num_layers)]
137
+ )
138
+ self.num_layers = num_layers
139
+
140
+ def forward(
141
+ self,
142
+ src: torch.Tensor,
143
+ mask: torch.Tensor = None,
144
+ src_key_padding_mask: torch.Tensor = None,
145
+ output_layer: Optional[int] = None,
146
+ ) -> torch.Tensor:
147
+ output = src
148
+ for layer in self.layers[:output_layer]:
149
+ output = layer(
150
+ output, src_mask=mask, src_key_padding_mask=src_key_padding_mask
151
+ )
152
+ return output
153
+
154
+
155
+ def _compute_mask(
156
+ shape: Tuple[int, int],
157
+ mask_prob: float,
158
+ mask_length: int,
159
+ device: torch.device,
160
+ min_masks: int = 0,
161
+ ) -> torch.Tensor:
162
+ batch_size, sequence_length = shape
163
+
164
+ if mask_length < 1:
165
+ raise ValueError("`mask_length` has to be bigger than 0.")
166
+
167
+ if mask_length > sequence_length:
168
+ raise ValueError(
169
+ f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length} and `sequence_length`: {sequence_length}`"
170
+ )
171
+
172
+ # compute number of masked spans in batch
173
+ num_masked_spans = int(mask_prob * sequence_length / mask_length + random.random())
174
+ num_masked_spans = max(num_masked_spans, min_masks)
175
+
176
+ # make sure num masked indices <= sequence_length
177
+ if num_masked_spans * mask_length > sequence_length:
178
+ num_masked_spans = sequence_length // mask_length
179
+
180
+ # SpecAugment mask to fill
181
+ mask = torch.zeros((batch_size, sequence_length), device=device, dtype=torch.bool)
182
+
183
+ # uniform distribution to sample from, make sure that offset samples are < sequence_length
184
+ uniform_dist = torch.ones(
185
+ (batch_size, sequence_length - (mask_length - 1)), device=device
186
+ )
187
+
188
+ # get random indices to mask
189
+ mask_indices = torch.multinomial(uniform_dist, num_masked_spans)
190
+
191
+ # expand masked indices to masked spans
192
+ mask_indices = (
193
+ mask_indices.unsqueeze(dim=-1)
194
+ .expand((batch_size, num_masked_spans, mask_length))
195
+ .reshape(batch_size, num_masked_spans * mask_length)
196
+ )
197
+ offsets = (
198
+ torch.arange(mask_length, device=device)[None, None, :]
199
+ .expand((batch_size, num_masked_spans, mask_length))
200
+ .reshape(batch_size, num_masked_spans * mask_length)
201
+ )
202
+ mask_idxs = mask_indices + offsets
203
+
204
+ # scatter indices to mask
205
+ mask = mask.scatter(1, mask_idxs, True)
206
+
207
+ return mask
208
+
209
+
210
+ def hubert_soft(
211
+ path: str,
212
+ ) -> HubertSoft:
213
+ r"""HuBERT-Soft from `"A Comparison of Discrete and Soft Speech Units for Improved Voice Conversion"`.
214
+ Args:
215
+ path (str): path of a pretrained model
216
+ """
217
+ hubert = HubertSoft()
218
+ checkpoint = torch.load(path)
219
+ consume_prefix_in_state_dict_if_present(checkpoint, "module.")
220
+ hubert.load_state_dict(checkpoint)
221
+ hubert.eval()
222
+ return hubert
inference/__init__.py ADDED
File without changes
inference/chunks_temp.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"6da25b17631773f3e267d9ea5e90fdf2": {"chunks": {"0": {"slice": true, "split_time": "0,23835"}, "1": {"slice": false, "split_time": "23835,905348"}, "2": {"slice": true, "split_time": "905348,910805"}, "3": {"slice": false, "split_time": "910805,1395266"}, "4": {"slice": true, "split_time": "1395266,1398353"}, "5": {"slice": false, "split_time": "1398353,2637030"}, "6": {"slice": true, "split_time": "2637030,2657548"}, "7": {"slice": false, "split_time": "2657548,3360683"}, "8": {"slice": true, "split_time": "3360683,3363848"}, "9": {"slice": false, "split_time": "3363848,4478614"}, "10": {"slice": true, "split_time": "4478614,4514816"}}, "time": 1670571633}, "90b894a25dfbca42c065e3a27d75a1b7": {"chunks": {"0": {"slice": true, "split_time": "0,24809"}, "1": {"slice": false, "split_time": "24809,905116"}, "2": {"slice": true, "split_time": "905116,910645"}, "3": {"slice": false, "split_time": "910645,1234800"}}, "time": 1670569815}, "c011425d4cb059beeef217ea9c291f67": {"chunks": {"0": {"slice": true, "split_time": "0,4304"}, "1": {"slice": false, "split_time": "4304,335402"}, "2": {"slice": true, "split_time": "335402,643324"}, "3": {"slice": false, "split_time": "643324,1659483"}}, "time": 1670570441}, "b8225c3a47ffea84e7a9639fde444c52": {"chunks": {"0": {"slice": true, "split_time": "0,61578"}, "1": {"slice": false, "split_time": "61578,1970306"}, "2": {"slice": true, "split_time": "1970306,1982351"}, "3": {"slice": false, "split_time": "1982351,3037480"}, "4": {"slice": true, "split_time": "3037480,3044033"}, "5": {"slice": false, "split_time": "3044033,5739816"}, "6": {"slice": true, "split_time": "5739816,5784949"}, "7": {"slice": false, "split_time": "5784949,7315823"}, "8": {"slice": true, "split_time": "7315823,7322762"}, "9": {"slice": false, "split_time": "7322762,9748878"}, "10": {"slice": true, "split_time": "9748878,9828171"}}, "time": 1670573169}, "36ad08d22d6241f08419ba19448bc1f1": {"chunks": {"0": {"slice": false, "split_time": "0,1136029"}, "1": {"slice": true, "split_time": "1136029,1153805"}, "2": {"slice": false, "split_time": "1153805,3491983"}}, "time": 1670644168}, "b884a288b565236668cc310088504c19": {"chunks": {"0": {"slice": false, "split_time": "0,216521"}, "1": {"slice": true, "split_time": "216521,219197"}, "2": {"slice": false, "split_time": "219197,400384"}, "3": {"slice": true, "split_time": "400384,405224"}, "4": {"slice": false, "split_time": "405224,618976"}, "5": {"slice": true, "split_time": "618976,624194"}, "6": {"slice": false, "split_time": "624194,764242"}, "7": {"slice": true, "split_time": "764242,766510"}, "8": {"slice": false, "split_time": "766510,1433828"}, "9": {"slice": true, "split_time": "1433828,1438002"}, "10": {"slice": false, "split_time": "1438002,1573799"}, "11": {"slice": true, "split_time": "1573799,1576760"}, "12": {"slice": false, "split_time": "1576760,1717339"}, "13": {"slice": true, "split_time": "1717339,1720688"}, "14": {"slice": false, "split_time": "1720688,1891282"}, "15": {"slice": true, "split_time": "1891282,1895616"}, "16": {"slice": false, "split_time": "1895616,2302548"}, "17": {"slice": true, "split_time": "2302548,2305292"}, "18": {"slice": false, "split_time": "2305292,2427056"}, "19": {"slice": true, "split_time": "2427056,2428698"}, "20": {"slice": false, "split_time": "2428698,2541785"}, "21": {"slice": true, "split_time": "2541785,2543993"}, "22": {"slice": false, "split_time": "2543993,2764393"}, "23": {"slice": true, "split_time": "2764393,2771788"}, "24": {"slice": false, "split_time": "2771788,2984762"}, "25": {"slice": true, "split_time": "2984762,2990841"}, "26": {"slice": false, "split_time": "2990841,3324911"}, "27": {"slice": true, "split_time": "3324911,3328212"}, "28": {"slice": false, "split_time": "3328212,3613048"}, "29": {"slice": true, "split_time": "3613048,3613552"}, "30": {"slice": false, "split_time": "3613552,4165908"}, "31": {"slice": true, "split_time": "4165908,4168709"}, "32": {"slice": false, "split_time": "4168709,4220263"}, "33": {"slice": true, "split_time": "4220263,4227485"}}, "time": 1670574749}, "9f02a93ae99d971888b35c785eb7d49b": {"chunks": {"0": {"slice": true, "split_time": "0,705669"}, "1": {"slice": false, "split_time": "705669,6527896"}, "2": {"slice": true, "split_time": "6527896,6597762"}, "3": {"slice": false, "split_time": "6597762,9310902"}, "4": {"slice": true, "split_time": "9310902,9314746"}, "5": {"slice": false, "split_time": "9314746,11243041"}, "6": {"slice": true, "split_time": "11243041,11283279"}, "7": {"slice": false, "split_time": "11283279,11346943"}, "8": {"slice": true, "split_time": "11346943,11630411"}}, "time": 1670575576}, "bf323c2270a30894ddfa25b5d3056d69": {"chunks": {"0": {"slice": true, "split_time": "0,705669"}, "1": {"slice": false, "split_time": "705669,3982080"}}, "time": 1670576110}, "26878ada67625dd6335439521f7ac03c": {"chunks": {"0": {"slice": true, "split_time": "0,30461"}, "1": {"slice": false, "split_time": "30461,1581600"}}, "time": 1670687236}, "3b1da6bfd1773aec9a26891f89a3efc4": {"chunks": {"0": {"slice": true, "split_time": "0,9744"}, "1": {"slice": false, "split_time": "9744,2402304"}}, "time": 1670577430}, "2c59bb37d2ddfc8b2b043edcfcbaa906": {"chunks": {"0": {"slice": true, "split_time": "0,19673"}, "1": {"slice": false, "split_time": "19673,1407635"}, "2": {"slice": true, "split_time": "1407635,1455090"}, "3": {"slice": false, "split_time": "1455090,3997397"}, "4": {"slice": true, "split_time": "3997397,4009124"}, "5": {"slice": false, "split_time": "4009124,6527176"}, "6": {"slice": true, "split_time": "6527176,6587813"}, "7": {"slice": false, "split_time": "6587813,9325038"}, "8": {"slice": true, "split_time": "9325038,9341404"}, "9": {"slice": false, "split_time": "9341404,9593839"}, "10": {"slice": true, "split_time": "9593839,9598960"}, "11": {"slice": false, "split_time": "9598960,9987461"}, "12": {"slice": true, "split_time": "9987461,9994148"}, "13": {"slice": false, "split_time": "9994148,10241257"}, "14": {"slice": true, "split_time": "10241257,10243691"}, "15": {"slice": false, "split_time": "10243691,10532345"}, "16": {"slice": true, "split_time": "10532345,10545150"}, "17": {"slice": false, "split_time": "10545150,10999746"}, "18": {"slice": true, "split_time": "10999746,11012824"}, "19": {"slice": false, "split_time": "11012824,11412797"}, "20": {"slice": true, "split_time": "11412797,11632083"}}, "time": 1670583436}, "ac5cb570b28d1bf43db55d3b55b0da49": {"chunks": {"0": {"slice": true, "split_time": "0,46106"}, "1": {"slice": false, "split_time": "46106,1812107"}, "2": {"slice": true, "split_time": "1812107,1821400"}, "3": {"slice": false, "split_time": "1821400,2684212"}, "4": {"slice": true, "split_time": "2684212,2691807"}, "5": {"slice": false, "split_time": "2691807,5278901"}, "6": {"slice": true, "split_time": "5278901,6171752"}, "7": {"slice": false, "split_time": "6171752,6723937"}, "8": {"slice": true, "split_time": "6723937,6727712"}, "9": {"slice": false, "split_time": "6727712,8961094"}, "10": {"slice": true, "split_time": "8961094,9030528"}}, "time": 1670588363}, "c6bd7a95c90241934030c1730662e7cc": {"chunks": {"0": {"slice": true, "split_time": "0,49204"}, "1": {"slice": false, "split_time": "49204,768993"}, "2": {"slice": true, "split_time": "768993,1419710"}, "3": {"slice": false, "split_time": "1419710,1961254"}, "4": {"slice": true, "split_time": "1961254,2002533"}, "5": {"slice": false, "split_time": "2002533,3400434"}, "6": {"slice": true, "split_time": "3400434,4044462"}, "7": {"slice": false, "split_time": "4044462,4586255"}, "8": {"slice": true, "split_time": "4586255,4627965"}, "9": {"slice": false, "split_time": "4627965,6109298"}, "10": {"slice": true, "split_time": "6109298,6754467"}, "11": {"slice": false, "split_time": "6754467,7126180"}, "12": {"slice": true, "split_time": "7126180,7232446"}, "13": {"slice": false, "split_time": "7232446,7510807"}, "14": {"slice": true, "split_time": "7510807,7579500"}, "15": {"slice": false, "split_time": "7579500,7845805"}, "16": {"slice": true, "split_time": "7845805,8321111"}, "17": {"slice": false, "split_time": "8321111,9008414"}, "18": {"slice": true, "split_time": "9008414,9013254"}, "19": {"slice": false, "split_time": "9013254,9329237"}, "20": {"slice": true, "split_time": "9329237,9719592"}, "21": {"slice": false, "split_time": "9719592,10107581"}, "22": {"slice": true, "split_time": "10107581,10113973"}, "23": {"slice": false, "split_time": "10113973,10350874"}, "24": {"slice": true, "split_time": "10350874,10373826"}, "25": {"slice": false, "split_time": "10373826,10600844"}, "26": {"slice": true, "split_time": "10600844,10616456"}, "27": {"slice": false, "split_time": "10616456,10708106"}, "28": {"slice": true, "split_time": "10708106,10749952"}}, "time": 1670606294}, "4b4f0edb689032a6d91572b9250785e7": {"chunks": {"0": {"slice": true, "split_time": "0,185991"}, "1": {"slice": false, "split_time": "185991,914678"}, "2": {"slice": true, "split_time": "914678,922072"}, "3": {"slice": false, "split_time": "922072,3343526"}, "4": {"slice": true, "split_time": "3343526,3346452"}, "5": {"slice": false, "split_time": "3346452,3597657"}, "6": {"slice": true, "split_time": "3597657,3854141"}}, "time": 1670603989}, "3b32214e143c12a9c2087c6f1a6e0079": {"chunks": {"0": {"slice": true, "split_time": "0,1111906"}, "1": {"slice": false, "split_time": "1111906,1384760"}, "2": {"slice": true, "split_time": "1384760,1431263"}, "3": {"slice": false, "split_time": "1431263,1725453"}, "4": {"slice": true, "split_time": "1725453,1772807"}, "5": {"slice": false, "split_time": "1772807,4592249"}, "6": {"slice": true, "split_time": "4592249,4717056"}}, "time": 1670604680}, "e37af0a83a37929baf38aaf41771f666": {"chunks": {"0": {"slice": true, "split_time": "0,712833"}, "1": {"slice": false, "split_time": "712833,968777"}, "2": {"slice": true, "split_time": "968777,1012890"}, "3": {"slice": false, "split_time": "1012890,1302528"}, "4": {"slice": true, "split_time": "1302528,1372173"}, "5": {"slice": false, "split_time": "1372173,1973196"}, "6": {"slice": true, "split_time": "1973196,1976084"}, "7": {"slice": false, "split_time": "1976084,4088114"}, "8": {"slice": true, "split_time": "4088114,4099072"}}, "time": 1670628295}, "1127f4a167db675427156eff884429f5": {"chunks": {"0": {"slice": true, "split_time": "0,718635"}, "1": {"slice": false, "split_time": "718635,1157581"}, "2": {"slice": true, "split_time": "1157581,1172737"}, "3": {"slice": false, "split_time": "1172737,1705170"}, "4": {"slice": true, "split_time": "1705170,1716523"}, "5": {"slice": false, "split_time": "1716523,1960831"}, "6": {"slice": true, "split_time": "1960831,2038462"}, "7": {"slice": false, "split_time": "2038462,2684694"}, "8": {"slice": true, "split_time": "2684694,2707156"}, "9": {"slice": false, "split_time": "2707156,3037090"}, "10": {"slice": true, "split_time": "3037090,3054814"}, "11": {"slice": false, "split_time": "3054814,4308021"}, "12": {"slice": true, "split_time": "4308021,4326415"}, "13": {"slice": false, "split_time": "4326415,4737386"}, "14": {"slice": true, "split_time": "4737386,5415908"}, "15": {"slice": false, "split_time": "5415908,6049275"}, "16": {"slice": true, "split_time": "6049275,6059272"}, "17": {"slice": false, "split_time": "6059272,6665627"}, "18": {"slice": true, "split_time": "6665627,6678679"}, "19": {"slice": false, "split_time": "6678679,8097473"}, "20": {"slice": true, "split_time": "8097473,8141374"}, "21": {"slice": false, "split_time": "8141374,8897047"}, "22": {"slice": true, "split_time": "8897047,9206103"}, "23": {"slice": false, "split_time": "9206103,9683995"}, "24": {"slice": true, "split_time": "9683995,9699995"}, "25": {"slice": false, "split_time": "9699995,10367622"}, "26": {"slice": true, "split_time": "10367622,10373657"}, "27": {"slice": false, "split_time": "10373657,10914289"}, "28": {"slice": true, "split_time": "10914289,12250463"}, "29": {"slice": false, "split_time": "12250463,12309513"}, "30": {"slice": true, "split_time": "12309513,12788736"}}, "time": 1670658498}, "488951d97170e877bdef769489b09113": {"chunks": {"0": {"slice": true, "split_time": "0,1516829"}, "1": {"slice": false, "split_time": "1516829,3428647"}, "2": {"slice": true, "split_time": "3428647,3434675"}, "3": {"slice": false, "split_time": "3434675,4541897"}, "4": {"slice": true, "split_time": "4541897,4556959"}, "5": {"slice": false, "split_time": "4556959,5514779"}, "6": {"slice": true, "split_time": "5514779,6385599"}, "7": {"slice": false, "split_time": "6385599,8295053"}, "8": {"slice": true, "split_time": "8295053,8312032"}, "9": {"slice": false, "split_time": "8312032,11213869"}, "10": {"slice": true, "split_time": "11213869,11339533"}, "11": {"slice": false, "split_time": "11339533,11810282"}, "12": {"slice": true, "split_time": "11810282,12298240"}}, "time": 1670688385}, "355d47ef6a1b96547e9cca1a0391c85c": {"chunks": {"0": {"slice": true, "split_time": "0,36661"}, "1": {"slice": false, "split_time": "36661,630669"}, "2": {"slice": true, "split_time": "630669,680688"}, "3": {"slice": false, "split_time": "680688,1464986"}, "4": {"slice": true, "split_time": "1464986,1585875"}, "5": {"slice": false, "split_time": "1585875,1843986"}, "6": {"slice": true, "split_time": "1843986,1921120"}, "7": {"slice": false, "split_time": "1921120,2490103"}, "8": {"slice": true, "split_time": "2490103,2536079"}, "9": {"slice": false, "split_time": "2536079,3149312"}, "10": {"slice": true, "split_time": "3149312,3185080"}, "11": {"slice": false, "split_time": "3185080,3709183"}, "12": {"slice": true, "split_time": "3709183,3800117"}, "13": {"slice": false, "split_time": "3800117,4508883"}, "14": {"slice": true, "split_time": "4508883,4582236"}, "15": {"slice": false, "split_time": "4582236,6021956"}}, "time": 1670689010}, "d6c8b7cf8a4245702985ac5be1b854ee": {"chunks": {"0": {"slice": true, "split_time": "0,253821"}, "1": {"slice": false, "split_time": "253821,617754"}, "2": {"slice": true, "split_time": "617754,645464"}, "3": {"slice": false, "split_time": "645464,1772902"}, "4": {"slice": true, "split_time": "1772902,1958678"}, "5": {"slice": false, "split_time": "1958678,4417999"}, "6": {"slice": true, "split_time": "4417999,4487483"}, "7": {"slice": false, "split_time": "4487483,4777645"}, "8": {"slice": true, "split_time": "4777645,4786501"}, "9": {"slice": false, "split_time": "4786501,7052109"}, "10": {"slice": true, "split_time": "7052109,7511077"}, "11": {"slice": false, "split_time": "7511077,9717344"}, "12": {"slice": true, "split_time": "9717344,10189630"}, "13": {"slice": false, "split_time": "10189630,10402183"}, "14": {"slice": true, "split_time": "10402183,10442752"}}, "time": 1670692231}, "06e514729c1002271fcf998844ad5830": {"chunks": {"0": {"slice": true, "split_time": "0,492335"}, "1": {"slice": false, "split_time": "492335,729432"}, "2": {"slice": true, "split_time": "729432,991792"}, "3": {"slice": false, "split_time": "991792,1812379"}, "4": {"slice": true, "split_time": "1812379,1852379"}, "5": {"slice": false, "split_time": "1852379,2572754"}, "6": {"slice": true, "split_time": "2572754,2699840"}, "7": {"slice": false, "split_time": "2699840,2922491"}, "8": {"slice": true, "split_time": "2922491,3000707"}, "9": {"slice": false, "split_time": "3000707,3533124"}, "10": {"slice": true, "split_time": "3533124,3575117"}, "11": {"slice": false, "split_time": "3575117,4140678"}, "12": {"slice": true, "split_time": "4140678,4144993"}, "13": {"slice": false, "split_time": "4144993,4648454"}, "14": {"slice": true, "split_time": "4648454,4713755"}, "15": {"slice": false, "split_time": "4713755,5376955"}, "16": {"slice": true, "split_time": "5376955,5439135"}, "17": {"slice": false, "split_time": "5439135,6808121"}, "18": {"slice": true, "split_time": "6808121,7155814"}, "19": {"slice": false, "split_time": "7155814,7431383"}, "20": {"slice": true, "split_time": "7431383,7436381"}, "21": {"slice": false, "split_time": "7436381,7713354"}, "22": {"slice": true, "split_time": "7713354,7722772"}, "23": {"slice": false, "split_time": "7722772,8255613"}, "24": {"slice": true, "split_time": "8255613,8289478"}, "25": {"slice": false, "split_time": "8289478,8807530"}, "26": {"slice": true, "split_time": "8807530,8861466"}, "27": {"slice": false, "split_time": "8861466,11559289"}, "28": {"slice": true, "split_time": "11559289,11579820"}, "29": {"slice": false, "split_time": "11579820,12102866"}, "30": {"slice": true, "split_time": "12102866,12310228"}, "31": {"slice": false, "split_time": "12310228,14242877"}, "32": {"slice": true, "split_time": "14242877,16470528"}}, "time": 1670694818}, "206f3ed94957c275404f384d6b19dde1": {"chunks": {"0": {"slice": true, "split_time": "0,21898"}, "1": {"slice": false, "split_time": "21898,541417"}, "2": {"slice": true, "split_time": "541417,922867"}, "3": {"slice": false, "split_time": "922867,1392503"}, "4": {"slice": true, "split_time": "1392503,1405901"}, "5": {"slice": false, "split_time": "1405901,1627345"}, "6": {"slice": true, "split_time": "1627345,1633183"}, "7": {"slice": false, "split_time": "1633183,1900663"}, "8": {"slice": true, "split_time": "1900663,1906756"}, "9": {"slice": false, "split_time": "1906756,2813575"}, "10": {"slice": true, "split_time": "2813575,2835695"}, "11": {"slice": false, "split_time": "2835695,3620910"}, "12": {"slice": true, "split_time": "3620910,3627896"}, "13": {"slice": false, "split_time": "3627896,4413893"}, "14": {"slice": true, "split_time": "4413893,4420556"}, "15": {"slice": false, "split_time": "4420556,4873361"}, "16": {"slice": true, "split_time": "4873361,4883277"}, "17": {"slice": false, "split_time": "4883277,5143983"}, "18": {"slice": true, "split_time": "5143983,5159518"}, "19": {"slice": false, "split_time": "5159518,6804276"}, "20": {"slice": true, "split_time": "6804276,6810099"}, "21": {"slice": false, "split_time": "6810099,8356887"}, "22": {"slice": true, "split_time": "8356887,8445078"}, "23": {"slice": false, "split_time": "8445078,9662214"}, "24": {"slice": true, "split_time": "9662214,9915170"}, "25": {"slice": false, "split_time": "9915170,10712473"}, "26": {"slice": true, "split_time": "10712473,10976256"}}, "time": 1670696167}, "8a58e2c47ef7998f534d18aedb26d104": {"chunks": {"0": {"slice": true, "split_time": "0,1016974"}, "1": {"slice": false, "split_time": "1016974,4183341"}, "2": {"slice": true, "split_time": "4183341,4195234"}, "3": {"slice": false, "split_time": "4195234,4563111"}, "4": {"slice": true, "split_time": "4563111,4566193"}, "5": {"slice": false, "split_time": "4566193,7734892"}, "6": {"slice": true, "split_time": "7734892,7740172"}, "7": {"slice": false, "split_time": "7740172,8110737"}, "8": {"slice": true, "split_time": "8110737,8120631"}, "9": {"slice": false, "split_time": "8120631,9762874"}, "10": {"slice": true, "split_time": "9762874,9806974"}, "11": {"slice": false, "split_time": "9806974,10232975"}, "12": {"slice": true, "split_time": "10232975,10261053"}, "13": {"slice": false, "split_time": "10261053,10703727"}, "14": {"slice": true, "split_time": "10703727,11484160"}}, "time": 1670698961}, "79fef7af12d80db21f1d449bc8e61b47": {"chunks": {"0": {"slice": true, "split_time": "0,599709"}, "1": {"slice": false, "split_time": "599709,1514834"}, "2": {"slice": true, "split_time": "1514834,1524038"}, "3": {"slice": false, "split_time": "1524038,3814846"}, "4": {"slice": true, "split_time": "3814846,3835226"}, "5": {"slice": false, "split_time": "3835226,7062348"}, "6": {"slice": true, "split_time": "7062348,7129100"}, "7": {"slice": false, "split_time": "7129100,7505629"}, "8": {"slice": true, "split_time": "7505629,7601940"}, "9": {"slice": false, "split_time": "7601940,9801911"}, "10": {"slice": true, "split_time": "9801911,10867200"}}, "time": 1670700629}, "3b55088bb8a3066013ddac86fd55e2ad": {"chunks": {"0": {"slice": true, "split_time": "0,624919"}, "1": {"slice": false, "split_time": "624919,905397"}, "2": {"slice": true, "split_time": "905397,918211"}, "3": {"slice": false, "split_time": "918211,1512000"}, "4": {"slice": true, "split_time": "1512000,1527441"}, "5": {"slice": false, "split_time": "1527441,2424306"}, "6": {"slice": true, "split_time": "2424306,2432801"}, "7": {"slice": false, "split_time": "2432801,3820594"}, "8": {"slice": true, "split_time": "3820594,3840607"}, "9": {"slice": false, "split_time": "3840607,4104884"}, "10": {"slice": true, "split_time": "4104884,4114263"}, "11": {"slice": false, "split_time": "4114263,5027433"}, "12": {"slice": true, "split_time": "5027433,5036666"}, "13": {"slice": false, "split_time": "5036666,7053171"}, "14": {"slice": true, "split_time": "7053171,7604908"}, "15": {"slice": false, "split_time": "7604908,8236806"}, "16": {"slice": true, "split_time": "8236806,8244096"}, "17": {"slice": false, "split_time": "8244096,9793094"}, "18": {"slice": true, "split_time": "9793094,10867200"}}, "time": 1670702000}, "82c947cb69a1be602676351b52d7ee80": {"chunks": {"0": {"slice": true, "split_time": "0,500454"}, "1": {"slice": false, "split_time": "500454,3450969"}, "2": {"slice": true, "split_time": "3450969,3801869"}, "3": {"slice": false, "split_time": "3801869,5043540"}, "4": {"slice": true, "split_time": "5043540,5308663"}, "5": {"slice": false, "split_time": "5308663,6079824"}, "6": {"slice": true, "split_time": "6079824,6256768"}, "7": {"slice": false, "split_time": "6256768,6944231"}, "8": {"slice": true, "split_time": "6944231,6950001"}, "9": {"slice": false, "split_time": "6950001,8637874"}, "10": {"slice": true, "split_time": "8637874,9378240"}}, "time": 1670706107}, "1b8f9bd7b27be8b597ca81e1eea2c42e": {"chunks": {"0": {"slice": true, "split_time": "0,9110"}, "1": {"slice": false, "split_time": "9110,705883"}, "2": {"slice": true, "split_time": "705883,718912"}, "3": {"slice": false, "split_time": "718912,4361016"}, "4": {"slice": true, "split_time": "4361016,4483527"}, "5": {"slice": false, "split_time": "4483527,8236744"}, "6": {"slice": true, "split_time": "8236744,8242271"}, "7": {"slice": false, "split_time": "8242271,8922519"}, "8": {"slice": true, "split_time": "8922519,10047781"}, "9": {"slice": false, "split_time": "10047781,11095794"}, "10": {"slice": true, "split_time": "11095794,11111120"}, "11": {"slice": false, "split_time": "11111120,14067827"}, "12": {"slice": true, "split_time": "14067827,15011040"}}, "time": 1670743675}, "d00da3c641d6ffb90f378fb124158474": {"chunks": {"0": {"slice": true, "split_time": "0,49890"}, "1": {"slice": false, "split_time": "49890,541445"}, "2": {"slice": true, "split_time": "541445,890954"}, "3": {"slice": false, "split_time": "890954,6800207"}, "4": {"slice": true, "split_time": "6800207,6820577"}, "5": {"slice": false, "split_time": "6820577,9448427"}, "6": {"slice": true, "split_time": "9448427,9711360"}}, "time": 1670766134}, "a02e853cfdd66de6264fa2dbdcf7bbb3": {"chunks": {"0": {"slice": true, "split_time": "0,49890"}, "1": {"slice": false, "split_time": "49890,541445"}, "2": {"slice": true, "split_time": "541445,890954"}, "3": {"slice": false, "split_time": "890954,3592747"}}, "time": 1670766345}, "e17e7721e276f0f2198e8b37b5757f8c": {"chunks": {"0": {"slice": true, "split_time": "0,3619457"}, "1": {"slice": false, "split_time": "3619457,6800207"}, "2": {"slice": true, "split_time": "6800207,6820577"}, "3": {"slice": false, "split_time": "6820577,9448427"}, "4": {"slice": true, "split_time": "9448427,9711360"}}, "time": 1670766536}, "24992cb6abdfd24fe115d7b3bdb6a77a": {"chunks": {"0": {"slice": true, "split_time": "0,1140146"}, "1": {"slice": false, "split_time": "1140146,4513827"}, "2": {"slice": true, "split_time": "4513827,4522460"}, "3": {"slice": false, "split_time": "4522460,7854253"}, "4": {"slice": true, "split_time": "7854253,8012303"}, "5": {"slice": false, "split_time": "8012303,8371267"}, "6": {"slice": true, "split_time": "8371267,8674359"}, "7": {"slice": false, "split_time": "8674359,10364809"}, "8": {"slice": true, "split_time": "10364809,12002400"}}, "time": 1670859513}, "d10881af08a0d90a7517585454d22674": {"chunks": {"0": {"slice": true, "split_time": "0,55515"}, "1": {"slice": false, "split_time": "55515,1810232"}, "2": {"slice": true, "split_time": "1810232,1821386"}, "3": {"slice": false, "split_time": "1821386,2687101"}, "4": {"slice": true, "split_time": "2687101,2690771"}, "5": {"slice": false, "split_time": "2690771,5273988"}, "6": {"slice": true, "split_time": "5273988,6165351"}, "7": {"slice": false, "split_time": "6165351,6721480"}, "8": {"slice": true, "split_time": "6721480,6727610"}, "9": {"slice": false, "split_time": "6727610,8962706"}, "10": {"slice": true, "split_time": "8962706,9029280"}}, "time": 1670863486}, "d6aaa656f3dfa79175dd7da1abfaa169": {"chunks": {"0": {"slice": true, "split_time": "0,1058932"}, "1": {"slice": false, "split_time": "1058932,1349051"}, "2": {"slice": true, "split_time": "1349051,1368137"}, "3": {"slice": false, "split_time": "1368137,1662781"}, "4": {"slice": true, "split_time": "1662781,1676436"}, "5": {"slice": false, "split_time": "1676436,2158243"}, "6": {"slice": true, "split_time": "2158243,2162622"}, "7": {"slice": false, "split_time": "2162622,2873063"}, "8": {"slice": true, "split_time": "2873063,2951428"}, "9": {"slice": false, "split_time": "2951428,3262830"}, "10": {"slice": true, "split_time": "3262830,3278072"}, "11": {"slice": false, "split_time": "3278072,3570154"}, "12": {"slice": true, "split_time": "3570154,3591188"}, "13": {"slice": false, "split_time": "3591188,3880090"}, "14": {"slice": true, "split_time": "3880090,3895745"}, "15": {"slice": false, "split_time": "3895745,4368396"}, "16": {"slice": true, "split_time": "4368396,4382892"}, "17": {"slice": false, "split_time": "4382892,4743754"}, "18": {"slice": true, "split_time": "4743754,4747764"}, "19": {"slice": false, "split_time": "4747764,5066193"}, "20": {"slice": true, "split_time": "5066193,5072951"}, "21": {"slice": false, "split_time": "5072951,5240665"}, "22": {"slice": true, "split_time": "5240665,6091680"}}, "time": 1670868921}, "834fb6eb0a9e8af2d8e75a2a97531b34": {"chunks": {"0": {"slice": false, "split_time": "0,144312"}}, "time": 1670939080}, "8170f5afd18e1501b5dbb07ffd008152": {"chunks": {"0": {"slice": true, "split_time": "0,519292"}, "1": {"slice": false, "split_time": "519292,1178914"}, "2": {"slice": true, "split_time": "1178914,1180942"}, "3": {"slice": false, "split_time": "1180942,1861164"}, "4": {"slice": true, "split_time": "1861164,1876075"}, "5": {"slice": false, "split_time": "1876075,2395697"}, "6": {"slice": true, "split_time": "2395697,2401759"}, "7": {"slice": false, "split_time": "2401759,3072500"}, "8": {"slice": true, "split_time": "3072500,3571954"}, "9": {"slice": false, "split_time": "3571954,4107039"}, "10": {"slice": true, "split_time": "4107039,4116965"}, "11": {"slice": false, "split_time": "4116965,4362326"}, "12": {"slice": true, "split_time": "4362326,4367003"}, "13": {"slice": false, "split_time": "4367003,4904071"}, "14": {"slice": true, "split_time": "4904071,4908341"}, "15": {"slice": false, "split_time": "4908341,6337673"}, "16": {"slice": true, "split_time": "6337673,6348520"}, "17": {"slice": false, "split_time": "6348520,6602318"}, "18": {"slice": true, "split_time": "6602318,6609065"}, "19": {"slice": false, "split_time": "6609065,7287032"}, "20": {"slice": true, "split_time": "7287032,7677135"}, "21": {"slice": false, "split_time": "7677135,8138276"}, "22": {"slice": true, "split_time": "8138276,8159058"}, "23": {"slice": false, "split_time": "8159058,8996050"}, "24": {"slice": true, "split_time": "8996050,9751680"}}, "time": 1671033273}, "8ca28e39078a405a79203976e468c50b": {"chunks": {"0": {"slice": true, "split_time": "0,497242"}, "1": {"slice": false, "split_time": "497242,1181163"}, "2": {"slice": true, "split_time": "1181163,1189671"}, "3": {"slice": false, "split_time": "1189671,1849697"}, "4": {"slice": true, "split_time": "1849697,1856537"}, "5": {"slice": false, "split_time": "1856537,3073808"}, "6": {"slice": true, "split_time": "3073808,3557665"}, "7": {"slice": false, "split_time": "3557665,4220637"}, "8": {"slice": true, "split_time": "4220637,4221887"}, "9": {"slice": false, "split_time": "4221887,6334512"}, "10": {"slice": true, "split_time": "6334512,6344041"}, "11": {"slice": false, "split_time": "6344041,6594961"}, "12": {"slice": true, "split_time": "6594961,6598932"}, "13": {"slice": false, "split_time": "6598932,7262331"}, "14": {"slice": true, "split_time": "7262331,7667422"}, "15": {"slice": false, "split_time": "7667422,8133291"}, "16": {"slice": true, "split_time": "8133291,8146462"}, "17": {"slice": false, "split_time": "8146462,8995577"}, "18": {"slice": true, "split_time": "8995577,9748320"}}, "time": 1671036817}, "37add5fae144aabb15b2698a775acb9f": {"chunks": {"0": {"slice": true, "split_time": "0,552464"}, "1": {"slice": false, "split_time": "552464,1664737"}, "2": {"slice": true, "split_time": "1664737,1713934"}, "3": {"slice": false, "split_time": "1713934,2128629"}, "4": {"slice": true, "split_time": "2128629,2190888"}, "5": {"slice": false, "split_time": "2190888,2467571"}, "6": {"slice": true, "split_time": "2467571,2492274"}, "7": {"slice": false, "split_time": "2492274,2786017"}, "8": {"slice": true, "split_time": "2786017,2888014"}, "9": {"slice": false, "split_time": "2888014,3126127"}, "10": {"slice": true, "split_time": "3126127,3192892"}, "11": {"slice": false, "split_time": "3192892,3462081"}, "12": {"slice": true, "split_time": "3462081,3510231"}, "13": {"slice": false, "split_time": "3510231,4088592"}, "14": {"slice": true, "split_time": "4088592,4131082"}, "15": {"slice": false, "split_time": "4131082,5405140"}, "16": {"slice": true, "split_time": "5405140,5444945"}, "17": {"slice": false, "split_time": "5444945,5744967"}, "18": {"slice": true, "split_time": "5744967,5958048"}, "19": {"slice": false, "split_time": "5958048,6530239"}, "20": {"slice": true, "split_time": "6530239,6583390"}, "21": {"slice": false, "split_time": "6583390,6858361"}, "22": {"slice": true, "split_time": "6858361,6902846"}, "23": {"slice": false, "split_time": "6902846,8834591"}, "24": {"slice": true, "split_time": "8834591,8837998"}, "25": {"slice": false, "split_time": "8837998,9132266"}, "26": {"slice": true, "split_time": "9132266,9668615"}, "27": {"slice": false, "split_time": "9668615,10936654"}, "28": {"slice": true, "split_time": "10936654,10951534"}, "29": {"slice": false, "split_time": "10951534,11236384"}, "30": {"slice": true, "split_time": "11236384,11381600"}, "31": {"slice": false, "split_time": "11381600,11577220"}, "32": {"slice": true, "split_time": "11577220,12037440"}}, "time": 1671109941}, "93d732f016d67271349fba5d1e75c18d": {"chunks": {"0": {"slice": true, "split_time": "0,8804"}, "1": {"slice": false, "split_time": "8804,438688"}, "2": {"slice": true, "split_time": "438688,486543"}, "3": {"slice": false, "split_time": "486543,1870403"}, "4": {"slice": true, "split_time": "1870403,1877776"}, "5": {"slice": false, "split_time": "1877776,3930315"}, "6": {"slice": true, "split_time": "3930315,4063338"}, "7": {"slice": false, "split_time": "4063338,4394494"}, "8": {"slice": true, "split_time": "4394494,4399789"}, "9": {"slice": false, "split_time": "4399789,5046717"}, "10": {"slice": true, "split_time": "5046717,5059510"}, "11": {"slice": false, "split_time": "5059510,5621793"}, "12": {"slice": true, "split_time": "5621793,5633688"}, "13": {"slice": false, "split_time": "5633688,6917893"}, "14": {"slice": true, "split_time": "6917893,6923244"}, "15": {"slice": false, "split_time": "6923244,7553373"}, "16": {"slice": true, "split_time": "7553373,7689423"}, "17": {"slice": false, "split_time": "7689423,8079372"}, "18": {"slice": true, "split_time": "8079372,8080948"}, "19": {"slice": false, "split_time": "8080948,8344057"}, "20": {"slice": true, "split_time": "8344057,8383507"}, "21": {"slice": false, "split_time": "8383507,8862061"}, "22": {"slice": true, "split_time": "8862061,8865820"}, "23": {"slice": false, "split_time": "8865820,9257710"}, "24": {"slice": true, "split_time": "9257710,9370835"}, "25": {"slice": false, "split_time": "9370835,10125170"}, "26": {"slice": true, "split_time": "10125170,10142843"}, "27": {"slice": false, "split_time": "10142843,11858753"}, "28": {"slice": true, "split_time": "11858753,12052800"}}, "time": 1671113987}, "751d0ea9f160787c40c810f367290353": {"chunks": {"0": {"slice": true, "split_time": "0,1579118"}, "1": {"slice": false, "split_time": "1579118,1820807"}, "2": {"slice": true, "split_time": "1820807,1873005"}, "3": {"slice": false, "split_time": "1873005,2144972"}, "4": {"slice": true, "split_time": "2144972,2176539"}, "5": {"slice": false, "split_time": "2176539,2486160"}, "6": {"slice": true, "split_time": "2486160,2489237"}, "7": {"slice": false, "split_time": "2489237,4090074"}, "8": {"slice": true, "split_time": "4090074,4450548"}, "9": {"slice": false, "split_time": "4450548,4714769"}, "10": {"slice": true, "split_time": "4714769,4751693"}, "11": {"slice": false, "split_time": "4751693,5019002"}, "12": {"slice": true, "split_time": "5019002,5050186"}, "13": {"slice": false, "split_time": "5050186,5356688"}, "14": {"slice": true, "split_time": "5356688,5365172"}, "15": {"slice": false, "split_time": "5365172,6967578"}, "16": {"slice": true, "split_time": "6967578,7620170"}, "17": {"slice": false, "split_time": "7620170,8820345"}, "18": {"slice": true, "split_time": "8820345,8834237"}, "19": {"slice": false, "split_time": "8834237,10763919"}, "20": {"slice": true, "split_time": "10763919,10780703"}, "21": {"slice": false, "split_time": "10780703,10930737"}, "22": {"slice": true, "split_time": "10930737,11670240"}}, "time": 1671122543}, "01160d6a8923cb22b9fcb057152d77c4": {"chunks": {"0": {"slice": true, "split_time": "0,1570889"}, "1": {"slice": false, "split_time": "1570889,1818327"}, "2": {"slice": true, "split_time": "1818327,1865958"}, "3": {"slice": false, "split_time": "1865958,2142600"}, "4": {"slice": true, "split_time": "2142600,2179347"}, "5": {"slice": false, "split_time": "2179347,2482440"}, "6": {"slice": true, "split_time": "2482440,2489004"}, "7": {"slice": false, "split_time": "2489004,4083686"}, "8": {"slice": true, "split_time": "4083686,4448991"}, "9": {"slice": false, "split_time": "4448991,4713912"}, "10": {"slice": true, "split_time": "4713912,4755720"}, "11": {"slice": false, "split_time": "4755720,5015037"}, "12": {"slice": true, "split_time": "5015037,5046087"}, "13": {"slice": false, "split_time": "5046087,5357051"}, "14": {"slice": true, "split_time": "5357051,5362838"}, "15": {"slice": false, "split_time": "5362838,6971462"}, "16": {"slice": true, "split_time": "6971462,7615732"}, "17": {"slice": false, "split_time": "7615732,10929758"}, "18": {"slice": true, "split_time": "10929758,11664480"}}, "time": 1671124339}, "5cbf5f07cf04349c7c9b184e3f964024": {"chunks": {"0": {"slice": true, "split_time": "0,691826"}, "1": {"slice": false, "split_time": "691826,1876389"}, "2": {"slice": true, "split_time": "1876389,1911382"}, "3": {"slice": false, "split_time": "1911382,4282343"}, "4": {"slice": true, "split_time": "4282343,4517196"}, "5": {"slice": false, "split_time": "4517196,5711146"}, "6": {"slice": true, "split_time": "5711146,5741551"}, "7": {"slice": false, "split_time": "5741551,8086325"}, "8": {"slice": true, "split_time": "8086325,9003110"}, "9": {"slice": false, "split_time": "9003110,11470072"}, "10": {"slice": true, "split_time": "11470072,13332960"}}, "time": 1671238083}, "e64b595ad8810c907b25d12bd57c3904": {"chunks": {"0": {"slice": true, "split_time": "0,36395"}, "1": {"slice": false, "split_time": "36395,1392029"}, "2": {"slice": true, "split_time": "1392029,1936181"}, "3": {"slice": false, "split_time": "1936181,3142145"}, "4": {"slice": true, "split_time": "3142145,3167534"}, "5": {"slice": false, "split_time": "3167534,5527939"}, "6": {"slice": true, "split_time": "5527939,5576252"}, "7": {"slice": false, "split_time": "5576252,6960530"}, "8": {"slice": true, "split_time": "6960530,6988768"}, "9": {"slice": false, "split_time": "6988768,9356930"}, "10": {"slice": true, "split_time": "9356930,9800850"}, "11": {"slice": false, "split_time": "9800850,12723584"}, "12": {"slice": true, "split_time": "12723584,12892059"}, "13": {"slice": false, "split_time": "12892059,13545240"}, "14": {"slice": true, "split_time": "13545240,13627603"}, "15": {"slice": false, "split_time": "13627603,14337070"}, "16": {"slice": true, "split_time": "14337070,14595072"}}, "time": 1671245700}}
inference/infer_tool.py ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import json
3
+ import logging
4
+ import os
5
+ import time
6
+ from pathlib import Path
7
+
8
+ import librosa
9
+ import maad
10
+ import numpy as np
11
+ # import onnxruntime
12
+ import parselmouth
13
+ import soundfile
14
+ import torch
15
+ import torchaudio
16
+
17
+ from hubert import hubert_model
18
+ import utils
19
+ from models import SynthesizerTrn
20
+
21
+ logging.getLogger('matplotlib').setLevel(logging.WARNING)
22
+
23
+
24
+ def read_temp(file_name):
25
+ if not os.path.exists(file_name):
26
+ with open(file_name, "w") as f:
27
+ f.write(json.dumps({"info": "temp_dict"}))
28
+ return {}
29
+ else:
30
+ try:
31
+ with open(file_name, "r") as f:
32
+ data = f.read()
33
+ data_dict = json.loads(data)
34
+ if os.path.getsize(file_name) > 50 * 1024 * 1024:
35
+ f_name = file_name.split("/")[-1]
36
+ print(f"clean {f_name}")
37
+ for wav_hash in list(data_dict.keys()):
38
+ if int(time.time()) - int(data_dict[wav_hash]["time"]) > 14 * 24 * 3600:
39
+ del data_dict[wav_hash]
40
+ except Exception as e:
41
+ print(e)
42
+ print(f"{file_name} error,auto rebuild file")
43
+ data_dict = {"info": "temp_dict"}
44
+ return data_dict
45
+
46
+
47
+ def write_temp(file_name, data):
48
+ with open(file_name, "w") as f:
49
+ f.write(json.dumps(data))
50
+
51
+
52
+ def timeit(func):
53
+ def run(*args, **kwargs):
54
+ t = time.time()
55
+ res = func(*args, **kwargs)
56
+ print('executing \'%s\' costed %.3fs' % (func.__name__, time.time() - t))
57
+ return res
58
+
59
+ return run
60
+
61
+
62
+ def format_wav(audio_path):
63
+ if Path(audio_path).suffix == '.wav':
64
+ return
65
+ raw_audio, raw_sample_rate = librosa.load(audio_path, mono=True, sr=None)
66
+ soundfile.write(Path(audio_path).with_suffix(".wav"), raw_audio, raw_sample_rate)
67
+
68
+
69
+ def get_end_file(dir_path, end):
70
+ file_lists = []
71
+ for root, dirs, files in os.walk(dir_path):
72
+ files = [f for f in files if f[0] != '.']
73
+ dirs[:] = [d for d in dirs if d[0] != '.']
74
+ for f_file in files:
75
+ if f_file.endswith(end):
76
+ file_lists.append(os.path.join(root, f_file).replace("\\", "/"))
77
+ return file_lists
78
+
79
+
80
+ def get_md5(content):
81
+ return hashlib.new("md5", content).hexdigest()
82
+
83
+
84
+ def resize2d_f0(x, target_len):
85
+ source = np.array(x)
86
+ source[source < 0.001] = np.nan
87
+ target = np.interp(np.arange(0, len(source) * target_len, len(source)) / target_len, np.arange(0, len(source)),
88
+ source)
89
+ res = np.nan_to_num(target)
90
+ return res
91
+
92
+ def get_f0(x, p_len,f0_up_key=0):
93
+
94
+ time_step = 160 / 16000 * 1000
95
+ f0_min = 50
96
+ f0_max = 1100
97
+ f0_mel_min = 1127 * np.log(1 + f0_min / 700)
98
+ f0_mel_max = 1127 * np.log(1 + f0_max / 700)
99
+
100
+ f0 = parselmouth.Sound(x, 16000).to_pitch_ac(
101
+ time_step=time_step / 1000, voicing_threshold=0.6,
102
+ pitch_floor=f0_min, pitch_ceiling=f0_max).selected_array['frequency']
103
+
104
+ pad_size=(p_len - len(f0) + 1) // 2
105
+ if(pad_size>0 or p_len - len(f0) - pad_size>0):
106
+ f0 = np.pad(f0,[[pad_size,p_len - len(f0) - pad_size]], mode='constant')
107
+
108
+ f0 *= pow(2, f0_up_key / 12)
109
+ f0_mel = 1127 * np.log(1 + f0 / 700)
110
+ f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / (f0_mel_max - f0_mel_min) + 1
111
+ f0_mel[f0_mel <= 1] = 1
112
+ f0_mel[f0_mel > 255] = 255
113
+ f0_coarse = np.rint(f0_mel).astype(np.int)
114
+ return f0_coarse, f0
115
+
116
+ def clean_pitch(input_pitch):
117
+ num_nan = np.sum(input_pitch == 1)
118
+ if num_nan / len(input_pitch) > 0.9:
119
+ input_pitch[input_pitch != 1] = 1
120
+ return input_pitch
121
+
122
+
123
+ def plt_pitch(input_pitch):
124
+ input_pitch = input_pitch.astype(float)
125
+ input_pitch[input_pitch == 1] = np.nan
126
+ return input_pitch
127
+
128
+
129
+ def f0_to_pitch(ff):
130
+ f0_pitch = 69 + 12 * np.log2(ff / 440)
131
+ return f0_pitch
132
+
133
+
134
+ def fill_a_to_b(a, b):
135
+ if len(a) < len(b):
136
+ for _ in range(0, len(b) - len(a)):
137
+ a.append(a[0])
138
+
139
+
140
+ def mkdir(paths: list):
141
+ for path in paths:
142
+ if not os.path.exists(path):
143
+ os.mkdir(path)
144
+
145
+
146
+ class Svc(object):
147
+ def __init__(self, net_g_path, config_path, hubert_path="hubert/hubert-soft-0d54a1f4.pt",
148
+ onnx=False):
149
+ self.onnx = onnx
150
+ self.net_g_path = net_g_path
151
+ self.hubert_path = hubert_path
152
+ self.dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
153
+ self.net_g_ms = None
154
+ self.hps_ms = utils.get_hparams_from_file(config_path)
155
+ self.target_sample = self.hps_ms.data.sampling_rate
156
+ self.hop_size = self.hps_ms.data.hop_length
157
+ self.speakers = {}
158
+ for spk, sid in self.hps_ms.spk.items():
159
+ self.speakers[sid] = spk
160
+ self.spk2id = self.hps_ms.spk
161
+ # 加载hubert
162
+ self.hubert_soft = hubert_model.hubert_soft(hubert_path)
163
+ if torch.cuda.is_available():
164
+ self.hubert_soft = self.hubert_soft.cuda()
165
+ self.load_model()
166
+
167
+ def load_model(self):
168
+ # 获取模型配置
169
+ if self.onnx:
170
+ raise NotImplementedError
171
+ # self.net_g_ms = SynthesizerTrnForONNX(
172
+ # 178,
173
+ # self.hps_ms.data.filter_length // 2 + 1,
174
+ # self.hps_ms.train.segment_size // self.hps_ms.data.hop_length,
175
+ # n_speakers=self.hps_ms.data.n_speakers,
176
+ # **self.hps_ms.model)
177
+ # _ = utils.load_checkpoint(self.net_g_path, self.net_g_ms, None)
178
+ else:
179
+ self.net_g_ms = SynthesizerTrn(
180
+ self.hps_ms.data.filter_length // 2 + 1,
181
+ self.hps_ms.train.segment_size // self.hps_ms.data.hop_length,
182
+ **self.hps_ms.model)
183
+ _ = utils.load_checkpoint(self.net_g_path, self.net_g_ms, None)
184
+ if "half" in self.net_g_path and torch.cuda.is_available():
185
+ _ = self.net_g_ms.half().eval().to(self.dev)
186
+ else:
187
+ _ = self.net_g_ms.eval().to(self.dev)
188
+
189
+ def get_units(self, source, sr):
190
+
191
+ source = source.unsqueeze(0).to(self.dev)
192
+ with torch.inference_mode():
193
+ start = time.time()
194
+ units = self.hubert_soft.units(source)
195
+ use_time = time.time() - start
196
+ print("hubert use time:{}".format(use_time))
197
+ return units
198
+
199
+
200
+ def get_unit_pitch(self, in_path, tran):
201
+ source, sr = torchaudio.load(in_path)
202
+ source = torchaudio.functional.resample(source, sr, 16000)
203
+ if len(source.shape) == 2 and source.shape[1] >= 2:
204
+ source = torch.mean(source, dim=0).unsqueeze(0)
205
+ soft = self.get_units(source, sr).squeeze(0).cpu().numpy()
206
+ f0_coarse, f0 = get_f0(source.cpu().numpy()[0], soft.shape[0]*2, tran)
207
+ f0 = resize2d_f0(f0, soft.shape[0]*3)
208
+ return soft, f0
209
+
210
+ def infer(self, speaker_id, tran, raw_path):
211
+ if type(speaker_id) == str:
212
+ speaker_id = self.spk2id[speaker_id]
213
+ sid = torch.LongTensor([int(speaker_id)]).to(self.dev).unsqueeze(0)
214
+ soft, pitch = self.get_unit_pitch(raw_path, tran)
215
+ f0 = torch.FloatTensor(clean_pitch(pitch)).unsqueeze(0).to(self.dev)
216
+ if "half" in self.net_g_path and torch.cuda.is_available():
217
+ stn_tst = torch.HalfTensor(soft)
218
+ else:
219
+ stn_tst = torch.FloatTensor(soft)
220
+ with torch.no_grad():
221
+ x_tst = stn_tst.unsqueeze(0).to(self.dev)
222
+ start = time.time()
223
+ x_tst = torch.repeat_interleave(x_tst, repeats=3, dim=1).transpose(1, 2)
224
+ audio = self.net_g_ms.infer(x_tst, f0=f0, g=sid)[0,0].data.float()
225
+ use_time = time.time() - start
226
+ print("vits use time:{}".format(use_time))
227
+ return audio, audio.shape[-1]
228
+
229
+
230
+ # class SvcONNXInferModel(object):
231
+ # def __init__(self, hubert_onnx, vits_onnx, config_path):
232
+ # self.config_path = config_path
233
+ # self.vits_onnx = vits_onnx
234
+ # self.hubert_onnx = hubert_onnx
235
+ # self.hubert_onnx_session = onnxruntime.InferenceSession(hubert_onnx, providers=['CUDAExecutionProvider', ])
236
+ # self.inspect_onnx(self.hubert_onnx_session)
237
+ # self.vits_onnx_session = onnxruntime.InferenceSession(vits_onnx, providers=['CUDAExecutionProvider', ])
238
+ # self.inspect_onnx(self.vits_onnx_session)
239
+ # self.hps_ms = utils.get_hparams_from_file(self.config_path)
240
+ # self.target_sample = self.hps_ms.data.sampling_rate
241
+ # self.feature_input = FeatureInput(self.hps_ms.data.sampling_rate, self.hps_ms.data.hop_length)
242
+ #
243
+ # @staticmethod
244
+ # def inspect_onnx(session):
245
+ # for i in session.get_inputs():
246
+ # print("name:{}\tshape:{}\tdtype:{}".format(i.name, i.shape, i.type))
247
+ # for i in session.get_outputs():
248
+ # print("name:{}\tshape:{}\tdtype:{}".format(i.name, i.shape, i.type))
249
+ #
250
+ # def infer(self, speaker_id, tran, raw_path):
251
+ # sid = np.array([int(speaker_id)], dtype=np.int64)
252
+ # soft, pitch = self.get_unit_pitch(raw_path, tran)
253
+ # pitch = np.expand_dims(pitch, axis=0).astype(np.int64)
254
+ # stn_tst = soft
255
+ # x_tst = np.expand_dims(stn_tst, axis=0)
256
+ # x_tst_lengths = np.array([stn_tst.shape[0]], dtype=np.int64)
257
+ # # 使用ONNX Runtime进行推理
258
+ # start = time.time()
259
+ # audio = self.vits_onnx_session.run(output_names=["audio"],
260
+ # input_feed={
261
+ # "hidden_unit": x_tst,
262
+ # "lengths": x_tst_lengths,
263
+ # "pitch": pitch,
264
+ # "sid": sid,
265
+ # })[0][0, 0]
266
+ # use_time = time.time() - start
267
+ # print("vits_onnx_session.run time:{}".format(use_time))
268
+ # audio = torch.from_numpy(audio)
269
+ # return audio, audio.shape[-1]
270
+ #
271
+ # def get_units(self, source, sr):
272
+ # source = torchaudio.functional.resample(source, sr, 16000)
273
+ # if len(source.shape) == 2 and source.shape[1] >= 2:
274
+ # source = torch.mean(source, dim=0).unsqueeze(0)
275
+ # source = source.unsqueeze(0)
276
+ # # 使用ONNX Runtime进行推理
277
+ # start = time.time()
278
+ # units = self.hubert_onnx_session.run(output_names=["embed"],
279
+ # input_feed={"source": source.numpy()})[0]
280
+ # use_time = time.time() - start
281
+ # print("hubert_onnx_session.run time:{}".format(use_time))
282
+ # return units
283
+ #
284
+ # def transcribe(self, source, sr, length, transform):
285
+ # feature_pit = self.feature_input.compute_f0(source, sr)
286
+ # feature_pit = feature_pit * 2 ** (transform / 12)
287
+ # feature_pit = resize2d_f0(feature_pit, length)
288
+ # coarse_pit = self.feature_input.coarse_f0(feature_pit)
289
+ # return coarse_pit
290
+ #
291
+ # def get_unit_pitch(self, in_path, tran):
292
+ # source, sr = torchaudio.load(in_path)
293
+ # soft = self.get_units(source, sr).squeeze(0)
294
+ # input_pitch = self.transcribe(source.numpy()[0], sr, soft.shape[0], tran)
295
+ # return soft, input_pitch
296
+
297
+
298
+ class RealTimeVC:
299
+ def __init__(self):
300
+ self.last_chunk = None
301
+ self.last_o = None
302
+ self.chunk_len = 16000 # 区块长度
303
+ self.pre_len = 3840 # 交叉淡化长度,640的倍数
304
+
305
+ """输入输出都是1维numpy 音频波形数组"""
306
+
307
+ def process(self, svc_model, speaker_id, f_pitch_change, input_wav_path):
308
+ audio, sr = torchaudio.load(input_wav_path)
309
+ audio = audio.cpu().numpy()[0]
310
+ temp_wav = io.BytesIO()
311
+ if self.last_chunk is None:
312
+ input_wav_path.seek(0)
313
+ audio, sr = svc_model.infer(speaker_id, f_pitch_change, input_wav_path)
314
+ audio = audio.cpu().numpy()
315
+ self.last_chunk = audio[-self.pre_len:]
316
+ self.last_o = audio
317
+ return audio[-self.chunk_len:]
318
+ else:
319
+ audio = np.concatenate([self.last_chunk, audio])
320
+ soundfile.write(temp_wav, audio, sr, format="wav")
321
+ temp_wav.seek(0)
322
+ audio, sr = svc_model.infer(speaker_id, f_pitch_change, temp_wav)
323
+ audio = audio.cpu().numpy()
324
+ ret = maad.util.crossfade(self.last_o, audio, self.pre_len)
325
+ self.last_chunk = audio[-self.pre_len:]
326
+ self.last_o = audio
327
+ return ret[self.chunk_len:2 * self.chunk_len]
inference/slicer.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+
3
+ import numpy as np
4
+ import torch
5
+ import torchaudio
6
+ from scipy.ndimage import maximum_filter1d, uniform_filter1d
7
+
8
+
9
+ def timeit(func):
10
+ def run(*args, **kwargs):
11
+ t = time.time()
12
+ res = func(*args, **kwargs)
13
+ print('executing \'%s\' costed %.3fs' % (func.__name__, time.time() - t))
14
+ return res
15
+
16
+ return run
17
+
18
+
19
+ # @timeit
20
+ def _window_maximum(arr, win_sz):
21
+ return maximum_filter1d(arr, size=win_sz)[win_sz // 2: win_sz // 2 + arr.shape[0] - win_sz + 1]
22
+
23
+
24
+ # @timeit
25
+ def _window_rms(arr, win_sz):
26
+ filtered = np.sqrt(uniform_filter1d(np.power(arr, 2), win_sz) - np.power(uniform_filter1d(arr, win_sz), 2))
27
+ return filtered[win_sz // 2: win_sz // 2 + arr.shape[0] - win_sz + 1]
28
+
29
+
30
+ def level2db(levels, eps=1e-12):
31
+ return 20 * np.log10(np.clip(levels, a_min=eps, a_max=1))
32
+
33
+
34
+ def _apply_slice(audio, begin, end):
35
+ if len(audio.shape) > 1:
36
+ return audio[:, begin: end]
37
+ else:
38
+ return audio[begin: end]
39
+
40
+
41
+ class Slicer:
42
+ def __init__(self,
43
+ sr: int,
44
+ db_threshold: float = -40,
45
+ min_length: int = 5000,
46
+ win_l: int = 300,
47
+ win_s: int = 20,
48
+ max_silence_kept: int = 500):
49
+ self.db_threshold = db_threshold
50
+ self.min_samples = round(sr * min_length / 1000)
51
+ self.win_ln = round(sr * win_l / 1000)
52
+ self.win_sn = round(sr * win_s / 1000)
53
+ self.max_silence = round(sr * max_silence_kept / 1000)
54
+ if not self.min_samples >= self.win_ln >= self.win_sn:
55
+ raise ValueError('The following condition must be satisfied: min_length >= win_l >= win_s')
56
+ if not self.max_silence >= self.win_sn:
57
+ raise ValueError('The following condition must be satisfied: max_silence_kept >= win_s')
58
+
59
+ @timeit
60
+ def slice(self, audio):
61
+ samples = audio
62
+ if samples.shape[0] <= self.min_samples:
63
+ return {"0": {"slice": False, "split_time": f"0,{len(audio)}"}}
64
+ # get absolute amplitudes
65
+ abs_amp = np.abs(samples - np.mean(samples))
66
+ # calculate local maximum with large window
67
+ win_max_db = level2db(_window_maximum(abs_amp, win_sz=self.win_ln))
68
+ sil_tags = []
69
+ left = right = 0
70
+ while right < win_max_db.shape[0]:
71
+ if win_max_db[right] < self.db_threshold:
72
+ right += 1
73
+ elif left == right:
74
+ left += 1
75
+ right += 1
76
+ else:
77
+ if left == 0:
78
+ split_loc_l = left
79
+ else:
80
+ sil_left_n = min(self.max_silence, (right + self.win_ln - left) // 2)
81
+ rms_db_left = level2db(_window_rms(samples[left: left + sil_left_n], win_sz=self.win_sn))
82
+ split_win_l = left + np.argmin(rms_db_left)
83
+ split_loc_l = split_win_l + np.argmin(abs_amp[split_win_l: split_win_l + self.win_sn])
84
+ if len(sil_tags) != 0 and split_loc_l - sil_tags[-1][1] < self.min_samples and right < win_max_db.shape[
85
+ 0] - 1:
86
+ right += 1
87
+ left = right
88
+ continue
89
+ if right == win_max_db.shape[0] - 1:
90
+ split_loc_r = right + self.win_ln
91
+ else:
92
+ sil_right_n = min(self.max_silence, (right + self.win_ln - left) // 2)
93
+ rms_db_right = level2db(_window_rms(samples[right + self.win_ln - sil_right_n: right + self.win_ln],
94
+ win_sz=self.win_sn))
95
+ split_win_r = right + self.win_ln - sil_right_n + np.argmin(rms_db_right)
96
+ split_loc_r = split_win_r + np.argmin(abs_amp[split_win_r: split_win_r + self.win_sn])
97
+ sil_tags.append((split_loc_l, split_loc_r))
98
+ right += 1
99
+ left = right
100
+ if left != right:
101
+ sil_left_n = min(self.max_silence, (right + self.win_ln - left) // 2)
102
+ rms_db_left = level2db(_window_rms(samples[left: left + sil_left_n], win_sz=self.win_sn))
103
+ split_win_l = left + np.argmin(rms_db_left)
104
+ split_loc_l = split_win_l + np.argmin(abs_amp[split_win_l: split_win_l + self.win_sn])
105
+ sil_tags.append((split_loc_l, samples.shape[0]))
106
+ if len(sil_tags) == 0:
107
+ return {"0": {"slice": False, "split_time": f"0,{len(audio)}"}}
108
+ else:
109
+ chunks = []
110
+ # 第一段静音并非从头开始,补上有声片段
111
+ if sil_tags[0][0]:
112
+ chunks.append({"slice": False, "split_time": f"0,{sil_tags[0][0]}"})
113
+ for i in range(0, len(sil_tags)):
114
+ # 标识有声片段(跳过第一段)
115
+ if i:
116
+ chunks.append({"slice": False, "split_time": f"{sil_tags[i - 1][1]},{sil_tags[i][0]}"})
117
+ # 标识所有静音片段
118
+ chunks.append({"slice": True, "split_time": f"{sil_tags[i][0]},{sil_tags[i][1]}"})
119
+ # 最后一段静音并非结尾,补上结尾片段
120
+ if sil_tags[-1][1] != len(audio):
121
+ chunks.append({"slice": False, "split_time": f"{sil_tags[-1][1]},{len(audio)}"})
122
+ chunk_dict = {}
123
+ for i in range(len(chunks)):
124
+ chunk_dict[str(i)] = chunks[i]
125
+ return chunk_dict
126
+
127
+
128
+ def cut(audio_path, db_thresh=-30, min_len=5000, win_l=300, win_s=20, max_sil_kept=500):
129
+ audio, sr = torchaudio.load(audio_path)
130
+ if len(audio.shape) == 2 and audio.shape[1] >= 2:
131
+ audio = torch.mean(audio, dim=0).unsqueeze(0)
132
+ audio = audio.cpu().numpy()[0]
133
+
134
+ slicer = Slicer(
135
+ sr=sr,
136
+ db_threshold=db_thresh,
137
+ min_length=min_len,
138
+ win_l=win_l,
139
+ win_s=win_s,
140
+ max_silence_kept=max_sil_kept
141
+ )
142
+ chunks = slicer.slice(audio)
143
+ return chunks
144
+
145
+
146
+ def chunks2audio(audio_path, chunks):
147
+ chunks = dict(chunks)
148
+ audio, sr = torchaudio.load(audio_path)
149
+ if len(audio.shape) == 2 and audio.shape[1] >= 2:
150
+ audio = torch.mean(audio, dim=0).unsqueeze(0)
151
+ audio = audio.cpu().numpy()[0]
152
+ result = []
153
+ for k, v in chunks.items():
154
+ tag = v["split_time"].split(",")
155
+ result.append((v["slice"], audio[int(tag[0]):int(tag[1])]))
156
+ return result, sr
157
+
158
+
logs/48k/aqua.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6045347e929c571751fa53e789b277f7737c2d53dae53e753b918af6503d2155
3
+ size 699505437
losses.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.nn import functional as F
3
+
4
+ import commons
5
+
6
+
7
+ def feature_loss(fmap_r, fmap_g):
8
+ loss = 0
9
+ for dr, dg in zip(fmap_r, fmap_g):
10
+ for rl, gl in zip(dr, dg):
11
+ rl = rl.float().detach()
12
+ gl = gl.float()
13
+ loss += torch.mean(torch.abs(rl - gl))
14
+
15
+ return loss * 2
16
+
17
+
18
+ def discriminator_loss(disc_real_outputs, disc_generated_outputs):
19
+ loss = 0
20
+ r_losses = []
21
+ g_losses = []
22
+ for dr, dg in zip(disc_real_outputs, disc_generated_outputs):
23
+ dr = dr.float()
24
+ dg = dg.float()
25
+ r_loss = torch.mean((1-dr)**2)
26
+ g_loss = torch.mean(dg**2)
27
+ loss += (r_loss + g_loss)
28
+ r_losses.append(r_loss.item())
29
+ g_losses.append(g_loss.item())
30
+
31
+ return loss, r_losses, g_losses
32
+
33
+
34
+ def generator_loss(disc_outputs):
35
+ loss = 0
36
+ gen_losses = []
37
+ for dg in disc_outputs:
38
+ dg = dg.float()
39
+ l = torch.mean((1-dg)**2)
40
+ gen_losses.append(l)
41
+ loss += l
42
+
43
+ return loss, gen_losses
44
+
45
+
46
+ def kl_loss(z_p, logs_q, m_p, logs_p, z_mask):
47
+ """
48
+ z_p, logs_q: [b, h, t_t]
49
+ m_p, logs_p: [b, h, t_t]
50
+ """
51
+ z_p = z_p.float()
52
+ logs_q = logs_q.float()
53
+ m_p = m_p.float()
54
+ logs_p = logs_p.float()
55
+ z_mask = z_mask.float()
56
+ #print(logs_p)
57
+ kl = logs_p - logs_q - 0.5
58
+ kl += 0.5 * ((z_p - m_p)**2) * torch.exp(-2. * logs_p)
59
+ kl = torch.sum(kl * z_mask)
60
+ l = kl / torch.sum(z_mask)
61
+ return l
mel_processing.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import random
4
+ import torch
5
+ from torch import nn
6
+ import torch.nn.functional as F
7
+ import torch.utils.data
8
+ import numpy as np
9
+ import librosa
10
+ import librosa.util as librosa_util
11
+ from librosa.util import normalize, pad_center, tiny
12
+ from scipy.signal import get_window
13
+ from scipy.io.wavfile import read
14
+ from librosa.filters import mel as librosa_mel_fn
15
+
16
+ MAX_WAV_VALUE = 32768.0
17
+
18
+
19
+ def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
20
+ """
21
+ PARAMS
22
+ ------
23
+ C: compression factor
24
+ """
25
+ return torch.log(torch.clamp(x, min=clip_val) * C)
26
+
27
+
28
+ def dynamic_range_decompression_torch(x, C=1):
29
+ """
30
+ PARAMS
31
+ ------
32
+ C: compression factor used to compress
33
+ """
34
+ return torch.exp(x) / C
35
+
36
+
37
+ def spectral_normalize_torch(magnitudes):
38
+ output = dynamic_range_compression_torch(magnitudes)
39
+ return output
40
+
41
+
42
+ def spectral_de_normalize_torch(magnitudes):
43
+ output = dynamic_range_decompression_torch(magnitudes)
44
+ return output
45
+
46
+
47
+ mel_basis = {}
48
+ hann_window = {}
49
+
50
+
51
+ def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False):
52
+ if torch.min(y) < -1.:
53
+ print('min value is ', torch.min(y))
54
+ if torch.max(y) > 1.:
55
+ print('max value is ', torch.max(y))
56
+
57
+ global hann_window
58
+ dtype_device = str(y.dtype) + '_' + str(y.device)
59
+ wnsize_dtype_device = str(win_size) + '_' + dtype_device
60
+ if wnsize_dtype_device not in hann_window:
61
+ hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device)
62
+
63
+ y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect')
64
+ y = y.squeeze(1)
65
+
66
+ spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device],
67
+ center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=False)
68
+
69
+ spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
70
+ return spec
71
+
72
+
73
+ def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax):
74
+ global mel_basis
75
+ dtype_device = str(spec.dtype) + '_' + str(spec.device)
76
+ fmax_dtype_device = str(fmax) + '_' + dtype_device
77
+ if fmax_dtype_device not in mel_basis:
78
+ mel = librosa_mel_fn(sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax)
79
+ mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=spec.dtype, device=spec.device)
80
+ spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
81
+ spec = spectral_normalize_torch(spec)
82
+ return spec
83
+
84
+
85
+ def mel_spectrogram_torch(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False):
86
+ if torch.min(y) < -1.:
87
+ print('min value is ', torch.min(y))
88
+ if torch.max(y) > 1.:
89
+ print('max value is ', torch.max(y))
90
+
91
+ global mel_basis, hann_window
92
+ dtype_device = str(y.dtype) + '_' + str(y.device)
93
+ fmax_dtype_device = str(fmax) + '_' + dtype_device
94
+ wnsize_dtype_device = str(win_size) + '_' + dtype_device
95
+ if fmax_dtype_device not in mel_basis:
96
+ mel = librosa_mel_fn(sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax)
97
+ mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(dtype=y.dtype, device=y.device)
98
+ if wnsize_dtype_device not in hann_window:
99
+ hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(dtype=y.dtype, device=y.device)
100
+
101
+ y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)), mode='reflect')
102
+ y = y.squeeze(1)
103
+
104
+ spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[wnsize_dtype_device],
105
+ center=center, pad_mode='reflect', normalized=False, onesided=True, return_complex=False)
106
+
107
+ spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
108
+
109
+ spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
110
+ spec = spectral_normalize_torch(spec)
111
+
112
+ return spec
models.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import math
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+ import attentions
8
+ import commons
9
+ import modules
10
+
11
+ from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
12
+ from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
13
+ from commons import init_weights, get_padding
14
+ from vdecoder.hifigan.models import Generator
15
+ from utils import f0_to_coarse
16
+
17
+ class ResidualCouplingBlock(nn.Module):
18
+ def __init__(self,
19
+ channels,
20
+ hidden_channels,
21
+ kernel_size,
22
+ dilation_rate,
23
+ n_layers,
24
+ n_flows=4,
25
+ gin_channels=0):
26
+ super().__init__()
27
+ self.channels = channels
28
+ self.hidden_channels = hidden_channels
29
+ self.kernel_size = kernel_size
30
+ self.dilation_rate = dilation_rate
31
+ self.n_layers = n_layers
32
+ self.n_flows = n_flows
33
+ self.gin_channels = gin_channels
34
+
35
+ self.flows = nn.ModuleList()
36
+ for i in range(n_flows):
37
+ self.flows.append(modules.ResidualCouplingLayer(channels, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels, mean_only=True))
38
+ self.flows.append(modules.Flip())
39
+
40
+ def forward(self, x, x_mask, g=None, reverse=False):
41
+ if not reverse:
42
+ for flow in self.flows:
43
+ x, _ = flow(x, x_mask, g=g, reverse=reverse)
44
+ else:
45
+ for flow in reversed(self.flows):
46
+ x = flow(x, x_mask, g=g, reverse=reverse)
47
+ return x
48
+
49
+
50
+ class Encoder(nn.Module):
51
+ def __init__(self,
52
+ in_channels,
53
+ out_channels,
54
+ hidden_channels,
55
+ kernel_size,
56
+ dilation_rate,
57
+ n_layers,
58
+ gin_channels=0):
59
+ super().__init__()
60
+ self.in_channels = in_channels
61
+ self.out_channels = out_channels
62
+ self.hidden_channels = hidden_channels
63
+ self.kernel_size = kernel_size
64
+ self.dilation_rate = dilation_rate
65
+ self.n_layers = n_layers
66
+ self.gin_channels = gin_channels
67
+
68
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
69
+ self.enc = modules.WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels)
70
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
71
+
72
+ def forward(self, x, x_lengths, g=None):
73
+ # print(x.shape,x_lengths.shape)
74
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
75
+ x = self.pre(x) * x_mask
76
+ x = self.enc(x, x_mask, g=g)
77
+ stats = self.proj(x) * x_mask
78
+ m, logs = torch.split(stats, self.out_channels, dim=1)
79
+ z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
80
+ return z, m, logs, x_mask
81
+
82
+
83
+ class TextEncoder(nn.Module):
84
+ def __init__(self,
85
+ in_channels,
86
+ out_channels,
87
+ hidden_channels,
88
+ kernel_size,
89
+ dilation_rate,
90
+ n_layers,
91
+ gin_channels=0,
92
+ filter_channels=None,
93
+ n_heads=None,
94
+ p_dropout=None):
95
+ super().__init__()
96
+ self.in_channels = in_channels
97
+ self.out_channels = out_channels
98
+ self.hidden_channels = hidden_channels
99
+ self.kernel_size = kernel_size
100
+ self.dilation_rate = dilation_rate
101
+ self.n_layers = n_layers
102
+ self.gin_channels = gin_channels
103
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
104
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
105
+ self.f0_emb = nn.Embedding(256, hidden_channels)
106
+
107
+ self.enc_ = attentions.Encoder(
108
+ hidden_channels,
109
+ filter_channels,
110
+ n_heads,
111
+ n_layers,
112
+ kernel_size,
113
+ p_dropout)
114
+
115
+ def forward(self, x, x_lengths, f0=None):
116
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(x.dtype)
117
+ x = self.pre(x) * x_mask
118
+ x = x + self.f0_emb(f0).transpose(1,2)
119
+ x = self.enc_(x * x_mask, x_mask)
120
+ stats = self.proj(x) * x_mask
121
+ m, logs = torch.split(stats, self.out_channels, dim=1)
122
+ z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
123
+
124
+ return z, m, logs, x_mask
125
+
126
+
127
+
128
+ class DiscriminatorP(torch.nn.Module):
129
+ def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
130
+ super(DiscriminatorP, self).__init__()
131
+ self.period = period
132
+ self.use_spectral_norm = use_spectral_norm
133
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
134
+ self.convs = nn.ModuleList([
135
+ norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
136
+ norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
137
+ norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
138
+ norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(kernel_size, 1), 0))),
139
+ norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(get_padding(kernel_size, 1), 0))),
140
+ ])
141
+ self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
142
+
143
+ def forward(self, x):
144
+ fmap = []
145
+
146
+ # 1d to 2d
147
+ b, c, t = x.shape
148
+ if t % self.period != 0: # pad first
149
+ n_pad = self.period - (t % self.period)
150
+ x = F.pad(x, (0, n_pad), "reflect")
151
+ t = t + n_pad
152
+ x = x.view(b, c, t // self.period, self.period)
153
+
154
+ for l in self.convs:
155
+ x = l(x)
156
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
157
+ fmap.append(x)
158
+ x = self.conv_post(x)
159
+ fmap.append(x)
160
+ x = torch.flatten(x, 1, -1)
161
+
162
+ return x, fmap
163
+
164
+
165
+ class DiscriminatorS(torch.nn.Module):
166
+ def __init__(self, use_spectral_norm=False):
167
+ super(DiscriminatorS, self).__init__()
168
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
169
+ self.convs = nn.ModuleList([
170
+ norm_f(Conv1d(1, 16, 15, 1, padding=7)),
171
+ norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
172
+ norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
173
+ norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
174
+ norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
175
+ norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
176
+ ])
177
+ self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
178
+
179
+ def forward(self, x):
180
+ fmap = []
181
+
182
+ for l in self.convs:
183
+ x = l(x)
184
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
185
+ fmap.append(x)
186
+ x = self.conv_post(x)
187
+ fmap.append(x)
188
+ x = torch.flatten(x, 1, -1)
189
+
190
+ return x, fmap
191
+
192
+
193
+ class MultiPeriodDiscriminator(torch.nn.Module):
194
+ def __init__(self, use_spectral_norm=False):
195
+ super(MultiPeriodDiscriminator, self).__init__()
196
+ periods = [2,3,5,7,11]
197
+
198
+ discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
199
+ discs = discs + [DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods]
200
+ self.discriminators = nn.ModuleList(discs)
201
+
202
+ def forward(self, y, y_hat):
203
+ y_d_rs = []
204
+ y_d_gs = []
205
+ fmap_rs = []
206
+ fmap_gs = []
207
+ for i, d in enumerate(self.discriminators):
208
+ y_d_r, fmap_r = d(y)
209
+ y_d_g, fmap_g = d(y_hat)
210
+ y_d_rs.append(y_d_r)
211
+ y_d_gs.append(y_d_g)
212
+ fmap_rs.append(fmap_r)
213
+ fmap_gs.append(fmap_g)
214
+
215
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
216
+
217
+
218
+ class SpeakerEncoder(torch.nn.Module):
219
+ def __init__(self, mel_n_channels=80, model_num_layers=3, model_hidden_size=256, model_embedding_size=256):
220
+ super(SpeakerEncoder, self).__init__()
221
+ self.lstm = nn.LSTM(mel_n_channels, model_hidden_size, model_num_layers, batch_first=True)
222
+ self.linear = nn.Linear(model_hidden_size, model_embedding_size)
223
+ self.relu = nn.ReLU()
224
+
225
+ def forward(self, mels):
226
+ self.lstm.flatten_parameters()
227
+ _, (hidden, _) = self.lstm(mels)
228
+ embeds_raw = self.relu(self.linear(hidden[-1]))
229
+ return embeds_raw / torch.norm(embeds_raw, dim=1, keepdim=True)
230
+
231
+ def compute_partial_slices(self, total_frames, partial_frames, partial_hop):
232
+ mel_slices = []
233
+ for i in range(0, total_frames-partial_frames, partial_hop):
234
+ mel_range = torch.arange(i, i+partial_frames)
235
+ mel_slices.append(mel_range)
236
+
237
+ return mel_slices
238
+
239
+ def embed_utterance(self, mel, partial_frames=128, partial_hop=64):
240
+ mel_len = mel.size(1)
241
+ last_mel = mel[:,-partial_frames:]
242
+
243
+ if mel_len > partial_frames:
244
+ mel_slices = self.compute_partial_slices(mel_len, partial_frames, partial_hop)
245
+ mels = list(mel[:,s] for s in mel_slices)
246
+ mels.append(last_mel)
247
+ mels = torch.stack(tuple(mels), 0).squeeze(1)
248
+
249
+ with torch.no_grad():
250
+ partial_embeds = self(mels)
251
+ embed = torch.mean(partial_embeds, axis=0).unsqueeze(0)
252
+ #embed = embed / torch.linalg.norm(embed, 2)
253
+ else:
254
+ with torch.no_grad():
255
+ embed = self(last_mel)
256
+
257
+ return embed
258
+
259
+
260
+ class SynthesizerTrn(nn.Module):
261
+ """
262
+ Synthesizer for Training
263
+ """
264
+
265
+ def __init__(self,
266
+ spec_channels,
267
+ segment_size,
268
+ inter_channels,
269
+ hidden_channels,
270
+ filter_channels,
271
+ n_heads,
272
+ n_layers,
273
+ kernel_size,
274
+ p_dropout,
275
+ resblock,
276
+ resblock_kernel_sizes,
277
+ resblock_dilation_sizes,
278
+ upsample_rates,
279
+ upsample_initial_channel,
280
+ upsample_kernel_sizes,
281
+ gin_channels,
282
+ ssl_dim,
283
+ n_speakers,
284
+ **kwargs):
285
+
286
+ super().__init__()
287
+ self.spec_channels = spec_channels
288
+ self.inter_channels = inter_channels
289
+ self.hidden_channels = hidden_channels
290
+ self.filter_channels = filter_channels
291
+ self.n_heads = n_heads
292
+ self.n_layers = n_layers
293
+ self.kernel_size = kernel_size
294
+ self.p_dropout = p_dropout
295
+ self.resblock = resblock
296
+ self.resblock_kernel_sizes = resblock_kernel_sizes
297
+ self.resblock_dilation_sizes = resblock_dilation_sizes
298
+ self.upsample_rates = upsample_rates
299
+ self.upsample_initial_channel = upsample_initial_channel
300
+ self.upsample_kernel_sizes = upsample_kernel_sizes
301
+ self.segment_size = segment_size
302
+ self.gin_channels = gin_channels
303
+ self.ssl_dim = ssl_dim
304
+ self.emb_g = nn.Embedding(n_speakers, gin_channels)
305
+
306
+ self.enc_p_ = TextEncoder(ssl_dim, inter_channels, hidden_channels, 5, 1, 16,0, filter_channels, n_heads, p_dropout)
307
+ hps = {
308
+ "sampling_rate": 48000,
309
+ "inter_channels": 192,
310
+ "resblock": "1",
311
+ "resblock_kernel_sizes": [3, 7, 11],
312
+ "resblock_dilation_sizes": [[1, 3, 5], [1, 3, 5], [1, 3, 5]],
313
+ "upsample_rates": [10, 8, 2, 2],
314
+ "upsample_initial_channel": 512,
315
+ "upsample_kernel_sizes": [16, 16, 4, 4],
316
+ "gin_channels": 256,
317
+ }
318
+ self.dec = Generator(h=hps)
319
+ self.enc_q = Encoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16, gin_channels=gin_channels)
320
+ self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, 4, gin_channels=gin_channels)
321
+
322
+ def forward(self, c, f0, spec, g=None, mel=None, c_lengths=None, spec_lengths=None):
323
+ if c_lengths == None:
324
+ c_lengths = (torch.ones(c.size(0)) * c.size(-1)).to(c.device)
325
+ if spec_lengths == None:
326
+ spec_lengths = (torch.ones(spec.size(0)) * spec.size(-1)).to(spec.device)
327
+
328
+ g = self.emb_g(g).transpose(1,2)
329
+
330
+ z_ptemp, m_p, logs_p, _ = self.enc_p_(c, c_lengths, f0=f0_to_coarse(f0))
331
+ z, m_q, logs_q, spec_mask = self.enc_q(spec, spec_lengths, g=g)
332
+
333
+ z_p = self.flow(z, spec_mask, g=g)
334
+ z_slice, pitch_slice, ids_slice = commons.rand_slice_segments_with_pitch(z, f0, spec_lengths, self.segment_size)
335
+
336
+ # o = self.dec(z_slice, g=g)
337
+ o = self.dec(z_slice, g=g, f0=pitch_slice)
338
+
339
+ return o, ids_slice, spec_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
340
+
341
+ def infer(self, c, f0, g=None, mel=None, c_lengths=None):
342
+ if c_lengths == None:
343
+ c_lengths = (torch.ones(c.size(0)) * c.size(-1)).to(c.device)
344
+ g = self.emb_g(g).transpose(1,2)
345
+
346
+ z_p, m_p, logs_p, c_mask = self.enc_p_(c, c_lengths, f0=f0_to_coarse(f0))
347
+ z = self.flow(z_p, c_mask, g=g, reverse=True)
348
+
349
+ o = self.dec(z * c_mask, g=g, f0=f0)
350
+
351
+ return o
modules.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import math
3
+ import numpy as np
4
+ import scipy
5
+ import torch
6
+ from torch import nn
7
+ from torch.nn import functional as F
8
+
9
+ from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
10
+ from torch.nn.utils import weight_norm, remove_weight_norm
11
+
12
+ import commons
13
+ from commons import init_weights, get_padding
14
+
15
+
16
+ LRELU_SLOPE = 0.1
17
+
18
+
19
+ class LayerNorm(nn.Module):
20
+ def __init__(self, channels, eps=1e-5):
21
+ super().__init__()
22
+ self.channels = channels
23
+ self.eps = eps
24
+
25
+ self.gamma = nn.Parameter(torch.ones(channels))
26
+ self.beta = nn.Parameter(torch.zeros(channels))
27
+
28
+ def forward(self, x):
29
+ x = x.transpose(1, -1)
30
+ x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
31
+ return x.transpose(1, -1)
32
+
33
+
34
+ class ConvReluNorm(nn.Module):
35
+ def __init__(self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout):
36
+ super().__init__()
37
+ self.in_channels = in_channels
38
+ self.hidden_channels = hidden_channels
39
+ self.out_channels = out_channels
40
+ self.kernel_size = kernel_size
41
+ self.n_layers = n_layers
42
+ self.p_dropout = p_dropout
43
+ assert n_layers > 1, "Number of layers should be larger than 0."
44
+
45
+ self.conv_layers = nn.ModuleList()
46
+ self.norm_layers = nn.ModuleList()
47
+ self.conv_layers.append(nn.Conv1d(in_channels, hidden_channels, kernel_size, padding=kernel_size//2))
48
+ self.norm_layers.append(LayerNorm(hidden_channels))
49
+ self.relu_drop = nn.Sequential(
50
+ nn.ReLU(),
51
+ nn.Dropout(p_dropout))
52
+ for _ in range(n_layers-1):
53
+ self.conv_layers.append(nn.Conv1d(hidden_channels, hidden_channels, kernel_size, padding=kernel_size//2))
54
+ self.norm_layers.append(LayerNorm(hidden_channels))
55
+ self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
56
+ self.proj.weight.data.zero_()
57
+ self.proj.bias.data.zero_()
58
+
59
+ def forward(self, x, x_mask):
60
+ x_org = x
61
+ for i in range(self.n_layers):
62
+ x = self.conv_layers[i](x * x_mask)
63
+ x = self.norm_layers[i](x)
64
+ x = self.relu_drop(x)
65
+ x = x_org + self.proj(x)
66
+ return x * x_mask
67
+
68
+
69
+ class DDSConv(nn.Module):
70
+ """
71
+ Dialted and Depth-Separable Convolution
72
+ """
73
+ def __init__(self, channels, kernel_size, n_layers, p_dropout=0.):
74
+ super().__init__()
75
+ self.channels = channels
76
+ self.kernel_size = kernel_size
77
+ self.n_layers = n_layers
78
+ self.p_dropout = p_dropout
79
+
80
+ self.drop = nn.Dropout(p_dropout)
81
+ self.convs_sep = nn.ModuleList()
82
+ self.convs_1x1 = nn.ModuleList()
83
+ self.norms_1 = nn.ModuleList()
84
+ self.norms_2 = nn.ModuleList()
85
+ for i in range(n_layers):
86
+ dilation = kernel_size ** i
87
+ padding = (kernel_size * dilation - dilation) // 2
88
+ self.convs_sep.append(nn.Conv1d(channels, channels, kernel_size,
89
+ groups=channels, dilation=dilation, padding=padding
90
+ ))
91
+ self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
92
+ self.norms_1.append(LayerNorm(channels))
93
+ self.norms_2.append(LayerNorm(channels))
94
+
95
+ def forward(self, x, x_mask, g=None):
96
+ if g is not None:
97
+ x = x + g
98
+ for i in range(self.n_layers):
99
+ y = self.convs_sep[i](x * x_mask)
100
+ y = self.norms_1[i](y)
101
+ y = F.gelu(y)
102
+ y = self.convs_1x1[i](y)
103
+ y = self.norms_2[i](y)
104
+ y = F.gelu(y)
105
+ y = self.drop(y)
106
+ x = x + y
107
+ return x * x_mask
108
+
109
+
110
+ class WN(torch.nn.Module):
111
+ def __init__(self, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, p_dropout=0):
112
+ super(WN, self).__init__()
113
+ assert(kernel_size % 2 == 1)
114
+ self.hidden_channels =hidden_channels
115
+ self.kernel_size = kernel_size,
116
+ self.dilation_rate = dilation_rate
117
+ self.n_layers = n_layers
118
+ self.gin_channels = gin_channels
119
+ self.p_dropout = p_dropout
120
+
121
+ self.in_layers = torch.nn.ModuleList()
122
+ self.res_skip_layers = torch.nn.ModuleList()
123
+ self.drop = nn.Dropout(p_dropout)
124
+
125
+ if gin_channels != 0:
126
+ cond_layer = torch.nn.Conv1d(gin_channels, 2*hidden_channels*n_layers, 1)
127
+ self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight')
128
+
129
+ for i in range(n_layers):
130
+ dilation = dilation_rate ** i
131
+ padding = int((kernel_size * dilation - dilation) / 2)
132
+ in_layer = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, kernel_size,
133
+ dilation=dilation, padding=padding)
134
+ in_layer = torch.nn.utils.weight_norm(in_layer, name='weight')
135
+ self.in_layers.append(in_layer)
136
+
137
+ # last one is not necessary
138
+ if i < n_layers - 1:
139
+ res_skip_channels = 2 * hidden_channels
140
+ else:
141
+ res_skip_channels = hidden_channels
142
+
143
+ res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
144
+ res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name='weight')
145
+ self.res_skip_layers.append(res_skip_layer)
146
+
147
+ def forward(self, x, x_mask, g=None, **kwargs):
148
+ output = torch.zeros_like(x)
149
+ n_channels_tensor = torch.IntTensor([self.hidden_channels])
150
+
151
+ if g is not None:
152
+ g = self.cond_layer(g)
153
+
154
+ for i in range(self.n_layers):
155
+ x_in = self.in_layers[i](x)
156
+ if g is not None:
157
+ cond_offset = i * 2 * self.hidden_channels
158
+ g_l = g[:,cond_offset:cond_offset+2*self.hidden_channels,:]
159
+ else:
160
+ g_l = torch.zeros_like(x_in)
161
+
162
+ acts = commons.fused_add_tanh_sigmoid_multiply(
163
+ x_in,
164
+ g_l,
165
+ n_channels_tensor)
166
+ acts = self.drop(acts)
167
+
168
+ res_skip_acts = self.res_skip_layers[i](acts)
169
+ if i < self.n_layers - 1:
170
+ res_acts = res_skip_acts[:,:self.hidden_channels,:]
171
+ x = (x + res_acts) * x_mask
172
+ output = output + res_skip_acts[:,self.hidden_channels:,:]
173
+ else:
174
+ output = output + res_skip_acts
175
+ return output * x_mask
176
+
177
+ def remove_weight_norm(self):
178
+ if self.gin_channels != 0:
179
+ torch.nn.utils.remove_weight_norm(self.cond_layer)
180
+ for l in self.in_layers:
181
+ torch.nn.utils.remove_weight_norm(l)
182
+ for l in self.res_skip_layers:
183
+ torch.nn.utils.remove_weight_norm(l)
184
+
185
+
186
+ class ResBlock1(torch.nn.Module):
187
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
188
+ super(ResBlock1, self).__init__()
189
+ self.convs1 = nn.ModuleList([
190
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
191
+ padding=get_padding(kernel_size, dilation[0]))),
192
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
193
+ padding=get_padding(kernel_size, dilation[1]))),
194
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
195
+ padding=get_padding(kernel_size, dilation[2])))
196
+ ])
197
+ self.convs1.apply(init_weights)
198
+
199
+ self.convs2 = nn.ModuleList([
200
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
201
+ padding=get_padding(kernel_size, 1))),
202
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
203
+ padding=get_padding(kernel_size, 1))),
204
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
205
+ padding=get_padding(kernel_size, 1)))
206
+ ])
207
+ self.convs2.apply(init_weights)
208
+
209
+ def forward(self, x, x_mask=None):
210
+ for c1, c2 in zip(self.convs1, self.convs2):
211
+ xt = F.leaky_relu(x, LRELU_SLOPE)
212
+ if x_mask is not None:
213
+ xt = xt * x_mask
214
+ xt = c1(xt)
215
+ xt = F.leaky_relu(xt, LRELU_SLOPE)
216
+ if x_mask is not None:
217
+ xt = xt * x_mask
218
+ xt = c2(xt)
219
+ x = xt + x
220
+ if x_mask is not None:
221
+ x = x * x_mask
222
+ return x
223
+
224
+ def remove_weight_norm(self):
225
+ for l in self.convs1:
226
+ remove_weight_norm(l)
227
+ for l in self.convs2:
228
+ remove_weight_norm(l)
229
+
230
+
231
+ class ResBlock2(torch.nn.Module):
232
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
233
+ super(ResBlock2, self).__init__()
234
+ self.convs = nn.ModuleList([
235
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
236
+ padding=get_padding(kernel_size, dilation[0]))),
237
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
238
+ padding=get_padding(kernel_size, dilation[1])))
239
+ ])
240
+ self.convs.apply(init_weights)
241
+
242
+ def forward(self, x, x_mask=None):
243
+ for c in self.convs:
244
+ xt = F.leaky_relu(x, LRELU_SLOPE)
245
+ if x_mask is not None:
246
+ xt = xt * x_mask
247
+ xt = c(xt)
248
+ x = xt + x
249
+ if x_mask is not None:
250
+ x = x * x_mask
251
+ return x
252
+
253
+ def remove_weight_norm(self):
254
+ for l in self.convs:
255
+ remove_weight_norm(l)
256
+
257
+
258
+ class Log(nn.Module):
259
+ def forward(self, x, x_mask, reverse=False, **kwargs):
260
+ if not reverse:
261
+ y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
262
+ logdet = torch.sum(-y, [1, 2])
263
+ return y, logdet
264
+ else:
265
+ x = torch.exp(x) * x_mask
266
+ return x
267
+
268
+
269
+ class Flip(nn.Module):
270
+ def forward(self, x, *args, reverse=False, **kwargs):
271
+ x = torch.flip(x, [1])
272
+ if not reverse:
273
+ logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
274
+ return x, logdet
275
+ else:
276
+ return x
277
+
278
+
279
+ class ElementwiseAffine(nn.Module):
280
+ def __init__(self, channels):
281
+ super().__init__()
282
+ self.channels = channels
283
+ self.m = nn.Parameter(torch.zeros(channels,1))
284
+ self.logs = nn.Parameter(torch.zeros(channels,1))
285
+
286
+ def forward(self, x, x_mask, reverse=False, **kwargs):
287
+ if not reverse:
288
+ y = self.m + torch.exp(self.logs) * x
289
+ y = y * x_mask
290
+ logdet = torch.sum(self.logs * x_mask, [1,2])
291
+ return y, logdet
292
+ else:
293
+ x = (x - self.m) * torch.exp(-self.logs) * x_mask
294
+ return x
295
+
296
+
297
+ class ResidualCouplingLayer(nn.Module):
298
+ def __init__(self,
299
+ channels,
300
+ hidden_channels,
301
+ kernel_size,
302
+ dilation_rate,
303
+ n_layers,
304
+ p_dropout=0,
305
+ gin_channels=0,
306
+ mean_only=False):
307
+ assert channels % 2 == 0, "channels should be divisible by 2"
308
+ super().__init__()
309
+ self.channels = channels
310
+ self.hidden_channels = hidden_channels
311
+ self.kernel_size = kernel_size
312
+ self.dilation_rate = dilation_rate
313
+ self.n_layers = n_layers
314
+ self.half_channels = channels // 2
315
+ self.mean_only = mean_only
316
+
317
+ self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
318
+ self.enc = WN(hidden_channels, kernel_size, dilation_rate, n_layers, p_dropout=p_dropout, gin_channels=gin_channels)
319
+ self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
320
+ self.post.weight.data.zero_()
321
+ self.post.bias.data.zero_()
322
+
323
+ def forward(self, x, x_mask, g=None, reverse=False):
324
+ x0, x1 = torch.split(x, [self.half_channels]*2, 1)
325
+ h = self.pre(x0) * x_mask
326
+ h = self.enc(h, x_mask, g=g)
327
+ stats = self.post(h) * x_mask
328
+ if not self.mean_only:
329
+ m, logs = torch.split(stats, [self.half_channels]*2, 1)
330
+ else:
331
+ m = stats
332
+ logs = torch.zeros_like(m)
333
+
334
+ if not reverse:
335
+ x1 = m + x1 * torch.exp(logs) * x_mask
336
+ x = torch.cat([x0, x1], 1)
337
+ logdet = torch.sum(logs, [1,2])
338
+ return x, logdet
339
+ else:
340
+ x1 = (x1 - m) * torch.exp(-logs) * x_mask
341
+ x = torch.cat([x0, x1], 1)
342
+ return x
raw/大手拉小手.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b89788bc5dfeb7a9662665a8c07f4a7f49c74e245282b7a1b2f21efa07ad121c
3
+ size 2808078
requirements.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ numpy
2
+ playsound
3
+ pydub
4
+ pyworld
5
+ requests
6
+ scipy
7
+ sounddevice
8
+ SoundFile
9
+ starlette
10
+ torch
11
+ torchaudio
12
+ tqdm
13
+ scikit-maad
14
+ praat-parselmouth
15
+ librosa
16
+ torchvision
spec_gen.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from data_utils import TextAudioSpeakerLoader, EvalDataLoader
2
+ import json
3
+ from tqdm import tqdm
4
+
5
+ from utils import HParams
6
+
7
+ config_path = 'configs/config.json'
8
+ with open(config_path, "r") as f:
9
+ data = f.read()
10
+ config = json.loads(data)
11
+ hps = HParams(**config)
12
+
13
+ train_dataset = TextAudioSpeakerLoader("filelists/train.txt", hps)
14
+ test_dataset = TextAudioSpeakerLoader("filelists/test.txt", hps)
15
+ eval_dataset = TextAudioSpeakerLoader("filelists/val.txt", hps)
16
+
17
+ for _ in tqdm(train_dataset):
18
+ pass
19
+ for _ in tqdm(eval_dataset):
20
+ pass
21
+ for _ in tqdm(test_dataset):
22
+ pass
terms.md ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 在使用此模型前请阅读以下协议
2
+
3
+ ## AI阿夸模型使用协议
4
+
5
+ **【前言】**AI阿夸模型所有者及训练者@MasterSatori(以下也称“我”)希望通过《AI阿夸模型使用协议》(以下简称“本协议”)向您说明您在使用AI阿夸模型时应当履行的责任及使用范围。
6
+
7
+ **【特别提示】**在使用AI阿夸模型前,请您务必仔细阅读并透彻理解本协议,特别是以粗体标识的条款,您应重点阅读,在确认充分理解并同意后再开始使用。
8
+
9
+ ​ **本协议将帮助您了解以下内容:**
10
+
11
+ ​ **一、免责声明**
12
+
13
+ ​ **二、您在非个人使用场合时使用AI阿夸模型应当做的事**
14
+
15
+ ​ **三、AI阿夸模型的使用范围**
16
+
17
+ ​ **四、如何联系我**
18
+
19
+ ​ **(一) 免责声明:**
20
+
21
+ ​ **您因使用AI阿夸模型对其它任何实体(个人/企业)所造成的任何损失由您自身承担,您因使用AI阿夸模型所产生的一切法律风险及法律纠纷由您自身承担。**
22
+
23
+ ​ **(二) 您在非个人使用场合时使用AI阿夸模型应当做的事:**
24
+
25
+ ​ 1、注明soVITS项目作者:Rcell
26
+
27
+ ​ 2、注明我:MasterSatori
28
+
29
+ ​ **(三) AI阿夸模型的使用范围:**
30
+
31
+ ​ 1、您可以使用的范围:
32
+
33
+ ​ (1) 个人使用√
34
+
35
+ ​ (2) 将产生的音频用于投稿(投稿内容不得包含“您不可使用的范围”中的内容)√
36
+
37
+ ​ (3) 二创内容√
38
+
39
+ ​ (4) 非付费粉丝向同人游戏√
40
+
41
+ ​ 2、您不可使用的范围:
42
+
43
+ ​ (1) 商业使用×
44
+
45
+ ​ (2) 假冒本人×
46
+
47
+ ​ (3) 当作变声器等使用(个人使用除外)×
48
+
49
+ ​ (4) 将AI阿夸模型再次上传×
50
+
51
+ ​ (5) 将AI阿夸模型作为底模进行训练×
52
+
53
+ ​ (6) 低创内容(音频中有过多的爆音或电音属于“低创内容”)×
54
+
55
+ ​ (7) 敏感内容×
56
+
57
+ ​ 3、补充内容:
58
+
59
+ ​ 在其他未被提及的场合使用AI阿夸模型及其所产生的数据您应当联系我给出答复。
60
+
61
+ ​ **(四)如何联系我:**
62
+
63
+ ​ 1、可在b站私信我(UID:8407182)
64
+
65
+ ​ 2、可发送邮件至:[email protected]
utils.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import glob
3
+ import sys
4
+ import argparse
5
+ import logging
6
+ import json
7
+ import subprocess
8
+
9
+ import librosa
10
+ import numpy as np
11
+ import torchaudio
12
+ from scipy.io.wavfile import read
13
+ import torch
14
+ import torchvision
15
+ from torch.nn import functional as F
16
+ from commons import sequence_mask
17
+ from hubert import hubert_model
18
+ MATPLOTLIB_FLAG = False
19
+
20
+ logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
21
+ logger = logging
22
+
23
+ f0_bin = 256
24
+ f0_max = 1100.0
25
+ f0_min = 50.0
26
+ f0_mel_min = 1127 * np.log(1 + f0_min / 700)
27
+ f0_mel_max = 1127 * np.log(1 + f0_max / 700)
28
+
29
+ def f0_to_coarse(f0):
30
+ is_torch = isinstance(f0, torch.Tensor)
31
+ f0_mel = 1127 * (1 + f0 / 700).log() if is_torch else 1127 * np.log(1 + f0 / 700)
32
+ f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * (f0_bin - 2) / (f0_mel_max - f0_mel_min) + 1
33
+
34
+ f0_mel[f0_mel <= 1] = 1
35
+ f0_mel[f0_mel > f0_bin - 1] = f0_bin - 1
36
+ f0_coarse = (f0_mel + 0.5).long() if is_torch else np.rint(f0_mel).astype(np.int)
37
+ assert f0_coarse.max() <= 255 and f0_coarse.min() >= 1, (f0_coarse.max(), f0_coarse.min())
38
+ return f0_coarse
39
+
40
+
41
+ def get_hubert_model(rank=None):
42
+
43
+ hubert_soft = hubert_model.hubert_soft("hubert/hubert-soft-0d54a1f4.pt")
44
+ if rank is not None:
45
+ hubert_soft = hubert_soft.cuda(rank)
46
+ return hubert_soft
47
+
48
+ def get_hubert_content(hmodel, y=None, path=None):
49
+ if path is not None:
50
+ source, sr = torchaudio.load(path)
51
+ source = torchaudio.functional.resample(source, sr, 16000)
52
+ if len(source.shape) == 2 and source.shape[1] >= 2:
53
+ source = torch.mean(source, dim=0).unsqueeze(0)
54
+ else:
55
+ source = y
56
+ source = source.unsqueeze(0)
57
+ with torch.inference_mode():
58
+ units = hmodel.units(source)
59
+ return units.transpose(1,2)
60
+
61
+
62
+ def get_content(cmodel, y):
63
+ with torch.no_grad():
64
+ c = cmodel.extract_features(y.squeeze(1))[0]
65
+ c = c.transpose(1, 2)
66
+ return c
67
+
68
+
69
+
70
+ def transform(mel, height): # 68-92
71
+ #r = np.random.random()
72
+ #rate = r * 0.3 + 0.85 # 0.85-1.15
73
+ #height = int(mel.size(-2) * rate)
74
+ tgt = torchvision.transforms.functional.resize(mel, (height, mel.size(-1)))
75
+ if height >= mel.size(-2):
76
+ return tgt[:, :mel.size(-2), :]
77
+ else:
78
+ silence = tgt[:,-1:,:].repeat(1,mel.size(-2)-height,1)
79
+ silence += torch.randn_like(silence) / 10
80
+ return torch.cat((tgt, silence), 1)
81
+
82
+
83
+ def stretch(mel, width): # 0.5-2
84
+ return torchvision.transforms.functional.resize(mel, (mel.size(-2), width))
85
+
86
+
87
+ def load_checkpoint(checkpoint_path, model, optimizer=None):
88
+ assert os.path.isfile(checkpoint_path)
89
+ checkpoint_dict = torch.load(checkpoint_path, map_location='cpu')
90
+ iteration = checkpoint_dict['iteration']
91
+ learning_rate = checkpoint_dict['learning_rate']
92
+ if iteration is None:
93
+ iteration = 1
94
+ if learning_rate is None:
95
+ learning_rate = 0.0002
96
+ if optimizer is not None and checkpoint_dict['optimizer'] is not None:
97
+ optimizer.load_state_dict(checkpoint_dict['optimizer'])
98
+ saved_state_dict = checkpoint_dict['model']
99
+ if hasattr(model, 'module'):
100
+ state_dict = model.module.state_dict()
101
+ else:
102
+ state_dict = model.state_dict()
103
+ new_state_dict= {}
104
+ for k, v in state_dict.items():
105
+ try:
106
+ new_state_dict[k] = saved_state_dict[k]
107
+ except:
108
+ logger.info("%s is not in the checkpoint" % k)
109
+ new_state_dict[k] = v
110
+ if hasattr(model, 'module'):
111
+ model.module.load_state_dict(new_state_dict)
112
+ else:
113
+ model.load_state_dict(new_state_dict)
114
+ logger.info("Loaded checkpoint '{}' (iteration {})" .format(
115
+ checkpoint_path, iteration))
116
+ return model, optimizer, learning_rate, iteration
117
+
118
+
119
+ def save_checkpoint(model, optimizer, learning_rate, iteration, checkpoint_path):
120
+ # ckptname = checkpoint_path.split(os.sep)[-1]
121
+ # newest_step = int(ckptname.split(".")[0].split("_")[1])
122
+ # val_steps = 2000
123
+ # last_ckptname = checkpoint_path.replace(str(newest_step), str(newest_step - val_steps*3))
124
+ # if newest_step >= val_steps*3:
125
+ # os.system(f"rm {last_ckptname}")
126
+ logger.info("Saving model and optimizer state at iteration {} to {}".format(
127
+ iteration, checkpoint_path))
128
+ if hasattr(model, 'module'):
129
+ state_dict = model.module.state_dict()
130
+ else:
131
+ state_dict = model.state_dict()
132
+ torch.save({'model': state_dict,
133
+ 'iteration': iteration,
134
+ 'optimizer': optimizer.state_dict(),
135
+ 'learning_rate': learning_rate}, checkpoint_path)
136
+
137
+
138
+ def summarize(writer, global_step, scalars={}, histograms={}, images={}, audios={}, audio_sampling_rate=22050):
139
+ for k, v in scalars.items():
140
+ writer.add_scalar(k, v, global_step)
141
+ for k, v in histograms.items():
142
+ writer.add_histogram(k, v, global_step)
143
+ for k, v in images.items():
144
+ writer.add_image(k, v, global_step, dataformats='HWC')
145
+ for k, v in audios.items():
146
+ writer.add_audio(k, v, global_step, audio_sampling_rate)
147
+
148
+
149
+ def latest_checkpoint_path(dir_path, regex="G_*.pth"):
150
+ f_list = glob.glob(os.path.join(dir_path, regex))
151
+ f_list.sort(key=lambda f: int("".join(filter(str.isdigit, f))))
152
+ x = f_list[-1]
153
+ print(x)
154
+ return x
155
+
156
+
157
+ def plot_spectrogram_to_numpy(spectrogram):
158
+ global MATPLOTLIB_FLAG
159
+ if not MATPLOTLIB_FLAG:
160
+ import matplotlib
161
+ matplotlib.use("Agg")
162
+ MATPLOTLIB_FLAG = True
163
+ mpl_logger = logging.getLogger('matplotlib')
164
+ mpl_logger.setLevel(logging.WARNING)
165
+ import matplotlib.pylab as plt
166
+ import numpy as np
167
+
168
+ fig, ax = plt.subplots(figsize=(10,2))
169
+ im = ax.imshow(spectrogram, aspect="auto", origin="lower",
170
+ interpolation='none')
171
+ plt.colorbar(im, ax=ax)
172
+ plt.xlabel("Frames")
173
+ plt.ylabel("Channels")
174
+ plt.tight_layout()
175
+
176
+ fig.canvas.draw()
177
+ data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
178
+ data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
179
+ plt.close()
180
+ return data
181
+
182
+
183
+ def plot_alignment_to_numpy(alignment, info=None):
184
+ global MATPLOTLIB_FLAG
185
+ if not MATPLOTLIB_FLAG:
186
+ import matplotlib
187
+ matplotlib.use("Agg")
188
+ MATPLOTLIB_FLAG = True
189
+ mpl_logger = logging.getLogger('matplotlib')
190
+ mpl_logger.setLevel(logging.WARNING)
191
+ import matplotlib.pylab as plt
192
+ import numpy as np
193
+
194
+ fig, ax = plt.subplots(figsize=(6, 4))
195
+ im = ax.imshow(alignment.transpose(), aspect='auto', origin='lower',
196
+ interpolation='none')
197
+ fig.colorbar(im, ax=ax)
198
+ xlabel = 'Decoder timestep'
199
+ if info is not None:
200
+ xlabel += '\n\n' + info
201
+ plt.xlabel(xlabel)
202
+ plt.ylabel('Encoder timestep')
203
+ plt.tight_layout()
204
+
205
+ fig.canvas.draw()
206
+ data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
207
+ data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
208
+ plt.close()
209
+ return data
210
+
211
+
212
+ def load_wav_to_torch(full_path):
213
+ sampling_rate, data = read(full_path)
214
+ return torch.FloatTensor(data.astype(np.float32)), sampling_rate
215
+
216
+
217
+ def load_filepaths_and_text(filename, split="|"):
218
+ with open(filename, encoding='utf-8') as f:
219
+ filepaths_and_text = [line.strip().split(split) for line in f]
220
+ return filepaths_and_text
221
+
222
+
223
+ def get_hparams(init=True):
224
+ parser = argparse.ArgumentParser()
225
+ parser.add_argument('-c', '--config', type=str, default="./configs/base.json",
226
+ help='JSON file for configuration')
227
+ parser.add_argument('-m', '--model', type=str, required=True,
228
+ help='Model name')
229
+
230
+ args = parser.parse_args()
231
+ model_dir = os.path.join("./logs", args.model)
232
+
233
+ if not os.path.exists(model_dir):
234
+ os.makedirs(model_dir)
235
+
236
+ config_path = args.config
237
+ config_save_path = os.path.join(model_dir, "config.json")
238
+ if init:
239
+ with open(config_path, "r") as f:
240
+ data = f.read()
241
+ with open(config_save_path, "w") as f:
242
+ f.write(data)
243
+ else:
244
+ with open(config_save_path, "r") as f:
245
+ data = f.read()
246
+ config = json.loads(data)
247
+
248
+ hparams = HParams(**config)
249
+ hparams.model_dir = model_dir
250
+ return hparams
251
+
252
+
253
+ def get_hparams_from_dir(model_dir):
254
+ config_save_path = os.path.join(model_dir, "config.json")
255
+ with open(config_save_path, "r") as f:
256
+ data = f.read()
257
+ config = json.loads(data)
258
+
259
+ hparams =HParams(**config)
260
+ hparams.model_dir = model_dir
261
+ return hparams
262
+
263
+
264
+ def get_hparams_from_file(config_path):
265
+ with open(config_path, "r") as f:
266
+ data = f.read()
267
+ config = json.loads(data)
268
+
269
+ hparams =HParams(**config)
270
+ return hparams
271
+
272
+
273
+ def check_git_hash(model_dir):
274
+ source_dir = os.path.dirname(os.path.realpath(__file__))
275
+ if not os.path.exists(os.path.join(source_dir, ".git")):
276
+ logger.warn("{} is not a git repository, therefore hash value comparison will be ignored.".format(
277
+ source_dir
278
+ ))
279
+ return
280
+
281
+ cur_hash = subprocess.getoutput("git rev-parse HEAD")
282
+
283
+ path = os.path.join(model_dir, "githash")
284
+ if os.path.exists(path):
285
+ saved_hash = open(path).read()
286
+ if saved_hash != cur_hash:
287
+ logger.warn("git hash values are different. {}(saved) != {}(current)".format(
288
+ saved_hash[:8], cur_hash[:8]))
289
+ else:
290
+ open(path, "w").write(cur_hash)
291
+
292
+
293
+ def get_logger(model_dir, filename="train.log"):
294
+ global logger
295
+ logger = logging.getLogger(os.path.basename(model_dir))
296
+ logger.setLevel(logging.DEBUG)
297
+
298
+ formatter = logging.Formatter("%(asctime)s\t%(name)s\t%(levelname)s\t%(message)s")
299
+ if not os.path.exists(model_dir):
300
+ os.makedirs(model_dir)
301
+ h = logging.FileHandler(os.path.join(model_dir, filename))
302
+ h.setLevel(logging.DEBUG)
303
+ h.setFormatter(formatter)
304
+ logger.addHandler(h)
305
+ return logger
306
+
307
+
308
+ class HParams():
309
+ def __init__(self, **kwargs):
310
+ for k, v in kwargs.items():
311
+ if type(v) == dict:
312
+ v = HParams(**v)
313
+ self[k] = v
314
+
315
+ def keys(self):
316
+ return self.__dict__.keys()
317
+
318
+ def items(self):
319
+ return self.__dict__.items()
320
+
321
+ def values(self):
322
+ return self.__dict__.values()
323
+
324
+ def __len__(self):
325
+ return len(self.__dict__)
326
+
327
+ def __getitem__(self, key):
328
+ return getattr(self, key)
329
+
330
+ def __setitem__(self, key, value):
331
+ return setattr(self, key, value)
332
+
333
+ def __contains__(self, key):
334
+ return key in self.__dict__
335
+
336
+ def __repr__(self):
337
+ return self.__dict__.__repr__()
338
+
vdecoder/__init__.py ADDED
File without changes
vdecoder/hifigan/env.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+
4
+
5
+ class AttrDict(dict):
6
+ def __init__(self, *args, **kwargs):
7
+ super(AttrDict, self).__init__(*args, **kwargs)
8
+ self.__dict__ = self
9
+
10
+
11
+ def build_env(config, config_name, path):
12
+ t_path = os.path.join(path, config_name)
13
+ if config != t_path:
14
+ os.makedirs(path, exist_ok=True)
15
+ shutil.copyfile(config, os.path.join(path, config_name))
vdecoder/hifigan/models.py ADDED
@@ -0,0 +1,500 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ from .env import AttrDict
4
+ import numpy as np
5
+ import torch
6
+ import torch.nn.functional as F
7
+ import torch.nn as nn
8
+ from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
9
+ from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
10
+ from .utils import init_weights, get_padding
11
+
12
+ LRELU_SLOPE = 0.1
13
+
14
+
15
+ def load_model(model_path, device='cuda'):
16
+ config_file = os.path.join(os.path.split(model_path)[0], 'config.json')
17
+ with open(config_file) as f:
18
+ data = f.read()
19
+
20
+ global h
21
+ json_config = json.loads(data)
22
+ h = AttrDict(json_config)
23
+
24
+ generator = Generator(h).to(device)
25
+
26
+ cp_dict = torch.load(model_path)
27
+ generator.load_state_dict(cp_dict['generator'])
28
+ generator.eval()
29
+ generator.remove_weight_norm()
30
+ del cp_dict
31
+ return generator, h
32
+
33
+
34
+ class ResBlock1(torch.nn.Module):
35
+ def __init__(self, h, channels, kernel_size=3, dilation=(1, 3, 5)):
36
+ super(ResBlock1, self).__init__()
37
+ self.h = h
38
+ self.convs1 = nn.ModuleList([
39
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
40
+ padding=get_padding(kernel_size, dilation[0]))),
41
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
42
+ padding=get_padding(kernel_size, dilation[1]))),
43
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
44
+ padding=get_padding(kernel_size, dilation[2])))
45
+ ])
46
+ self.convs1.apply(init_weights)
47
+
48
+ self.convs2 = nn.ModuleList([
49
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
50
+ padding=get_padding(kernel_size, 1))),
51
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
52
+ padding=get_padding(kernel_size, 1))),
53
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
54
+ padding=get_padding(kernel_size, 1)))
55
+ ])
56
+ self.convs2.apply(init_weights)
57
+
58
+ def forward(self, x):
59
+ for c1, c2 in zip(self.convs1, self.convs2):
60
+ xt = F.leaky_relu(x, LRELU_SLOPE)
61
+ xt = c1(xt)
62
+ xt = F.leaky_relu(xt, LRELU_SLOPE)
63
+ xt = c2(xt)
64
+ x = xt + x
65
+ return x
66
+
67
+ def remove_weight_norm(self):
68
+ for l in self.convs1:
69
+ remove_weight_norm(l)
70
+ for l in self.convs2:
71
+ remove_weight_norm(l)
72
+
73
+
74
+ class ResBlock2(torch.nn.Module):
75
+ def __init__(self, h, channels, kernel_size=3, dilation=(1, 3)):
76
+ super(ResBlock2, self).__init__()
77
+ self.h = h
78
+ self.convs = nn.ModuleList([
79
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
80
+ padding=get_padding(kernel_size, dilation[0]))),
81
+ weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
82
+ padding=get_padding(kernel_size, dilation[1])))
83
+ ])
84
+ self.convs.apply(init_weights)
85
+
86
+ def forward(self, x):
87
+ for c in self.convs:
88
+ xt = F.leaky_relu(x, LRELU_SLOPE)
89
+ xt = c(xt)
90
+ x = xt + x
91
+ return x
92
+
93
+ def remove_weight_norm(self):
94
+ for l in self.convs:
95
+ remove_weight_norm(l)
96
+
97
+
98
+ class SineGen(torch.nn.Module):
99
+ """ Definition of sine generator
100
+ SineGen(samp_rate, harmonic_num = 0,
101
+ sine_amp = 0.1, noise_std = 0.003,
102
+ voiced_threshold = 0,
103
+ flag_for_pulse=False)
104
+ samp_rate: sampling rate in Hz
105
+ harmonic_num: number of harmonic overtones (default 0)
106
+ sine_amp: amplitude of sine-wavefrom (default 0.1)
107
+ noise_std: std of Gaussian noise (default 0.003)
108
+ voiced_thoreshold: F0 threshold for U/V classification (default 0)
109
+ flag_for_pulse: this SinGen is used inside PulseGen (default False)
110
+ Note: when flag_for_pulse is True, the first time step of a voiced
111
+ segment is always sin(np.pi) or cos(0)
112
+ """
113
+
114
+ def __init__(self, samp_rate, harmonic_num=0,
115
+ sine_amp=0.1, noise_std=0.003,
116
+ voiced_threshold=0,
117
+ flag_for_pulse=False):
118
+ super(SineGen, self).__init__()
119
+ self.sine_amp = sine_amp
120
+ self.noise_std = noise_std
121
+ self.harmonic_num = harmonic_num
122
+ self.dim = self.harmonic_num + 1
123
+ self.sampling_rate = samp_rate
124
+ self.voiced_threshold = voiced_threshold
125
+ self.flag_for_pulse = flag_for_pulse
126
+
127
+ def _f02uv(self, f0):
128
+ # generate uv signal
129
+ uv = (f0 > self.voiced_threshold).type(torch.float32)
130
+ return uv
131
+
132
+ def _f02sine(self, f0_values):
133
+ """ f0_values: (batchsize, length, dim)
134
+ where dim indicates fundamental tone and overtones
135
+ """
136
+ # convert to F0 in rad. The interger part n can be ignored
137
+ # because 2 * np.pi * n doesn't affect phase
138
+ rad_values = (f0_values / self.sampling_rate) % 1
139
+
140
+ # initial phase noise (no noise for fundamental component)
141
+ rand_ini = torch.rand(f0_values.shape[0], f0_values.shape[2], \
142
+ device=f0_values.device)
143
+ rand_ini[:, 0] = 0
144
+ rad_values[:, 0, :] = rad_values[:, 0, :] + rand_ini
145
+
146
+ # instantanouse phase sine[t] = sin(2*pi \sum_i=1 ^{t} rad)
147
+ if not self.flag_for_pulse:
148
+ # for normal case
149
+
150
+ # To prevent torch.cumsum numerical overflow,
151
+ # it is necessary to add -1 whenever \sum_k=1^n rad_value_k > 1.
152
+ # Buffer tmp_over_one_idx indicates the time step to add -1.
153
+ # This will not change F0 of sine because (x-1) * 2*pi = x * 2*pi
154
+ tmp_over_one = torch.cumsum(rad_values, 1) % 1
155
+ tmp_over_one_idx = (torch.diff(tmp_over_one, dim=1)) < 0
156
+ cumsum_shift = torch.zeros_like(rad_values)
157
+ cumsum_shift[:, 1:, :] = tmp_over_one_idx * -1.0
158
+
159
+ sines = torch.sin(torch.cumsum(rad_values + cumsum_shift, dim=1)
160
+ * 2 * np.pi)
161
+ else:
162
+ # If necessary, make sure that the first time step of every
163
+ # voiced segments is sin(pi) or cos(0)
164
+ # This is used for pulse-train generation
165
+
166
+ # identify the last time step in unvoiced segments
167
+ uv = self._f02uv(f0_values)
168
+ uv_1 = torch.roll(uv, shifts=-1, dims=1)
169
+ uv_1[:, -1, :] = 1
170
+ u_loc = (uv < 1) * (uv_1 > 0)
171
+
172
+ # get the instantanouse phase
173
+ tmp_cumsum = torch.cumsum(rad_values, dim=1)
174
+ # different batch needs to be processed differently
175
+ for idx in range(f0_values.shape[0]):
176
+ temp_sum = tmp_cumsum[idx, u_loc[idx, :, 0], :]
177
+ temp_sum[1:, :] = temp_sum[1:, :] - temp_sum[0:-1, :]
178
+ # stores the accumulation of i.phase within
179
+ # each voiced segments
180
+ tmp_cumsum[idx, :, :] = 0
181
+ tmp_cumsum[idx, u_loc[idx, :, 0], :] = temp_sum
182
+
183
+ # rad_values - tmp_cumsum: remove the accumulation of i.phase
184
+ # within the previous voiced segment.
185
+ i_phase = torch.cumsum(rad_values - tmp_cumsum, dim=1)
186
+
187
+ # get the sines
188
+ sines = torch.cos(i_phase * 2 * np.pi)
189
+ return sines
190
+
191
+ def forward(self, f0):
192
+ """ sine_tensor, uv = forward(f0)
193
+ input F0: tensor(batchsize=1, length, dim=1)
194
+ f0 for unvoiced steps should be 0
195
+ output sine_tensor: tensor(batchsize=1, length, dim)
196
+ output uv: tensor(batchsize=1, length, 1)
197
+ """
198
+ with torch.no_grad():
199
+ f0_buf = torch.zeros(f0.shape[0], f0.shape[1], self.dim,
200
+ device=f0.device)
201
+ # fundamental component
202
+ fn = torch.multiply(f0, torch.FloatTensor([[range(1, self.harmonic_num + 2)]]).to(f0.device))
203
+
204
+ # generate sine waveforms
205
+ sine_waves = self._f02sine(fn) * self.sine_amp
206
+
207
+ # generate uv signal
208
+ # uv = torch.ones(f0.shape)
209
+ # uv = uv * (f0 > self.voiced_threshold)
210
+ uv = self._f02uv(f0)
211
+
212
+ # noise: for unvoiced should be similar to sine_amp
213
+ # std = self.sine_amp/3 -> max value ~ self.sine_amp
214
+ # . for voiced regions is self.noise_std
215
+ noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3
216
+ noise = noise_amp * torch.randn_like(sine_waves)
217
+
218
+ # first: set the unvoiced part to 0 by uv
219
+ # then: additive noise
220
+ sine_waves = sine_waves * uv + noise
221
+ return sine_waves, uv, noise
222
+
223
+
224
+ class SourceModuleHnNSF(torch.nn.Module):
225
+ """ SourceModule for hn-nsf
226
+ SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1,
227
+ add_noise_std=0.003, voiced_threshod=0)
228
+ sampling_rate: sampling_rate in Hz
229
+ harmonic_num: number of harmonic above F0 (default: 0)
230
+ sine_amp: amplitude of sine source signal (default: 0.1)
231
+ add_noise_std: std of additive Gaussian noise (default: 0.003)
232
+ note that amplitude of noise in unvoiced is decided
233
+ by sine_amp
234
+ voiced_threshold: threhold to set U/V given F0 (default: 0)
235
+ Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
236
+ F0_sampled (batchsize, length, 1)
237
+ Sine_source (batchsize, length, 1)
238
+ noise_source (batchsize, length 1)
239
+ uv (batchsize, length, 1)
240
+ """
241
+
242
+ def __init__(self, sampling_rate, harmonic_num=0, sine_amp=0.1,
243
+ add_noise_std=0.003, voiced_threshod=0):
244
+ super(SourceModuleHnNSF, self).__init__()
245
+
246
+ self.sine_amp = sine_amp
247
+ self.noise_std = add_noise_std
248
+
249
+ # to produce sine waveforms
250
+ self.l_sin_gen = SineGen(sampling_rate, harmonic_num,
251
+ sine_amp, add_noise_std, voiced_threshod)
252
+
253
+ # to merge source harmonics into a single excitation
254
+ self.l_linear = torch.nn.Linear(harmonic_num + 1, 1)
255
+ self.l_tanh = torch.nn.Tanh()
256
+
257
+ def forward(self, x):
258
+ """
259
+ Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
260
+ F0_sampled (batchsize, length, 1)
261
+ Sine_source (batchsize, length, 1)
262
+ noise_source (batchsize, length 1)
263
+ """
264
+ # source for harmonic branch
265
+ sine_wavs, uv, _ = self.l_sin_gen(x)
266
+ sine_merge = self.l_tanh(self.l_linear(sine_wavs))
267
+
268
+ # source for noise branch, in the same shape as uv
269
+ noise = torch.randn_like(uv) * self.sine_amp / 3
270
+ return sine_merge, noise, uv
271
+
272
+
273
+ class Generator(torch.nn.Module):
274
+ def __init__(self, h):
275
+ super(Generator, self).__init__()
276
+ self.h = h
277
+
278
+ self.num_kernels = len(h["resblock_kernel_sizes"])
279
+ self.num_upsamples = len(h["upsample_rates"])
280
+ self.f0_upsamp = torch.nn.Upsample(scale_factor=np.prod(h["upsample_rates"]))
281
+ self.m_source = SourceModuleHnNSF(
282
+ sampling_rate=h["sampling_rate"],
283
+ harmonic_num=8)
284
+ self.noise_convs = nn.ModuleList()
285
+ self.conv_pre = weight_norm(Conv1d(h["inter_channels"], h["upsample_initial_channel"], 7, 1, padding=3))
286
+ resblock = ResBlock1 if h["resblock"] == '1' else ResBlock2
287
+ self.ups = nn.ModuleList()
288
+ for i, (u, k) in enumerate(zip(h["upsample_rates"], h["upsample_kernel_sizes"])):
289
+ c_cur = h["upsample_initial_channel"] // (2 ** (i + 1))
290
+ self.ups.append(weight_norm(
291
+ ConvTranspose1d(h["upsample_initial_channel"] // (2 ** i), h["upsample_initial_channel"] // (2 ** (i + 1)),
292
+ k, u, padding=(k - u) // 2)))
293
+ if i + 1 < len(h["upsample_rates"]): #
294
+ stride_f0 = np.prod(h["upsample_rates"][i + 1:])
295
+ self.noise_convs.append(Conv1d(
296
+ 1, c_cur, kernel_size=stride_f0 * 2, stride=stride_f0, padding=stride_f0 // 2))
297
+ else:
298
+ self.noise_convs.append(Conv1d(1, c_cur, kernel_size=1))
299
+ self.resblocks = nn.ModuleList()
300
+ for i in range(len(self.ups)):
301
+ ch = h["upsample_initial_channel"] // (2 ** (i + 1))
302
+ for j, (k, d) in enumerate(zip(h["resblock_kernel_sizes"], h["resblock_dilation_sizes"])):
303
+ self.resblocks.append(resblock(h, ch, k, d))
304
+
305
+ self.conv_post = weight_norm(Conv1d(ch, 1, 7, 1, padding=3))
306
+ self.ups.apply(init_weights)
307
+ self.conv_post.apply(init_weights)
308
+ self.cond = nn.Conv1d(h['gin_channels'], h['upsample_initial_channel'], 1)
309
+
310
+ def forward(self, x, f0, g=None):
311
+ # print(1,x.shape,f0.shape,f0[:, None].shape)
312
+ f0 = self.f0_upsamp(f0[:, None]).transpose(1, 2) # bs,n,t
313
+ # print(2,f0.shape)
314
+ har_source, noi_source, uv = self.m_source(f0)
315
+ har_source = har_source.transpose(1, 2)
316
+ x = self.conv_pre(x)
317
+ x = x + self.cond(g)
318
+ # print(124,x.shape,har_source.shape)
319
+ for i in range(self.num_upsamples):
320
+ x = F.leaky_relu(x, LRELU_SLOPE)
321
+ # print(3,x.shape)
322
+ x = self.ups[i](x)
323
+ x_source = self.noise_convs[i](har_source)
324
+ # print(4,x_source.shape,har_source.shape,x.shape)
325
+ x = x + x_source
326
+ xs = None
327
+ for j in range(self.num_kernels):
328
+ if xs is None:
329
+ xs = self.resblocks[i * self.num_kernels + j](x)
330
+ else:
331
+ xs += self.resblocks[i * self.num_kernels + j](x)
332
+ x = xs / self.num_kernels
333
+ x = F.leaky_relu(x)
334
+ x = self.conv_post(x)
335
+ x = torch.tanh(x)
336
+
337
+ return x
338
+
339
+ def remove_weight_norm(self):
340
+ print('Removing weight norm...')
341
+ for l in self.ups:
342
+ remove_weight_norm(l)
343
+ for l in self.resblocks:
344
+ l.remove_weight_norm()
345
+ remove_weight_norm(self.conv_pre)
346
+ remove_weight_norm(self.conv_post)
347
+
348
+
349
+ class DiscriminatorP(torch.nn.Module):
350
+ def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
351
+ super(DiscriminatorP, self).__init__()
352
+ self.period = period
353
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
354
+ self.convs = nn.ModuleList([
355
+ norm_f(Conv2d(1, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))),
356
+ norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))),
357
+ norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))),
358
+ norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))),
359
+ norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(2, 0))),
360
+ ])
361
+ self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
362
+
363
+ def forward(self, x):
364
+ fmap = []
365
+
366
+ # 1d to 2d
367
+ b, c, t = x.shape
368
+ if t % self.period != 0: # pad first
369
+ n_pad = self.period - (t % self.period)
370
+ x = F.pad(x, (0, n_pad), "reflect")
371
+ t = t + n_pad
372
+ x = x.view(b, c, t // self.period, self.period)
373
+
374
+ for l in self.convs:
375
+ x = l(x)
376
+ x = F.leaky_relu(x, LRELU_SLOPE)
377
+ fmap.append(x)
378
+ x = self.conv_post(x)
379
+ fmap.append(x)
380
+ x = torch.flatten(x, 1, -1)
381
+
382
+ return x, fmap
383
+
384
+
385
+ class MultiPeriodDiscriminator(torch.nn.Module):
386
+ def __init__(self, periods=None):
387
+ super(MultiPeriodDiscriminator, self).__init__()
388
+ self.periods = periods if periods is not None else [2, 3, 5, 7, 11]
389
+ self.discriminators = nn.ModuleList()
390
+ for period in self.periods:
391
+ self.discriminators.append(DiscriminatorP(period))
392
+
393
+ def forward(self, y, y_hat):
394
+ y_d_rs = []
395
+ y_d_gs = []
396
+ fmap_rs = []
397
+ fmap_gs = []
398
+ for i, d in enumerate(self.discriminators):
399
+ y_d_r, fmap_r = d(y)
400
+ y_d_g, fmap_g = d(y_hat)
401
+ y_d_rs.append(y_d_r)
402
+ fmap_rs.append(fmap_r)
403
+ y_d_gs.append(y_d_g)
404
+ fmap_gs.append(fmap_g)
405
+
406
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
407
+
408
+
409
+ class DiscriminatorS(torch.nn.Module):
410
+ def __init__(self, use_spectral_norm=False):
411
+ super(DiscriminatorS, self).__init__()
412
+ norm_f = weight_norm if use_spectral_norm == False else spectral_norm
413
+ self.convs = nn.ModuleList([
414
+ norm_f(Conv1d(1, 128, 15, 1, padding=7)),
415
+ norm_f(Conv1d(128, 128, 41, 2, groups=4, padding=20)),
416
+ norm_f(Conv1d(128, 256, 41, 2, groups=16, padding=20)),
417
+ norm_f(Conv1d(256, 512, 41, 4, groups=16, padding=20)),
418
+ norm_f(Conv1d(512, 1024, 41, 4, groups=16, padding=20)),
419
+ norm_f(Conv1d(1024, 1024, 41, 1, groups=16, padding=20)),
420
+ norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
421
+ ])
422
+ self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
423
+
424
+ def forward(self, x):
425
+ fmap = []
426
+ for l in self.convs:
427
+ x = l(x)
428
+ x = F.leaky_relu(x, LRELU_SLOPE)
429
+ fmap.append(x)
430
+ x = self.conv_post(x)
431
+ fmap.append(x)
432
+ x = torch.flatten(x, 1, -1)
433
+
434
+ return x, fmap
435
+
436
+
437
+ class MultiScaleDiscriminator(torch.nn.Module):
438
+ def __init__(self):
439
+ super(MultiScaleDiscriminator, self).__init__()
440
+ self.discriminators = nn.ModuleList([
441
+ DiscriminatorS(use_spectral_norm=True),
442
+ DiscriminatorS(),
443
+ DiscriminatorS(),
444
+ ])
445
+ self.meanpools = nn.ModuleList([
446
+ AvgPool1d(4, 2, padding=2),
447
+ AvgPool1d(4, 2, padding=2)
448
+ ])
449
+
450
+ def forward(self, y, y_hat):
451
+ y_d_rs = []
452
+ y_d_gs = []
453
+ fmap_rs = []
454
+ fmap_gs = []
455
+ for i, d in enumerate(self.discriminators):
456
+ if i != 0:
457
+ y = self.meanpools[i - 1](y)
458
+ y_hat = self.meanpools[i - 1](y_hat)
459
+ y_d_r, fmap_r = d(y)
460
+ y_d_g, fmap_g = d(y_hat)
461
+ y_d_rs.append(y_d_r)
462
+ fmap_rs.append(fmap_r)
463
+ y_d_gs.append(y_d_g)
464
+ fmap_gs.append(fmap_g)
465
+
466
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
467
+
468
+
469
+ def feature_loss(fmap_r, fmap_g):
470
+ loss = 0
471
+ for dr, dg in zip(fmap_r, fmap_g):
472
+ for rl, gl in zip(dr, dg):
473
+ loss += torch.mean(torch.abs(rl - gl))
474
+
475
+ return loss * 2
476
+
477
+
478
+ def discriminator_loss(disc_real_outputs, disc_generated_outputs):
479
+ loss = 0
480
+ r_losses = []
481
+ g_losses = []
482
+ for dr, dg in zip(disc_real_outputs, disc_generated_outputs):
483
+ r_loss = torch.mean((1 - dr) ** 2)
484
+ g_loss = torch.mean(dg ** 2)
485
+ loss += (r_loss + g_loss)
486
+ r_losses.append(r_loss.item())
487
+ g_losses.append(g_loss.item())
488
+
489
+ return loss, r_losses, g_losses
490
+
491
+
492
+ def generator_loss(disc_outputs):
493
+ loss = 0
494
+ gen_losses = []
495
+ for dg in disc_outputs:
496
+ l = torch.mean((1 - dg) ** 2)
497
+ gen_losses.append(l)
498
+ loss += l
499
+
500
+ return loss, gen_losses
vdecoder/hifigan/nvSTFT.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()
vdecoder/hifigan/utils.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import os
3
+ import matplotlib
4
+ import torch
5
+ from torch.nn.utils import weight_norm
6
+ matplotlib.use("Agg")
7
+ import matplotlib.pylab as plt
8
+
9
+
10
+ def plot_spectrogram(spectrogram):
11
+ fig, ax = plt.subplots(figsize=(10, 2))
12
+ im = ax.imshow(spectrogram, aspect="auto", origin="lower",
13
+ interpolation='none')
14
+ plt.colorbar(im, ax=ax)
15
+
16
+ fig.canvas.draw()
17
+ plt.close()
18
+
19
+ return fig
20
+
21
+
22
+ def init_weights(m, mean=0.0, std=0.01):
23
+ classname = m.__class__.__name__
24
+ if classname.find("Conv") != -1:
25
+ m.weight.data.normal_(mean, std)
26
+
27
+
28
+ def apply_weight_norm(m):
29
+ classname = m.__class__.__name__
30
+ if classname.find("Conv") != -1:
31
+ weight_norm(m)
32
+
33
+
34
+ def get_padding(kernel_size, dilation=1):
35
+ return int((kernel_size*dilation - dilation)/2)
36
+
37
+
38
+ def load_checkpoint(filepath, device):
39
+ assert os.path.isfile(filepath)
40
+ print("Loading '{}'".format(filepath))
41
+ checkpoint_dict = torch.load(filepath, map_location=device)
42
+ print("Complete.")
43
+ return checkpoint_dict
44
+
45
+
46
+ def save_checkpoint(filepath, obj):
47
+ print("Saving checkpoint to {}".format(filepath))
48
+ torch.save(obj, filepath)
49
+ print("Complete.")
50
+
51
+
52
+ def del_old_checkpoints(cp_dir, prefix, n_models=2):
53
+ pattern = os.path.join(cp_dir, prefix + '????????')
54
+ cp_list = glob.glob(pattern) # get checkpoint paths
55
+ cp_list = sorted(cp_list)# sort by iter
56
+ if len(cp_list) > n_models: # if more than n_models models are found
57
+ for cp in cp_list[:-n_models]:# delete the oldest models other than lastest n_models
58
+ open(cp, 'w').close()# empty file contents
59
+ os.unlink(cp)# delete file (move to trash when using Colab)
60
+
61
+
62
+ def scan_checkpoint(cp_dir, prefix):
63
+ pattern = os.path.join(cp_dir, prefix + '????????')
64
+ cp_list = glob.glob(pattern)
65
+ if len(cp_list) == 0:
66
+ return None
67
+ return sorted(cp_list)[-1]
68
+