Eempostor commited on
Commit
04f87da
1 Parent(s): 1933c64

Upload pipeline.py

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