videopython-chatterbox 0.1.7.post1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- chatterbox/__init__.py +14 -0
- chatterbox/models/__init__.py +0 -0
- chatterbox/models/s3gen/__init__.py +2 -0
- chatterbox/models/s3gen/configs.py +10 -0
- chatterbox/models/s3gen/const.py +2 -0
- chatterbox/models/s3gen/decoder.py +333 -0
- chatterbox/models/s3gen/f0_predictor.py +55 -0
- chatterbox/models/s3gen/flow.py +198 -0
- chatterbox/models/s3gen/flow_matching.py +246 -0
- chatterbox/models/s3gen/hifigan.py +474 -0
- chatterbox/models/s3gen/matcha/decoder.py +443 -0
- chatterbox/models/s3gen/matcha/flow_matching.py +129 -0
- chatterbox/models/s3gen/matcha/text_encoder.py +413 -0
- chatterbox/models/s3gen/matcha/transformer.py +316 -0
- chatterbox/models/s3gen/s3gen.py +362 -0
- chatterbox/models/s3gen/transformer/__init__.py +0 -0
- chatterbox/models/s3gen/transformer/activation.py +84 -0
- chatterbox/models/s3gen/transformer/attention.py +330 -0
- chatterbox/models/s3gen/transformer/convolution.py +145 -0
- chatterbox/models/s3gen/transformer/embedding.py +294 -0
- chatterbox/models/s3gen/transformer/encoder_layer.py +236 -0
- chatterbox/models/s3gen/transformer/positionwise_feed_forward.py +115 -0
- chatterbox/models/s3gen/transformer/subsampling.py +383 -0
- chatterbox/models/s3gen/transformer/upsample_encoder.py +318 -0
- chatterbox/models/s3gen/utils/class_utils.py +71 -0
- chatterbox/models/s3gen/utils/intmeanflow.py +36 -0
- chatterbox/models/s3gen/utils/mask.py +194 -0
- chatterbox/models/s3gen/utils/mel.py +85 -0
- chatterbox/models/s3gen/xvector.py +428 -0
- chatterbox/models/s3tokenizer/__init__.py +30 -0
- chatterbox/models/s3tokenizer/s3tokenizer.py +168 -0
- chatterbox/models/t3/__init__.py +1 -0
- chatterbox/models/t3/inference/alignment_stream_analyzer.py +181 -0
- chatterbox/models/t3/inference/t3_hf_backend.py +116 -0
- chatterbox/models/t3/llama_configs.py +73 -0
- chatterbox/models/t3/modules/cond_enc.py +97 -0
- chatterbox/models/t3/modules/learned_pos_emb.py +32 -0
- chatterbox/models/t3/modules/perceiver.py +212 -0
- chatterbox/models/t3/modules/t3_config.py +41 -0
- chatterbox/models/t3/t3.py +490 -0
- chatterbox/models/tokenizers/__init__.py +1 -0
- chatterbox/models/tokenizers/tokenizer.py +313 -0
- chatterbox/models/utils.py +4 -0
- chatterbox/models/voice_encoder/__init__.py +1 -0
- chatterbox/models/voice_encoder/config.py +18 -0
- chatterbox/models/voice_encoder/melspec.py +78 -0
- chatterbox/models/voice_encoder/voice_encoder.py +274 -0
- chatterbox/mtl_tts.py +317 -0
- chatterbox/tts.py +272 -0
- chatterbox/tts_turbo.py +296 -0
- chatterbox/vc.py +104 -0
- videopython_chatterbox-0.1.7.post1.dist-info/METADATA +154 -0
- videopython_chatterbox-0.1.7.post1.dist-info/RECORD +56 -0
- videopython_chatterbox-0.1.7.post1.dist-info/WHEEL +4 -0
- videopython_chatterbox-0.1.7.post1.dist-info/licenses/LICENSE +21 -0
- videopython_chatterbox-0.1.7.post1.dist-info/licenses/NOTICE +29 -0
|
@@ -0,0 +1,474 @@
|
|
|
1
|
+
# jrm: adapted from CosyVoice/cosyvoice/hifigan/generator.py
|
|
2
|
+
# most modules should be reusable, but I found their SineGen changed a git.
|
|
3
|
+
|
|
4
|
+
# Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu, Kai Hu)
|
|
5
|
+
#
|
|
6
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
7
|
+
# you may not use this file except in compliance with the License.
|
|
8
|
+
# You may obtain a copy of the License at
|
|
9
|
+
#
|
|
10
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
11
|
+
#
|
|
12
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
13
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
14
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
|
+
# See the License for the specific language governing permissions and
|
|
16
|
+
# limitations under the License.
|
|
17
|
+
|
|
18
|
+
"""HIFI-GAN"""
|
|
19
|
+
|
|
20
|
+
from typing import Dict, Optional, List
|
|
21
|
+
import numpy as np
|
|
22
|
+
from scipy.signal import get_window
|
|
23
|
+
import torch
|
|
24
|
+
import torch.nn.functional as F
|
|
25
|
+
from torch.nn import Conv1d
|
|
26
|
+
from torch.nn import ConvTranspose1d
|
|
27
|
+
from torch.nn.utils import remove_weight_norm
|
|
28
|
+
from torch.nn.utils.parametrizations import weight_norm
|
|
29
|
+
from torch.distributions.uniform import Uniform
|
|
30
|
+
from torch import nn, sin, pow
|
|
31
|
+
from torch.nn import Parameter
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Snake(nn.Module):
|
|
35
|
+
'''
|
|
36
|
+
Implementation of a sine-based periodic activation function
|
|
37
|
+
Shape:
|
|
38
|
+
- Input: (B, C, T)
|
|
39
|
+
- Output: (B, C, T), same shape as the input
|
|
40
|
+
Parameters:
|
|
41
|
+
- alpha - trainable parameter
|
|
42
|
+
References:
|
|
43
|
+
- This activation function is from this paper by Liu Ziyin, Tilman Hartwig, Masahito Ueda:
|
|
44
|
+
https://arxiv.org/abs/2006.08195
|
|
45
|
+
Examples:
|
|
46
|
+
>>> a1 = snake(256)
|
|
47
|
+
>>> x = torch.randn(256)
|
|
48
|
+
>>> x = a1(x)
|
|
49
|
+
'''
|
|
50
|
+
def __init__(self, in_features, alpha=1.0, alpha_trainable=True, alpha_logscale=False):
|
|
51
|
+
'''
|
|
52
|
+
Initialization.
|
|
53
|
+
INPUT:
|
|
54
|
+
- in_features: shape of the input
|
|
55
|
+
- alpha: trainable parameter
|
|
56
|
+
alpha is initialized to 1 by default, higher values = higher-frequency.
|
|
57
|
+
alpha will be trained along with the rest of your model.
|
|
58
|
+
'''
|
|
59
|
+
super(Snake, self).__init__()
|
|
60
|
+
self.in_features = in_features
|
|
61
|
+
|
|
62
|
+
# initialize alpha
|
|
63
|
+
self.alpha_logscale = alpha_logscale
|
|
64
|
+
if self.alpha_logscale: # log scale alphas initialized to zeros
|
|
65
|
+
self.alpha = Parameter(torch.zeros(in_features) * alpha)
|
|
66
|
+
else: # linear scale alphas initialized to ones
|
|
67
|
+
self.alpha = Parameter(torch.ones(in_features) * alpha)
|
|
68
|
+
|
|
69
|
+
self.alpha.requires_grad = alpha_trainable
|
|
70
|
+
|
|
71
|
+
self.no_div_by_zero = 0.000000001
|
|
72
|
+
|
|
73
|
+
def forward(self, x):
|
|
74
|
+
'''
|
|
75
|
+
Forward pass of the function.
|
|
76
|
+
Applies the function to the input elementwise.
|
|
77
|
+
Snake ∶= x + 1/a * sin^2 (xa)
|
|
78
|
+
'''
|
|
79
|
+
alpha = self.alpha.unsqueeze(0).unsqueeze(-1) # line up with x to [B, C, T]
|
|
80
|
+
if self.alpha_logscale:
|
|
81
|
+
alpha = torch.exp(alpha)
|
|
82
|
+
x = x + (1.0 / (alpha + self.no_div_by_zero)) * pow(sin(x * alpha), 2)
|
|
83
|
+
|
|
84
|
+
return x
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def get_padding(kernel_size, dilation=1):
|
|
89
|
+
return int((kernel_size * dilation - dilation) / 2)
|
|
90
|
+
|
|
91
|
+
def init_weights(m, mean=0.0, std=0.01):
|
|
92
|
+
classname = m.__class__.__name__
|
|
93
|
+
if classname.find("Conv") != -1:
|
|
94
|
+
m.weight.data.normal_(mean, std)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
"""hifigan based generator implementation.
|
|
98
|
+
|
|
99
|
+
This code is modified from https://github.com/jik876/hifi-gan
|
|
100
|
+
,https://github.com/kan-bayashi/ParallelWaveGAN and
|
|
101
|
+
https://github.com/NVIDIA/BigVGAN
|
|
102
|
+
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class ResBlock(torch.nn.Module):
|
|
107
|
+
"""Residual block module in HiFiGAN/BigVGAN."""
|
|
108
|
+
def __init__(
|
|
109
|
+
self,
|
|
110
|
+
channels: int = 512,
|
|
111
|
+
kernel_size: int = 3,
|
|
112
|
+
dilations: List[int] = [1, 3, 5],
|
|
113
|
+
):
|
|
114
|
+
super(ResBlock, self).__init__()
|
|
115
|
+
self.convs1 = nn.ModuleList()
|
|
116
|
+
self.convs2 = nn.ModuleList()
|
|
117
|
+
|
|
118
|
+
for dilation in dilations:
|
|
119
|
+
self.convs1.append(
|
|
120
|
+
weight_norm(
|
|
121
|
+
Conv1d(
|
|
122
|
+
channels,
|
|
123
|
+
channels,
|
|
124
|
+
kernel_size,
|
|
125
|
+
1,
|
|
126
|
+
dilation=dilation,
|
|
127
|
+
padding=get_padding(kernel_size, dilation)
|
|
128
|
+
)
|
|
129
|
+
)
|
|
130
|
+
)
|
|
131
|
+
self.convs2.append(
|
|
132
|
+
weight_norm(
|
|
133
|
+
Conv1d(
|
|
134
|
+
channels,
|
|
135
|
+
channels,
|
|
136
|
+
kernel_size,
|
|
137
|
+
1,
|
|
138
|
+
dilation=1,
|
|
139
|
+
padding=get_padding(kernel_size, 1)
|
|
140
|
+
)
|
|
141
|
+
)
|
|
142
|
+
)
|
|
143
|
+
self.convs1.apply(init_weights)
|
|
144
|
+
self.convs2.apply(init_weights)
|
|
145
|
+
self.activations1 = nn.ModuleList([
|
|
146
|
+
Snake(channels, alpha_logscale=False)
|
|
147
|
+
for _ in range(len(self.convs1))
|
|
148
|
+
])
|
|
149
|
+
self.activations2 = nn.ModuleList([
|
|
150
|
+
Snake(channels, alpha_logscale=False)
|
|
151
|
+
for _ in range(len(self.convs2))
|
|
152
|
+
])
|
|
153
|
+
|
|
154
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
155
|
+
for idx in range(len(self.convs1)):
|
|
156
|
+
xt = self.activations1[idx](x)
|
|
157
|
+
xt = self.convs1[idx](xt)
|
|
158
|
+
xt = self.activations2[idx](xt)
|
|
159
|
+
xt = self.convs2[idx](xt)
|
|
160
|
+
x = xt + x
|
|
161
|
+
return x
|
|
162
|
+
|
|
163
|
+
def remove_weight_norm(self):
|
|
164
|
+
for idx in range(len(self.convs1)):
|
|
165
|
+
remove_weight_norm(self.convs1[idx])
|
|
166
|
+
remove_weight_norm(self.convs2[idx])
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
class SineGen(torch.nn.Module):
|
|
170
|
+
""" Definition of sine generator
|
|
171
|
+
SineGen(samp_rate, harmonic_num = 0,
|
|
172
|
+
sine_amp = 0.1, noise_std = 0.003,
|
|
173
|
+
voiced_threshold = 0,
|
|
174
|
+
flag_for_pulse=False)
|
|
175
|
+
samp_rate: sampling rate in Hz
|
|
176
|
+
harmonic_num: number of harmonic overtones (default 0)
|
|
177
|
+
sine_amp: amplitude of sine-wavefrom (default 0.1)
|
|
178
|
+
noise_std: std of Gaussian noise (default 0.003)
|
|
179
|
+
voiced_thoreshold: F0 threshold for U/V classification (default 0)
|
|
180
|
+
flag_for_pulse: this SinGen is used inside PulseGen (default False)
|
|
181
|
+
Note: when flag_for_pulse is True, the first time step of a voiced
|
|
182
|
+
segment is always sin(np.pi) or cos(0)
|
|
183
|
+
"""
|
|
184
|
+
|
|
185
|
+
def __init__(self, samp_rate, harmonic_num=0,
|
|
186
|
+
sine_amp=0.1, noise_std=0.003,
|
|
187
|
+
voiced_threshold=0):
|
|
188
|
+
super(SineGen, self).__init__()
|
|
189
|
+
self.sine_amp = sine_amp
|
|
190
|
+
self.noise_std = noise_std
|
|
191
|
+
self.harmonic_num = harmonic_num
|
|
192
|
+
self.sampling_rate = samp_rate
|
|
193
|
+
self.voiced_threshold = voiced_threshold
|
|
194
|
+
|
|
195
|
+
def _f02uv(self, f0):
|
|
196
|
+
# generate uv signal
|
|
197
|
+
uv = (f0 > self.voiced_threshold).type(torch.float32)
|
|
198
|
+
return uv
|
|
199
|
+
|
|
200
|
+
@torch.no_grad()
|
|
201
|
+
def forward(self, f0):
|
|
202
|
+
"""
|
|
203
|
+
:param f0: [B, 1, sample_len], Hz
|
|
204
|
+
:return: [B, 1, sample_len]
|
|
205
|
+
"""
|
|
206
|
+
|
|
207
|
+
F_mat = torch.zeros((f0.size(0), self.harmonic_num + 1, f0.size(-1))).to(f0.device)
|
|
208
|
+
for i in range(self.harmonic_num + 1):
|
|
209
|
+
F_mat[:, i: i + 1, :] = f0 * (i + 1) / self.sampling_rate
|
|
210
|
+
|
|
211
|
+
theta_mat = 2 * np.pi * (torch.cumsum(F_mat, dim=-1) % 1)
|
|
212
|
+
u_dist = Uniform(low=-np.pi, high=np.pi)
|
|
213
|
+
phase_vec = u_dist.sample(sample_shape=(f0.size(0), self.harmonic_num + 1, 1)).to(F_mat.device)
|
|
214
|
+
phase_vec[:, 0, :] = 0
|
|
215
|
+
|
|
216
|
+
# generate sine waveforms
|
|
217
|
+
sine_waves = self.sine_amp * torch.sin(theta_mat + phase_vec)
|
|
218
|
+
|
|
219
|
+
# generate uv signal
|
|
220
|
+
uv = self._f02uv(f0)
|
|
221
|
+
|
|
222
|
+
# noise: for unvoiced should be similar to sine_amp
|
|
223
|
+
# std = self.sine_amp/3 -> max value ~ self.sine_amp
|
|
224
|
+
# . for voiced regions is self.noise_std
|
|
225
|
+
noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3
|
|
226
|
+
noise = noise_amp * torch.randn_like(sine_waves)
|
|
227
|
+
|
|
228
|
+
# first: set the unvoiced part to 0 by uv
|
|
229
|
+
# then: additive noise
|
|
230
|
+
sine_waves = sine_waves * uv + noise
|
|
231
|
+
return sine_waves, uv, noise
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
class SourceModuleHnNSF(torch.nn.Module):
|
|
235
|
+
""" SourceModule for hn-nsf
|
|
236
|
+
SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1,
|
|
237
|
+
add_noise_std=0.003, voiced_threshod=0)
|
|
238
|
+
sampling_rate: sampling_rate in Hz
|
|
239
|
+
harmonic_num: number of harmonic above F0 (default: 0)
|
|
240
|
+
sine_amp: amplitude of sine source signal (default: 0.1)
|
|
241
|
+
add_noise_std: std of additive Gaussian noise (default: 0.003)
|
|
242
|
+
note that amplitude of noise in unvoiced is decided
|
|
243
|
+
by sine_amp
|
|
244
|
+
voiced_threshold: threhold to set U/V given F0 (default: 0)
|
|
245
|
+
Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
|
|
246
|
+
F0_sampled (batchsize, length, 1)
|
|
247
|
+
Sine_source (batchsize, length, 1)
|
|
248
|
+
noise_source (batchsize, length 1)
|
|
249
|
+
uv (batchsize, length, 1)
|
|
250
|
+
"""
|
|
251
|
+
|
|
252
|
+
def __init__(self, sampling_rate, upsample_scale, harmonic_num=0, sine_amp=0.1,
|
|
253
|
+
add_noise_std=0.003, voiced_threshod=0):
|
|
254
|
+
super(SourceModuleHnNSF, self).__init__()
|
|
255
|
+
|
|
256
|
+
self.sine_amp = sine_amp
|
|
257
|
+
self.noise_std = add_noise_std
|
|
258
|
+
|
|
259
|
+
# to produce sine waveforms
|
|
260
|
+
self.l_sin_gen = SineGen(sampling_rate, harmonic_num,
|
|
261
|
+
sine_amp, add_noise_std, voiced_threshod)
|
|
262
|
+
|
|
263
|
+
# to merge source harmonics into a single excitation
|
|
264
|
+
self.l_linear = torch.nn.Linear(harmonic_num + 1, 1)
|
|
265
|
+
self.l_tanh = torch.nn.Tanh()
|
|
266
|
+
|
|
267
|
+
def forward(self, x):
|
|
268
|
+
"""
|
|
269
|
+
Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
|
|
270
|
+
F0_sampled (batchsize, length, 1)
|
|
271
|
+
Sine_source (batchsize, length, 1)
|
|
272
|
+
noise_source (batchsize, length 1)
|
|
273
|
+
"""
|
|
274
|
+
# source for harmonic branch
|
|
275
|
+
with torch.no_grad():
|
|
276
|
+
sine_wavs, uv, _ = self.l_sin_gen(x.transpose(1, 2))
|
|
277
|
+
sine_wavs = sine_wavs.transpose(1, 2)
|
|
278
|
+
uv = uv.transpose(1, 2)
|
|
279
|
+
sine_merge = self.l_tanh(self.l_linear(sine_wavs))
|
|
280
|
+
|
|
281
|
+
# source for noise branch, in the same shape as uv
|
|
282
|
+
noise = torch.randn_like(uv) * self.sine_amp / 3
|
|
283
|
+
return sine_merge, noise, uv
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
class HiFTGenerator(nn.Module):
|
|
287
|
+
"""
|
|
288
|
+
HiFTNet Generator: Neural Source Filter + ISTFTNet
|
|
289
|
+
https://arxiv.org/abs/2309.09493
|
|
290
|
+
"""
|
|
291
|
+
def __init__(
|
|
292
|
+
self,
|
|
293
|
+
in_channels: int = 80,
|
|
294
|
+
base_channels: int = 512,
|
|
295
|
+
nb_harmonics: int = 8,
|
|
296
|
+
sampling_rate: int = 22050,
|
|
297
|
+
nsf_alpha: float = 0.1,
|
|
298
|
+
nsf_sigma: float = 0.003,
|
|
299
|
+
nsf_voiced_threshold: float = 10,
|
|
300
|
+
upsample_rates: List[int] = [8, 8],
|
|
301
|
+
upsample_kernel_sizes: List[int] = [16, 16],
|
|
302
|
+
istft_params: Dict[str, int] = {"n_fft": 16, "hop_len": 4},
|
|
303
|
+
resblock_kernel_sizes: List[int] = [3, 7, 11],
|
|
304
|
+
resblock_dilation_sizes: List[List[int]] = [[1, 3, 5], [1, 3, 5], [1, 3, 5]],
|
|
305
|
+
source_resblock_kernel_sizes: List[int] = [7, 11],
|
|
306
|
+
source_resblock_dilation_sizes: List[List[int]] = [[1, 3, 5], [1, 3, 5]],
|
|
307
|
+
lrelu_slope: float = 0.1,
|
|
308
|
+
audio_limit: float = 0.99,
|
|
309
|
+
f0_predictor: torch.nn.Module = None,
|
|
310
|
+
):
|
|
311
|
+
super(HiFTGenerator, self).__init__()
|
|
312
|
+
|
|
313
|
+
self.out_channels = 1
|
|
314
|
+
self.nb_harmonics = nb_harmonics
|
|
315
|
+
self.sampling_rate = sampling_rate
|
|
316
|
+
self.istft_params = istft_params
|
|
317
|
+
self.lrelu_slope = lrelu_slope
|
|
318
|
+
self.audio_limit = audio_limit
|
|
319
|
+
|
|
320
|
+
self.num_kernels = len(resblock_kernel_sizes)
|
|
321
|
+
self.num_upsamples = len(upsample_rates)
|
|
322
|
+
self.m_source = SourceModuleHnNSF(
|
|
323
|
+
sampling_rate=sampling_rate,
|
|
324
|
+
upsample_scale=np.prod(upsample_rates) * istft_params["hop_len"],
|
|
325
|
+
harmonic_num=nb_harmonics,
|
|
326
|
+
sine_amp=nsf_alpha,
|
|
327
|
+
add_noise_std=nsf_sigma,
|
|
328
|
+
voiced_threshod=nsf_voiced_threshold)
|
|
329
|
+
self.f0_upsamp = torch.nn.Upsample(scale_factor=np.prod(upsample_rates) * istft_params["hop_len"])
|
|
330
|
+
|
|
331
|
+
self.conv_pre = weight_norm(
|
|
332
|
+
Conv1d(in_channels, base_channels, 7, 1, padding=3)
|
|
333
|
+
)
|
|
334
|
+
|
|
335
|
+
# Up
|
|
336
|
+
self.ups = nn.ModuleList()
|
|
337
|
+
for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
|
|
338
|
+
self.ups.append(
|
|
339
|
+
weight_norm(
|
|
340
|
+
ConvTranspose1d(
|
|
341
|
+
base_channels // (2**i),
|
|
342
|
+
base_channels // (2**(i + 1)),
|
|
343
|
+
k,
|
|
344
|
+
u,
|
|
345
|
+
padding=(k - u) // 2,
|
|
346
|
+
)
|
|
347
|
+
)
|
|
348
|
+
)
|
|
349
|
+
|
|
350
|
+
# Down
|
|
351
|
+
self.source_downs = nn.ModuleList()
|
|
352
|
+
self.source_resblocks = nn.ModuleList()
|
|
353
|
+
downsample_rates = [1] + upsample_rates[::-1][:-1]
|
|
354
|
+
downsample_cum_rates = np.cumprod(downsample_rates)
|
|
355
|
+
for i, (u, k, d) in enumerate(zip(downsample_cum_rates[::-1], source_resblock_kernel_sizes, source_resblock_dilation_sizes)):
|
|
356
|
+
if u == 1:
|
|
357
|
+
self.source_downs.append(
|
|
358
|
+
Conv1d(istft_params["n_fft"] + 2, base_channels // (2 ** (i + 1)), 1, 1)
|
|
359
|
+
)
|
|
360
|
+
else:
|
|
361
|
+
self.source_downs.append(
|
|
362
|
+
Conv1d(istft_params["n_fft"] + 2, base_channels // (2 ** (i + 1)), u * 2, u, padding=(u // 2))
|
|
363
|
+
)
|
|
364
|
+
|
|
365
|
+
self.source_resblocks.append(
|
|
366
|
+
ResBlock(base_channels // (2 ** (i + 1)), k, d)
|
|
367
|
+
)
|
|
368
|
+
|
|
369
|
+
self.resblocks = nn.ModuleList()
|
|
370
|
+
for i in range(len(self.ups)):
|
|
371
|
+
ch = base_channels // (2**(i + 1))
|
|
372
|
+
for _, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)):
|
|
373
|
+
self.resblocks.append(ResBlock(ch, k, d))
|
|
374
|
+
|
|
375
|
+
self.conv_post = weight_norm(Conv1d(ch, istft_params["n_fft"] + 2, 7, 1, padding=3))
|
|
376
|
+
self.ups.apply(init_weights)
|
|
377
|
+
self.conv_post.apply(init_weights)
|
|
378
|
+
self.reflection_pad = nn.ReflectionPad1d((1, 0))
|
|
379
|
+
self.stft_window = torch.from_numpy(get_window("hann", istft_params["n_fft"], fftbins=True).astype(np.float32))
|
|
380
|
+
self.f0_predictor = f0_predictor
|
|
381
|
+
|
|
382
|
+
def remove_weight_norm(self):
|
|
383
|
+
print('Removing weight norm...')
|
|
384
|
+
for l in self.ups:
|
|
385
|
+
remove_weight_norm(l)
|
|
386
|
+
for l in self.resblocks:
|
|
387
|
+
l.remove_weight_norm()
|
|
388
|
+
remove_weight_norm(self.conv_pre)
|
|
389
|
+
remove_weight_norm(self.conv_post)
|
|
390
|
+
self.m_source.remove_weight_norm()
|
|
391
|
+
for l in self.source_downs:
|
|
392
|
+
remove_weight_norm(l)
|
|
393
|
+
for l in self.source_resblocks:
|
|
394
|
+
l.remove_weight_norm()
|
|
395
|
+
|
|
396
|
+
def _stft(self, x):
|
|
397
|
+
spec = torch.stft(
|
|
398
|
+
x,
|
|
399
|
+
self.istft_params["n_fft"], self.istft_params["hop_len"], self.istft_params["n_fft"], window=self.stft_window.to(x.device),
|
|
400
|
+
return_complex=True)
|
|
401
|
+
spec = torch.view_as_real(spec) # [B, F, TT, 2]
|
|
402
|
+
return spec[..., 0], spec[..., 1]
|
|
403
|
+
|
|
404
|
+
def _istft(self, magnitude, phase):
|
|
405
|
+
magnitude = torch.clip(magnitude, max=1e2)
|
|
406
|
+
real = magnitude * torch.cos(phase)
|
|
407
|
+
img = magnitude * torch.sin(phase)
|
|
408
|
+
inverse_transform = torch.istft(torch.complex(real, img), self.istft_params["n_fft"], self.istft_params["hop_len"],
|
|
409
|
+
self.istft_params["n_fft"], window=self.stft_window.to(magnitude.device))
|
|
410
|
+
return inverse_transform
|
|
411
|
+
|
|
412
|
+
def decode(self, x: torch.Tensor, s: torch.Tensor = torch.zeros(1, 1, 0)) -> torch.Tensor:
|
|
413
|
+
s_stft_real, s_stft_imag = self._stft(s.squeeze(1))
|
|
414
|
+
s_stft = torch.cat([s_stft_real, s_stft_imag], dim=1)
|
|
415
|
+
|
|
416
|
+
x = self.conv_pre(x)
|
|
417
|
+
for i in range(self.num_upsamples):
|
|
418
|
+
x = F.leaky_relu(x, self.lrelu_slope)
|
|
419
|
+
x = self.ups[i](x)
|
|
420
|
+
|
|
421
|
+
if i == self.num_upsamples - 1:
|
|
422
|
+
x = self.reflection_pad(x)
|
|
423
|
+
|
|
424
|
+
# fusion
|
|
425
|
+
si = self.source_downs[i](s_stft)
|
|
426
|
+
si = self.source_resblocks[i](si)
|
|
427
|
+
x = x + si
|
|
428
|
+
|
|
429
|
+
xs = None
|
|
430
|
+
for j in range(self.num_kernels):
|
|
431
|
+
if xs is None:
|
|
432
|
+
xs = self.resblocks[i * self.num_kernels + j](x)
|
|
433
|
+
else:
|
|
434
|
+
xs += self.resblocks[i * self.num_kernels + j](x)
|
|
435
|
+
x = xs / self.num_kernels
|
|
436
|
+
|
|
437
|
+
x = F.leaky_relu(x)
|
|
438
|
+
x = self.conv_post(x)
|
|
439
|
+
magnitude = torch.exp(x[:, :self.istft_params["n_fft"] // 2 + 1, :])
|
|
440
|
+
phase = torch.sin(x[:, self.istft_params["n_fft"] // 2 + 1:, :]) # actually, sin is redundancy
|
|
441
|
+
|
|
442
|
+
x = self._istft(magnitude, phase)
|
|
443
|
+
x = torch.clamp(x, -self.audio_limit, self.audio_limit)
|
|
444
|
+
return x
|
|
445
|
+
|
|
446
|
+
def forward(
|
|
447
|
+
self,
|
|
448
|
+
batch: dict,
|
|
449
|
+
device: torch.device,
|
|
450
|
+
) -> Dict[str, Optional[torch.Tensor]]:
|
|
451
|
+
speech_feat = batch['speech_feat'].transpose(1, 2).to(device)
|
|
452
|
+
# mel->f0
|
|
453
|
+
f0 = self.f0_predictor(speech_feat)
|
|
454
|
+
# f0->source
|
|
455
|
+
s = self.f0_upsamp(f0[:, None]).transpose(1, 2) # bs,n,t
|
|
456
|
+
s, _, _ = self.m_source(s)
|
|
457
|
+
s = s.transpose(1, 2)
|
|
458
|
+
# mel+source->speech
|
|
459
|
+
generated_speech = self.decode(x=speech_feat, s=s)
|
|
460
|
+
return generated_speech, f0
|
|
461
|
+
|
|
462
|
+
@torch.inference_mode()
|
|
463
|
+
def inference(self, speech_feat: torch.Tensor, cache_source: torch.Tensor = torch.zeros(1, 1, 0)) -> torch.Tensor:
|
|
464
|
+
# mel->f0
|
|
465
|
+
f0 = self.f0_predictor(speech_feat)
|
|
466
|
+
# f0->source
|
|
467
|
+
s = self.f0_upsamp(f0[:, None]).transpose(1, 2) # bs,n,t
|
|
468
|
+
s, _, _ = self.m_source(s)
|
|
469
|
+
s = s.transpose(1, 2)
|
|
470
|
+
# use cache_source to avoid glitch
|
|
471
|
+
if cache_source.shape[2] != 0:
|
|
472
|
+
s[:, :, :cache_source.shape[2]] = cache_source
|
|
473
|
+
generated_speech = self.decode(x=speech_feat, s=s)
|
|
474
|
+
return generated_speech, s
|