firzaelbuho commited on
Commit
848d745
1 Parent(s): 7fd9653

Upload app2.py

Browse files
Files changed (1) hide show
  1. app2.py +896 -0
app2.py ADDED
@@ -0,0 +1,896 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import unicode_literals
2
+
3
+ import os
4
+ import glob
5
+ import json
6
+ import traceback
7
+ import logging
8
+ import gradio as gr
9
+ import numpy as np
10
+ import librosa
11
+ import torch
12
+ import asyncio
13
+ import edge_tts
14
+ import yt_dlp
15
+ import ffmpeg
16
+ import subprocess
17
+ import sys
18
+ import io
19
+ import wave
20
+ from datetime import datetime
21
+ from fairseq import checkpoint_utils
22
+ from lib.infer_pack.models import (
23
+ SynthesizerTrnMs256NSFsid,
24
+ SynthesizerTrnMs256NSFsid_nono,
25
+ SynthesizerTrnMs768NSFsid,
26
+ SynthesizerTrnMs768NSFsid_nono,
27
+ )
28
+ from vc_infer_pipeline import VC
29
+ from config import Config
30
+ config = Config()
31
+ logging.getLogger("numba").setLevel(logging.WARNING)
32
+ spaces = os.getenv("SYSTEM") == "spaces"
33
+ force_support = None
34
+ if config.unsupported is False:
35
+ if config.device == "mps" or config.device == "cpu":
36
+ force_support = False
37
+ else:
38
+ force_support = True
39
+
40
+ audio_mode = []
41
+ f0method_mode = []
42
+ f0method_info = ""
43
+
44
+ if force_support is False or spaces is True:
45
+ if spaces is True:
46
+ audio_mode = ["Upload audio", "TTS Audio"]
47
+ else:
48
+ audio_mode = ["Input path", "Upload audio", "TTS Audio"]
49
+ f0method_mode = ["pm", "harvest"]
50
+ f0method_info = "PM is fast, Harvest is good but extremely slow, Rvmpe is alternative to harvest (might be better). (Default: PM)"
51
+ else:
52
+ audio_mode = ["Input path", "Upload audio", "Youtube", "TTS Audio"]
53
+ f0method_mode = ["pm", "harvest", "crepe"]
54
+ 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)"
55
+
56
+ if os.path.isfile("rmvpe.pt"):
57
+ f0method_mode.insert(2, "rmvpe")
58
+
59
+ def create_vc_fn(model_name, tgt_sr, net_g, vc, if_f0, version, file_index):
60
+ def vc_fn(
61
+ vc_audio_mode,
62
+ vc_input,
63
+ vc_upload,
64
+ tts_text,
65
+ tts_voice,
66
+ f0_up_key,
67
+ f0_method,
68
+ index_rate,
69
+ filter_radius,
70
+ resample_sr,
71
+ rms_mix_rate,
72
+ protect,
73
+ ):
74
+ try:
75
+ logs = []
76
+ print(f"Converting using {model_name}...")
77
+ logs.append(f"Converting using {model_name}...")
78
+ yield "\n".join(logs), None
79
+ if vc_audio_mode == "Input path" or "Youtube" and vc_input != "":
80
+ audio, sr = librosa.load(vc_input, sr=16000, mono=True)
81
+ elif vc_audio_mode == "Upload audio":
82
+ if vc_upload is None:
83
+ return "You need to upload an audio", None
84
+ sampling_rate, audio = vc_upload
85
+ duration = audio.shape[0] / sampling_rate
86
+ if duration > 20 and spaces:
87
+ 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
88
+ audio = (audio / np.iinfo(audio.dtype).max).astype(np.float32)
89
+ if len(audio.shape) > 1:
90
+ audio = librosa.to_mono(audio.transpose(1, 0))
91
+ if sampling_rate != 16000:
92
+ audio = librosa.resample(audio, orig_sr=sampling_rate, target_sr=16000)
93
+ elif vc_audio_mode == "TTS Audio":
94
+ if len(tts_text) > 100 and spaces:
95
+ return "Text is too long", None
96
+ if tts_text is None or tts_voice is None:
97
+ return "You need to enter text and select a voice", None
98
+ asyncio.run(edge_tts.Communicate(tts_text, "-".join(tts_voice.split('-')[:-1])).save("tts.mp3"))
99
+ audio, sr = librosa.load("tts.mp3", sr=16000, mono=True)
100
+ vc_input = "tts.mp3"
101
+ times = [0, 0, 0]
102
+ f0_up_key = int(f0_up_key)
103
+ audio_opt = vc.pipeline(
104
+ hubert_model,
105
+ net_g,
106
+ 0,
107
+ audio,
108
+ vc_input,
109
+ times,
110
+ f0_up_key,
111
+ f0_method,
112
+ file_index,
113
+ # file_big_npy,
114
+ index_rate,
115
+ if_f0,
116
+ filter_radius,
117
+ tgt_sr,
118
+ resample_sr,
119
+ rms_mix_rate,
120
+ version,
121
+ protect,
122
+ f0_file=None,
123
+ )
124
+ info = f"[{datetime.now().strftime('%Y-%m-%d %H:%M')}]: npy: {times[0]}, f0: {times[1]}s, infer: {times[2]}s"
125
+ print(f"{model_name} | {info}")
126
+ logs.append(f"Successfully Convert {model_name}\n{info}")
127
+ yield "\n".join(logs), (tgt_sr, audio_opt)
128
+ except Exception as err:
129
+ info = traceback.format_exc()
130
+ print(info)
131
+ primt(f"Error when using {model_name}.\n{str(err)}")
132
+ yield info, None
133
+ return vc_fn
134
+
135
+ def load_model():
136
+ categories = []
137
+ if os.path.isfile("weights/folder_info.json"):
138
+ for _, w_dirs, _ in os.walk(f"weights"):
139
+ category_count_total = len(w_dirs)
140
+ category_count = 1
141
+ with open("weights/folder_info.json", "r", encoding="utf-8") as f:
142
+ folder_info = json.load(f)
143
+ for category_name, category_info in folder_info.items():
144
+ if not category_info['enable']:
145
+ continue
146
+ category_title = category_info['title']
147
+ category_folder = category_info['folder_path']
148
+ description = category_info['description']
149
+ print(f"Load {category_title} [{category_count}/{category_count_total}]")
150
+ models = []
151
+ for _, m_dirs, _ in os.walk(f"weights/{category_folder}"):
152
+ model_count_total = len(m_dirs)
153
+ model_count = 1
154
+ with open(f"weights/{category_folder}/model_info.json", "r", encoding="utf-8") as f:
155
+ models_info = json.load(f)
156
+ for character_name, info in models_info.items():
157
+ if not info['enable']:
158
+ continue
159
+ model_title = info['title']
160
+ model_name = info['model_path']
161
+ model_author = info.get("author", None)
162
+ model_cover = f"weights/{category_folder}/{character_name}/{info['cover']}"
163
+ model_index = f"weights/{category_folder}/{character_name}/{info['feature_retrieval_library']}"
164
+ cpt = torch.load(f"weights/{category_folder}/{character_name}/{model_name}", map_location="cpu")
165
+ tgt_sr = cpt["config"][-1]
166
+ cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] # n_spk
167
+ if_f0 = cpt.get("f0", 1)
168
+ version = cpt.get("version", "v1")
169
+ if version == "v1":
170
+ if if_f0 == 1:
171
+ net_g = SynthesizerTrnMs256NSFsid(*cpt["config"], is_half=config.is_half)
172
+ else:
173
+ net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"])
174
+ model_version = "V1"
175
+ elif version == "v2":
176
+ if if_f0 == 1:
177
+ net_g = SynthesizerTrnMs768NSFsid(*cpt["config"], is_half=config.is_half)
178
+ else:
179
+ net_g = SynthesizerTrnMs768NSFsid_nono(*cpt["config"])
180
+ model_version = "V2"
181
+ del net_g.enc_q
182
+ print(net_g.load_state_dict(cpt["weight"], strict=False))
183
+ net_g.eval().to(config.device)
184
+ if config.is_half:
185
+ net_g = net_g.half()
186
+ else:
187
+ net_g = net_g.float()
188
+ vc = VC(tgt_sr, config)
189
+ print(f"Model loaded [{model_count}/{model_count_total}]: {character_name} / {info['feature_retrieval_library']} | ({model_version})")
190
+ model_count += 1
191
+ 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)))
192
+ category_count += 1
193
+ categories.append([category_title, description, models])
194
+ elif os.path.exists("weights"):
195
+ models = []
196
+ for w_root, w_dirs, _ in os.walk("weights"):
197
+ model_count = 1
198
+ for sub_dir in w_dirs:
199
+ pth_files = glob.glob(f"weights/{sub_dir}/*.pth")
200
+ index_files = glob.glob(f"weights/{sub_dir}/*.index")
201
+ if pth_files == []:
202
+ print(f"Model [{model_count}/{len(w_dirs)}]: No Model file detected, skipping...")
203
+ continue
204
+ cpt = torch.load(pth_files[0])
205
+ tgt_sr = cpt["config"][-1]
206
+ cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] # n_spk
207
+ if_f0 = cpt.get("f0", 1)
208
+ version = cpt.get("version", "v1")
209
+ if version == "v1":
210
+ if if_f0 == 1:
211
+ net_g = SynthesizerTrnMs256NSFsid(*cpt["config"], is_half=config.is_half)
212
+ else:
213
+ net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"])
214
+ model_version = "V1"
215
+ elif version == "v2":
216
+ if if_f0 == 1:
217
+ net_g = SynthesizerTrnMs768NSFsid(*cpt["config"], is_half=config.is_half)
218
+ else:
219
+ net_g = SynthesizerTrnMs768NSFsid_nono(*cpt["config"])
220
+ model_version = "V2"
221
+ del net_g.enc_q
222
+ print(net_g.load_state_dict(cpt["weight"], strict=False))
223
+ net_g.eval().to(config.device)
224
+ if config.is_half:
225
+ net_g = net_g.half()
226
+ else:
227
+ net_g = net_g.float()
228
+ vc = VC(tgt_sr, config)
229
+ if index_files == []:
230
+ print("Warning: No Index file detected!")
231
+ index_info = "None"
232
+ model_index = ""
233
+ else:
234
+ index_info = index_files[0]
235
+ model_index = index_files[0]
236
+ print(f"Model loaded [{model_count}/{len(w_dirs)}]: {index_files[0]} / {index_info} | ({model_version})")
237
+ model_count += 1
238
+ models.append((index_files[0][:-4], index_files[0][:-4], "", "", model_version, create_vc_fn(index_files[0], tgt_sr, net_g, vc, if_f0, version, model_index)))
239
+ categories.append(["Models", "", models])
240
+ else:
241
+ categories = []
242
+ return categories
243
+
244
+ def download_audio(url, audio_provider):
245
+ logs = []
246
+ if url == "":
247
+ logs.append("URL required!")
248
+ yield None, "\n".join(logs)
249
+ return None, "\n".join(logs)
250
+ if not os.path.exists("dl_audio"):
251
+ os.mkdir("dl_audio")
252
+ if audio_provider == "Youtube":
253
+ logs.append("Downloading the audio...")
254
+ yield None, "\n".join(logs)
255
+ ydl_opts = {
256
+ 'noplaylist': True,
257
+ 'format': 'bestaudio/best',
258
+ 'postprocessors': [{
259
+ 'key': 'FFmpegExtractAudio',
260
+ 'preferredcodec': 'wav',
261
+ }],
262
+ "outtmpl": 'dl_audio/audio',
263
+ }
264
+ audio_path = "dl_audio/audio.wav"
265
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
266
+ ydl.download([url])
267
+ logs.append("Download Complete.")
268
+ yield audio_path, "\n".join(logs)
269
+
270
+ def cut_vocal_and_inst(split_model):
271
+ logs = []
272
+ logs.append("Starting the audio splitting process...")
273
+ yield "\n".join(logs), None, None, None
274
+ command = f"demucs --two-stems=vocals -n {split_model} dl_audio/audio.wav -o output"
275
+ result = subprocess.Popen(command.split(), stdout=subprocess.PIPE, text=True)
276
+ for line in result.stdout:
277
+ logs.append(line)
278
+ yield "\n".join(logs), None, None, None
279
+ print(result.stdout)
280
+ vocal = f"output/{split_model}/audio/vocals.wav"
281
+ inst = f"output/{split_model}/audio/no_vocals.wav"
282
+ logs.append("Audio splitting complete.")
283
+ yield "\n".join(logs), vocal, inst, vocal
284
+
285
+ def combine_vocal_and_inst(audio_data, vocal_volume, inst_volume, split_model):
286
+ if not os.path.exists("output/result"):
287
+ os.mkdir("output/result")
288
+ vocal_path = "output/result/output.wav"
289
+ output_path = "output/result/combine.mp3"
290
+ inst_path = f"output/{split_model}/audio/no_vocals.wav"
291
+ with wave.open(vocal_path, "w") as wave_file:
292
+ wave_file.setnchannels(1)
293
+ wave_file.setsampwidth(2)
294
+ wave_file.setframerate(audio_data[0])
295
+ wave_file.writeframes(audio_data[1].tobytes())
296
+ 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}'
297
+ result = subprocess.run(command.split(), stdout=subprocess.PIPE)
298
+ print(result.stdout.decode())
299
+ return output_path
300
+
301
+ def load_hubert():
302
+ global hubert_model
303
+ models, _, _ = checkpoint_utils.load_model_ensemble_and_task(
304
+ ["hubert_base.pt"],
305
+ suffix="",
306
+ )
307
+ hubert_model = models[0]
308
+ hubert_model = hubert_model.to(config.device)
309
+ if config.is_half:
310
+ hubert_model = hubert_model.half()
311
+ else:
312
+ hubert_model = hubert_model.float()
313
+ hubert_model.eval()
314
+
315
+ def change_audio_mode(vc_audio_mode):
316
+ if vc_audio_mode == "Input path":
317
+ return (
318
+ # Input & Upload
319
+ gr.Textbox.update(visible=True),
320
+ gr.Checkbox.update(visible=False),
321
+ gr.Audio.update(visible=False),
322
+ # Youtube
323
+ gr.Dropdown.update(visible=False),
324
+ gr.Textbox.update(visible=False),
325
+ gr.Textbox.update(visible=False),
326
+ gr.Button.update(visible=False),
327
+ # Splitter
328
+ gr.Dropdown.update(visible=False),
329
+ gr.Textbox.update(visible=False),
330
+ gr.Button.update(visible=False),
331
+ gr.Audio.update(visible=False),
332
+ gr.Audio.update(visible=False),
333
+ gr.Audio.update(visible=False),
334
+ gr.Slider.update(visible=False),
335
+ gr.Slider.update(visible=False),
336
+ gr.Audio.update(visible=False),
337
+ gr.Button.update(visible=False),
338
+ # TTS
339
+ gr.Textbox.update(visible=False),
340
+ gr.Dropdown.update(visible=False)
341
+ )
342
+ elif vc_audio_mode == "Upload audio":
343
+ return (
344
+ # Input & Upload
345
+ gr.Textbox.update(visible=False),
346
+ gr.Checkbox.update(visible=True),
347
+ gr.Audio.update(visible=True),
348
+ # Youtube
349
+ gr.Dropdown.update(visible=False),
350
+ gr.Textbox.update(visible=False),
351
+ gr.Textbox.update(visible=False),
352
+ gr.Button.update(visible=False),
353
+ # Splitter
354
+ gr.Dropdown.update(visible=False),
355
+ gr.Textbox.update(visible=False),
356
+ gr.Button.update(visible=False),
357
+ gr.Audio.update(visible=False),
358
+ gr.Audio.update(visible=False),
359
+ gr.Audio.update(visible=False),
360
+ gr.Slider.update(visible=False),
361
+ gr.Slider.update(visible=False),
362
+ gr.Audio.update(visible=False),
363
+ gr.Button.update(visible=False),
364
+ # TTS
365
+ gr.Textbox.update(visible=False),
366
+ gr.Dropdown.update(visible=False)
367
+ )
368
+ elif vc_audio_mode == "Youtube":
369
+ return (
370
+ # Input & Upload
371
+ gr.Textbox.update(visible=False),
372
+ gr.Checkbox.update(visible=False),
373
+ gr.Audio.update(visible=False),
374
+ # Youtube
375
+ gr.Dropdown.update(visible=True),
376
+ gr.Textbox.update(visible=True),
377
+ gr.Textbox.update(visible=True),
378
+ gr.Button.update(visible=True),
379
+ # Splitter
380
+ gr.Dropdown.update(visible=True),
381
+ gr.Textbox.update(visible=True),
382
+ gr.Button.update(visible=True),
383
+ gr.Audio.update(visible=True),
384
+ gr.Audio.update(visible=True),
385
+ gr.Audio.update(visible=True),
386
+ gr.Slider.update(visible=True),
387
+ gr.Slider.update(visible=True),
388
+ gr.Audio.update(visible=True),
389
+ gr.Button.update(visible=True),
390
+ # TTS
391
+ gr.Textbox.update(visible=False),
392
+ gr.Dropdown.update(visible=False)
393
+ )
394
+ elif vc_audio_mode == "TTS Audio":
395
+ return (
396
+ # Input & Upload
397
+ gr.Textbox.update(visible=False),
398
+ gr.Checkbox.update(visible=False),
399
+ gr.Audio.update(visible=False),
400
+ # Youtube
401
+ gr.Dropdown.update(visible=False),
402
+ gr.Textbox.update(visible=False),
403
+ gr.Textbox.update(visible=False),
404
+ gr.Button.update(visible=False),
405
+ # Splitter
406
+ gr.Dropdown.update(visible=False),
407
+ gr.Textbox.update(visible=False),
408
+ gr.Button.update(visible=False),
409
+ gr.Audio.update(visible=False),
410
+ gr.Audio.update(visible=False),
411
+ gr.Audio.update(visible=False),
412
+ gr.Slider.update(visible=False),
413
+ gr.Slider.update(visible=False),
414
+ gr.Audio.update(visible=False),
415
+ gr.Button.update(visible=False),
416
+ # TTS
417
+ gr.Textbox.update(visible=True),
418
+ gr.Dropdown.update(visible=True)
419
+ )
420
+
421
+ def use_microphone(microphone):
422
+ if microphone == True:
423
+ return gr.Audio.update(source="microphone")
424
+ else:
425
+ return gr.Audio.update(source="upload")
426
+
427
+
428
+
429
+ # Audio Tool Functions
430
+
431
+ # cvt audio
432
+
433
+ from pydub import AudioSegment
434
+ def convert_audio(url,title):
435
+
436
+ # Mendefinisikan path untuk file audio
437
+ input_path = url
438
+ file_name = os.path.basename(input_path)
439
+ filename = os.path.splitext(file_name)[0]
440
+
441
+
442
+ parent_dir = os.path.dirname(url)
443
+ new_path = os.path.relpath(parent_dir, "")
444
+
445
+
446
+
447
+ output_path = f'youtubeaudio/{title}_converted.mp3'
448
+
449
+ # Mengkonversi file audio WAV menjadi MP3 menggunakan pydub
450
+ sound = AudioSegment.from_wav(input_path)
451
+ sound.export(output_path, format="mp3")
452
+
453
+ # Mengecek apakah file audio MP3 sudah tersimpan
454
+ if os.path.isfile(output_path):
455
+ # return output_path
456
+ return "sukses"
457
+ else:
458
+ return "Konversi gagal"
459
+
460
+
461
+ # Fungsi play Audio
462
+ def play_audio(url):
463
+
464
+ file_path = url
465
+ file_name = os.path.basename(file_path)
466
+ filename = os.path.splitext(file_name)[0]
467
+
468
+ original_path = f"/content/youtubeaudio/{filename}.wav"
469
+ vocal_path = f"/content/separated/htdemucs/{filename}/vocals.wav"
470
+ instrument_path = f"/content/separated/htdemucs/{filename}/no_vocals.wav"
471
+
472
+ return url
473
+
474
+
475
+
476
+ # Fungsi download audio
477
+
478
+ import yt_dlp
479
+ import ffmpeg
480
+ import sys
481
+
482
+
483
+ def download_audio(title, url):
484
+
485
+ ydl_opts = {
486
+ 'format': 'bestaudio/best',
487
+ # 'outtmpl': 'output.%(ext)s',
488
+ 'postprocessors': [{
489
+ 'key': 'FFmpegExtractAudio',
490
+ 'preferredcodec': 'wav',
491
+ }],
492
+ "outtmpl": f'youtubeaudio/{title}', # this is where you can edit how you'd like the filenames to be formatted
493
+ }
494
+
495
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
496
+ # url = "https://www.youtube.com/watch?v=LCcNtQuhUgg" #@param {type:"string"}
497
+ ydl.download([url])
498
+ # return f"/content/youtubeaudio/{title}.wav"
499
+ # return f"/content/youtubeaudio/adudio.wav"
500
+ return "sukses"
501
+
502
+ #fungsi download video
503
+ def download_video(url, resolution):
504
+
505
+ from pytube import YouTube
506
+
507
+ yt = YouTube(url)
508
+ try:
509
+ stream_check = yt.streams.filter(res=f"{resolution}p")
510
+ if len(stream_check) > 0:
511
+ stream = yt.streams.filter(file_extension='mp4', res=f'{resolution}p').first()
512
+ else:
513
+ stream = yt.streams.get_highest_resolution()
514
+ except Exception as e:
515
+ return "error"
516
+
517
+
518
+
519
+
520
+ folder_path = 'youtubevideo'
521
+ if not os.path.exists(folder_path):
522
+ os.makedirs(folder_path)
523
+
524
+ file_path = os.path.join(folder_path, stream.default_filename)
525
+ stream.download(output_path=folder_path, filename=stream.default_filename)
526
+
527
+ return "sukses"
528
+
529
+
530
+ # fungsi split audio
531
+ def split_audio(url):
532
+ import subprocess
533
+
534
+ command = f"demucs --two-stems=vocals {url}"
535
+ result = subprocess.run(command.split(), stdout=subprocess.PIPE)
536
+ print(result.stdout.decode())
537
+ return "sukses"
538
+
539
+
540
+ def aio(title, yt_url):
541
+ download_status = download_audio(title, yt_url)
542
+
543
+ audio_url = f"youtubeaudio/{title}.wav"
544
+ split_status = split_audio(audio_url)
545
+
546
+ vocal_url = f"separated/htdemucs/{title}/vocals.wav"
547
+ no_vocal_url = f"separated/htdemucs/{title}/no_vocals.wav"
548
+
549
+ vocal_convert_status = convert_audio(vocal_url, title+"_vocal")
550
+ no_vocal_convert_status = convert_audio(no_vocal_url, title+"_instrumen")
551
+
552
+ import os
553
+
554
+ # specify old file path name
555
+ # old_vocal_name = f"separated/htdemucs/{title}/vocals_converted.mp3"
556
+ # old_instrumen_name = f"separated/htdemucs/{title}/no_vocals_converted.mp3"
557
+
558
+
559
+ # Specify the new file path and name
560
+ # new_vocal_name = f"separated/htdemucs/{title}/{title}_vocal.mp3"
561
+ # new_instrumen_name = f"separated/htdemucs/{title}/{title}_instrumen.mp3"
562
+
563
+ # Rename the file separated
564
+ # os.rename(old_vocal_name, new_vocal_name)
565
+ # os.rename(old_instrumen_name, new_instrumen_name)
566
+
567
+
568
+ return "sukses"
569
+
570
+
571
+
572
+
573
+ if __name__ == '__main__':
574
+ load_hubert()
575
+ categories = load_model()
576
+ tts_voice_list = asyncio.new_event_loop().run_until_complete(edge_tts.list_voices())
577
+ voices = [f"{v['ShortName']}-{v['Gender']}" for v in tts_voice_list]
578
+ with gr.Blocks() as app:
579
+ gr.Markdown(
580
+ "<div align='center'>\n\n"+
581
+ "# RVC Genshin Impact\n\n"+
582
+ "### Recommended to use Google Colab to use other character and feature.\n\n"+
583
+ "[![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"+
584
+ "</div>\n\n"+
585
+ "[![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)"
586
+ )
587
+ if categories == []:
588
+ gr.Markdown(
589
+ "<div align='center'>\n\n"+
590
+ "## No model found, please add the model into weights folder\n\n"+
591
+ "</div>"
592
+ )
593
+ for (folder_title, description, models) in categories:
594
+ with gr.TabItem(folder_title):
595
+ if description:
596
+ gr.Markdown(f"### <center> {description}")
597
+ with gr.Tabs():
598
+ if not models:
599
+ gr.Markdown("# <center> No Model Loaded.")
600
+ gr.Markdown("## <center> Please add the model or fix your model path.")
601
+ continue
602
+ for (name, title, author, cover, model_version, vc_fn) in models:
603
+ with gr.TabItem(name):
604
+ with gr.Row():
605
+ gr.Markdown(
606
+ '<div align="center">'
607
+ f'<div>{title}</div>\n'+
608
+ f'<div>RVC {model_version} Model</div>\n'+
609
+ (f'<div>Model author: {author}</div>' if author else "")+
610
+ (f'<img style="width:auto;height:300px;" src="file/{cover}">' if cover else "")+
611
+ '</div>'
612
+ )
613
+ with gr.Row():
614
+ if spaces is False:
615
+ with gr.TabItem("Input"):
616
+ with gr.Row():
617
+ with gr.Column():
618
+ vc_audio_mode = gr.Dropdown(label="Input voice", choices=audio_mode, allow_custom_value=False, value="Upload audio")
619
+ # Input
620
+ vc_input = gr.Textbox(label="Input audio path", visible=False)
621
+ # Upload
622
+ vc_microphone_mode = gr.Checkbox(label="Use Microphone", value=False, visible=True, interactive=True)
623
+ vc_upload = gr.Audio(label="Upload audio file", source="upload", visible=True, interactive=True)
624
+ # Youtube
625
+ vc_download_audio = gr.Dropdown(label="Provider", choices=["Youtube"], allow_custom_value=False, visible=False, value="Youtube", info="Select provider (Default: Youtube)")
626
+ 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=...")
627
+ vc_log_yt = gr.Textbox(label="Output Information", visible=False, interactive=False)
628
+ vc_download_button = gr.Button("Download Audio", variant="primary", visible=False)
629
+ vc_audio_preview = gr.Audio(label="Audio Preview", visible=False)
630
+ # TTS
631
+ tts_text = gr.Textbox(label="TTS text", info="Text to speech input", visible=False)
632
+ tts_voice = gr.Dropdown(label="Edge-tts speaker", choices=voices, visible=False, allow_custom_value=False, value="en-US-AnaNeural-Female")
633
+ with gr.Column():
634
+ 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)")
635
+ vc_split_log = gr.Textbox(label="Output Information", visible=False, interactive=False)
636
+ vc_split = gr.Button("Split Audio", variant="primary", visible=False)
637
+ vc_vocal_preview = gr.Audio(label="Vocal Preview", visible=False)
638
+ vc_inst_preview = gr.Audio(label="Instrumental Preview", visible=False)
639
+ with gr.TabItem("Convert"):
640
+ with gr.Row():
641
+ with gr.Column():
642
+ 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')
643
+ f0method0 = gr.Radio(
644
+ label="Pitch extraction algorithm",
645
+ info=f0method_info,
646
+ choices=f0method_mode,
647
+ value="pm",
648
+ interactive=True
649
+ )
650
+ index_rate1 = gr.Slider(
651
+ minimum=0,
652
+ maximum=1,
653
+ label="Retrieval feature ratio",
654
+ info="(Default: 0.7)",
655
+ value=0.7,
656
+ interactive=True,
657
+ )
658
+ filter_radius0 = gr.Slider(
659
+ minimum=0,
660
+ maximum=7,
661
+ label="Apply Median Filtering",
662
+ info="The value represents the filter radius and can reduce breathiness.",
663
+ value=3,
664
+ step=1,
665
+ interactive=True,
666
+ )
667
+ resample_sr0 = gr.Slider(
668
+ minimum=0,
669
+ maximum=48000,
670
+ label="Resample the output audio",
671
+ info="Resample the output audio in post-processing to the final sample rate. Set to 0 for no resampling",
672
+ value=0,
673
+ step=1,
674
+ interactive=True,
675
+ )
676
+ rms_mix_rate0 = gr.Slider(
677
+ minimum=0,
678
+ maximum=1,
679
+ label="Volume Envelope",
680
+ 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",
681
+ value=1,
682
+ interactive=True,
683
+ )
684
+ protect0 = gr.Slider(
685
+ minimum=0,
686
+ maximum=0.5,
687
+ label="Voice Protection",
688
+ 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",
689
+ value=0.5,
690
+ step=0.01,
691
+ interactive=True,
692
+ )
693
+ with gr.Column():
694
+ vc_log = gr.Textbox(label="Output Information", interactive=False)
695
+ vc_output = gr.Audio(label="Output Audio", interactive=False)
696
+ vc_convert = gr.Button("Convert", variant="primary")
697
+ vc_vocal_volume = gr.Slider(
698
+ minimum=0,
699
+ maximum=10,
700
+ label="Vocal volume",
701
+ value=1,
702
+ interactive=True,
703
+ step=1,
704
+ info="Adjust vocal volume (Default: 1}",
705
+ visible=False
706
+ )
707
+ vc_inst_volume = gr.Slider(
708
+ minimum=0,
709
+ maximum=10,
710
+ label="Instrument volume",
711
+ value=1,
712
+ interactive=True,
713
+ step=1,
714
+ info="Adjust instrument volume (Default: 1}",
715
+ visible=False
716
+ )
717
+ vc_combined_output = gr.Audio(label="Output Combined Audio", visible=False)
718
+ vc_combine = gr.Button("Combine",variant="primary", visible=False)
719
+ else:
720
+ with gr.Column():
721
+ vc_audio_mode = gr.Dropdown(label="Input voice", choices=audio_mode, allow_custom_value=False, value="Upload audio")
722
+ # Input
723
+ vc_input = gr.Textbox(label="Input audio path", visible=False)
724
+ # Upload
725
+ vc_microphone_mode = gr.Checkbox(label="Use Microphone", value=False, visible=True, interactive=True)
726
+ vc_upload = gr.Audio(label="Upload audio file", source="upload", visible=True, interactive=True)
727
+ # Youtube
728
+ vc_download_audio = gr.Dropdown(label="Provider", choices=["Youtube"], allow_custom_value=False, visible=False, value="Youtube", info="Select provider (Default: Youtube)")
729
+ 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=...")
730
+ vc_log_yt = gr.Textbox(label="Output Information", visible=False, interactive=False)
731
+ vc_download_button = gr.Button("Download Audio", variant="primary", visible=False)
732
+ vc_audio_preview = gr.Audio(label="Audio Preview", visible=False)
733
+ # Splitter
734
+ 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)")
735
+ vc_split_log = gr.Textbox(label="Output Information", visible=False, interactive=False)
736
+ vc_split = gr.Button("Split Audio", variant="primary", visible=False)
737
+ vc_vocal_preview = gr.Audio(label="Vocal Preview", visible=False)
738
+ vc_inst_preview = gr.Audio(label="Instrumental Preview", visible=False)
739
+ # TTS
740
+ tts_text = gr.Textbox(label="TTS text", info="Text to speech input", visible=False)
741
+ tts_voice = gr.Dropdown(label="Edge-tts speaker", choices=voices, visible=False, allow_custom_value=False, value="en-US-AnaNeural-Female")
742
+ with gr.Column():
743
+ 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')
744
+ f0method0 = gr.Radio(
745
+ label="Pitch extraction algorithm",
746
+ info=f0method_info,
747
+ choices=f0method_mode,
748
+ value="pm",
749
+ interactive=True
750
+ )
751
+ index_rate1 = gr.Slider(
752
+ minimum=0,
753
+ maximum=1,
754
+ label="Retrieval feature ratio",
755
+ info="(Default: 0.7)",
756
+ value=0.7,
757
+ interactive=True,
758
+ )
759
+ filter_radius0 = gr.Slider(
760
+ minimum=0,
761
+ maximum=7,
762
+ label="Apply Median Filtering",
763
+ info="The value represents the filter radius and can reduce breathiness.",
764
+ value=3,
765
+ step=1,
766
+ interactive=True,
767
+ )
768
+ resample_sr0 = gr.Slider(
769
+ minimum=0,
770
+ maximum=48000,
771
+ label="Resample the output audio",
772
+ info="Resample the output audio in post-processing to the final sample rate. Set to 0 for no resampling",
773
+ value=0,
774
+ step=1,
775
+ interactive=True,
776
+ )
777
+ rms_mix_rate0 = gr.Slider(
778
+ minimum=0,
779
+ maximum=1,
780
+ label="Volume Envelope",
781
+ 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",
782
+ value=1,
783
+ interactive=True,
784
+ )
785
+ protect0 = gr.Slider(
786
+ minimum=0,
787
+ maximum=0.5,
788
+ label="Voice Protection",
789
+ 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",
790
+ value=0.5,
791
+ step=0.01,
792
+ interactive=True,
793
+ )
794
+ with gr.Column():
795
+ vc_log = gr.Textbox(label="Output Information", interactive=False)
796
+ vc_output = gr.Audio(label="Output Audio", interactive=False)
797
+ vc_convert = gr.Button("Convert", variant="primary")
798
+ vc_vocal_volume = gr.Slider(
799
+ minimum=0,
800
+ maximum=10,
801
+ label="Vocal volume",
802
+ value=1,
803
+ interactive=True,
804
+ step=1,
805
+ info="Adjust vocal volume (Default: 1}",
806
+ visible=False
807
+ )
808
+ vc_inst_volume = gr.Slider(
809
+ minimum=0,
810
+ maximum=10,
811
+ label="Instrument volume",
812
+ value=1,
813
+ interactive=True,
814
+ step=1,
815
+ info="Adjust instrument volume (Default: 1}",
816
+ visible=False
817
+ )
818
+ vc_combined_output = gr.Audio(label="Output Combined Audio", visible=False)
819
+ vc_combine = gr.Button("Combine",variant="primary", visible=False)
820
+ vc_convert.click(
821
+ fn=vc_fn,
822
+ inputs=[
823
+ vc_audio_mode,
824
+ vc_input,
825
+ vc_upload,
826
+ tts_text,
827
+ tts_voice,
828
+ vc_transform0,
829
+ f0method0,
830
+ index_rate1,
831
+ filter_radius0,
832
+ resample_sr0,
833
+ rms_mix_rate0,
834
+ protect0,
835
+ ],
836
+ outputs=[vc_log ,vc_output]
837
+ )
838
+ vc_download_button.click(
839
+ fn=download_audio,
840
+ inputs=[vc_link, vc_download_audio],
841
+ outputs=[vc_audio_preview, vc_log_yt]
842
+ )
843
+ vc_split.click(
844
+ fn=cut_vocal_and_inst,
845
+ inputs=[vc_split_model],
846
+ outputs=[vc_split_log, vc_vocal_preview, vc_inst_preview, vc_input]
847
+ )
848
+ vc_combine.click(
849
+ fn=combine_vocal_and_inst,
850
+ inputs=[vc_output, vc_vocal_volume, vc_inst_volume, vc_split_model],
851
+ outputs=[vc_combined_output]
852
+ )
853
+ vc_microphone_mode.change(
854
+ fn=use_microphone,
855
+ inputs=vc_microphone_mode,
856
+ outputs=vc_upload
857
+ )
858
+ vc_audio_mode.change(
859
+ fn=change_audio_mode,
860
+ inputs=[vc_audio_mode],
861
+ outputs=[
862
+ vc_input,
863
+ vc_microphone_mode,
864
+ vc_upload,
865
+ vc_download_audio,
866
+ vc_link,
867
+ vc_log_yt,
868
+ vc_download_button,
869
+ vc_split_model,
870
+ vc_split_log,
871
+ vc_split,
872
+ vc_audio_preview,
873
+ vc_vocal_preview,
874
+ vc_inst_preview,
875
+ vc_vocal_volume,
876
+ vc_inst_volume,
877
+ vc_combined_output,
878
+ vc_combine,
879
+ tts_text,
880
+ tts_voice
881
+ ]
882
+ )
883
+ # Audio tool
884
+
885
+ with gr.Tab("AIO"):
886
+ with gr.Row():
887
+ with gr.Column():
888
+ aio_input = [gr.Textbox(label = "title"), gr.Textbox(label = "Youtube Url")]
889
+ aio_button = gr.Button("Procces")
890
+ with gr.Column():
891
+ aio_output =[gr.Textbox(label = "Status Output")]
892
+
893
+ aio_button.click(aio, inputs=aio_input, outputs=aio_output)
894
+
895
+
896
+ app.queue(concurrency_count=5, max_size=50, api_open=config.api).launch(share=config.share, debug=True)