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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
from torchfcpe import spawn_bundled_infer_model
|
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_rmvpe(self, x, *args, **kwargs):
|
200 |
+
if not hasattr(self, "model_rmvpe"):
|
201 |
+
from lib.infer.infer_libs.rmvpe import RMVPE
|
202 |
+
|
203 |
+
logger.info(
|
204 |
+
f"Loading rmvpe model, {os.environ['rmvpe_model_path']}"
|
205 |
+
)
|
206 |
+
self.model_rmvpe = RMVPE(
|
207 |
+
os.environ["rmvpe_model_path"],
|
208 |
+
is_half=self.is_half,
|
209 |
+
device=self.device,
|
210 |
+
)
|
211 |
+
f0 = self.model_rmvpe.infer_from_audio(x, thred=0.03)
|
212 |
+
|
213 |
+
if "privateuseone" in str(self.device): # clean ortruntime memory
|
214 |
+
del self.model_rmvpe.model
|
215 |
+
del self.model_rmvpe
|
216 |
+
logger.info("Cleaning ortruntime memory")
|
217 |
+
|
218 |
+
return f0
|
219 |
+
|
220 |
+
|
221 |
+
def get_pitch_dependant_rmvpe(self, x, f0_min=1, f0_max=40000, *args, **kwargs):
|
222 |
+
if not hasattr(self, "model_rmvpe"):
|
223 |
+
from lib.infer.infer_libs.rmvpe import RMVPE
|
224 |
+
|
225 |
+
logger.info(
|
226 |
+
f"Loading rmvpe model, {os.environ['rmvpe_model_path']}"
|
227 |
+
)
|
228 |
+
self.model_rmvpe = RMVPE(
|
229 |
+
os.environ["rmvpe_model_path"],
|
230 |
+
is_half=self.is_half,
|
231 |
+
device=self.device,
|
232 |
+
)
|
233 |
+
f0 = self.model_rmvpe.infer_from_audio_with_pitch(x, thred=0.03, f0_min=f0_min, f0_max=f0_max)
|
234 |
+
if "privateuseone" in str(self.device): # clean ortruntime memory
|
235 |
+
del self.model_rmvpe.model
|
236 |
+
del self.model_rmvpe
|
237 |
+
logger.info("Cleaning ortruntime memory")
|
238 |
+
|
239 |
+
return f0
|
240 |
+
|
241 |
+
def get_fcpe(self, x, f0_min, f0_max, p_len, *args, **kwargs):
|
242 |
+
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)
|
243 |
+
f0 = self.model_fcpe.compute_f0(x, p_len=p_len)
|
244 |
+
del self.model_fcpe
|
245 |
+
gc.collect()
|
246 |
+
return f0
|
247 |
+
|
248 |
+
def get_torchfcpe(self, x, sr, f0_min, f0_max, p_len, *args, **kwargs):
|
249 |
+
self.model_torchfcpe = spawn_bundled_infer_model(device=self.device)
|
250 |
+
f0 = self.model_torchfcpe.infer(
|
251 |
+
torch.from_numpy(x).float().unsqueeze(0).unsqueeze(-1).to(self.device),
|
252 |
+
sr=sr,
|
253 |
+
decoder_mode="local_argmax",
|
254 |
+
threshold=0.03,
|
255 |
+
f0_min=f0_min,
|
256 |
+
f0_max=f0_max,
|
257 |
+
output_interp_target_length=p_len
|
258 |
+
)
|
259 |
+
return f0.squeeze().cpu().numpy()
|
260 |
+
|
261 |
+
def autotune_f0(self, f0):
|
262 |
+
autotuned_f0 = []
|
263 |
+
for freq in f0:
|
264 |
+
closest_notes = [x for x in self.note_dict if abs(x - freq) == min(abs(n - freq) for n in self.note_dict)]
|
265 |
+
autotuned_f0.append(random.choice(closest_notes))
|
266 |
+
return np.array(autotuned_f0, np.float64)
|
267 |
+
|
268 |
+
|
269 |
+
# Fork Feature: Acquire median hybrid f0 estimation calculation
|
270 |
+
def get_f0_hybrid_computation(
|
271 |
+
self,
|
272 |
+
methods_str,
|
273 |
+
input_audio_path,
|
274 |
+
x,
|
275 |
+
f0_min,
|
276 |
+
f0_max,
|
277 |
+
p_len,
|
278 |
+
filter_radius,
|
279 |
+
crepe_hop_length,
|
280 |
+
time_step,
|
281 |
+
):
|
282 |
+
# Get various f0 methods from input to use in the computation stack
|
283 |
+
methods_str = re.search('hybrid\[(.+)\]', methods_str)
|
284 |
+
if methods_str: # Ensure a match was found
|
285 |
+
methods = [method.strip() for method in methods_str.group(1).split('+')]
|
286 |
+
f0_computation_stack = []
|
287 |
+
|
288 |
+
print("Calculating f0 pitch estimations for methods: %s" % str(methods))
|
289 |
+
x = x.astype(np.float32)
|
290 |
+
x /= np.quantile(np.abs(x), 0.999)
|
291 |
+
# Get f0 calculations for all methods specified
|
292 |
+
for method in methods:
|
293 |
+
f0 = None
|
294 |
+
if method == "pm":
|
295 |
+
f0 = (
|
296 |
+
parselmouth.Sound(x, self.sr)
|
297 |
+
.to_pitch_ac(
|
298 |
+
time_step=time_step / 1000,
|
299 |
+
voicing_threshold=0.6,
|
300 |
+
pitch_floor=f0_min,
|
301 |
+
pitch_ceiling=f0_max,
|
302 |
+
)
|
303 |
+
.selected_array["frequency"]
|
304 |
+
)
|
305 |
+
pad_size = (p_len - len(f0) + 1) // 2
|
306 |
+
if pad_size > 0 or p_len - len(f0) - pad_size > 0:
|
307 |
+
f0 = np.pad(
|
308 |
+
f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant"
|
309 |
+
)
|
310 |
+
elif method == "crepe":
|
311 |
+
f0 = self.get_f0_official_crepe_computation(x, f0_min, f0_max, model="full")
|
312 |
+
f0 = f0[1:]
|
313 |
+
elif method == "crepe-tiny":
|
314 |
+
f0 = self.get_f0_official_crepe_computation(x, f0_min, f0_max, model="tiny")
|
315 |
+
f0 = f0[1:] # Get rid of extra first frame
|
316 |
+
elif method == "mangio-crepe":
|
317 |
+
f0 = self.get_f0_crepe_computation(
|
318 |
+
x, f0_min, f0_max, p_len, crepe_hop_length=crepe_hop_length
|
319 |
+
)
|
320 |
+
elif method == "mangio-crepe-tiny":
|
321 |
+
f0 = self.get_f0_crepe_computation(
|
322 |
+
x, f0_min, f0_max, p_len, crepe_hop_length=crepe_hop_length, model="tiny"
|
323 |
+
)
|
324 |
+
elif method == "harvest":
|
325 |
+
input_audio_path2wav[input_audio_path] = x.astype(np.double)
|
326 |
+
f0 = cache_harvest_f0(input_audio_path, self.sr, f0_max, f0_min, 10)
|
327 |
+
if filter_radius > 2:
|
328 |
+
f0 = signal.medfilt(f0, 3)
|
329 |
+
elif method == "dio":
|
330 |
+
f0, t = pyworld.dio(
|
331 |
+
x.astype(np.double),
|
332 |
+
fs=self.sr,
|
333 |
+
f0_ceil=f0_max,
|
334 |
+
f0_floor=f0_min,
|
335 |
+
frame_period=10,
|
336 |
+
)
|
337 |
+
f0 = pyworld.stonemask(x.astype(np.double), f0, t, self.sr)
|
338 |
+
f0 = signal.medfilt(f0, 3)
|
339 |
+
f0 = f0[1:]
|
340 |
+
elif method == "rmvpe":
|
341 |
+
f0 = self.get_rmvpe(x)
|
342 |
+
f0 = f0[1:]
|
343 |
+
elif method == "fcpe_legacy":
|
344 |
+
f0 = self.get_fcpe(x, f0_min=f0_min, f0_max=f0_max, p_len=p_len)
|
345 |
+
elif method == "fcpe":
|
346 |
+
f0 = self.get_torchfcpe(x, self.sr, f0_min, f0_max, p_len)
|
347 |
+
elif method == "pyin":
|
348 |
+
f0 = self.get_f0_pyin_computation(input_audio_path, f0_min, f0_max)
|
349 |
+
# Push method to the stack
|
350 |
+
f0_computation_stack.append(f0)
|
351 |
+
|
352 |
+
for fc in f0_computation_stack:
|
353 |
+
print(len(fc))
|
354 |
+
|
355 |
+
print("Calculating hybrid median f0 from the stack of: %s" % str(methods))
|
356 |
+
f0_median_hybrid = None
|
357 |
+
if len(f0_computation_stack) == 1:
|
358 |
+
f0_median_hybrid = f0_computation_stack[0]
|
359 |
+
else:
|
360 |
+
f0_median_hybrid = np.nanmedian(f0_computation_stack, axis=0)
|
361 |
+
return f0_median_hybrid
|
362 |
+
|
363 |
+
def get_f0(
|
364 |
+
self,
|
365 |
+
input_audio_path,
|
366 |
+
x,
|
367 |
+
p_len,
|
368 |
+
f0_up_key,
|
369 |
+
f0_method,
|
370 |
+
filter_radius,
|
371 |
+
crepe_hop_length,
|
372 |
+
f0_autotune,
|
373 |
+
inp_f0=None,
|
374 |
+
f0_min=50,
|
375 |
+
f0_max=1100,
|
376 |
+
):
|
377 |
+
global input_audio_path2wav
|
378 |
+
time_step = self.window / self.sr * 1000
|
379 |
+
f0_min = f0_min
|
380 |
+
f0_max = f0_max
|
381 |
+
f0_mel_min = 1127 * np.log(1 + f0_min / 700)
|
382 |
+
f0_mel_max = 1127 * np.log(1 + f0_max / 700)
|
383 |
+
|
384 |
+
if f0_method == "pm":
|
385 |
+
f0 = (
|
386 |
+
parselmouth.Sound(x, self.sr)
|
387 |
+
.to_pitch_ac(
|
388 |
+
time_step=time_step / 1000,
|
389 |
+
voicing_threshold=0.6,
|
390 |
+
pitch_floor=f0_min,
|
391 |
+
pitch_ceiling=f0_max,
|
392 |
+
)
|
393 |
+
.selected_array["frequency"]
|
394 |
+
)
|
395 |
+
pad_size = (p_len - len(f0) + 1) // 2
|
396 |
+
if pad_size > 0 or p_len - len(f0) - pad_size > 0:
|
397 |
+
f0 = np.pad(
|
398 |
+
f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant"
|
399 |
+
)
|
400 |
+
elif f0_method == "harvest":
|
401 |
+
input_audio_path2wav[input_audio_path] = x.astype(np.double)
|
402 |
+
f0 = cache_harvest_f0(input_audio_path, self.sr, f0_max, f0_min, 10)
|
403 |
+
if filter_radius > 2:
|
404 |
+
f0 = signal.medfilt(f0, 3)
|
405 |
+
elif f0_method == "dio": # Potentially Buggy?
|
406 |
+
f0, t = pyworld.dio(
|
407 |
+
x.astype(np.double),
|
408 |
+
fs=self.sr,
|
409 |
+
f0_ceil=f0_max,
|
410 |
+
f0_floor=f0_min,
|
411 |
+
frame_period=10,
|
412 |
+
)
|
413 |
+
f0 = pyworld.stonemask(x.astype(np.double), f0, t, self.sr)
|
414 |
+
f0 = signal.medfilt(f0, 3)
|
415 |
+
elif f0_method == "crepe":
|
416 |
+
model = "full"
|
417 |
+
# Pick a batch size that doesn't cause memory errors on your gpu
|
418 |
+
batch_size = 512
|
419 |
+
# Compute pitch using first gpu
|
420 |
+
audio = torch.tensor(np.copy(x))[None].float()
|
421 |
+
f0, pd = torchcrepe.predict(
|
422 |
+
audio,
|
423 |
+
self.sr,
|
424 |
+
self.window,
|
425 |
+
f0_min,
|
426 |
+
f0_max,
|
427 |
+
model,
|
428 |
+
batch_size=batch_size,
|
429 |
+
device=self.device,
|
430 |
+
return_periodicity=True,
|
431 |
+
)
|
432 |
+
pd = torchcrepe.filter.median(pd, 3)
|
433 |
+
f0 = torchcrepe.filter.mean(f0, 3)
|
434 |
+
f0[pd < 0.1] = 0
|
435 |
+
f0 = f0[0].cpu().numpy()
|
436 |
+
elif f0_method == "crepe-tiny":
|
437 |
+
f0 = self.get_f0_official_crepe_computation(x, f0_min, f0_max, model="tiny")
|
438 |
+
elif f0_method == "mangio-crepe":
|
439 |
+
f0 = self.get_f0_crepe_computation(
|
440 |
+
x, f0_min, f0_max, p_len, crepe_hop_length=crepe_hop_length
|
441 |
+
)
|
442 |
+
elif f0_method == "mangio-crepe-tiny":
|
443 |
+
f0 = self.get_f0_crepe_computation(
|
444 |
+
x, f0_min, f0_max, p_len, crepe_hop_length=crepe_hop_length, model="tiny"
|
445 |
+
)
|
446 |
+
elif f0_method == "rmvpe":
|
447 |
+
if not hasattr(self, "model_rmvpe"):
|
448 |
+
from lib.infer.infer_libs.rmvpe import RMVPE
|
449 |
+
|
450 |
+
logger.info(
|
451 |
+
f"Loading rmvpe model, {os.environ['rmvpe_model_path']}"
|
452 |
+
)
|
453 |
+
self.model_rmvpe = RMVPE(
|
454 |
+
os.environ["rmvpe_model_path"],
|
455 |
+
is_half=self.is_half,
|
456 |
+
device=self.device,
|
457 |
+
)
|
458 |
+
f0 = self.model_rmvpe.infer_from_audio(x, thred=0.03)
|
459 |
+
|
460 |
+
if "privateuseone" in str(self.device): # clean ortruntime memory
|
461 |
+
del self.model_rmvpe.model
|
462 |
+
del self.model_rmvpe
|
463 |
+
logger.info("Cleaning ortruntime memory")
|
464 |
+
elif f0_method == "rmvpe+":
|
465 |
+
params = {'x': x, 'p_len': p_len, 'f0_up_key': f0_up_key, 'f0_min': f0_min,
|
466 |
+
'f0_max': f0_max, 'time_step': time_step, 'filter_radius': filter_radius,
|
467 |
+
'crepe_hop_length': crepe_hop_length, 'model': "full"
|
468 |
+
}
|
469 |
+
f0 = self.get_pitch_dependant_rmvpe(**params)
|
470 |
+
elif f0_method == "pyin":
|
471 |
+
f0 = self.get_f0_pyin_computation(input_audio_path, f0_min, f0_max)
|
472 |
+
elif f0_method == "fcpe_legacy":
|
473 |
+
f0 = self.get_fcpe(x, f0_min=f0_min, f0_max=f0_max, p_len=p_len)
|
474 |
+
elif f0_method == "fcpe":
|
475 |
+
f0 = self.get_torchfcpe(x, self.sr, f0_min, f0_max, p_len)
|
476 |
+
elif "hybrid" in f0_method:
|
477 |
+
# Perform hybrid median pitch estimation
|
478 |
+
input_audio_path2wav[input_audio_path] = x.astype(np.double)
|
479 |
+
f0 = self.get_f0_hybrid_computation(
|
480 |
+
f0_method,
|
481 |
+
input_audio_path,
|
482 |
+
x,
|
483 |
+
f0_min,
|
484 |
+
f0_max,
|
485 |
+
p_len,
|
486 |
+
filter_radius,
|
487 |
+
crepe_hop_length,
|
488 |
+
time_step,
|
489 |
+
)
|
490 |
+
#print("Autotune:", f0_autotune)
|
491 |
+
if f0_autotune == True:
|
492 |
+
print("Autotune:", f0_autotune)
|
493 |
+
f0 = self.autotune_f0(f0)
|
494 |
+
|
495 |
+
f0 *= pow(2, f0_up_key / 12)
|
496 |
+
# with open("test.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()]))
|
497 |
+
tf0 = self.sr // self.window # 每秒f0点数
|
498 |
+
if inp_f0 is not None:
|
499 |
+
delta_t = np.round(
|
500 |
+
(inp_f0[:, 0].max() - inp_f0[:, 0].min()) * tf0 + 1
|
501 |
+
).astype("int16")
|
502 |
+
replace_f0 = np.interp(
|
503 |
+
list(range(delta_t)), inp_f0[:, 0] * 100, inp_f0[:, 1]
|
504 |
+
)
|
505 |
+
shape = f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)].shape[0]
|
506 |
+
f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)] = replace_f0[
|
507 |
+
:shape
|
508 |
+
]
|
509 |
+
# with open("test_opt.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()]))
|
510 |
+
f0bak = f0.copy()
|
511 |
+
f0_mel = 1127 * np.log(1 + f0 / 700)
|
512 |
+
f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / (
|
513 |
+
f0_mel_max - f0_mel_min
|
514 |
+
) + 1
|
515 |
+
f0_mel[f0_mel <= 1] = 1
|
516 |
+
f0_mel[f0_mel > 255] = 255
|
517 |
+
f0_coarse = np.rint(f0_mel).astype(np.int32)
|
518 |
+
return f0_coarse, f0bak # 1-0
|
519 |
+
|
520 |
+
def vc(
|
521 |
+
self,
|
522 |
+
model,
|
523 |
+
net_g,
|
524 |
+
sid,
|
525 |
+
audio0,
|
526 |
+
pitch,
|
527 |
+
pitchf,
|
528 |
+
times,
|
529 |
+
index,
|
530 |
+
big_npy,
|
531 |
+
index_rate,
|
532 |
+
version,
|
533 |
+
protect,
|
534 |
+
): # ,file_index,file_big_npy
|
535 |
+
feats = torch.from_numpy(audio0)
|
536 |
+
if self.is_half:
|
537 |
+
feats = feats.half()
|
538 |
+
else:
|
539 |
+
feats = feats.float()
|
540 |
+
if feats.dim() == 2: # double channels
|
541 |
+
feats = feats.mean(-1)
|
542 |
+
assert feats.dim() == 1, feats.dim()
|
543 |
+
feats = feats.view(1, -1)
|
544 |
+
padding_mask = torch.BoolTensor(feats.shape).to(self.device).fill_(False)
|
545 |
+
|
546 |
+
inputs = {
|
547 |
+
"source": feats.to(self.device),
|
548 |
+
"padding_mask": padding_mask,
|
549 |
+
"output_layer": 9 if version == "v1" else 12,
|
550 |
+
}
|
551 |
+
t0 = ttime()
|
552 |
+
with torch.no_grad():
|
553 |
+
logits = model.extract_features(**inputs)
|
554 |
+
feats = model.final_proj(logits[0]) if version == "v1" else logits[0]
|
555 |
+
if protect < 0.5 and pitch is not None and pitchf is not None:
|
556 |
+
feats0 = feats.clone()
|
557 |
+
if (
|
558 |
+
not isinstance(index, type(None))
|
559 |
+
and not isinstance(big_npy, type(None))
|
560 |
+
and index_rate != 0
|
561 |
+
):
|
562 |
+
npy = feats[0].cpu().numpy()
|
563 |
+
if self.is_half:
|
564 |
+
npy = npy.astype("float32")
|
565 |
+
|
566 |
+
# _, I = index.search(npy, 1)
|
567 |
+
# npy = big_npy[I.squeeze()]
|
568 |
+
|
569 |
+
score, ix = index.search(npy, k=8)
|
570 |
+
weight = np.square(1 / score)
|
571 |
+
weight /= weight.sum(axis=1, keepdims=True)
|
572 |
+
npy = np.sum(big_npy[ix] * np.expand_dims(weight, axis=2), axis=1)
|
573 |
+
|
574 |
+
if self.is_half:
|
575 |
+
npy = npy.astype("float16")
|
576 |
+
feats = (
|
577 |
+
torch.from_numpy(npy).unsqueeze(0).to(self.device) * index_rate
|
578 |
+
+ (1 - index_rate) * feats
|
579 |
+
)
|
580 |
+
|
581 |
+
feats = F.interpolate(feats.permute(0, 2, 1), scale_factor=2).permute(0, 2, 1)
|
582 |
+
if protect < 0.5 and pitch is not None and pitchf is not None:
|
583 |
+
feats0 = F.interpolate(feats0.permute(0, 2, 1), scale_factor=2).permute(
|
584 |
+
0, 2, 1
|
585 |
+
)
|
586 |
+
t1 = ttime()
|
587 |
+
p_len = audio0.shape[0] // self.window
|
588 |
+
if feats.shape[1] < p_len:
|
589 |
+
p_len = feats.shape[1]
|
590 |
+
if pitch is not None and pitchf is not None:
|
591 |
+
pitch = pitch[:, :p_len]
|
592 |
+
pitchf = pitchf[:, :p_len]
|
593 |
+
|
594 |
+
if protect < 0.5 and pitch is not None and pitchf is not None:
|
595 |
+
pitchff = pitchf.clone()
|
596 |
+
pitchff[pitchf > 0] = 1
|
597 |
+
pitchff[pitchf < 1] = protect
|
598 |
+
pitchff = pitchff.unsqueeze(-1)
|
599 |
+
feats = feats * pitchff + feats0 * (1 - pitchff)
|
600 |
+
feats = feats.to(feats0.dtype)
|
601 |
+
p_len = torch.tensor([p_len], device=self.device).long()
|
602 |
+
with torch.no_grad():
|
603 |
+
hasp = pitch is not None and pitchf is not None
|
604 |
+
arg = (feats, p_len, pitch, pitchf, sid) if hasp else (feats, p_len, sid)
|
605 |
+
audio1 = (net_g.infer(*arg)[0][0, 0]).data.cpu().float().numpy()
|
606 |
+
del hasp, arg
|
607 |
+
del feats, p_len, padding_mask
|
608 |
+
if torch.cuda.is_available():
|
609 |
+
torch.cuda.empty_cache()
|
610 |
+
t2 = ttime()
|
611 |
+
times[0] += t1 - t0
|
612 |
+
times[2] += t2 - t1
|
613 |
+
return audio1
|
614 |
+
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):
|
615 |
+
t = t // window * window
|
616 |
+
if if_f0 == 1:
|
617 |
+
return self.vc(
|
618 |
+
model,
|
619 |
+
net_g,
|
620 |
+
sid,
|
621 |
+
audio_pad[s : t + t_pad_tgt + window],
|
622 |
+
pitch[:, s // window : (t + t_pad_tgt) // window],
|
623 |
+
pitchf[:, s // window : (t + t_pad_tgt) // window],
|
624 |
+
times,
|
625 |
+
index,
|
626 |
+
big_npy,
|
627 |
+
index_rate,
|
628 |
+
version,
|
629 |
+
protect,
|
630 |
+
)[t_pad_tgt : -t_pad_tgt]
|
631 |
+
else:
|
632 |
+
return self.vc(
|
633 |
+
model,
|
634 |
+
net_g,
|
635 |
+
sid,
|
636 |
+
audio_pad[s : t + t_pad_tgt + window],
|
637 |
+
None,
|
638 |
+
None,
|
639 |
+
times,
|
640 |
+
index,
|
641 |
+
big_npy,
|
642 |
+
index_rate,
|
643 |
+
version,
|
644 |
+
protect,
|
645 |
+
)[t_pad_tgt : -t_pad_tgt]
|
646 |
+
|
647 |
+
|
648 |
+
def pipeline(
|
649 |
+
self,
|
650 |
+
model,
|
651 |
+
net_g,
|
652 |
+
sid,
|
653 |
+
audio,
|
654 |
+
input_audio_path,
|
655 |
+
times,
|
656 |
+
f0_up_key,
|
657 |
+
f0_method,
|
658 |
+
file_index,
|
659 |
+
index_rate,
|
660 |
+
if_f0,
|
661 |
+
filter_radius,
|
662 |
+
tgt_sr,
|
663 |
+
resample_sr,
|
664 |
+
rms_mix_rate,
|
665 |
+
version,
|
666 |
+
protect,
|
667 |
+
crepe_hop_length,
|
668 |
+
f0_autotune,
|
669 |
+
f0_min=50,
|
670 |
+
f0_max=1100
|
671 |
+
):
|
672 |
+
if (
|
673 |
+
file_index != ""
|
674 |
+
and isinstance(file_index, str)
|
675 |
+
# and file_big_npy != ""
|
676 |
+
# and os.path.exists(file_big_npy) == True
|
677 |
+
and os.path.exists(file_index)
|
678 |
+
and index_rate != 0
|
679 |
+
):
|
680 |
+
try:
|
681 |
+
index = faiss.read_index(file_index)
|
682 |
+
# big_npy = np.load(file_big_npy)
|
683 |
+
big_npy = index.reconstruct_n(0, index.ntotal)
|
684 |
+
except:
|
685 |
+
traceback.print_exc()
|
686 |
+
index = big_npy = None
|
687 |
+
else:
|
688 |
+
index = big_npy = None
|
689 |
+
audio = signal.filtfilt(bh, ah, audio)
|
690 |
+
audio_pad = np.pad(audio, (self.window // 2, self.window // 2), mode="reflect")
|
691 |
+
opt_ts = []
|
692 |
+
if audio_pad.shape[0] > self.t_max:
|
693 |
+
audio_sum = np.zeros_like(audio)
|
694 |
+
for i in range(self.window):
|
695 |
+
audio_sum += audio_pad[i : i - self.window]
|
696 |
+
for t in range(self.t_center, audio.shape[0], self.t_center):
|
697 |
+
opt_ts.append(
|
698 |
+
t
|
699 |
+
- self.t_query
|
700 |
+
+ np.where(
|
701 |
+
np.abs(audio_sum[t - self.t_query : t + self.t_query])
|
702 |
+
== np.abs(audio_sum[t - self.t_query : t + self.t_query]).min()
|
703 |
+
)[0][0]
|
704 |
+
)
|
705 |
+
s = 0
|
706 |
+
audio_opt = []
|
707 |
+
t = None
|
708 |
+
t1 = ttime()
|
709 |
+
audio_pad = np.pad(audio, (self.t_pad, self.t_pad), mode="reflect")
|
710 |
+
p_len = audio_pad.shape[0] // self.window
|
711 |
+
inp_f0 = None
|
712 |
+
|
713 |
+
sid = torch.tensor(sid, device=self.device).unsqueeze(0).long()
|
714 |
+
pitch, pitchf = None, None
|
715 |
+
if if_f0:
|
716 |
+
pitch, pitchf = self.get_f0(
|
717 |
+
input_audio_path,
|
718 |
+
audio_pad,
|
719 |
+
p_len,
|
720 |
+
f0_up_key,
|
721 |
+
f0_method,
|
722 |
+
filter_radius,
|
723 |
+
crepe_hop_length,
|
724 |
+
f0_autotune,
|
725 |
+
inp_f0,
|
726 |
+
f0_min,
|
727 |
+
f0_max
|
728 |
+
)
|
729 |
+
pitch = pitch[:p_len]
|
730 |
+
pitchf = pitchf[:p_len]
|
731 |
+
if "mps" not in str(self.device) or "xpu" not in str(self.device):
|
732 |
+
pitchf = pitchf.astype(np.float32)
|
733 |
+
pitch = torch.tensor(pitch, device=self.device).unsqueeze(0).long()
|
734 |
+
pitchf = torch.tensor(pitchf, device=self.device).unsqueeze(0).float()
|
735 |
+
t2 = ttime()
|
736 |
+
times[1] += t2 - t1
|
737 |
+
|
738 |
+
with tqdm(total=len(opt_ts), desc="Processing", unit="window") as pbar:
|
739 |
+
for i, t in enumerate(opt_ts):
|
740 |
+
t = t // self.window * self.window
|
741 |
+
start = s
|
742 |
+
end = t + self.t_pad2 + self.window
|
743 |
+
audio_slice = audio_pad[start:end]
|
744 |
+
pitch_slice = pitch[:, start // self.window:end // self.window] if if_f0 else None
|
745 |
+
pitchf_slice = pitchf[:, start // self.window:end // self.window] if if_f0 else None
|
746 |
+
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])
|
747 |
+
s = t
|
748 |
+
pbar.update(1)
|
749 |
+
pbar.refresh()
|
750 |
+
|
751 |
+
audio_slice = audio_pad[t:]
|
752 |
+
pitch_slice = pitch[:, t // self.window:] if if_f0 and t is not None else pitch
|
753 |
+
pitchf_slice = pitchf[:, t // self.window:] if if_f0 and t is not None else pitchf
|
754 |
+
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])
|
755 |
+
|
756 |
+
audio_opt = np.concatenate(audio_opt)
|
757 |
+
if rms_mix_rate != 1:
|
758 |
+
audio_opt = change_rms(audio, 16000, audio_opt, tgt_sr, rms_mix_rate)
|
759 |
+
if tgt_sr != resample_sr >= 16000:
|
760 |
+
audio_opt = librosa.resample(
|
761 |
+
audio_opt, orig_sr=tgt_sr, target_sr=resample_sr
|
762 |
+
)
|
763 |
+
audio_max = np.abs(audio_opt).max() / 0.99
|
764 |
+
max_int16 = 32768
|
765 |
+
if audio_max > 1:
|
766 |
+
max_int16 /= audio_max
|
767 |
+
audio_opt = (audio_opt * max_int16).astype(np.int16)
|
768 |
+
del pitch, pitchf, sid
|
769 |
+
if torch.cuda.is_available():
|
770 |
+
torch.cuda.empty_cache()
|
771 |
+
|
772 |
+
print("Returning completed audio...")
|
773 |
+
return audio_opt
|