_Noxty commited on
Commit
8a42f74
·
verified ·
1 Parent(s): 6dd95c2

Upload 4 files

Browse files
Files changed (4) hide show
  1. libs/audio.py +60 -0
  2. libs/rmvpe.py +670 -0
  3. libs/rtrvc.py +461 -0
  4. libs/slicer2.py +260 -0
libs/audio.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import platform, os
2
+ import ffmpeg
3
+ import numpy as np
4
+ import av
5
+ from io import BytesIO
6
+ import traceback
7
+ import re
8
+
9
+
10
+ def wav2(i, o, format):
11
+ inp = av.open(i, "rb")
12
+ if format == "m4a":
13
+ format = "mp4"
14
+ out = av.open(o, "wb", format=format)
15
+ if format == "ogg":
16
+ format = "libvorbis"
17
+ if format == "mp4":
18
+ format = "aac"
19
+
20
+ ostream = out.add_stream(format)
21
+
22
+ for frame in inp.decode(audio=0):
23
+ for p in ostream.encode(frame):
24
+ out.mux(p)
25
+
26
+ for p in ostream.encode(None):
27
+ out.mux(p)
28
+
29
+ out.close()
30
+ inp.close()
31
+
32
+
33
+ def load_audio(file, sr):
34
+ try:
35
+ # https://github.com/openai/whisper/blob/main/whisper/audio.py#L26
36
+ # This launches a subprocess to decode audio while down-mixing and resampling as necessary.
37
+ # Requires the ffmpeg CLI and `ffmpeg-python` package to be installed.
38
+ file = clean_path(file) # 防止小白拷路径头尾带了空格和"和回车
39
+ if os.path.exists(file) == False:
40
+ raise RuntimeError(
41
+ "You input a wrong audio path that does not exists, please fix it!"
42
+ )
43
+ out, _ = (
44
+ ffmpeg.input(file, threads=0)
45
+ .output("-", format="f32le", acodec="pcm_f32le", ac=1, ar=sr)
46
+ .run(cmd=["ffmpeg", "-nostdin"], capture_stdout=True, capture_stderr=True)
47
+ )
48
+ except Exception as e:
49
+ traceback.print_exc()
50
+ raise RuntimeError(f"Failed to load audio: {e}")
51
+
52
+ return np.frombuffer(out, np.float32).flatten()
53
+
54
+
55
+
56
+ def clean_path(path_str):
57
+ if platform.system() == "Windows":
58
+ path_str = path_str.replace("/", "\\")
59
+ path_str = re.sub(r'[\u202a\u202b\u202c\u202d\u202e]', '', path_str) # 移除 Unicode 控制字符
60
+ return path_str.strip(" ").strip('"').strip("\n").strip('"').strip(" ")
libs/rmvpe.py ADDED
@@ -0,0 +1,670 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from io import BytesIO
2
+ import os
3
+ from typing import List, Optional, Tuple
4
+ import numpy as np
5
+ import torch
6
+
7
+ from infer.lib import jit
8
+
9
+ try:
10
+ # Fix "Torch not compiled with CUDA enabled"
11
+ import intel_extension_for_pytorch as ipex # pylint: disable=import-error, unused-import
12
+
13
+ if torch.xpu.is_available():
14
+ from infer.modules.ipex import ipex_init
15
+
16
+ ipex_init()
17
+ except Exception: # pylint: disable=broad-exception-caught
18
+ pass
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+ from librosa.util import normalize, pad_center, tiny
22
+ from scipy.signal import get_window
23
+
24
+ import logging
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ class STFT(torch.nn.Module):
30
+ def __init__(
31
+ self, filter_length=1024, hop_length=512, win_length=None, window="hann"
32
+ ):
33
+ """
34
+ This module implements an STFT using 1D convolution and 1D transpose convolutions.
35
+ This is a bit tricky so there are some cases that probably won't work as working
36
+ out the same sizes before and after in all overlap add setups is tough. Right now,
37
+ this code should work with hop lengths that are half the filter length (50% overlap
38
+ between frames).
39
+
40
+ Keyword Arguments:
41
+ filter_length {int} -- Length of filters used (default: {1024})
42
+ hop_length {int} -- Hop length of STFT (restrict to 50% overlap between frames) (default: {512})
43
+ win_length {[type]} -- Length of the window function applied to each frame (if not specified, it
44
+ equals the filter length). (default: {None})
45
+ window {str} -- Type of window to use (options are bartlett, hann, hamming, blackman, blackmanharris)
46
+ (default: {'hann'})
47
+ """
48
+ super(STFT, self).__init__()
49
+ self.filter_length = filter_length
50
+ self.hop_length = hop_length
51
+ self.win_length = win_length if win_length else filter_length
52
+ self.window = window
53
+ self.forward_transform = None
54
+ self.pad_amount = int(self.filter_length / 2)
55
+ fourier_basis = np.fft.fft(np.eye(self.filter_length))
56
+
57
+ cutoff = int((self.filter_length / 2 + 1))
58
+ fourier_basis = np.vstack(
59
+ [np.real(fourier_basis[:cutoff, :]), np.imag(fourier_basis[:cutoff, :])]
60
+ )
61
+ forward_basis = torch.FloatTensor(fourier_basis)
62
+ inverse_basis = torch.FloatTensor(np.linalg.pinv(fourier_basis))
63
+
64
+ assert filter_length >= self.win_length
65
+ # get window and zero center pad it to filter_length
66
+ fft_window = get_window(window, self.win_length, fftbins=True)
67
+ fft_window = pad_center(fft_window, size=filter_length)
68
+ fft_window = torch.from_numpy(fft_window).float()
69
+
70
+ # window the bases
71
+ forward_basis *= fft_window
72
+ inverse_basis = (inverse_basis.T * fft_window).T
73
+
74
+ self.register_buffer("forward_basis", forward_basis.float())
75
+ self.register_buffer("inverse_basis", inverse_basis.float())
76
+ self.register_buffer("fft_window", fft_window.float())
77
+
78
+ def transform(self, input_data, return_phase=False):
79
+ """Take input data (audio) to STFT domain.
80
+
81
+ Arguments:
82
+ input_data {tensor} -- Tensor of floats, with shape (num_batch, num_samples)
83
+
84
+ Returns:
85
+ magnitude {tensor} -- Magnitude of STFT with shape (num_batch,
86
+ num_frequencies, num_frames)
87
+ phase {tensor} -- Phase of STFT with shape (num_batch,
88
+ num_frequencies, num_frames)
89
+ """
90
+ input_data = F.pad(
91
+ input_data,
92
+ (self.pad_amount, self.pad_amount),
93
+ mode="reflect",
94
+ )
95
+ forward_transform = input_data.unfold(
96
+ 1, self.filter_length, self.hop_length
97
+ ).permute(0, 2, 1)
98
+ forward_transform = torch.matmul(self.forward_basis, forward_transform)
99
+ cutoff = int((self.filter_length / 2) + 1)
100
+ real_part = forward_transform[:, :cutoff, :]
101
+ imag_part = forward_transform[:, cutoff:, :]
102
+ magnitude = torch.sqrt(real_part**2 + imag_part**2)
103
+ if return_phase:
104
+ phase = torch.atan2(imag_part.data, real_part.data)
105
+ return magnitude, phase
106
+ else:
107
+ return magnitude
108
+
109
+ def inverse(self, magnitude, phase):
110
+ """Call the inverse STFT (iSTFT), given magnitude and phase tensors produced
111
+ by the ```transform``` function.
112
+
113
+ Arguments:
114
+ magnitude {tensor} -- Magnitude of STFT with shape (num_batch,
115
+ num_frequencies, num_frames)
116
+ phase {tensor} -- Phase of STFT with shape (num_batch,
117
+ num_frequencies, num_frames)
118
+
119
+ Returns:
120
+ inverse_transform {tensor} -- Reconstructed audio given magnitude and phase. Of
121
+ shape (num_batch, num_samples)
122
+ """
123
+ cat = torch.cat(
124
+ [magnitude * torch.cos(phase), magnitude * torch.sin(phase)], dim=1
125
+ )
126
+ fold = torch.nn.Fold(
127
+ output_size=(1, (cat.size(-1) - 1) * self.hop_length + self.filter_length),
128
+ kernel_size=(1, self.filter_length),
129
+ stride=(1, self.hop_length),
130
+ )
131
+ inverse_transform = torch.matmul(self.inverse_basis, cat)
132
+ inverse_transform = fold(inverse_transform)[
133
+ :, 0, 0, self.pad_amount : -self.pad_amount
134
+ ]
135
+ window_square_sum = (
136
+ self.fft_window.pow(2).repeat(cat.size(-1), 1).T.unsqueeze(0)
137
+ )
138
+ window_square_sum = fold(window_square_sum)[
139
+ :, 0, 0, self.pad_amount : -self.pad_amount
140
+ ]
141
+ inverse_transform /= window_square_sum
142
+ return inverse_transform
143
+
144
+ def forward(self, input_data):
145
+ """Take input data (audio) to STFT domain and then back to audio.
146
+
147
+ Arguments:
148
+ input_data {tensor} -- Tensor of floats, with shape (num_batch, num_samples)
149
+
150
+ Returns:
151
+ reconstruction {tensor} -- Reconstructed audio given magnitude and phase. Of
152
+ shape (num_batch, num_samples)
153
+ """
154
+ self.magnitude, self.phase = self.transform(input_data, return_phase=True)
155
+ reconstruction = self.inverse(self.magnitude, self.phase)
156
+ return reconstruction
157
+
158
+
159
+ from time import time as ttime
160
+
161
+
162
+ class BiGRU(nn.Module):
163
+ def __init__(self, input_features, hidden_features, num_layers):
164
+ super(BiGRU, self).__init__()
165
+ self.gru = nn.GRU(
166
+ input_features,
167
+ hidden_features,
168
+ num_layers=num_layers,
169
+ batch_first=True,
170
+ bidirectional=True,
171
+ )
172
+
173
+ def forward(self, x):
174
+ return self.gru(x)[0]
175
+
176
+
177
+ class ConvBlockRes(nn.Module):
178
+ def __init__(self, in_channels, out_channels, momentum=0.01):
179
+ super(ConvBlockRes, self).__init__()
180
+ self.conv = nn.Sequential(
181
+ nn.Conv2d(
182
+ in_channels=in_channels,
183
+ out_channels=out_channels,
184
+ kernel_size=(3, 3),
185
+ stride=(1, 1),
186
+ padding=(1, 1),
187
+ bias=False,
188
+ ),
189
+ nn.BatchNorm2d(out_channels, momentum=momentum),
190
+ nn.ReLU(),
191
+ nn.Conv2d(
192
+ in_channels=out_channels,
193
+ out_channels=out_channels,
194
+ kernel_size=(3, 3),
195
+ stride=(1, 1),
196
+ padding=(1, 1),
197
+ bias=False,
198
+ ),
199
+ nn.BatchNorm2d(out_channels, momentum=momentum),
200
+ nn.ReLU(),
201
+ )
202
+ # self.shortcut:Optional[nn.Module] = None
203
+ if in_channels != out_channels:
204
+ self.shortcut = nn.Conv2d(in_channels, out_channels, (1, 1))
205
+
206
+ def forward(self, x: torch.Tensor):
207
+ if not hasattr(self, "shortcut"):
208
+ return self.conv(x) + x
209
+ else:
210
+ return self.conv(x) + self.shortcut(x)
211
+
212
+
213
+ class Encoder(nn.Module):
214
+ def __init__(
215
+ self,
216
+ in_channels,
217
+ in_size,
218
+ n_encoders,
219
+ kernel_size,
220
+ n_blocks,
221
+ out_channels=16,
222
+ momentum=0.01,
223
+ ):
224
+ super(Encoder, self).__init__()
225
+ self.n_encoders = n_encoders
226
+ self.bn = nn.BatchNorm2d(in_channels, momentum=momentum)
227
+ self.layers = nn.ModuleList()
228
+ self.latent_channels = []
229
+ for i in range(self.n_encoders):
230
+ self.layers.append(
231
+ ResEncoderBlock(
232
+ in_channels, out_channels, kernel_size, n_blocks, momentum=momentum
233
+ )
234
+ )
235
+ self.latent_channels.append([out_channels, in_size])
236
+ in_channels = out_channels
237
+ out_channels *= 2
238
+ in_size //= 2
239
+ self.out_size = in_size
240
+ self.out_channel = out_channels
241
+
242
+ def forward(self, x: torch.Tensor):
243
+ concat_tensors: List[torch.Tensor] = []
244
+ x = self.bn(x)
245
+ for i, layer in enumerate(self.layers):
246
+ t, x = layer(x)
247
+ concat_tensors.append(t)
248
+ return x, concat_tensors
249
+
250
+
251
+ class ResEncoderBlock(nn.Module):
252
+ def __init__(
253
+ self, in_channels, out_channels, kernel_size, n_blocks=1, momentum=0.01
254
+ ):
255
+ super(ResEncoderBlock, self).__init__()
256
+ self.n_blocks = n_blocks
257
+ self.conv = nn.ModuleList()
258
+ self.conv.append(ConvBlockRes(in_channels, out_channels, momentum))
259
+ for i in range(n_blocks - 1):
260
+ self.conv.append(ConvBlockRes(out_channels, out_channels, momentum))
261
+ self.kernel_size = kernel_size
262
+ if self.kernel_size is not None:
263
+ self.pool = nn.AvgPool2d(kernel_size=kernel_size)
264
+
265
+ def forward(self, x):
266
+ for i, conv in enumerate(self.conv):
267
+ x = conv(x)
268
+ if self.kernel_size is not None:
269
+ return x, self.pool(x)
270
+ else:
271
+ return x
272
+
273
+
274
+ class Intermediate(nn.Module): #
275
+ def __init__(self, in_channels, out_channels, n_inters, n_blocks, momentum=0.01):
276
+ super(Intermediate, self).__init__()
277
+ self.n_inters = n_inters
278
+ self.layers = nn.ModuleList()
279
+ self.layers.append(
280
+ ResEncoderBlock(in_channels, out_channels, None, n_blocks, momentum)
281
+ )
282
+ for i in range(self.n_inters - 1):
283
+ self.layers.append(
284
+ ResEncoderBlock(out_channels, out_channels, None, n_blocks, momentum)
285
+ )
286
+
287
+ def forward(self, x):
288
+ for i, layer in enumerate(self.layers):
289
+ x = layer(x)
290
+ return x
291
+
292
+
293
+ class ResDecoderBlock(nn.Module):
294
+ def __init__(self, in_channels, out_channels, stride, n_blocks=1, momentum=0.01):
295
+ super(ResDecoderBlock, self).__init__()
296
+ out_padding = (0, 1) if stride == (1, 2) else (1, 1)
297
+ self.n_blocks = n_blocks
298
+ self.conv1 = nn.Sequential(
299
+ nn.ConvTranspose2d(
300
+ in_channels=in_channels,
301
+ out_channels=out_channels,
302
+ kernel_size=(3, 3),
303
+ stride=stride,
304
+ padding=(1, 1),
305
+ output_padding=out_padding,
306
+ bias=False,
307
+ ),
308
+ nn.BatchNorm2d(out_channels, momentum=momentum),
309
+ nn.ReLU(),
310
+ )
311
+ self.conv2 = nn.ModuleList()
312
+ self.conv2.append(ConvBlockRes(out_channels * 2, out_channels, momentum))
313
+ for i in range(n_blocks - 1):
314
+ self.conv2.append(ConvBlockRes(out_channels, out_channels, momentum))
315
+
316
+ def forward(self, x, concat_tensor):
317
+ x = self.conv1(x)
318
+ x = torch.cat((x, concat_tensor), dim=1)
319
+ for i, conv2 in enumerate(self.conv2):
320
+ x = conv2(x)
321
+ return x
322
+
323
+
324
+ class Decoder(nn.Module):
325
+ def __init__(self, in_channels, n_decoders, stride, n_blocks, momentum=0.01):
326
+ super(Decoder, self).__init__()
327
+ self.layers = nn.ModuleList()
328
+ self.n_decoders = n_decoders
329
+ for i in range(self.n_decoders):
330
+ out_channels = in_channels // 2
331
+ self.layers.append(
332
+ ResDecoderBlock(in_channels, out_channels, stride, n_blocks, momentum)
333
+ )
334
+ in_channels = out_channels
335
+
336
+ def forward(self, x: torch.Tensor, concat_tensors: List[torch.Tensor]):
337
+ for i, layer in enumerate(self.layers):
338
+ x = layer(x, concat_tensors[-1 - i])
339
+ return x
340
+
341
+
342
+ class DeepUnet(nn.Module):
343
+ def __init__(
344
+ self,
345
+ kernel_size,
346
+ n_blocks,
347
+ en_de_layers=5,
348
+ inter_layers=4,
349
+ in_channels=1,
350
+ en_out_channels=16,
351
+ ):
352
+ super(DeepUnet, self).__init__()
353
+ self.encoder = Encoder(
354
+ in_channels, 128, en_de_layers, kernel_size, n_blocks, en_out_channels
355
+ )
356
+ self.intermediate = Intermediate(
357
+ self.encoder.out_channel // 2,
358
+ self.encoder.out_channel,
359
+ inter_layers,
360
+ n_blocks,
361
+ )
362
+ self.decoder = Decoder(
363
+ self.encoder.out_channel, en_de_layers, kernel_size, n_blocks
364
+ )
365
+
366
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
367
+ x, concat_tensors = self.encoder(x)
368
+ x = self.intermediate(x)
369
+ x = self.decoder(x, concat_tensors)
370
+ return x
371
+
372
+
373
+ class E2E(nn.Module):
374
+ def __init__(
375
+ self,
376
+ n_blocks,
377
+ n_gru,
378
+ kernel_size,
379
+ en_de_layers=5,
380
+ inter_layers=4,
381
+ in_channels=1,
382
+ en_out_channels=16,
383
+ ):
384
+ super(E2E, self).__init__()
385
+ self.unet = DeepUnet(
386
+ kernel_size,
387
+ n_blocks,
388
+ en_de_layers,
389
+ inter_layers,
390
+ in_channels,
391
+ en_out_channels,
392
+ )
393
+ self.cnn = nn.Conv2d(en_out_channels, 3, (3, 3), padding=(1, 1))
394
+ if n_gru:
395
+ self.fc = nn.Sequential(
396
+ BiGRU(3 * 128, 256, n_gru),
397
+ nn.Linear(512, 360),
398
+ nn.Dropout(0.25),
399
+ nn.Sigmoid(),
400
+ )
401
+ else:
402
+ self.fc = nn.Sequential(
403
+ nn.Linear(3 * nn.N_MELS, nn.N_CLASS), nn.Dropout(0.25), nn.Sigmoid()
404
+ )
405
+
406
+ def forward(self, mel):
407
+ # print(mel.shape)
408
+ mel = mel.transpose(-1, -2).unsqueeze(1)
409
+ x = self.cnn(self.unet(mel)).transpose(1, 2).flatten(-2)
410
+ x = self.fc(x)
411
+ # print(x.shape)
412
+ return x
413
+
414
+
415
+ from librosa.filters import mel
416
+
417
+
418
+ class MelSpectrogram(torch.nn.Module):
419
+ def __init__(
420
+ self,
421
+ is_half,
422
+ n_mel_channels,
423
+ sampling_rate,
424
+ win_length,
425
+ hop_length,
426
+ n_fft=None,
427
+ mel_fmin=0,
428
+ mel_fmax=None,
429
+ clamp=1e-5,
430
+ ):
431
+ super().__init__()
432
+ n_fft = win_length if n_fft is None else n_fft
433
+ self.hann_window = {}
434
+ mel_basis = mel(
435
+ sr=sampling_rate,
436
+ n_fft=n_fft,
437
+ n_mels=n_mel_channels,
438
+ fmin=mel_fmin,
439
+ fmax=mel_fmax,
440
+ htk=True,
441
+ )
442
+ mel_basis = torch.from_numpy(mel_basis).float()
443
+ self.register_buffer("mel_basis", mel_basis)
444
+ self.n_fft = win_length if n_fft is None else n_fft
445
+ self.hop_length = hop_length
446
+ self.win_length = win_length
447
+ self.sampling_rate = sampling_rate
448
+ self.n_mel_channels = n_mel_channels
449
+ self.clamp = clamp
450
+ self.is_half = is_half
451
+
452
+ def forward(self, audio, keyshift=0, speed=1, center=True):
453
+ factor = 2 ** (keyshift / 12)
454
+ n_fft_new = int(np.round(self.n_fft * factor))
455
+ win_length_new = int(np.round(self.win_length * factor))
456
+ hop_length_new = int(np.round(self.hop_length * speed))
457
+ keyshift_key = str(keyshift) + "_" + str(audio.device)
458
+ if keyshift_key not in self.hann_window:
459
+ self.hann_window[keyshift_key] = torch.hann_window(win_length_new).to(
460
+ audio.device
461
+ )
462
+ if "privateuseone" in str(audio.device):
463
+ if not hasattr(self, "stft"):
464
+ self.stft = STFT(
465
+ filter_length=n_fft_new,
466
+ hop_length=hop_length_new,
467
+ win_length=win_length_new,
468
+ window="hann",
469
+ ).to(audio.device)
470
+ magnitude = self.stft.transform(audio)
471
+ else:
472
+ fft = torch.stft(
473
+ audio,
474
+ n_fft=n_fft_new,
475
+ hop_length=hop_length_new,
476
+ win_length=win_length_new,
477
+ window=self.hann_window[keyshift_key],
478
+ center=center,
479
+ return_complex=True,
480
+ )
481
+ magnitude = torch.sqrt(fft.real.pow(2) + fft.imag.pow(2))
482
+ if keyshift != 0:
483
+ size = self.n_fft // 2 + 1
484
+ resize = magnitude.size(1)
485
+ if resize < size:
486
+ magnitude = F.pad(magnitude, (0, 0, 0, size - resize))
487
+ magnitude = magnitude[:, :size, :] * self.win_length / win_length_new
488
+ mel_output = torch.matmul(self.mel_basis, magnitude)
489
+ if self.is_half == True:
490
+ mel_output = mel_output.half()
491
+ log_mel_spec = torch.log(torch.clamp(mel_output, min=self.clamp))
492
+ return log_mel_spec
493
+
494
+
495
+ class RMVPE:
496
+ def __init__(self, model_path: str, is_half, device=None, use_jit=False):
497
+ self.resample_kernel = {}
498
+ self.resample_kernel = {}
499
+ self.is_half = is_half
500
+ if device is None:
501
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
502
+ self.device = device
503
+ self.mel_extractor = MelSpectrogram(
504
+ is_half, 128, 16000, 1024, 160, None, 30, 8000
505
+ ).to(device)
506
+ if "privateuseone" in str(device):
507
+ import onnxruntime as ort
508
+
509
+ ort_session = ort.InferenceSession(
510
+ "%s/rmvpe.onnx" % os.environ["rmvpe_root"],
511
+ providers=["DmlExecutionProvider"],
512
+ )
513
+ self.model = ort_session
514
+ else:
515
+ if str(self.device) == "cuda":
516
+ self.device = torch.device("cuda:0")
517
+
518
+ def get_jit_model():
519
+ jit_model_path = model_path.rstrip(".pth")
520
+ jit_model_path += ".half.jit" if is_half else ".jit"
521
+ reload = False
522
+ if os.path.exists(jit_model_path):
523
+ ckpt = jit.load(jit_model_path)
524
+ model_device = ckpt["device"]
525
+ if model_device != str(self.device):
526
+ reload = True
527
+ else:
528
+ reload = True
529
+
530
+ if reload:
531
+ ckpt = jit.rmvpe_jit_export(
532
+ model_path=model_path,
533
+ mode="script",
534
+ inputs_path=None,
535
+ save_path=jit_model_path,
536
+ device=device,
537
+ is_half=is_half,
538
+ )
539
+ model = torch.jit.load(BytesIO(ckpt["model"]), map_location=device)
540
+ return model
541
+
542
+ def get_default_model():
543
+ model = E2E(4, 1, (2, 2))
544
+ ckpt = torch.load(model_path, map_location="cpu")
545
+ model.load_state_dict(ckpt)
546
+ model.eval()
547
+ if is_half:
548
+ model = model.half()
549
+ else:
550
+ model = model.float()
551
+ return model
552
+
553
+ if use_jit:
554
+ if is_half and "cpu" in str(self.device):
555
+ logger.warning(
556
+ "Use default rmvpe model. \
557
+ Jit is not supported on the CPU for half floating point"
558
+ )
559
+ self.model = get_default_model()
560
+ else:
561
+ self.model = get_jit_model()
562
+ else:
563
+ self.model = get_default_model()
564
+
565
+ self.model = self.model.to(device)
566
+ cents_mapping = 20 * np.arange(360) + 1997.3794084376191
567
+ self.cents_mapping = np.pad(cents_mapping, (4, 4)) # 368
568
+
569
+ def mel2hidden(self, mel):
570
+ with torch.no_grad():
571
+ n_frames = mel.shape[-1]
572
+ n_pad = 32 * ((n_frames - 1) // 32 + 1) - n_frames
573
+ if n_pad > 0:
574
+ mel = F.pad(mel, (0, n_pad), mode="constant")
575
+ if "privateuseone" in str(self.device):
576
+ onnx_input_name = self.model.get_inputs()[0].name
577
+ onnx_outputs_names = self.model.get_outputs()[0].name
578
+ hidden = self.model.run(
579
+ [onnx_outputs_names],
580
+ input_feed={onnx_input_name: mel.cpu().numpy()},
581
+ )[0]
582
+ else:
583
+ mel = mel.half() if self.is_half else mel.float()
584
+ hidden = self.model(mel)
585
+ return hidden[:, :n_frames]
586
+
587
+ def decode(self, hidden, thred=0.03):
588
+ cents_pred = self.to_local_average_cents(hidden, thred=thred)
589
+ f0 = 10 * (2 ** (cents_pred / 1200))
590
+ f0[f0 == 10] = 0
591
+ # f0 = np.array([10 * (2 ** (cent_pred / 1200)) if cent_pred else 0 for cent_pred in cents_pred])
592
+ return f0
593
+
594
+ def infer_from_audio(self, audio, thred=0.03):
595
+ # torch.cuda.synchronize()
596
+ # t0 = ttime()
597
+ if not torch.is_tensor(audio):
598
+ audio = torch.from_numpy(audio)
599
+ mel = self.mel_extractor(
600
+ audio.float().to(self.device).unsqueeze(0), center=True
601
+ )
602
+ # print(123123123,mel.device.type)
603
+ # torch.cuda.synchronize()
604
+ # t1 = ttime()
605
+ hidden = self.mel2hidden(mel)
606
+ # torch.cuda.synchronize()
607
+ # t2 = ttime()
608
+ # print(234234,hidden.device.type)
609
+ if "privateuseone" not in str(self.device):
610
+ hidden = hidden.squeeze(0).cpu().numpy()
611
+ else:
612
+ hidden = hidden[0]
613
+ if self.is_half == True:
614
+ hidden = hidden.astype("float32")
615
+
616
+ f0 = self.decode(hidden, thred=thred)
617
+ # torch.cuda.synchronize()
618
+ # t3 = ttime()
619
+ # print("hmvpe:%s\t%s\t%s\t%s"%(t1-t0,t2-t1,t3-t2,t3-t0))
620
+ return f0
621
+
622
+ def to_local_average_cents(self, salience, thred=0.05):
623
+ # t0 = ttime()
624
+ center = np.argmax(salience, axis=1) # 帧长#index
625
+ salience = np.pad(salience, ((0, 0), (4, 4))) # 帧长,368
626
+ # t1 = ttime()
627
+ center += 4
628
+ todo_salience = []
629
+ todo_cents_mapping = []
630
+ starts = center - 4
631
+ ends = center + 5
632
+ for idx in range(salience.shape[0]):
633
+ todo_salience.append(salience[:, starts[idx] : ends[idx]][idx])
634
+ todo_cents_mapping.append(self.cents_mapping[starts[idx] : ends[idx]])
635
+ # t2 = ttime()
636
+ todo_salience = np.array(todo_salience) # 帧长,9
637
+ todo_cents_mapping = np.array(todo_cents_mapping) # 帧长,9
638
+ product_sum = np.sum(todo_salience * todo_cents_mapping, 1)
639
+ weight_sum = np.sum(todo_salience, 1) # 帧长
640
+ devided = product_sum / weight_sum # 帧长
641
+ # t3 = ttime()
642
+ maxx = np.max(salience, axis=1) # 帧长
643
+ devided[maxx <= thred] = 0
644
+ # t4 = ttime()
645
+ # print("decode:%s\t%s\t%s\t%s" % (t1 - t0, t2 - t1, t3 - t2, t4 - t3))
646
+ return devided
647
+
648
+
649
+ if __name__ == "__main__":
650
+ import librosa
651
+ import soundfile as sf
652
+
653
+ audio, sampling_rate = sf.read(r"C:\Users\liujing04\Desktop\Z\冬之花clip1.wav")
654
+ if len(audio.shape) > 1:
655
+ audio = librosa.to_mono(audio.transpose(1, 0))
656
+ audio_bak = audio.copy()
657
+ if sampling_rate != 16000:
658
+ audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=16000)
659
+ model_path = r"D:\BaiduNetdiskDownload\RVC-beta-v2-0727AMD_realtime\rmvpe.pt"
660
+ thred = 0.03 # 0.01
661
+ device = "cuda" if torch.cuda.is_available() else "cpu"
662
+ rmvpe = RMVPE(model_path, is_half=False, device=device)
663
+ t0 = ttime()
664
+ f0 = rmvpe.infer_from_audio(audio, thred=thred)
665
+ # f0 = rmvpe.infer_from_audio(audio, thred=thred)
666
+ # f0 = rmvpe.infer_from_audio(audio, thred=thred)
667
+ # f0 = rmvpe.infer_from_audio(audio, thred=thred)
668
+ # f0 = rmvpe.infer_from_audio(audio, thred=thred)
669
+ t1 = ttime()
670
+ logger.info("%s %.2f", f0.shape, t1 - t0)
libs/rtrvc.py ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from io import BytesIO
2
+ import os
3
+ import sys
4
+ import traceback
5
+ from infer.lib import jit
6
+ from infer.lib.jit.get_synthesizer import get_synthesizer
7
+ from time import time as ttime
8
+ import fairseq
9
+ import faiss
10
+ import numpy as np
11
+ import parselmouth
12
+ import pyworld
13
+ import scipy.signal as signal
14
+ import torch
15
+ import torch.nn as nn
16
+ import torch.nn.functional as F
17
+ import torchcrepe
18
+ from torchaudio.transforms import Resample
19
+
20
+ now_dir = os.getcwd()
21
+ sys.path.append(now_dir)
22
+ from multiprocessing import Manager as M
23
+
24
+ from configs.config import Config
25
+
26
+ # config = Config()
27
+
28
+ mm = M()
29
+
30
+
31
+ def printt(strr, *args):
32
+ if len(args) == 0:
33
+ print(strr)
34
+ else:
35
+ print(strr % args)
36
+
37
+
38
+ # config.device=torch.device("cpu")########强制cpu测试
39
+ # config.is_half=False########强制cpu测试
40
+ class RVC:
41
+ def __init__(
42
+ self,
43
+ key,
44
+ formant,
45
+ pth_path,
46
+ index_path,
47
+ index_rate,
48
+ n_cpu,
49
+ inp_q,
50
+ opt_q,
51
+ config: Config,
52
+ last_rvc=None,
53
+ ) -> None:
54
+ """
55
+ 初始化
56
+ """
57
+ try:
58
+ if config.dml == True:
59
+
60
+ def forward_dml(ctx, x, scale):
61
+ ctx.scale = scale
62
+ res = x.clone().detach()
63
+ return res
64
+
65
+ fairseq.modules.grad_multiply.GradMultiply.forward = forward_dml
66
+ # global config
67
+ self.config = config
68
+ self.inp_q = inp_q
69
+ self.opt_q = opt_q
70
+ # device="cpu"########强制cpu测试
71
+ self.device = config.device
72
+ self.f0_up_key = key
73
+ self.formant_shift = formant
74
+ self.f0_min = 50
75
+ self.f0_max = 1100
76
+ self.f0_mel_min = 1127 * np.log(1 + self.f0_min / 700)
77
+ self.f0_mel_max = 1127 * np.log(1 + self.f0_max / 700)
78
+ self.n_cpu = n_cpu
79
+ self.use_jit = self.config.use_jit
80
+ self.is_half = config.is_half
81
+
82
+ if index_rate != 0:
83
+ self.index = faiss.read_index(index_path)
84
+ self.big_npy = self.index.reconstruct_n(0, self.index.ntotal)
85
+ printt("Index search enabled")
86
+ self.pth_path: str = pth_path
87
+ self.index_path = index_path
88
+ self.index_rate = index_rate
89
+ self.cache_pitch: torch.Tensor = torch.zeros(
90
+ 1024, device=self.device, dtype=torch.long
91
+ )
92
+ self.cache_pitchf = torch.zeros(
93
+ 1024, device=self.device, dtype=torch.float32
94
+ )
95
+
96
+ self.resample_kernel = {}
97
+
98
+ if last_rvc is None:
99
+ models, _, _ = fairseq.checkpoint_utils.load_model_ensemble_and_task(
100
+ ["assets/hubert/hubert_base.pt"],
101
+ suffix="",
102
+ )
103
+ hubert_model = models[0]
104
+ hubert_model = hubert_model.to(self.device)
105
+ if self.is_half:
106
+ hubert_model = hubert_model.half()
107
+ else:
108
+ hubert_model = hubert_model.float()
109
+ hubert_model.eval()
110
+ self.model = hubert_model
111
+ else:
112
+ self.model = last_rvc.model
113
+
114
+ self.net_g: nn.Module = None
115
+
116
+ def set_default_model():
117
+ self.net_g, cpt = get_synthesizer(self.pth_path, self.device)
118
+ self.tgt_sr = cpt["config"][-1]
119
+ cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0]
120
+ self.if_f0 = cpt.get("f0", 1)
121
+ self.version = cpt.get("version", "v1")
122
+ if self.is_half:
123
+ self.net_g = self.net_g.half()
124
+ else:
125
+ self.net_g = self.net_g.float()
126
+
127
+ def set_jit_model():
128
+ jit_pth_path = self.pth_path.rstrip(".pth")
129
+ jit_pth_path += ".half.jit" if self.is_half else ".jit"
130
+ reload = False
131
+ if str(self.device) == "cuda":
132
+ self.device = torch.device("cuda:0")
133
+ if os.path.exists(jit_pth_path):
134
+ cpt = jit.load(jit_pth_path)
135
+ model_device = cpt["device"]
136
+ if model_device != str(self.device):
137
+ reload = True
138
+ else:
139
+ reload = True
140
+
141
+ if reload:
142
+ cpt = jit.synthesizer_jit_export(
143
+ self.pth_path,
144
+ "script",
145
+ None,
146
+ device=self.device,
147
+ is_half=self.is_half,
148
+ )
149
+
150
+ self.tgt_sr = cpt["config"][-1]
151
+ self.if_f0 = cpt.get("f0", 1)
152
+ self.version = cpt.get("version", "v1")
153
+ self.net_g = torch.jit.load(
154
+ BytesIO(cpt["model"]), map_location=self.device
155
+ )
156
+ self.net_g.infer = self.net_g.forward
157
+ self.net_g.eval().to(self.device)
158
+
159
+ def set_synthesizer():
160
+ if self.use_jit and not config.dml:
161
+ if self.is_half and "cpu" in str(self.device):
162
+ printt(
163
+ "Use default Synthesizer model. \
164
+ Jit is not supported on the CPU for half floating point"
165
+ )
166
+ set_default_model()
167
+ else:
168
+ set_jit_model()
169
+ else:
170
+ set_default_model()
171
+
172
+ if last_rvc is None or last_rvc.pth_path != self.pth_path:
173
+ set_synthesizer()
174
+ else:
175
+ self.tgt_sr = last_rvc.tgt_sr
176
+ self.if_f0 = last_rvc.if_f0
177
+ self.version = last_rvc.version
178
+ self.is_half = last_rvc.is_half
179
+ if last_rvc.use_jit != self.use_jit:
180
+ set_synthesizer()
181
+ else:
182
+ self.net_g = last_rvc.net_g
183
+
184
+ if last_rvc is not None and hasattr(last_rvc, "model_rmvpe"):
185
+ self.model_rmvpe = last_rvc.model_rmvpe
186
+ if last_rvc is not None and hasattr(last_rvc, "model_fcpe"):
187
+ self.device_fcpe = last_rvc.device_fcpe
188
+ self.model_fcpe = last_rvc.model_fcpe
189
+ except:
190
+ printt(traceback.format_exc())
191
+
192
+ def change_key(self, new_key):
193
+ self.f0_up_key = new_key
194
+
195
+ def change_formant(self, new_formant):
196
+ self.formant_shift = new_formant
197
+
198
+ def change_index_rate(self, new_index_rate):
199
+ if new_index_rate != 0 and self.index_rate == 0:
200
+ self.index = faiss.read_index(self.index_path)
201
+ self.big_npy = self.index.reconstruct_n(0, self.index.ntotal)
202
+ printt("Index search enabled")
203
+ self.index_rate = new_index_rate
204
+
205
+ def get_f0_post(self, f0):
206
+ if not torch.is_tensor(f0):
207
+ f0 = torch.from_numpy(f0)
208
+ f0 = f0.float().to(self.device).squeeze()
209
+ f0_mel = 1127 * torch.log(1 + f0 / 700)
210
+ f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - self.f0_mel_min) * 254 / (
211
+ self.f0_mel_max - self.f0_mel_min
212
+ ) + 1
213
+ f0_mel[f0_mel <= 1] = 1
214
+ f0_mel[f0_mel > 255] = 255
215
+ f0_coarse = torch.round(f0_mel).long()
216
+ return f0_coarse, f0
217
+
218
+ def get_f0(self, x, f0_up_key, n_cpu, method="harvest"):
219
+ n_cpu = int(n_cpu)
220
+ if method == "crepe":
221
+ return self.get_f0_crepe(x, f0_up_key)
222
+ if method == "rmvpe":
223
+ return self.get_f0_rmvpe(x, f0_up_key)
224
+ if method == "fcpe":
225
+ return self.get_f0_fcpe(x, f0_up_key)
226
+ x = x.cpu().numpy()
227
+ if method == "pm":
228
+ p_len = x.shape[0] // 160 + 1
229
+ f0_min = 65
230
+ l_pad = int(np.ceil(1.5 / f0_min * 16000))
231
+ r_pad = l_pad + 1
232
+ s = parselmouth.Sound(np.pad(x, (l_pad, r_pad)), 16000).to_pitch_ac(
233
+ time_step=0.01,
234
+ voicing_threshold=0.6,
235
+ pitch_floor=f0_min,
236
+ pitch_ceiling=1100,
237
+ )
238
+ assert np.abs(s.t1 - 1.5 / f0_min) < 0.001
239
+ f0 = s.selected_array["frequency"]
240
+ if len(f0) < p_len:
241
+ f0 = np.pad(f0, (0, p_len - len(f0)))
242
+ f0 = f0[:p_len]
243
+ f0 *= pow(2, f0_up_key / 12)
244
+ return self.get_f0_post(f0)
245
+ if n_cpu == 1:
246
+ f0, t = pyworld.harvest(
247
+ x.astype(np.double),
248
+ fs=16000,
249
+ f0_ceil=1100,
250
+ f0_floor=50,
251
+ frame_period=10,
252
+ )
253
+ f0 = signal.medfilt(f0, 3)
254
+ f0 *= pow(2, f0_up_key / 12)
255
+ return self.get_f0_post(f0)
256
+ f0bak = np.zeros(x.shape[0] // 160 + 1, dtype=np.float64)
257
+ length = len(x)
258
+ part_length = 160 * ((length // 160 - 1) // n_cpu + 1)
259
+ n_cpu = (length // 160 - 1) // (part_length // 160) + 1
260
+ ts = ttime()
261
+ res_f0 = mm.dict()
262
+ for idx in range(n_cpu):
263
+ tail = part_length * (idx + 1) + 320
264
+ if idx == 0:
265
+ self.inp_q.put((idx, x[:tail], res_f0, n_cpu, ts))
266
+ else:
267
+ self.inp_q.put(
268
+ (idx, x[part_length * idx - 320 : tail], res_f0, n_cpu, ts)
269
+ )
270
+ while 1:
271
+ res_ts = self.opt_q.get()
272
+ if res_ts == ts:
273
+ break
274
+ f0s = [i[1] for i in sorted(res_f0.items(), key=lambda x: x[0])]
275
+ for idx, f0 in enumerate(f0s):
276
+ if idx == 0:
277
+ f0 = f0[:-3]
278
+ elif idx != n_cpu - 1:
279
+ f0 = f0[2:-3]
280
+ else:
281
+ f0 = f0[2:]
282
+ f0bak[part_length * idx // 160 : part_length * idx // 160 + f0.shape[0]] = (
283
+ f0
284
+ )
285
+ f0bak = signal.medfilt(f0bak, 3)
286
+ f0bak *= pow(2, f0_up_key / 12)
287
+ return self.get_f0_post(f0bak)
288
+
289
+ def get_f0_crepe(self, x, f0_up_key):
290
+ if "privateuseone" in str(
291
+ self.device
292
+ ): ###不支持dml,cpu又太慢用不成,拿fcpe顶替
293
+ return self.get_f0(x, f0_up_key, 1, "fcpe")
294
+ # printt("using crepe,device:%s"%self.device)
295
+ f0, pd = torchcrepe.predict(
296
+ x.unsqueeze(0).float(),
297
+ 16000,
298
+ 160,
299
+ self.f0_min,
300
+ self.f0_max,
301
+ "full",
302
+ batch_size=512,
303
+ # device=self.device if self.device.type!="privateuseone" else "cpu",###crepe不用半精度全部是全精度所以不愁###cpu延迟高到没法用
304
+ device=self.device,
305
+ return_periodicity=True,
306
+ )
307
+ pd = torchcrepe.filter.median(pd, 3)
308
+ f0 = torchcrepe.filter.mean(f0, 3)
309
+ f0[pd < 0.1] = 0
310
+ f0 *= pow(2, f0_up_key / 12)
311
+ return self.get_f0_post(f0)
312
+
313
+ def get_f0_rmvpe(self, x, f0_up_key):
314
+ if hasattr(self, "model_rmvpe") == False:
315
+ from infer.lib.rmvpe import RMVPE
316
+
317
+ printt("Loading rmvpe model")
318
+ self.model_rmvpe = RMVPE(
319
+ "assets/rmvpe/rmvpe.pt",
320
+ is_half=self.is_half,
321
+ device=self.device,
322
+ use_jit=self.config.use_jit,
323
+ )
324
+ f0 = self.model_rmvpe.infer_from_audio(x, thred=0.03)
325
+ f0 *= pow(2, f0_up_key / 12)
326
+ return self.get_f0_post(f0)
327
+
328
+ def get_f0_fcpe(self, x, f0_up_key):
329
+ if hasattr(self, "model_fcpe") == False:
330
+ from torchfcpe import spawn_bundled_infer_model
331
+
332
+ printt("Loading fcpe model")
333
+ if "privateuseone" in str(self.device):
334
+ self.device_fcpe = "cpu"
335
+ else:
336
+ self.device_fcpe = self.device
337
+ self.model_fcpe = spawn_bundled_infer_model(self.device_fcpe)
338
+ f0 = self.model_fcpe.infer(
339
+ x.to(self.device_fcpe).unsqueeze(0).float(),
340
+ sr=16000,
341
+ decoder_mode="local_argmax",
342
+ threshold=0.006,
343
+ )
344
+ f0 *= pow(2, f0_up_key / 12)
345
+ return self.get_f0_post(f0)
346
+
347
+ def infer(
348
+ self,
349
+ input_wav: torch.Tensor,
350
+ block_frame_16k,
351
+ skip_head,
352
+ return_length,
353
+ f0method,
354
+ ) -> np.ndarray:
355
+ t1 = ttime()
356
+ with torch.no_grad():
357
+ if self.config.is_half:
358
+ feats = input_wav.half().view(1, -1)
359
+ else:
360
+ feats = input_wav.float().view(1, -1)
361
+ padding_mask = torch.BoolTensor(feats.shape).to(self.device).fill_(False)
362
+ inputs = {
363
+ "source": feats,
364
+ "padding_mask": padding_mask,
365
+ "output_layer": 9 if self.version == "v1" else 12,
366
+ }
367
+ logits = self.model.extract_features(**inputs)
368
+ feats = (
369
+ self.model.final_proj(logits[0]) if self.version == "v1" else logits[0]
370
+ )
371
+ feats = torch.cat((feats, feats[:, -1:, :]), 1)
372
+ t2 = ttime()
373
+ try:
374
+ if hasattr(self, "index") and self.index_rate != 0:
375
+ npy = feats[0][skip_head // 2 :].cpu().numpy().astype("float32")
376
+ score, ix = self.index.search(npy, k=8)
377
+ if (ix >= 0).all():
378
+ weight = np.square(1 / score)
379
+ weight /= weight.sum(axis=1, keepdims=True)
380
+ npy = np.sum(
381
+ self.big_npy[ix] * np.expand_dims(weight, axis=2), axis=1
382
+ )
383
+ if self.config.is_half:
384
+ npy = npy.astype("float16")
385
+ feats[0][skip_head // 2 :] = (
386
+ torch.from_numpy(npy).unsqueeze(0).to(self.device)
387
+ * self.index_rate
388
+ + (1 - self.index_rate) * feats[0][skip_head // 2 :]
389
+ )
390
+ else:
391
+ printt(
392
+ "Invalid index. You MUST use added_xxxx.index but not trained_xxxx.index!"
393
+ )
394
+ else:
395
+ printt("Index search FAILED or disabled")
396
+ except:
397
+ traceback.print_exc()
398
+ printt("Index search FAILED")
399
+ t3 = ttime()
400
+ p_len = input_wav.shape[0] // 160
401
+ factor = pow(2, self.formant_shift / 12)
402
+ return_length2 = int(np.ceil(return_length * factor))
403
+ if self.if_f0 == 1:
404
+ f0_extractor_frame = block_frame_16k + 800
405
+ if f0method == "rmvpe":
406
+ f0_extractor_frame = 5120 * ((f0_extractor_frame - 1) // 5120 + 1) - 160
407
+ pitch, pitchf = self.get_f0(
408
+ input_wav[-f0_extractor_frame:], self.f0_up_key - self.formant_shift, self.n_cpu, f0method
409
+ )
410
+ shift = block_frame_16k // 160
411
+ self.cache_pitch[:-shift] = self.cache_pitch[shift:].clone()
412
+ self.cache_pitchf[:-shift] = self.cache_pitchf[shift:].clone()
413
+ self.cache_pitch[4 - pitch.shape[0] :] = pitch[3:-1]
414
+ self.cache_pitchf[4 - pitch.shape[0] :] = pitchf[3:-1]
415
+ cache_pitch = self.cache_pitch[None, -p_len:]
416
+ cache_pitchf = self.cache_pitchf[None, -p_len:] * return_length2 / return_length
417
+ t4 = ttime()
418
+ feats = F.interpolate(feats.permute(0, 2, 1), scale_factor=2).permute(0, 2, 1)
419
+ feats = feats[:, :p_len, :]
420
+ p_len = torch.LongTensor([p_len]).to(self.device)
421
+ sid = torch.LongTensor([0]).to(self.device)
422
+ skip_head = torch.LongTensor([skip_head])
423
+ return_length2 = torch.LongTensor([return_length2])
424
+ return_length = torch.LongTensor([return_length])
425
+ with torch.no_grad():
426
+ if self.if_f0 == 1:
427
+ infered_audio, _, _ = self.net_g.infer(
428
+ feats,
429
+ p_len,
430
+ cache_pitch,
431
+ cache_pitchf,
432
+ sid,
433
+ skip_head,
434
+ return_length,
435
+ return_length2,
436
+ )
437
+ else:
438
+ infered_audio, _, _ = self.net_g.infer(
439
+ feats, p_len, sid, skip_head, return_length, return_length2
440
+ )
441
+ infered_audio = infered_audio.squeeze(1).float()
442
+ upp_res = int(np.floor(factor * self.tgt_sr // 100))
443
+ if upp_res != self.tgt_sr // 100:
444
+ if upp_res not in self.resample_kernel:
445
+ self.resample_kernel[upp_res] = Resample(
446
+ orig_freq=upp_res,
447
+ new_freq=self.tgt_sr // 100,
448
+ dtype=torch.float32,
449
+ ).to(self.device)
450
+ infered_audio = self.resample_kernel[upp_res](
451
+ infered_audio[:, : return_length * upp_res]
452
+ )
453
+ t5 = ttime()
454
+ printt(
455
+ "Spent time: fea = %.3fs, index = %.3fs, f0 = %.3fs, model = %.3fs",
456
+ t2 - t1,
457
+ t3 - t2,
458
+ t4 - t3,
459
+ t5 - t4,
460
+ )
461
+ return infered_audio.squeeze()
libs/slicer2.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+
4
+ # This function is obtained from librosa.
5
+ def get_rms(
6
+ y,
7
+ frame_length=2048,
8
+ hop_length=512,
9
+ pad_mode="constant",
10
+ ):
11
+ padding = (int(frame_length // 2), int(frame_length // 2))
12
+ y = np.pad(y, padding, mode=pad_mode)
13
+
14
+ axis = -1
15
+ # put our new within-frame axis at the end for now
16
+ out_strides = y.strides + tuple([y.strides[axis]])
17
+ # Reduce the shape on the framing axis
18
+ x_shape_trimmed = list(y.shape)
19
+ x_shape_trimmed[axis] -= frame_length - 1
20
+ out_shape = tuple(x_shape_trimmed) + tuple([frame_length])
21
+ xw = np.lib.stride_tricks.as_strided(y, shape=out_shape, strides=out_strides)
22
+ if axis < 0:
23
+ target_axis = axis - 1
24
+ else:
25
+ target_axis = axis + 1
26
+ xw = np.moveaxis(xw, -1, target_axis)
27
+ # Downsample along the target axis
28
+ slices = [slice(None)] * xw.ndim
29
+ slices[axis] = slice(0, None, hop_length)
30
+ x = xw[tuple(slices)]
31
+
32
+ # Calculate power
33
+ power = np.mean(np.abs(x) ** 2, axis=-2, keepdims=True)
34
+
35
+ return np.sqrt(power)
36
+
37
+
38
+ class Slicer:
39
+ def __init__(
40
+ self,
41
+ sr: int,
42
+ threshold: float = -40.0,
43
+ min_length: int = 5000,
44
+ min_interval: int = 300,
45
+ hop_size: int = 20,
46
+ max_sil_kept: int = 5000,
47
+ ):
48
+ if not min_length >= min_interval >= hop_size:
49
+ raise ValueError(
50
+ "The following condition must be satisfied: min_length >= min_interval >= hop_size"
51
+ )
52
+ if not max_sil_kept >= hop_size:
53
+ raise ValueError(
54
+ "The following condition must be satisfied: max_sil_kept >= hop_size"
55
+ )
56
+ min_interval = sr * min_interval / 1000
57
+ self.threshold = 10 ** (threshold / 20.0)
58
+ self.hop_size = round(sr * hop_size / 1000)
59
+ self.win_size = min(round(min_interval), 4 * self.hop_size)
60
+ self.min_length = round(sr * min_length / 1000 / self.hop_size)
61
+ self.min_interval = round(min_interval / self.hop_size)
62
+ self.max_sil_kept = round(sr * max_sil_kept / 1000 / self.hop_size)
63
+
64
+ def _apply_slice(self, waveform, begin, end):
65
+ if len(waveform.shape) > 1:
66
+ return waveform[
67
+ :, begin * self.hop_size : min(waveform.shape[1], end * self.hop_size)
68
+ ]
69
+ else:
70
+ return waveform[
71
+ begin * self.hop_size : min(waveform.shape[0], end * self.hop_size)
72
+ ]
73
+
74
+ # @timeit
75
+ def slice(self, waveform):
76
+ if len(waveform.shape) > 1:
77
+ samples = waveform.mean(axis=0)
78
+ else:
79
+ samples = waveform
80
+ if samples.shape[0] <= self.min_length:
81
+ return [waveform]
82
+ rms_list = get_rms(
83
+ y=samples, frame_length=self.win_size, hop_length=self.hop_size
84
+ ).squeeze(0)
85
+ sil_tags = []
86
+ silence_start = None
87
+ clip_start = 0
88
+ for i, rms in enumerate(rms_list):
89
+ # Keep looping while frame is silent.
90
+ if rms < self.threshold:
91
+ # Record start of silent frames.
92
+ if silence_start is None:
93
+ silence_start = i
94
+ continue
95
+ # Keep looping while frame is not silent and silence start has not been recorded.
96
+ if silence_start is None:
97
+ continue
98
+ # Clear recorded silence start if interval is not enough or clip is too short
99
+ is_leading_silence = silence_start == 0 and i > self.max_sil_kept
100
+ need_slice_middle = (
101
+ i - silence_start >= self.min_interval
102
+ and i - clip_start >= self.min_length
103
+ )
104
+ if not is_leading_silence and not need_slice_middle:
105
+ silence_start = None
106
+ continue
107
+ # Need slicing. Record the range of silent frames to be removed.
108
+ if i - silence_start <= self.max_sil_kept:
109
+ pos = rms_list[silence_start : i + 1].argmin() + silence_start
110
+ if silence_start == 0:
111
+ sil_tags.append((0, pos))
112
+ else:
113
+ sil_tags.append((pos, pos))
114
+ clip_start = pos
115
+ elif i - silence_start <= self.max_sil_kept * 2:
116
+ pos = rms_list[
117
+ i - self.max_sil_kept : silence_start + self.max_sil_kept + 1
118
+ ].argmin()
119
+ pos += i - self.max_sil_kept
120
+ pos_l = (
121
+ rms_list[
122
+ silence_start : silence_start + self.max_sil_kept + 1
123
+ ].argmin()
124
+ + silence_start
125
+ )
126
+ pos_r = (
127
+ rms_list[i - self.max_sil_kept : i + 1].argmin()
128
+ + i
129
+ - self.max_sil_kept
130
+ )
131
+ if silence_start == 0:
132
+ sil_tags.append((0, pos_r))
133
+ clip_start = pos_r
134
+ else:
135
+ sil_tags.append((min(pos_l, pos), max(pos_r, pos)))
136
+ clip_start = max(pos_r, pos)
137
+ else:
138
+ pos_l = (
139
+ rms_list[
140
+ silence_start : silence_start + self.max_sil_kept + 1
141
+ ].argmin()
142
+ + silence_start
143
+ )
144
+ pos_r = (
145
+ rms_list[i - self.max_sil_kept : i + 1].argmin()
146
+ + i
147
+ - self.max_sil_kept
148
+ )
149
+ if silence_start == 0:
150
+ sil_tags.append((0, pos_r))
151
+ else:
152
+ sil_tags.append((pos_l, pos_r))
153
+ clip_start = pos_r
154
+ silence_start = None
155
+ # Deal with trailing silence.
156
+ total_frames = rms_list.shape[0]
157
+ if (
158
+ silence_start is not None
159
+ and total_frames - silence_start >= self.min_interval
160
+ ):
161
+ silence_end = min(total_frames, silence_start + self.max_sil_kept)
162
+ pos = rms_list[silence_start : silence_end + 1].argmin() + silence_start
163
+ sil_tags.append((pos, total_frames + 1))
164
+ # Apply and return slices.
165
+ if len(sil_tags) == 0:
166
+ return [waveform]
167
+ else:
168
+ chunks = []
169
+ if sil_tags[0][0] > 0:
170
+ chunks.append(self._apply_slice(waveform, 0, sil_tags[0][0]))
171
+ for i in range(len(sil_tags) - 1):
172
+ chunks.append(
173
+ self._apply_slice(waveform, sil_tags[i][1], sil_tags[i + 1][0])
174
+ )
175
+ if sil_tags[-1][1] < total_frames:
176
+ chunks.append(
177
+ self._apply_slice(waveform, sil_tags[-1][1], total_frames)
178
+ )
179
+ return chunks
180
+
181
+
182
+ def main():
183
+ import os.path
184
+ from argparse import ArgumentParser
185
+
186
+ import librosa
187
+ import soundfile
188
+
189
+ parser = ArgumentParser()
190
+ parser.add_argument("audio", type=str, help="The audio to be sliced")
191
+ parser.add_argument(
192
+ "--out", type=str, help="Output directory of the sliced audio clips"
193
+ )
194
+ parser.add_argument(
195
+ "--db_thresh",
196
+ type=float,
197
+ required=False,
198
+ default=-40,
199
+ help="The dB threshold for silence detection",
200
+ )
201
+ parser.add_argument(
202
+ "--min_length",
203
+ type=int,
204
+ required=False,
205
+ default=5000,
206
+ help="The minimum milliseconds required for each sliced audio clip",
207
+ )
208
+ parser.add_argument(
209
+ "--min_interval",
210
+ type=int,
211
+ required=False,
212
+ default=300,
213
+ help="The minimum milliseconds for a silence part to be sliced",
214
+ )
215
+ parser.add_argument(
216
+ "--hop_size",
217
+ type=int,
218
+ required=False,
219
+ default=10,
220
+ help="Frame length in milliseconds",
221
+ )
222
+ parser.add_argument(
223
+ "--max_sil_kept",
224
+ type=int,
225
+ required=False,
226
+ default=500,
227
+ help="The maximum silence length kept around the sliced clip, presented in milliseconds",
228
+ )
229
+ args = parser.parse_args()
230
+ out = args.out
231
+ if out is None:
232
+ out = os.path.dirname(os.path.abspath(args.audio))
233
+ audio, sr = librosa.load(args.audio, sr=None, mono=False)
234
+ slicer = Slicer(
235
+ sr=sr,
236
+ threshold=args.db_thresh,
237
+ min_length=args.min_length,
238
+ min_interval=args.min_interval,
239
+ hop_size=args.hop_size,
240
+ max_sil_kept=args.max_sil_kept,
241
+ )
242
+ chunks = slicer.slice(audio)
243
+ if not os.path.exists(out):
244
+ os.makedirs(out)
245
+ for i, chunk in enumerate(chunks):
246
+ if len(chunk.shape) > 1:
247
+ chunk = chunk.T
248
+ soundfile.write(
249
+ os.path.join(
250
+ out,
251
+ f"%s_%d.wav"
252
+ % (os.path.basename(args.audio).rsplit(".", maxsplit=1)[0], i),
253
+ ),
254
+ chunk,
255
+ sr,
256
+ )
257
+
258
+
259
+ if __name__ == "__main__":
260
+ main()