ChazzyG/Retrieval-based-Voice-Conversion-WebUI
0
1import os, sys2 3now_dir = os.getcwd()4sys.path.append(now_dir)5import PySimpleGUI as sg6import sounddevice as sd7import noisereduce as nr8import numpy as np9from fairseq import checkpoint_utils10import librosa, torch, pyworld, faiss, time, threading11import torch.nn.functional as F12import torchaudio.transforms as tat13import scipy.signal as signal14 15# import matplotlib.pyplot as plt16from infer_pack.models import SynthesizerTrnMs256NSFsid, SynthesizerTrnMs256NSFsid_nono17from i18n import I18nAuto18 19i18n = I18nAuto()20device = torch.device("cuda" if torch.cuda.is_available() else "cpu")21 22 23class RVC:24 def __init__(25 self, key, hubert_path, pth_path, index_path, npy_path, index_rate26 ) -> None:27 """28 初始化29 """30 try:31 self.f0_up_key = key32 self.time_step = 160 / 16000 * 100033 self.f0_min = 5034 self.f0_max = 110035 self.f0_mel_min = 1127 * np.log(1 + self.f0_min / 700)36 self.f0_mel_max = 1127 * np.log(1 + self.f0_max / 700)37 self.sr = 1600038 self.window = 16039 if index_rate != 0:40 self.index = faiss.read_index(index_path)41 # self.big_npy = np.load(npy_path)42 self.big_npy = index.reconstruct_n(0, self.index.ntotal)43 print("index search enabled")44 self.index_rate = index_rate45 model_path = hubert_path46 print("load model(s) from {}".format(model_path))47 models, saved_cfg, task = checkpoint_utils.load_model_ensemble_and_task(48 [model_path],49 suffix="",50 )51 self.model = models[0]52 self.model = self.model.to(device)53 self.model = self.model.half()54 self.model.eval()55 cpt = torch.load(pth_path, map_location="cpu")56 self.tgt_sr = cpt["config"][-1]57 cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] # n_spk58 self.if_f0 = cpt.get("f0", 1)59 if self.if_f0 == 1:60 self.net_g = SynthesizerTrnMs256NSFsid(*cpt["config"], is_half=True)61 else:62 self.net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"])63 del self.net_g.enc_q64 print(self.net_g.load_state_dict(cpt["weight"], strict=False))65 self.net_g.eval().to(device)66 self.net_g.half()67 except Exception as e:68 print(e)69 70 def get_f0(self, x, f0_up_key, inp_f0=None):71 x_pad = 172 f0_min = 5073 f0_max = 110074 f0_mel_min = 1127 * np.log(1 + f0_min / 700)75 f0_mel_max = 1127 * np.log(1 + f0_max / 700)76 f0, t = pyworld.harvest(77 x.astype(np.double),78 fs=self.sr,79 f0_ceil=f0_max,80 f0_floor=f0_min,81 frame_period=10,82 )83 f0 = pyworld.stonemask(x.astype(np.double), f0, t, self.sr)84 f0 = signal.medfilt(f0, 3)85 f0 *= pow(2, f0_up_key / 12)86 # with open("test.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()]))87 tf0 = self.sr // self.window # 每秒f0点数88 if inp_f0 is not None:89 delta_t = np.round(90 (inp_f0[:, 0].max() - inp_f0[:, 0].min()) * tf0 + 191 ).astype("int16")92 replace_f0 = np.interp(93 list(range(delta_t)), inp_f0[:, 0] * 100, inp_f0[:, 1]94 )95 shape = f0[x_pad * tf0 : x_pad * tf0 + len(replace_f0)].shape[0]96 f0[x_pad * tf0 : x_pad * tf0 + len(replace_f0)] = replace_f0[:shape]97 # with open("test_opt.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()]))98 f0bak = f0.copy()99 f0_mel = 1127 * np.log(1 + f0 / 700)100 f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / (101 f0_mel_max - f0_mel_min102 ) + 1103 f0_mel[f0_mel <= 1] = 1104 f0_mel[f0_mel > 255] = 255105 f0_coarse = np.rint(f0_mel).astype(np.int)106 return f0_coarse, f0bak # 1-0107 108 def infer(self, feats: torch.Tensor) -> np.ndarray:109 """110 推理函数111 """112 audio = feats.clone().cpu().numpy()113 assert feats.dim() == 1, feats.dim()114 feats = feats.view(1, -1)115 padding_mask = torch.BoolTensor(feats.shape).fill_(False)116 inputs = {117 "source": feats.half().to(device),118 "padding_mask": padding_mask.to(device),119 "output_layer": 9, # layer 9120 }121 torch.cuda.synchronize()122 with torch.no_grad():123 logits = self.model.extract_features(**inputs)124 feats = self.model.final_proj(logits[0])125 126 ####索引优化127 if hasattr(self, "index") and hasattr(self, "big_npy") and self.index_rate != 0:128 npy = feats[0].cpu().numpy().astype("float32")129 130 # _, I = self.index.search(npy, 1)131 # npy = self.big_npy[I.squeeze()].astype("float16")132 133 score, ix = index.search(npy, k=8)134 weight = np.square(1 / score)135 weight /= weight.sum(axis=1, keepdims=True)136 npy = np.sum(big_npy[ix] * np.expand_dims(weight, axis=2), axis=1).astype(137 "float16"138 )139 140 feats = (141 torch.from_numpy(npy).unsqueeze(0).to(device) * self.index_rate142 + (1 - self.index_rate) * feats143 )144 else:145 print("index search FAIL or disabled")146 147 feats = F.interpolate(feats.permute(0, 2, 1), scale_factor=2).permute(0, 2, 1)148 torch.cuda.synchronize()149 print(feats.shape)150 if self.if_f0 == 1:151 pitch, pitchf = self.get_f0(audio, self.f0_up_key)152 p_len = min(feats.shape[1], 13000, pitch.shape[0]) # 太大了爆显存153 else:154 pitch, pitchf = None, None155 p_len = min(feats.shape[1], 13000) # 太大了爆显存156 torch.cuda.synchronize()157 # print(feats.shape,pitch.shape)158 feats = feats[:, :p_len, :]159 if self.if_f0 == 1:160 pitch = pitch[:p_len]161 pitchf = pitchf[:p_len]162 pitch = torch.LongTensor(pitch).unsqueeze(0).to(device)163 pitchf = torch.FloatTensor(pitchf).unsqueeze(0).to(device)164 p_len = torch.LongTensor([p_len]).to(device)165 ii = 0 # sid166 sid = torch.LongTensor([ii]).to(device)167 with torch.no_grad():168 if self.if_f0 == 1:169 infered_audio = (170 self.net_g.infer(feats, p_len, pitch, pitchf, sid)[0][0, 0]171 .data.cpu()172 .float()173 )174 else:175 infered_audio = (176 self.net_g.infer(feats, p_len, sid)[0][0, 0].data.cpu().float()177 )178 torch.cuda.synchronize()179 return infered_audio180 181 182class Config:183 def __init__(self) -> None:184 self.hubert_path: str = ""185 self.pth_path: str = ""186 self.index_path: str = ""187 self.npy_path: str = ""188 self.pitch: int = 12189 self.samplerate: int = 44100190 self.block_time: float = 1.0 # s191 self.buffer_num: int = 1192 self.threhold: int = -30193 self.crossfade_time: float = 0.08194 self.extra_time: float = 0.04195 self.I_noise_reduce = False196 self.O_noise_reduce = False197 self.index_rate = 0.3198 199 200class GUI:201 def __init__(self) -> None:202 self.config = Config()203 self.flag_vc = False204 205 self.launcher()206 207 def launcher(self):208 sg.theme("LightBlue3")209 input_devices, output_devices, _, _ = self.get_devices()210 layout = [211 [212 sg.Frame(213 title=i18n("加载模型"),214 layout=[215 [216 sg.Input(default_text="hubert_base.pt", key="hubert_path"),217 sg.FileBrowse(i18n("Hubert模型")),218 ],219 [220 sg.Input(default_text="TEMP\\atri.pth", key="pth_path"),221 sg.FileBrowse(i18n("选择.pth文件")),222 ],223 [224 sg.Input(225 default_text="TEMP\\added_IVF512_Flat_atri_baseline_src_feat.index",226 key="index_path",227 ),228 sg.FileBrowse(i18n("选择.index文件")),229 ],230 [231 sg.Input(232 default_text="你不需要填写这个You don't need write this.",233 key="npy_path",234 ),235 sg.FileBrowse(i18n("选择.npy文件")),236 ],237 ],238 )239 ],240 [241 sg.Frame(242 layout=[243 [244 sg.Text(i18n("输入设备")),245 sg.Combo(246 input_devices,247 key="sg_input_device",248 default_value=input_devices[sd.default.device[0]],249 ),250 ],251 [252 sg.Text(i18n("输出设备")),253 sg.Combo(254 output_devices,255 key="sg_output_device",256 default_value=output_devices[sd.default.device[1]],257 ),258 ],259 ],260 title=i18n("音频设备(请使用同种类驱动)"),261 )262 ],263 [264 sg.Frame(265 layout=[266 [267 sg.Text(i18n("响应阈值")),268 sg.Slider(269 range=(-60, 0),270 key="threhold",271 resolution=1,272 orientation="h",273 default_value=-30,274 ),275 ],276 [277 sg.Text(i18n("音调设置")),278 sg.Slider(279 range=(-24, 24),280 key="pitch",281 resolution=1,282 orientation="h",283 default_value=12,284 ),285 ],286 [287 sg.Text(i18n("Index Rate")),288 sg.Slider(289 range=(0.0, 1.0),290 key="index_rate",291 resolution=0.01,292 orientation="h",293 default_value=0.5,294 ),295 ],296 ],297 title=i18n("常规设置"),298 ),299 sg.Frame(300 layout=[301 [302 sg.Text(i18n("采样长度")),303 sg.Slider(304 range=(0.1, 3.0),305 key="block_time",306 resolution=0.1,307 orientation="h",308 default_value=1.0,309 ),310 ],311 [312 sg.Text(i18n("淡入淡出长度")),313 sg.Slider(314 range=(0.01, 0.15),315 key="crossfade_length",316 resolution=0.01,317 orientation="h",318 default_value=0.08,319 ),320 ],321 [322 sg.Text(i18n("额外推理时长")),323 sg.Slider(324 range=(0.05, 3.00),325 key="extra_time",326 resolution=0.01,327 orientation="h",328 default_value=0.05,329 ),330 ],331 [332 sg.Checkbox(i18n("输入降噪"), key="I_noise_reduce"),333 sg.Checkbox(i18n("输出降噪"), key="O_noise_reduce"),334 ],335 ],336 title=i18n("性能设置"),337 ),338 ],339 [340 sg.Button(i18n("开始音频转换"), key="start_vc"),341 sg.Button(i18n("停止音频转换"), key="stop_vc"),342 sg.Text(i18n("推理时间(ms):")),343 sg.Text("0", key="infer_time"),344 ],345 ]346 347 self.window = sg.Window("RVC - GUI", layout=layout)348 self.event_handler()349 350 def event_handler(self):351 while True:352 event, values = self.window.read()353 if event == sg.WINDOW_CLOSED:354 self.flag_vc = False355 exit()356 if event == "start_vc" and self.flag_vc == False:357 self.set_values(values)358 print(str(self.config.__dict__))359 print("using_cuda:" + str(torch.cuda.is_available()))360 self.start_vc()361 if event == "stop_vc" and self.flag_vc == True:362 self.flag_vc = False363 364 def set_values(self, values):365 self.set_devices(values["sg_input_device"], values["sg_output_device"])366 self.config.hubert_path = values["hubert_path"]367 self.config.pth_path = values["pth_path"]368 self.config.index_path = values["index_path"]369 self.config.npy_path = values["npy_path"]370 self.config.threhold = values["threhold"]371 self.config.pitch = values["pitch"]372 self.config.block_time = values["block_time"]373 self.config.crossfade_time = values["crossfade_length"]374 self.config.extra_time = values["extra_time"]375 self.config.I_noise_reduce = values["I_noise_reduce"]376 self.config.O_noise_reduce = values["O_noise_reduce"]377 self.config.index_rate = values["index_rate"]378 379 def start_vc(self):380 torch.cuda.empty_cache()381 self.flag_vc = True382 self.block_frame = int(self.config.block_time * self.config.samplerate)383 self.crossfade_frame = int(self.config.crossfade_time * self.config.samplerate)384 self.sola_search_frame = int(0.012 * self.config.samplerate)385 self.delay_frame = int(0.01 * self.config.samplerate) # 往前预留0.02s386 self.extra_frame = int(self.config.extra_time * self.config.samplerate)387 self.rvc = None388 self.rvc = RVC(389 self.config.pitch,390 self.config.hubert_path,391 self.config.pth_path,392 self.config.index_path,393 self.config.npy_path,394 self.config.index_rate,395 )396 self.input_wav: np.ndarray = np.zeros(397 self.extra_frame398 + self.crossfade_frame399 + self.sola_search_frame400 + self.block_frame,401 dtype="float32",402 )403 self.output_wav: torch.Tensor = torch.zeros(404 self.block_frame, device=device, dtype=torch.float32405 )406 self.sola_buffer: torch.Tensor = torch.zeros(407 self.crossfade_frame, device=device, dtype=torch.float32408 )409 self.fade_in_window: torch.Tensor = torch.linspace(410 0.0, 1.0, steps=self.crossfade_frame, device=device, dtype=torch.float32411 )412 self.fade_out_window: torch.Tensor = 1 - self.fade_in_window413 self.resampler1 = tat.Resample(414 orig_freq=self.config.samplerate, new_freq=16000, dtype=torch.float32415 )416 self.resampler2 = tat.Resample(417 orig_freq=self.rvc.tgt_sr,418 new_freq=self.config.samplerate,419 dtype=torch.float32,420 )421 thread_vc = threading.Thread(target=self.soundinput)422 thread_vc.start()423 424 def soundinput(self):425 """426 接受音频输入427 """428 with sd.Stream(429 callback=self.audio_callback,430 blocksize=self.block_frame,431 samplerate=self.config.samplerate,432 dtype="float32",433 ):434 while self.flag_vc:435 time.sleep(self.config.block_time)436 print("Audio block passed.")437 print("ENDing VC")438 439 def audio_callback(440 self, indata: np.ndarray, outdata: np.ndarray, frames, times, status441 ):442 """443 音频处理444 """445 start_time = time.perf_counter()446 indata = librosa.to_mono(indata.T)447 if self.config.I_noise_reduce:448 indata[:] = nr.reduce_noise(y=indata, sr=self.config.samplerate)449 450 """noise gate"""451 frame_length = 2048452 hop_length = 1024453 rms = librosa.feature.rms(454 y=indata, frame_length=frame_length, hop_length=hop_length455 )456 db_threhold = librosa.amplitude_to_db(rms, ref=1.0)[0] < self.config.threhold457 # print(rms.shape,db.shape,db)458 for i in range(db_threhold.shape[0]):459 if db_threhold[i]:460 indata[i * hop_length : (i + 1) * hop_length] = 0461 self.input_wav[:] = np.append(self.input_wav[self.block_frame :], indata)462 463 # infer464 print("input_wav:" + str(self.input_wav.shape))465 # print('infered_wav:'+str(infer_wav.shape))466 infer_wav: torch.Tensor = self.resampler2(467 self.rvc.infer(self.resampler1(torch.from_numpy(self.input_wav)))468 )[-self.crossfade_frame - self.sola_search_frame - self.block_frame :].to(469 device470 )471 print("infer_wav:" + str(infer_wav.shape))472 473 # SOLA algorithm from https://github.com/yxlllc/DDSP-SVC474 cor_nom = F.conv1d(475 infer_wav[None, None, : self.crossfade_frame + self.sola_search_frame],476 self.sola_buffer[None, None, :],477 )478 cor_den = torch.sqrt(479 F.conv1d(480 infer_wav[None, None, : self.crossfade_frame + self.sola_search_frame]481 ** 2,482 torch.ones(1, 1, self.crossfade_frame, device=device),483 )484 + 1e-8485 )486 sola_offset = torch.argmax(cor_nom[0, 0] / cor_den[0, 0])487 print("sola offset: " + str(int(sola_offset)))488 489 # crossfade490 self.output_wav[:] = infer_wav[sola_offset : sola_offset + self.block_frame]491 self.output_wav[: self.crossfade_frame] *= self.fade_in_window492 self.output_wav[: self.crossfade_frame] += self.sola_buffer[:]493 if sola_offset < self.sola_search_frame:494 self.sola_buffer[:] = (495 infer_wav[496 -self.sola_search_frame497 - self.crossfade_frame498 + sola_offset : -self.sola_search_frame499 + sola_offset500 ]501 * self.fade_out_window502 )503 else:504 self.sola_buffer[:] = (505 infer_wav[-self.crossfade_frame :] * self.fade_out_window506 )507 508 if self.config.O_noise_reduce:509 outdata[:] = np.tile(510 nr.reduce_noise(511 y=self.output_wav[:].cpu().numpy(), sr=self.config.samplerate512 ),513 (2, 1),514 ).T515 else:516 outdata[:] = self.output_wav[:].repeat(2, 1).t().cpu().numpy()517 total_time = time.perf_counter() - start_time518 self.window["infer_time"].update(int(total_time * 1000))519 print("infer time:" + str(total_time))520 521 def get_devices(self, update: bool = True):522 """获取设备列表"""523 if update:524 sd._terminate()525 sd._initialize()526 devices = sd.query_devices()527 hostapis = sd.query_hostapis()528 for hostapi in hostapis:529 for device_idx in hostapi["devices"]:530 devices[device_idx]["hostapi_name"] = hostapi["name"]531 input_devices = [532 f"{d['name']} ({d['hostapi_name']})"533 for d in devices534 if d["max_input_channels"] > 0535 ]536 output_devices = [537 f"{d['name']} ({d['hostapi_name']})"538 for d in devices539 if d["max_output_channels"] > 0540 ]541 input_devices_indices = [542 d["index"] for d in devices if d["max_input_channels"] > 0543 ]544 output_devices_indices = [545 d["index"] for d in devices if d["max_output_channels"] > 0546 ]547 return (548 input_devices,549 output_devices,550 input_devices_indices,551 output_devices_indices,552 )553 554 def set_devices(self, input_device, output_device):555 """设置输出设备"""556 (557 input_devices,558 output_devices,559 input_device_indices,560 output_device_indices,561 ) = self.get_devices()562 sd.default.device[0] = input_device_indices[input_devices.index(input_device)]563 sd.default.device[1] = output_device_indices[564 output_devices.index(output_device)565 ]566 print("input device:" + str(sd.default.device[0]) + ":" + str(input_device))567 print("output device:" + str(sd.default.device[1]) + ":" + str(output_device))568 569 570gui = GUI()571 