Jarod Castillo commited on
Commit
02a998b
·
1 Parent(s): 15a1132
.gitignore CHANGED
@@ -21,7 +21,6 @@ dist/
21
  downloads/
22
  eggs/
23
  .eggs/
24
- lib/
25
  lib64/
26
  parts/
27
  sdist/
 
21
  downloads/
22
  eggs/
23
  .eggs/
 
24
  lib64/
25
  parts/
26
  sdist/
app.py CHANGED
@@ -16,7 +16,6 @@ from src.constants import ONNX_MODEL_PATH
16
  INPUT_FOLDER = "./datasets/input"
17
  OUTPUT_FOLDER = "./datasets/output"
18
 
19
-
20
  def main():
21
  # Set page configuration and theming
22
  st.set_page_config(
@@ -77,6 +76,17 @@ def main():
77
  # TODO: Is it encoding it wrong? Maybe fix it later.
78
  st.audio(data=vocals_array, format="audio/mpeg", sample_rate=samplerate)
79
 
 
 
 
 
 
 
 
 
 
 
80
 
81
  if __name__ == "__main__":
82
  main()
 
 
16
  INPUT_FOLDER = "./datasets/input"
17
  OUTPUT_FOLDER = "./datasets/output"
18
 
 
19
  def main():
20
  # Set page configuration and theming
21
  st.set_page_config(
 
76
  # TODO: Is it encoding it wrong? Maybe fix it later.
77
  st.audio(data=vocals_array, format="audio/mpeg", sample_rate=samplerate)
78
 
79
+ def test():
80
+ import soundfile
81
+ import numpy as np
82
+
83
+ audio, sr = soundfile.read(r'G:\AI-Personal-Projects\huggingface-repos\Vocal-Isolator\datasets\input\test-falsetto.wav')
84
+ mono_audio = np.mean(audio, axis=1)
85
+ print(audio)
86
+ print(len(audio))
87
+ print(mono_audio)
88
+ print(len(mono_audio))
89
 
90
  if __name__ == "__main__":
91
  main()
92
+ # test()
gradio_app.py ADDED
@@ -0,0 +1,678 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 lib.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
+ spaces = os.getenv("SYSTEM") == "spaces"
31
+ force_support = None
32
+ if config.unsupported is False:
33
+ if config.device == "mps" or config.device == "cpu":
34
+ force_support = False
35
+ else:
36
+ force_support = True
37
+
38
+ audio_mode = []
39
+ f0method_mode = []
40
+ f0method_info = ""
41
+
42
+ if force_support is False or spaces is True:
43
+ if spaces is True:
44
+ audio_mode = ["Upload audio", "TTS Audio"]
45
+ else:
46
+ audio_mode = ["Input path", "Upload audio", "TTS Audio"]
47
+ f0method_mode = ["pm", "harvest"]
48
+ f0method_info = "PM is fast, Harvest is good but extremely slow, Rvmpe is alternative to harvest (might be better). (Default: PM)"
49
+ else:
50
+ audio_mode = ["Input path", "Upload audio", "Youtube", "TTS Audio"]
51
+ f0method_mode = ["pm", "harvest", "crepe"]
52
+ 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)"
53
+
54
+ if os.path.isfile("rmvpe.pt"):
55
+ f0method_mode.insert(2, "rmvpe")
56
+
57
+ def create_vc_fn(model_name, tgt_sr, net_g, vc, if_f0, version, file_index):
58
+ def vc_fn(
59
+ vc_audio_mode,
60
+ vc_input,
61
+ vc_upload,
62
+ tts_text,
63
+ tts_voice,
64
+ f0_up_key,
65
+ f0_method,
66
+ index_rate,
67
+ filter_radius,
68
+ resample_sr,
69
+ rms_mix_rate,
70
+ protect,
71
+ ):
72
+ try:
73
+ logs = []
74
+ print(f"Converting using {model_name}...")
75
+ logs.append(f"Converting using {model_name}...")
76
+ yield "\n".join(logs), None
77
+ if vc_audio_mode == "Input path" or "Youtube" and vc_input != "":
78
+ audio, sr = librosa.load(vc_input, sr=16000, mono=True)
79
+ elif vc_audio_mode == "Upload audio":
80
+ if vc_upload is None:
81
+ return "You need to upload an audio", None
82
+ sampling_rate, audio = vc_upload
83
+ duration = audio.shape[0] / sampling_rate
84
+ if duration > 20 and spaces:
85
+ 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
86
+ audio = (audio / np.iinfo(audio.dtype).max).astype(np.float32)
87
+ if len(audio.shape) > 1:
88
+ audio = librosa.to_mono(audio.transpose(1, 0))
89
+ if sampling_rate != 16000:
90
+ audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=16000)
91
+ elif vc_audio_mode == "TTS Audio":
92
+ if len(tts_text) > 100 and spaces:
93
+ return "Text is too long", None
94
+ if tts_text is None or tts_voice is None:
95
+ return "You need to enter text and select a voice", None
96
+ asyncio.run(edge_tts.Communicate(tts_text, "-".join(tts_voice.split('-')[:-1])).save("tts.mp3"))
97
+ audio, sr = librosa.load("tts.mp3", sr=16000, mono=True)
98
+ vc_input = "tts.mp3"
99
+ times = [0, 0, 0]
100
+ f0_up_key = int(f0_up_key)
101
+ audio_opt = vc.pipeline(
102
+ hubert_model,
103
+ net_g,
104
+ 0,
105
+ audio,
106
+ vc_input,
107
+ times,
108
+ f0_up_key,
109
+ f0_method,
110
+ file_index,
111
+ # file_big_npy,
112
+ index_rate,
113
+ if_f0,
114
+ filter_radius,
115
+ tgt_sr,
116
+ resample_sr,
117
+ rms_mix_rate,
118
+ version,
119
+ protect,
120
+ f0_file=None,
121
+ )
122
+ info = f"[{datetime.now().strftime('%Y-%m-%d %H:%M')}]: npy: {times[0]}, f0: {times[1]}s, infer: {times[2]}s"
123
+ print(f"{model_name} | {info}")
124
+ logs.append(f"Successfully Convert {model_name}\n{info}")
125
+ yield "\n".join(logs), (tgt_sr, audio_opt)
126
+ except:
127
+ info = traceback.format_exc()
128
+ print(info)
129
+ yield info, None
130
+ return vc_fn
131
+
132
+ def load_model():
133
+ categories = []
134
+ if os.path.isfile("weights/folder_info.json"):
135
+ with open("weights/folder_info.json", "r", encoding="utf-8") as f:
136
+ folder_info = json.load(f)
137
+ for category_name, category_info in folder_info.items():
138
+ if not category_info['enable']:
139
+ continue
140
+ category_title = category_info['title']
141
+ category_folder = category_info['folder_path']
142
+ description = category_info['description']
143
+ models = []
144
+ with open(f"weights/{category_folder}/model_info.json", "r", encoding="utf-8") as f:
145
+ models_info = json.load(f)
146
+ for character_name, info in models_info.items():
147
+ if not info['enable']:
148
+ continue
149
+ model_title = info['title']
150
+ model_name = info['model_path']
151
+ model_author = info.get("author", None)
152
+ model_cover = f"weights/{category_folder}/{character_name}/{info['cover']}"
153
+ model_index = f"weights/{category_folder}/{character_name}/{info['feature_retrieval_library']}"
154
+ cpt = torch.load(f"weights/{category_folder}/{character_name}/{model_name}", map_location="cpu")
155
+ tgt_sr = cpt["config"][-1]
156
+ cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] # n_spk
157
+ if_f0 = cpt.get("f0", 1)
158
+ version = cpt.get("version", "v1")
159
+ if version == "v1":
160
+ if if_f0 == 1:
161
+ net_g = SynthesizerTrnMs256NSFsid(*cpt["config"], is_half=config.is_half)
162
+ else:
163
+ net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"])
164
+ model_version = "V1"
165
+ elif version == "v2":
166
+ if if_f0 == 1:
167
+ net_g = SynthesizerTrnMs768NSFsid(*cpt["config"], is_half=config.is_half)
168
+ else:
169
+ net_g = SynthesizerTrnMs768NSFsid_nono(*cpt["config"])
170
+ model_version = "V2"
171
+ del net_g.enc_q
172
+ print(net_g.load_state_dict(cpt["weight"], strict=False))
173
+ net_g.eval().to(config.device)
174
+ if config.is_half:
175
+ net_g = net_g.half()
176
+ else:
177
+ net_g = net_g.float()
178
+ vc = VC(tgt_sr, config)
179
+ print(f"Model loaded: {character_name} / {info['feature_retrieval_library']} | ({model_version})")
180
+ models.append((character_name, model_title, model_author, model_cover, model_version, create_vc_fn(model_name, tgt_sr, net_g, vc, if_f0, version, model_index)))
181
+ categories.append([category_title, category_folder, description, models])
182
+ else:
183
+ categories = []
184
+ return categories
185
+
186
+ def download_audio(url, audio_provider):
187
+ logs = []
188
+ if url == "":
189
+ raise gr.Error("URL Required!")
190
+ return "URL Required"
191
+ if not os.path.exists("dl_audio"):
192
+ os.mkdir("dl_audio")
193
+ if audio_provider == "Youtube":
194
+ logs.append("Downloading the audio...")
195
+ yield None, "\n".join(logs)
196
+ ydl_opts = {
197
+ 'noplaylist': True,
198
+ 'format': 'bestaudio/best',
199
+ 'postprocessors': [{
200
+ 'key': 'FFmpegExtractAudio',
201
+ 'preferredcodec': 'wav',
202
+ }],
203
+ "outtmpl": 'dl_audio/audio',
204
+ }
205
+ audio_path = "dl_audio/audio.wav"
206
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
207
+ ydl.download([url])
208
+ logs.append("Download Complete.")
209
+ yield audio_path, "\n".join(logs)
210
+
211
+ def cut_vocal_and_inst(split_model):
212
+ logs = []
213
+ logs.append("Starting the audio splitting process...")
214
+ yield "\n".join(logs), None, None, None, None
215
+ command = f"demucs --two-stems=vocals -n {split_model} dl_audio/audio.wav -o output"
216
+ result = subprocess.Popen(command.split(), stdout=subprocess.PIPE, text=True)
217
+ for line in result.stdout:
218
+ logs.append(line)
219
+ yield "\n".join(logs), None, None, None, None
220
+ print(result.stdout)
221
+ vocal = f"output/{split_model}/audio/vocals.wav"
222
+ inst = f"output/{split_model}/audio/no_vocals.wav"
223
+ logs.append("Audio splitting complete.")
224
+ yield "\n".join(logs), vocal, inst, vocal
225
+
226
+ def combine_vocal_and_inst(audio_data, vocal_volume, inst_volume, split_model):
227
+ if not os.path.exists("output/result"):
228
+ os.mkdir("output/result")
229
+ vocal_path = "output/result/output.wav"
230
+ output_path = "output/result/combine.mp3"
231
+ inst_path = f"output/{split_model}/audio/no_vocals.wav"
232
+ with wave.open(vocal_path, "w") as wave_file:
233
+ wave_file.setnchannels(1)
234
+ wave_file.setsampwidth(2)
235
+ wave_file.setframerate(audio_data[0])
236
+ wave_file.writeframes(audio_data[1].tobytes())
237
+ 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}'
238
+ result = subprocess.run(command.split(), stdout=subprocess.PIPE)
239
+ print(result.stdout.decode())
240
+ return output_path
241
+
242
+ def load_hubert():
243
+ global hubert_model
244
+ models, _, _ = checkpoint_utils.load_model_ensemble_and_task(
245
+ ["hubert_base.pt"],
246
+ suffix="",
247
+ )
248
+ hubert_model = models[0]
249
+ hubert_model = hubert_model.to(config.device)
250
+ if config.is_half:
251
+ hubert_model = hubert_model.half()
252
+ else:
253
+ hubert_model = hubert_model.float()
254
+ hubert_model.eval()
255
+
256
+ def change_audio_mode(vc_audio_mode):
257
+ if vc_audio_mode == "Input path":
258
+ return (
259
+ # Input & Upload
260
+ gr.Textbox.update(visible=True),
261
+ gr.Checkbox.update(visible=False),
262
+ gr.Audio.update(visible=False),
263
+ # Youtube
264
+ gr.Dropdown.update(visible=False),
265
+ gr.Textbox.update(visible=False),
266
+ gr.Textbox.update(visible=False),
267
+ gr.Button.update(visible=False),
268
+ # Splitter
269
+ gr.Dropdown.update(visible=False),
270
+ gr.Textbox.update(visible=False),
271
+ gr.Button.update(visible=False),
272
+ gr.Audio.update(visible=False),
273
+ gr.Audio.update(visible=False),
274
+ gr.Audio.update(visible=False),
275
+ gr.Slider.update(visible=False),
276
+ gr.Slider.update(visible=False),
277
+ gr.Audio.update(visible=False),
278
+ gr.Button.update(visible=False),
279
+ # TTS
280
+ gr.Textbox.update(visible=False),
281
+ gr.Dropdown.update(visible=False)
282
+ )
283
+ elif vc_audio_mode == "Upload audio":
284
+ return (
285
+ # Input & Upload
286
+ gr.Textbox.update(visible=False),
287
+ gr.Checkbox.update(visible=True),
288
+ gr.Audio.update(visible=True),
289
+ # Youtube
290
+ gr.Dropdown.update(visible=False),
291
+ gr.Textbox.update(visible=False),
292
+ gr.Textbox.update(visible=False),
293
+ gr.Button.update(visible=False),
294
+ # Splitter
295
+ gr.Dropdown.update(visible=False),
296
+ gr.Textbox.update(visible=False),
297
+ gr.Button.update(visible=False),
298
+ gr.Audio.update(visible=False),
299
+ gr.Audio.update(visible=False),
300
+ gr.Audio.update(visible=False),
301
+ gr.Slider.update(visible=False),
302
+ gr.Slider.update(visible=False),
303
+ gr.Audio.update(visible=False),
304
+ gr.Button.update(visible=False),
305
+ # TTS
306
+ gr.Textbox.update(visible=False),
307
+ gr.Dropdown.update(visible=False)
308
+ )
309
+ elif vc_audio_mode == "Youtube":
310
+ return (
311
+ # Input & Upload
312
+ gr.Textbox.update(visible=False),
313
+ gr.Checkbox.update(visible=False),
314
+ gr.Audio.update(visible=False),
315
+ # Youtube
316
+ gr.Dropdown.update(visible=True),
317
+ gr.Textbox.update(visible=True),
318
+ gr.Textbox.update(visible=True),
319
+ gr.Button.update(visible=True),
320
+ # Splitter
321
+ gr.Dropdown.update(visible=True),
322
+ gr.Textbox.update(visible=True),
323
+ gr.Button.update(visible=True),
324
+ gr.Audio.update(visible=True),
325
+ gr.Audio.update(visible=True),
326
+ gr.Audio.update(visible=True),
327
+ gr.Slider.update(visible=True),
328
+ gr.Slider.update(visible=True),
329
+ gr.Audio.update(visible=True),
330
+ gr.Button.update(visible=True),
331
+ # TTS
332
+ gr.Textbox.update(visible=False),
333
+ gr.Dropdown.update(visible=False)
334
+ )
335
+ elif vc_audio_mode == "TTS Audio":
336
+ return (
337
+ # Input & Upload
338
+ gr.Textbox.update(visible=False),
339
+ gr.Checkbox.update(visible=False),
340
+ gr.Audio.update(visible=False),
341
+ # Youtube
342
+ gr.Dropdown.update(visible=False),
343
+ gr.Textbox.update(visible=False),
344
+ gr.Textbox.update(visible=False),
345
+ gr.Button.update(visible=False),
346
+ # Splitter
347
+ gr.Dropdown.update(visible=False),
348
+ gr.Textbox.update(visible=False),
349
+ gr.Button.update(visible=False),
350
+ gr.Audio.update(visible=False),
351
+ gr.Audio.update(visible=False),
352
+ gr.Audio.update(visible=False),
353
+ gr.Slider.update(visible=False),
354
+ gr.Slider.update(visible=False),
355
+ gr.Audio.update(visible=False),
356
+ gr.Button.update(visible=False),
357
+ # TTS
358
+ gr.Textbox.update(visible=True),
359
+ gr.Dropdown.update(visible=True)
360
+ )
361
+
362
+ def use_microphone(microphone):
363
+ if microphone == True:
364
+ return gr.Audio.update(source="microphone")
365
+ else:
366
+ return gr.Audio.update(source="upload")
367
+
368
+ if __name__ == '__main__':
369
+ load_hubert()
370
+ categories = load_model()
371
+ tts_voice_list = asyncio.new_event_loop().run_until_complete(edge_tts.list_voices())
372
+ voices = [f"{v['ShortName']}-{v['Gender']}" for v in tts_voice_list]
373
+ with gr.Blocks() as app:
374
+ gr.Markdown(
375
+ "<div align='center'>\n\n"+
376
+ "# RVC Genshin Impact\n\n"+
377
+ "### Recommended to use Google Colab to use other character and feature.\n\n"+
378
+ "[![Colab](https://img.shields.io/badge/Colab-RVC%20Genshin%20Impact-blue?style=for-the-badge&logo=googlecolab)](https://colab.research.google.com/drive/110kiMZTdP6Ri1lY9-NbQf17GVPPhHyeT?usp=sharing)\n\n"+
379
+ "</div>\n\n"+
380
+ "[![Repository](https://img.shields.io/badge/Github-Multi%20Model%20RVC%20Inference-blue?style=for-the-badge&logo=github)](https://github.com/ArkanDash/Multi-Model-RVC-Inference)"
381
+ )
382
+ if categories == []:
383
+ gr.Markdown(
384
+ "<div align='center'>\n\n"+
385
+ "## No model found, please add the model into weights folder\n\n"+
386
+ "</div>"
387
+ )
388
+ for (folder_title, folder, description, models) in categories:
389
+ with gr.TabItem(folder_title):
390
+ if description:
391
+ gr.Markdown(f"### <center> {description}")
392
+ with gr.Tabs():
393
+ if not models:
394
+ gr.Markdown("# <center> No Model Loaded.")
395
+ gr.Markdown("## <center> Please add the model or fix your model path.")
396
+ continue
397
+ for (name, title, author, cover, model_version, vc_fn) in models:
398
+ with gr.TabItem(name):
399
+ with gr.Row():
400
+ gr.Markdown(
401
+ '<div align="center">'
402
+ f'<div>{title}</div>\n'+
403
+ f'<div>RVC {model_version} Model</div>\n'+
404
+ (f'<div>Model author: {author}</div>' if author else "")+
405
+ (f'<img style="width:auto;height:300px;" src="file/{cover}">' if cover else "")+
406
+ '</div>'
407
+ )
408
+ with gr.Row():
409
+ if spaces is False:
410
+ with gr.TabItem("Input"):
411
+ with gr.Row():
412
+ with gr.Column():
413
+ vc_audio_mode = gr.Dropdown(label="Input voice", choices=audio_mode, allow_custom_value=False, value="Upload audio")
414
+ # Input
415
+ vc_input = gr.Textbox(label="Input audio path", visible=False)
416
+ # Upload
417
+ vc_microphone_mode = gr.Checkbox(label="Use Microphone", value=False, visible=True, interactive=True)
418
+ vc_upload = gr.Audio(label="Upload audio file", source="upload", visible=True, interactive=True)
419
+ # Youtube
420
+ vc_download_audio = gr.Dropdown(label="Provider", choices=["Youtube"], allow_custom_value=False, visible=False, value="Youtube", info="Select provider (Default: Youtube)")
421
+ 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=...")
422
+ vc_log_yt = gr.Textbox(label="Output Information", visible=False, interactive=False)
423
+ vc_download_button = gr.Button("Download Audio", variant="primary", visible=False)
424
+ vc_audio_preview = gr.Audio(label="Audio Preview", visible=False)
425
+ # TTS
426
+ tts_text = gr.Textbox(label="TTS text", info="Text to speech input", visible=False)
427
+ tts_voice = gr.Dropdown(label="Edge-tts speaker", choices=voices, visible=False, allow_custom_value=False, value="en-US-AnaNeural-Female")
428
+ with gr.Column():
429
+ 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=False, value="htdemucs", info="Select the splitter model (Default: htdemucs)")
430
+ vc_split_log = gr.Textbox(label="Output Information", visible=False, interactive=False)
431
+ vc_split = gr.Button("Split Audio", variant="primary", visible=False)
432
+ vc_vocal_preview = gr.Audio(label="Vocal Preview", visible=False)
433
+ vc_inst_preview = gr.Audio(label="Instrumental Preview", visible=False)
434
+ with gr.TabItem("Convert"):
435
+ with gr.Row():
436
+ with gr.Column():
437
+ 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')
438
+ f0method0 = gr.Radio(
439
+ label="Pitch extraction algorithm",
440
+ info=f0method_info,
441
+ choices=f0method_mode,
442
+ value="pm",
443
+ interactive=True
444
+ )
445
+ index_rate1 = gr.Slider(
446
+ minimum=0,
447
+ maximum=1,
448
+ label="Retrieval feature ratio",
449
+ info="(Default: 0.7)",
450
+ value=0.7,
451
+ interactive=True,
452
+ )
453
+ filter_radius0 = gr.Slider(
454
+ minimum=0,
455
+ maximum=7,
456
+ label="Apply Median Filtering",
457
+ info="The value represents the filter radius and can reduce breathiness.",
458
+ value=3,
459
+ step=1,
460
+ interactive=True,
461
+ )
462
+ resample_sr0 = gr.Slider(
463
+ minimum=0,
464
+ maximum=48000,
465
+ label="Resample the output audio",
466
+ info="Resample the output audio in post-processing to the final sample rate. Set to 0 for no resampling",
467
+ value=0,
468
+ step=1,
469
+ interactive=True,
470
+ )
471
+ rms_mix_rate0 = gr.Slider(
472
+ minimum=0,
473
+ maximum=1,
474
+ label="Volume Envelope",
475
+ 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",
476
+ value=1,
477
+ interactive=True,
478
+ )
479
+ protect0 = gr.Slider(
480
+ minimum=0,
481
+ maximum=0.5,
482
+ label="Voice Protection",
483
+ 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",
484
+ value=0.5,
485
+ step=0.01,
486
+ interactive=True,
487
+ )
488
+ with gr.Column():
489
+ vc_log = gr.Textbox(label="Output Information", interactive=False)
490
+ vc_output = gr.Audio(label="Output Audio", interactive=False)
491
+ vc_convert = gr.Button("Convert", variant="primary")
492
+ vc_vocal_volume = gr.Slider(
493
+ minimum=0,
494
+ maximum=10,
495
+ label="Vocal volume",
496
+ value=1,
497
+ interactive=True,
498
+ step=1,
499
+ info="Adjust vocal volume (Default: 1}",
500
+ visible=False
501
+ )
502
+ vc_inst_volume = gr.Slider(
503
+ minimum=0,
504
+ maximum=10,
505
+ label="Instrument volume",
506
+ value=1,
507
+ interactive=True,
508
+ step=1,
509
+ info="Adjust instrument volume (Default: 1}",
510
+ visible=False
511
+ )
512
+ vc_combined_output = gr.Audio(label="Output Combined Audio", visible=False)
513
+ vc_combine = gr.Button("Combine",variant="primary", visible=False)
514
+ else:
515
+ with gr.Column():
516
+ vc_audio_mode = gr.Dropdown(label="Input voice", choices=audio_mode, allow_custom_value=False, value="Upload audio")
517
+ # Input
518
+ vc_input = gr.Textbox(label="Input audio path", visible=False)
519
+ # Upload
520
+ vc_microphone_mode = gr.Checkbox(label="Use Microphone", value=False, visible=True, interactive=True)
521
+ vc_upload = gr.Audio(label="Upload audio file", source="upload", visible=True, interactive=True)
522
+ # Youtube
523
+ vc_download_audio = gr.Dropdown(label="Provider", choices=["Youtube"], allow_custom_value=False, visible=False, value="Youtube", info="Select provider (Default: Youtube)")
524
+ 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=...")
525
+ vc_log_yt = gr.Textbox(label="Output Information", visible=False, interactive=False)
526
+ vc_download_button = gr.Button("Download Audio", variant="primary", visible=False)
527
+ vc_audio_preview = gr.Audio(label="Audio Preview", visible=False)
528
+ # Splitter
529
+ 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=False, value="htdemucs", info="Select the splitter model (Default: htdemucs)")
530
+ vc_split_log = gr.Textbox(label="Output Information", visible=False, interactive=False)
531
+ vc_split = gr.Button("Split Audio", variant="primary", visible=False)
532
+ vc_vocal_preview = gr.Audio(label="Vocal Preview", visible=False)
533
+ vc_inst_preview = gr.Audio(label="Instrumental Preview", visible=False)
534
+ # TTS
535
+ tts_text = gr.Textbox(label="TTS text", info="Text to speech input", visible=False)
536
+ tts_voice = gr.Dropdown(label="Edge-tts speaker", choices=voices, visible=False, allow_custom_value=False, value="en-US-AnaNeural-Female")
537
+ with gr.Column():
538
+ 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')
539
+ f0method0 = gr.Radio(
540
+ label="Pitch extraction algorithm",
541
+ info=f0method_info,
542
+ choices=f0method_mode,
543
+ value="pm",
544
+ interactive=True
545
+ )
546
+ index_rate1 = gr.Slider(
547
+ minimum=0,
548
+ maximum=1,
549
+ label="Retrieval feature ratio",
550
+ info="(Default: 0.7)",
551
+ value=0.7,
552
+ interactive=True,
553
+ )
554
+ filter_radius0 = gr.Slider(
555
+ minimum=0,
556
+ maximum=7,
557
+ label="Apply Median Filtering",
558
+ info="The value represents the filter radius and can reduce breathiness.",
559
+ value=3,
560
+ step=1,
561
+ interactive=True,
562
+ )
563
+ resample_sr0 = gr.Slider(
564
+ minimum=0,
565
+ maximum=48000,
566
+ label="Resample the output audio",
567
+ info="Resample the output audio in post-processing to the final sample rate. Set to 0 for no resampling",
568
+ value=0,
569
+ step=1,
570
+ interactive=True,
571
+ )
572
+ rms_mix_rate0 = gr.Slider(
573
+ minimum=0,
574
+ maximum=1,
575
+ label="Volume Envelope",
576
+ 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",
577
+ value=1,
578
+ interactive=True,
579
+ )
580
+ protect0 = gr.Slider(
581
+ minimum=0,
582
+ maximum=0.5,
583
+ label="Voice Protection",
584
+ 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",
585
+ value=0.5,
586
+ step=0.01,
587
+ interactive=True,
588
+ )
589
+ with gr.Column():
590
+ vc_log = gr.Textbox(label="Output Information", interactive=False)
591
+ vc_output = gr.Audio(label="Output Audio", interactive=False)
592
+ vc_convert = gr.Button("Convert", variant="primary")
593
+ vc_vocal_volume = gr.Slider(
594
+ minimum=0,
595
+ maximum=10,
596
+ label="Vocal volume",
597
+ value=1,
598
+ interactive=True,
599
+ step=1,
600
+ info="Adjust vocal volume (Default: 1}",
601
+ visible=False
602
+ )
603
+ vc_inst_volume = gr.Slider(
604
+ minimum=0,
605
+ maximum=10,
606
+ label="Instrument volume",
607
+ value=1,
608
+ interactive=True,
609
+ step=1,
610
+ info="Adjust instrument volume (Default: 1}",
611
+ visible=False
612
+ )
613
+ vc_combined_output = gr.Audio(label="Output Combined Audio", visible=False)
614
+ vc_combine = gr.Button("Combine",variant="primary", visible=False)
615
+ vc_convert.click(
616
+ fn=vc_fn,
617
+ inputs=[
618
+ vc_audio_mode,
619
+ vc_input,
620
+ vc_upload,
621
+ tts_text,
622
+ tts_voice,
623
+ vc_transform0,
624
+ f0method0,
625
+ index_rate1,
626
+ filter_radius0,
627
+ resample_sr0,
628
+ rms_mix_rate0,
629
+ protect0,
630
+ ],
631
+ outputs=[vc_log ,vc_output]
632
+ )
633
+ vc_download_button.click(
634
+ fn=download_audio,
635
+ inputs=[vc_link, vc_download_audio],
636
+ outputs=[vc_audio_preview, vc_log_yt]
637
+ )
638
+ vc_split.click(
639
+ fn=cut_vocal_and_inst,
640
+ inputs=[vc_split_model],
641
+ outputs=[vc_split_log, vc_vocal_preview, vc_inst_preview, vc_input]
642
+ )
643
+ vc_combine.click(
644
+ fn=combine_vocal_and_inst,
645
+ inputs=[vc_output, vc_vocal_volume, vc_inst_volume, vc_split_model],
646
+ outputs=[vc_combined_output]
647
+ )
648
+ vc_microphone_mode.change(
649
+ fn=use_microphone,
650
+ inputs=vc_microphone_mode,
651
+ outputs=vc_upload
652
+ )
653
+ vc_audio_mode.change(
654
+ fn=change_audio_mode,
655
+ inputs=[vc_audio_mode],
656
+ outputs=[
657
+ vc_input,
658
+ vc_microphone_mode,
659
+ vc_upload,
660
+ vc_download_audio,
661
+ vc_link,
662
+ vc_log_yt,
663
+ vc_download_button,
664
+ vc_split_model,
665
+ vc_split_log,
666
+ vc_split,
667
+ vc_audio_preview,
668
+ vc_vocal_preview,
669
+ vc_inst_preview,
670
+ vc_vocal_volume,
671
+ vc_inst_volume,
672
+ vc_combined_output,
673
+ vc_combine,
674
+ tts_text,
675
+ tts_voice
676
+ ]
677
+ )
678
+ app.queue(concurrency_count=1, max_size=20, api_open=config.api).launch(share=config.colab)
requirements.txt CHANGED
@@ -1,8 +1,15 @@
1
  torch~=2.0.1
2
  onnxruntime~=1.15.1
3
  onnxruntime-gpu~=1.15.1
4
- librosa~=0.10.0.post2
5
  soundfile~=0.12.1
6
  numpy~=1.24.4
7
  scipy~=1.11.1
8
- streamlit~=1.25.0
 
 
 
 
 
 
 
 
1
  torch~=2.0.1
2
  onnxruntime~=1.15.1
3
  onnxruntime-gpu~=1.15.1
4
+ librosa~=0.9.1
5
  soundfile~=0.12.1
6
  numpy~=1.24.4
7
  scipy~=1.11.1
8
+ streamlit~=1.25.0
9
+ fairseq~=0.12.2
10
+ praat-parselmouth~=0.4.3
11
+ pyworld~=0.3.4
12
+ faiss-cpu~=1.7.4
13
+ torchcrepe~=0.0.21
14
+ chardet~=5.2.0
15
+ ffmpeg-python~=0.2.0
src/Sound_Feature_Extraction/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # src.Sound_Feature_Extraction package
src/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # src package
src/config.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.unsupported
17
+ ) = self.arg_parse()
18
+ self.x_pad, self.x_query, self.x_center, self.x_max = self.device_config()
19
+
20
+ @staticmethod
21
+ def arg_parse() -> tuple:
22
+ parser = argparse.ArgumentParser()
23
+ parser.add_argument("--colab", action="store_true", help="Launch in colab")
24
+ parser.add_argument("--api", action="store_true", help="Launch with api")
25
+ parser.add_argument("--unsupported", action="store_true", help="Enable unsupported feature")
26
+ cmd_opts = parser.parse_args()
27
+
28
+ return (
29
+ cmd_opts.colab,
30
+ cmd_opts.api,
31
+ cmd_opts.unsupported
32
+ )
33
+
34
+ # has_mps is only available in nightly pytorch (for now) and MasOS 12.3+.
35
+ # check `getattr` and try it for compatibility
36
+ @staticmethod
37
+ def has_mps() -> bool:
38
+ if not torch.backends.mps.is_available():
39
+ return False
40
+ try:
41
+ torch.zeros(1).to(torch.device("mps"))
42
+ return True
43
+ except Exception:
44
+ return False
45
+
46
+ def device_config(self) -> tuple:
47
+ if torch.cuda.is_available():
48
+ i_device = int(self.device.split(":")[-1])
49
+ self.gpu_name = torch.cuda.get_device_name(i_device)
50
+ if (
51
+ ("16" in self.gpu_name and "V100" not in self.gpu_name.upper())
52
+ or "P40" in self.gpu_name.upper()
53
+ or "1060" in self.gpu_name
54
+ or "1070" in self.gpu_name
55
+ or "1080" in self.gpu_name
56
+ ):
57
+ print("INFO: Found GPU", self.gpu_name, ", force to fp32")
58
+ self.is_half = False
59
+ else:
60
+ print("INFO: Found GPU", self.gpu_name)
61
+ self.gpu_mem = int(
62
+ torch.cuda.get_device_properties(i_device).total_memory
63
+ / 1024
64
+ / 1024
65
+ / 1024
66
+ + 0.4
67
+ )
68
+ elif self.has_mps():
69
+ print("INFO: No supported Nvidia GPU found, use MPS instead")
70
+ self.device = "mps"
71
+ self.is_half = False
72
+ else:
73
+ print("INFO: No supported Nvidia GPU found, use CPU instead")
74
+ self.device = "cpu"
75
+ self.is_half = False
76
+
77
+ if self.n_cpu == 0:
78
+ self.n_cpu = cpu_count()
79
+
80
+ if self.is_half:
81
+ # 6G显存配置
82
+ x_pad = 3
83
+ x_query = 10
84
+ x_center = 60
85
+ x_max = 65
86
+ else:
87
+ # 5G显存配置
88
+ x_pad = 1
89
+ x_query = 6
90
+ x_center = 38
91
+ x_max = 41
92
+
93
+ if self.gpu_mem != None and self.gpu_mem <= 4:
94
+ x_pad = 1
95
+ x_query = 5
96
+ x_center = 30
97
+ x_max = 32
98
+
99
+ return x_pad, x_query, x_center, x_max
src/infer.py DELETED
@@ -1,20 +0,0 @@
1
- # Standard Library Imports
2
- import os
3
- import subprocess
4
-
5
- # Third Party Imports
6
- import torch
7
- import onnxruntime as ort
8
-
9
- # Local Imports
10
- from models.MDX_net.mdx_net import Conv_TDF_net_trimm
11
- from loader import Loader
12
-
13
- vocal_path = "./datasets/output/vocals.wav"
14
-
15
- # Global Variables
16
- COMPUTATION_DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
17
-
18
-
19
- def main():
20
- print(COMPUTATION_DEVICE)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/loader.py CHANGED
@@ -16,11 +16,13 @@ class Loader:
16
  def __init__(self, INPUT_FOLDER, OUTPUT_FOLDER):
17
  self.input = INPUT_FOLDER
18
  self.output = OUTPUT_FOLDER
19
- def load_wav(self, name) -> Tuple[ndarray, int]:
 
20
  music_array, samplerate = librosa.load(
21
  os.path.join(self.input, name + ".wav"), mono=False, sr=44100
22
  )
23
- return music_array, samplerate
 
24
 
25
  def prepare_uploaded_file(self, uploaded_file) -> Tuple[torch.Tensor, int]:
26
  music_array, samplerate = librosa.load(uploaded_file, mono=False, sr=44100)
 
16
  def __init__(self, INPUT_FOLDER, OUTPUT_FOLDER):
17
  self.input = INPUT_FOLDER
18
  self.output = OUTPUT_FOLDER
19
+
20
+ def load_wav(self, name) -> Tuple[torch.Tensor, int]:
21
  music_array, samplerate = librosa.load(
22
  os.path.join(self.input, name + ".wav"), mono=False, sr=44100
23
  )
24
+ music_tensor = torch.tensor(music_array, dtype=torch.float32)
25
+ return music_tensor, samplerate
26
 
27
  def prepare_uploaded_file(self, uploaded_file) -> Tuple[torch.Tensor, int]:
28
  music_array, samplerate = librosa.load(uploaded_file, mono=False, sr=44100)
src/models/MDX_net/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # src.models.MDX_net package
src/models/MDX_net/kimvocal.py CHANGED
@@ -43,7 +43,9 @@ class KimVocal:
43
  )
44
 
45
  # Start running the session for the model
46
- ort_session = ort.InferenceSession(ONNX_MODEL_PATH, providers=EXECUTION_PROVIDER_LIST)
 
 
47
 
48
  # TODO: any way to optimize against silence? I think that's what skips are for, gotta double check.
49
  # process one chunk at a time (batch_size=1)
 
43
  )
44
 
45
  # Start running the session for the model
46
+ ort_session = ort.InferenceSession(
47
+ ONNX_MODEL_PATH, providers=EXECUTION_PROVIDER_LIST
48
+ )
49
 
50
  # TODO: any way to optimize against silence? I think that's what skips are for, gotta double check.
51
  # process one chunk at a time (batch_size=1)
src/models/Pitch_Feature_Extraction/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # src.models.Pitch_Feature_Extraction package
src/models/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # src.models package