Vijish commited on
Commit
33ea1c2
·
verified ·
1 Parent(s): a6d28e0

Update vc_infer_pipeline.py

Browse files
Files changed (1) hide show
  1. vc_infer_pipeline.py +443 -451
vc_infer_pipeline.py CHANGED
@@ -1,451 +1,443 @@
1
- import os
2
- import sys
3
- import traceback
4
- from functools import lru_cache
5
- from time import time as ttime
6
-
7
- import faiss
8
- import librosa
9
- import numpy as np
10
- import parselmouth
11
- import pyworld
12
- import torch
13
- import torch.nn.functional as F
14
- import torchcrepe
15
- from scipy import signal
16
-
17
- now_dir = os.getcwd()
18
- sys.path.append(now_dir)
19
-
20
- bh, ah = signal.butter(N=5, Wn=48, btype="high", fs=16000)
21
-
22
- input_audio_path2wav = {}
23
-
24
-
25
- @lru_cache
26
- def cache_harvest_f0(input_audio_path, fs, f0max, f0min, frame_period):
27
- audio = input_audio_path2wav[input_audio_path]
28
- f0, t = pyworld.harvest(
29
- audio,
30
- fs=fs,
31
- f0_ceil=f0max,
32
- f0_floor=f0min,
33
- frame_period=frame_period,
34
- )
35
- f0 = pyworld.stonemask(audio, f0, t, fs)
36
- return f0
37
-
38
-
39
- def change_rms(data1, sr1, data2, sr2, rate): # 1是输入音频,2是输出音频,rate是2的占比
40
- # print(data1.max(),data2.max())
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 # hubert输入采样率
71
- self.window = 160 # 每帧点数
72
- self.t_pad = self.sr * self.x_pad # 每条前后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
- def get_f0(
81
- self,
82
- input_audio_path,
83
- x,
84
- p_len,
85
- f0_up_key,
86
- f0_method,
87
- filter_radius,
88
- inp_f0=None,
89
- ):
90
- global input_audio_path2wav
91
- time_step = self.window / self.sr * 1000
92
- f0_min = 50
93
- f0_max = 1100
94
- f0_mel_min = 1127 * np.log(1 + f0_min / 700)
95
- f0_mel_max = 1127 * np.log(1 + f0_max / 700)
96
- if f0_method == "pm":
97
- f0 = (
98
- parselmouth.Sound(x, self.sr)
99
- .to_pitch_ac(
100
- time_step=time_step / 1000,
101
- voicing_threshold=0.6,
102
- pitch_floor=f0_min,
103
- pitch_ceiling=f0_max,
104
- )
105
- .selected_array["frequency"]
106
- )
107
- pad_size = (p_len - len(f0) + 1) // 2
108
- if pad_size > 0 or p_len - len(f0) - pad_size > 0:
109
- f0 = np.pad(
110
- f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant"
111
- )
112
- elif f0_method == "harvest":
113
- input_audio_path2wav[input_audio_path] = x.astype(np.double)
114
- f0 = cache_harvest_f0(input_audio_path, self.sr, f0_max, f0_min, 10)
115
- if filter_radius > 2:
116
- f0 = signal.medfilt(f0, 3)
117
- elif f0_method == "crepe":
118
- model = "full"
119
- # Pick a batch size that doesn't cause memory errors on your gpu
120
- batch_size = 512
121
- # Compute pitch using first gpu
122
- audio = torch.tensor(np.copy(x))[None].float()
123
- f0, pd = torchcrepe.predict(
124
- audio,
125
- self.sr,
126
- self.window,
127
- f0_min,
128
- f0_max,
129
- model,
130
- batch_size=batch_size,
131
- device=self.device,
132
- return_periodicity=True,
133
- )
134
- pd = torchcrepe.filter.median(pd, 3)
135
- f0 = torchcrepe.filter.mean(f0, 3)
136
- f0[pd < 0.1] = 0
137
- f0 = f0[0].cpu().numpy()
138
- elif f0_method == "rmvpe":
139
- if hasattr(self, "model_rmvpe") == False:
140
- from rmvpe import RMVPE
141
-
142
- print("loading rmvpe model")
143
- self.model_rmvpe = RMVPE(
144
- "rmvpe.pt", is_half=self.is_half, device=self.device
145
- )
146
- f0 = self.model_rmvpe.infer_from_audio(x, thred=0.03)
147
- f0 *= pow(2, f0_up_key / 12)
148
- # with open("test.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()]))
149
- tf0 = self.sr // self.window # 每秒f0点数
150
- if inp_f0 is not None:
151
- delta_t = np.round(
152
- (inp_f0[:, 0].max() - inp_f0[:, 0].min()) * tf0 + 1
153
- ).astype("int16")
154
- replace_f0 = np.interp(
155
- list(range(delta_t)), inp_f0[:, 0] * 100, inp_f0[:, 1]
156
- )
157
- shape = f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)].shape[0]
158
- f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)] = replace_f0[
159
- :shape
160
- ]
161
- # with open("test_opt.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()]))
162
- f0bak = f0.copy()
163
- f0_mel = 1127 * np.log(1 + f0 / 700)
164
- f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / (
165
- f0_mel_max - f0_mel_min
166
- ) + 1
167
- f0_mel[f0_mel <= 1] = 1
168
- f0_mel[f0_mel > 255] = 255
169
- f0_coarse = np.rint(f0_mel).astype(np.int)
170
- return f0_coarse, f0bak # 1-0
171
-
172
- def vc(
173
- self,
174
- model,
175
- net_g,
176
- sid,
177
- audio0,
178
- pitch,
179
- pitchf,
180
- times,
181
- index,
182
- big_npy,
183
- index_rate,
184
- version,
185
- protect,
186
- ): # ,file_index,file_big_npy
187
- feats = torch.from_numpy(audio0)
188
- if self.is_half:
189
- feats = feats.half()
190
- else:
191
- feats = feats.float()
192
- if feats.dim() == 2: # double channels
193
- feats = feats.mean(-1)
194
- assert feats.dim() == 1, feats.dim()
195
- feats = feats.view(1, -1)
196
- padding_mask = torch.BoolTensor(feats.shape).to(self.device).fill_(False)
197
-
198
- inputs = {
199
- "source": feats.to(self.device),
200
- "padding_mask": padding_mask,
201
- "output_layer": 9 if version == "v1" else 12,
202
- }
203
- t0 = ttime()
204
- with torch.no_grad():
205
- logits = model.extract_features(**inputs)
206
- feats = model.final_proj(logits[0]) if version == "v1" else logits[0]
207
- if protect < 0.5 and pitch != None and pitchf != None:
208
- feats0 = feats.clone()
209
- if (
210
- isinstance(index, type(None)) == False
211
- and isinstance(big_npy, type(None)) == False
212
- and index_rate != 0
213
- ):
214
- npy = feats[0].cpu().numpy()
215
- if self.is_half:
216
- npy = npy.astype("float32")
217
-
218
- # _, I = index.search(npy, 1)
219
- # npy = big_npy[I.squeeze()]
220
-
221
- score, ix = index.search(npy, k=8)
222
- weight = np.square(1 / score)
223
- weight /= weight.sum(axis=1, keepdims=True)
224
- npy = np.sum(big_npy[ix] * np.expand_dims(weight, axis=2), axis=1)
225
-
226
- if self.is_half:
227
- npy = npy.astype("float16")
228
- feats = (
229
- torch.from_numpy(npy).unsqueeze(0).to(self.device) * index_rate
230
- + (1 - index_rate) * feats
231
- )
232
-
233
- feats = F.interpolate(feats.permute(0, 2, 1), scale_factor=2).permute(0, 2, 1)
234
- if protect < 0.5 and pitch != None and pitchf != None:
235
- feats0 = F.interpolate(feats0.permute(0, 2, 1), scale_factor=2).permute(
236
- 0, 2, 1
237
- )
238
- t1 = ttime()
239
- p_len = audio0.shape[0] // self.window
240
- if feats.shape[1] < p_len:
241
- p_len = feats.shape[1]
242
- if pitch != None and pitchf != None:
243
- pitch = pitch[:, :p_len]
244
- pitchf = pitchf[:, :p_len]
245
-
246
- if protect < 0.5 and pitch != None and pitchf != None:
247
- pitchff = pitchf.clone()
248
- pitchff[pitchf > 0] = 1
249
- pitchff[pitchf < 1] = protect
250
- pitchff = pitchff.unsqueeze(-1)
251
- feats = feats * pitchff + feats0 * (1 - pitchff)
252
- feats = feats.to(feats0.dtype)
253
- p_len = torch.tensor([p_len], device=self.device).long()
254
- with torch.no_grad():
255
- if pitch != None and pitchf != None:
256
- audio1 = (
257
- (net_g.infer(feats, p_len, pitch, pitchf, sid)[0][0, 0])
258
- .data.cpu()
259
- .float()
260
- .numpy()
261
- )
262
- else:
263
- audio1 = (
264
- (net_g.infer(feats, p_len, sid)[0][0, 0]).data.cpu().float().numpy()
265
- )
266
- del feats, p_len, padding_mask
267
- if torch.cuda.is_available():
268
- torch.cuda.empty_cache()
269
- t2 = ttime()
270
- times[0] += t1 - t0
271
- times[2] += t2 - t1
272
- return audio1
273
-
274
- def pipeline(
275
- self,
276
- model,
277
- net_g,
278
- sid,
279
- audio,
280
- input_audio_path,
281
- times,
282
- f0_up_key,
283
- f0_method,
284
- file_index,
285
- # file_big_npy,
286
- index_rate,
287
- if_f0,
288
- filter_radius,
289
- tgt_sr,
290
- resample_sr,
291
- rms_mix_rate,
292
- version,
293
- protect,
294
- f0_file=None,
295
- ):
296
- if (
297
- file_index != ""
298
- # and file_big_npy != ""
299
- # and os.path.exists(file_big_npy) == True
300
- and os.path.exists(file_index) == True
301
- and index_rate != 0
302
- ):
303
- try:
304
- index = faiss.read_index(file_index)
305
- # big_npy = np.load(file_big_npy)
306
- big_npy = index.reconstruct_n(0, index.ntotal)
307
- except:
308
- traceback.print_exc()
309
- index = big_npy = None
310
- else:
311
- index = big_npy = None
312
- audio = signal.filtfilt(bh, ah, audio)
313
- audio_pad = np.pad(audio, (self.window // 2, self.window // 2), mode="reflect")
314
- opt_ts = []
315
- if audio_pad.shape[0] > self.t_max:
316
- audio_sum = np.zeros_like(audio)
317
- for i in range(self.window):
318
- audio_sum += audio_pad[i : i - self.window]
319
- for t in range(self.t_center, audio.shape[0], self.t_center):
320
- opt_ts.append(
321
- t
322
- - self.t_query
323
- + np.where(
324
- np.abs(audio_sum[t - self.t_query : t + self.t_query])
325
- == np.abs(audio_sum[t - self.t_query : t + self.t_query]).min()
326
- )[0][0]
327
- )
328
- s = 0
329
- audio_opt = []
330
- t = None
331
- t1 = ttime()
332
- audio_pad = np.pad(audio, (self.t_pad, self.t_pad), mode="reflect")
333
- p_len = audio_pad.shape[0] // self.window
334
- inp_f0 = None
335
- if hasattr(f0_file, "name") == True:
336
- try:
337
- with open(f0_file.name, "r") as f:
338
- lines = f.read().strip("\n").split("\n")
339
- inp_f0 = []
340
- for line in lines:
341
- inp_f0.append([float(i) for i in line.split(",")])
342
- inp_f0 = np.array(inp_f0, dtype="float32")
343
- except:
344
- traceback.print_exc()
345
- sid = torch.tensor(sid, device=self.device).unsqueeze(0).long()
346
- pitch, pitchf = None, None
347
- if if_f0 == 1:
348
- pitch, pitchf = self.get_f0(
349
- input_audio_path,
350
- audio_pad,
351
- p_len,
352
- f0_up_key,
353
- f0_method,
354
- filter_radius,
355
- inp_f0,
356
- )
357
- pitch = pitch[:p_len]
358
- pitchf = pitchf[:p_len]
359
- if self.device == "mps":
360
- pitchf = pitchf.astype(np.float32)
361
- pitch = torch.tensor(pitch, device=self.device).unsqueeze(0).long()
362
- pitchf = torch.tensor(pitchf, device=self.device).unsqueeze(0).float()
363
- t2 = ttime()
364
- times[1] += t2 - t1
365
- for t in opt_ts:
366
- t = t // self.window * self.window
367
- if if_f0 == 1:
368
- audio_opt.append(
369
- self.vc(
370
- model,
371
- net_g,
372
- sid,
373
- audio_pad[s : t + self.t_pad2 + self.window],
374
- pitch[:, s // self.window : (t + self.t_pad2) // self.window],
375
- pitchf[:, s // self.window : (t + self.t_pad2) // self.window],
376
- times,
377
- index,
378
- big_npy,
379
- index_rate,
380
- version,
381
- protect,
382
- )[self.t_pad_tgt : -self.t_pad_tgt]
383
- )
384
- else:
385
- audio_opt.append(
386
- self.vc(
387
- model,
388
- net_g,
389
- sid,
390
- audio_pad[s : t + self.t_pad2 + self.window],
391
- None,
392
- None,
393
- times,
394
- index,
395
- big_npy,
396
- index_rate,
397
- version,
398
- protect,
399
- )[self.t_pad_tgt : -self.t_pad_tgt]
400
- )
401
- s = t
402
- if if_f0 == 1:
403
- audio_opt.append(
404
- self.vc(
405
- model,
406
- net_g,
407
- sid,
408
- audio_pad[t:],
409
- pitch[:, t // self.window :] if t is not None else pitch,
410
- pitchf[:, t // self.window :] if t is not None else pitchf,
411
- times,
412
- index,
413
- big_npy,
414
- index_rate,
415
- version,
416
- protect,
417
- )[self.t_pad_tgt : -self.t_pad_tgt]
418
- )
419
- else:
420
- audio_opt.append(
421
- self.vc(
422
- model,
423
- net_g,
424
- sid,
425
- audio_pad[t:],
426
- None,
427
- None,
428
- times,
429
- index,
430
- big_npy,
431
- index_rate,
432
- version,
433
- protect,
434
- )[self.t_pad_tgt : -self.t_pad_tgt]
435
- )
436
- audio_opt = np.concatenate(audio_opt)
437
- if rms_mix_rate != 1:
438
- audio_opt = change_rms(audio, 16000, audio_opt, tgt_sr, rms_mix_rate)
439
- if resample_sr >= 16000 and tgt_sr != resample_sr:
440
- audio_opt = librosa.resample(
441
- audio_opt, orig_sr=tgt_sr, target_sr=resample_sr
442
- )
443
- audio_max = np.abs(audio_opt).max() / 0.99
444
- max_int16 = 32768
445
- if audio_max > 1:
446
- max_int16 /= audio_max
447
- audio_opt = (audio_opt * max_int16).astype(np.int16)
448
- del pitch, pitchf, sid
449
- if torch.cuda.is_available():
450
- torch.cuda.empty_cache()
451
- return audio_opt
 
1
+ import os
2
+ import sys
3
+ import traceback
4
+ from functools import lru_cache
5
+ from time import time as ttime
6
+ from concurrent.futures import ThreadPoolExecutor
7
+
8
+ import faiss
9
+ import librosa
10
+ import numpy as np
11
+ import parselmouth
12
+ import pyworld
13
+ import torch
14
+ import torch.nn.functional as F
15
+ import torchcrepe
16
+ from scipy import signal
17
+
18
+ now_dir = os.getcwd()
19
+ sys.path.append(now_dir)
20
+
21
+ bh, ah = signal.butter(N=5, Wn=48, btype="high", fs=16000)
22
+
23
+ input_audio_path2wav = {}
24
+
25
+ @lru_cache
26
+ def cache_harvest_f0(input_audio_path, fs, f0max, f0min, frame_period):
27
+ audio = input_audio_path2wav[input_audio_path]
28
+ f0, t = pyworld.harvest(
29
+ audio,
30
+ fs=fs,
31
+ f0_ceil=f0max,
32
+ f0_floor=f0min,
33
+ frame_period=frame_period,
34
+ )
35
+ f0 = pyworld.stonemask(audio, f0, t, fs)
36
+ return f0
37
+
38
+ def change_rms(data1, sr1, data2, sr2, rate): # 1是输入音频,2是输出音频,rate是2的占比
39
+ rms1 = librosa.feature.rms(
40
+ y=data1, frame_length=sr1 // 2 * 2, hop_length=sr1 // 2
41
+ ) # 每半秒一个点
42
+ rms2 = librosa.feature.rms(y=data2, frame_length=sr2 // 2 * 2, hop_length=sr2 // 2)
43
+ rms1 = torch.from_numpy(rms1)
44
+ rms1 = F.interpolate(
45
+ rms1.unsqueeze(0), size=data2.shape[0], mode="linear"
46
+ ).squeeze()
47
+ rms2 = torch.from_numpy(rms2)
48
+ rms2 = F.interpolate(
49
+ rms2.unsqueeze(0), size=data2.shape[0], mode="linear"
50
+ ).squeeze()
51
+ rms2 = torch.max(rms2, torch.zeros_like(rms2) + 1e-6)
52
+ data2 *= (
53
+ torch.pow(rms1, torch.tensor(1 - rate))
54
+ * torch.pow(rms2, torch.tensor(rate - 1))
55
+ ).numpy()
56
+ return data2
57
+
58
+ class VC(object):
59
+ def __init__(self, tgt_sr, config):
60
+ self.x_pad, self.x_query, self.x_center, self.x_max, self.is_half = (
61
+ config.x_pad,
62
+ config.x_query,
63
+ config.x_center,
64
+ config.x_max,
65
+ config.is_half,
66
+ )
67
+ self.sr = 16000 # hubert输入采样率
68
+ self.window = 160 # 每帧点数
69
+ self.t_pad = self.sr * self.x_pad # 每条前后pad时间
70
+ self.t_pad_tgt = tgt_sr * self.x_pad
71
+ self.t_pad2 = self.t_pad * 2
72
+ self.t_query = self.sr * self.x_query # 查询切点前后查询时间
73
+ self.t_center = self.sr * self.x_center # 查询切点位置
74
+ self.t_max = self.sr * self.x_max # 免查询时长阈值
75
+ self.device = config.device
76
+
77
+ def get_f0(
78
+ self,
79
+ input_audio_path,
80
+ x,
81
+ p_len,
82
+ f0_up_key,
83
+ f0_method,
84
+ filter_radius,
85
+ inp_f0=None,
86
+ ):
87
+ global input_audio_path2wav
88
+ time_step = self.window / self.sr * 1000
89
+ f0_min = 50
90
+ f0_max = 1100
91
+ f0_mel_min = 1127 * np.log(1 + f0_min / 700)
92
+ f0_mel_max = 1127 * np.log(1 + f0_max / 700)
93
+ if f0_method == "pm":
94
+ f0 = (
95
+ parselmouth.Sound(x, self.sr)
96
+ .to_pitch_ac(
97
+ time_step=time_step / 1000,
98
+ voicing_threshold=0.6,
99
+ pitch_floor=f0_min,
100
+ pitch_ceiling=f0_max,
101
+ )
102
+ .selected_array["frequency"]
103
+ )
104
+ pad_size = (p_len - len(f0) + 1) // 2
105
+ if pad_size > 0 or p_len - len(f0) - pad_size > 0:
106
+ f0 = np.pad(
107
+ f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant"
108
+ )
109
+ elif f0_method == "harvest":
110
+ input_audio_path2wav[input_audio_path] = x.astype(np.double)
111
+ f0 = cache_harvest_f0(input_audio_path, self.sr, f0_max, f0_min, 10)
112
+ if filter_radius > 2:
113
+ f0 = signal.medfilt(f0, 3)
114
+ elif f0_method == "crepe":
115
+ model = "full"
116
+ # Pick a batch size that doesn't cause memory errors on your gpu
117
+ batch_size = 512
118
+ # Compute pitch using first gpu
119
+ audio = torch.tensor(np.copy(x))[None].float()
120
+ f0, pd = torchcrepe.predict(
121
+ audio,
122
+ self.sr,
123
+ self.window,
124
+ f0_min,
125
+ f0_max,
126
+ model,
127
+ batch_size=batch_size,
128
+ device=self.device,
129
+ return_periodicity=True,
130
+ )
131
+ pd = torchcrepe.filter.median(pd, 3)
132
+ f0 = torchcrepe.filter.mean(f0, 3)
133
+ f0[pd < 0.1] = 0
134
+ f0 = f0[0].cpu().numpy()
135
+ elif f0_method == "rmvpe":
136
+ if hasattr(self, "model_rmvpe") == False:
137
+ from rmvpe import RMVPE
138
+
139
+ print("loading rmvpe model")
140
+ self.model_rmvpe = RMVPE(
141
+ "rmvpe.pt", is_half=self.is_half, device=self.device
142
+ )
143
+ f0 = self.model_rmvpe.infer_from_audio(x, thred=0.03)
144
+ f0 *= pow(2, f0_up_key / 12)
145
+ tf0 = self.sr // self.window # 每秒f0点数
146
+ if inp_f0 is not None:
147
+ delta_t = np.round(
148
+ (inp_f0[:, 0].max() - inp_f0[:, 0].min()) * tf0 + 1
149
+ ).astype("int16")
150
+ replace_f0 = np.interp(
151
+ list(range(delta_t)), inp_f0[:, 0] * 100, inp_f0[:, 1]
152
+ )
153
+ shape = f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)].shape[0]
154
+ f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)] = replace_f0[
155
+ :shape
156
+ ]
157
+ f0bak = f0.copy()
158
+ f0_mel = 1127 * np.log(1 + f0 / 700)
159
+ f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / (
160
+ f0_mel_max - f0_mel_min
161
+ ) + 1
162
+ f0_mel[f0_mel <= 1] = 1
163
+ f0_mel[f0_mel > 255] = 255
164
+ f0_coarse = np.rint(f0_mel).astype(np.int)
165
+ return f0_coarse, f0bak # 1-0
166
+
167
+ def vc(
168
+ self,
169
+ model,
170
+ net_g,
171
+ sid,
172
+ audio0,
173
+ pitch,
174
+ pitchf,
175
+ times,
176
+ index,
177
+ big_npy,
178
+ index_rate,
179
+ version,
180
+ protect,
181
+ ):
182
+ feats = torch.from_numpy(audio0)
183
+ if self.is_half:
184
+ feats = feats.half()
185
+ else:
186
+ feats = feats.float()
187
+ if feats.dim() == 2: # double channels
188
+ feats = feats.mean(-1)
189
+ assert feats.dim() == 1, feats.dim()
190
+ feats = feats.view(1, -1)
191
+ padding_mask = torch.BoolTensor(feats.shape).to(self.device).fill_(False)
192
+
193
+ inputs = {
194
+ "source": feats.to(self.device),
195
+ "padding_mask": padding_mask,
196
+ "output_layer": 9 if version == "v1" else 12,
197
+ }
198
+ t0 = ttime()
199
+ with torch.no_grad():
200
+ logits = model.extract_features(**inputs)
201
+ feats = model.final_proj(logits[0]) if version == "v1" else logits[0]
202
+ if protect < 0.5 and pitch is not None and pitchf is not None:
203
+ feats0 = feats.clone()
204
+ if (
205
+ index is not None
206
+ and big_npy is not None
207
+ and index_rate != 0
208
+ ):
209
+ npy = feats[0].cpu().numpy()
210
+ if self.is_half:
211
+ npy = npy.astype("float32")
212
+
213
+ score, ix = index.search(npy, k=8)
214
+ weight = np.square(1 / score)
215
+ weight /= weight.sum(axis=1, keepdims=True)
216
+ npy = np.sum(big_npy[ix] * np.expand_dims(weight, axis=2), axis=1)
217
+
218
+ if self.is_half:
219
+ npy = npy.astype("float16")
220
+ feats = (
221
+ torch.from_numpy(npy).unsqueeze(0).to(self.device) * index_rate
222
+ + (1 - index_rate) * feats
223
+ )
224
+
225
+ feats = F.interpolate(feats.permute(0, 2, 1), scale_factor=2).permute(0, 2, 1)
226
+ if protect < 0.5 and pitch is not None and pitchf is not None:
227
+ feats0 = F.interpolate(feats0.permute(0, 2, 1), scale_factor=2).permute(
228
+ 0, 2, 1
229
+ )
230
+ t1 = ttime()
231
+ p_len = audio0.shape[0] // self.window
232
+ if feats.shape[1] < p_len:
233
+ p_len = feats.shape[1]
234
+ if pitch is not None and pitchf is not None:
235
+ pitch = pitch[:, :p_len]
236
+ pitchf = pitchf[:, :p_len]
237
+
238
+ if protect < 0.5 and pitch is not None and pitchf is not None:
239
+ pitchff = pitchf.clone()
240
+ pitchff[pitchf > 0] = 1
241
+ pitchff[pitchf < 1] = protect
242
+ pitchff = pitchff.unsqueeze(-1)
243
+ feats = feats * pitchff + feats0 * (1 - pitchff)
244
+ feats = feats.to(feats0.dtype)
245
+ p_len = torch.tensor([p_len], device=self.device).long()
246
+ with torch.no_grad():
247
+ if pitch is not None and pitchf is not None:
248
+ audio1 = (
249
+ (net_g.infer(feats, p_len, pitch, pitchf, sid)[0][0, 0])
250
+ .data.cpu()
251
+ .float()
252
+ .numpy()
253
+ )
254
+ else:
255
+ audio1 = (
256
+ (net_g.infer(feats, p_len, sid)[0][0, 0]).data.cpu().float().numpy()
257
+ )
258
+ del feats, p_len, padding_mask
259
+ if torch.cuda.is_available():
260
+ torch.cuda.empty_cache()
261
+ t2 = ttime()
262
+ times[0] += t1 - t0
263
+ times[2] += t2 - t1
264
+ return audio1
265
+
266
+ def pipeline(
267
+ self,
268
+ model,
269
+ net_g,
270
+ sid,
271
+ audio,
272
+ input_audio_path,
273
+ times,
274
+ f0_up_key,
275
+ f0_method,
276
+ file_index,
277
+ index_rate,
278
+ if_f0,
279
+ filter_radius,
280
+ tgt_sr,
281
+ resample_sr,
282
+ rms_mix_rate,
283
+ version,
284
+ protect,
285
+ f0_file=None,
286
+ ):
287
+ if (
288
+ file_index != ""
289
+ and os.path.exists(file_index)
290
+ and index_rate != 0
291
+ ):
292
+ try:
293
+ index = faiss.read_index(file_index)
294
+ big_npy = index.reconstruct_n(0, index.ntotal)
295
+ except:
296
+ traceback.print_exc()
297
+ index = big_npy = None
298
+ else:
299
+ index = big_npy = None
300
+ audio = signal.filtfilt(bh, ah, audio)
301
+ audio_pad = np.pad(audio, (self.window // 2, self.window // 2), mode="reflect")
302
+ opt_ts = []
303
+ if audio_pad.shape[0] > self.t_max:
304
+ audio_sum = np.zeros_like(audio)
305
+ for i in range(self.window):
306
+ audio_sum += audio_pad[i : i - self.window]
307
+ for t in range(self.t_center, audio.shape[0], self.t_center):
308
+ opt_ts.append(
309
+ t
310
+ - self.t_query
311
+ + np.where(
312
+ np.abs(audio_sum[t - self.t_query : t + self.t_query])
313
+ == np.abs(audio_sum[t - self.t_query : t + self.t_query]).min()
314
+ )[0][0]
315
+ )
316
+ s = 0
317
+ audio_opt = []
318
+ t = None
319
+ t1 = ttime()
320
+ audio_pad = np.pad(audio, (self.t_pad, self.t_pad), mode="reflect")
321
+ p_len = audio_pad.shape[0] // self.window
322
+ inp_f0 = None
323
+ if hasattr(f0_file, "name"):
324
+ try:
325
+ with open(f0_file.name, "r") as f:
326
+ lines = f.read().strip("\n").split("\n")
327
+ inp_f0 = []
328
+ for line in lines:
329
+ inp_f0.append([float(i) for i in line.split(",")])
330
+ inp_f0 = np.array(inp_f0, dtype="float32")
331
+ except:
332
+ traceback.print_exc()
333
+ sid = torch.tensor(sid, device=self.device).unsqueeze(0).long()
334
+ pitch, pitchf = None, None
335
+ if if_f0 == 1:
336
+ pitch, pitchf = self.get_f0(
337
+ input_audio_path,
338
+ audio_pad,
339
+ p_len,
340
+ f0_up_key,
341
+ f0_method,
342
+ filter_radius,
343
+ inp_f0,
344
+ )
345
+ pitch = pitch[:p_len]
346
+ pitchf = pitchf[:p_len]
347
+ if self.device == "mps":
348
+ pitchf = pitchf.astype(np.float32)
349
+ pitch = torch.tensor(pitch, device=self.device).unsqueeze(0).long()
350
+ pitchf = torch.tensor(pitchf, device=self.device).unsqueeze(0).float()
351
+ t2 = ttime()
352
+ times[1] += t2 - t1
353
+ for t in opt_ts:
354
+ t = t // self.window * self.window
355
+ if if_f0 == 1:
356
+ audio_opt.append(
357
+ self.vc(
358
+ model,
359
+ net_g,
360
+ sid,
361
+ audio_pad[s : t + self.t_pad2 + self.window],
362
+ pitch[:, s // self.window : (t + self.t_pad2) // self.window],
363
+ pitchf[:, s // self.window : (t + self.t_pad2) // self.window],
364
+ times,
365
+ index,
366
+ big_npy,
367
+ index_rate,
368
+ version,
369
+ protect,
370
+ )[self.t_pad_tgt : -self.t_pad_tgt]
371
+ )
372
+ else:
373
+ audio_opt.append(
374
+ self.vc(
375
+ model,
376
+ net_g,
377
+ sid,
378
+ audio_pad[s : t + self.t_pad2 + self.window],
379
+ None,
380
+ None,
381
+ times,
382
+ index,
383
+ big_npy,
384
+ index_rate,
385
+ version,
386
+ protect,
387
+ )[self.t_pad_tgt : -self.t_pad_tgt]
388
+ )
389
+ s = t
390
+ if if_f0 == 1:
391
+ audio_opt.append(
392
+ self.vc(
393
+ model,
394
+ net_g,
395
+ sid,
396
+ audio_pad[t:],
397
+ pitch[:, t // self.window :] if t is not None else pitch,
398
+ pitchf[:, t // self.window :] if t is not None else pitchf,
399
+ times,
400
+ index,
401
+ big_npy,
402
+ index_rate,
403
+ version,
404
+ protect,
405
+ )[self.t_pad_tgt : -self.t_pad_tgt]
406
+ )
407
+ else:
408
+ audio_opt.append(
409
+ self.vc(
410
+ model,
411
+ net_g,
412
+ sid,
413
+ audio_pad[t:],
414
+ None,
415
+ None,
416
+ times,
417
+ index,
418
+ big_npy,
419
+ index_rate,
420
+ version,
421
+ protect,
422
+ )[self.t_pad_tgt : -self.t_pad_tgt]
423
+ )
424
+ audio_opt = np.concatenate(audio_opt)
425
+ if rms_mix_rate != 1:
426
+ audio_opt = change_rms(audio, 16000, audio_opt, tgt_sr, rms_mix_rate)
427
+ if resample_sr >= 16000 and tgt_sr != resample_sr:
428
+ audio_opt = librosa.resample(audio_opt, orig_sr=tgt_sr, target_sr=resample_sr)
429
+ audio_max = np.abs(audio_opt).max() / 0.99
430
+ max_int16 = 32768
431
+ if audio_max > 1:
432
+ max_int16 /= audio_max
433
+ audio_opt = (audio_opt * max_int16).astype(np.int16)
434
+ del pitch, pitchf, sid
435
+ if torch.cuda.is_available():
436
+ torch.cuda.empty_cache()
437
+ return audio_opt
438
+
439
+ def parallel_pipeline(self, tasks):
440
+ with ThreadPoolExecutor() as executor:
441
+ futures = [executor.submit(self.pipeline, *task) for task in tasks]
442
+ results = [future.result() for future in futures]
443
+ return results