Spaces:
Running
Running
Upload 6 files
Browse files- LICENSE +21 -0
- config.py +96 -0
- infer.py +942 -0
- requirements.txt +25 -0
- rmvpe.py +432 -0
- vc_infer_pipeline.py +443 -0
LICENSE
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
MIT License
|
2 |
+
|
3 |
+
Copyright (c) 2023 arkandash
|
4 |
+
|
5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6 |
+
of this software and associated documentation files (the "Software"), to deal
|
7 |
+
in the Software without restriction, including without limitation the rights
|
8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9 |
+
copies of the Software, and to permit persons to whom the Software is
|
10 |
+
furnished to do so, subject to the following conditions:
|
11 |
+
|
12 |
+
The above copyright notice and this permission notice shall be included in all
|
13 |
+
copies or substantial portions of the Software.
|
14 |
+
|
15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21 |
+
SOFTWARE.
|
config.py
ADDED
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import sys
|
3 |
+
import torch
|
4 |
+
from multiprocessing import cpu_count
|
5 |
+
|
6 |
+
class Config:
|
7 |
+
def __init__(self):
|
8 |
+
self.device = "cuda:0"
|
9 |
+
self.is_half = True
|
10 |
+
self.n_cpu = 0
|
11 |
+
self.gpu_name = None
|
12 |
+
self.gpu_mem = None
|
13 |
+
(
|
14 |
+
self.colab,
|
15 |
+
self.api,
|
16 |
+
) = self.arg_parse()
|
17 |
+
self.x_pad, self.x_query, self.x_center, self.x_max = self.device_config()
|
18 |
+
|
19 |
+
@staticmethod
|
20 |
+
def arg_parse() -> tuple:
|
21 |
+
parser = argparse.ArgumentParser()
|
22 |
+
parser.add_argument("--colab", action="store_true", help="Launch in colab")
|
23 |
+
parser.add_argument("--api", action="store_true", help="Launch with api")
|
24 |
+
cmd_opts = parser.parse_args()
|
25 |
+
|
26 |
+
return (
|
27 |
+
cmd_opts.colab,
|
28 |
+
cmd_opts.api
|
29 |
+
)
|
30 |
+
|
31 |
+
# has_mps is only available in nightly pytorch (for now) and MasOS 12.3+.
|
32 |
+
# check `getattr` and try it for compatibility
|
33 |
+
@staticmethod
|
34 |
+
def has_mps() -> bool:
|
35 |
+
if not torch.backends.mps.is_available():
|
36 |
+
return False
|
37 |
+
try:
|
38 |
+
torch.zeros(1).to(torch.device("mps"))
|
39 |
+
return True
|
40 |
+
except Exception:
|
41 |
+
return False
|
42 |
+
|
43 |
+
def device_config(self) -> tuple:
|
44 |
+
if torch.cuda.is_available():
|
45 |
+
i_device = int(self.device.split(":")[-1])
|
46 |
+
self.gpu_name = torch.cuda.get_device_name(i_device)
|
47 |
+
if (
|
48 |
+
("16" in self.gpu_name and "V100" not in self.gpu_name.upper())
|
49 |
+
or "P40" in self.gpu_name.upper()
|
50 |
+
or "1060" in self.gpu_name
|
51 |
+
or "1070" in self.gpu_name
|
52 |
+
or "1080" in self.gpu_name
|
53 |
+
):
|
54 |
+
print("INFO: Found GPU", self.gpu_name, ", force to fp32")
|
55 |
+
self.is_half = False
|
56 |
+
else:
|
57 |
+
print("INFO: Found GPU", self.gpu_name)
|
58 |
+
self.gpu_mem = int(
|
59 |
+
torch.cuda.get_device_properties(i_device).total_memory
|
60 |
+
/ 1024
|
61 |
+
/ 1024
|
62 |
+
/ 1024
|
63 |
+
+ 0.4
|
64 |
+
)
|
65 |
+
elif self.has_mps():
|
66 |
+
print("INFO: No supported Nvidia GPU found, use MPS instead")
|
67 |
+
self.device = "mps"
|
68 |
+
self.is_half = False
|
69 |
+
else:
|
70 |
+
print("INFO: No supported Nvidia GPU found, use CPU instead")
|
71 |
+
self.device = "cpu"
|
72 |
+
self.is_half = False
|
73 |
+
|
74 |
+
if self.n_cpu == 0:
|
75 |
+
self.n_cpu = cpu_count()
|
76 |
+
|
77 |
+
if self.is_half:
|
78 |
+
# 6G显存配置
|
79 |
+
x_pad = 3
|
80 |
+
x_query = 10
|
81 |
+
x_center = 60
|
82 |
+
x_max = 65
|
83 |
+
else:
|
84 |
+
# 5G显存配置
|
85 |
+
x_pad = 1
|
86 |
+
x_query = 6
|
87 |
+
x_center = 38
|
88 |
+
x_max = 41
|
89 |
+
|
90 |
+
if self.gpu_mem != None and self.gpu_mem <= 4:
|
91 |
+
x_pad = 1
|
92 |
+
x_query = 5
|
93 |
+
x_center = 30
|
94 |
+
x_max = 32
|
95 |
+
|
96 |
+
return x_pad, x_query, x_center, x_max
|
infer.py
ADDED
@@ -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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch, os, traceback, sys, warnings, shutil, numpy as np
|
2 |
+
import gradio as gr
|
3 |
+
import librosa
|
4 |
+
import asyncio
|
5 |
+
import rarfile
|
6 |
+
import edge_tts
|
7 |
+
import yt_dlp
|
8 |
+
import ffmpeg
|
9 |
+
import gdown
|
10 |
+
import subprocess
|
11 |
+
import wave
|
12 |
+
import soundfile as sf
|
13 |
+
from scipy.io import wavfile
|
14 |
+
from datetime import datetime
|
15 |
+
from urllib.parse import urlparse
|
16 |
+
from mega import Mega
|
17 |
+
|
18 |
+
now_dir = os.getcwd()
|
19 |
+
tmp = os.path.join(now_dir, "TEMP")
|
20 |
+
shutil.rmtree(tmp, ignore_errors=True)
|
21 |
+
os.makedirs(tmp, exist_ok=True)
|
22 |
+
os.environ["TEMP"] = tmp
|
23 |
+
from lib.infer_pack.models import (
|
24 |
+
SynthesizerTrnMs256NSFsid,
|
25 |
+
SynthesizerTrnMs256NSFsid_nono,
|
26 |
+
SynthesizerTrnMs768NSFsid,
|
27 |
+
SynthesizerTrnMs768NSFsid_nono,
|
28 |
+
)
|
29 |
+
from fairseq import checkpoint_utils
|
30 |
+
from vc_infer_pipeline import VC
|
31 |
+
from config import Config
|
32 |
+
config = Config()
|
33 |
+
|
34 |
+
tts_voice_list = asyncio.get_event_loop().run_until_complete(edge_tts.list_voices())
|
35 |
+
voices = [f"{v['ShortName']}-{v['Gender']}" for v in tts_voice_list]
|
36 |
+
|
37 |
+
hubert_model = None
|
38 |
+
|
39 |
+
f0method_mode = ["pm", "harvest", "crepe"]
|
40 |
+
f0method_info = "PM is fast, Harvest is good but extremely slow, and Crepe effect is good but requires GPU (Default: PM)"
|
41 |
+
|
42 |
+
if os.path.isfile("rmvpe.pt"):
|
43 |
+
f0method_mode.insert(2, "rmvpe")
|
44 |
+
f0method_info = "PM is fast, Harvest is good but extremely slow, Rvmpe is alternative to harvest (might be better), and Crepe effect is good but requires GPU (Default: PM)"
|
45 |
+
|
46 |
+
def load_hubert():
|
47 |
+
global hubert_model
|
48 |
+
models, _, _ = checkpoint_utils.load_model_ensemble_and_task(
|
49 |
+
["hubert_base.pt"],
|
50 |
+
suffix="",
|
51 |
+
)
|
52 |
+
hubert_model = models[0]
|
53 |
+
hubert_model = hubert_model.to(config.device)
|
54 |
+
if config.is_half:
|
55 |
+
hubert_model = hubert_model.half()
|
56 |
+
else:
|
57 |
+
hubert_model = hubert_model.float()
|
58 |
+
hubert_model.eval()
|
59 |
+
|
60 |
+
load_hubert()
|
61 |
+
|
62 |
+
weight_root = "weights"
|
63 |
+
index_root = "weights/index"
|
64 |
+
weights_model = []
|
65 |
+
weights_index = []
|
66 |
+
for _, _, model_files in os.walk(weight_root):
|
67 |
+
for file in model_files:
|
68 |
+
if file.endswith(".pth"):
|
69 |
+
weights_model.append(file)
|
70 |
+
for _, _, index_files in os.walk(index_root):
|
71 |
+
for file in index_files:
|
72 |
+
if file.endswith('.index') and "trained" not in file:
|
73 |
+
weights_index.append(os.path.join(index_root, file))
|
74 |
+
|
75 |
+
def check_models():
|
76 |
+
weights_model = []
|
77 |
+
weights_index = []
|
78 |
+
for _, _, model_files in os.walk(weight_root):
|
79 |
+
for file in model_files:
|
80 |
+
if file.endswith(".pth"):
|
81 |
+
weights_model.append(file)
|
82 |
+
for _, _, index_files in os.walk(index_root):
|
83 |
+
for file in index_files:
|
84 |
+
if file.endswith('.index') and "trained" not in file:
|
85 |
+
weights_index.append(os.path.join(index_root, file))
|
86 |
+
return (
|
87 |
+
gr.Dropdown.update(choices=sorted(weights_model), value=weights_model[0]),
|
88 |
+
gr.Dropdown.update(choices=sorted(weights_index))
|
89 |
+
)
|
90 |
+
|
91 |
+
def clean():
|
92 |
+
return (
|
93 |
+
gr.Dropdown.update(value=""),
|
94 |
+
gr.Slider.update(visible=False)
|
95 |
+
)
|
96 |
+
|
97 |
+
def vc_single(
|
98 |
+
sid,
|
99 |
+
vc_audio_mode,
|
100 |
+
input_audio_path,
|
101 |
+
input_upload_audio,
|
102 |
+
vocal_audio,
|
103 |
+
tts_text,
|
104 |
+
tts_voice,
|
105 |
+
f0_up_key,
|
106 |
+
f0_file,
|
107 |
+
f0_method,
|
108 |
+
file_index,
|
109 |
+
index_rate,
|
110 |
+
filter_radius,
|
111 |
+
resample_sr,
|
112 |
+
rms_mix_rate,
|
113 |
+
protect
|
114 |
+
): # spk_item, input_audio0, vc_transform0,f0_file,f0method0
|
115 |
+
global tgt_sr, net_g, vc, hubert_model, version, cpt
|
116 |
+
try:
|
117 |
+
logs = []
|
118 |
+
print(f"Converting...")
|
119 |
+
logs.append(f"Converting...")
|
120 |
+
yield "\n".join(logs), None
|
121 |
+
if vc_audio_mode == "Input path" or "Youtube" and input_audio_path != "":
|
122 |
+
audio, sr = librosa.load(input_audio_path, sr=16000, mono=True)
|
123 |
+
elif vc_audio_mode == "Upload audio":
|
124 |
+
selected_audio = input_upload_audio
|
125 |
+
if vocal_audio:
|
126 |
+
selected_audio = vocal_audio
|
127 |
+
elif input_upload_audio:
|
128 |
+
selected_audio = input_upload_audio
|
129 |
+
sampling_rate, audio = selected_audio
|
130 |
+
duration = audio.shape[0] / sampling_rate
|
131 |
+
audio = (audio / np.iinfo(audio.dtype).max).astype(np.float32)
|
132 |
+
if len(audio.shape) > 1:
|
133 |
+
audio = librosa.to_mono(audio.transpose(1, 0))
|
134 |
+
if sampling_rate != 16000:
|
135 |
+
audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=16000)
|
136 |
+
elif vc_audio_mode == "TTS Audio":
|
137 |
+
if tts_text is None or tts_voice is None:
|
138 |
+
return "You need to enter text and select a voice", None
|
139 |
+
asyncio.run(edge_tts.Communicate(tts_text, "-".join(tts_voice.split('-')[:-1])).save("tts.mp3"))
|
140 |
+
audio, sr = librosa.load("tts.mp3", sr=16000, mono=True)
|
141 |
+
input_audio_path = "tts.mp3"
|
142 |
+
f0_up_key = int(f0_up_key)
|
143 |
+
times = [0, 0, 0]
|
144 |
+
if hubert_model == None:
|
145 |
+
load_hubert()
|
146 |
+
if_f0 = cpt.get("f0", 1)
|
147 |
+
audio_opt = vc.pipeline(
|
148 |
+
hubert_model,
|
149 |
+
net_g,
|
150 |
+
sid,
|
151 |
+
audio,
|
152 |
+
input_audio_path,
|
153 |
+
times,
|
154 |
+
f0_up_key,
|
155 |
+
f0_method,
|
156 |
+
file_index,
|
157 |
+
# file_big_npy,
|
158 |
+
index_rate,
|
159 |
+
if_f0,
|
160 |
+
filter_radius,
|
161 |
+
tgt_sr,
|
162 |
+
resample_sr,
|
163 |
+
rms_mix_rate,
|
164 |
+
version,
|
165 |
+
protect,
|
166 |
+
f0_file=f0_file
|
167 |
+
)
|
168 |
+
if resample_sr >= 16000 and tgt_sr != resample_sr:
|
169 |
+
tgt_sr = resample_sr
|
170 |
+
index_info = (
|
171 |
+
"Using index:%s." % file_index
|
172 |
+
if os.path.exists(file_index)
|
173 |
+
else "Index not used."
|
174 |
+
)
|
175 |
+
print("Success.\n %s\nTime:\n npy:%ss, f0:%ss, infer:%ss" % (
|
176 |
+
index_info,
|
177 |
+
times[0],
|
178 |
+
times[1],
|
179 |
+
times[2],
|
180 |
+
))
|
181 |
+
info = f"{index_info}\n[{datetime.now().strftime('%Y-%m-%d %H:%M')}]: npy: {times[0]}, f0: {times[1]}s, infer: {times[2]}s"
|
182 |
+
logs.append(info)
|
183 |
+
yield "\n".join(logs), (tgt_sr, audio_opt)
|
184 |
+
except:
|
185 |
+
info = traceback.format_exc()
|
186 |
+
print(info)
|
187 |
+
logs.append(info)
|
188 |
+
yield "\n".join(logs), None
|
189 |
+
|
190 |
+
def get_vc(sid, to_return_protect0):
|
191 |
+
global n_spk, tgt_sr, net_g, vc, cpt, version, weights_index
|
192 |
+
if sid == "" or sid == []:
|
193 |
+
global hubert_model
|
194 |
+
if hubert_model is not None: # 考虑到轮询, 需要加个判断看是否 sid 是由有模型切换到无模型的
|
195 |
+
print("clean_empty_cache")
|
196 |
+
del net_g, n_spk, vc, hubert_model, tgt_sr # ,cpt
|
197 |
+
hubert_model = net_g = n_spk = vc = hubert_model = tgt_sr = None
|
198 |
+
if torch.cuda.is_available():
|
199 |
+
torch.cuda.empty_cache()
|
200 |
+
###楼下不这么折腾清理不干净
|
201 |
+
if_f0 = cpt.get("f0", 1)
|
202 |
+
version = cpt.get("version", "v1")
|
203 |
+
if version == "v1":
|
204 |
+
if if_f0 == 1:
|
205 |
+
net_g = SynthesizerTrnMs256NSFsid(
|
206 |
+
*cpt["config"], is_half=config.is_half
|
207 |
+
)
|
208 |
+
else:
|
209 |
+
net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"])
|
210 |
+
elif version == "v2":
|
211 |
+
if if_f0 == 1:
|
212 |
+
net_g = SynthesizerTrnMs768NSFsid(
|
213 |
+
*cpt["config"], is_half=config.is_half
|
214 |
+
)
|
215 |
+
else:
|
216 |
+
net_g = SynthesizerTrnMs768NSFsid_nono(*cpt["config"])
|
217 |
+
del net_g, cpt
|
218 |
+
if torch.cuda.is_available():
|
219 |
+
torch.cuda.empty_cache()
|
220 |
+
cpt = None
|
221 |
+
return (
|
222 |
+
gr.Slider.update(maximum=2333, visible=False),
|
223 |
+
gr.Slider.update(visible=True),
|
224 |
+
gr.Dropdown.update(choices=sorted(weights_index), value=""),
|
225 |
+
gr.Markdown.update(value="# <center> No model selected")
|
226 |
+
)
|
227 |
+
print(f"Loading {sid} model...")
|
228 |
+
selected_model = sid[:-4]
|
229 |
+
cpt = torch.load(os.path.join(weight_root, sid), map_location="cpu")
|
230 |
+
tgt_sr = cpt["config"][-1]
|
231 |
+
cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0]
|
232 |
+
if_f0 = cpt.get("f0", 1)
|
233 |
+
if if_f0 == 0:
|
234 |
+
to_return_protect0 = {
|
235 |
+
"visible": False,
|
236 |
+
"value": 0.5,
|
237 |
+
"__type__": "update",
|
238 |
+
}
|
239 |
+
else:
|
240 |
+
to_return_protect0 = {
|
241 |
+
"visible": True,
|
242 |
+
"value": to_return_protect0,
|
243 |
+
"__type__": "update",
|
244 |
+
}
|
245 |
+
version = cpt.get("version", "v1")
|
246 |
+
if version == "v1":
|
247 |
+
if if_f0 == 1:
|
248 |
+
net_g = SynthesizerTrnMs256NSFsid(*cpt["config"], is_half=config.is_half)
|
249 |
+
else:
|
250 |
+
net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"])
|
251 |
+
elif version == "v2":
|
252 |
+
if if_f0 == 1:
|
253 |
+
net_g = SynthesizerTrnMs768NSFsid(*cpt["config"], is_half=config.is_half)
|
254 |
+
else:
|
255 |
+
net_g = SynthesizerTrnMs768NSFsid_nono(*cpt["config"])
|
256 |
+
del net_g.enc_q
|
257 |
+
print(net_g.load_state_dict(cpt["weight"], strict=False))
|
258 |
+
net_g.eval().to(config.device)
|
259 |
+
if config.is_half:
|
260 |
+
net_g = net_g.half()
|
261 |
+
else:
|
262 |
+
net_g = net_g.float()
|
263 |
+
vc = VC(tgt_sr, config)
|
264 |
+
n_spk = cpt["config"][-3]
|
265 |
+
weights_index = []
|
266 |
+
for _, _, index_files in os.walk(index_root):
|
267 |
+
for file in index_files:
|
268 |
+
if file.endswith('.index') and "trained" not in file:
|
269 |
+
weights_index.append(os.path.join(index_root, file))
|
270 |
+
if weights_index == []:
|
271 |
+
selected_index = gr.Dropdown.update(value="")
|
272 |
+
else
|
273 |
+
selected_index = gr.Dropdown.update(value=weights_index[0])
|
274 |
+
for index, model_index in enumerate(weights_index):
|
275 |
+
if selected_model in model_index:
|
276 |
+
selected_index = gr.Dropdown.update(value=weights_index[index])
|
277 |
+
break
|
278 |
+
return (
|
279 |
+
gr.Slider.update(maximum=n_spk, visible=True),
|
280 |
+
to_return_protect0,
|
281 |
+
selected_index,
|
282 |
+
gr.Markdown.update(
|
283 |
+
f'## <center> {selected_model}\n'+
|
284 |
+
f'### <center> RVC {version} Model'
|
285 |
+
)
|
286 |
+
)
|
287 |
+
|
288 |
+
def find_audio_files(folder_path, extensions):
|
289 |
+
audio_files = []
|
290 |
+
for root, dirs, files in os.walk(folder_path):
|
291 |
+
for file in files:
|
292 |
+
if any(file.endswith(ext) for ext in extensions):
|
293 |
+
audio_files.append(file)
|
294 |
+
return audio_files
|
295 |
+
|
296 |
+
def vc_multi(
|
297 |
+
spk_item,
|
298 |
+
vc_input,
|
299 |
+
vc_output,
|
300 |
+
vc_transform0,
|
301 |
+
f0method0,
|
302 |
+
file_index,
|
303 |
+
index_rate,
|
304 |
+
filter_radius,
|
305 |
+
resample_sr,
|
306 |
+
rms_mix_rate,
|
307 |
+
protect,
|
308 |
+
):
|
309 |
+
global tgt_sr, net_g, vc, hubert_model, version, cpt
|
310 |
+
logs = []
|
311 |
+
logs.append("Converting...")
|
312 |
+
yield "\n".join(logs)
|
313 |
+
print()
|
314 |
+
try:
|
315 |
+
if os.path.exists(vc_input):
|
316 |
+
folder_path = vc_input
|
317 |
+
extensions = [".mp3", ".wav", ".flac", ".ogg"]
|
318 |
+
audio_files = find_audio_files(folder_path, extensions)
|
319 |
+
for index, file in enumerate(audio_files, start=1):
|
320 |
+
audio, sr = librosa.load(os.path.join(folder_path, file), sr=16000, mono=True)
|
321 |
+
input_audio_path = folder_path, file
|
322 |
+
f0_up_key = int(vc_transform0)
|
323 |
+
times = [0, 0, 0]
|
324 |
+
if hubert_model == None:
|
325 |
+
load_hubert()
|
326 |
+
if_f0 = cpt.get("f0", 1)
|
327 |
+
audio_opt = vc.pipeline(
|
328 |
+
hubert_model,
|
329 |
+
net_g,
|
330 |
+
spk_item,
|
331 |
+
audio,
|
332 |
+
input_audio_path,
|
333 |
+
times,
|
334 |
+
f0_up_key,
|
335 |
+
f0method0,
|
336 |
+
file_index,
|
337 |
+
index_rate,
|
338 |
+
if_f0,
|
339 |
+
filter_radius,
|
340 |
+
tgt_sr,
|
341 |
+
resample_sr,
|
342 |
+
rms_mix_rate,
|
343 |
+
version,
|
344 |
+
protect,
|
345 |
+
f0_file=None
|
346 |
+
)
|
347 |
+
if resample_sr >= 16000 and tgt_sr != resample_sr:
|
348 |
+
tgt_sr = resample_sr
|
349 |
+
output_path = f"{os.path.join(vc_output, file)}"
|
350 |
+
os.makedirs(os.path.join(vc_output), exist_ok=True)
|
351 |
+
sf.write(
|
352 |
+
output_path,
|
353 |
+
audio_opt,
|
354 |
+
tgt_sr,
|
355 |
+
)
|
356 |
+
info = f"{index} / {len(audio_files)} | {file}"
|
357 |
+
print(info)
|
358 |
+
logs.append(info)
|
359 |
+
yield "\n".join(logs)
|
360 |
+
else:
|
361 |
+
logs.append("Folder not found or path doesn't exist.")
|
362 |
+
yield "\n".join(logs)
|
363 |
+
except:
|
364 |
+
info = traceback.format_exc()
|
365 |
+
print(info)
|
366 |
+
logs.append(info)
|
367 |
+
yield "\n".join(logs)
|
368 |
+
|
369 |
+
def download_audio(url, audio_provider):
|
370 |
+
logs = []
|
371 |
+
os.makedirs("dl_audio", exist_ok=True)
|
372 |
+
if url == "":
|
373 |
+
logs.append("URL required!")
|
374 |
+
yield None, "\n".join(logs)
|
375 |
+
return None, "\n".join(logs)
|
376 |
+
if audio_provider == "Youtube":
|
377 |
+
logs.append("Downloading the audio...")
|
378 |
+
yield None, "\n".join(logs)
|
379 |
+
ydl_opts = {
|
380 |
+
'noplaylist': True,
|
381 |
+
'format': 'bestaudio/best',
|
382 |
+
'postprocessors': [{
|
383 |
+
'key': 'FFmpegExtractAudio',
|
384 |
+
'preferredcodec': 'wav',
|
385 |
+
}],
|
386 |
+
"outtmpl": 'result/dl_audio/audio',
|
387 |
+
}
|
388 |
+
audio_path = "result/dl_audio/audio.wav"
|
389 |
+
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
390 |
+
ydl.download([url])
|
391 |
+
logs.append("Download Complete.")
|
392 |
+
yield audio_path, "\n".join(logs)
|
393 |
+
|
394 |
+
def cut_vocal_and_inst_yt(split_model):
|
395 |
+
logs = []
|
396 |
+
logs.append("Starting the audio splitting process...")
|
397 |
+
yield "\n".join(logs), None, None, None
|
398 |
+
command = f"demucs --two-stems=vocals -n {split_model} result/dl_audio/audio.wav -o output"
|
399 |
+
result = subprocess.Popen(command.split(), stdout=subprocess.PIPE, text=True)
|
400 |
+
for line in result.stdout:
|
401 |
+
logs.append(line)
|
402 |
+
yield "\n".join(logs), None, None, None
|
403 |
+
print(result.stdout)
|
404 |
+
vocal = f"output/{split_model}/audio/vocals.wav"
|
405 |
+
inst = f"output/{split_model}/audio/no_vocals.wav"
|
406 |
+
logs.append("Audio splitting complete.")
|
407 |
+
yield "\n".join(logs), vocal, inst, vocal
|
408 |
+
|
409 |
+
def cut_vocal_and_inst(split_model, audio_data):
|
410 |
+
logs = []
|
411 |
+
vocal_path = "output/result/audio.wav"
|
412 |
+
os.makedirs("output/result", exist_ok=True)
|
413 |
+
wavfile.write(vocal_path, audio_data[0], audio_data[1])
|
414 |
+
logs.append("Starting the audio splitting process...")
|
415 |
+
yield "\n".join(logs), None, None
|
416 |
+
command = f"demucs --two-stems=vocals -n {split_model} {vocal_path} -o output"
|
417 |
+
result = subprocess.Popen(command.split(), stdout=subprocess.PIPE, text=True)
|
418 |
+
for line in result.stdout:
|
419 |
+
logs.append(line)
|
420 |
+
yield "\n".join(logs), None, None
|
421 |
+
print(result.stdout)
|
422 |
+
vocal = f"output/{split_model}/audio/vocals.wav"
|
423 |
+
inst = f"output/{split_model}/audio/no_vocals.wav"
|
424 |
+
logs.append("Audio splitting complete.")
|
425 |
+
yield "\n".join(logs), vocal, inst
|
426 |
+
|
427 |
+
def combine_vocal_and_inst(audio_data, vocal_volume, inst_volume, split_model):
|
428 |
+
os.makedirs("output/result", exist_ok=True)
|
429 |
+
vocal_path = "output/result/output.wav"
|
430 |
+
output_path = "output/result/combine.mp3"
|
431 |
+
inst_path = f"output/{split_model}/audio/no_vocals.wav"
|
432 |
+
wavfile.write(vocal_path, audio_data[0], audio_data[1])
|
433 |
+
command = f'ffmpeg -y -i {inst_path} -i {vocal_path} -filter_complex [0:a]volume={inst_volume}[i];[1:a]volume={vocal_volume}[v];[i][v]amix=inputs=2:duration=longest[a] -map [a] -b:a 320k -c:a libmp3lame {output_path}'
|
434 |
+
result = subprocess.run(command.split(), stdout=subprocess.PIPE)
|
435 |
+
print(result.stdout.decode())
|
436 |
+
return output_path
|
437 |
+
|
438 |
+
def download_and_extract_models(urls):
|
439 |
+
logs = []
|
440 |
+
os.makedirs("zips", exist_ok=True)
|
441 |
+
os.makedirs(os.path.join("zips", "extract"), exist_ok=True)
|
442 |
+
os.makedirs(os.path.join(weight_root), exist_ok=True)
|
443 |
+
os.makedirs(os.path.join(index_root), exist_ok=True)
|
444 |
+
for link in urls.splitlines():
|
445 |
+
url = link.strip()
|
446 |
+
if not url:
|
447 |
+
raise gr.Error("URL Required!")
|
448 |
+
return "No URLs provided."
|
449 |
+
model_zip = urlparse(url).path.split('/')[-2] + '.zip'
|
450 |
+
model_zip_path = os.path.join('zips', model_zip)
|
451 |
+
logs.append(f"Downloading...")
|
452 |
+
yield "\n".join(logs)
|
453 |
+
if "drive.google.com" in url:
|
454 |
+
gdown.download(url, os.path.join("zips", "extract"), quiet=False)
|
455 |
+
elif "mega.nz" in url:
|
456 |
+
m = Mega()
|
457 |
+
m.download_url(url, 'zips')
|
458 |
+
else:
|
459 |
+
os.system(f"wget {url} -O {model_zip_path}")
|
460 |
+
logs.append(f"Extracting...")
|
461 |
+
yield "\n".join(logs)
|
462 |
+
for filename in os.listdir("zips"):
|
463 |
+
archived_file = os.path.join("zips", filename)
|
464 |
+
if filename.endswith(".zip"):
|
465 |
+
shutil.unpack_archive(archived_file, os.path.join("zips", "extract"), 'zip')
|
466 |
+
elif filename.endswith(".rar"):
|
467 |
+
with rarfile.RarFile(archived_file, 'r') as rar:
|
468 |
+
rar.extractall(os.path.join("zips", "extract"))
|
469 |
+
for _, dirs, files in os.walk(os.path.join("zips", "extract")):
|
470 |
+
logs.append(f"Searching Model and Index...")
|
471 |
+
yield "\n".join(logs)
|
472 |
+
model = False
|
473 |
+
index = False
|
474 |
+
if files:
|
475 |
+
for file in files:
|
476 |
+
if file.endswith(".pth"):
|
477 |
+
basename = file[:-4]
|
478 |
+
shutil.move(os.path.join("zips", "extract", file), os.path.join(weight_root, file))
|
479 |
+
model = True
|
480 |
+
if file.endswith('.index') and "trained" not in file:
|
481 |
+
shutil.move(os.path.join("zips", "extract", file), os.path.join(index_root, file))
|
482 |
+
index = True
|
483 |
+
else:
|
484 |
+
logs.append("No model in main folder.")
|
485 |
+
yield "\n".join(logs)
|
486 |
+
logs.append("Searching in subfolders...")
|
487 |
+
yield "\n".join(logs)
|
488 |
+
for sub_dir in dirs:
|
489 |
+
for _, _, sub_files in os.walk(os.path.join("zips", "extract", sub_dir)):
|
490 |
+
for file in sub_files:
|
491 |
+
if file.endswith(".pth"):
|
492 |
+
basename = file[:-4]
|
493 |
+
shutil.move(os.path.join("zips", "extract", sub_dir, file), os.path.join(weight_root, file))
|
494 |
+
model = True
|
495 |
+
if file.endswith('.index') and "trained" not in file:
|
496 |
+
shutil.move(os.path.join("zips", "extract", sub_dir, file), os.path.join(index_root, file))
|
497 |
+
index = True
|
498 |
+
shutil.rmtree(os.path.join("zips", "extract", sub_dir))
|
499 |
+
if index is False:
|
500 |
+
logs.append("Model only file, no Index file detected.")
|
501 |
+
yield "\n".join(logs)
|
502 |
+
logs.append("Download Completed!")
|
503 |
+
yield "\n".join(logs)
|
504 |
+
logs.append("Successfully download all models! Refresh your model list to load the model")
|
505 |
+
yield "\n".join(logs)
|
506 |
+
|
507 |
+
def use_microphone(microphone):
|
508 |
+
if microphone == True:
|
509 |
+
return gr.Audio.update(source="microphone")
|
510 |
+
else:
|
511 |
+
return gr.Audio.update(source="upload")
|
512 |
+
|
513 |
+
def change_audio_mode(vc_audio_mode):
|
514 |
+
if vc_audio_mode == "Input path":
|
515 |
+
return (
|
516 |
+
# Input & Upload
|
517 |
+
gr.Textbox.update(visible=True),
|
518 |
+
gr.Checkbox.update(visible=False),
|
519 |
+
gr.Audio.update(visible=False),
|
520 |
+
# Youtube
|
521 |
+
gr.Dropdown.update(visible=False),
|
522 |
+
gr.Textbox.update(visible=False),
|
523 |
+
gr.Textbox.update(visible=False),
|
524 |
+
gr.Button.update(visible=False),
|
525 |
+
# Splitter
|
526 |
+
gr.Dropdown.update(visible=True),
|
527 |
+
gr.Textbox.update(visible=True),
|
528 |
+
gr.Button.update(visible=True),
|
529 |
+
gr.Button.update(visible=False),
|
530 |
+
gr.Audio.update(visible=False),
|
531 |
+
gr.Audio.update(visible=True),
|
532 |
+
gr.Audio.update(visible=True),
|
533 |
+
gr.Slider.update(visible=True),
|
534 |
+
gr.Slider.update(visible=True),
|
535 |
+
gr.Audio.update(visible=True),
|
536 |
+
gr.Button.update(visible=True),
|
537 |
+
# TTS
|
538 |
+
gr.Textbox.update(visible=False),
|
539 |
+
gr.Dropdown.update(visible=False)
|
540 |
+
)
|
541 |
+
elif vc_audio_mode == "Upload audio":
|
542 |
+
return (
|
543 |
+
# Input & Upload
|
544 |
+
gr.Textbox.update(visible=False),
|
545 |
+
gr.Checkbox.update(visible=True),
|
546 |
+
gr.Audio.update(visible=True),
|
547 |
+
# Youtube
|
548 |
+
gr.Dropdown.update(visible=False),
|
549 |
+
gr.Textbox.update(visible=False),
|
550 |
+
gr.Textbox.update(visible=False),
|
551 |
+
gr.Button.update(visible=False),
|
552 |
+
# Splitter
|
553 |
+
gr.Dropdown.update(visible=True),
|
554 |
+
gr.Textbox.update(visible=True),
|
555 |
+
gr.Button.update(visible=False),
|
556 |
+
gr.Button.update(visible=True),
|
557 |
+
gr.Audio.update(visible=False),
|
558 |
+
gr.Audio.update(visible=True),
|
559 |
+
gr.Audio.update(visible=True),
|
560 |
+
gr.Slider.update(visible=True),
|
561 |
+
gr.Slider.update(visible=True),
|
562 |
+
gr.Audio.update(visible=True),
|
563 |
+
gr.Button.update(visible=True),
|
564 |
+
# TTS
|
565 |
+
gr.Textbox.update(visible=False),
|
566 |
+
gr.Dropdown.update(visible=False)
|
567 |
+
)
|
568 |
+
elif vc_audio_mode == "Youtube":
|
569 |
+
return (
|
570 |
+
# Input & Upload
|
571 |
+
gr.Textbox.update(visible=False),
|
572 |
+
gr.Checkbox.update(visible=False),
|
573 |
+
gr.Audio.update(visible=False),
|
574 |
+
# Youtube
|
575 |
+
gr.Dropdown.update(visible=True),
|
576 |
+
gr.Textbox.update(visible=True),
|
577 |
+
gr.Textbox.update(visible=True),
|
578 |
+
gr.Button.update(visible=True),
|
579 |
+
# Splitter
|
580 |
+
gr.Dropdown.update(visible=True),
|
581 |
+
gr.Textbox.update(visible=True),
|
582 |
+
gr.Button.update(visible=True),
|
583 |
+
gr.Button.update(visible=False),
|
584 |
+
gr.Audio.update(visible=True),
|
585 |
+
gr.Audio.update(visible=True),
|
586 |
+
gr.Audio.update(visible=True),
|
587 |
+
gr.Slider.update(visible=True),
|
588 |
+
gr.Slider.update(visible=True),
|
589 |
+
gr.Audio.update(visible=True),
|
590 |
+
gr.Button.update(visible=True),
|
591 |
+
# TTS
|
592 |
+
gr.Textbox.update(visible=False),
|
593 |
+
gr.Dropdown.update(visible=False)
|
594 |
+
)
|
595 |
+
elif vc_audio_mode == "TTS Audio":
|
596 |
+
return (
|
597 |
+
# Input & Upload
|
598 |
+
gr.Textbox.update(visible=False),
|
599 |
+
gr.Checkbox.update(visible=False),
|
600 |
+
gr.Audio.update(visible=False),
|
601 |
+
# Youtube
|
602 |
+
gr.Dropdown.update(visible=False),
|
603 |
+
gr.Textbox.update(visible=False),
|
604 |
+
gr.Textbox.update(visible=False),
|
605 |
+
gr.Button.update(visible=False),
|
606 |
+
# Splitter
|
607 |
+
gr.Dropdown.update(visible=False),
|
608 |
+
gr.Textbox.update(visible=False),
|
609 |
+
gr.Button.update(visible=False),
|
610 |
+
gr.Button.update(visible=False),
|
611 |
+
gr.Audio.update(visible=False),
|
612 |
+
gr.Audio.update(visible=False),
|
613 |
+
gr.Audio.update(visible=False),
|
614 |
+
gr.Slider.update(visible=False),
|
615 |
+
gr.Slider.update(visible=False),
|
616 |
+
gr.Audio.update(visible=False),
|
617 |
+
gr.Button.update(visible=False),
|
618 |
+
# TTS
|
619 |
+
gr.Textbox.update(visible=True),
|
620 |
+
gr.Dropdown.update(visible=True)
|
621 |
+
)
|
622 |
+
|
623 |
+
with gr.Blocks() as app:
|
624 |
+
gr.Markdown(
|
625 |
+
"# <center> Advanced RVC Inference\n"
|
626 |
+
)
|
627 |
+
with gr.Row():
|
628 |
+
sid = gr.Dropdown(
|
629 |
+
label="Weight",
|
630 |
+
choices=sorted(weights_model),
|
631 |
+
)
|
632 |
+
file_index = gr.Dropdown(
|
633 |
+
label="List of index file",
|
634 |
+
choices=sorted(weights_index),
|
635 |
+
interactive=True,
|
636 |
+
)
|
637 |
+
spk_item = gr.Slider(
|
638 |
+
minimum=0,
|
639 |
+
maximum=2333,
|
640 |
+
step=1,
|
641 |
+
label="Speaker ID",
|
642 |
+
value=0,
|
643 |
+
visible=False,
|
644 |
+
interactive=True,
|
645 |
+
)
|
646 |
+
refresh_model = gr.Button("Refresh model list", variant="primary")
|
647 |
+
clean_button = gr.Button("Clear Model from memory", variant="primary")
|
648 |
+
refresh_model.click(
|
649 |
+
fn=check_models, inputs=[], outputs=[sid, file_index]
|
650 |
+
)
|
651 |
+
clean_button.click(fn=clean, inputs=[], outputs=[sid, spk_item])
|
652 |
+
with gr.TabItem("Inference"):
|
653 |
+
selected_model = gr.Markdown(value="# <center> No model selected")
|
654 |
+
with gr.Row():
|
655 |
+
with gr.Column():
|
656 |
+
vc_audio_mode = gr.Dropdown(label="Input voice", choices=["Input path", "Upload audio", "Youtube", "TTS Audio"], allow_custom_value=False, value="Upload audio")
|
657 |
+
# Input
|
658 |
+
vc_input = gr.Textbox(label="Input audio path", visible=False)
|
659 |
+
# Upload
|
660 |
+
vc_microphone_mode = gr.Checkbox(label="Use Microphone", value=False, visible=True, interactive=True)
|
661 |
+
vc_upload = gr.Audio(label="Upload audio file", source="upload", visible=True, interactive=True)
|
662 |
+
# Youtube
|
663 |
+
vc_download_audio = gr.Dropdown(label="Provider", choices=["Youtube"], allow_custom_value=False, visible=False, value="Youtube", info="Select provider (Default: Youtube)")
|
664 |
+
vc_link = gr.Textbox(label="Youtube URL", visible=False, info="Example: https://www.youtube.com/watch?v=Nc0sB1Bmf-A", placeholder="https://www.youtube.com/watch?v=...")
|
665 |
+
vc_log_yt = gr.Textbox(label="Output Information", visible=False, interactive=False)
|
666 |
+
vc_download_button = gr.Button("Download Audio", variant="primary", visible=False)
|
667 |
+
vc_audio_preview = gr.Audio(label="Downloaded Audio Preview", visible=False)
|
668 |
+
# TTS
|
669 |
+
tts_text = gr.Textbox(label="TTS text", info="Text to speech input", visible=False)
|
670 |
+
tts_voice = gr.Dropdown(label="Edge-tts speaker", choices=voices, visible=False, allow_custom_value=False, value="en-US-AnaNeural-Female")
|
671 |
+
# Splitter
|
672 |
+
vc_split_model = gr.Dropdown(label="Splitter Model", choices=["hdemucs_mmi", "htdemucs", "htdemucs_ft", "mdx", "mdx_q", "mdx_extra_q"], allow_custom_value=False, visible=True, value="htdemucs", info="Select the splitter model (Default: htdemucs)")
|
673 |
+
vc_split_log = gr.Textbox(label="Output Information", visible=True, interactive=False)
|
674 |
+
vc_split_yt = gr.Button("Split Audio", variant="primary", visible=False)
|
675 |
+
vc_split = gr.Button("Split Audio", variant="primary", visible=True)
|
676 |
+
vc_vocal_preview = gr.Audio(label="Vocal Preview", interactive=False, visible=True)
|
677 |
+
vc_inst_preview = gr.Audio(label="Instrumental Preview", interactive=False, visible=True)
|
678 |
+
with gr.Column():
|
679 |
+
vc_transform0 = gr.Number(
|
680 |
+
label="Transpose",
|
681 |
+
info='Type "12" to change from male to female convertion or Type "-12" to change female to male convertion.',
|
682 |
+
value=0
|
683 |
+
)
|
684 |
+
f0method0 = gr.Radio(
|
685 |
+
label="Pitch extraction algorithm",
|
686 |
+
info=f0method_info,
|
687 |
+
choices=f0method_mode,
|
688 |
+
value="pm",
|
689 |
+
interactive=True,
|
690 |
+
)
|
691 |
+
index_rate0 = gr.Slider(
|
692 |
+
minimum=0,
|
693 |
+
maximum=1,
|
694 |
+
label="Retrieval feature ratio",
|
695 |
+
value=0.7,
|
696 |
+
interactive=True,
|
697 |
+
)
|
698 |
+
filter_radius0 = gr.Slider(
|
699 |
+
minimum=0,
|
700 |
+
maximum=7,
|
701 |
+
label="Apply Median Filtering",
|
702 |
+
info="The value represents the filter radius and can reduce breathiness.",
|
703 |
+
value=3,
|
704 |
+
step=1,
|
705 |
+
interactive=True,
|
706 |
+
)
|
707 |
+
resample_sr0 = gr.Slider(
|
708 |
+
minimum=0,
|
709 |
+
maximum=48000,
|
710 |
+
label="Resample the output audio",
|
711 |
+
info="Resample the output audio in post-processing to the final sample rate. Set to 0 for no resampling",
|
712 |
+
value=0,
|
713 |
+
step=1,
|
714 |
+
interactive=True,
|
715 |
+
)
|
716 |
+
rms_mix_rate0 = gr.Slider(
|
717 |
+
minimum=0,
|
718 |
+
maximum=1,
|
719 |
+
label="Volume Envelope",
|
720 |
+
info="Use the volume envelope of the input to replace or mix with the volume envelope of the output. The closer the ratio is to 1, the more the output envelope is used",
|
721 |
+
value=1,
|
722 |
+
interactive=True,
|
723 |
+
)
|
724 |
+
protect0 = gr.Slider(
|
725 |
+
minimum=0,
|
726 |
+
maximum=0.5,
|
727 |
+
label="Voice Protection",
|
728 |
+
info="Protect voiceless consonants and breath sounds to prevent artifacts such as tearing in electronic music. Set to 0.5 to disable. Decrease the value to increase protection, but it may reduce indexing accuracy",
|
729 |
+
value=0.5,
|
730 |
+
step=0.01,
|
731 |
+
interactive=True,
|
732 |
+
)
|
733 |
+
f0_file0 = gr.File(
|
734 |
+
label="F0 curve file (Optional)",
|
735 |
+
info="One pitch per line, Replace the default F0 and pitch modulation"
|
736 |
+
)
|
737 |
+
with gr.Column():
|
738 |
+
vc_log = gr.Textbox(label="Output Information", interactive=False)
|
739 |
+
vc_output = gr.Audio(label="Output Audio", interactive=False)
|
740 |
+
vc_convert = gr.Button("Convert", variant="primary")
|
741 |
+
vc_vocal_volume = gr.Slider(
|
742 |
+
minimum=0,
|
743 |
+
maximum=10,
|
744 |
+
label="Vocal volume",
|
745 |
+
value=1,
|
746 |
+
interactive=True,
|
747 |
+
step=1,
|
748 |
+
info="Adjust vocal volume (Default: 1}",
|
749 |
+
visible=True
|
750 |
+
)
|
751 |
+
vc_inst_volume = gr.Slider(
|
752 |
+
minimum=0,
|
753 |
+
maximum=10,
|
754 |
+
label="Instrument volume",
|
755 |
+
value=1,
|
756 |
+
interactive=True,
|
757 |
+
step=1,
|
758 |
+
info="Adjust instrument volume (Default: 1}",
|
759 |
+
visible=True
|
760 |
+
)
|
761 |
+
vc_combined_output = gr.Audio(label="Output Combined Audio", visible=True)
|
762 |
+
vc_combine = gr.Button("Combine",variant="primary", visible=True)
|
763 |
+
vc_convert.click(
|
764 |
+
vc_single,
|
765 |
+
[
|
766 |
+
spk_item,
|
767 |
+
vc_audio_mode,
|
768 |
+
vc_input,
|
769 |
+
vc_upload,
|
770 |
+
vc_vocal_preview,
|
771 |
+
tts_text,
|
772 |
+
tts_voice,
|
773 |
+
vc_transform0,
|
774 |
+
f0_file0,
|
775 |
+
f0method0,
|
776 |
+
file_index,
|
777 |
+
index_rate0,
|
778 |
+
filter_radius0,
|
779 |
+
resample_sr0,
|
780 |
+
rms_mix_rate0,
|
781 |
+
protect0,
|
782 |
+
],
|
783 |
+
[vc_log, vc_output],
|
784 |
+
)
|
785 |
+
vc_download_button.click(
|
786 |
+
fn=download_audio,
|
787 |
+
inputs=[vc_link, vc_download_audio],
|
788 |
+
outputs=[vc_audio_preview, vc_log_yt]
|
789 |
+
)
|
790 |
+
vc_split_yt.click(
|
791 |
+
fn=cut_vocal_and_inst_yt,
|
792 |
+
inputs=[vc_split_model],
|
793 |
+
outputs=[vc_split_log, vc_vocal_preview, vc_inst_preview, vc_input]
|
794 |
+
)
|
795 |
+
vc_split.click(
|
796 |
+
fn=cut_vocal_and_inst,
|
797 |
+
inputs=[vc_split_model, vc_upload],
|
798 |
+
outputs=[vc_split_log, vc_vocal_preview, vc_inst_preview]
|
799 |
+
)
|
800 |
+
vc_combine.click(
|
801 |
+
fn=combine_vocal_and_inst,
|
802 |
+
inputs=[vc_output, vc_vocal_volume, vc_inst_volume, vc_split_model],
|
803 |
+
outputs=[vc_combined_output]
|
804 |
+
)
|
805 |
+
vc_microphone_mode.change(
|
806 |
+
fn=use_microphone,
|
807 |
+
inputs=vc_microphone_mode,
|
808 |
+
outputs=vc_upload
|
809 |
+
)
|
810 |
+
vc_audio_mode.change(
|
811 |
+
fn=change_audio_mode,
|
812 |
+
inputs=[vc_audio_mode],
|
813 |
+
outputs=[
|
814 |
+
# Input & Upload
|
815 |
+
vc_input,
|
816 |
+
vc_microphone_mode,
|
817 |
+
vc_upload,
|
818 |
+
# Youtube
|
819 |
+
vc_download_audio,
|
820 |
+
vc_link,
|
821 |
+
vc_log_yt,
|
822 |
+
vc_download_button,
|
823 |
+
# Splitter
|
824 |
+
vc_split_model,
|
825 |
+
vc_split_log,
|
826 |
+
vc_split_yt,
|
827 |
+
vc_split,
|
828 |
+
vc_audio_preview,
|
829 |
+
vc_vocal_preview,
|
830 |
+
vc_inst_preview,
|
831 |
+
vc_vocal_volume,
|
832 |
+
vc_inst_volume,
|
833 |
+
vc_combined_output,
|
834 |
+
vc_combine,
|
835 |
+
# TTS
|
836 |
+
tts_text,
|
837 |
+
tts_voice
|
838 |
+
]
|
839 |
+
)
|
840 |
+
sid.change(fn=get_vc, inputs=[sid, protect0], outputs=[spk_item, protect0, file_index, selected_model])
|
841 |
+
with gr.TabItem("Batch Inference"):
|
842 |
+
with gr.Row():
|
843 |
+
with gr.Column():
|
844 |
+
vc_input_bat = gr.Textbox(label="Input audio path (folder)", visible=True)
|
845 |
+
vc_output_bat = gr.Textbox(label="Output audio path (folder)", value="result/batch", visible=True)
|
846 |
+
with gr.Column():
|
847 |
+
vc_transform0_bat = gr.Number(
|
848 |
+
label="Transpose",
|
849 |
+
info='Type "12" to change from male to female convertion or Type "-12" to change female to male convertion.',
|
850 |
+
value=0
|
851 |
+
)
|
852 |
+
f0method0_bat = gr.Radio(
|
853 |
+
label="Pitch extraction algorithm",
|
854 |
+
info=f0method_info,
|
855 |
+
choices=f0method_mode,
|
856 |
+
value="pm",
|
857 |
+
interactive=True,
|
858 |
+
)
|
859 |
+
index_rate0_bat = gr.Slider(
|
860 |
+
minimum=0,
|
861 |
+
maximum=1,
|
862 |
+
label="Retrieval feature ratio",
|
863 |
+
value=0.7,
|
864 |
+
interactive=True,
|
865 |
+
)
|
866 |
+
filter_radius0_bat = gr.Slider(
|
867 |
+
minimum=0,
|
868 |
+
maximum=7,
|
869 |
+
label="Apply Median Filtering",
|
870 |
+
info="The value represents the filter radius and can reduce breathiness.",
|
871 |
+
value=3,
|
872 |
+
step=1,
|
873 |
+
interactive=True,
|
874 |
+
)
|
875 |
+
resample_sr0_bat = gr.Slider(
|
876 |
+
minimum=0,
|
877 |
+
maximum=48000,
|
878 |
+
label="Resample the output audio",
|
879 |
+
info="Resample the output audio in post-processing to the final sample rate. Set to 0 for no resampling",
|
880 |
+
value=0,
|
881 |
+
step=1,
|
882 |
+
interactive=True,
|
883 |
+
)
|
884 |
+
rms_mix_rate0_bat = gr.Slider(
|
885 |
+
minimum=0,
|
886 |
+
maximum=1,
|
887 |
+
label="Volume Envelope",
|
888 |
+
info="Use the volume envelope of the input to replace or mix with the volume envelope of the output. The closer the ratio is to 1, the more the output envelope is used",
|
889 |
+
value=1,
|
890 |
+
interactive=True,
|
891 |
+
)
|
892 |
+
protect0_bat = gr.Slider(
|
893 |
+
minimum=0,
|
894 |
+
maximum=0.5,
|
895 |
+
label="Voice Protection",
|
896 |
+
info="Protect voiceless consonants and breath sounds to prevent artifacts such as tearing in electronic music. Set to 0.5 to disable. Decrease the value to increase protection, but it may reduce indexing accuracy",
|
897 |
+
value=0.5,
|
898 |
+
step=0.01,
|
899 |
+
interactive=True,
|
900 |
+
)
|
901 |
+
with gr.Column():
|
902 |
+
vc_log_bat = gr.Textbox(label="Output Information", interactive=False)
|
903 |
+
vc_convert_bat = gr.Button("Convert", variant="primary")
|
904 |
+
vc_convert_bat.click(
|
905 |
+
vc_multi,
|
906 |
+
[
|
907 |
+
spk_item,
|
908 |
+
vc_input_bat,
|
909 |
+
vc_output_bat,
|
910 |
+
vc_transform0_bat,
|
911 |
+
f0method0_bat,
|
912 |
+
file_index,
|
913 |
+
index_rate0_bat,
|
914 |
+
filter_radius0_bat,
|
915 |
+
resample_sr0_bat,
|
916 |
+
rms_mix_rate0_bat,
|
917 |
+
protect0_bat,
|
918 |
+
],
|
919 |
+
[vc_log_bat],
|
920 |
+
)
|
921 |
+
with gr.TabItem("Model Downloader"):
|
922 |
+
gr.Markdown(
|
923 |
+
"# <center> Model Downloader (Beta)\n"+
|
924 |
+
"#### <center> To download multi link you have to put your link to the textbox and every link separated by space\n"+
|
925 |
+
"#### <center> Support Direct Link, Mega, Google Drive, etc"
|
926 |
+
)
|
927 |
+
with gr.Column():
|
928 |
+
md_text = gr.Textbox(label="URL")
|
929 |
+
with gr.Row():
|
930 |
+
md_download = gr.Button(label="Convert", variant="primary")
|
931 |
+
md_download_logs = gr.Textbox(label="Output information", interactive=False)
|
932 |
+
md_download.click(
|
933 |
+
fn=download_and_extract_models,
|
934 |
+
inputs=[md_text],
|
935 |
+
outputs=[md_download_logs]
|
936 |
+
)
|
937 |
+
with gr.TabItem("Settings"):
|
938 |
+
gr.Markdown(
|
939 |
+
"# <center> Settings\n"+
|
940 |
+
"#### <center> Work in progress"
|
941 |
+
)
|
942 |
+
app.queue(concurrency_count=1, max_size=50, api_open=config.api).launch(share=config.colab)
|
requirements.txt
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
wheel
|
2 |
+
setuptools
|
3 |
+
ffmpeg
|
4 |
+
numba==0.56.4
|
5 |
+
numpy==1.23.5
|
6 |
+
scipy==1.9.3
|
7 |
+
librosa==0.9.1
|
8 |
+
fairseq==0.12.2
|
9 |
+
faiss-cpu==1.7.3
|
10 |
+
gradio==3.40.1
|
11 |
+
pyworld==0.3.2
|
12 |
+
soundfile>=0.12.1
|
13 |
+
praat-parselmouth>=0.4.2
|
14 |
+
httpx==0.23.0
|
15 |
+
tensorboard
|
16 |
+
tensorboardX
|
17 |
+
torchcrepe
|
18 |
+
onnxruntime
|
19 |
+
asyncio
|
20 |
+
demucs
|
21 |
+
edge-tts
|
22 |
+
yt_dlp
|
23 |
+
rarfile
|
24 |
+
mega.py
|
25 |
+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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys, torch, numpy as np, traceback, pdb
|
2 |
+
import torch.nn as nn
|
3 |
+
from time import time as ttime
|
4 |
+
import torch.nn.functional as F
|
5 |
+
|
6 |
+
|
7 |
+
class BiGRU(nn.Module):
|
8 |
+
def __init__(self, input_features, hidden_features, num_layers):
|
9 |
+
super(BiGRU, self).__init__()
|
10 |
+
self.gru = nn.GRU(
|
11 |
+
input_features,
|
12 |
+
hidden_features,
|
13 |
+
num_layers=num_layers,
|
14 |
+
batch_first=True,
|
15 |
+
bidirectional=True,
|
16 |
+
)
|
17 |
+
|
18 |
+
def forward(self, x):
|
19 |
+
return self.gru(x)[0]
|
20 |
+
|
21 |
+
|
22 |
+
class ConvBlockRes(nn.Module):
|
23 |
+
def __init__(self, in_channels, out_channels, momentum=0.01):
|
24 |
+
super(ConvBlockRes, self).__init__()
|
25 |
+
self.conv = nn.Sequential(
|
26 |
+
nn.Conv2d(
|
27 |
+
in_channels=in_channels,
|
28 |
+
out_channels=out_channels,
|
29 |
+
kernel_size=(3, 3),
|
30 |
+
stride=(1, 1),
|
31 |
+
padding=(1, 1),
|
32 |
+
bias=False,
|
33 |
+
),
|
34 |
+
nn.BatchNorm2d(out_channels, momentum=momentum),
|
35 |
+
nn.ReLU(),
|
36 |
+
nn.Conv2d(
|
37 |
+
in_channels=out_channels,
|
38 |
+
out_channels=out_channels,
|
39 |
+
kernel_size=(3, 3),
|
40 |
+
stride=(1, 1),
|
41 |
+
padding=(1, 1),
|
42 |
+
bias=False,
|
43 |
+
),
|
44 |
+
nn.BatchNorm2d(out_channels, momentum=momentum),
|
45 |
+
nn.ReLU(),
|
46 |
+
)
|
47 |
+
if in_channels != out_channels:
|
48 |
+
self.shortcut = nn.Conv2d(in_channels, out_channels, (1, 1))
|
49 |
+
self.is_shortcut = True
|
50 |
+
else:
|
51 |
+
self.is_shortcut = False
|
52 |
+
|
53 |
+
def forward(self, x):
|
54 |
+
if self.is_shortcut:
|
55 |
+
return self.conv(x) + self.shortcut(x)
|
56 |
+
else:
|
57 |
+
return self.conv(x) + x
|
58 |
+
|
59 |
+
|
60 |
+
class Encoder(nn.Module):
|
61 |
+
def __init__(
|
62 |
+
self,
|
63 |
+
in_channels,
|
64 |
+
in_size,
|
65 |
+
n_encoders,
|
66 |
+
kernel_size,
|
67 |
+
n_blocks,
|
68 |
+
out_channels=16,
|
69 |
+
momentum=0.01,
|
70 |
+
):
|
71 |
+
super(Encoder, self).__init__()
|
72 |
+
self.n_encoders = n_encoders
|
73 |
+
self.bn = nn.BatchNorm2d(in_channels, momentum=momentum)
|
74 |
+
self.layers = nn.ModuleList()
|
75 |
+
self.latent_channels = []
|
76 |
+
for i in range(self.n_encoders):
|
77 |
+
self.layers.append(
|
78 |
+
ResEncoderBlock(
|
79 |
+
in_channels, out_channels, kernel_size, n_blocks, momentum=momentum
|
80 |
+
)
|
81 |
+
)
|
82 |
+
self.latent_channels.append([out_channels, in_size])
|
83 |
+
in_channels = out_channels
|
84 |
+
out_channels *= 2
|
85 |
+
in_size //= 2
|
86 |
+
self.out_size = in_size
|
87 |
+
self.out_channel = out_channels
|
88 |
+
|
89 |
+
def forward(self, x):
|
90 |
+
concat_tensors = []
|
91 |
+
x = self.bn(x)
|
92 |
+
for i in range(self.n_encoders):
|
93 |
+
_, x = self.layers[i](x)
|
94 |
+
concat_tensors.append(_)
|
95 |
+
return x, concat_tensors
|
96 |
+
|
97 |
+
|
98 |
+
class ResEncoderBlock(nn.Module):
|
99 |
+
def __init__(
|
100 |
+
self, in_channels, out_channels, kernel_size, n_blocks=1, momentum=0.01
|
101 |
+
):
|
102 |
+
super(ResEncoderBlock, self).__init__()
|
103 |
+
self.n_blocks = n_blocks
|
104 |
+
self.conv = nn.ModuleList()
|
105 |
+
self.conv.append(ConvBlockRes(in_channels, out_channels, momentum))
|
106 |
+
for i in range(n_blocks - 1):
|
107 |
+
self.conv.append(ConvBlockRes(out_channels, out_channels, momentum))
|
108 |
+
self.kernel_size = kernel_size
|
109 |
+
if self.kernel_size is not None:
|
110 |
+
self.pool = nn.AvgPool2d(kernel_size=kernel_size)
|
111 |
+
|
112 |
+
def forward(self, x):
|
113 |
+
for i in range(self.n_blocks):
|
114 |
+
x = self.conv[i](x)
|
115 |
+
if self.kernel_size is not None:
|
116 |
+
return x, self.pool(x)
|
117 |
+
else:
|
118 |
+
return x
|
119 |
+
|
120 |
+
|
121 |
+
class Intermediate(nn.Module): #
|
122 |
+
def __init__(self, in_channels, out_channels, n_inters, n_blocks, momentum=0.01):
|
123 |
+
super(Intermediate, self).__init__()
|
124 |
+
self.n_inters = n_inters
|
125 |
+
self.layers = nn.ModuleList()
|
126 |
+
self.layers.append(
|
127 |
+
ResEncoderBlock(in_channels, out_channels, None, n_blocks, momentum)
|
128 |
+
)
|
129 |
+
for i in range(self.n_inters - 1):
|
130 |
+
self.layers.append(
|
131 |
+
ResEncoderBlock(out_channels, out_channels, None, n_blocks, momentum)
|
132 |
+
)
|
133 |
+
|
134 |
+
def forward(self, x):
|
135 |
+
for i in range(self.n_inters):
|
136 |
+
x = self.layers[i](x)
|
137 |
+
return x
|
138 |
+
|
139 |
+
|
140 |
+
class ResDecoderBlock(nn.Module):
|
141 |
+
def __init__(self, in_channels, out_channels, stride, n_blocks=1, momentum=0.01):
|
142 |
+
super(ResDecoderBlock, self).__init__()
|
143 |
+
out_padding = (0, 1) if stride == (1, 2) else (1, 1)
|
144 |
+
self.n_blocks = n_blocks
|
145 |
+
self.conv1 = nn.Sequential(
|
146 |
+
nn.ConvTranspose2d(
|
147 |
+
in_channels=in_channels,
|
148 |
+
out_channels=out_channels,
|
149 |
+
kernel_size=(3, 3),
|
150 |
+
stride=stride,
|
151 |
+
padding=(1, 1),
|
152 |
+
output_padding=out_padding,
|
153 |
+
bias=False,
|
154 |
+
),
|
155 |
+
nn.BatchNorm2d(out_channels, momentum=momentum),
|
156 |
+
nn.ReLU(),
|
157 |
+
)
|
158 |
+
self.conv2 = nn.ModuleList()
|
159 |
+
self.conv2.append(ConvBlockRes(out_channels * 2, out_channels, momentum))
|
160 |
+
for i in range(n_blocks - 1):
|
161 |
+
self.conv2.append(ConvBlockRes(out_channels, out_channels, momentum))
|
162 |
+
|
163 |
+
def forward(self, x, concat_tensor):
|
164 |
+
x = self.conv1(x)
|
165 |
+
x = torch.cat((x, concat_tensor), dim=1)
|
166 |
+
for i in range(self.n_blocks):
|
167 |
+
x = self.conv2[i](x)
|
168 |
+
return x
|
169 |
+
|
170 |
+
|
171 |
+
class Decoder(nn.Module):
|
172 |
+
def __init__(self, in_channels, n_decoders, stride, n_blocks, momentum=0.01):
|
173 |
+
super(Decoder, self).__init__()
|
174 |
+
self.layers = nn.ModuleList()
|
175 |
+
self.n_decoders = n_decoders
|
176 |
+
for i in range(self.n_decoders):
|
177 |
+
out_channels = in_channels // 2
|
178 |
+
self.layers.append(
|
179 |
+
ResDecoderBlock(in_channels, out_channels, stride, n_blocks, momentum)
|
180 |
+
)
|
181 |
+
in_channels = out_channels
|
182 |
+
|
183 |
+
def forward(self, x, concat_tensors):
|
184 |
+
for i in range(self.n_decoders):
|
185 |
+
x = self.layers[i](x, concat_tensors[-1 - i])
|
186 |
+
return x
|
187 |
+
|
188 |
+
|
189 |
+
class DeepUnet(nn.Module):
|
190 |
+
def __init__(
|
191 |
+
self,
|
192 |
+
kernel_size,
|
193 |
+
n_blocks,
|
194 |
+
en_de_layers=5,
|
195 |
+
inter_layers=4,
|
196 |
+
in_channels=1,
|
197 |
+
en_out_channels=16,
|
198 |
+
):
|
199 |
+
super(DeepUnet, self).__init__()
|
200 |
+
self.encoder = Encoder(
|
201 |
+
in_channels, 128, en_de_layers, kernel_size, n_blocks, en_out_channels
|
202 |
+
)
|
203 |
+
self.intermediate = Intermediate(
|
204 |
+
self.encoder.out_channel // 2,
|
205 |
+
self.encoder.out_channel,
|
206 |
+
inter_layers,
|
207 |
+
n_blocks,
|
208 |
+
)
|
209 |
+
self.decoder = Decoder(
|
210 |
+
self.encoder.out_channel, en_de_layers, kernel_size, n_blocks
|
211 |
+
)
|
212 |
+
|
213 |
+
def forward(self, x):
|
214 |
+
x, concat_tensors = self.encoder(x)
|
215 |
+
x = self.intermediate(x)
|
216 |
+
x = self.decoder(x, concat_tensors)
|
217 |
+
return x
|
218 |
+
|
219 |
+
|
220 |
+
class E2E(nn.Module):
|
221 |
+
def __init__(
|
222 |
+
self,
|
223 |
+
n_blocks,
|
224 |
+
n_gru,
|
225 |
+
kernel_size,
|
226 |
+
en_de_layers=5,
|
227 |
+
inter_layers=4,
|
228 |
+
in_channels=1,
|
229 |
+
en_out_channels=16,
|
230 |
+
):
|
231 |
+
super(E2E, self).__init__()
|
232 |
+
self.unet = DeepUnet(
|
233 |
+
kernel_size,
|
234 |
+
n_blocks,
|
235 |
+
en_de_layers,
|
236 |
+
inter_layers,
|
237 |
+
in_channels,
|
238 |
+
en_out_channels,
|
239 |
+
)
|
240 |
+
self.cnn = nn.Conv2d(en_out_channels, 3, (3, 3), padding=(1, 1))
|
241 |
+
if n_gru:
|
242 |
+
self.fc = nn.Sequential(
|
243 |
+
BiGRU(3 * 128, 256, n_gru),
|
244 |
+
nn.Linear(512, 360),
|
245 |
+
nn.Dropout(0.25),
|
246 |
+
nn.Sigmoid(),
|
247 |
+
)
|
248 |
+
else:
|
249 |
+
self.fc = nn.Sequential(
|
250 |
+
nn.Linear(3 * N_MELS, N_CLASS), nn.Dropout(0.25), nn.Sigmoid()
|
251 |
+
)
|
252 |
+
|
253 |
+
def forward(self, mel):
|
254 |
+
mel = mel.transpose(-1, -2).unsqueeze(1)
|
255 |
+
x = self.cnn(self.unet(mel)).transpose(1, 2).flatten(-2)
|
256 |
+
x = self.fc(x)
|
257 |
+
return x
|
258 |
+
|
259 |
+
|
260 |
+
from librosa.filters import mel
|
261 |
+
|
262 |
+
|
263 |
+
class MelSpectrogram(torch.nn.Module):
|
264 |
+
def __init__(
|
265 |
+
self,
|
266 |
+
is_half,
|
267 |
+
n_mel_channels,
|
268 |
+
sampling_rate,
|
269 |
+
win_length,
|
270 |
+
hop_length,
|
271 |
+
n_fft=None,
|
272 |
+
mel_fmin=0,
|
273 |
+
mel_fmax=None,
|
274 |
+
clamp=1e-5,
|
275 |
+
):
|
276 |
+
super().__init__()
|
277 |
+
n_fft = win_length if n_fft is None else n_fft
|
278 |
+
self.hann_window = {}
|
279 |
+
mel_basis = mel(
|
280 |
+
sr=sampling_rate,
|
281 |
+
n_fft=n_fft,
|
282 |
+
n_mels=n_mel_channels,
|
283 |
+
fmin=mel_fmin,
|
284 |
+
fmax=mel_fmax,
|
285 |
+
htk=True,
|
286 |
+
)
|
287 |
+
mel_basis = torch.from_numpy(mel_basis).float()
|
288 |
+
self.register_buffer("mel_basis", mel_basis)
|
289 |
+
self.n_fft = win_length if n_fft is None else n_fft
|
290 |
+
self.hop_length = hop_length
|
291 |
+
self.win_length = win_length
|
292 |
+
self.sampling_rate = sampling_rate
|
293 |
+
self.n_mel_channels = n_mel_channels
|
294 |
+
self.clamp = clamp
|
295 |
+
self.is_half = is_half
|
296 |
+
|
297 |
+
def forward(self, audio, keyshift=0, speed=1, center=True):
|
298 |
+
factor = 2 ** (keyshift / 12)
|
299 |
+
n_fft_new = int(np.round(self.n_fft * factor))
|
300 |
+
win_length_new = int(np.round(self.win_length * factor))
|
301 |
+
hop_length_new = int(np.round(self.hop_length * speed))
|
302 |
+
keyshift_key = str(keyshift) + "_" + str(audio.device)
|
303 |
+
if keyshift_key not in self.hann_window:
|
304 |
+
self.hann_window[keyshift_key] = torch.hann_window(win_length_new).to(
|
305 |
+
audio.device
|
306 |
+
)
|
307 |
+
fft = torch.stft(
|
308 |
+
audio,
|
309 |
+
n_fft=n_fft_new,
|
310 |
+
hop_length=hop_length_new,
|
311 |
+
win_length=win_length_new,
|
312 |
+
window=self.hann_window[keyshift_key],
|
313 |
+
center=center,
|
314 |
+
return_complex=True,
|
315 |
+
)
|
316 |
+
magnitude = torch.sqrt(fft.real.pow(2) + fft.imag.pow(2))
|
317 |
+
if keyshift != 0:
|
318 |
+
size = self.n_fft // 2 + 1
|
319 |
+
resize = magnitude.size(1)
|
320 |
+
if resize < size:
|
321 |
+
magnitude = F.pad(magnitude, (0, 0, 0, size - resize))
|
322 |
+
magnitude = magnitude[:, :size, :] * self.win_length / win_length_new
|
323 |
+
mel_output = torch.matmul(self.mel_basis, magnitude)
|
324 |
+
if self.is_half == True:
|
325 |
+
mel_output = mel_output.half()
|
326 |
+
log_mel_spec = torch.log(torch.clamp(mel_output, min=self.clamp))
|
327 |
+
return log_mel_spec
|
328 |
+
|
329 |
+
|
330 |
+
class RMVPE:
|
331 |
+
def __init__(self, model_path, is_half, device=None):
|
332 |
+
self.resample_kernel = {}
|
333 |
+
model = E2E(4, 1, (2, 2))
|
334 |
+
ckpt = torch.load(model_path, map_location="cpu")
|
335 |
+
model.load_state_dict(ckpt)
|
336 |
+
model.eval()
|
337 |
+
if is_half == True:
|
338 |
+
model = model.half()
|
339 |
+
self.model = model
|
340 |
+
self.resample_kernel = {}
|
341 |
+
self.is_half = is_half
|
342 |
+
if device is None:
|
343 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
344 |
+
self.device = device
|
345 |
+
self.mel_extractor = MelSpectrogram(
|
346 |
+
is_half, 128, 16000, 1024, 160, None, 30, 8000
|
347 |
+
).to(device)
|
348 |
+
self.model = self.model.to(device)
|
349 |
+
cents_mapping = 20 * np.arange(360) + 1997.3794084376191
|
350 |
+
self.cents_mapping = np.pad(cents_mapping, (4, 4)) # 368
|
351 |
+
|
352 |
+
def mel2hidden(self, mel):
|
353 |
+
with torch.no_grad():
|
354 |
+
n_frames = mel.shape[-1]
|
355 |
+
mel = F.pad(
|
356 |
+
mel, (0, 32 * ((n_frames - 1) // 32 + 1) - n_frames), mode="reflect"
|
357 |
+
)
|
358 |
+
hidden = self.model(mel)
|
359 |
+
return hidden[:, :n_frames]
|
360 |
+
|
361 |
+
def decode(self, hidden, thred=0.03):
|
362 |
+
cents_pred = self.to_local_average_cents(hidden, thred=thred)
|
363 |
+
f0 = 10 * (2 ** (cents_pred / 1200))
|
364 |
+
f0[f0 == 10] = 0
|
365 |
+
# f0 = np.array([10 * (2 ** (cent_pred / 1200)) if cent_pred else 0 for cent_pred in cents_pred])
|
366 |
+
return f0
|
367 |
+
|
368 |
+
def infer_from_audio(self, audio, thred=0.03):
|
369 |
+
audio = torch.from_numpy(audio).float().to(self.device).unsqueeze(0)
|
370 |
+
# torch.cuda.synchronize()
|
371 |
+
# t0=ttime()
|
372 |
+
mel = self.mel_extractor(audio, center=True)
|
373 |
+
# torch.cuda.synchronize()
|
374 |
+
# t1=ttime()
|
375 |
+
hidden = self.mel2hidden(mel)
|
376 |
+
# torch.cuda.synchronize()
|
377 |
+
# t2=ttime()
|
378 |
+
hidden = hidden.squeeze(0).cpu().numpy()
|
379 |
+
if self.is_half == True:
|
380 |
+
hidden = hidden.astype("float32")
|
381 |
+
f0 = self.decode(hidden, thred=thred)
|
382 |
+
# torch.cuda.synchronize()
|
383 |
+
# t3=ttime()
|
384 |
+
# print("hmvpe:%s\t%s\t%s\t%s"%(t1-t0,t2-t1,t3-t2,t3-t0))
|
385 |
+
return f0
|
386 |
+
|
387 |
+
def to_local_average_cents(self, salience, thred=0.05):
|
388 |
+
# t0 = ttime()
|
389 |
+
center = np.argmax(salience, axis=1) # 帧长#index
|
390 |
+
salience = np.pad(salience, ((0, 0), (4, 4))) # 帧长,368
|
391 |
+
# t1 = ttime()
|
392 |
+
center += 4
|
393 |
+
todo_salience = []
|
394 |
+
todo_cents_mapping = []
|
395 |
+
starts = center - 4
|
396 |
+
ends = center + 5
|
397 |
+
for idx in range(salience.shape[0]):
|
398 |
+
todo_salience.append(salience[:, starts[idx] : ends[idx]][idx])
|
399 |
+
todo_cents_mapping.append(self.cents_mapping[starts[idx] : ends[idx]])
|
400 |
+
# t2 = ttime()
|
401 |
+
todo_salience = np.array(todo_salience) # 帧长,9
|
402 |
+
todo_cents_mapping = np.array(todo_cents_mapping) # 帧长,9
|
403 |
+
product_sum = np.sum(todo_salience * todo_cents_mapping, 1)
|
404 |
+
weight_sum = np.sum(todo_salience, 1) # 帧长
|
405 |
+
devided = product_sum / weight_sum # 帧长
|
406 |
+
# t3 = ttime()
|
407 |
+
maxx = np.max(salience, axis=1) # 帧长
|
408 |
+
devided[maxx <= thred] = 0
|
409 |
+
# t4 = ttime()
|
410 |
+
# print("decode:%s\t%s\t%s\t%s" % (t1 - t0, t2 - t1, t3 - t2, t4 - t3))
|
411 |
+
return devided
|
412 |
+
|
413 |
+
|
414 |
+
# if __name__ == '__main__':
|
415 |
+
# audio, sampling_rate = sf.read("卢本伟语录~1.wav")
|
416 |
+
# if len(audio.shape) > 1:
|
417 |
+
# audio = librosa.to_mono(audio.transpose(1, 0))
|
418 |
+
# audio_bak = audio.copy()
|
419 |
+
# if sampling_rate != 16000:
|
420 |
+
# audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=16000)
|
421 |
+
# model_path = "/bili-coeus/jupyter/jupyterhub-liujing04/vits_ch/test-RMVPE/weights/rmvpe_llc_half.pt"
|
422 |
+
# thred = 0.03 # 0.01
|
423 |
+
# device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
424 |
+
# rmvpe = RMVPE(model_path,is_half=False, device=device)
|
425 |
+
# t0=ttime()
|
426 |
+
# f0 = rmvpe.infer_from_audio(audio, thred=thred)
|
427 |
+
# f0 = rmvpe.infer_from_audio(audio, thred=thred)
|
428 |
+
# f0 = rmvpe.infer_from_audio(audio, thred=thred)
|
429 |
+
# f0 = rmvpe.infer_from_audio(audio, thred=thred)
|
430 |
+
# f0 = rmvpe.infer_from_audio(audio, thred=thred)
|
431 |
+
# t1=ttime()
|
432 |
+
# print(f0.shape,t1-t0)
|
vc_infer_pipeline.py
ADDED
@@ -0,0 +1,443 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np, parselmouth, torch, pdb, sys, os
|
2 |
+
from time import time as ttime
|
3 |
+
import torch.nn.functional as F
|
4 |
+
import scipy.signal as signal
|
5 |
+
import pyworld, os, traceback, faiss, librosa, torchcrepe
|
6 |
+
from scipy import signal
|
7 |
+
from functools import lru_cache
|
8 |
+
|
9 |
+
now_dir = os.getcwd()
|
10 |
+
sys.path.append(now_dir)
|
11 |
+
|
12 |
+
bh, ah = signal.butter(N=5, Wn=48, btype="high", fs=16000)
|
13 |
+
|
14 |
+
input_audio_path2wav = {}
|
15 |
+
|
16 |
+
|
17 |
+
@lru_cache
|
18 |
+
def cache_harvest_f0(input_audio_path, fs, f0max, f0min, frame_period):
|
19 |
+
audio = input_audio_path2wav[input_audio_path]
|
20 |
+
f0, t = pyworld.harvest(
|
21 |
+
audio,
|
22 |
+
fs=fs,
|
23 |
+
f0_ceil=f0max,
|
24 |
+
f0_floor=f0min,
|
25 |
+
frame_period=frame_period,
|
26 |
+
)
|
27 |
+
f0 = pyworld.stonemask(audio, f0, t, fs)
|
28 |
+
return f0
|
29 |
+
|
30 |
+
|
31 |
+
def change_rms(data1, sr1, data2, sr2, rate): # 1是输入音频,2是输出音频,rate是2的占比
|
32 |
+
# print(data1.max(),data2.max())
|
33 |
+
rms1 = librosa.feature.rms(
|
34 |
+
y=data1, frame_length=sr1 // 2 * 2, hop_length=sr1 // 2
|
35 |
+
) # 每半秒一个点
|
36 |
+
rms2 = librosa.feature.rms(y=data2, frame_length=sr2 // 2 * 2, hop_length=sr2 // 2)
|
37 |
+
rms1 = torch.from_numpy(rms1)
|
38 |
+
rms1 = F.interpolate(
|
39 |
+
rms1.unsqueeze(0), size=data2.shape[0], mode="linear"
|
40 |
+
).squeeze()
|
41 |
+
rms2 = torch.from_numpy(rms2)
|
42 |
+
rms2 = F.interpolate(
|
43 |
+
rms2.unsqueeze(0), size=data2.shape[0], mode="linear"
|
44 |
+
).squeeze()
|
45 |
+
rms2 = torch.max(rms2, torch.zeros_like(rms2) + 1e-6)
|
46 |
+
data2 *= (
|
47 |
+
torch.pow(rms1, torch.tensor(1 - rate))
|
48 |
+
* torch.pow(rms2, torch.tensor(rate - 1))
|
49 |
+
).numpy()
|
50 |
+
return data2
|
51 |
+
|
52 |
+
|
53 |
+
class VC(object):
|
54 |
+
def __init__(self, tgt_sr, config):
|
55 |
+
self.x_pad, self.x_query, self.x_center, self.x_max, self.is_half = (
|
56 |
+
config.x_pad,
|
57 |
+
config.x_query,
|
58 |
+
config.x_center,
|
59 |
+
config.x_max,
|
60 |
+
config.is_half,
|
61 |
+
)
|
62 |
+
self.sr = 16000 # hubert输入采样率
|
63 |
+
self.window = 160 # 每帧点数
|
64 |
+
self.t_pad = self.sr * self.x_pad # 每条前后pad时间
|
65 |
+
self.t_pad_tgt = tgt_sr * self.x_pad
|
66 |
+
self.t_pad2 = self.t_pad * 2
|
67 |
+
self.t_query = self.sr * self.x_query # 查询切点前后查询时间
|
68 |
+
self.t_center = self.sr * self.x_center # 查询切点位置
|
69 |
+
self.t_max = self.sr * self.x_max # 免查询时长阈值
|
70 |
+
self.device = config.device
|
71 |
+
|
72 |
+
def get_f0(
|
73 |
+
self,
|
74 |
+
input_audio_path,
|
75 |
+
x,
|
76 |
+
p_len,
|
77 |
+
f0_up_key,
|
78 |
+
f0_method,
|
79 |
+
filter_radius,
|
80 |
+
inp_f0=None,
|
81 |
+
):
|
82 |
+
global input_audio_path2wav
|
83 |
+
time_step = self.window / self.sr * 1000
|
84 |
+
f0_min = 50
|
85 |
+
f0_max = 1100
|
86 |
+
f0_mel_min = 1127 * np.log(1 + f0_min / 700)
|
87 |
+
f0_mel_max = 1127 * np.log(1 + f0_max / 700)
|
88 |
+
if f0_method == "pm":
|
89 |
+
f0 = (
|
90 |
+
parselmouth.Sound(x, self.sr)
|
91 |
+
.to_pitch_ac(
|
92 |
+
time_step=time_step / 1000,
|
93 |
+
voicing_threshold=0.6,
|
94 |
+
pitch_floor=f0_min,
|
95 |
+
pitch_ceiling=f0_max,
|
96 |
+
)
|
97 |
+
.selected_array["frequency"]
|
98 |
+
)
|
99 |
+
pad_size = (p_len - len(f0) + 1) // 2
|
100 |
+
if pad_size > 0 or p_len - len(f0) - pad_size > 0:
|
101 |
+
f0 = np.pad(
|
102 |
+
f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant"
|
103 |
+
)
|
104 |
+
elif f0_method == "harvest":
|
105 |
+
input_audio_path2wav[input_audio_path] = x.astype(np.double)
|
106 |
+
f0 = cache_harvest_f0(input_audio_path, self.sr, f0_max, f0_min, 10)
|
107 |
+
if filter_radius > 2:
|
108 |
+
f0 = signal.medfilt(f0, 3)
|
109 |
+
elif f0_method == "crepe":
|
110 |
+
model = "full"
|
111 |
+
# Pick a batch size that doesn't cause memory errors on your gpu
|
112 |
+
batch_size = 512
|
113 |
+
# Compute pitch using first gpu
|
114 |
+
audio = torch.tensor(np.copy(x))[None].float()
|
115 |
+
f0, pd = torchcrepe.predict(
|
116 |
+
audio,
|
117 |
+
self.sr,
|
118 |
+
self.window,
|
119 |
+
f0_min,
|
120 |
+
f0_max,
|
121 |
+
model,
|
122 |
+
batch_size=batch_size,
|
123 |
+
device=self.device,
|
124 |
+
return_periodicity=True,
|
125 |
+
)
|
126 |
+
pd = torchcrepe.filter.median(pd, 3)
|
127 |
+
f0 = torchcrepe.filter.mean(f0, 3)
|
128 |
+
f0[pd < 0.1] = 0
|
129 |
+
f0 = f0[0].cpu().numpy()
|
130 |
+
elif f0_method == "rmvpe":
|
131 |
+
if hasattr(self, "model_rmvpe") == False:
|
132 |
+
from rmvpe import RMVPE
|
133 |
+
|
134 |
+
print("loading rmvpe model")
|
135 |
+
self.model_rmvpe = RMVPE(
|
136 |
+
"rmvpe.pt", is_half=self.is_half, device=self.device
|
137 |
+
)
|
138 |
+
f0 = self.model_rmvpe.infer_from_audio(x, thred=0.03)
|
139 |
+
f0 *= pow(2, f0_up_key / 12)
|
140 |
+
# with open("test.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()]))
|
141 |
+
tf0 = self.sr // self.window # 每秒f0点数
|
142 |
+
if inp_f0 is not None:
|
143 |
+
delta_t = np.round(
|
144 |
+
(inp_f0[:, 0].max() - inp_f0[:, 0].min()) * tf0 + 1
|
145 |
+
).astype("int16")
|
146 |
+
replace_f0 = np.interp(
|
147 |
+
list(range(delta_t)), inp_f0[:, 0] * 100, inp_f0[:, 1]
|
148 |
+
)
|
149 |
+
shape = f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)].shape[0]
|
150 |
+
f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)] = replace_f0[
|
151 |
+
:shape
|
152 |
+
]
|
153 |
+
# with open("test_opt.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()]))
|
154 |
+
f0bak = f0.copy()
|
155 |
+
f0_mel = 1127 * np.log(1 + f0 / 700)
|
156 |
+
f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / (
|
157 |
+
f0_mel_max - f0_mel_min
|
158 |
+
) + 1
|
159 |
+
f0_mel[f0_mel <= 1] = 1
|
160 |
+
f0_mel[f0_mel > 255] = 255
|
161 |
+
f0_coarse = np.rint(f0_mel).astype(np.int)
|
162 |
+
return f0_coarse, f0bak # 1-0
|
163 |
+
|
164 |
+
def vc(
|
165 |
+
self,
|
166 |
+
model,
|
167 |
+
net_g,
|
168 |
+
sid,
|
169 |
+
audio0,
|
170 |
+
pitch,
|
171 |
+
pitchf,
|
172 |
+
times,
|
173 |
+
index,
|
174 |
+
big_npy,
|
175 |
+
index_rate,
|
176 |
+
version,
|
177 |
+
protect,
|
178 |
+
): # ,file_index,file_big_npy
|
179 |
+
feats = torch.from_numpy(audio0)
|
180 |
+
if self.is_half:
|
181 |
+
feats = feats.half()
|
182 |
+
else:
|
183 |
+
feats = feats.float()
|
184 |
+
if feats.dim() == 2: # double channels
|
185 |
+
feats = feats.mean(-1)
|
186 |
+
assert feats.dim() == 1, feats.dim()
|
187 |
+
feats = feats.view(1, -1)
|
188 |
+
padding_mask = torch.BoolTensor(feats.shape).to(self.device).fill_(False)
|
189 |
+
|
190 |
+
inputs = {
|
191 |
+
"source": feats.to(self.device),
|
192 |
+
"padding_mask": padding_mask,
|
193 |
+
"output_layer": 9 if version == "v1" else 12,
|
194 |
+
}
|
195 |
+
t0 = ttime()
|
196 |
+
with torch.no_grad():
|
197 |
+
logits = model.extract_features(**inputs)
|
198 |
+
feats = model.final_proj(logits[0]) if version == "v1" else logits[0]
|
199 |
+
if protect < 0.5 and pitch != None and pitchf != None:
|
200 |
+
feats0 = feats.clone()
|
201 |
+
if (
|
202 |
+
isinstance(index, type(None)) == False
|
203 |
+
and isinstance(big_npy, type(None)) == False
|
204 |
+
and index_rate != 0
|
205 |
+
):
|
206 |
+
npy = feats[0].cpu().numpy()
|
207 |
+
if self.is_half:
|
208 |
+
npy = npy.astype("float32")
|
209 |
+
|
210 |
+
# _, I = index.search(npy, 1)
|
211 |
+
# npy = big_npy[I.squeeze()]
|
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 != None and pitchf != 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 != None and pitchf != None:
|
235 |
+
pitch = pitch[:, :p_len]
|
236 |
+
pitchf = pitchf[:, :p_len]
|
237 |
+
|
238 |
+
if protect < 0.5 and pitch != None and pitchf != 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 != None and pitchf != 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 |
+
# file_big_npy,
|
278 |
+
index_rate,
|
279 |
+
if_f0,
|
280 |
+
filter_radius,
|
281 |
+
tgt_sr,
|
282 |
+
resample_sr,
|
283 |
+
rms_mix_rate,
|
284 |
+
version,
|
285 |
+
protect,
|
286 |
+
f0_file=None,
|
287 |
+
):
|
288 |
+
if (
|
289 |
+
file_index != ""
|
290 |
+
# and file_big_npy != ""
|
291 |
+
# and os.path.exists(file_big_npy) == True
|
292 |
+
and os.path.exists(file_index) == True
|
293 |
+
and index_rate != 0
|
294 |
+
):
|
295 |
+
try:
|
296 |
+
index = faiss.read_index(file_index)
|
297 |
+
# big_npy = np.load(file_big_npy)
|
298 |
+
big_npy = index.reconstruct_n(0, index.ntotal)
|
299 |
+
except:
|
300 |
+
traceback.print_exc()
|
301 |
+
index = big_npy = None
|
302 |
+
else:
|
303 |
+
index = big_npy = None
|
304 |
+
audio = signal.filtfilt(bh, ah, audio)
|
305 |
+
audio_pad = np.pad(audio, (self.window // 2, self.window // 2), mode="reflect")
|
306 |
+
opt_ts = []
|
307 |
+
if audio_pad.shape[0] > self.t_max:
|
308 |
+
audio_sum = np.zeros_like(audio)
|
309 |
+
for i in range(self.window):
|
310 |
+
audio_sum += audio_pad[i : i - self.window]
|
311 |
+
for t in range(self.t_center, audio.shape[0], self.t_center):
|
312 |
+
opt_ts.append(
|
313 |
+
t
|
314 |
+
- self.t_query
|
315 |
+
+ np.where(
|
316 |
+
np.abs(audio_sum[t - self.t_query : t + self.t_query])
|
317 |
+
== np.abs(audio_sum[t - self.t_query : t + self.t_query]).min()
|
318 |
+
)[0][0]
|
319 |
+
)
|
320 |
+
s = 0
|
321 |
+
audio_opt = []
|
322 |
+
t = None
|
323 |
+
t1 = ttime()
|
324 |
+
audio_pad = np.pad(audio, (self.t_pad, self.t_pad), mode="reflect")
|
325 |
+
p_len = audio_pad.shape[0] // self.window
|
326 |
+
inp_f0 = None
|
327 |
+
if hasattr(f0_file, "name") == True:
|
328 |
+
try:
|
329 |
+
with open(f0_file.name, "r") as f:
|
330 |
+
lines = f.read().strip("\n").split("\n")
|
331 |
+
inp_f0 = []
|
332 |
+
for line in lines:
|
333 |
+
inp_f0.append([float(i) for i in line.split(",")])
|
334 |
+
inp_f0 = np.array(inp_f0, dtype="float32")
|
335 |
+
except:
|
336 |
+
traceback.print_exc()
|
337 |
+
sid = torch.tensor(sid, device=self.device).unsqueeze(0).long()
|
338 |
+
pitch, pitchf = None, None
|
339 |
+
if if_f0 == 1:
|
340 |
+
pitch, pitchf = self.get_f0(
|
341 |
+
input_audio_path,
|
342 |
+
audio_pad,
|
343 |
+
p_len,
|
344 |
+
f0_up_key,
|
345 |
+
f0_method,
|
346 |
+
filter_radius,
|
347 |
+
inp_f0,
|
348 |
+
)
|
349 |
+
pitch = pitch[:p_len]
|
350 |
+
pitchf = pitchf[:p_len]
|
351 |
+
if self.device == "mps":
|
352 |
+
pitchf = pitchf.astype(np.float32)
|
353 |
+
pitch = torch.tensor(pitch, device=self.device).unsqueeze(0).long()
|
354 |
+
pitchf = torch.tensor(pitchf, device=self.device).unsqueeze(0).float()
|
355 |
+
t2 = ttime()
|
356 |
+
times[1] += t2 - t1
|
357 |
+
for t in opt_ts:
|
358 |
+
t = t // self.window * self.window
|
359 |
+
if if_f0 == 1:
|
360 |
+
audio_opt.append(
|
361 |
+
self.vc(
|
362 |
+
model,
|
363 |
+
net_g,
|
364 |
+
sid,
|
365 |
+
audio_pad[s : t + self.t_pad2 + self.window],
|
366 |
+
pitch[:, s // self.window : (t + self.t_pad2) // self.window],
|
367 |
+
pitchf[:, s // self.window : (t + self.t_pad2) // self.window],
|
368 |
+
times,
|
369 |
+
index,
|
370 |
+
big_npy,
|
371 |
+
index_rate,
|
372 |
+
version,
|
373 |
+
protect,
|
374 |
+
)[self.t_pad_tgt : -self.t_pad_tgt]
|
375 |
+
)
|
376 |
+
else:
|
377 |
+
audio_opt.append(
|
378 |
+
self.vc(
|
379 |
+
model,
|
380 |
+
net_g,
|
381 |
+
sid,
|
382 |
+
audio_pad[s : t + self.t_pad2 + self.window],
|
383 |
+
None,
|
384 |
+
None,
|
385 |
+
times,
|
386 |
+
index,
|
387 |
+
big_npy,
|
388 |
+
index_rate,
|
389 |
+
version,
|
390 |
+
protect,
|
391 |
+
)[self.t_pad_tgt : -self.t_pad_tgt]
|
392 |
+
)
|
393 |
+
s = t
|
394 |
+
if if_f0 == 1:
|
395 |
+
audio_opt.append(
|
396 |
+
self.vc(
|
397 |
+
model,
|
398 |
+
net_g,
|
399 |
+
sid,
|
400 |
+
audio_pad[t:],
|
401 |
+
pitch[:, t // self.window :] if t is not None else pitch,
|
402 |
+
pitchf[:, t // self.window :] if t is not None else pitchf,
|
403 |
+
times,
|
404 |
+
index,
|
405 |
+
big_npy,
|
406 |
+
index_rate,
|
407 |
+
version,
|
408 |
+
protect,
|
409 |
+
)[self.t_pad_tgt : -self.t_pad_tgt]
|
410 |
+
)
|
411 |
+
else:
|
412 |
+
audio_opt.append(
|
413 |
+
self.vc(
|
414 |
+
model,
|
415 |
+
net_g,
|
416 |
+
sid,
|
417 |
+
audio_pad[t:],
|
418 |
+
None,
|
419 |
+
None,
|
420 |
+
times,
|
421 |
+
index,
|
422 |
+
big_npy,
|
423 |
+
index_rate,
|
424 |
+
version,
|
425 |
+
protect,
|
426 |
+
)[self.t_pad_tgt : -self.t_pad_tgt]
|
427 |
+
)
|
428 |
+
audio_opt = np.concatenate(audio_opt)
|
429 |
+
if rms_mix_rate != 1:
|
430 |
+
audio_opt = change_rms(audio, 16000, audio_opt, tgt_sr, rms_mix_rate)
|
431 |
+
if resample_sr >= 16000 and tgt_sr != resample_sr:
|
432 |
+
audio_opt = librosa.resample(
|
433 |
+
audio_opt, orig_sr=tgt_sr, target_sr=resample_sr
|
434 |
+
)
|
435 |
+
audio_max = np.abs(audio_opt).max() / 0.99
|
436 |
+
max_int16 = 32768
|
437 |
+
if audio_max > 1:
|
438 |
+
max_int16 /= audio_max
|
439 |
+
audio_opt = (audio_opt * max_int16).astype(np.int16)
|
440 |
+
del pitch, pitchf, sid
|
441 |
+
if torch.cuda.is_available():
|
442 |
+
torch.cuda.empty_cache()
|
443 |
+
return audio_opt
|