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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import glob
3
+ import json
4
+ import traceback
5
+ import logging
6
+ import gradio as gr
7
+ import numpy as np
8
+ import librosa
9
+ import torch
10
+ import asyncio
11
+ import edge_tts
12
+ import yt_dlp
13
+ import ffmpeg
14
+ import subprocess
15
+ import sys
16
+ import io
17
+ import wave
18
+ from datetime import datetime
19
+ from fairseq import checkpoint_utils
20
+ from infer_pack.models import (
21
+ SynthesizerTrnMs256NSFsid,
22
+ SynthesizerTrnMs256NSFsid_nono,
23
+ SynthesizerTrnMs768NSFsid,
24
+ SynthesizerTrnMs768NSFsid_nono,
25
+ )
26
+ from vc_infer_pipeline import VC
27
+ from config import Config
28
+ config = Config()
29
+ logging.getLogger("numba").setLevel(logging.WARNING)
30
+
31
+ def create_vc_fn(tgt_sr, net_g, vc, if_f0, file_index):
32
+ def vc_fn(
33
+ vc_audio_mode,
34
+ vc_input,
35
+ vc_upload,
36
+ tts_text,
37
+ tts_voice,
38
+ spk_item,
39
+ f0_up_key,
40
+ f0_method,
41
+ index_rate,
42
+ filter_radius,
43
+ resample_sr,
44
+ rms_mix_rate,
45
+ protect,
46
+ ):
47
+ try:
48
+ if vc_audio_mode == "Input path" or "Youtube" and vc_input != "":
49
+ audio, sr = librosa.load(vc_input, sr=16000, mono=True)
50
+ elif vc_audio_mode == "Upload audio":
51
+ if vc_upload is None:
52
+ return "You need to upload an audio", None
53
+ sampling_rate, audio = vc_upload
54
+ duration = audio.shape[0] / sampling_rate
55
+ audio = (audio / np.iinfo(audio.dtype).max).astype(np.float32)
56
+ if len(audio.shape) > 1:
57
+ audio = librosa.to_mono(audio.transpose(1, 0))
58
+ if sampling_rate != 16000:
59
+ audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=16000)
60
+ elif vc_audio_mode == "TTS Audio":
61
+ if tts_text is None or tts_voice is None:
62
+ return "You need to enter text and select a voice", None
63
+ asyncio.run(edge_tts.Communicate(tts_text, "-".join(tts_voice.split('-')[:-1])).save("tts.mp3"))
64
+ audio, sr = librosa.load("tts.mp3", sr=16000, mono=True)
65
+ vc_input = "tts.mp3"
66
+ times = [0, 0, 0]
67
+ f0_up_key = int(f0_up_key)
68
+ audio_opt = vc.pipeline(
69
+ hubert_model,
70
+ net_g,
71
+ spk_item,
72
+ audio,
73
+ vc_input,
74
+ times,
75
+ f0_up_key,
76
+ f0_method,
77
+ file_index,
78
+ index_rate,
79
+ if_f0,
80
+ filter_radius,
81
+ tgt_sr,
82
+ resample_sr,
83
+ rms_mix_rate,
84
+ version,
85
+ protect,
86
+ f0_file=None,
87
+ )
88
+ info = f"[{datetime.now().strftime('%Y-%m-%d %H:%M')}]: npy: {times[0]}, f0: {times[1]}s, infer: {times[2]}s"
89
+ print(info)
90
+ return info, (tgt_sr, audio_opt)
91
+ except:
92
+ info = traceback.format_exc()
93
+ print(info)
94
+ return info, (None, None)
95
+ return vc_fn
96
+
97
+ def cut_vocal_and_inst(url, audio_provider, split_model):
98
+ if url != "":
99
+ if not os.path.exists("dl_audio"):
100
+ os.mkdir("dl_audio")
101
+ if audio_provider == "Youtube":
102
+ ydl_opts = {
103
+ 'format': 'bestaudio/best',
104
+ 'postprocessors': [{
105
+ 'key': 'FFmpegExtractAudio',
106
+ 'preferredcodec': 'wav',
107
+ }],
108
+ "outtmpl": 'dl_audio/youtube_audio',
109
+ }
110
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
111
+ ydl.download([url])
112
+ audio_path = "dl_audio/youtube_audio.wav"
113
+ else:
114
+ # Spotify doesnt work.
115
+ # Need to find other solution soon.
116
+ '''
117
+ command = f"spotdl download {url} --output dl_audio/.wav"
118
+ result = subprocess.run(command.split(), stdout=subprocess.PIPE)
119
+ print(result.stdout.decode())
120
+ audio_path = "dl_audio/spotify_audio.wav"
121
+ '''
122
+ if split_model == "htdemucs":
123
+ command = f"demucs --two-stems=vocals {audio_path} -o output"
124
+ result = subprocess.run(command.split(), stdout=subprocess.PIPE)
125
+ print(result.stdout.decode())
126
+ return "output/htdemucs/youtube_audio/vocals.wav", "output/htdemucs/youtube_audio/no_vocals.wav", audio_path, "output/htdemucs/youtube_audio/vocals.wav"
127
+ else:
128
+ command = f"demucs --two-stems=vocals -n mdx_extra_q {audio_path} -o output"
129
+ result = subprocess.run(command.split(), stdout=subprocess.PIPE)
130
+ print(result.stdout.decode())
131
+ return "output/mdx_extra_q/youtube_audio/vocals.wav", "output/mdx_extra_q/youtube_audio/no_vocals.wav", audio_path, "output/mdx_extra_q/youtube_audio/vocals.wav"
132
+ else:
133
+ raise gr.Error("URL Required!")
134
+ return None, None, None, None
135
+
136
+ def combine_vocal_and_inst(audio_data, audio_volume, split_model):
137
+ if not os.path.exists("output/result"):
138
+ os.mkdir("output/result")
139
+ vocal_path = "output/result/output.wav"
140
+ output_path = "output/result/combine.mp3"
141
+ if split_model == "htdemucs":
142
+ inst_path = "output/htdemucs/youtube_audio/no_vocals.wav"
143
+ else:
144
+ inst_path = "output/mdx_extra_q/youtube_audio/no_vocals.wav"
145
+ with wave.open(vocal_path, "w") as wave_file:
146
+ wave_file.setnchannels(1)
147
+ wave_file.setsampwidth(2)
148
+ wave_file.setframerate(audio_data[0])
149
+ wave_file.writeframes(audio_data[1].tobytes())
150
+ command = f'ffmpeg -y -i {inst_path} -i {vocal_path} -filter_complex [1:a]volume={audio_volume}dB[v];[0:a][v]amix=inputs=2:duration=longest -b:a 320k -c:a libmp3lame {output_path}'
151
+ result = subprocess.run(command.split(), stdout=subprocess.PIPE)
152
+ print(result.stdout.decode())
153
+ return output_path
154
+
155
+ def load_hubert():
156
+ global hubert_model
157
+ models, _, _ = checkpoint_utils.load_model_ensemble_and_task(
158
+ ["hubert_base.pt"],
159
+ suffix="",
160
+ )
161
+ hubert_model = models[0]
162
+ hubert_model = hubert_model.to(config.device)
163
+ if config.is_half:
164
+ hubert_model = hubert_model.half()
165
+ else:
166
+ hubert_model = hubert_model.float()
167
+ hubert_model.eval()
168
+
169
+ def change_audio_mode(vc_audio_mode):
170
+ if vc_audio_mode == "Input path":
171
+ return (
172
+ # Input & Upload
173
+ gr.Textbox.update(visible=True),
174
+ gr.Audio.update(visible=False),
175
+ # Youtube
176
+ gr.Dropdown.update(visible=False),
177
+ gr.Textbox.update(visible=False),
178
+ gr.Dropdown.update(visible=False),
179
+ gr.Button.update(visible=False),
180
+ gr.Audio.update(visible=False),
181
+ gr.Audio.update(visible=False),
182
+ gr.Audio.update(visible=False),
183
+ gr.Slider.update(visible=False),
184
+ gr.Audio.update(visible=False),
185
+ gr.Button.update(visible=False),
186
+ # TTS
187
+ gr.Textbox.update(visible=False),
188
+ gr.Dropdown.update(visible=False)
189
+ )
190
+ elif vc_audio_mode == "Upload audio":
191
+ return (
192
+ # Input & Upload
193
+ gr.Textbox.update(visible=False),
194
+ gr.Audio.update(visible=True),
195
+ # Youtube
196
+ gr.Dropdown.update(visible=False),
197
+ gr.Textbox.update(visible=False),
198
+ gr.Dropdown.update(visible=False),
199
+ gr.Button.update(visible=False),
200
+ gr.Audio.update(visible=False),
201
+ gr.Audio.update(visible=False),
202
+ gr.Audio.update(visible=False),
203
+ gr.Slider.update(visible=False),
204
+ gr.Audio.update(visible=False),
205
+ gr.Button.update(visible=False),
206
+ # TTS
207
+ gr.Textbox.update(visible=False),
208
+ gr.Dropdown.update(visible=False)
209
+ )
210
+ elif vc_audio_mode == "Youtube":
211
+ return (
212
+ # Input & Upload
213
+ gr.Textbox.update(visible=False),
214
+ gr.Audio.update(visible=False),
215
+ # Youtube
216
+ gr.Dropdown.update(visible=True),
217
+ gr.Textbox.update(visible=True),
218
+ gr.Dropdown.update(visible=True),
219
+ gr.Button.update(visible=True),
220
+ gr.Audio.update(visible=True),
221
+ gr.Audio.update(visible=True),
222
+ gr.Audio.update(visible=True),
223
+ gr.Slider.update(visible=True),
224
+ gr.Audio.update(visible=True),
225
+ gr.Button.update(visible=True),
226
+ # TTS
227
+ gr.Textbox.update(visible=False),
228
+ gr.Dropdown.update(visible=False)
229
+ )
230
+ elif vc_audio_mode == "TTS Audio":
231
+ return (
232
+ # Input & Upload
233
+ gr.Textbox.update(visible=False),
234
+ gr.Audio.update(visible=False),
235
+ # Youtube
236
+ gr.Dropdown.update(visible=False),
237
+ gr.Textbox.update(visible=False),
238
+ gr.Dropdown.update(visible=False),
239
+ gr.Button.update(visible=False),
240
+ gr.Audio.update(visible=False),
241
+ gr.Audio.update(visible=False),
242
+ gr.Audio.update(visible=False),
243
+ gr.Slider.update(visible=False),
244
+ gr.Audio.update(visible=False),
245
+ gr.Button.update(visible=False),
246
+ # TTS
247
+ gr.Textbox.update(visible=True),
248
+ gr.Dropdown.update(visible=True)
249
+ )
250
+ else:
251
+ return (
252
+ # Input & Upload
253
+ gr.Textbox.update(visible=False),
254
+ gr.Audio.update(visible=True),
255
+ # Youtube
256
+ gr.Dropdown.update(visible=False),
257
+ gr.Textbox.update(visible=False),
258
+ gr.Dropdown.update(visible=False),
259
+ gr.Button.update(visible=False),
260
+ gr.Audio.update(visible=False),
261
+ gr.Audio.update(visible=False),
262
+ gr.Audio.update(visible=False),
263
+ gr.Slider.update(visible=False),
264
+ gr.Audio.update(visible=False),
265
+ gr.Button.update(visible=False),
266
+ # TTS
267
+ gr.Textbox.update(visible=False),
268
+ gr.Dropdown.update(visible=False)
269
+ )
270
+
271
+ if __name__ == '__main__':
272
+ load_hubert()
273
+ categories = []
274
+ tts_voice_list = asyncio.get_event_loop().run_until_complete(edge_tts.list_voices())
275
+ voices = [f"{v['ShortName']}-{v['Gender']}" for v in tts_voice_list]
276
+ with open("weights/folder_info.json", "r", encoding="utf-8") as f:
277
+ folder_info = json.load(f)
278
+ for category_name, category_info in folder_info.items():
279
+ if not category_info['enable']:
280
+ continue
281
+ category_title = category_info['title']
282
+ category_folder = category_info['folder_path']
283
+ description = category_info['description']
284
+ models = []
285
+ with open(f"weights/{category_folder}/model_info.json", "r", encoding="utf-8") as f:
286
+ models_info = json.load(f)
287
+ for model_name, info in models_info.items():
288
+ if not info['enable']:
289
+ continue
290
+ model_title = info['title']
291
+ model_author = info.get("author", None)
292
+ model_cover = f"weights/{category_folder}/{model_name}/{info['cover']}"
293
+ model_index = f"weights/{category_folder}/{model_name}/{info['feature_retrieval_library']}"
294
+ cpt = torch.load(f"weights/{category_folder}/{model_name}/{model_name}.pth", map_location="cpu")
295
+ tgt_sr = cpt["config"][-1]
296
+ cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] # n_spk
297
+ if_f0 = cpt.get("f0", 1)
298
+ version = cpt.get("version", "v1")
299
+ if version == "v1":
300
+ if if_f0 == 1:
301
+ net_g = SynthesizerTrnMs256NSFsid(*cpt["config"], is_half=config.is_half)
302
+ else:
303
+ net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"])
304
+ nodel_version = "V1"
305
+ elif version == "v2":
306
+ if if_f0 == 1:
307
+ net_g = SynthesizerTrnMs768NSFsid(*cpt["config"], is_half=config.is_half)
308
+ else:
309
+ net_g = SynthesizerTrnMs768NSFsid_nono(*cpt["config"])
310
+ nodel_version = "V2"
311
+ del net_g.enc_q
312
+ print(net_g.load_state_dict(cpt["weight"], strict=False))
313
+ net_g.eval().to(config.device)
314
+ if config.is_half:
315
+ net_g = net_g.half()
316
+ else:
317
+ net_g = net_g.float()
318
+ vc = VC(tgt_sr, config)
319
+ print(f"Model loaded: {model_name}")
320
+ models.append((model_name, model_title, model_author, model_cover, nodel_version, create_vc_fn(tgt_sr, net_g, vc, if_f0, model_index)))
321
+ categories.append([category_title, category_folder, description, models])
322
+ with gr.Blocks() as app:
323
+ gr.Markdown(
324
+ "# <center> Multi Model RVC Inference\n"
325
+ "### <center> Support v2 Model\n"
326
+ "#### From [Retrieval-based-Voice-Conversion](https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI)\n"
327
+ "[![Original Repo](https://badgen.net/badge/icon/github?icon=github&label=Original%20Repo)](https://github.com/ArkanDash/Multi-Model-RVC-Inference)"
328
+ )
329
+ for (folder_title, folder, description, models) in categories:
330
+ with gr.TabItem(folder_title):
331
+ if description:
332
+ gr.Markdown(f"### <center> {description}")
333
+ with gr.Tabs():
334
+ if not models:
335
+ gr.Markdown("# <center> No Model Loaded.")
336
+ gr.Markdown("## <center> Please add model or fix your model path.")
337
+ continue
338
+ for (name, title, author, cover, model_version, vc_fn) in models:
339
+ with gr.TabItem(name):
340
+ with gr.Row():
341
+ gr.Markdown(
342
+ '<div align="center">'
343
+ f'<div>{title}</div>\n'+
344
+ f'<div>RVC {model_version} Model</div>\n'+
345
+ (f'<div>Model author: {author}</div>' if author else "")+
346
+ (f'<img style="width:auto;height:300px;" src="file/{cover}">' if cover else "")+
347
+ '</div>'
348
+ )
349
+ with gr.Row():
350
+ with gr.Column():
351
+ vc_audio_mode = gr.Dropdown(label="Input voice", choices=["Input path", "Upload audio", "Youtube", "TTS Audio"], allow_custom_value=False, value="Upload audio")
352
+ # Input and Upload
353
+ vc_input = gr.Textbox(label="Input audio path", visible=False)
354
+ vc_upload = gr.Audio(label="Upload audio file", visible=True, interactive=True)
355
+ # Youtube
356
+ vc_download_audio = gr.Dropdown(label="Provider", choices=["Youtube"], allow_custom_value=False, visible=False, value="Youtube", info="Select provider (Default: Youtube)")
357
+ 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=...")
358
+ vc_split_model = gr.Dropdown(label="Splitter Model", choices=["htdemucs", "mdx_extra_q"], allow_custom_value=False, visible=False, value="htdemucs", info="Select the splitter model (Default: htdemucs)")
359
+ vc_split = gr.Button("Split Audio", variant="primary", visible=False)
360
+ vc_vocal_preview = gr.Audio(label="Vocal Preview", visible=False)
361
+ vc_inst_preview = gr.Audio(label="Instrumental Preview", visible=False)
362
+ vc_audio_preview = gr.Audio(label="Audio Preview", visible=False)
363
+ # TTS
364
+ tts_text = gr.Textbox(visible=False, label="TTS text", info="Text to speech input")
365
+ tts_voice = gr.Dropdown(label="Edge-tts speaker", choices=voices, visible=False, allow_custom_value=False, value="en-US-AnaNeural-Female")
366
+ with gr.Column():
367
+ spk_item = gr.Slider(
368
+ minimum=0,
369
+ maximum=2333,
370
+ step=1,
371
+ label="Speaker ID",
372
+ info="(Default: 0)",
373
+ value=0,
374
+ interactive=True,
375
+ )
376
+ vc_transform0 = gr.Number(label="Transpose", value=0, info='Type "12" to change from male to female voice. Type "-12" to change female to male voice')
377
+ f0method0 = gr.Radio(
378
+ label="Pitch extraction algorithm",
379
+ info="PM is fast, Harvest is good but extremely slow, and Crepe effect is good but requires GPU (Default: PM)",
380
+ choices=["pm", "harvest", "crepe"],
381
+ value="pm",
382
+ interactive=True,
383
+ )
384
+ index_rate1 = gr.Slider(
385
+ minimum=0,
386
+ maximum=1,
387
+ label="Retrieval feature ratio",
388
+ info="(Default: 0.6)",
389
+ value=0.6,
390
+ interactive=True,
391
+ )
392
+ filter_radius0 = gr.Slider(
393
+ minimum=0,
394
+ maximum=7,
395
+ label="Apply Median Filtering",
396
+ info="The value represents the filter radius and can reduce breathiness.",
397
+ value=3,
398
+ step=1,
399
+ interactive=True,
400
+ )
401
+ resample_sr0 = gr.Slider(
402
+ minimum=0,
403
+ maximum=48000,
404
+ label="Resample the output audio",
405
+ info="Resample the output audio in post-processing to the final sample rate. Set to 0 for no resampling",
406
+ value=0,
407
+ step=1,
408
+ interactive=True,
409
+ )
410
+ rms_mix_rate0 = gr.Slider(
411
+ minimum=0,
412
+ maximum=1,
413
+ label="Volume Envelope",
414
+ 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",
415
+ value=1,
416
+ interactive=True,
417
+ )
418
+ protect0 = gr.Slider(
419
+ minimum=0,
420
+ maximum=0.5,
421
+ label="Voice Protection",
422
+ 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",
423
+ value=0.35,
424
+ step=0.01,
425
+ interactive=True,
426
+ )
427
+ with gr.Column():
428
+ vc_log = gr.Textbox(label="Output Information", interactive=False)
429
+ vc_output = gr.Audio(label="Output Audio", interactive=False)
430
+ vc_convert = gr.Button("Convert", variant="primary")
431
+ vc_volume = gr.Slider(
432
+ minimum=0,
433
+ maximum=10,
434
+ label="Vocal volume",
435
+ value=4,
436
+ interactive=True,
437
+ step=1,
438
+ info="Adjust vocal volume (Default: 4}",
439
+ visible=False
440
+ )
441
+ vc_combined_output = gr.Audio(label="Output Combined Audio", visible=False)
442
+ vc_combine = gr.Button("Combine",variant="primary", visible=False)
443
+ vc_convert.click(
444
+ fn=vc_fn,
445
+ inputs=[
446
+ vc_audio_mode,
447
+ vc_input,
448
+ vc_upload,
449
+ tts_text,
450
+ tts_voice,
451
+ spk_item,
452
+ vc_transform0,
453
+ f0method0,
454
+ index_rate1,
455
+ filter_radius0,
456
+ resample_sr0,
457
+ rms_mix_rate0,
458
+ protect0,
459
+ ],
460
+ outputs=[vc_log ,vc_output]
461
+ )
462
+ vc_split.click(
463
+ fn=cut_vocal_and_inst,
464
+ inputs=[vc_link, vc_download_audio, vc_split_model],
465
+ outputs=[vc_vocal_preview, vc_inst_preview, vc_audio_preview, vc_input]
466
+ )
467
+ vc_combine.click(
468
+ fn=combine_vocal_and_inst,
469
+ inputs=[vc_output, vc_volume, vc_split_model],
470
+ outputs=[vc_combined_output]
471
+ )
472
+ vc_audio_mode.change(
473
+ fn=change_audio_mode,
474
+ inputs=[vc_audio_mode],
475
+ outputs=[
476
+ vc_input,
477
+ vc_upload,
478
+ vc_download_audio,
479
+ vc_link,
480
+ vc_split_model,
481
+ vc_split,
482
+ vc_vocal_preview,
483
+ vc_inst_preview,
484
+ vc_audio_preview,
485
+ vc_volume,
486
+ vc_combined_output,
487
+ vc_combine,
488
+ tts_text,
489
+ tts_voice
490
+ ]
491
+ )
492
+ app.queue(concurrency_count=1, max_size=20, api_open=config.api).launch(share=config.colab)