ArkanDash commited on
Commit
c4ecee6
1 Parent(s): 1c86be8

feat: update infer

Browse files
Files changed (2) hide show
  1. app.py +356 -200
  2. config.py +9 -27
app.py CHANGED
@@ -27,14 +27,23 @@ from vc_infer_pipeline import VC
27
  from config import Config
28
  config = Config()
29
  logging.getLogger("numba").setLevel(logging.WARNING)
30
- limitation = os.getenv("SYSTEM") == "spaces"
 
 
 
 
 
 
31
 
32
  audio_mode = []
33
  f0method_mode = []
34
  f0method_info = ""
35
 
36
- if limitation is True:
37
- audio_mode = ["Upload audio", "TTS Audio"]
 
 
 
38
  f0method_mode = ["pm", "harvest"]
39
  f0method_info = "PM is fast, Harvest is good but extremely slow, Rvmpe is alternative to harvest (might be better). (Default: PM)"
40
  else:
@@ -61,7 +70,10 @@ def create_vc_fn(model_name, tgt_sr, net_g, vc, if_f0, version, file_index):
61
  protect,
62
  ):
63
  try:
 
64
  print(f"Converting using {model_name}...")
 
 
65
  if vc_audio_mode == "Input path" or "Youtube" and vc_input != "":
66
  audio, sr = librosa.load(vc_input, sr=16000, mono=True)
67
  elif vc_audio_mode == "Upload audio":
@@ -69,7 +81,7 @@ def create_vc_fn(model_name, tgt_sr, net_g, vc, if_f0, version, file_index):
69
  return "You need to upload an audio", None
70
  sampling_rate, audio = vc_upload
71
  duration = audio.shape[0] / sampling_rate
72
- if duration > 20 and limitation:
73
  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
74
  audio = (audio / np.iinfo(audio.dtype).max).astype(np.float32)
75
  if len(audio.shape) > 1:
@@ -77,7 +89,7 @@ def create_vc_fn(model_name, tgt_sr, net_g, vc, if_f0, version, file_index):
77
  if sampling_rate != 16000:
78
  audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=16000)
79
  elif vc_audio_mode == "TTS Audio":
80
- if len(tts_text) > 100 and limitation:
81
  return "Text is too long", None
82
  if tts_text is None or tts_voice is None:
83
  return "You need to enter text and select a voice", None
@@ -109,110 +121,120 @@ def create_vc_fn(model_name, tgt_sr, net_g, vc, if_f0, version, file_index):
109
  )
110
  info = f"[{datetime.now().strftime('%Y-%m-%d %H:%M')}]: npy: {times[0]}, f0: {times[1]}s, infer: {times[2]}s"
111
  print(f"{model_name} | {info}")
112
- return info, (tgt_sr, audio_opt)
 
113
  except:
114
  info = traceback.format_exc()
115
  print(info)
116
- return info, None
117
  return vc_fn
118
 
119
  def load_model():
120
  categories = []
121
- with open("weights/folder_info.json", "r", encoding="utf-8") as f:
122
- folder_info = json.load(f)
123
- for category_name, category_info in folder_info.items():
124
- if not category_info['enable']:
125
- continue
126
- category_title = category_info['title']
127
- category_folder = category_info['folder_path']
128
- description = category_info['description']
129
- models = []
130
- with open(f"weights/{category_folder}/model_info.json", "r", encoding="utf-8") as f:
131
- models_info = json.load(f)
132
- for character_name, info in models_info.items():
133
- if not info['enable']:
134
  continue
135
- model_title = info['title']
136
- model_name = info['model_path']
137
- model_author = info.get("author", None)
138
- model_cover = f"weights/{category_folder}/{character_name}/{info['cover']}"
139
- model_index = f"weights/{category_folder}/{character_name}/{info['feature_retrieval_library']}"
140
- cpt = torch.load(f"weights/{category_folder}/{character_name}/{model_name}", map_location="cpu")
141
- tgt_sr = cpt["config"][-1]
142
- cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] # n_spk
143
- if_f0 = cpt.get("f0", 1)
144
- version = cpt.get("version", "v1")
145
- if version == "v1":
146
- if if_f0 == 1:
147
- net_g = SynthesizerTrnMs256NSFsid(*cpt["config"], is_half=config.is_half)
148
- else:
149
- net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"])
150
- model_version = "V1"
151
- elif version == "v2":
152
- if if_f0 == 1:
153
- net_g = SynthesizerTrnMs768NSFsid(*cpt["config"], is_half=config.is_half)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  else:
155
- net_g = SynthesizerTrnMs768NSFsid_nono(*cpt["config"])
156
- model_version = "V2"
157
- del net_g.enc_q
158
- print(net_g.load_state_dict(cpt["weight"], strict=False))
159
- net_g.eval().to(config.device)
160
- if config.is_half:
161
- net_g = net_g.half()
162
- else:
163
- net_g = net_g.float()
164
- vc = VC(tgt_sr, config)
165
- print(f"Model loaded: {character_name} / {info['feature_retrieval_library']} | ({model_version})")
166
- 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)))
167
- categories.append([category_title, category_folder, description, models])
168
  return categories
169
 
170
- def cut_vocal_and_inst(url, audio_provider, split_model):
171
- if url != "":
172
- if not os.path.exists("dl_audio"):
173
- os.mkdir("dl_audio")
174
- if audio_provider == "Youtube":
175
- ydl_opts = {
176
- 'noplaylist': True,
177
- 'format': 'bestaudio/best',
178
- 'postprocessors': [{
179
- 'key': 'FFmpegExtractAudio',
180
- 'preferredcodec': 'wav',
181
- }],
182
- "outtmpl": 'dl_audio/youtube_audio',
183
- }
184
- with yt_dlp.YoutubeDL(ydl_opts) as ydl:
185
- ydl.download([url])
186
- audio_path = "dl_audio/youtube_audio.wav"
187
- if split_model == "htdemucs":
188
- command = f"demucs --two-stems=vocals {audio_path} -o output"
189
- result = subprocess.run(command.split(), stdout=subprocess.PIPE)
190
- print(result.stdout.decode())
191
- return "output/htdemucs/youtube_audio/vocals.wav", "output/htdemucs/youtube_audio/no_vocals.wav", audio_path, "output/htdemucs/youtube_audio/vocals.wav"
192
- else:
193
- command = f"demucs --two-stems=vocals -n mdx_extra_q {audio_path} -o output"
194
- result = subprocess.run(command.split(), stdout=subprocess.PIPE)
195
- print(result.stdout.decode())
196
- 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"
197
- else:
198
  raise gr.Error("URL Required!")
199
- return None, None, None, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
 
201
- def combine_vocal_and_inst(audio_data, audio_volume, split_model):
202
  if not os.path.exists("output/result"):
203
  os.mkdir("output/result")
204
  vocal_path = "output/result/output.wav"
205
  output_path = "output/result/combine.mp3"
206
- if split_model == "htdemucs":
207
- inst_path = "output/htdemucs/youtube_audio/no_vocals.wav"
208
- else:
209
- inst_path = "output/mdx_extra_q/youtube_audio/no_vocals.wav"
210
  with wave.open(vocal_path, "w") as wave_file:
211
  wave_file.setnchannels(1)
212
  wave_file.setsampwidth(2)
213
  wave_file.setframerate(audio_data[0])
214
  wave_file.writeframes(audio_data[1].tobytes())
215
- 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}'
216
  result = subprocess.run(command.split(), stdout=subprocess.PIPE)
217
  print(result.stdout.decode())
218
  return output_path
@@ -241,12 +263,17 @@ def change_audio_mode(vc_audio_mode):
241
  # Youtube
242
  gr.Dropdown.update(visible=False),
243
  gr.Textbox.update(visible=False),
 
 
 
244
  gr.Dropdown.update(visible=False),
 
245
  gr.Button.update(visible=False),
246
  gr.Audio.update(visible=False),
247
  gr.Audio.update(visible=False),
248
  gr.Audio.update(visible=False),
249
  gr.Slider.update(visible=False),
 
250
  gr.Audio.update(visible=False),
251
  gr.Button.update(visible=False),
252
  # TTS
@@ -262,12 +289,17 @@ def change_audio_mode(vc_audio_mode):
262
  # Youtube
263
  gr.Dropdown.update(visible=False),
264
  gr.Textbox.update(visible=False),
 
 
 
265
  gr.Dropdown.update(visible=False),
 
266
  gr.Button.update(visible=False),
267
  gr.Audio.update(visible=False),
268
  gr.Audio.update(visible=False),
269
  gr.Audio.update(visible=False),
270
  gr.Slider.update(visible=False),
 
271
  gr.Audio.update(visible=False),
272
  gr.Button.update(visible=False),
273
  # TTS
@@ -283,12 +315,17 @@ def change_audio_mode(vc_audio_mode):
283
  # Youtube
284
  gr.Dropdown.update(visible=True),
285
  gr.Textbox.update(visible=True),
 
 
 
286
  gr.Dropdown.update(visible=True),
 
287
  gr.Button.update(visible=True),
288
  gr.Audio.update(visible=True),
289
  gr.Audio.update(visible=True),
290
  gr.Audio.update(visible=True),
291
  gr.Slider.update(visible=True),
 
292
  gr.Audio.update(visible=True),
293
  gr.Button.update(visible=True),
294
  # TTS
@@ -304,38 +341,22 @@ def change_audio_mode(vc_audio_mode):
304
  # Youtube
305
  gr.Dropdown.update(visible=False),
306
  gr.Textbox.update(visible=False),
307
- gr.Dropdown.update(visible=False),
308
- gr.Button.update(visible=False),
309
- gr.Audio.update(visible=False),
310
- gr.Audio.update(visible=False),
311
- gr.Audio.update(visible=False),
312
- gr.Slider.update(visible=False),
313
- gr.Audio.update(visible=False),
314
- gr.Button.update(visible=False),
315
- # TTS
316
- gr.Textbox.update(visible=True),
317
- gr.Dropdown.update(visible=True)
318
- )
319
- else:
320
- return (
321
- # Input & Upload
322
  gr.Textbox.update(visible=False),
323
- gr.Checkbox.update(visible=True),
324
- gr.Audio.update(visible=True),
325
- # Youtube
326
  gr.Dropdown.update(visible=False),
327
  gr.Textbox.update(visible=False),
328
- gr.Dropdown.update(visible=False),
329
  gr.Button.update(visible=False),
330
  gr.Audio.update(visible=False),
331
  gr.Audio.update(visible=False),
332
  gr.Audio.update(visible=False),
333
  gr.Slider.update(visible=False),
 
334
  gr.Audio.update(visible=False),
335
  gr.Button.update(visible=False),
336
  # TTS
337
- gr.Textbox.update(visible=False),
338
- gr.Dropdown.update(visible=False)
339
  )
340
 
341
  def use_microphone(microphone):
@@ -358,6 +379,12 @@ if __name__ == '__main__':
358
  "</div>\n\n"+
359
  "[![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)"
360
  )
 
 
 
 
 
 
361
  for (folder_title, folder, description, models) in categories:
362
  with gr.TabItem(folder_title):
363
  if description:
@@ -365,7 +392,7 @@ if __name__ == '__main__':
365
  with gr.Tabs():
366
  if not models:
367
  gr.Markdown("# <center> No Model Loaded.")
368
- gr.Markdown("## <center> Please add model or fix your model path.")
369
  continue
370
  for (name, title, author, cover, model_version, vc_fn) in models:
371
  with gr.TabItem(name):
@@ -379,92 +406,212 @@ if __name__ == '__main__':
379
  '</div>'
380
  )
381
  with gr.Row():
382
- with gr.Column():
383
- vc_audio_mode = gr.Dropdown(label="Input voice", choices=audio_mode, allow_custom_value=False, value="Upload audio")
384
- # Input
385
- vc_input = gr.Textbox(label="Input audio path", visible=False)
386
- # Upload
387
- vc_microphone_mode = gr.Checkbox(label="Use Microphone", value=False, visible=True, interactive=True)
388
- vc_upload = gr.Audio(label="Upload audio file", source="upload", visible=True, interactive=True)
389
- # Youtube
390
- vc_download_audio = gr.Dropdown(label="Provider", choices=["Youtube"], allow_custom_value=False, visible=False, value="Youtube", info="Select provider (Default: Youtube)")
391
- 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=...")
392
- 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)")
393
- vc_split = gr.Button("Split Audio", variant="primary", visible=False)
394
- vc_vocal_preview = gr.Audio(label="Vocal Preview", visible=False)
395
- vc_inst_preview = gr.Audio(label="Instrumental Preview", visible=False)
396
- vc_audio_preview = gr.Audio(label="Audio Preview", visible=False)
397
- # TTS
398
- tts_text = gr.Textbox(visible=False, label="TTS text", info="Text to speech input")
399
- tts_voice = gr.Dropdown(label="Edge-tts speaker", choices=voices, visible=False, allow_custom_value=False, value="en-US-AnaNeural-Female")
400
- with gr.Column():
401
- 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')
402
- f0method0 = gr.Radio(
403
- label="Pitch extraction algorithm",
404
- info=f0method_info,
405
- choices=f0method_mode,
406
- value="pm",
407
- interactive=True
408
- )
409
- index_rate1 = gr.Slider(
410
- minimum=0,
411
- maximum=1,
412
- label="Retrieval feature ratio",
413
- info="(Default: 0.7)",
414
- value=0.7,
415
- interactive=True,
416
- )
417
- filter_radius0 = gr.Slider(
418
- minimum=0,
419
- maximum=7,
420
- label="Apply Median Filtering",
421
- info="The value represents the filter radius and can reduce breathiness.",
422
- value=3,
423
- step=1,
424
- interactive=True,
425
- )
426
- resample_sr0 = gr.Slider(
427
- minimum=0,
428
- maximum=48000,
429
- label="Resample the output audio",
430
- info="Resample the output audio in post-processing to the final sample rate. Set to 0 for no resampling",
431
- value=0,
432
- step=1,
433
- interactive=True,
434
- )
435
- rms_mix_rate0 = gr.Slider(
436
- minimum=0,
437
- maximum=1,
438
- label="Volume Envelope",
439
- 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",
440
- value=1,
441
- interactive=True,
442
- )
443
- protect0 = gr.Slider(
444
- minimum=0,
445
- maximum=0.5,
446
- label="Voice Protection",
447
- 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",
448
- value=0.5,
449
- step=0.01,
450
- interactive=True,
451
- )
452
- with gr.Column():
453
- vc_log = gr.Textbox(label="Output Information", interactive=False)
454
- vc_output = gr.Audio(label="Output Audio", interactive=False)
455
- vc_convert = gr.Button("Convert", variant="primary")
456
- vc_volume = gr.Slider(
457
- minimum=0,
458
- maximum=10,
459
- label="Vocal volume",
460
- value=4,
461
- interactive=True,
462
- step=1,
463
- info="Adjust vocal volume (Default: 4}",
464
- visible=False
465
- )
466
- vc_combined_output = gr.Audio(label="Output Combined Audio", visible=False)
467
- vc_combine = gr.Button("Combine",variant="primary", visible=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
468
  vc_convert.click(
469
  fn=vc_fn,
470
  inputs=[
@@ -483,14 +630,19 @@ if __name__ == '__main__':
483
  ],
484
  outputs=[vc_log ,vc_output]
485
  )
 
 
 
 
 
486
  vc_split.click(
487
  fn=cut_vocal_and_inst,
488
- inputs=[vc_link, vc_download_audio, vc_split_model],
489
- outputs=[vc_vocal_preview, vc_inst_preview, vc_audio_preview, vc_input]
490
  )
491
  vc_combine.click(
492
  fn=combine_vocal_and_inst,
493
- inputs=[vc_output, vc_volume, vc_split_model],
494
  outputs=[vc_combined_output]
495
  )
496
  vc_microphone_mode.change(
@@ -507,12 +659,16 @@ if __name__ == '__main__':
507
  vc_upload,
508
  vc_download_audio,
509
  vc_link,
 
 
510
  vc_split_model,
 
511
  vc_split,
 
512
  vc_vocal_preview,
513
  vc_inst_preview,
514
- vc_audio_preview,
515
- vc_volume,
516
  vc_combined_output,
517
  vc_combine,
518
  tts_text,
 
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:
 
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":
 
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:
 
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
 
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
 
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
 
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
 
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
 
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):
 
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:
 
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):
 
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=[
 
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(
 
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,
config.py CHANGED
@@ -11,42 +11,24 @@ class Config:
11
  self.gpu_name = None
12
  self.gpu_mem = None
13
  (
14
- self.python_cmd,
15
- self.listen_port,
16
  self.colab,
17
- self.noparallel,
18
- self.noautoopen,
19
- self.api
20
  ) = self.arg_parse()
21
  self.x_pad, self.x_query, self.x_center, self.x_max = self.device_config()
22
 
23
  @staticmethod
24
  def arg_parse() -> tuple:
25
- exe = sys.executable or "python"
26
  parser = argparse.ArgumentParser()
27
- parser.add_argument("--port", type=int, default=7865, help="Listen port")
28
- parser.add_argument("--pycmd", type=str, default=exe, help="Python command")
29
  parser.add_argument("--colab", action="store_true", help="Launch in colab")
30
- parser.add_argument(
31
- "--noparallel", action="store_true", help="Disable parallel processing"
32
- )
33
- parser.add_argument(
34
- "--noautoopen",
35
- action="store_true",
36
- help="Do not open in browser automatically",
37
- )
38
  parser.add_argument("--api", action="store_true", help="Launch with api")
 
39
  cmd_opts = parser.parse_args()
40
 
41
- cmd_opts.port = cmd_opts.port if 0 <= cmd_opts.port <= 65535 else 7865
42
-
43
  return (
44
- cmd_opts.pycmd,
45
- cmd_opts.port,
46
  cmd_opts.colab,
47
- cmd_opts.noparallel,
48
- cmd_opts.noautoopen,
49
- cmd_opts.api
50
  )
51
 
52
  # has_mps is only available in nightly pytorch (for now) and MasOS 12.3+.
@@ -72,10 +54,10 @@ class Config:
72
  or "1070" in self.gpu_name
73
  or "1080" in self.gpu_name
74
  ):
75
- print("Found GPU", self.gpu_name, ", force to fp32")
76
  self.is_half = False
77
  else:
78
- print("Found GPU", self.gpu_name)
79
  self.gpu_mem = int(
80
  torch.cuda.get_device_properties(i_device).total_memory
81
  / 1024
@@ -84,11 +66,11 @@ class Config:
84
  + 0.4
85
  )
86
  elif self.has_mps():
87
- print("No supported Nvidia GPU found, use MPS instead")
88
  self.device = "mps"
89
  self.is_half = False
90
  else:
91
- print("No supported Nvidia GPU found, use CPU instead")
92
  self.device = "cpu"
93
  self.is_half = False
94
 
 
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+.
 
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
 
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