Eempostor commited on
Commit
a5c3a84
·
verified ·
1 Parent(s): ada005c

Delete lib/pipeline.py

Browse files
Files changed (1) hide show
  1. lib/pipeline.py +0 -766
lib/pipeline.py DELETED
@@ -1,766 +0,0 @@
1
- import os
2
- import sys
3
- import gc
4
- import traceback
5
- import logging
6
-
7
- logger = logging.getLogger(__name__)
8
-
9
- from functools import lru_cache
10
- from time import time as ttime
11
- from torch import Tensor
12
- import faiss
13
- import librosa
14
- import numpy as np
15
- import parselmouth
16
- import pyworld
17
- import torch.nn.functional as F
18
- from scipy import signal
19
- from tqdm import tqdm
20
-
21
- import random
22
- now_dir = os.getcwd()
23
- sys.path.append(now_dir)
24
- import re
25
- from functools import partial
26
- bh, ah = signal.butter(N=5, Wn=48, btype="high", fs=16000)
27
-
28
- input_audio_path2wav = {}
29
- import torchcrepe # Fork Feature. Crepe algo for training and preprocess
30
- import torch
31
- from lib.infer_libs.rmvpe import RMVPE
32
- from lib.infer_libs.fcpe import FCPE
33
-
34
- @lru_cache
35
- def cache_harvest_f0(input_audio_path, fs, f0max, f0min, frame_period):
36
- audio = input_audio_path2wav[input_audio_path]
37
- f0, t = pyworld.harvest(
38
- audio,
39
- fs=fs,
40
- f0_ceil=f0max,
41
- f0_floor=f0min,
42
- frame_period=frame_period,
43
- )
44
- f0 = pyworld.stonemask(audio, f0, t, fs)
45
- return f0
46
-
47
-
48
- def change_rms(data1, sr1, data2, sr2, rate): # 1是输入音频,2是输出音频,rate是2的占比
49
- # print(data1.max(),data2.max())
50
- rms1 = librosa.feature.rms(
51
- y=data1, frame_length=sr1 // 2 * 2, hop_length=sr1 // 2
52
- ) # 每半秒一个点
53
- rms2 = librosa.feature.rms(y=data2, frame_length=sr2 // 2 * 2, hop_length=sr2 // 2)
54
- rms1 = torch.from_numpy(rms1)
55
- rms1 = F.interpolate(
56
- rms1.unsqueeze(0), size=data2.shape[0], mode="linear"
57
- ).squeeze()
58
- rms2 = torch.from_numpy(rms2)
59
- rms2 = F.interpolate(
60
- rms2.unsqueeze(0), size=data2.shape[0], mode="linear"
61
- ).squeeze()
62
- rms2 = torch.max(rms2, torch.zeros_like(rms2) + 1e-6)
63
- data2 *= (
64
- torch.pow(rms1, torch.tensor(1 - rate))
65
- * torch.pow(rms2, torch.tensor(rate - 1))
66
- ).numpy()
67
- return data2
68
-
69
-
70
- class Pipeline(object):
71
- def __init__(self, tgt_sr, config):
72
- self.x_pad, self.x_query, self.x_center, self.x_max, self.is_half = (
73
- config.x_pad,
74
- config.x_query,
75
- config.x_center,
76
- config.x_max,
77
- config.is_half,
78
- )
79
- self.sr = 16000 # hubert输入采样率
80
- self.window = 160 # 每帧点数
81
- self.t_pad = self.sr * self.x_pad # 每条前后pad时间
82
- self.t_pad_tgt = tgt_sr * self.x_pad
83
- self.t_pad2 = self.t_pad * 2
84
- self.t_query = self.sr * self.x_query # 查询切点前后查询时间
85
- self.t_center = self.sr * self.x_center # 查询切点位置
86
- self.t_max = self.sr * self.x_max # 免查询时长阈值
87
- self.device = config.device
88
- self.model_rmvpe = RMVPE("%s/rmvpe.pt" % os.environ["rmvpe_root"], is_half=self.is_half, device=self.device)
89
-
90
- self.note_dict = [
91
- 65.41, 69.30, 73.42, 77.78, 82.41, 87.31,
92
- 92.50, 98.00, 103.83, 110.00, 116.54, 123.47,
93
- 130.81, 138.59, 146.83, 155.56, 164.81, 174.61,
94
- 185.00, 196.00, 207.65, 220.00, 233.08, 246.94,
95
- 261.63, 277.18, 293.66, 311.13, 329.63, 349.23,
96
- 369.99, 392.00, 415.30, 440.00, 466.16, 493.88,
97
- 523.25, 554.37, 587.33, 622.25, 659.25, 698.46,
98
- 739.99, 783.99, 830.61, 880.00, 932.33, 987.77,
99
- 1046.50, 1108.73, 1174.66, 1244.51, 1318.51, 1396.91,
100
- 1479.98, 1567.98, 1661.22, 1760.00, 1864.66, 1975.53,
101
- 2093.00, 2217.46, 2349.32, 2489.02, 2637.02, 2793.83,
102
- 2959.96, 3135.96, 3322.44, 3520.00, 3729.31, 3951.07
103
- ]
104
-
105
- # Fork Feature: Get the best torch device to use for f0 algorithms that require a torch device. Will return the type (torch.device)
106
- def get_optimal_torch_device(self, index: int = 0) -> torch.device:
107
- if torch.cuda.is_available():
108
- return torch.device(
109
- f"cuda:{index % torch.cuda.device_count()}"
110
- ) # Very fast
111
- elif torch.backends.mps.is_available():
112
- return torch.device("mps")
113
- return torch.device("cpu")
114
-
115
- # Fork Feature: Compute f0 with the crepe method
116
- def get_f0_crepe_computation(
117
- self,
118
- x,
119
- f0_min,
120
- f0_max,
121
- p_len,
122
- *args, # 512 before. Hop length changes the speed that the voice jumps to a different dramatic pitch. Lower hop lengths means more pitch accuracy but longer inference time.
123
- **kwargs, # Either use crepe-tiny "tiny" or crepe "full". Default is full
124
- ):
125
- x = x.astype(
126
- np.float32
127
- ) # fixes the F.conv2D exception. We needed to convert double to float.
128
- x /= np.quantile(np.abs(x), 0.999)
129
- torch_device = self.get_optimal_torch_device()
130
- audio = torch.from_numpy(x).to(torch_device, copy=True)
131
- audio = torch.unsqueeze(audio, dim=0)
132
- if audio.ndim == 2 and audio.shape[0] > 1:
133
- audio = torch.mean(audio, dim=0, keepdim=True).detach()
134
- audio = audio.detach()
135
- hop_length = kwargs.get('crepe_hop_length', 160)
136
- model = kwargs.get('model', 'full')
137
- print("Initiating prediction with a crepe_hop_length of: " + str(hop_length))
138
- pitch: Tensor = torchcrepe.predict(
139
- audio,
140
- self.sr,
141
- hop_length,
142
- f0_min,
143
- f0_max,
144
- model,
145
- batch_size=hop_length * 2,
146
- device=torch_device,
147
- pad=True,
148
- )
149
- p_len = p_len or x.shape[0] // hop_length
150
- # Resize the pitch for final f0
151
- source = np.array(pitch.squeeze(0).cpu().float().numpy())
152
- source[source < 0.001] = np.nan
153
- target = np.interp(
154
- np.arange(0, len(source) * p_len, len(source)) / p_len,
155
- np.arange(0, len(source)),
156
- source,
157
- )
158
- f0 = np.nan_to_num(target)
159
- return f0 # Resized f0
160
-
161
- def get_f0_official_crepe_computation(
162
- self,
163
- x,
164
- f0_min,
165
- f0_max,
166
- *args,
167
- **kwargs
168
- ):
169
- # Pick a batch size that doesn't cause memory errors on your gpu
170
- batch_size = 512
171
- # Compute pitch using first gpu
172
- audio = torch.tensor(np.copy(x))[None].float()
173
- model = kwargs.get('model', 'full')
174
- f0, pd = torchcrepe.predict(
175
- audio,
176
- self.sr,
177
- self.window,
178
- f0_min,
179
- f0_max,
180
- model,
181
- batch_size=batch_size,
182
- device=self.device,
183
- return_periodicity=True,
184
- )
185
- pd = torchcrepe.filter.median(pd, 3)
186
- f0 = torchcrepe.filter.mean(f0, 3)
187
- f0[pd < 0.1] = 0
188
- f0 = f0[0].cpu().numpy()
189
- return f0
190
-
191
- # Fork Feature: Compute pYIN f0 method
192
- def get_f0_pyin_computation(self, x, f0_min, f0_max):
193
- y, sr = librosa.load(x, sr=self.sr, mono=True)
194
- f0, _, _ = librosa.pyin(y, fmin=f0_min, fmax=f0_max, sr=self.sr)
195
- f0 = f0[1:] # Get rid of extra first frame
196
- return f0
197
-
198
- def get_pm(self, x, p_len, *args, **kwargs):
199
- f0 = parselmouth.Sound(x, self.sr).to_pitch_ac(
200
- time_step=160 / 16000,
201
- voicing_threshold=0.6,
202
- pitch_floor=kwargs.get('f0_min'),
203
- pitch_ceiling=kwargs.get('f0_max'),
204
- ).selected_array["frequency"]
205
-
206
- return np.pad(
207
- f0,
208
- [[max(0, (p_len - len(f0) + 1) // 2), max(0, p_len - len(f0) - (p_len - len(f0) + 1) // 2)]],
209
- mode="constant"
210
- )
211
-
212
- def get_harvest(self, x, *args, **kwargs):
213
- f0_spectral = pyworld.harvest(
214
- x.astype(np.double),
215
- fs=self.sr,
216
- f0_ceil=kwargs.get('f0_max'),
217
- f0_floor=kwargs.get('f0_min'),
218
- frame_period=1000 * kwargs.get('hop_length', 160) / self.sr,
219
- )
220
- return pyworld.stonemask(x.astype(np.double), *f0_spectral, self.sr)
221
-
222
- def get_dio(self, x, *args, **kwargs):
223
- f0_spectral = pyworld.dio(
224
- x.astype(np.double),
225
- fs=self.sr,
226
- f0_ceil=kwargs.get('f0_max'),
227
- f0_floor=kwargs.get('f0_min'),
228
- frame_period=1000 * kwargs.get('hop_length', 160) / self.sr,
229
- )
230
- return pyworld.stonemask(x.astype(np.double), *f0_spectral, self.sr)
231
-
232
-
233
- def get_rmvpe(self, x, *args, **kwargs):
234
- if not hasattr(self, "model_rmvpe"):
235
- from lib.infer.infer_libs.rmvpe import RMVPE
236
-
237
- logger.info(
238
- "Loading rmvpe model,%s" % "%s/rmvpe.pt" % os.environ["rmvpe_root"]
239
- )
240
- self.model_rmvpe = RMVPE(
241
- "%s/rmvpe.pt" % os.environ["rmvpe_root"],
242
- is_half=self.is_half,
243
- device=self.device,
244
- )
245
- f0 = self.model_rmvpe.infer_from_audio(x, thred=0.03)
246
-
247
- if "privateuseone" in str(self.device): # clean ortruntime memory
248
- del self.model_rmvpe.model
249
- del self.model_rmvpe
250
- logger.info("Cleaning ortruntime memory")
251
-
252
- return f0
253
-
254
-
255
- def get_pitch_dependant_rmvpe(self, x, f0_min=1, f0_max=40000, *args, **kwargs):
256
- if not hasattr(self, "model_rmvpe"):
257
- from lib.infer.infer_libs.rmvpe import RMVPE
258
-
259
- logger.info(
260
- "Loading rmvpe model,%s" % "%s/rmvpe.pt" % os.environ["rmvpe_root"]
261
- )
262
- self.model_rmvpe = RMVPE(
263
- "%s/rmvpe.pt" % os.environ["rmvpe_root"],
264
- is_half=self.is_half,
265
- device=self.device,
266
- )
267
- f0 = self.model_rmvpe.infer_from_audio_with_pitch(x, thred=0.03, f0_min=f0_min, f0_max=f0_max)
268
- if "privateuseone" in str(self.device): # clean ortruntime memory
269
- del self.model_rmvpe.model
270
- del self.model_rmvpe
271
- logger.info("Cleaning ortruntime memory")
272
-
273
- return f0
274
-
275
- def get_fcpe(self, x, f0_min, f0_max, p_len, *args, **kwargs):
276
- self.model_fcpe = FCPEF0Predictor("%s/fcpe.pt" % os.environ["fcpe_root"], f0_min=f0_min, f0_max=f0_max, dtype=torch.float32, device=self.device, sampling_rate=self.sr, threshold=0.03)
277
- f0 = self.model_fcpe.compute_f0(x, p_len=p_len)
278
- del self.model_fcpe
279
- gc.collect()
280
- return f0
281
-
282
- def autotune_f0(self, f0):
283
- autotuned_f0 = []
284
- for freq in f0:
285
- closest_notes = [x for x in self.note_dict if abs(x - freq) == min(abs(n - freq) for n in self.note_dict)]
286
- autotuned_f0.append(random.choice(closest_notes))
287
- return np.array(autotuned_f0, np.float64)
288
-
289
-
290
- # Fork Feature: Acquire median hybrid f0 estimation calculation
291
- def get_f0_hybrid_computation(
292
- self,
293
- methods_str,
294
- input_audio_path,
295
- x,
296
- f0_min,
297
- f0_max,
298
- p_len,
299
- filter_radius,
300
- crepe_hop_length,
301
- time_step,
302
- ):
303
- # Get various f0 methods from input to use in the computation stack
304
- methods_str = re.search('hybrid\[(.+)\]', methods_str)
305
- if methods_str: # Ensure a match was found
306
- methods = [method.strip() for method in methods_str.group(1).split('+')]
307
- f0_computation_stack = []
308
-
309
- print("Calculating f0 pitch estimations for methods: %s" % str(methods))
310
- x = x.astype(np.float32)
311
- x /= np.quantile(np.abs(x), 0.999)
312
- # Get f0 calculations for all methods specified
313
- for method in methods:
314
- f0 = None
315
- if method == "pm":
316
- f0 = self.get_pm(x, p_len=p_len)
317
- elif method == "crepe":
318
- f0 = self.get_f0_official_crepe_computation(x, f0_min, f0_max, model="full")
319
- f0 = f0[1:]
320
- elif method == "crepe-tiny":
321
- f0 = self.get_f0_official_crepe_computation(x, f0_min, f0_max, model="tiny")
322
- f0 = f0[1:] # Get rid of extra first frame
323
- elif method == "mangio-crepe":
324
- f0 = self.get_f0_crepe_computation(
325
- x, f0_min, f0_max, p_len, crepe_hop_length=crepe_hop_length
326
- )
327
- elif method == "mangio-crepe-tiny":
328
- f0 = self.get_f0_crepe_computation(
329
- x, f0_min, f0_max, p_len, crepe_hop_length=crepe_hop_length, model="tiny"
330
- )
331
- elif method == "harvest":
332
- f0 = self.get_harvest(x)
333
- f0 = f0[1:]
334
- elif method == "dio":
335
- f0 = self.get_dio(x)
336
- f0 = f0[1:]
337
- elif method == "rmvpe":
338
- f0 = self.get_rmvpe(x)
339
- f0 = f0[1:]
340
- elif method == "fcpe":
341
- f0 = self.get_fcpe(x, f0_min=f0_min, f0_max=f0_max, p_len=p_len)
342
- elif method == "pyin":
343
- f0 = self.get_f0_pyin_computation(input_audio_path, f0_min, f0_max)
344
- # Push method to the stack
345
- f0_computation_stack.append(f0)
346
-
347
- for fc in f0_computation_stack:
348
- print(len(fc))
349
-
350
- print("Calculating hybrid median f0 from the stack of: %s" % str(methods))
351
- f0_median_hybrid = None
352
- if len(f0_computation_stack) == 1:
353
- f0_median_hybrid = f0_computation_stack[0]
354
- else:
355
- f0_median_hybrid = np.nanmedian(f0_computation_stack, axis=0)
356
- return f0_median_hybrid
357
-
358
- def get_f0(
359
- self,
360
- input_audio_path,
361
- x,
362
- p_len,
363
- f0_up_key,
364
- f0_method,
365
- filter_radius,
366
- crepe_hop_length,
367
- f0_autotune,
368
- inp_f0=None,
369
- f0_min=50,
370
- f0_max=1100,
371
- ):
372
- global input_audio_path2wav
373
- time_step = self.window / self.sr * 1000
374
- f0_min = f0_min
375
- f0_max = f0_max
376
- f0_mel_min = 1127 * np.log(1 + f0_min / 700)
377
- f0_mel_max = 1127 * np.log(1 + f0_max / 700)
378
-
379
- if f0_method == "pm":
380
- f0 = (
381
- parselmouth.Sound(x, self.sr)
382
- .to_pitch_ac(
383
- time_step=time_step / 1000,
384
- voicing_threshold=0.6,
385
- pitch_floor=f0_min,
386
- pitch_ceiling=f0_max,
387
- )
388
- .selected_array["frequency"]
389
- )
390
- pad_size = (p_len - len(f0) + 1) // 2
391
- if pad_size > 0 or p_len - len(f0) - pad_size > 0:
392
- f0 = np.pad(
393
- f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant"
394
- )
395
- elif f0_method == "harvest":
396
- input_audio_path2wav[input_audio_path] = x.astype(np.double)
397
- f0 = cache_harvest_f0(input_audio_path, self.sr, f0_max, f0_min, 10)
398
- if filter_radius > 2:
399
- f0 = signal.medfilt(f0, 3)
400
- elif f0_method == "dio": # Potentially Buggy?
401
- f0, t = pyworld.dio(
402
- x.astype(np.double),
403
- fs=self.sr,
404
- f0_ceil=f0_max,
405
- f0_floor=f0_min,
406
- frame_period=10,
407
- )
408
- f0 = pyworld.stonemask(x.astype(np.double), f0, t, self.sr)
409
- f0 = signal.medfilt(f0, 3)
410
- elif f0_method == "crepe":
411
- model = "full"
412
- # Pick a batch size that doesn't cause memory errors on your gpu
413
- batch_size = 512
414
- # Compute pitch using first gpu
415
- audio = torch.tensor(np.copy(x))[None].float()
416
- f0, pd = torchcrepe.predict(
417
- audio,
418
- self.sr,
419
- self.window,
420
- f0_min,
421
- f0_max,
422
- model,
423
- batch_size=batch_size,
424
- device=self.device,
425
- return_periodicity=True,
426
- )
427
- pd = torchcrepe.filter.median(pd, 3)
428
- f0 = torchcrepe.filter.mean(f0, 3)
429
- f0[pd < 0.1] = 0
430
- f0 = f0[0].cpu().numpy()
431
- elif f0_method == "crepe-tiny":
432
- f0 = self.get_f0_official_crepe_computation(x, f0_min, f0_max, model="tiny")
433
- elif f0_method == "mangio-crepe":
434
- f0 = self.get_f0_crepe_computation(
435
- x, f0_min, f0_max, p_len, crepe_hop_length=crepe_hop_length
436
- )
437
- elif f0_method == "mangio-crepe-tiny":
438
- f0 = self.get_f0_crepe_computation(
439
- x, f0_min, f0_max, p_len, crepe_hop_length=crepe_hop_length, model="tiny"
440
- )
441
- elif f0_method == "rmvpe":
442
- if not hasattr(self, "model_rmvpe"):
443
- from lib.infer.infer_libs.rmvpe import RMVPE
444
-
445
- logger.info(
446
- "Loading rmvpe model,%s" % "%s/rmvpe.pt" % os.environ["rmvpe_root"]
447
- )
448
- self.model_rmvpe = RMVPE(
449
- "%s/rmvpe.pt" % os.environ["rmvpe_root"],
450
- is_half=self.is_half,
451
- device=self.device,
452
- )
453
- f0 = self.model_rmvpe.infer_from_audio(x, thred=0.03)
454
-
455
- if "privateuseone" in str(self.device): # clean ortruntime memory
456
- del self.model_rmvpe.model
457
- del self.model_rmvpe
458
- logger.info("Cleaning ortruntime memory")
459
- elif f0_method == "rmvpe+":
460
- params = {'x': x, 'p_len': p_len, 'f0_up_key': f0_up_key, 'f0_min': f0_min,
461
- 'f0_max': f0_max, 'time_step': time_step, 'filter_radius': filter_radius,
462
- 'crepe_hop_length': crepe_hop_length, 'model': "full"
463
- }
464
- f0 = self.get_pitch_dependant_rmvpe(**params)
465
- elif f0_method == "pyin":
466
- f0 = self.get_f0_pyin_computation(input_audio_path, f0_min, f0_max)
467
- elif f0_method == "fcpe":
468
- f0 = self.get_fcpe(x, f0_min=f0_min, f0_max=f0_max, p_len=p_len)
469
- elif "hybrid" in f0_method:
470
- # Perform hybrid median pitch estimation
471
- input_audio_path2wav[input_audio_path] = x.astype(np.double)
472
- f0 = self.get_f0_hybrid_computation(
473
- f0_method,
474
- input_audio_path,
475
- x,
476
- f0_min,
477
- f0_max,
478
- p_len,
479
- filter_radius,
480
- crepe_hop_length,
481
- time_step,
482
- )
483
- #print("Autotune:", f0_autotune)
484
- if f0_autotune == True:
485
- print("Autotune:", f0_autotune)
486
- f0 = self.autotune_f0(f0)
487
-
488
- f0 *= pow(2, f0_up_key / 12)
489
- # with open("test.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()]))
490
- tf0 = self.sr // self.window # 每秒f0点数
491
- if inp_f0 is not None:
492
- delta_t = np.round(
493
- (inp_f0[:, 0].max() - inp_f0[:, 0].min()) * tf0 + 1
494
- ).astype("int16")
495
- replace_f0 = np.interp(
496
- list(range(delta_t)), inp_f0[:, 0] * 100, inp_f0[:, 1]
497
- )
498
- shape = f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)].shape[0]
499
- f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)] = replace_f0[
500
- :shape
501
- ]
502
- # with open("test_opt.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()]))
503
- f0bak = f0.copy()
504
- f0_mel = 1127 * np.log(1 + f0 / 700)
505
- f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / (
506
- f0_mel_max - f0_mel_min
507
- ) + 1
508
- f0_mel[f0_mel <= 1] = 1
509
- f0_mel[f0_mel > 255] = 255
510
- f0_coarse = np.rint(f0_mel).astype(np.int32)
511
- return f0_coarse, f0bak # 1-0
512
-
513
- def vc(
514
- self,
515
- model,
516
- net_g,
517
- sid,
518
- audio0,
519
- pitch,
520
- pitchf,
521
- times,
522
- index,
523
- big_npy,
524
- index_rate,
525
- version,
526
- protect,
527
- ): # ,file_index,file_big_npy
528
- feats = torch.from_numpy(audio0)
529
- if self.is_half:
530
- feats = feats.half()
531
- else:
532
- feats = feats.float()
533
- if feats.dim() == 2: # double channels
534
- feats = feats.mean(-1)
535
- assert feats.dim() == 1, feats.dim()
536
- feats = feats.view(1, -1)
537
- padding_mask = torch.BoolTensor(feats.shape).to(self.device).fill_(False)
538
-
539
- inputs = {
540
- "source": feats.to(self.device),
541
- "padding_mask": padding_mask,
542
- "output_layer": 9 if version == "v1" else 12,
543
- }
544
- t0 = ttime()
545
- with torch.no_grad():
546
- logits = model.extract_features(**inputs)
547
- feats = model.final_proj(logits[0]) if version == "v1" else logits[0]
548
- if protect < 0.5 and pitch is not None and pitchf is not None:
549
- feats0 = feats.clone()
550
- if (
551
- not isinstance(index, type(None))
552
- and not isinstance(big_npy, type(None))
553
- and index_rate != 0
554
- ):
555
- npy = feats[0].cpu().numpy()
556
- if self.is_half:
557
- npy = npy.astype("float32")
558
-
559
- # _, I = index.search(npy, 1)
560
- # npy = big_npy[I.squeeze()]
561
-
562
- score, ix = index.search(npy, k=8)
563
- weight = np.square(1 / score)
564
- weight /= weight.sum(axis=1, keepdims=True)
565
- npy = np.sum(big_npy[ix] * np.expand_dims(weight, axis=2), axis=1)
566
-
567
- if self.is_half:
568
- npy = npy.astype("float16")
569
- feats = (
570
- torch.from_numpy(npy).unsqueeze(0).to(self.device) * index_rate
571
- + (1 - index_rate) * feats
572
- )
573
-
574
- feats = F.interpolate(feats.permute(0, 2, 1), scale_factor=2).permute(0, 2, 1)
575
- if protect < 0.5 and pitch is not None and pitchf is not None:
576
- feats0 = F.interpolate(feats0.permute(0, 2, 1), scale_factor=2).permute(
577
- 0, 2, 1
578
- )
579
- t1 = ttime()
580
- p_len = audio0.shape[0] // self.window
581
- if feats.shape[1] < p_len:
582
- p_len = feats.shape[1]
583
- if pitch is not None and pitchf is not None:
584
- pitch = pitch[:, :p_len]
585
- pitchf = pitchf[:, :p_len]
586
-
587
- if protect < 0.5 and pitch is not None and pitchf is not None:
588
- pitchff = pitchf.clone()
589
- pitchff[pitchf > 0] = 1
590
- pitchff[pitchf < 1] = protect
591
- pitchff = pitchff.unsqueeze(-1)
592
- feats = feats * pitchff + feats0 * (1 - pitchff)
593
- feats = feats.to(feats0.dtype)
594
- p_len = torch.tensor([p_len], device=self.device).long()
595
- with torch.no_grad():
596
- hasp = pitch is not None and pitchf is not None
597
- arg = (feats, p_len, pitch, pitchf, sid) if hasp else (feats, p_len, sid)
598
- audio1 = (net_g.infer(*arg)[0][0, 0]).data.cpu().float().numpy()
599
- del hasp, arg
600
- del feats, p_len, padding_mask
601
- if torch.cuda.is_available():
602
- torch.cuda.empty_cache()
603
- t2 = ttime()
604
- times[0] += t1 - t0
605
- times[2] += t2 - t1
606
- return audio1
607
- def process_t(self, t, s, window, audio_pad, pitch, pitchf, times, index, big_npy, index_rate, version, protect, t_pad_tgt, if_f0, sid, model, net_g):
608
- t = t // window * window
609
- if if_f0 == 1:
610
- return self.vc(
611
- model,
612
- net_g,
613
- sid,
614
- audio_pad[s : t + t_pad_tgt + window],
615
- pitch[:, s // window : (t + t_pad_tgt) // window],
616
- pitchf[:, s // window : (t + t_pad_tgt) // window],
617
- times,
618
- index,
619
- big_npy,
620
- index_rate,
621
- version,
622
- protect,
623
- )[t_pad_tgt : -t_pad_tgt]
624
- else:
625
- return self.vc(
626
- model,
627
- net_g,
628
- sid,
629
- audio_pad[s : t + t_pad_tgt + window],
630
- None,
631
- None,
632
- times,
633
- index,
634
- big_npy,
635
- index_rate,
636
- version,
637
- protect,
638
- )[t_pad_tgt : -t_pad_tgt]
639
-
640
-
641
- def pipeline(
642
- self,
643
- model,
644
- net_g,
645
- sid,
646
- audio,
647
- input_audio_path,
648
- times,
649
- f0_up_key,
650
- f0_method,
651
- file_index,
652
- index_rate,
653
- if_f0,
654
- filter_radius,
655
- tgt_sr,
656
- resample_sr,
657
- rms_mix_rate,
658
- version,
659
- protect,
660
- crepe_hop_length,
661
- f0_autotune,
662
- f0_min=50,
663
- f0_max=1100
664
- ):
665
- if (
666
- file_index != ""
667
- and isinstance(file_index, str)
668
- # and file_big_npy != ""
669
- # and os.path.exists(file_big_npy) == True
670
- and os.path.exists(file_index)
671
- and index_rate != 0
672
- ):
673
- try:
674
- index = faiss.read_index(file_index)
675
- # big_npy = np.load(file_big_npy)
676
- big_npy = index.reconstruct_n(0, index.ntotal)
677
- except:
678
- traceback.print_exc()
679
- index = big_npy = None
680
- else:
681
- index = big_npy = None
682
- audio = signal.filtfilt(bh, ah, audio)
683
- audio_pad = np.pad(audio, (self.window // 2, self.window // 2), mode="reflect")
684
- opt_ts = []
685
- if audio_pad.shape[0] > self.t_max:
686
- audio_sum = np.zeros_like(audio)
687
- for i in range(self.window):
688
- audio_sum += audio_pad[i : i - self.window]
689
- for t in range(self.t_center, audio.shape[0], self.t_center):
690
- opt_ts.append(
691
- t
692
- - self.t_query
693
- + np.where(
694
- np.abs(audio_sum[t - self.t_query : t + self.t_query])
695
- == np.abs(audio_sum[t - self.t_query : t + self.t_query]).min()
696
- )[0][0]
697
- )
698
- s = 0
699
- audio_opt = []
700
- t = None
701
- t1 = ttime()
702
- audio_pad = np.pad(audio, (self.t_pad, self.t_pad), mode="reflect")
703
- p_len = audio_pad.shape[0] // self.window
704
- inp_f0 = None
705
-
706
- sid = torch.tensor(sid, device=self.device).unsqueeze(0).long()
707
- pitch, pitchf = None, None
708
- if if_f0:
709
- pitch, pitchf = self.get_f0(
710
- input_audio_path,
711
- audio_pad,
712
- p_len,
713
- f0_up_key,
714
- f0_method,
715
- filter_radius,
716
- crepe_hop_length,
717
- f0_autotune,
718
- inp_f0,
719
- f0_min,
720
- f0_max
721
- )
722
- pitch = pitch[:p_len]
723
- pitchf = pitchf[:p_len]
724
- if "mps" not in str(self.device) or "xpu" not in str(self.device):
725
- pitchf = pitchf.astype(np.float32)
726
- pitch = torch.tensor(pitch, device=self.device).unsqueeze(0).long()
727
- pitchf = torch.tensor(pitchf, device=self.device).unsqueeze(0).float()
728
- t2 = ttime()
729
- times[1] += t2 - t1
730
-
731
- with tqdm(total=len(opt_ts), desc="Processing", unit="window") as pbar:
732
- for i, t in enumerate(opt_ts):
733
- t = t // self.window * self.window
734
- start = s
735
- end = t + self.t_pad2 + self.window
736
- audio_slice = audio_pad[start:end]
737
- pitch_slice = pitch[:, start // self.window:end // self.window] if if_f0 else None
738
- pitchf_slice = pitchf[:, start // self.window:end // self.window] if if_f0 else None
739
- audio_opt.append(self.vc(model, net_g, sid, audio_slice, pitch_slice, pitchf_slice, times, index, big_npy, index_rate, version, protect)[self.t_pad_tgt : -self.t_pad_tgt])
740
- s = t
741
- pbar.update(1)
742
- pbar.refresh()
743
-
744
- audio_slice = audio_pad[t:]
745
- pitch_slice = pitch[:, t // self.window:] if if_f0 and t is not None else pitch
746
- pitchf_slice = pitchf[:, t // self.window:] if if_f0 and t is not None else pitchf
747
- audio_opt.append(self.vc(model, net_g, sid, audio_slice, pitch_slice, pitchf_slice, times, index, big_npy, index_rate, version, protect)[self.t_pad_tgt : -self.t_pad_tgt])
748
-
749
- audio_opt = np.concatenate(audio_opt)
750
- if rms_mix_rate != 1:
751
- audio_opt = change_rms(audio, 16000, audio_opt, tgt_sr, rms_mix_rate)
752
- if tgt_sr != resample_sr >= 16000:
753
- audio_opt = librosa.resample(
754
- audio_opt, orig_sr=tgt_sr, target_sr=resample_sr
755
- )
756
- audio_max = np.abs(audio_opt).max() / 0.99
757
- max_int16 = 32768
758
- if audio_max > 1:
759
- max_int16 /= audio_max
760
- audio_opt = (audio_opt * max_int16).astype(np.int16)
761
- del pitch, pitchf, sid
762
- if torch.cuda.is_available():
763
- torch.cuda.empty_cache()
764
-
765
- print("Returning completed audio...")
766
- return audio_opt