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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# adapted for Zero GPU on Hugging Face
|
2 |
+
|
3 |
+
import spaces
|
4 |
+
|
5 |
import os
|
6 |
+
import glob
|
7 |
+
import json
|
8 |
+
import traceback
|
9 |
+
import logging
|
10 |
+
import gradio as gr
|
11 |
+
import numpy as np
|
12 |
+
import librosa
|
13 |
+
import torch
|
14 |
+
import asyncio
|
15 |
+
import ffmpeg
|
16 |
+
import subprocess
|
17 |
+
import sys
|
18 |
+
import io
|
19 |
+
import wave
|
20 |
+
from datetime import datetime
|
21 |
+
#from fairseq import checkpoint_utils
|
22 |
+
import urllib.request
|
23 |
+
import zipfile
|
24 |
+
import shutil
|
25 |
+
import gradio as gr
|
26 |
+
from textwrap import dedent
|
27 |
+
import pprint
|
28 |
+
import time
|
29 |
+
|
30 |
+
import re
|
31 |
+
import requests
|
32 |
+
import subprocess
|
33 |
+
from pathlib import Path
|
34 |
+
from scipy.io.wavfile import write
|
35 |
+
from scipy.io import wavfile
|
36 |
+
import soundfile as sf
|
37 |
+
|
38 |
+
from lib.infer_pack.models import (
|
39 |
+
SynthesizerTrnMs256NSFsid,
|
40 |
+
SynthesizerTrnMs256NSFsid_nono,
|
41 |
+
SynthesizerTrnMs768NSFsid,
|
42 |
+
SynthesizerTrnMs768NSFsid_nono,
|
43 |
+
)
|
44 |
+
from vc_infer_pipeline import VC
|
45 |
+
from config import Config
|
46 |
+
config = Config()
|
47 |
+
logging.getLogger("numba").setLevel(logging.WARNING)
|
48 |
+
spaces_hf = True #os.getenv("SYSTEM") == "spaces"
|
49 |
+
force_support = True
|
50 |
+
|
51 |
+
audio_mode = []
|
52 |
+
f0method_mode = []
|
53 |
+
f0method_info = ""
|
54 |
+
|
55 |
+
headers = {
|
56 |
+
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"
|
57 |
+
}
|
58 |
+
pattern = r'//www\.bilibili\.com/video[^"]*'
|
59 |
+
|
60 |
+
# Download models
|
61 |
+
|
62 |
+
#urllib.request.urlretrieve("https://download.openxlab.org.cn/models/Kevin676/rvc-models/weight/hubert_base", "hubert_base.pt")
|
63 |
+
urllib.request.urlretrieve("https://download.openxlab.org.cn/models/Kevin676/rvc-models/weight/rmvpe", "rmvpe.pt")
|
64 |
+
|
65 |
+
# Get zip name
|
66 |
+
|
67 |
+
pattern_zip = r"/([^/]+)\.zip$"
|
68 |
+
|
69 |
+
def get_file_name(url):
|
70 |
+
match = re.search(pattern_zip, url)
|
71 |
+
if match:
|
72 |
+
extracted_string = match.group(1)
|
73 |
+
return extracted_string
|
74 |
+
else:
|
75 |
+
raise Exception("没有找到AI歌手模型的zip压缩包。")
|
76 |
+
|
77 |
+
# Get RVC models
|
78 |
+
|
79 |
+
def extract_zip(extraction_folder, zip_name):
|
80 |
+
os.makedirs(extraction_folder)
|
81 |
+
with zipfile.ZipFile(zip_name, 'r') as zip_ref:
|
82 |
+
zip_ref.extractall(extraction_folder)
|
83 |
+
os.remove(zip_name)
|
84 |
+
|
85 |
+
index_filepath, model_filepath = None, None
|
86 |
+
for root, dirs, files in os.walk(extraction_folder):
|
87 |
+
for name in files:
|
88 |
+
if name.endswith('.index') and os.stat(os.path.join(root, name)).st_size > 1024 * 100:
|
89 |
+
index_filepath = os.path.join(root, name)
|
90 |
+
|
91 |
+
if name.endswith('.pth') and os.stat(os.path.join(root, name)).st_size > 1024 * 1024 * 40:
|
92 |
+
model_filepath = os.path.join(root, name)
|
93 |
+
|
94 |
+
if not model_filepath:
|
95 |
+
raise Exception(f'No .pth model file was found in the extracted zip. Please check {extraction_folder}.')
|
96 |
+
|
97 |
+
# move model and index file to extraction folder
|
98 |
+
os.rename(model_filepath, os.path.join(extraction_folder, os.path.basename(model_filepath)))
|
99 |
+
if index_filepath:
|
100 |
+
os.rename(index_filepath, os.path.join(extraction_folder, os.path.basename(index_filepath)))
|
101 |
+
|
102 |
+
# remove any unnecessary nested folders
|
103 |
+
for filepath in os.listdir(extraction_folder):
|
104 |
+
if os.path.isdir(os.path.join(extraction_folder, filepath)):
|
105 |
+
shutil.rmtree(os.path.join(extraction_folder, filepath))
|
106 |
+
|
107 |
+
# Get username in OpenXLab
|
108 |
+
|
109 |
+
def get_username(url):
|
110 |
+
match_username = re.search(r'models/(.*?)/', url)
|
111 |
+
if match_username:
|
112 |
+
result = match_username.group(1)
|
113 |
+
return result
|
114 |
+
|
115 |
+
def download_online_model(url, dir_name):
|
116 |
+
if url.startswith('https://download.openxlab.org.cn/models/'):
|
117 |
+
zip_path = get_username(url) + "-" + get_file_name(url)
|
118 |
+
else:
|
119 |
+
zip_path = get_file_name(url)
|
120 |
+
if not os.path.exists(zip_path):
|
121 |
+
try:
|
122 |
+
zip_name = url.split('/')[-1]
|
123 |
+
extraction_folder = os.path.join(zip_path, dir_name)
|
124 |
+
if os.path.exists(extraction_folder):
|
125 |
+
raise Exception(f'Voice model directory {dir_name} already exists! Choose a different name for your voice model.')
|
126 |
+
|
127 |
+
if 'pixeldrain.com' in url:
|
128 |
+
url = f'https://pixeldrain.com/api/file/{zip_name}'
|
129 |
+
|
130 |
+
urllib.request.urlretrieve(url, zip_name)
|
131 |
+
|
132 |
+
extract_zip(extraction_folder, zip_name)
|
133 |
+
#return f'[√] {dir_name} Model successfully downloaded!'
|
134 |
+
|
135 |
+
except Exception as e:
|
136 |
+
raise Exception(str(e))
|
137 |
+
|
138 |
+
#Get bilibili BV id
|
139 |
+
|
140 |
+
def get_bilibili_video_id(url):
|
141 |
+
match = re.search(r'/video/([a-zA-Z0-9]+)/', url)
|
142 |
+
extracted_value = match.group(1)
|
143 |
+
return extracted_value
|
144 |
+
|
145 |
+
# Get bilibili audio
|
146 |
+
def find_first_appearance_with_neighborhood(text, pattern):
|
147 |
+
match = re.search(pattern, text)
|
148 |
+
|
149 |
+
if match:
|
150 |
+
return match.group()
|
151 |
+
else:
|
152 |
+
return None
|
153 |
+
|
154 |
+
def search_bilibili(keyword):
|
155 |
+
if keyword.startswith("BV"):
|
156 |
+
req = requests.get("https://search.bilibili.com/all?keyword={}&duration=1".format(keyword), headers=headers).text
|
157 |
+
else:
|
158 |
+
req = requests.get("https://search.bilibili.com/all?keyword={}&duration=1&tids=3&page=1".format(keyword), headers=headers).text
|
159 |
+
|
160 |
+
video_link = "https:" + find_first_appearance_with_neighborhood(req, pattern)
|
161 |
+
|
162 |
+
return video_link
|
163 |
+
|
164 |
+
# Save bilibili audio
|
165 |
+
|
166 |
+
def get_response(html_url):
|
167 |
+
headers = {
|
168 |
+
"referer": "https://www.bilibili.com/",
|
169 |
+
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"
|
170 |
+
}
|
171 |
+
response = requests.get(html_url, headers=headers)
|
172 |
+
return response
|
173 |
+
|
174 |
+
def get_video_info(html_url):
|
175 |
+
response = get_response(html_url)
|
176 |
+
html_data = re.findall('<script>window.__playinfo__=(.*?)</script>', response.text)[0]
|
177 |
+
json_data = json.loads(html_data)
|
178 |
+
if json_data['data']['dash']['audio'][0]['backupUrl']!=None:
|
179 |
+
audio_url = json_data['data']['dash']['audio'][0]['backupUrl'][0]
|
180 |
+
else:
|
181 |
+
audio_url = json_data['data']['dash']['audio'][0]['baseUrl']
|
182 |
+
return audio_url
|
183 |
+
|
184 |
+
def save_audio(title, audio_url):
|
185 |
+
audio_content = get_response(audio_url).content
|
186 |
+
with open(title + '.wav', mode='wb') as f:
|
187 |
+
f.write(audio_content)
|
188 |
+
print("音乐内容保存完成")
|
189 |
+
|
190 |
+
|
191 |
+
# Use UVR-HP5/2
|
192 |
+
|
193 |
+
urllib.request.urlretrieve("https://download.openxlab.org.cn/models/Kevin676/rvc-models/weight/UVR-HP2.pth", "uvr5/uvr_model/UVR-HP2.pth")
|
194 |
+
urllib.request.urlretrieve("https://download.openxlab.org.cn/models/Kevin676/rvc-models/weight/UVR-HP5.pth", "uvr5/uvr_model/UVR-HP5.pth")
|
195 |
+
#urllib.request.urlretrieve("https://huggingface.co/fastrolling/uvr/resolve/main/Main_Models/5_HP-Karaoke-UVR.pth", "uvr5/uvr_model/UVR-HP5.pth")
|
196 |
+
|
197 |
+
from uvr5.vr import AudioPre
|
198 |
+
weight_uvr5_root = "uvr5/uvr_model"
|
199 |
+
uvr5_names = []
|
200 |
+
for name in os.listdir(weight_uvr5_root):
|
201 |
+
if name.endswith(".pth") or "onnx" in name:
|
202 |
+
uvr5_names.append(name.replace(".pth", ""))
|
203 |
+
|
204 |
+
func = AudioPre
|
205 |
+
pre_fun_hp2 = func(
|
206 |
+
agg=int(10),
|
207 |
+
model_path=os.path.join(weight_uvr5_root, "UVR-HP2.pth"),
|
208 |
+
device="cuda",
|
209 |
+
is_half=True,
|
210 |
+
)
|
211 |
+
|
212 |
+
pre_fun_hp5 = func(
|
213 |
+
agg=int(10),
|
214 |
+
model_path=os.path.join(weight_uvr5_root, "UVR-HP5.pth"),
|
215 |
+
device="cuda",
|
216 |
+
is_half=True,
|
217 |
+
)
|
218 |
+
|
219 |
+
# Separate vocals
|
220 |
+
@spaces.GPU(duration=80)
|
221 |
+
def youtube_downloader(
|
222 |
+
video_identifier,
|
223 |
+
filename,
|
224 |
+
split_model,
|
225 |
+
):
|
226 |
+
print(video_identifier)
|
227 |
+
video_info = get_video_info(video_identifier)
|
228 |
+
print(video_info)
|
229 |
+
audio_content = get_response(video_info).content
|
230 |
+
with open(filename.strip() + ".wav", mode="wb") as f:
|
231 |
+
f.write(audio_content)
|
232 |
+
audio_path = filename.strip() + ".wav"
|
233 |
+
|
234 |
+
# make dir output
|
235 |
+
os.makedirs("output", exist_ok=True)
|
236 |
+
|
237 |
+
if split_model=="UVR-HP2":
|
238 |
+
pre_fun = pre_fun_hp2
|
239 |
+
else:
|
240 |
+
pre_fun = pre_fun_hp5
|
241 |
+
|
242 |
+
pre_fun._path_audio_(audio_path, f"./output/{split_model}/{filename}/", f"./output/{split_model}/{filename}/", "wav")
|
243 |
+
os.remove(filename.strip()+".wav")
|
244 |
+
|
245 |
+
return f"./output/{split_model}/{filename}/vocal_{filename}.wav_10.wav", f"./output/{split_model}/{filename}/instrument_{filename}.wav_10.wav"
|
246 |
+
|
247 |
+
# Original code
|
248 |
+
|
249 |
+
if force_support is False or spaces_hf is True:
|
250 |
+
if spaces_hf is True:
|
251 |
+
audio_mode = ["Upload audio", "TTS Audio"]
|
252 |
+
else:
|
253 |
+
audio_mode = ["Input path", "Upload audio", "TTS Audio"]
|
254 |
+
f0method_mode = ["pm", "harvest"]
|
255 |
+
f0method_info = "PM is fast, Harvest is good but extremely slow, Rvmpe is alternative to harvest (might be better). (Default: PM)"
|
256 |
+
else:
|
257 |
+
audio_mode = ["Input path", "Upload audio", "Youtube", "TTS Audio"]
|
258 |
+
f0method_mode = ["pm", "harvest", "crepe"]
|
259 |
+
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)"
|
260 |
+
|
261 |
+
if os.path.isfile("rmvpe.pt"):
|
262 |
+
f0method_mode.insert(2, "rmvpe")
|
263 |
+
|
264 |
+
def create_vc_fn(model_name, tgt_sr, net_g, vc, if_f0, version, file_index):
|
265 |
+
def vc_fn(
|
266 |
+
vc_audio_mode,
|
267 |
+
vc_input,
|
268 |
+
vc_upload,
|
269 |
+
tts_text,
|
270 |
+
tts_voice,
|
271 |
+
f0_up_key,
|
272 |
+
f0_method,
|
273 |
+
index_rate,
|
274 |
+
filter_radius,
|
275 |
+
resample_sr,
|
276 |
+
rms_mix_rate,
|
277 |
+
protect,
|
278 |
+
):
|
279 |
+
try:
|
280 |
+
logs = []
|
281 |
+
print(f"Converting using {model_name}...")
|
282 |
+
logs.append(f"Converting using {model_name}...")
|
283 |
+
yield "\n".join(logs), None
|
284 |
+
if vc_audio_mode == "Input path" or "Youtube" and vc_input != "":
|
285 |
+
audio, sr = librosa.load(vc_input, sr=16000, mono=True)
|
286 |
+
elif vc_audio_mode == "Upload audio":
|
287 |
+
if vc_upload is None:
|
288 |
+
return "You need to upload an audio", None
|
289 |
+
sampling_rate, audio = vc_upload
|
290 |
+
duration = audio.shape[0] / sampling_rate
|
291 |
+
if duration > 20 and spaces_hf:
|
292 |
+
return "Please upload an audio file that is less than 20 seconds. If you need to generate a longer audio file, please use Colab.", None
|
293 |
+
audio = (audio / np.iinfo(audio.dtype).max).astype(np.float32)
|
294 |
+
if len(audio.shape) > 1:
|
295 |
+
audio = librosa.to_mono(audio.transpose(1, 0))
|
296 |
+
if sampling_rate != 16000:
|
297 |
+
audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=16000)
|
298 |
+
times = [0, 0, 0]
|
299 |
+
f0_up_key = int(f0_up_key)
|
300 |
+
audio_opt = vc.pipeline(
|
301 |
+
hubert_model,
|
302 |
+
net_g,
|
303 |
+
0,
|
304 |
+
audio,
|
305 |
+
vc_input,
|
306 |
+
times,
|
307 |
+
f0_up_key,
|
308 |
+
f0_method,
|
309 |
+
file_index,
|
310 |
+
# file_big_npy,
|
311 |
+
index_rate,
|
312 |
+
if_f0,
|
313 |
+
filter_radius,
|
314 |
+
tgt_sr,
|
315 |
+
resample_sr,
|
316 |
+
rms_mix_rate,
|
317 |
+
version,
|
318 |
+
protect,
|
319 |
+
f0_file=None,
|
320 |
+
)
|
321 |
+
info = f"[{datetime.now().strftime('%Y-%m-%d %H:%M')}]: npy: {times[0]}, f0: {times[1]}s, infer: {times[2]}s"
|
322 |
+
print(f"{model_name} | {info}")
|
323 |
+
logs.append(f"Successfully Convert {model_name}\n{info}")
|
324 |
+
yield "\n".join(logs), (tgt_sr, audio_opt)
|
325 |
+
except Exception as err:
|
326 |
+
info = traceback.format_exc()
|
327 |
+
print(info)
|
328 |
+
print(f"Error when using {model_name}.\n{str(err)}")
|
329 |
+
yield info, None
|
330 |
+
return vc_fn
|
331 |
+
|
332 |
+
def combine_vocal_and_inst(model_name, song_name, song_id, split_model, cover_song, vocal_volume, inst_volume):
|
333 |
+
#samplerate, data = wavfile.read(cover_song)
|
334 |
+
vocal_path = cover_song #f"output/{split_model}/{song_id}/vocal_{song_id}.wav_10.wav"
|
335 |
+
output_path = song_name.strip() + "-AI-" + ''.join(os.listdir(f"{model_name}")).strip() + "翻唱版.mp3"
|
336 |
+
inst_path = f"output/{split_model}/{song_id}/instrument_{song_id}.wav_10.wav"
|
337 |
+
#with wave.open(vocal_path, "w") as wave_file:
|
338 |
+
#wave_file.setnchannels(1)
|
339 |
+
#wave_file.setsampwidth(2)
|
340 |
+
#wave_file.setframerate(samplerate)
|
341 |
+
#wave_file.writeframes(data.tobytes())
|
342 |
+
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}'
|
343 |
+
result = subprocess.run(command.split(), stdout=subprocess.PIPE)
|
344 |
+
print(result.stdout.decode())
|
345 |
+
return output_path
|
346 |
+
|
347 |
+
'''
|
348 |
+
def load_hubert():
|
349 |
+
from fairseq import checkpoint_utils
|
350 |
+
|
351 |
+
global hubert_model
|
352 |
+
models, _, _ = checkpoint_utils.load_model_ensemble_and_task(
|
353 |
+
["hubert_base.pt"],
|
354 |
+
suffix="",
|
355 |
+
)
|
356 |
+
hubert_model = models[0]
|
357 |
+
hubert_model = hubert_model.to(config.device)
|
358 |
+
if config.is_half:
|
359 |
+
hubert_model = hubert_model.half()
|
360 |
+
else:
|
361 |
+
hubert_model = hubert_model.float()
|
362 |
+
hubert_model.eval()
|
363 |
+
'''
|
364 |
+
|
365 |
+
def load_hubert():
|
366 |
+
global hubert_model
|
367 |
+
|
368 |
+
# Load the model state dictionary from the file
|
369 |
+
state_dict = torch.load("hubert_base.pt", map_location="cpu")
|
370 |
+
|
371 |
+
# Initialize the model
|
372 |
+
from fairseq.models.hubert import HubertModel
|
373 |
+
hubert_model = HubertModel.build_model(state_dict['args'], task=None)
|
374 |
+
|
375 |
+
# Load the state dictionary into the model
|
376 |
+
hubert_model.load_state_dict(state_dict['model'])
|
377 |
+
|
378 |
+
# Move the model to the desired device
|
379 |
+
hubert_model = hubert_model.to("cpu")
|
380 |
+
|
381 |
+
# Set the model to half precision if required
|
382 |
+
if config.is_half:
|
383 |
+
hubert_model = hubert_model.half()
|
384 |
+
else:
|
385 |
+
hubert_model = hubert_model.float()
|
386 |
+
|
387 |
+
# Set the model to evaluation mode
|
388 |
+
hubert_model.eval()
|
389 |
+
|
390 |
+
load_hubert()
|
391 |
+
|
392 |
+
def rvc_models(model_name):
|
393 |
+
global vc, net_g, index_files, tgt_sr, version
|
394 |
+
categories = []
|
395 |
+
models = []
|
396 |
+
for w_root, w_dirs, _ in os.walk(f"{model_name}"):
|
397 |
+
model_count = 1
|
398 |
+
for sub_dir in w_dirs:
|
399 |
+
pth_files = glob.glob(f"{model_name}/{sub_dir}/*.pth")
|
400 |
+
index_files = glob.glob(f"{model_name}/{sub_dir}/*.index")
|
401 |
+
if pth_files == []:
|
402 |
+
print(f"Model [{model_count}/{len(w_dirs)}]: No Model file detected, skipping...")
|
403 |
+
continue
|
404 |
+
cpt = torch.load(pth_files[0])
|
405 |
+
tgt_sr = cpt["config"][-1]
|
406 |
+
cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] # n_spk
|
407 |
+
if_f0 = cpt.get("f0", 1)
|
408 |
+
version = cpt.get("version", "v1")
|
409 |
+
if version == "v1":
|
410 |
+
if if_f0 == 1:
|
411 |
+
net_g = SynthesizerTrnMs256NSFsid(*cpt["config"], is_half=config.is_half)
|
412 |
+
else:
|
413 |
+
net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"])
|
414 |
+
model_version = "V1"
|
415 |
+
elif version == "v2":
|
416 |
+
if if_f0 == 1:
|
417 |
+
net_g = SynthesizerTrnMs768NSFsid(*cpt["config"], is_half=config.is_half)
|
418 |
+
else:
|
419 |
+
net_g = SynthesizerTrnMs768NSFsid_nono(*cpt["config"])
|
420 |
+
model_version = "V2"
|
421 |
+
del net_g.enc_q
|
422 |
+
print(net_g.load_state_dict(cpt["weight"], strict=False))
|
423 |
+
net_g.eval().to(config.device)
|
424 |
+
if config.is_half:
|
425 |
+
net_g = net_g.half()
|
426 |
+
else:
|
427 |
+
net_g = net_g.float()
|
428 |
+
vc = VC(tgt_sr, config)
|
429 |
+
if index_files == []:
|
430 |
+
print("Warning: No Index file detected!")
|
431 |
+
index_info = "None"
|
432 |
+
model_index = ""
|
433 |
+
else:
|
434 |
+
index_info = index_files[0]
|
435 |
+
model_index = index_files[0]
|
436 |
+
print(f"Model loaded [{model_count}/{len(w_dirs)}]: {index_files[0]} / {index_info} | ({model_version})")
|
437 |
+
model_count += 1
|
438 |
+
models.append((index_files[0][:-4], index_files[0][:-4], "", "", model_version, create_vc_fn(index_files[0], tgt_sr, net_g, vc, if_f0, version, model_index)))
|
439 |
+
categories.append(["Models", "", models])
|
440 |
+
return vc, net_g, index_files, tgt_sr, version
|
441 |
+
|
442 |
+
#load_hubert()
|
443 |
+
|
444 |
+
singers="您的专属AI歌手阵容:"
|
445 |
+
|
446 |
+
@spaces.GPU(duration=60)
|
447 |
+
def infer_gpu(hubert_model, net_g, audio, f0_up_key, index_file, tgt_sr, version, f0_file=None):
|
448 |
+
return vc.pipeline(
|
449 |
+
hubert_model,
|
450 |
+
net_g,
|
451 |
+
0,
|
452 |
+
audio,
|
453 |
+
"",
|
454 |
+
[0, 0, 0],
|
455 |
+
f0_up_key,
|
456 |
+
"rmvpe",
|
457 |
+
index_file,
|
458 |
+
0.7,
|
459 |
+
1,
|
460 |
+
3,
|
461 |
+
tgt_sr,
|
462 |
+
0,
|
463 |
+
0.25,
|
464 |
+
version,
|
465 |
+
0.33,
|
466 |
+
f0_file=None,
|
467 |
+
)
|
468 |
+
|
469 |
+
def rvc_infer_music(url, model_name, song_name, split_model, f0_up_key, vocal_volume, inst_volume):
|
470 |
+
#load_hubert()
|
471 |
+
#print(hubert_model)
|
472 |
+
url = url.strip().replace(" ", "")
|
473 |
+
model_name = model_name.strip().replace(" ", "")
|
474 |
+
if url.startswith('https://download.openxlab.org.cn/models/'):
|
475 |
+
zip_path = get_username(url) + "-" + get_file_name(url)
|
476 |
+
else:
|
477 |
+
zip_path = get_file_name(url)
|
478 |
+
global singers
|
479 |
+
if model_name not in singers:
|
480 |
+
singers = singers+ ' '+ model_name
|
481 |
+
download_online_model(url, model_name)
|
482 |
+
rvc_models(zip_path)
|
483 |
+
song_name = song_name.strip().replace(" ", "")
|
484 |
+
video_identifier = search_bilibili(song_name)
|
485 |
+
song_id = get_bilibili_video_id(video_identifier)
|
486 |
+
|
487 |
+
if os.path.isdir(f"./output/{split_model}/{song_id}")==True:
|
488 |
+
audio, sr = librosa.load(f"./output/{split_model}/{song_id}/vocal_{song_id}.wav_10.wav", sr=16000, mono=True)
|
489 |
+
song_infer = infer_gpu(hubert_model, net_g, audio, f0_up_key, index_files[0], tgt_sr, version, f0_file=None)
|
490 |
+
else:
|
491 |
+
audio, sr = librosa.load(youtube_downloader(video_identifier, song_id, split_model)[0], sr=16000, mono=True)
|
492 |
+
song_infer = infer_gpu(hubert_model, net_g, audio, f0_up_key, index_files[0], tgt_sr, version, f0_file=None)
|
493 |
+
|
494 |
+
sf.write(song_name.strip()+zip_path+"AI翻唱.wav", song_infer, tgt_sr)
|
495 |
+
output_full_song = combine_vocal_and_inst(zip_path, song_name.strip(), song_id, split_model, song_name.strip()+zip_path+"AI翻唱.wav", vocal_volume, inst_volume)
|
496 |
+
os.remove(song_name.strip()+zip_path+"AI翻唱.wav")
|
497 |
+
return output_full_song, singers
|
498 |
+
|
499 |
+
app = gr.Blocks(theme="JohnSmith9982/small_and_pretty")
|
500 |
+
with app:
|
501 |
+
with gr.Tab("中文版"):
|
502 |
+
gr.Markdown("# <center>🌊💕🎶 滔滔AI,您的专属AI全明星乐团</center>")
|
503 |
+
gr.Markdown("## <center>🌟 只需一个歌曲名,全网AI歌手任您选择!随时随地,听我想听!</center>")
|
504 |
+
gr.Markdown("### <center>🤗 更多精彩应用,敬请关注[滔滔AI](http://www.talktalkai.com);相关问题欢迎在我们的[B站](https://space.bilibili.com/501495851)账号交流!滔滔AI,为爱滔滔!💕</center>")
|
505 |
+
with gr.Accordion("💡 一些AI歌手模型链接及使用说明(建议阅读)", open=False):
|
506 |
+
_ = f""" 任何能够在线下载的zip压缩包的链接都可以哦(zip压缩包只需包括AI歌手模型的.pth和.index文件,zip压缩包的链接需要以.zip作为后缀):
|
507 |
+
* Taylor Swift: https://download.openxlab.org.cn/models/Kevin676/rvc-models/weight/taylor.zip
|
508 |
+
* Blackpink Lisa: https://download.openxlab.org.cn/models/Kevin676/rvc-models/weight/Lisa.zip
|
509 |
+
* AI派蒙: https://download.openxlab.org.cn/models/Kevin676/rvc-models/weight/paimon.zip
|
510 |
+
* AI孙燕姿: https://download.openxlab.org.cn/models/Kevin676/rvc-models/weight/syz.zip
|
511 |
+
* AI[一清清清](https://www.bilibili.com/video/BV1wV411u74P)(推荐使用[OpenXLab](https://openxlab.org.cn/models)存放模型zip压缩包): https://download.openxlab.org.cn/models/Kevin676/rvc-models/weight/yiqing.zip\n
|
512 |
+
说明1:点击“一键开启AI翻唱之旅吧!”按钮即可使用!✨\n
|
513 |
+
说明2:一般情况下,男声演唱的歌曲转换成AI女声演唱需要升调,反之则需要降调;在“歌曲人声升降调”模块可以调整\n
|
514 |
+
说明3:对于同一个AI歌手模型或者同一首歌曲,第一次的运行时间会比较长(大约1分钟),请您耐心等待;之后的运行时间会大大缩短哦!\n
|
515 |
+
说明4:您之前下载过的模型会在“已下载的AI歌手全明星阵容”模块出现\n
|
516 |
+
说明5:此程序使用 [RVC](https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI) AI歌手模型,感谢[作者](https://space.bilibili.com/5760446)的开源!RVC模型训练教程参见[视频](https://www.bilibili.com/video/BV1mX4y1C7w4)\n
|
517 |
+
🤗 我们正在创建一个完全开源、共建共享的AI歌手模型社区,让更多的人感受到AI音乐的乐趣与魅力!请关注我们的[B站](https://space.bilibili.com/501495851)账号,了解社区的最新进展!合作联系:talktalkai.kevin@gmail.com
|
518 |
+
"""
|
519 |
+
gr.Markdown(dedent(_))
|
520 |
+
|
521 |
+
with gr.Row():
|
522 |
+
with gr.Column():
|
523 |
+
inp1 = gr.Textbox(label="请输入AI歌手模型链接", info="模型需要是含有.pth和.index文件的zip压缩包", lines=2, value="https://download.openxlab.org.cn/models/Kevin676/rvc-models/weight/taylor.zip", placeholder="https://download.openxlab.org.cn/models/Kevin676/rvc-models/weight/taylor.zip")
|
524 |
+
with gr.Column():
|
525 |
+
inp2 = gr.Textbox(label="请给您的AI歌手起一个昵称吧", info="可自定义名称,但名称中不能有特殊符号", lines=1, value="AI Taylor", placeholder="AI Taylor")
|
526 |
+
inp3 = gr.Textbox(label="请输入您需要AI翻唱的歌曲名", info="如果您对搜索结果不满意,可在歌曲名后加上“无损”或“歌手的名字”等关键词;歌曲名中不能有特殊符号", lines=1, value="小幸运", placeholder="小幸运")
|
527 |
+
with gr.Row():
|
528 |
+
inp4 = gr.Dropdown(label="请选择用于分离伴奏的模型", choices=["UVR-HP2", "UVR-HP5"], value="UVR-HP5", visible=False)
|
529 |
+
inp5 = gr.Slider(label="歌曲人声升降调", info="默认为0,+2为升高2个key,以此类推", minimum=-12, maximum=12, value=0, step=1)
|
530 |
+
inp6 = gr.Slider(label="歌曲人声音量调节", info="默认为1,等于0时为静音", minimum=0, maximum=3, value=1, step=0.2)
|
531 |
+
inp7 = gr.Slider(label="歌曲伴奏音量调节", info="默认为1,等于0时为静音", minimum=0, maximum=3, value=1, step=0.2)
|
532 |
+
btn = gr.Button("一键开启AI翻唱之旅吧!💕", variant="primary")
|
533 |
+
with gr.Row():
|
534 |
+
output_song = gr.Audio(label="AI歌手为您倾情演绎")
|
535 |
+
singer_list = gr.Textbox(label="已下载的AI歌手全明星阵容")
|
536 |
+
|
537 |
+
btn.click(fn=rvc_infer_music, inputs=[inp1, inp2, inp3, inp4, inp5, inp6, inp7], outputs=[output_song, singer_list])
|
538 |
+
|
539 |
+
gr.Markdown("### <center>注意❗:请不要生成会对个人以及组织造成侵害的内容,此程序仅供科研、学习及个人娱乐使用。请自觉合规使用此程序,程序开发者不负有任何责任。</center>")
|
540 |
+
gr.HTML('''
|
541 |
+
<div class="footer">
|
542 |
+
<p>🌊🏞️🎶 - 江水东流急,滔滔无尽声。 明·顾璘
|
543 |
+
</p>
|
544 |
+
</div>
|
545 |
+
''')
|
546 |
+
with gr.Tab("EN"):
|
547 |
+
gr.Markdown("# <center>🌊💕🎶 TalkTalkAI - Best AI song cover generator ever</center>")
|
548 |
+
gr.Markdown("## <center>🌟 Provide the name of a song and our application running on A100 will handle everything else!</center>")
|
549 |
+
gr.Markdown("### <center>🤗 [TalkTalkAI](http://www.talktalkai.com/), let everyone enjoy a better life through human-centered AI💕</center>")
|
550 |
+
with gr.Accordion("💡 Some AI singers you can try", open=False):
|
551 |
+
_ = f""" Any Zip file that you can download online will be fine (The Zip file should contain .pth and .index files):
|
552 |
+
* AI Taylor Swift: https://download.openxlab.org.cn/models/Kevin676/rvc-models/weight/taylor.zip
|
553 |
+
* AI Blackpink Lisa: https://download.openxlab.org.cn/models/Kevin676/rvc-models/weight/Lisa.zip
|
554 |
+
* AI Paimon: https://download.openxlab.org.cn/models/Kevin676/rvc-models/weight/paimon.zip
|
555 |
+
* AI Stefanie Sun: https://download.openxlab.org.cn/models/Kevin676/rvc-models/weight/syz.zip
|
556 |
+
* AI[一清清清](https://www.bilibili.com/video/BV1wV411u74P): https://download.openxlab.org.cn/models/Kevin676/rvc-models/weight/yiqing.zip\n
|
557 |
+
"""
|
558 |
+
gr.Markdown(dedent(_))
|
559 |
+
|
560 |
+
with gr.Row():
|
561 |
+
with gr.Column():
|
562 |
+
inp1_en = gr.Textbox(label="The Zip file of an AI singer", info="The Zip file should contain .pth and .index files", lines=2, value="https://download.openxlab.org.cn/models/Kevin676/rvc-models/weight/taylor.zip", placeholder="https://download.openxlab.org.cn/models/Kevin676/rvc-models/weight/taylor.zip")
|
563 |
+
with gr.Column():
|
564 |
+
inp2_en = gr.Textbox(label="The name of your AI singer", lines=1, value="AI Taylor", placeholder="AI Taylor")
|
565 |
+
inp3_en = gr.Textbox(label="The name of a song", lines=1, value="Hotel California Eagles", placeholder="Hotel California Eagles")
|
566 |
+
with gr.Row():
|
567 |
+
inp4_en = gr.Dropdown(label="UVR models", choices=["UVR-HP2", "UVR-HP5"], value="UVR-HP5", visible=False)
|
568 |
+
inp5_en = gr.Slider(label="Transpose", info="0 from man to man (or woman to woman); 12 from man to woman and -12 from woman to man.", minimum=-12, maximum=12, value=0, step=1)
|
569 |
+
inp6_en = gr.Slider(label="Vocal volume", info="Adjust vocal volume (Default: 1)", minimum=0, maximum=3, value=1, step=0.2)
|
570 |
+
inp7_en = gr.Slider(label="Instrument volume", info="Adjust instrument volume (Default: 1)", minimum=0, maximum=3, value=1, step=0.2)
|
571 |
+
btn_en = gr.Button("Convert💕", variant="primary")
|
572 |
+
with gr.Row():
|
573 |
+
output_song_en = gr.Audio(label="AI song cover")
|
574 |
+
singer_list_en = gr.Textbox(label="The AI singers you have")
|
575 |
+
|
576 |
+
btn_en.click(fn=rvc_infer_music, inputs=[inp1_en, inp2_en, inp3_en, inp4_en, inp5_en, inp6_en, inp7_en], outputs=[output_song_en, singer_list_en])
|
577 |
+
|
578 |
+
|
579 |
+
gr.HTML('''
|
580 |
+
<div class="footer">
|
581 |
+
<p>🤗 - Stay tuned! The best is yet to come.
|
582 |
+
</p>
|
583 |
+
<p>📧 - Contact us: talktalkai.kevin@gmail.com
|
584 |
+
</p>
|
585 |
+
</div>
|
586 |
+
''')
|
587 |
+
|
588 |
+
app.queue(max_size=40, api_open=False)
|
589 |
+
app.launch(max_threads=400, show_error=True)
|