aboohg commited on
Commit
96efa9c
·
verified ·
1 Parent(s): e7d9d1d

Update src/webui.py

Browse files
Files changed (1) hide show
  1. src/webui.py +337 -390
src/webui.py CHANGED
@@ -1,390 +1,337 @@
1
- import json
2
- import os
3
- import shutil
4
- import urllib.request
5
- import zipfile
6
- from argparse import ArgumentParser
7
- import spaces
8
- import gradio as gr
9
- import logging
10
- def configure_logging_libs(debug=False):
11
- modules = [
12
- "numba",
13
- "httpx",
14
- "markdown_it",
15
- "fairseq",
16
- "faiss",
17
- ]
18
- try:
19
- for module in modules:
20
- logging.getLogger(module).setLevel(logging.WARNING)
21
- os.environ['TF_CPP_MIN_LOG_LEVEL'] = "3" if not debug else "1"
22
-
23
- except Exception as error:
24
- pass
25
- configure_logging_libs()
26
-
27
- from main import song_cover_pipeline, yt_download
28
-
29
- BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
30
- IS_ZERO_GPU = os.getenv("SPACES_ZERO_GPU")
31
-
32
- mdxnet_models_dir = os.path.join(BASE_DIR, 'mdxnet_models')
33
- rvc_models_dir = os.path.join(BASE_DIR, 'rvc_models')
34
- output_dir = os.path.join(BASE_DIR, 'song_output')
35
-
36
-
37
- def get_current_models(models_dir):
38
- models_list = os.listdir(models_dir)
39
- items_to_remove = ['hubert_base.pt', 'MODELS.txt', 'public_models.json', 'rmvpe.pt']
40
- return [item for item in models_list if item not in items_to_remove]
41
-
42
-
43
- def update_models_list():
44
- models_l = get_current_models(rvc_models_dir)
45
- return gr.update(choices=models_l)
46
-
47
-
48
- def load_public_models():
49
- models_table = []
50
- for model in public_models['voice_models']:
51
- if not model['name'] in voice_models:
52
- model = [model['name'], model['description'], model['credit'], model['url'], ', '.join(model['tags'])]
53
- models_table.append(model)
54
-
55
- tags = list(public_models['tags'].keys())
56
- return gr.update(value=models_table), gr.update(choices=tags)
57
-
58
-
59
- def extract_zip(extraction_folder, zip_name):
60
- os.makedirs(extraction_folder)
61
- with zipfile.ZipFile(zip_name, 'r') as zip_ref:
62
- zip_ref.extractall(extraction_folder)
63
- os.remove(zip_name)
64
-
65
- index_filepath, model_filepath = None, None
66
- for root, dirs, files in os.walk(extraction_folder):
67
- for name in files:
68
- if name.endswith('.index') and os.stat(os.path.join(root, name)).st_size > 1024 * 100:
69
- index_filepath = os.path.join(root, name)
70
-
71
- if name.endswith('.pth') and os.stat(os.path.join(root, name)).st_size > 1024 * 1024 * 40:
72
- model_filepath = os.path.join(root, name)
73
-
74
- if not model_filepath:
75
- raise gr.Error(f'No .pth model file was found in the extracted zip. Please check {extraction_folder}.')
76
-
77
- # move model and index file to extraction folder
78
- os.rename(model_filepath, os.path.join(extraction_folder, os.path.basename(model_filepath)))
79
- if index_filepath:
80
- os.rename(index_filepath, os.path.join(extraction_folder, os.path.basename(index_filepath)))
81
-
82
- # remove any unnecessary nested folders
83
- for filepath in os.listdir(extraction_folder):
84
- if os.path.isdir(os.path.join(extraction_folder, filepath)):
85
- shutil.rmtree(os.path.join(extraction_folder, filepath))
86
-
87
-
88
- def download_online_model(url, dir_name, progress=gr.Progress()):
89
- try:
90
- progress(0, desc=f'[~] Downloading voice model with name {dir_name}...')
91
- zip_name = url.split('/')[-1]
92
- extraction_folder = os.path.join(rvc_models_dir, dir_name)
93
- if os.path.exists(extraction_folder):
94
- raise gr.Error(f'Voice model directory {dir_name} already exists! Choose a different name for your voice model.')
95
-
96
- if 'pixeldrain.com' in url:
97
- url = f'https://pixeldrain.com/api/file/{zip_name}'
98
-
99
-
100
- if "," in url:
101
- urls = [u.strip() for u in url.split(",") if u.strip()]
102
- os.makedirs(extraction_folder, exist_ok=True)
103
- for u in urls:
104
- u = u.replace("?download=true", "")
105
- file_name = u.split('/')[-1]
106
- file_path = os.path.join(extraction_folder, file_name)
107
- if not os.path.exists(file_path): # avoid re-downloading
108
- urllib.request.urlretrieve(u, file_path)
109
- else:
110
- urllib.request.urlretrieve(url, zip_name)
111
-
112
- progress(0.5, desc='[~] Extracting zip...')
113
- extract_zip(extraction_folder, zip_name)
114
- return f'[+] {dir_name} Model successfully downloaded!'
115
-
116
- except Exception as e:
117
- raise gr.Error(str(e))
118
-
119
-
120
- def upload_local_model(zip_path, dir_name, progress=gr.Progress()):
121
- try:
122
- extraction_folder = os.path.join(rvc_models_dir, dir_name)
123
- if os.path.exists(extraction_folder):
124
- raise gr.Error(f'Voice model directory {dir_name} already exists! Choose a different name for your voice model.')
125
-
126
- zip_name = zip_path.name
127
- progress(0.5, desc='[~] Extracting zip...')
128
- extract_zip(extraction_folder, zip_name)
129
- return f'[+] {dir_name} Model successfully uploaded!'
130
-
131
- except Exception as e:
132
- raise gr.Error(str(e))
133
-
134
-
135
- def filter_models(tags, query):
136
- models_table = []
137
-
138
- # no filter
139
- if len(tags) == 0 and len(query) == 0:
140
- for model in public_models['voice_models']:
141
- models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']])
142
-
143
- # filter based on tags and query
144
- elif len(tags) > 0 and len(query) > 0:
145
- for model in public_models['voice_models']:
146
- if all(tag in model['tags'] for tag in tags):
147
- model_attributes = f"{model['name']} {model['description']} {model['credit']} {' '.join(model['tags'])}".lower()
148
- if query.lower() in model_attributes:
149
- models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']])
150
-
151
- # filter based on only tags
152
- elif len(tags) > 0:
153
- for model in public_models['voice_models']:
154
- if all(tag in model['tags'] for tag in tags):
155
- models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']])
156
-
157
- # filter based on only query
158
- else:
159
- for model in public_models['voice_models']:
160
- model_attributes = f"{model['name']} {model['description']} {model['credit']} {' '.join(model['tags'])}".lower()
161
- if query.lower() in model_attributes:
162
- models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']])
163
-
164
- return gr.update(value=models_table)
165
-
166
-
167
- def pub_dl_autofill(pub_models, event: gr.SelectData):
168
- return gr.update(value=pub_models.loc[event.index[0], 'URL']), gr.update(value=pub_models.loc[event.index[0], 'Model Name'])
169
-
170
-
171
- def swap_visibility():
172
- return gr.update(visible=True), gr.update(visible=False), gr.update(value=''), gr.update(value=None)
173
-
174
-
175
- def process_file_upload(file):
176
- return file.name, gr.update(value=file.name)
177
-
178
-
179
- def show_hop_slider(pitch_detection_algo):
180
- if pitch_detection_algo == 'mangio-crepe':
181
- return gr.update(visible=True)
182
- else:
183
- return gr.update(visible=False)
184
-
185
-
186
- if __name__ == '__main__':
187
- parser = ArgumentParser(description='Generate a AI cover song in the song_output/id directory.', add_help=True)
188
- parser.add_argument("--share", action="store_true", dest="share_enabled", default=False, help="Enable sharing")
189
- parser.add_argument("--builtin-player", action="store_true", default=False, help="Use the builtin audio player")
190
- parser.add_argument("--listen", action="store_true", default=False, help="Make the WebUI reachable from your local network.")
191
- parser.add_argument('--listen-host', type=str, help='The hostname that the server will use.')
192
- parser.add_argument('--listen-port', type=int, help='The listening port that the server will use.')
193
- parser.add_argument('--theme', type=str, default="NoCrypt/miku", help='Set the theme (default: NoCrypt/miku)')
194
- parser.add_argument("--ssr", action="store_true", help="Enable SSR (Server-Side Rendering)")
195
- args = parser.parse_args()
196
-
197
- voice_models = get_current_models(rvc_models_dir)
198
- with open(os.path.join(rvc_models_dir, 'public_models.json'), encoding='utf8') as infile:
199
- public_models = json.load(infile)
200
-
201
- with gr.Blocks(title='AICoverGenWebUI', theme=args.theme, fill_width=True, fill_height=False) as app:
202
-
203
- gr.Label(f'AICoverGen WebUI {"ZeroGPU mode" if IS_ZERO_GPU else ""} created with ❤️', show_label=False)
204
- if IS_ZERO_GPU:
205
- gr.Markdown(
206
- """
207
- <details>
208
- <summary style="font-size: 1.5em;">⚠️ Important (click to expand)</summary>
209
- <ul>
210
- <li>🚀 This demo use a Zero GPU, which is available only for a limited time. It's recommended to use audio files that are no longer than 5 minutes. If you want to use it without time restrictions, you can duplicate the 'old CPU space'. ⏳</li>
211
- </ul>
212
- </details>
213
- """
214
- )
215
- gr.Markdown("Duplicate the old CPU space for use in private: [![Duplicate this Space](https://huggingface.co/datasets/huggingface/badges/raw/main/duplicate-this-space-sm-dark.svg)](https://huggingface.co/spaces/r3gm/AICoverGen_old_stable_cpu?duplicate=true)\n\n")
216
-
217
- # main tab
218
- with gr.Tab("Generate"):
219
-
220
- with gr.Accordion('Main Options'):
221
- with gr.Row():
222
- with gr.Column():
223
- rvc_model = gr.Dropdown(voice_models, label='Voice Models', info='Models folder "AICoverGen --> rvc_models". After new models are added into this folder, click the refresh button')
224
- ref_btn = gr.Button('Refresh Models 🔁', variant='primary')
225
-
226
- with gr.Column(visible=False) as yt_link_col:
227
- song_input = gr.Text(label='Song input', info='Link to a song on YouTube or full path to a local file. For file upload, click the button below.')
228
- show_file_upload_button = gr.Button('Upload file instead')
229
-
230
- with gr.Column(visible=True) as file_upload_col:
231
- audio_extensions = ['.mp3', '.m4a', '.flac', '.wav', '.aac', '.ogg', '.wma', '.alac', '.aiff', '.opus', 'amr']
232
- local_file = gr.File(label='Audio file', interactive=True, type="filepath", file_types=audio_extensions, height=150)
233
- if not IS_ZERO_GPU:
234
- with gr.Row():
235
- with gr.Row(scale=2):
236
- url_media_gui = gr.Textbox(value="", label="Enter URL", placeholder="www.youtube.com/watch?v=g_9rPvbENUw", lines=1)
237
- with gr.Row(scale=1):
238
- url_button_gui = gr.Button("Process URL", variant="secondary")
239
- url_button_gui.click(yt_download, [url_media_gui], [local_file])
240
- song_input_file = gr.UploadButton('Upload 📂', file_types=['audio'], variant='primary', visible=False)
241
- show_yt_link_button = gr.Button('Paste YouTube link/Path to local file instead', visible=False)
242
- song_input_file.upload(process_file_upload, inputs=[song_input_file], outputs=[local_file, song_input])
243
-
244
- with gr.Column():
245
- pitch = gr.Slider(-3, 3, value=0, step=1, label='Pitch Change (Vocals ONLY)', info='Generally, use 1 for male to female conversions and -1 for vice-versa. (Octaves)')
246
- pitch_all = gr.Slider(-12, 12, value=0, step=1, label='Overall Pitch Change', info='Changes pitch/key of vocals and instrumentals together. Altering this slightly reduces sound quality. (Semitones)')
247
- show_file_upload_button.click(swap_visibility, outputs=[file_upload_col, yt_link_col, song_input, local_file])
248
- show_yt_link_button.click(swap_visibility, outputs=[yt_link_col, file_upload_col, song_input, local_file])
249
-
250
- with gr.Accordion('Voice conversion options', open=False):
251
- with gr.Row():
252
- index_rate = gr.Slider(0, 1, value=0.5, label='Index Rate', info="Controls how much of the AI voice's accent to keep in the vocals")
253
- filter_radius = gr.Slider(0, 7, value=3, step=1, label='Filter radius', info='If >=3: apply median filtering median filtering to the harvested pitch results. Can reduce breathiness')
254
- rms_mix_rate = gr.Slider(0, 1, value=0.25, label='RMS mix rate', info="Control how much to mimic the original vocal's loudness (0) or a fixed loudness (1)")
255
- protect = gr.Slider(0, 0.5, value=0.33, label='Protect rate', info='Protect voiceless consonants and breath sounds. Set to 0.5 to disable.')
256
- with gr.Column():
257
- f0_method = gr.Dropdown(['rmvpe+', 'rmvpe', 'mangio-crepe'], value='rmvpe+', label='Pitch detection algorithm', info='Best option is rmvpe (clarity in vocals), then mangio-crepe (smoother vocals), rmvpe+ use a minimum and maximum allowed pitch values.')
258
- crepe_hop_length = gr.Slider(32, 320, value=128, step=1, visible=False, label='Crepe hop length', info='Lower values leads to longer conversions and higher risk of voice cracks, but better pitch accuracy.')
259
- f0_method.change(show_hop_slider, inputs=f0_method, outputs=crepe_hop_length)
260
- with gr.Row():
261
- with gr.Row():
262
- steps = gr.Slider(minimum=1, maximum=3, label="Steps", value=1, step=1, interactive=True)
263
- with gr.Row():
264
- extra_denoise = gr.Checkbox(True, label='Denoise', info='Apply an additional noise reduction step to clean up the audio further.')
265
- keep_files = gr.Checkbox((False if IS_ZERO_GPU else True), label='Keep intermediate files', info='Keep all audio files generated in the song_output/id directory, e.g. Isolated Vocals/Instrumentals. Leave unchecked to save space', interactive=(False if IS_ZERO_GPU else True))
266
-
267
- with gr.Accordion('Audio mixing options', open=False):
268
- gr.Markdown('### Volume Change (decibels)')
269
- with gr.Row():
270
- main_gain = gr.Slider(-20, 20, value=0, step=1, label='Main Vocals')
271
- backup_gain = gr.Slider(-20, 20, value=0, step=1, label='Backup Vocals')
272
- inst_gain = gr.Slider(-20, 20, value=0, step=1, label='Music')
273
-
274
- gr.Markdown('### Reverb Control on AI Vocals')
275
- with gr.Row():
276
- reverb_rm_size = gr.Slider(0, 1, value=0.15, label='Room size', info='The larger the room, the longer the reverb time')
277
- reverb_wet = gr.Slider(0, 1, value=0.2, label='Wetness level', info='Level of AI vocals with reverb')
278
- reverb_dry = gr.Slider(0, 1, value=0.8, label='Dryness level', info='Level of AI vocals without reverb')
279
- reverb_damping = gr.Slider(0, 1, value=0.7, label='Damping level', info='Absorption of high frequencies in the reverb')
280
-
281
- gr.Markdown('### Audio Output Format')
282
- output_format = gr.Dropdown(['mp3', 'wav'], value='mp3', label='Output file type', info='mp3: small file size, decent quality. wav: Large file size, best quality')
283
-
284
- with gr.Row():
285
- clear_btn = gr.ClearButton(value='Clear', components=[song_input, rvc_model, keep_files, local_file])
286
- generate_btn = gr.Button("Generate", variant='primary')
287
- ai_cover = (
288
- gr.Audio(label='AI Cover', show_share_button=True)
289
- if args.builtin_player else
290
- gr.File(label="AI Cover", interactive=False)
291
- )
292
- gr.Markdown("- You can also try `AICoverGen❤️` in Colab’s free tier, which provides free GPU [link](https://github.com/R3gm/AICoverGen?tab=readme-ov-file#aicovergen).")
293
-
294
- ref_btn.click(update_models_list, None, outputs=rvc_model)
295
- is_webui = gr.Number(value=1, visible=False)
296
- generate_btn.click(song_cover_pipeline,
297
- inputs=[local_file, rvc_model, pitch, keep_files, is_webui, main_gain, backup_gain,
298
- inst_gain, index_rate, filter_radius, rms_mix_rate, f0_method, crepe_hop_length,
299
- protect, pitch_all, reverb_rm_size, reverb_wet, reverb_dry, reverb_damping,
300
- output_format, extra_denoise, steps],
301
- outputs=[ai_cover])
302
- clear_btn.click(lambda: [0, 0, 0, 0, 0.5, 3, 0.25, 0.33, 'rmvpe+', 128, 0, 0.15, 0.2, 0.8, 0.7, 'mp3', None, True, 1],
303
- outputs=[pitch, main_gain, backup_gain, inst_gain, index_rate, filter_radius, rms_mix_rate,
304
- protect, f0_method, crepe_hop_length, pitch_all, reverb_rm_size, reverb_wet,
305
- reverb_dry, reverb_damping, output_format, ai_cover, extra_denoise, steps])
306
-
307
- # Download tab
308
- with gr.Tab('Download model'):
309
-
310
- with gr.Tab('From HuggingFace/Pixeldrain URL'):
311
- with gr.Row():
312
- model_zip_link = gr.Text(label='Download link to model', info='Should be a zip file containing a .pth model file and an optional .index file.')
313
- model_name = gr.Text(label='Name your model', info='Give your new model a unique name from your other voice models.')
314
-
315
- with gr.Row():
316
- download_btn = gr.Button('Download 🌐', variant='primary', scale=19)
317
- dl_output_message = gr.Text(label='Output Message', interactive=False, scale=20)
318
-
319
- download_btn.click(download_online_model, inputs=[model_zip_link, model_name], outputs=dl_output_message)
320
-
321
- gr.Markdown('## Input Examples')
322
- gr.Examples(
323
- [
324
- ['https://huggingface.co/MrDawg/ToothBrushing/resolve/main/ToothBrushing.zip?download=true', 'ToothBrushing'],
325
- ['https://huggingface.co/sail-rvc/Aldeano_Minecraft__RVC_V2_-_500_Epochs_/resolve/main/model.pth?download=true, https://huggingface.co/sail-rvc/Aldeano_Minecraft__RVC_V2_-_500_Epochs_/resolve/main/model.index?download=true', 'Minecraft_Villager'],
326
- ['https://huggingface.co/phant0m4r/LiSA/resolve/main/LiSA.zip', 'Lisa'],
327
- ['https://pixeldrain.com/u/3tJmABXA', 'Gura'],
328
- ['https://huggingface.co/Kit-Lemonfoot/kitlemonfoot_rvc_models/resolve/main/AZKi%20(Hybrid).zip', 'Azki']
329
- ],
330
- [model_zip_link, model_name],
331
- [],
332
- download_online_model,
333
- cache_examples=False,
334
- )
335
-
336
- with gr.Tab('From Public Index'):
337
-
338
- gr.Markdown('## How to use')
339
- gr.Markdown('- Click Initialize public models table')
340
- gr.Markdown('- Filter models using tags or search bar')
341
- gr.Markdown('- Select a row to autofill the download link and model name')
342
- gr.Markdown('- Click Download')
343
-
344
- with gr.Row():
345
- pub_zip_link = gr.Text(label='Download link to model')
346
- pub_model_name = gr.Text(label='Model name')
347
-
348
- with gr.Row():
349
- download_pub_btn = gr.Button('Download 🌐', variant='primary', scale=19)
350
- pub_dl_output_message = gr.Text(label='Output Message', interactive=False, scale=20)
351
-
352
- filter_tags = gr.CheckboxGroup(value=[], label='Show voice models with tags', choices=[])
353
- search_query = gr.Text(label='Search')
354
- load_public_models_button = gr.Button(value='Initialize public models table', variant='primary')
355
-
356
- public_models_table = gr.DataFrame(value=[], headers=['Model Name', 'Description', 'Credit', 'URL', 'Tags'], label='Available Public Models', interactive=False)
357
- public_models_table.select(pub_dl_autofill, inputs=[public_models_table], outputs=[pub_zip_link, pub_model_name])
358
- load_public_models_button.click(load_public_models, outputs=[public_models_table, filter_tags])
359
- search_query.change(filter_models, inputs=[filter_tags, search_query], outputs=public_models_table)
360
- filter_tags.change(filter_models, inputs=[filter_tags, search_query], outputs=public_models_table)
361
- download_pub_btn.click(download_online_model, inputs=[pub_zip_link, pub_model_name], outputs=pub_dl_output_message)
362
-
363
- # Upload tab
364
- with gr.Tab('Upload model'):
365
- gr.Markdown('## Upload locally trained RVC v2 model and index file')
366
- gr.Markdown('- Find model file (weights folder) and optional index file (logs/[name] folder)')
367
- gr.Markdown('- Compress files into zip file')
368
- gr.Markdown('- Upload zip file and give unique name for voice')
369
- gr.Markdown('- Click Upload model')
370
-
371
- with gr.Row():
372
- with gr.Column():
373
- zip_file = gr.File(label='Zip file')
374
-
375
- local_model_name = gr.Text(label='Model name')
376
-
377
- with gr.Row():
378
- model_upload_button = gr.Button('Upload model', variant='primary', scale=19)
379
- local_upload_output_message = gr.Text(label='Output Message', interactive=False, scale=20)
380
- model_upload_button.click(upload_local_model, inputs=[zip_file, local_model_name], outputs=local_upload_output_message)
381
-
382
- app.launch(
383
- share=args.share_enabled,
384
- debug=args.share_enabled,
385
- show_error=True,
386
- # enable_queue=True,
387
- server_name=None if not args.listen else (args.listen_host or '0.0.0.0'),
388
- server_port=args.listen_port,
389
- ssr_mode=args.ssr
390
- )
 
1
+ import json
2
+ import os
3
+ import shutil
4
+ import urllib.request
5
+ import zipfile
6
+ from argparse import ArgumentParser
7
+ import spaces
8
+ import gradio as gr
9
+ import logging
10
+
11
+ def configure_logging_libs(debug=False):
12
+ modules = [
13
+ "numba",
14
+ "httpx",
15
+ "markdown_it",
16
+ "fairseq",
17
+ "faiss",
18
+ ]
19
+ try:
20
+ for module in modules:
21
+ logging.getLogger(module).setLevel(logging.WARNING)
22
+ os.environ['TF_CPP_MIN_LOG_LEVEL'] = "3" if not debug else "1"
23
+ except Exception as error:
24
+ pass
25
+
26
+ configure_logging_libs()
27
+
28
+ from main import song_cover_pipeline, yt_download
29
+
30
+ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
31
+ IS_ZERO_GPU = os.getenv("SPACES_ZERO_GPU")
32
+ mdxnet_models_dir = os.path.join(BASE_DIR, 'mdxnet_models')
33
+ rvc_models_dir = os.path.join(BASE_DIR, 'rvc_models')
34
+ output_dir = os.path.join(BASE_DIR, 'song_output')
35
+
36
+ def get_current_models(models_dir):
37
+ models_list = os.listdir(models_dir)
38
+ items_to_remove = ['hubert_base.pt', 'MODELS.txt', 'public_models.json', 'rmvpe.pt']
39
+ return [item for item in models_list if item not in items_to_remove]
40
+
41
+ def update_models_list():
42
+ models_l = get_current_models(rvc_models_dir)
43
+ return gr.update(choices=models_l)
44
+
45
+ def load_public_models():
46
+ models_table = []
47
+ for model in public_models['voice_models']:
48
+ if not model['name'] in voice_models:
49
+ model = [model['name'], model['description'], model['credit'], model['url'], ', '.join(model['tags'])]
50
+ models_table.append(model)
51
+ tags = list(public_models['tags'].keys())
52
+ return gr.update(value=models_table), gr.update(choices=tags)
53
+
54
+ def extract_zip(extraction_folder, zip_name):
55
+ os.makedirs(extraction_folder)
56
+ with zipfile.ZipFile(zip_name, 'r') as zip_ref:
57
+ zip_ref.extractall(extraction_folder)
58
+ os.remove(zip_name)
59
+ index_filepath, model_filepath = None, None
60
+ for root, dirs, files in os.walk(extraction_folder):
61
+ for name in files:
62
+ if name.endswith('.index') and os.stat(os.path.join(root, name)).st_size > 1024 * 100:
63
+ index_filepath = os.path.join(root, name)
64
+ if name.endswith('.pth') and os.stat(os.path.join(root, name)).st_size > 1024 * 1024 * 40:
65
+ model_filepath = os.path.join(root, name)
66
+ if not model_filepath:
67
+ raise gr.Error(f'No .pth model file was found in the extracted zip. Please check {extraction_folder}.')
68
+ # move model and index file to extraction folder
69
+ os.rename(model_filepath, os.path.join(extraction_folder, os.path.basename(model_filepath)))
70
+ if index_filepath:
71
+ os.rename(index_filepath, os.path.join(extraction_folder, os.path.basename(index_filepath)))
72
+ # remove any unnecessary nested folders
73
+ for filepath in os.listdir(extraction_folder):
74
+ if os.path.isdir(os.path.join(extraction_folder, filepath)):
75
+ shutil.rmtree(os.path.join(extraction_folder, filepath))
76
+
77
+ def download_online_model(url, dir_name, progress=gr.Progress()):
78
+ try:
79
+ progress(0, desc=f'[~] Downloading voice model with name {dir_name}...')
80
+ zip_name = url.split('/')[-1]
81
+ extraction_folder = os.path.join(rvc_models_dir, dir_name)
82
+ if os.path.exists(extraction_folder):
83
+ raise gr.Error(f'Voice model directory {dir_name} already exists! Choose a different name for your voice model.')
84
+ if 'pixeldrain.com' in url:
85
+ url = f'https://pixeldrain.com/api/file/{zip_name}'
86
+ if "," in url:
87
+ urls = [u.strip() for u in url.split(",") if u.strip()]
88
+ os.makedirs(extraction_folder, exist_ok=True)
89
+ for u in urls:
90
+ u = u.replace("?download=true", "")
91
+ file_name = u.split('/')[-1]
92
+ file_path = os.path.join(extraction_folder, file_name)
93
+ if not os.path.exists(file_path): # avoid re-downloading
94
+ urllib.request.urlretrieve(u, file_path)
95
+ else:
96
+ urllib.request.urlretrieve(url, zip_name)
97
+ progress(0.5, desc='[~] Extracting zip...')
98
+ extract_zip(extraction_folder, zip_name)
99
+ return f'[+] {dir_name} Model successfully downloaded!'
100
+ except Exception as e:
101
+ raise gr.Error(str(e))
102
+
103
+ def upload_local_model(zip_path, dir_name, progress=gr.Progress()):
104
+ try:
105
+ extraction_folder = os.path.join(rvc_models_dir, dir_name)
106
+ if os.path.exists(extraction_folder):
107
+ raise gr.Error(f'Voice model directory {dir_name} already exists! Choose a different name for your voice model.')
108
+ zip_name = zip_path.name
109
+ progress(0.5, desc='[~] Extracting zip...')
110
+ extract_zip(extraction_folder, zip_name)
111
+ return f'[+] {dir_name} Model successfully uploaded!'
112
+ except Exception as e:
113
+ raise gr.Error(str(e))
114
+
115
+ def filter_models(tags, query):
116
+ models_table = []
117
+ # no filter
118
+ if len(tags) == 0 and len(query) == 0:
119
+ for model in public_models['voice_models']:
120
+ models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']])
121
+ # filter based on tags and query
122
+ elif len(tags) > 0 and len(query) > 0:
123
+ for model in public_models['voice_models']:
124
+ if all(tag in model['tags'] for tag in tags):
125
+ model_attributes = f"{model['name']} {model['description']} {model['credit']} {' '.join(model['tags'])}".lower()
126
+ if query.lower() in model_attributes:
127
+ models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']])
128
+ # filter based on only tags
129
+ elif len(tags) > 0:
130
+ for model in public_models['voice_models']:
131
+ if all(tag in model['tags'] for tag in tags):
132
+ models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']])
133
+ # filter based on only query
134
+ else:
135
+ for model in public_models['voice_models']:
136
+ model_attributes = f"{model['name']} {model['description']} {model['credit']} {' '.join(model['tags'])}".lower()
137
+ if query.lower() in model_attributes:
138
+ models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']])
139
+ return gr.update(value=models_table)
140
+
141
+ def pub_dl_autofill(pub_models, event: gr.SelectData):
142
+ return gr.update(value=pub_models.loc[event.index[0], 'URL']), gr.update(value=pub_models.loc[event.index[0], 'Model Name'])
143
+
144
+ def swap_visibility():
145
+ return gr.update(visible=True), gr.update(visible=False), gr.update(value=''), gr.update(value=None)
146
+
147
+ def process_file_upload(file):
148
+ return file.name, gr.update(value=file.name)
149
+
150
+ def show_hop_slider(pitch_detection_algo):
151
+ if pitch_detection_algo == 'mangio-crepe':
152
+ return gr.update(visible=True)
153
+ else:
154
+ return gr.update(visible=False)
155
+
156
+ if __name__ == '__main__':
157
+ parser = ArgumentParser(description='Generate a AI cover song in the song_output/id directory.', add_help=True)
158
+ parser.add_argument("--share", action="store_true", dest="share_enabled", default=False, help="Enable sharing")
159
+ parser.add_argument("--builtin-player", action="store_true", default=False, help="Use the builtin audio player")
160
+ parser.add_argument("--listen", action="store_true", default=False, help="Make the WebUI reachable from your local network.")
161
+ parser.add_argument('--listen-host', type=str, help='The hostname that the server will use.')
162
+ parser.add_argument('--listen-port', type=int, help='The listening port that the server will use.')
163
+ parser.add_argument('--theme', type=str, default="NoCrypt/miku", help='Set the theme (default: NoCrypt/miku)')
164
+ parser.add_argument("--ssr", action="store_true", help="Enable SSR (Server-Side Rendering)")
165
+ args = parser.parse_args()
166
+
167
+ voice_models = get_current_models(rvc_models_dir)
168
+ with open(os.path.join(rvc_models_dir, 'public_models.json'), encoding='utf8') as infile:
169
+ public_models = json.load(infile)
170
+
171
+ with gr.Blocks(title='AICoverGenWebUI', theme=args.theme, fill_width=True, fill_height=False) as app:
172
+ gr.Label(f'AICoverGen WebUI {"ZeroGPU mode" if IS_ZERO_GPU else ""} created with ❤️', show_label=False)
173
+ if IS_ZERO_GPU:
174
+ gr.Markdown(
175
+ """
176
+ <details>
177
+ <summary style="font-size: 1.5em;">⚠️ Important (click to expand)</summary>
178
+ <ul>
179
+ <li>🚀 This demo use a Zero GPU, which is available only for a limited time. It's recommended to use audio files that are no longer than 5 minutes. If you want to use it without time restrictions, you can duplicate the 'old CPU space'. ⏳</li>
180
+ </ul>
181
+ </details>
182
+ """
183
+ )
184
+ gr.Markdown("Duplicate the old CPU space for use in private: [![Duplicate this Space](https://huggingface.co/datasets/huggingface/badges/raw/main/duplicate-this-space-sm-dark.svg)](https://huggingface.co/spaces/r3gm/AICoverGen_old_stable_cpu?duplicate=true)\n\n")
185
+
186
+ # main tab
187
+ with gr.Tab("Generate"):
188
+ with gr.Accordion('Main Options'):
189
+ with gr.Row():
190
+ with gr.Column():
191
+ rvc_model = gr.Dropdown(voice_models, label='Voice Models', info='Models folder "AICoverGen --> rvc_models". After new models are added into this folder, click the refresh button')
192
+ ref_btn = gr.Button('Refresh Models 🔁', variant='primary')
193
+ with gr.Column(visible=False) as yt_link_col:
194
+ song_input = gr.Text(label='Song input', info='Link to a song on YouTube or full path to a local file. For file upload, click the button below.')
195
+ show_file_upload_button = gr.Button('Upload file instead')
196
+ with gr.Column(visible=True) as file_upload_col:
197
+ audio_extensions = ['.mp3', '.m4a', '.flac', '.wav', '.aac', '.ogg', '.wma', '.alac', '.aiff', '.opus', 'amr']
198
+ local_file = gr.File(label='Audio file', interactive=True, type="filepath", file_types=audio_extensions, height=150)
199
+ if not IS_ZERO_GPU:
200
+ with gr.Row():
201
+ with gr.Row(scale=2):
202
+ url_media_gui = gr.Textbox(value="", label="Enter URL", placeholder="www.youtube.com/watch?v=g_9rPvbENUw", lines=1)
203
+ with gr.Row(scale=1):
204
+ url_button_gui = gr.Button("Process URL", variant="secondary")
205
+ url_button_gui.click(yt_download, [url_media_gui], [local_file])
206
+ song_input_file = gr.UploadButton('Upload 📂', file_types=['audio'], variant='primary', visible=False)
207
+ show_yt_link_button = gr.Button('Paste YouTube link/Path to local file instead', visible=False)
208
+ song_input_file.upload(process_file_upload, inputs=[song_input_file], outputs=[local_file, song_input])
209
+
210
+ with gr.Column():
211
+ pitch = gr.Slider(-3, 3, value=0, step=1, label='Pitch Change (Vocals ONLY)', info='Generally, use 1 for male to female conversions and -1 for vice-versa. (Octaves)')
212
+ pitch_all = gr.Slider(-12, 12, value=0, step=1, label='Overall Pitch Change', info='Changes pitch/key of vocals and instrumentals together. Altering this slightly reduces sound quality. (Semitones)')
213
+
214
+ show_file_upload_button.click(swap_visibility, outputs=[file_upload_col, yt_link_col, song_input, local_file])
215
+ show_yt_link_button.click(swap_visibility, outputs=[yt_link_col, file_upload_col, song_input, local_file])
216
+
217
+ with gr.Accordion('Voice conversion options', open=False):
218
+ with gr.Row():
219
+ index_rate = gr.Slider(0, 1, value=0.5, label='Index Rate', info="Controls how much of the AI voice's accent to keep in the vocals")
220
+ filter_radius = gr.Slider(0, 7, value=3, step=1, label='Filter radius', info='If >=3: apply median filtering median filtering to the harvested pitch results. Can reduce breathiness')
221
+ rms_mix_rate = gr.Slider(0, 1, value=0.25, label='RMS mix rate', info="Control how much to mimic the original vocal's loudness (0) or a fixed loudness (1)")
222
+ protect = gr.Slider(0, 0.5, value=0.33, label='Protect rate', info='Protect voiceless consonants and breath sounds. Set to 0.5 to disable.')
223
+ with gr.Column():
224
+ f0_method = gr.Dropdown(['rmvpe+', 'rmvpe', 'mangio-crepe'], value='rmvpe+', label='Pitch detection algorithm', info='Best option is rmvpe (clarity in vocals), then mangio-crepe (smoother vocals), rmvpe+ use a minimum and maximum allowed pitch values.')
225
+ crepe_hop_length = gr.Slider(32, 320, value=128, step=1, visible=False, label='Crepe hop length', info='Lower values leads to longer conversions and higher risk of voice cracks, but better pitch accuracy.')
226
+ f0_method.change(show_hop_slider, inputs=f0_method, outputs=crepe_hop_length)
227
+ with gr.Row():
228
+ with gr.Row():
229
+ steps = gr.Slider(minimum=1, maximum=3, label="Steps", value=1, step=1, interactive=True)
230
+ with gr.Row():
231
+ extra_denoise = gr.Checkbox(True, label='Denoise', info='Apply an additional noise reduction step to clean up the audio further.')
232
+ keep_files = gr.Checkbox((False if IS_ZERO_GPU else True), label='Keep intermediate files', info='Keep all audio files generated in the song_output/id directory, e.g. Isolated Vocals/Instrumentals. Leave unchecked to save space', interactive=(False if IS_ZERO_GPU else True))
233
+
234
+ with gr.Accordion('Audio mixing options', open=False):
235
+ gr.Markdown('### Volume Change (decibels)')
236
+ with gr.Row():
237
+ main_gain = gr.Slider(-20, 20, value=0, step=1, label='Main Vocals')
238
+ backup_gain = gr.Slider(-20, 20, value=0, step=1, label='Backup Vocals')
239
+ inst_gain = gr.Slider(-20, 20, value=0, step=1, label='Music')
240
+ gr.Markdown('### Reverb Control on AI Vocals')
241
+ with gr.Row():
242
+ reverb_rm_size = gr.Slider(0, 1, value=0.15, label='Room size', info='The larger the room, the longer the reverb time')
243
+ reverb_wet = gr.Slider(0, 1, value=0.2, label='Wetness level', info='Level of AI vocals with reverb')
244
+ reverb_dry = gr.Slider(0, 1, value=0.8, label='Dryness level', info='Level of AI vocals without reverb')
245
+ reverb_damping = gr.Slider(0, 1, value=0.7, label='Damping level', info='Absorption of high frequencies in the reverb')
246
+ gr.Markdown('### Audio Output Format')
247
+ output_format = gr.Dropdown(['mp3', 'wav'], value='mp3', label='Output file type', info='mp3: small file size, decent quality. wav: Large file size, best quality')
248
+
249
+ with gr.Row():
250
+ clear_btn = gr.ClearButton(value='Clear', components=[song_input, rvc_model, keep_files, local_file])
251
+ generate_btn = gr.Button("Generate", variant='primary')
252
+
253
+ # التعديل هنا: تم فرض مشغل الصوت المباشر دائماً دون شروط
254
+ ai_cover = gr.Audio(label='AI Cover', show_share_button=True)
255
+
256
+ gr.Markdown("- You can also try `AICoverGen❤️` in Colab’s free tier, which provides free GPU [link](https://github.com/R3gm/AICoverGen?tab=readme-ov-file#aicovergen).")
257
+
258
+ ref_btn.click(update_models_list, None, outputs=rvc_model)
259
+ is_webui = gr.Number(value=1, visible=False)
260
+ generate_btn.click(song_cover_pipeline,
261
+ inputs=[local_file, rvc_model, pitch, keep_files, is_webui, main_gain, backup_gain, inst_gain, index_rate, filter_radius, rms_mix_rate, f0_method, crepe_hop_length, protect, pitch_all, reverb_rm_size, reverb_wet, reverb_dry, reverb_damping, output_format, extra_denoise, steps],
262
+ outputs=[ai_cover])
263
+ clear_btn.click(lambda: [0, 0, 0, 0, 0.5, 3, 0.25, 0.33, 'rmvpe+', 128, 0, 0.15, 0.2, 0.8, 0.7, 'mp3', None, True, 1],
264
+ outputs=[pitch, main_gain, backup_gain, inst_gain, index_rate, filter_radius, rms_mix_rate, protect, f0_method, crepe_hop_length, pitch_all, reverb_rm_size, reverb_wet, reverb_dry, reverb_damping, output_format, ai_cover, extra_denoise, steps])
265
+
266
+ # Download tab
267
+ with gr.Tab('Download model'):
268
+ with gr.Tab('From HuggingFace/Pixeldrain URL'):
269
+ with gr.Row():
270
+ model_zip_link = gr.Text(label='Download link to model', info='Should be a zip file containing a .pth model file and an optional .index file.')
271
+ model_name = gr.Text(label='Name your model', info='Give your new model a unique name from your other voice models.')
272
+ with gr.Row():
273
+ download_btn = gr.Button('Download 🌐', variant='primary', scale=19)
274
+ dl_output_message = gr.Text(label='Output Message', interactive=False, scale=20)
275
+ download_btn.click(download_online_model, inputs=[model_zip_link, model_name], outputs=dl_output_message)
276
+
277
+ gr.Markdown('## Input Examples')
278
+ gr.Examples(
279
+ [
280
+ ['https://huggingface.co/MrDawg/ToothBrushing/resolve/main/ToothBrushing.zip?download=true', 'ToothBrushing'],
281
+ ['https://huggingface.co/sail-rvc/Aldeano_Minecraft__RVC_V2_-_500_Epochs_/resolve/main/model.pth?download=true, https://huggingface.co/sail-rvc/Aldeano_Minecraft__RVC_V2_-_500_Epochs_/resolve/main/model.index?download=true', 'Minecraft_Villager'],
282
+ ['https://huggingface.co/phant0m4r/LiSA/resolve/main/LiSA.zip', 'Lisa'],
283
+ ['https://pixeldrain.com/u/3tJmABXA', 'Gura'],
284
+ ['https://huggingface.co/Kit-Lemonfoot/kitlemonfoot_rvc_models/resolve/main/AZKi%20(Hybrid).zip', 'Azki']
285
+ ],
286
+ [model_zip_link, model_name],
287
+ [],
288
+ download_online_model,
289
+ cache_examples=False,
290
+ )
291
+
292
+ with gr.Tab('From Public Index'):
293
+ gr.Markdown('## How to use')
294
+ gr.Markdown('- Click Initialize public models table')
295
+ gr.Markdown('- Filter models using tags or search bar')
296
+ gr.Markdown('- Select a row to autofill the download link and model name')
297
+ gr.Markdown('- Click Download')
298
+ with gr.Row():
299
+ pub_zip_link = gr.Text(label='Download link to model')
300
+ pub_model_name = gr.Text(label='Model name')
301
+ with gr.Row():
302
+ download_pub_btn = gr.Button('Download 🌐', variant='primary', scale=19)
303
+ pub_dl_output_message = gr.Text(label='Output Message', interactive=False, scale=20)
304
+ filter_tags = gr.CheckboxGroup(value=[], label='Show voice models with tags', choices=[])
305
+ search_query = gr.Text(label='Search')
306
+ load_public_models_button = gr.Button(value='Initialize public models table', variant='primary')
307
+ public_models_table = gr.DataFrame(value=[], headers=['Model Name', 'Description', 'Credit', 'URL', 'Tags'], label='Available Public Models', interactive=False)
308
+ public_models_table.select(pub_dl_autofill, inputs=[public_models_table], outputs=[pub_zip_link, pub_model_name])
309
+ load_public_models_button.click(load_public_models, outputs=[public_models_table, filter_tags])
310
+ search_query.change(filter_models, inputs=[filter_tags, search_query], outputs=public_models_table)
311
+ filter_tags.change(filter_models, inputs=[filter_tags, search_query], outputs=public_models_table)
312
+ download_pub_btn.click(download_online_model, inputs=[pub_zip_link, pub_model_name], outputs=pub_dl_output_message)
313
+
314
+ # Upload tab
315
+ with gr.Tab('Upload model'):
316
+ gr.Markdown('## Upload locally trained RVC v2 model and index file')
317
+ gr.Markdown('- Find model file (weights folder) and optional index file (logs/[name] folder)')
318
+ gr.Markdown('- Compress files into zip file')
319
+ gr.Markdown('- Upload zip file and give unique name for voice')
320
+ gr.Markdown('- Click Upload model')
321
+ with gr.Row():
322
+ with gr.Column():
323
+ zip_file = gr.File(label='Zip file')
324
+ local_model_name = gr.Text(label='Model name')
325
+ with gr.Row():
326
+ model_upload_button = gr.Button('Upload model', variant='primary', scale=19)
327
+ local_upload_output_message = gr.Text(label='Output Message', interactive=False, scale=20)
328
+ model_upload_button.click(upload_local_model, inputs=[zip_file, local_model_name], outputs=local_upload_output_message)
329
+
330
+ app.launch(
331
+ share=args.share_enabled,
332
+ debug=args.share_enabled,
333
+ show_error=True,
334
+ server_name=None if not args.listen else (args.listen_host or '0.0.0.0'),
335
+ server_port=args.listen_port,
336
+ ssr_mode=args.ssr
337
+ )