Blane187 commited on
Commit
975a6e8
·
verified ·
1 Parent(s): 2b3c46a

Create pipeline.py

Browse files
Files changed (1) hide show
  1. pipeline.py +643 -0
pipeline.py ADDED
@@ -0,0 +1,643 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np, parselmouth, torch, pdb, sys, os
2
+ from time import time as ttime
3
+ import torch.nn.functional as F
4
+ import torchcrepe
5
+ from torch import Tensor
6
+ import scipy.signal as signal
7
+ import pyworld, os, traceback, faiss, librosa, torchcrepe
8
+ from scipy import signal
9
+ from functools import lru_cache
10
+ import gc, re
11
+
12
+ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
13
+ now_dir = os.path.join(BASE_DIR, 'src')
14
+ sys.path.append(now_dir)
15
+
16
+ from fcpe import fcpe
17
+ from rmvpe import rmvpe
18
+
19
+
20
+
21
+ bh, ah = signal.butter(N=5, Wn=48, btype="high", fs=16000)
22
+
23
+ input_audio_path2wav = {}
24
+
25
+
26
+ @lru_cache
27
+ def cache_harvest_f0(input_audio_path, fs, f0max, f0min, frame_period):
28
+ audio = input_audio_path2wav[input_audio_path]
29
+ f0, t = pyworld.harvest(
30
+ audio,
31
+ fs=fs,
32
+ f0_ceil=f0max,
33
+ f0_floor=f0min,
34
+ frame_period=frame_period,
35
+ )
36
+ f0 = pyworld.stonemask(audio, f0, t, fs)
37
+ return f0
38
+
39
+
40
+ def change_rms(data1, sr1, data2, sr2, rate):
41
+ rms1 = librosa.feature.rms(
42
+ y=data1, frame_length=sr1 // 2 * 2, hop_length=sr1 // 2
43
+ )
44
+ rms2 = librosa.feature.rms(y=data2, frame_length=sr2 // 2 * 2, hop_length=sr2 // 2)
45
+ rms1 = torch.from_numpy(rms1)
46
+ rms1 = F.interpolate(
47
+ rms1.unsqueeze(0), size=data2.shape[0], mode="linear"
48
+ ).squeeze()
49
+ rms2 = torch.from_numpy(rms2)
50
+ rms2 = F.interpolate(
51
+ rms2.unsqueeze(0), size=data2.shape[0], mode="linear"
52
+ ).squeeze()
53
+ rms2 = torch.max(rms2, torch.zeros_like(rms2) + 1e-6)
54
+ data2 *= (
55
+ torch.pow(rms1, torch.tensor(1 - rate))
56
+ * torch.pow(rms2, torch.tensor(rate - 1))
57
+ ).numpy()
58
+ return data2
59
+
60
+
61
+ class VC(object):
62
+ def __init__(self, tgt_sr, config):
63
+ self.x_pad, self.x_query, self.x_center, self.x_max, self.is_half = (
64
+ config.x_pad,
65
+ config.x_query,
66
+ config.x_center,
67
+ config.x_max,
68
+ config.is_half,
69
+ )
70
+ self.sr = 16000
71
+ self.window = 160
72
+ self.t_pad = self.sr * self.x_pad
73
+ self.t_pad_tgt = tgt_sr * self.x_pad
74
+ self.t_pad2 = self.t_pad * 2
75
+ self.t_query = self.sr * self.x_query
76
+ self.t_center = self.sr * self.x_center
77
+ self.t_max = self.sr * self.x_max
78
+ self.device = config.device
79
+
80
+
81
+ def get_optimal_torch_device(self, index: int = 0) -> torch.device:
82
+ if torch.cuda.is_available():
83
+ return torch.device(
84
+ f"cuda:{index % torch.cuda.device_count()}"
85
+ )
86
+ elif torch.backends.mps.is_available():
87
+ return torch.device("mps")
88
+ return torch.device("cpu")
89
+
90
+ def get_f0_crepe_computation(
91
+ self,
92
+ x,
93
+ f0_min,
94
+ f0_max,
95
+ p_len,
96
+ hop_length=160,
97
+ model="full",
98
+ ):
99
+ x = x.astype(
100
+ np.float32
101
+ )
102
+ x /= np.quantile(np.abs(x), 0.999)
103
+ torch_device = self.get_optimal_torch_device()
104
+ audio = torch.from_numpy(x).to(torch_device, copy=True)
105
+ audio = torch.unsqueeze(audio, dim=0)
106
+ if audio.ndim == 2 and audio.shape[0] > 1:
107
+ audio = torch.mean(audio, dim=0, keepdim=True).detach()
108
+ audio = audio.detach()
109
+ pitch: Tensor = torchcrepe.predict(
110
+ audio,
111
+ self.sr,
112
+ hop_length,
113
+ f0_min,
114
+ f0_max,
115
+ model,
116
+ batch_size=hop_length * 2,
117
+ device=torch_device,
118
+ pad=True,
119
+ )
120
+ p_len = p_len or x.shape[0] // hop_length
121
+ source = np.array(pitch.squeeze(0).cpu().float().numpy())
122
+ source[source < 0.001] = np.nan
123
+ target = np.interp(
124
+ np.arange(0, len(source) * p_len, len(source)) / p_len,
125
+ np.arange(0, len(source)),
126
+ source,
127
+ )
128
+ f0 = np.nan_to_num(target)
129
+ return f0
130
+
131
+ def get_f0_official_crepe_computation(
132
+ self,
133
+ x,
134
+ f0_min,
135
+ f0_max,
136
+ model="full",
137
+ ):
138
+ batch_size = 512
139
+ audio = torch.tensor(np.copy(x))[None].float()
140
+ f0, pd = torchcrepe.predict(
141
+ audio,
142
+ self.sr,
143
+ self.window,
144
+ f0_min,
145
+ f0_max,
146
+ model,
147
+ batch_size=batch_size,
148
+ device=self.device,
149
+ return_periodicity=True,
150
+ )
151
+ pd = torchcrepe.filter.median(pd, 3)
152
+ f0 = torchcrepe.filter.mean(f0, 3)
153
+ f0[pd < 0.1] = 0
154
+ f0 = f0[0].cpu().numpy()
155
+ return f0
156
+
157
+ def get_f0_pyin_computation(self, x, f0_min, f0_max):
158
+ y, sr = librosa.load("saudio/Sidney.wav", self.sr, mono=True)
159
+ f0, _, _ = librosa.pyin(y, sr=self.sr, fmin=f0_min, fmax=f0_max)
160
+ f0 = f0[1:]
161
+ return f0
162
+
163
+ def get_f0_hybrid_computation(
164
+ self,
165
+ methods_str,
166
+ input_audio_path,
167
+ x,
168
+ f0_min,
169
+ f0_max,
170
+ p_len,
171
+ filter_radius,
172
+ crepe_hop_length,
173
+ time_step,
174
+ ):
175
+ methods_str = re.search("hybrid\[(.+)\]", methods_str)
176
+ if methods_str:
177
+ methods = [method.strip() for method in methods_str.group(1).split("+")]
178
+ f0_computation_stack = []
179
+ print(f"Calculating f0 pitch estimations for methods {str(methods)}")
180
+ x = x.astype(np.float32)
181
+ x /= np.quantile(np.abs(x), 0.999)
182
+ for method in methods:
183
+ f0 = None
184
+ if method == "crepe":
185
+ f0 = self.get_f0_official_crepe_computation(x, f0_min, f0_max)
186
+ f0 = f0[1:]
187
+ elif method == "mangio-crepe":
188
+ f0 = self.get_f0_crepe_computation(
189
+ x, f0_min, f0_max, p_len, crepe_hop_length
190
+ )
191
+ elif method == "rmvpe":
192
+ if hasattr(self, "model_rmvpe") == False:
193
+
194
+ self.model_rmvpe = RMVPE(
195
+ os.path.join(BASE_DIR, 'rvc_models', 'rmvpe.pt'), is_half=self.is_half, device=self.device
196
+ )
197
+ f0 = self.model_rmvpe.infer_from_audio(x, thred=0.03)
198
+ f0 = f0[1:]
199
+ elif method == "fcpe":
200
+ self.model_fcpe = FCPEF0Predictor(
201
+ os.path.join(BASE_DIR, 'rvc_models', 'fcpe.pt'),
202
+ f0_min=int(f0_min),
203
+ f0_max=int(f0_max),
204
+ dtype=torch.float32,
205
+ device=self.device,
206
+ sampling_rate=self.sr,
207
+ threshold=0.03,
208
+ )
209
+ f0 = self.model_fcpe.compute_f0(x, p_len=p_len)
210
+ del self.model_fcpe
211
+ gc.collect()
212
+ f0_computation_stack.append(f0)
213
+
214
+
215
+
216
+ print(f"Calculating hybrid median f0 from the stack of {str(methods)}....")
217
+ f0_computation_stack = [fc for fc in f0_computation_stack if fc is not None]
218
+ f0_median_hybrid = None
219
+ if len(f0_computation_stack) == 1:
220
+ f0_median_hybrid = f0_computation_stack[0]
221
+ else:
222
+ f0_median_hybrid = np.nanmedian(f0_computation_stack, axis=0)
223
+ return f0_median_hybrid
224
+
225
+ def get_f0(
226
+ self,
227
+ input_audio_path,
228
+ x,
229
+ p_len,
230
+ f0_up_key,
231
+ f0_method,
232
+ filter_radius,
233
+ crepe_hop_length,
234
+ inp_f0=None,
235
+ ):
236
+ global input_audio_path2wav
237
+ time_step = self.window / self.sr * 1000
238
+ f0_min = 50
239
+ f0_max = 1100
240
+ f0_mel_min = 1127 * np.log(1 + f0_min / 700)
241
+ f0_mel_max = 1127 * np.log(1 + f0_max / 700)
242
+ if f0_method == "pm":
243
+ f0 = (
244
+ parselmouth.Sound(x, self.sr)
245
+ .to_pitch_ac(
246
+ time_step=time_step / 1000,
247
+ voicing_threshold=0.6,
248
+ pitch_floor=f0_min,
249
+ pitch_ceiling=f0_max,
250
+ )
251
+ .selected_array["frequency"]
252
+ )
253
+ pad_size = (p_len - len(f0) + 1) // 2
254
+ if pad_size > 0 or p_len - len(f0) - pad_size > 0:
255
+ f0 = np.pad(
256
+ f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant"
257
+ )
258
+
259
+ elif f0_method == "harvest":
260
+ input_audio_path2wav[input_audio_path] = x.astype(np.double)
261
+ f0 = cache_harvest_f0(input_audio_path, self.sr, f0_max, f0_min, 10)
262
+ if int(filter_radius) > 2:
263
+ f0 = signal.medfilt(f0, 3)
264
+
265
+ elif f0_method == "dio":
266
+ f0, t = pyworld.dio(
267
+ x.astype(np.double),
268
+ fs=self.sr,
269
+ f0_ceil=f0_max,
270
+ f0_floor=f0_min,
271
+ frame_period=10,
272
+ )
273
+ f0 = pyworld.stonemask(x.astype(np.double), f0, t, self.sr)
274
+ f0 = signal.medfilt(f0, 3)
275
+
276
+ elif f0_method == "crepe":
277
+ f0 = self.get_f0_official_crepe_computation(x, f0_min, f0_max)
278
+
279
+ elif f0_method == "mangio-crepe":
280
+ f0 = self.get_f0_crepe_computation(x, f0_min, f0_max, p_len, crepe_hop_length)
281
+
282
+ elif f0_method == "rmvpe":
283
+ if hasattr(self, "model_rmvpe") == False:
284
+
285
+ self.model_rmvpe = rmvpe(
286
+ os.path.join(BASE_DIR, 'rvc_models', 'rmvpe.pt'), is_half=self.is_half, device=self.device
287
+ )
288
+ f0 = self.model_rmvpe.infer_from_audio(x, thred=0.03)
289
+
290
+ elif f0_method == "rmvpe_legacy":
291
+ self.model_rmvpe = rmvpe(
292
+ os.path.join(BASE_DIR, 'rvc_models', 'rmvpe.pt', 'fcpe.pt'), is_half=self.is_half, device=self.device
293
+ )
294
+
295
+ params = {'x': x, 'p_len': p_len, 'f0_up_key': f0_up_key, 'f0_min': f0_min,
296
+ 'f0_max': f0_max, 'time_step': time_step, 'filter_radius': filter_radius,
297
+ 'crepe_hop_length': crepe_hop_length, 'model': "full"
298
+ }
299
+ f0 = self.get_pitch_dependant_rmvpe(**params)
300
+
301
+ elif f0_method == "fcpe":
302
+ self.model_fcpe = fcpe(
303
+ os.path.join(BASE_DIR, 'rvc_models', 'fcpe.pt'),
304
+ f0_min=int(f0_min),
305
+ f0_max=int(f0_max),
306
+ dtype=torch.float32,
307
+ device=self.device,
308
+ sampling_rate=self.sr,
309
+ threshold=0.03,
310
+ )
311
+ f0 = self.model_fcpe.compute_f0(x, p_len=p_len)
312
+ del self.model_fcpe
313
+ gc.collect()
314
+
315
+
316
+
317
+ elif "hybrid" in f0_method:
318
+ input_audio_path2wav[input_audio_path] = x.astype(np.double)
319
+ f0 = self.get_f0_hybrid_computation(
320
+ f0_method,
321
+ input_audio_path,
322
+ x,
323
+ f0_min,
324
+ f0_max,
325
+ p_len,
326
+ filter_radius,
327
+ crepe_hop_length,
328
+ time_step,
329
+ )
330
+
331
+ f0 *= pow(2, f0_up_key / 12)
332
+ tf0 = self.sr // self.window
333
+ if inp_f0 is not None:
334
+ delta_t = np.round(
335
+ (inp_f0[:, 0].max() - inp_f0[:, 0].min()) * tf0 + 1
336
+ ).astype("int16")
337
+ replace_f0 = np.interp(
338
+ list(range(delta_t)), inp_f0[:, 0] * 100, inp_f0[:, 1]
339
+ )
340
+ shape = f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)].shape[0]
341
+ f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)] = replace_f0[
342
+ :shape
343
+ ]
344
+ f0bak = f0.copy()
345
+ f0_mel = 1127 * np.log(1 + f0 / 700)
346
+ f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / (
347
+ f0_mel_max - f0_mel_min
348
+ ) + 1
349
+ f0_mel[f0_mel <= 1] = 1
350
+ f0_mel[f0_mel > 255] = 255
351
+ f0_coarse = np.rint(f0_mel).astype(int)
352
+
353
+ return f0_coarse, f0bak
354
+
355
+ def get_pitch_dependant_rmvpe(self, x, f0_min=1, f0_max=40000, *args, **kwargs):
356
+ if not hasattr(self, "model_rmvpe"):
357
+
358
+ self.model_rmvpe = RMVPE(
359
+ os.path.join(BASE_DIR, 'rvc_models', 'rmvpe.pt'),
360
+ is_half=self.is_half,
361
+ device=self.device,
362
+ )
363
+
364
+ f0 = self.model_rmvpe.infer_from_audio_with_pitch(x, thred=0.03, f0_min=f0_min, f0_max=f0_max)
365
+
366
+ return f0
367
+
368
+
369
+ def vc(
370
+ self,
371
+ model,
372
+ net_g,
373
+ sid,
374
+ audio0,
375
+ pitch,
376
+ pitchf,
377
+ times,
378
+ index,
379
+ big_npy,
380
+ index_rate,
381
+ version,
382
+ protect,
383
+ ):
384
+ feats = torch.from_numpy(audio0)
385
+ if self.is_half:
386
+ feats = feats.half()
387
+ else:
388
+ feats = feats.float()
389
+ if feats.dim() == 2:
390
+ feats = feats.mean(-1)
391
+ assert feats.dim() == 1, feats.dim()
392
+ feats = feats.view(1, -1)
393
+ padding_mask = torch.BoolTensor(feats.shape).to(self.device).fill_(False)
394
+
395
+ inputs = {
396
+ "source": feats.to(self.device),
397
+ "padding_mask": padding_mask,
398
+ "output_layer": 9 if version == "v1" else 12,
399
+ }
400
+ t0 = ttime()
401
+ with torch.no_grad():
402
+ logits = model.extract_features(**inputs)
403
+ feats = model.final_proj(logits[0]) if version == "v1" else logits[0]
404
+ if protect < 0.5 and pitch != None and pitchf != None:
405
+ feats0 = feats.clone()
406
+ if (
407
+ isinstance(index, type(None)) == False
408
+ and isinstance(big_npy, type(None)) == False
409
+ and index_rate != 0
410
+ ):
411
+ npy = feats[0].cpu().numpy()
412
+ if self.is_half:
413
+ npy = npy.astype("float32")
414
+
415
+ score, ix = index.search(npy, k=8)
416
+ weight = np.square(1 / score)
417
+ weight /= weight.sum(axis=1, keepdims=True)
418
+ npy = np.sum(big_npy[ix] * np.expand_dims(weight, axis=2), axis=1)
419
+
420
+ if self.is_half:
421
+ npy = npy.astype("float16")
422
+ feats = (
423
+ torch.from_numpy(npy).unsqueeze(0).to(self.device) * index_rate
424
+ + (1 - index_rate) * feats
425
+ )
426
+
427
+ feats = F.interpolate(feats.permute(0, 2, 1), scale_factor=2).permute(0, 2, 1)
428
+ if protect < 0.5 and pitch != None and pitchf != None:
429
+ feats0 = F.interpolate(feats0.permute(0, 2, 1), scale_factor=2).permute(
430
+ 0, 2, 1
431
+ )
432
+ t1 = ttime()
433
+ p_len = audio0.shape[0] // self.window
434
+ if feats.shape[1] < p_len:
435
+ p_len = feats.shape[1]
436
+ if pitch != None and pitchf != None:
437
+ pitch = pitch[:, :p_len]
438
+ pitchf = pitchf[:, :p_len]
439
+
440
+ if protect < 0.5 and pitch != None and pitchf != None:
441
+ pitchff = pitchf.clone()
442
+ pitchff[pitchf > 0] = 1
443
+ pitchff[pitchf < 1] = protect
444
+ pitchff = pitchff.unsqueeze(-1)
445
+ feats = feats * pitchff + feats0 * (1 - pitchff)
446
+ feats = feats.to(feats0.dtype)
447
+ p_len = torch.tensor([p_len], device=self.device).long()
448
+ with torch.no_grad():
449
+ if pitch != None and pitchf != None:
450
+ audio1 = (
451
+ (net_g.infer(feats, p_len, pitch, pitchf, sid)[0][0, 0])
452
+ .data.cpu()
453
+ .float()
454
+ .numpy()
455
+ )
456
+ else:
457
+ audio1 = (
458
+ (net_g.infer(feats, p_len, sid)[0][0, 0]).data.cpu().float().numpy()
459
+ )
460
+ del feats, p_len, padding_mask
461
+ if torch.cuda.is_available():
462
+ torch.cuda.empty_cache()
463
+ t2 = ttime()
464
+ times[0] += t1 - t0
465
+ times[2] += t2 - t1
466
+ return audio1
467
+
468
+ def pipeline(
469
+ self,
470
+ model,
471
+ net_g,
472
+ sid,
473
+ audio,
474
+ input_audio_path,
475
+ times,
476
+ f0_up_key,
477
+ f0_method,
478
+ file_index,
479
+ index_rate,
480
+ if_f0,
481
+ filter_radius,
482
+ tgt_sr,
483
+ resample_sr,
484
+ rms_mix_rate,
485
+ version,
486
+ protect,
487
+ crepe_hop_length,
488
+ f0_file=None,
489
+ ):
490
+ if (
491
+ file_index != ""
492
+ and os.path.exists(file_index) == True
493
+ and index_rate != 0
494
+ ):
495
+ try:
496
+ index = faiss.read_index(file_index)
497
+ big_npy = index.reconstruct_n(0, index.ntotal)
498
+ except:
499
+ traceback.print_exc()
500
+ index = big_npy = None
501
+ else:
502
+ index = big_npy = None
503
+ audio = signal.filtfilt(bh, ah, audio)
504
+ audio_pad = np.pad(audio, (self.window // 2, self.window // 2), mode="reflect")
505
+ opt_ts = []
506
+ if audio_pad.shape[0] > self.t_max:
507
+ audio_sum = np.zeros_like(audio)
508
+ for i in range(self.window):
509
+ audio_sum += audio_pad[i : i - self.window]
510
+ for t in range(self.t_center, audio.shape[0], self.t_center):
511
+ opt_ts.append(
512
+ t
513
+ - self.t_query
514
+ + np.where(
515
+ np.abs(audio_sum[t - self.t_query : t + self.t_query])
516
+ == np.abs(audio_sum[t - self.t_query : t + self.t_query]).min()
517
+ )[0][0]
518
+ )
519
+ s = 0
520
+ audio_opt = []
521
+ t = None
522
+ t1 = ttime()
523
+ audio_pad = np.pad(audio, (self.t_pad, self.t_pad), mode="reflect")
524
+ p_len = audio_pad.shape[0] // self.window
525
+ inp_f0 = None
526
+ if hasattr(f0_file, "name") == True:
527
+ try:
528
+ with open(f0_file.name, "r") as f:
529
+ lines = f.read().strip("\n").split("\n")
530
+ inp_f0 = []
531
+ for line in lines:
532
+ inp_f0.append([float(i) for i in line.split(",")])
533
+ inp_f0 = np.array(inp_f0, dtype="float32")
534
+ except:
535
+ traceback.print_exc()
536
+ sid = torch.tensor(sid, device=self.device).unsqueeze(0).long()
537
+ pitch, pitchf = None, None
538
+ if if_f0 == 1:
539
+ pitch, pitchf = self.get_f0(
540
+ input_audio_path,
541
+ audio_pad,
542
+ p_len,
543
+ f0_up_key,
544
+ f0_method,
545
+ filter_radius,
546
+ crepe_hop_length,
547
+ inp_f0,
548
+ )
549
+ pitch = pitch[:p_len]
550
+ pitchf = pitchf[:p_len]
551
+ if self.device == "mps":
552
+ pitchf = pitchf.astype(np.float32)
553
+ pitch = torch.tensor(pitch, device=self.device).unsqueeze(0).long()
554
+ pitchf = torch.tensor(pitchf, device=self.device).unsqueeze(0).float()
555
+ t2 = ttime()
556
+ times[1] += t2 - t1
557
+ for t in opt_ts:
558
+ t = t // self.window * self.window
559
+ if if_f0 == 1:
560
+ audio_opt.append(
561
+ self.vc(
562
+ model,
563
+ net_g,
564
+ sid,
565
+ audio_pad[s : t + self.t_pad2 + self.window],
566
+ pitch[:, s // self.window : (t + self.t_pad2) // self.window],
567
+ pitchf[:, s // self.window : (t + self.t_pad2) // self.window],
568
+ times,
569
+ index,
570
+ big_npy,
571
+ index_rate,
572
+ version,
573
+ protect,
574
+ )[self.t_pad_tgt : -self.t_pad_tgt]
575
+ )
576
+ else:
577
+ audio_opt.append(
578
+ self.vc(
579
+ model,
580
+ net_g,
581
+ sid,
582
+ audio_pad[s : t + self.t_pad2 + self.window],
583
+ None,
584
+ None,
585
+ times,
586
+ index,
587
+ big_npy,
588
+ index_rate,
589
+ version,
590
+ protect,
591
+ )[self.t_pad_tgt : -self.t_pad_tgt]
592
+ )
593
+ s = t
594
+ if if_f0 == 1:
595
+ audio_opt.append(
596
+ self.vc(
597
+ model,
598
+ net_g,
599
+ sid,
600
+ audio_pad[t:],
601
+ pitch[:, t // self.window :] if t is not None else pitch,
602
+ pitchf[:, t // self.window :] if t is not None else pitchf,
603
+ times,
604
+ index,
605
+ big_npy,
606
+ index_rate,
607
+ version,
608
+ protect,
609
+ )[self.t_pad_tgt : -self.t_pad_tgt]
610
+ )
611
+ else:
612
+ audio_opt.append(
613
+ self.vc(
614
+ model,
615
+ net_g,
616
+ sid,
617
+ audio_pad[t:],
618
+ None,
619
+ None,
620
+ times,
621
+ index,
622
+ big_npy,
623
+ index_rate,
624
+ version,
625
+ protect,
626
+ )[self.t_pad_tgt : -self.t_pad_tgt]
627
+ )
628
+ audio_opt = np.concatenate(audio_opt)
629
+ if rms_mix_rate != 1:
630
+ audio_opt = change_rms(audio, 16000, audio_opt, tgt_sr, rms_mix_rate)
631
+ if resample_sr >= 16000 and tgt_sr != resample_sr:
632
+ audio_opt = librosa.resample(
633
+ audio_opt, orig_sr=tgt_sr, target_sr=resample_sr
634
+ )
635
+ audio_max = np.abs(audio_opt).max() / 0.99
636
+ max_int16 = 32768
637
+ if audio_max > 1:
638
+ max_int16 /= audio_max
639
+ audio_opt = (audio_opt * max_int16).astype(np.int16)
640
+ del pitch, pitchf, sid
641
+ if torch.cuda.is_available():
642
+ torch.cuda.empty_cache()
643
+ return audio_opt