Delete gui_v0.py
Browse files
gui_v0.py
DELETED
@@ -1,696 +0,0 @@
|
|
1 |
-
import os, sys, traceback, re
|
2 |
-
|
3 |
-
import json
|
4 |
-
|
5 |
-
now_dir = os.getcwd()
|
6 |
-
sys.path.append(now_dir)
|
7 |
-
from config import Config
|
8 |
-
|
9 |
-
Config = Config()
|
10 |
-
import PySimpleGUI as sg
|
11 |
-
import sounddevice as sd
|
12 |
-
import noisereduce as nr
|
13 |
-
import numpy as np
|
14 |
-
from fairseq import checkpoint_utils
|
15 |
-
import librosa, torch, pyworld, faiss, time, threading
|
16 |
-
import torch.nn.functional as F
|
17 |
-
import torchaudio.transforms as tat
|
18 |
-
import scipy.signal as signal
|
19 |
-
|
20 |
-
|
21 |
-
# import matplotlib.pyplot as plt
|
22 |
-
from lib.infer_pack.models import (
|
23 |
-
SynthesizerTrnMs256NSFsid,
|
24 |
-
SynthesizerTrnMs256NSFsid_nono,
|
25 |
-
SynthesizerTrnMs768NSFsid,
|
26 |
-
SynthesizerTrnMs768NSFsid_nono,
|
27 |
-
)
|
28 |
-
from i18n import I18nAuto
|
29 |
-
|
30 |
-
i18n = I18nAuto()
|
31 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
32 |
-
current_dir = os.getcwd()
|
33 |
-
|
34 |
-
|
35 |
-
class RVC:
|
36 |
-
def __init__(
|
37 |
-
self, key, hubert_path, pth_path, index_path, npy_path, index_rate
|
38 |
-
) -> None:
|
39 |
-
"""
|
40 |
-
初始化
|
41 |
-
"""
|
42 |
-
try:
|
43 |
-
self.f0_up_key = key
|
44 |
-
self.time_step = 160 / 16000 * 1000
|
45 |
-
self.f0_min = 50
|
46 |
-
self.f0_max = 1100
|
47 |
-
self.f0_mel_min = 1127 * np.log(1 + self.f0_min / 700)
|
48 |
-
self.f0_mel_max = 1127 * np.log(1 + self.f0_max / 700)
|
49 |
-
self.sr = 16000
|
50 |
-
self.window = 160
|
51 |
-
if index_rate != 0:
|
52 |
-
self.index = faiss.read_index(index_path)
|
53 |
-
# self.big_npy = np.load(npy_path)
|
54 |
-
self.big_npy = self.index.reconstruct_n(0, self.index.ntotal)
|
55 |
-
print("index search enabled")
|
56 |
-
self.index_rate = index_rate
|
57 |
-
model_path = hubert_path
|
58 |
-
print("load model(s) from {}".format(model_path))
|
59 |
-
models, saved_cfg, task = checkpoint_utils.load_model_ensemble_and_task(
|
60 |
-
[model_path],
|
61 |
-
suffix="",
|
62 |
-
)
|
63 |
-
self.model = models[0]
|
64 |
-
self.model = self.model.to(device)
|
65 |
-
if Config.is_half:
|
66 |
-
self.model = self.model.half()
|
67 |
-
else:
|
68 |
-
self.model = self.model.float()
|
69 |
-
self.model.eval()
|
70 |
-
cpt = torch.load(pth_path, map_location="cpu")
|
71 |
-
self.tgt_sr = cpt["config"][-1]
|
72 |
-
cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] # n_spk
|
73 |
-
self.if_f0 = cpt.get("f0", 1)
|
74 |
-
self.version = cpt.get("version", "v1")
|
75 |
-
if self.version == "v1":
|
76 |
-
if self.if_f0 == 1:
|
77 |
-
self.net_g = SynthesizerTrnMs256NSFsid(
|
78 |
-
*cpt["config"], is_half=Config.is_half
|
79 |
-
)
|
80 |
-
else:
|
81 |
-
self.net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"])
|
82 |
-
elif self.version == "v2":
|
83 |
-
if self.if_f0 == 1:
|
84 |
-
self.net_g = SynthesizerTrnMs768NSFsid(
|
85 |
-
*cpt["config"], is_half=Config.is_half
|
86 |
-
)
|
87 |
-
else:
|
88 |
-
self.net_g = SynthesizerTrnMs768NSFsid_nono(*cpt["config"])
|
89 |
-
del self.net_g.enc_q
|
90 |
-
print(self.net_g.load_state_dict(cpt["weight"], strict=False))
|
91 |
-
self.net_g.eval().to(device)
|
92 |
-
if Config.is_half:
|
93 |
-
self.net_g = self.net_g.half()
|
94 |
-
else:
|
95 |
-
self.net_g = self.net_g.float()
|
96 |
-
except:
|
97 |
-
print(traceback.format_exc())
|
98 |
-
|
99 |
-
def get_f0(self, x, f0_up_key, inp_f0=None):
|
100 |
-
x_pad = 1
|
101 |
-
f0_min = 50
|
102 |
-
f0_max = 1100
|
103 |
-
f0_mel_min = 1127 * np.log(1 + f0_min / 700)
|
104 |
-
f0_mel_max = 1127 * np.log(1 + f0_max / 700)
|
105 |
-
f0, t = pyworld.harvest(
|
106 |
-
x.astype(np.double),
|
107 |
-
fs=self.sr,
|
108 |
-
f0_ceil=f0_max,
|
109 |
-
f0_floor=f0_min,
|
110 |
-
frame_period=10,
|
111 |
-
)
|
112 |
-
f0 = pyworld.stonemask(x.astype(np.double), f0, t, self.sr)
|
113 |
-
f0 = signal.medfilt(f0, 3)
|
114 |
-
f0 *= pow(2, f0_up_key / 12)
|
115 |
-
# with open("test.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()]))
|
116 |
-
tf0 = self.sr // self.window # 每秒f0点数
|
117 |
-
if inp_f0 is not None:
|
118 |
-
delta_t = np.round(
|
119 |
-
(inp_f0[:, 0].max() - inp_f0[:, 0].min()) * tf0 + 1
|
120 |
-
).astype("int16")
|
121 |
-
replace_f0 = np.interp(
|
122 |
-
list(range(delta_t)), inp_f0[:, 0] * 100, inp_f0[:, 1]
|
123 |
-
)
|
124 |
-
shape = f0[x_pad * tf0 : x_pad * tf0 + len(replace_f0)].shape[0]
|
125 |
-
f0[x_pad * tf0 : x_pad * tf0 + len(replace_f0)] = replace_f0[:shape]
|
126 |
-
# with open("test_opt.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()]))
|
127 |
-
f0bak = f0.copy()
|
128 |
-
f0_mel = 1127 * np.log(1 + f0 / 700)
|
129 |
-
f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / (
|
130 |
-
f0_mel_max - f0_mel_min
|
131 |
-
) + 1
|
132 |
-
f0_mel[f0_mel <= 1] = 1
|
133 |
-
f0_mel[f0_mel > 255] = 255
|
134 |
-
f0_coarse = np.rint(f0_mel).astype(np.int)
|
135 |
-
return f0_coarse, f0bak # 1-0
|
136 |
-
|
137 |
-
def infer(self, feats: torch.Tensor) -> np.ndarray:
|
138 |
-
"""
|
139 |
-
推理函数
|
140 |
-
"""
|
141 |
-
audio = feats.clone().cpu().numpy()
|
142 |
-
assert feats.dim() == 1, feats.dim()
|
143 |
-
feats = feats.view(1, -1)
|
144 |
-
padding_mask = torch.BoolTensor(feats.shape).fill_(False)
|
145 |
-
if Config.is_half:
|
146 |
-
feats = feats.half()
|
147 |
-
else:
|
148 |
-
feats = feats.float()
|
149 |
-
inputs = {
|
150 |
-
"source": feats.to(device),
|
151 |
-
"padding_mask": padding_mask.to(device),
|
152 |
-
"output_layer": 9 if self.version == "v1" else 12,
|
153 |
-
}
|
154 |
-
torch.cuda.synchronize()
|
155 |
-
with torch.no_grad():
|
156 |
-
logits = self.model.extract_features(**inputs)
|
157 |
-
feats = (
|
158 |
-
self.model.final_proj(logits[0]) if self.version == "v1" else logits[0]
|
159 |
-
)
|
160 |
-
|
161 |
-
####索引优化
|
162 |
-
try:
|
163 |
-
if (
|
164 |
-
hasattr(self, "index")
|
165 |
-
and hasattr(self, "big_npy")
|
166 |
-
and self.index_rate != 0
|
167 |
-
):
|
168 |
-
npy = feats[0].cpu().numpy().astype("float32")
|
169 |
-
score, ix = self.index.search(npy, k=8)
|
170 |
-
weight = np.square(1 / score)
|
171 |
-
weight /= weight.sum(axis=1, keepdims=True)
|
172 |
-
npy = np.sum(self.big_npy[ix] * np.expand_dims(weight, axis=2), axis=1)
|
173 |
-
if Config.is_half:
|
174 |
-
npy = npy.astype("float16")
|
175 |
-
feats = (
|
176 |
-
torch.from_numpy(npy).unsqueeze(0).to(device) * self.index_rate
|
177 |
-
+ (1 - self.index_rate) * feats
|
178 |
-
)
|
179 |
-
else:
|
180 |
-
print("index search FAIL or disabled")
|
181 |
-
except:
|
182 |
-
traceback.print_exc()
|
183 |
-
print("index search FAIL")
|
184 |
-
feats = F.interpolate(feats.permute(0, 2, 1), scale_factor=2).permute(0, 2, 1)
|
185 |
-
torch.cuda.synchronize()
|
186 |
-
print(feats.shape)
|
187 |
-
if self.if_f0 == 1:
|
188 |
-
pitch, pitchf = self.get_f0(audio, self.f0_up_key)
|
189 |
-
p_len = min(feats.shape[1], 13000, pitch.shape[0]) # 太大了爆显存
|
190 |
-
else:
|
191 |
-
pitch, pitchf = None, None
|
192 |
-
p_len = min(feats.shape[1], 13000) # 太大了爆显存
|
193 |
-
torch.cuda.synchronize()
|
194 |
-
# print(feats.shape,pitch.shape)
|
195 |
-
feats = feats[:, :p_len, :]
|
196 |
-
if self.if_f0 == 1:
|
197 |
-
pitch = pitch[:p_len]
|
198 |
-
pitchf = pitchf[:p_len]
|
199 |
-
pitch = torch.LongTensor(pitch).unsqueeze(0).to(device)
|
200 |
-
pitchf = torch.FloatTensor(pitchf).unsqueeze(0).to(device)
|
201 |
-
p_len = torch.LongTensor([p_len]).to(device)
|
202 |
-
ii = 0 # sid
|
203 |
-
sid = torch.LongTensor([ii]).to(device)
|
204 |
-
with torch.no_grad():
|
205 |
-
if self.if_f0 == 1:
|
206 |
-
infered_audio = (
|
207 |
-
self.net_g.infer(feats, p_len, pitch, pitchf, sid)[0][0, 0]
|
208 |
-
.data.cpu()
|
209 |
-
.float()
|
210 |
-
)
|
211 |
-
else:
|
212 |
-
infered_audio = (
|
213 |
-
self.net_g.infer(feats, p_len, sid)[0][0, 0].data.cpu().float()
|
214 |
-
)
|
215 |
-
torch.cuda.synchronize()
|
216 |
-
return infered_audio
|
217 |
-
|
218 |
-
|
219 |
-
class GUIConfig:
|
220 |
-
def __init__(self) -> None:
|
221 |
-
self.hubert_path: str = ""
|
222 |
-
self.pth_path: str = ""
|
223 |
-
self.index_path: str = ""
|
224 |
-
self.npy_path: str = ""
|
225 |
-
self.pitch: int = 12
|
226 |
-
self.samplerate: int = 44100
|
227 |
-
self.block_time: float = 1.0 # s
|
228 |
-
self.buffer_num: int = 1
|
229 |
-
self.threhold: int = -30
|
230 |
-
self.crossfade_time: float = 0.08
|
231 |
-
self.extra_time: float = 0.04
|
232 |
-
self.I_noise_reduce = False
|
233 |
-
self.O_noise_reduce = False
|
234 |
-
self.index_rate = 0.3
|
235 |
-
|
236 |
-
|
237 |
-
class GUI:
|
238 |
-
def __init__(self) -> None:
|
239 |
-
self.config = GUIConfig()
|
240 |
-
self.flag_vc = False
|
241 |
-
|
242 |
-
self.launcher()
|
243 |
-
|
244 |
-
def load(self):
|
245 |
-
(
|
246 |
-
input_devices,
|
247 |
-
output_devices,
|
248 |
-
input_devices_indices,
|
249 |
-
output_devices_indices,
|
250 |
-
) = self.get_devices()
|
251 |
-
try:
|
252 |
-
with open("values1.json", "r") as j:
|
253 |
-
data = json.load(j)
|
254 |
-
except:
|
255 |
-
with open("values1.json", "w") as j:
|
256 |
-
data = {
|
257 |
-
"pth_path": "",
|
258 |
-
"index_path": "",
|
259 |
-
"sg_input_device": input_devices[
|
260 |
-
input_devices_indices.index(sd.default.device[0])
|
261 |
-
],
|
262 |
-
"sg_output_device": output_devices[
|
263 |
-
output_devices_indices.index(sd.default.device[1])
|
264 |
-
],
|
265 |
-
"threhold": "-45",
|
266 |
-
"pitch": "0",
|
267 |
-
"index_rate": "0",
|
268 |
-
"block_time": "1",
|
269 |
-
"crossfade_length": "0.04",
|
270 |
-
"extra_time": "1",
|
271 |
-
}
|
272 |
-
return data
|
273 |
-
|
274 |
-
def launcher(self):
|
275 |
-
data = self.load()
|
276 |
-
sg.theme("LightBlue3")
|
277 |
-
input_devices, output_devices, _, _ = self.get_devices()
|
278 |
-
layout = [
|
279 |
-
[
|
280 |
-
sg.Frame(
|
281 |
-
title=i18n("加载模型"),
|
282 |
-
layout=[
|
283 |
-
[
|
284 |
-
sg.Input(
|
285 |
-
default_text="hubert_base.pt",
|
286 |
-
key="hubert_path",
|
287 |
-
disabled=True,
|
288 |
-
),
|
289 |
-
sg.FileBrowse(
|
290 |
-
i18n("Hubert模型"),
|
291 |
-
initial_folder=os.path.join(os.getcwd()),
|
292 |
-
file_types=(("pt files", "*.pt"),),
|
293 |
-
),
|
294 |
-
],
|
295 |
-
[
|
296 |
-
sg.Input(
|
297 |
-
default_text=data.get("pth_path", ""),
|
298 |
-
key="pth_path",
|
299 |
-
),
|
300 |
-
sg.FileBrowse(
|
301 |
-
i18n("选择.pth文件"),
|
302 |
-
initial_folder=os.path.join(os.getcwd(), "weights"),
|
303 |
-
file_types=(("weight files", "*.pth"),),
|
304 |
-
),
|
305 |
-
],
|
306 |
-
[
|
307 |
-
sg.Input(
|
308 |
-
default_text=data.get("index_path", ""),
|
309 |
-
key="index_path",
|
310 |
-
),
|
311 |
-
sg.FileBrowse(
|
312 |
-
i18n("选择.index文件"),
|
313 |
-
initial_folder=os.path.join(os.getcwd(), "logs"),
|
314 |
-
file_types=(("index files", "*.index"),),
|
315 |
-
),
|
316 |
-
],
|
317 |
-
[
|
318 |
-
sg.Input(
|
319 |
-
default_text="你不需要填写这个You don't need write this.",
|
320 |
-
key="npy_path",
|
321 |
-
disabled=True,
|
322 |
-
),
|
323 |
-
sg.FileBrowse(
|
324 |
-
i18n("选择.npy文件"),
|
325 |
-
initial_folder=os.path.join(os.getcwd(), "logs"),
|
326 |
-
file_types=(("feature files", "*.npy"),),
|
327 |
-
),
|
328 |
-
],
|
329 |
-
],
|
330 |
-
)
|
331 |
-
],
|
332 |
-
[
|
333 |
-
sg.Frame(
|
334 |
-
layout=[
|
335 |
-
[
|
336 |
-
sg.Text(i18n("输入设备")),
|
337 |
-
sg.Combo(
|
338 |
-
input_devices,
|
339 |
-
key="sg_input_device",
|
340 |
-
default_value=data.get("sg_input_device", ""),
|
341 |
-
),
|
342 |
-
],
|
343 |
-
[
|
344 |
-
sg.Text(i18n("输出设备")),
|
345 |
-
sg.Combo(
|
346 |
-
output_devices,
|
347 |
-
key="sg_output_device",
|
348 |
-
default_value=data.get("sg_output_device", ""),
|
349 |
-
),
|
350 |
-
],
|
351 |
-
],
|
352 |
-
title=i18n("音频设备(请使用同种类驱动)"),
|
353 |
-
)
|
354 |
-
],
|
355 |
-
[
|
356 |
-
sg.Frame(
|
357 |
-
layout=[
|
358 |
-
[
|
359 |
-
sg.Text(i18n("响应阈值")),
|
360 |
-
sg.Slider(
|
361 |
-
range=(-60, 0),
|
362 |
-
key="threhold",
|
363 |
-
resolution=1,
|
364 |
-
orientation="h",
|
365 |
-
default_value=data.get("threhold", ""),
|
366 |
-
),
|
367 |
-
],
|
368 |
-
[
|
369 |
-
sg.Text(i18n("音调设置")),
|
370 |
-
sg.Slider(
|
371 |
-
range=(-24, 24),
|
372 |
-
key="pitch",
|
373 |
-
resolution=1,
|
374 |
-
orientation="h",
|
375 |
-
default_value=data.get("pitch", ""),
|
376 |
-
),
|
377 |
-
],
|
378 |
-
[
|
379 |
-
sg.Text(i18n("Index Rate")),
|
380 |
-
sg.Slider(
|
381 |
-
range=(0.0, 1.0),
|
382 |
-
key="index_rate",
|
383 |
-
resolution=0.01,
|
384 |
-
orientation="h",
|
385 |
-
default_value=data.get("index_rate", ""),
|
386 |
-
),
|
387 |
-
],
|
388 |
-
],
|
389 |
-
title=i18n("常规设置"),
|
390 |
-
),
|
391 |
-
sg.Frame(
|
392 |
-
layout=[
|
393 |
-
[
|
394 |
-
sg.Text(i18n("采样长度")),
|
395 |
-
sg.Slider(
|
396 |
-
range=(0.1, 3.0),
|
397 |
-
key="block_time",
|
398 |
-
resolution=0.1,
|
399 |
-
orientation="h",
|
400 |
-
default_value=data.get("block_time", ""),
|
401 |
-
),
|
402 |
-
],
|
403 |
-
[
|
404 |
-
sg.Text(i18n("淡入淡出长度")),
|
405 |
-
sg.Slider(
|
406 |
-
range=(0.01, 0.15),
|
407 |
-
key="crossfade_length",
|
408 |
-
resolution=0.01,
|
409 |
-
orientation="h",
|
410 |
-
default_value=data.get("crossfade_length", ""),
|
411 |
-
),
|
412 |
-
],
|
413 |
-
[
|
414 |
-
sg.Text(i18n("额外推理时长")),
|
415 |
-
sg.Slider(
|
416 |
-
range=(0.05, 3.00),
|
417 |
-
key="extra_time",
|
418 |
-
resolution=0.01,
|
419 |
-
orientation="h",
|
420 |
-
default_value=data.get("extra_time", ""),
|
421 |
-
),
|
422 |
-
],
|
423 |
-
[
|
424 |
-
sg.Checkbox(i18n("输入降噪"), key="I_noise_reduce"),
|
425 |
-
sg.Checkbox(i18n("输出降噪"), key="O_noise_reduce"),
|
426 |
-
],
|
427 |
-
],
|
428 |
-
title=i18n("性能设置"),
|
429 |
-
),
|
430 |
-
],
|
431 |
-
[
|
432 |
-
sg.Button(i18n("开始音频转换"), key="start_vc"),
|
433 |
-
sg.Button(i18n("停止音频转换"), key="stop_vc"),
|
434 |
-
sg.Text(i18n("推理时间(ms):")),
|
435 |
-
sg.Text("0", key="infer_time"),
|
436 |
-
],
|
437 |
-
]
|
438 |
-
self.window = sg.Window("RVC - GUI", layout=layout)
|
439 |
-
self.event_handler()
|
440 |
-
|
441 |
-
def event_handler(self):
|
442 |
-
while True:
|
443 |
-
event, values = self.window.read()
|
444 |
-
if event == sg.WINDOW_CLOSED:
|
445 |
-
self.flag_vc = False
|
446 |
-
exit()
|
447 |
-
if event == "start_vc" and self.flag_vc == False:
|
448 |
-
if self.set_values(values) == True:
|
449 |
-
print("using_cuda:" + str(torch.cuda.is_available()))
|
450 |
-
self.start_vc()
|
451 |
-
settings = {
|
452 |
-
"pth_path": values["pth_path"],
|
453 |
-
"index_path": values["index_path"],
|
454 |
-
"sg_input_device": values["sg_input_device"],
|
455 |
-
"sg_output_device": values["sg_output_device"],
|
456 |
-
"threhold": values["threhold"],
|
457 |
-
"pitch": values["pitch"],
|
458 |
-
"index_rate": values["index_rate"],
|
459 |
-
"block_time": values["block_time"],
|
460 |
-
"crossfade_length": values["crossfade_length"],
|
461 |
-
"extra_time": values["extra_time"],
|
462 |
-
}
|
463 |
-
with open("values1.json", "w") as j:
|
464 |
-
json.dump(settings, j)
|
465 |
-
if event == "stop_vc" and self.flag_vc == True:
|
466 |
-
self.flag_vc = False
|
467 |
-
|
468 |
-
def set_values(self, values):
|
469 |
-
if len(values["pth_path"].strip()) == 0:
|
470 |
-
sg.popup(i18n("请选择pth文件"))
|
471 |
-
return False
|
472 |
-
if len(values["index_path"].strip()) == 0:
|
473 |
-
sg.popup(i18n("请选择index文件"))
|
474 |
-
return False
|
475 |
-
pattern = re.compile("[^\x00-\x7F]+")
|
476 |
-
if pattern.findall(values["hubert_path"]):
|
477 |
-
sg.popup(i18n("hubert模型路径不可包含中文"))
|
478 |
-
return False
|
479 |
-
if pattern.findall(values["pth_path"]):
|
480 |
-
sg.popup(i18n("pth文件路径不可包含中文"))
|
481 |
-
return False
|
482 |
-
if pattern.findall(values["index_path"]):
|
483 |
-
sg.popup(i18n("index文件路径不可包含中文"))
|
484 |
-
return False
|
485 |
-
self.set_devices(values["sg_input_device"], values["sg_output_device"])
|
486 |
-
self.config.hubert_path = os.path.join(current_dir, "hubert_base.pt")
|
487 |
-
self.config.pth_path = values["pth_path"]
|
488 |
-
self.config.index_path = values["index_path"]
|
489 |
-
self.config.npy_path = values["npy_path"]
|
490 |
-
self.config.threhold = values["threhold"]
|
491 |
-
self.config.pitch = values["pitch"]
|
492 |
-
self.config.block_time = values["block_time"]
|
493 |
-
self.config.crossfade_time = values["crossfade_length"]
|
494 |
-
self.config.extra_time = values["extra_time"]
|
495 |
-
self.config.I_noise_reduce = values["I_noise_reduce"]
|
496 |
-
self.config.O_noise_reduce = values["O_noise_reduce"]
|
497 |
-
self.config.index_rate = values["index_rate"]
|
498 |
-
return True
|
499 |
-
|
500 |
-
def start_vc(self):
|
501 |
-
torch.cuda.empty_cache()
|
502 |
-
self.flag_vc = True
|
503 |
-
self.block_frame = int(self.config.block_time * self.config.samplerate)
|
504 |
-
self.crossfade_frame = int(self.config.crossfade_time * self.config.samplerate)
|
505 |
-
self.sola_search_frame = int(0.012 * self.config.samplerate)
|
506 |
-
self.delay_frame = int(0.01 * self.config.samplerate) # 往前预留0.02s
|
507 |
-
self.extra_frame = int(self.config.extra_time * self.config.samplerate)
|
508 |
-
self.rvc = None
|
509 |
-
self.rvc = RVC(
|
510 |
-
self.config.pitch,
|
511 |
-
self.config.hubert_path,
|
512 |
-
self.config.pth_path,
|
513 |
-
self.config.index_path,
|
514 |
-
self.config.npy_path,
|
515 |
-
self.config.index_rate,
|
516 |
-
)
|
517 |
-
self.input_wav: np.ndarray = np.zeros(
|
518 |
-
self.extra_frame
|
519 |
-
+ self.crossfade_frame
|
520 |
-
+ self.sola_search_frame
|
521 |
-
+ self.block_frame,
|
522 |
-
dtype="float32",
|
523 |
-
)
|
524 |
-
self.output_wav: torch.Tensor = torch.zeros(
|
525 |
-
self.block_frame, device=device, dtype=torch.float32
|
526 |
-
)
|
527 |
-
self.sola_buffer: torch.Tensor = torch.zeros(
|
528 |
-
self.crossfade_frame, device=device, dtype=torch.float32
|
529 |
-
)
|
530 |
-
self.fade_in_window: torch.Tensor = torch.linspace(
|
531 |
-
0.0, 1.0, steps=self.crossfade_frame, device=device, dtype=torch.float32
|
532 |
-
)
|
533 |
-
self.fade_out_window: torch.Tensor = 1 - self.fade_in_window
|
534 |
-
self.resampler1 = tat.Resample(
|
535 |
-
orig_freq=self.config.samplerate, new_freq=16000, dtype=torch.float32
|
536 |
-
)
|
537 |
-
self.resampler2 = tat.Resample(
|
538 |
-
orig_freq=self.rvc.tgt_sr,
|
539 |
-
new_freq=self.config.samplerate,
|
540 |
-
dtype=torch.float32,
|
541 |
-
)
|
542 |
-
thread_vc = threading.Thread(target=self.soundinput)
|
543 |
-
thread_vc.start()
|
544 |
-
|
545 |
-
def soundinput(self):
|
546 |
-
"""
|
547 |
-
接受音频输入
|
548 |
-
"""
|
549 |
-
with sd.Stream(
|
550 |
-
channels=2,
|
551 |
-
callback=self.audio_callback,
|
552 |
-
blocksize=self.block_frame,
|
553 |
-
samplerate=self.config.samplerate,
|
554 |
-
dtype="float32",
|
555 |
-
):
|
556 |
-
while self.flag_vc:
|
557 |
-
time.sleep(self.config.block_time)
|
558 |
-
print("Audio block passed.")
|
559 |
-
print("ENDing VC")
|
560 |
-
|
561 |
-
def audio_callback(
|
562 |
-
self, indata: np.ndarray, outdata: np.ndarray, frames, times, status
|
563 |
-
):
|
564 |
-
"""
|
565 |
-
音频处理
|
566 |
-
"""
|
567 |
-
start_time = time.perf_counter()
|
568 |
-
indata = librosa.to_mono(indata.T)
|
569 |
-
if self.config.I_noise_reduce:
|
570 |
-
indata[:] = nr.reduce_noise(y=indata, sr=self.config.samplerate)
|
571 |
-
|
572 |
-
"""noise gate"""
|
573 |
-
frame_length = 2048
|
574 |
-
hop_length = 1024
|
575 |
-
rms = librosa.feature.rms(
|
576 |
-
y=indata, frame_length=frame_length, hop_length=hop_length
|
577 |
-
)
|
578 |
-
db_threhold = librosa.amplitude_to_db(rms, ref=1.0)[0] < self.config.threhold
|
579 |
-
# print(rms.shape,db.shape,db)
|
580 |
-
for i in range(db_threhold.shape[0]):
|
581 |
-
if db_threhold[i]:
|
582 |
-
indata[i * hop_length : (i + 1) * hop_length] = 0
|
583 |
-
self.input_wav[:] = np.append(self.input_wav[self.block_frame :], indata)
|
584 |
-
|
585 |
-
# infer
|
586 |
-
print("input_wav:" + str(self.input_wav.shape))
|
587 |
-
# print('infered_wav:'+str(infer_wav.shape))
|
588 |
-
infer_wav: torch.Tensor = self.resampler2(
|
589 |
-
self.rvc.infer(self.resampler1(torch.from_numpy(self.input_wav)))
|
590 |
-
)[-self.crossfade_frame - self.sola_search_frame - self.block_frame :].to(
|
591 |
-
device
|
592 |
-
)
|
593 |
-
print("infer_wav:" + str(infer_wav.shape))
|
594 |
-
|
595 |
-
# SOLA algorithm from https://github.com/yxlllc/DDSP-SVC
|
596 |
-
cor_nom = F.conv1d(
|
597 |
-
infer_wav[None, None, : self.crossfade_frame + self.sola_search_frame],
|
598 |
-
self.sola_buffer[None, None, :],
|
599 |
-
)
|
600 |
-
cor_den = torch.sqrt(
|
601 |
-
F.conv1d(
|
602 |
-
infer_wav[None, None, : self.crossfade_frame + self.sola_search_frame]
|
603 |
-
** 2,
|
604 |
-
torch.ones(1, 1, self.crossfade_frame, device=device),
|
605 |
-
)
|
606 |
-
+ 1e-8
|
607 |
-
)
|
608 |
-
sola_offset = torch.argmax(cor_nom[0, 0] / cor_den[0, 0])
|
609 |
-
print("sola offset: " + str(int(sola_offset)))
|
610 |
-
|
611 |
-
# crossfade
|
612 |
-
self.output_wav[:] = infer_wav[sola_offset : sola_offset + self.block_frame]
|
613 |
-
self.output_wav[: self.crossfade_frame] *= self.fade_in_window
|
614 |
-
self.output_wav[: self.crossfade_frame] += self.sola_buffer[:]
|
615 |
-
if sola_offset < self.sola_search_frame:
|
616 |
-
self.sola_buffer[:] = (
|
617 |
-
infer_wav[
|
618 |
-
-self.sola_search_frame
|
619 |
-
- self.crossfade_frame
|
620 |
-
+ sola_offset : -self.sola_search_frame
|
621 |
-
+ sola_offset
|
622 |
-
]
|
623 |
-
* self.fade_out_window
|
624 |
-
)
|
625 |
-
else:
|
626 |
-
self.sola_buffer[:] = (
|
627 |
-
infer_wav[-self.crossfade_frame :] * self.fade_out_window
|
628 |
-
)
|
629 |
-
|
630 |
-
if self.config.O_noise_reduce:
|
631 |
-
outdata[:] = np.tile(
|
632 |
-
nr.reduce_noise(
|
633 |
-
y=self.output_wav[:].cpu().numpy(), sr=self.config.samplerate
|
634 |
-
),
|
635 |
-
(2, 1),
|
636 |
-
).T
|
637 |
-
else:
|
638 |
-
outdata[:] = self.output_wav[:].repeat(2, 1).t().cpu().numpy()
|
639 |
-
total_time = time.perf_counter() - start_time
|
640 |
-
self.window["infer_time"].update(int(total_time * 1000))
|
641 |
-
print("infer time:" + str(total_time))
|
642 |
-
|
643 |
-
def get_devices(self, update: bool = True):
|
644 |
-
"""获取设备列表"""
|
645 |
-
if update:
|
646 |
-
sd._terminate()
|
647 |
-
sd._initialize()
|
648 |
-
devices = sd.query_devices()
|
649 |
-
hostapis = sd.query_hostapis()
|
650 |
-
for hostapi in hostapis:
|
651 |
-
for device_idx in hostapi["devices"]:
|
652 |
-
devices[device_idx]["hostapi_name"] = hostapi["name"]
|
653 |
-
input_devices = [
|
654 |
-
f"{d['name']} ({d['hostapi_name']})"
|
655 |
-
for d in devices
|
656 |
-
if d["max_input_channels"] > 0
|
657 |
-
]
|
658 |
-
output_devices = [
|
659 |
-
f"{d['name']} ({d['hostapi_name']})"
|
660 |
-
for d in devices
|
661 |
-
if d["max_output_channels"] > 0
|
662 |
-
]
|
663 |
-
input_devices_indices = [
|
664 |
-
d["index"] if "index" in d else d["name"]
|
665 |
-
for d in devices
|
666 |
-
if d["max_input_channels"] > 0
|
667 |
-
]
|
668 |
-
output_devices_indices = [
|
669 |
-
d["index"] if "index" in d else d["name"]
|
670 |
-
for d in devices
|
671 |
-
if d["max_output_channels"] > 0
|
672 |
-
]
|
673 |
-
return (
|
674 |
-
input_devices,
|
675 |
-
output_devices,
|
676 |
-
input_devices_indices,
|
677 |
-
output_devices_indices,
|
678 |
-
)
|
679 |
-
|
680 |
-
def set_devices(self, input_device, output_device):
|
681 |
-
"""设置输出设备"""
|
682 |
-
(
|
683 |
-
input_devices,
|
684 |
-
output_devices,
|
685 |
-
input_device_indices,
|
686 |
-
output_device_indices,
|
687 |
-
) = self.get_devices()
|
688 |
-
sd.default.device[0] = input_device_indices[input_devices.index(input_device)]
|
689 |
-
sd.default.device[1] = output_device_indices[
|
690 |
-
output_devices.index(output_device)
|
691 |
-
]
|
692 |
-
print("input device:" + str(sd.default.device[0]) + ":" + str(input_device))
|
693 |
-
print("output device:" + str(sd.default.device[1]) + ":" + str(output_device))
|
694 |
-
|
695 |
-
|
696 |
-
gui = GUI()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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