Adam3 commited on
Commit
de723d1
·
verified ·
1 Parent(s): 1806c3f

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +696 -0
app.py ADDED
@@ -0,0 +1,696 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import shutil
4
+ import urllib.request
5
+ import zipfile
6
+ from argparse import ArgumentParser
7
+
8
+ import gradio as gr
9
+
10
+ from main import song_cover_pipeline
11
+
12
+ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
13
+
14
+ mdxnet_models_dir = os.path.join(BASE_DIR, 'mdxnet_models')
15
+ rvc_models_dir = os.path.join(BASE_DIR, 'rvc_models')
16
+ output_dir = os.path.join(BASE_DIR, 'song_output')
17
+
18
+
19
+ def get_current_models(models_dir):
20
+ models_list = os.listdir(models_dir)
21
+ items_to_remove = ['hubert_base.pt', 'MODELS.txt', 'public_models.json', 'rmvpe.pt']
22
+ return [item for item in models_list if item not in items_to_remove]
23
+
24
+
25
+ def update_models_list():
26
+ models_l = get_current_models(rvc_models_dir)
27
+ return gr.Dropdown.update(choices=models_l)
28
+
29
+
30
+ def load_public_models():
31
+ models_table = []
32
+ for model in public_models['voice_models']:
33
+ if not model['name'] in voice_models:
34
+ model = [model['name'], model['description'], model['credit'], model['url'], ', '.join(model['tags'])]
35
+ models_table.append(model)
36
+
37
+ tags = list(public_models['tags'].keys())
38
+ return gr.DataFrame.update(value=models_table), gr.CheckboxGroup.update(choices=tags)
39
+
40
+
41
+ def extract_zip(extraction_folder, zip_name):
42
+ os.makedirs(extraction_folder)
43
+ with zipfile.ZipFile(zip_name, 'r') as zip_ref:
44
+ zip_ref.extractall(extraction_folder)
45
+ os.remove(zip_name)
46
+
47
+ index_filepath, model_filepath = None, None
48
+ for root, dirs, files in os.walk(extraction_folder):
49
+ for name in files:
50
+ if name.endswith('.index') and os.stat(os.path.join(root, name)).st_size > 1024 * 100:
51
+ index_filepath = os.path.join(root, name)
52
+
53
+ if name.endswith('.pth') and os.stat(os.path.join(root, name)).st_size > 1024 * 1024 * 40:
54
+ model_filepath = os.path.join(root, name)
55
+
56
+ if not model_filepath:
57
+ raise gr.Error(f'No .pth model file was found in the extracted zip. Please check {extraction_folder}.')
58
+
59
+ # move model and index file to extraction folder
60
+ os.rename(model_filepath, os.path.join(extraction_folder, os.path.basename(model_filepath)))
61
+ if index_filepath:
62
+ os.rename(index_filepath, os.path.join(extraction_folder, os.path.basename(index_filepath)))
63
+
64
+ # remove any unnecessary nested folders
65
+ for filepath in os.listdir(extraction_folder):
66
+ if os.path.isdir(os.path.join(extraction_folder, filepath)):
67
+ shutil.rmtree(os.path.join(extraction_folder, filepath))
68
+
69
+
70
+ def download_online_model(url, dir_name, progress=gr.Progress()):
71
+ try:
72
+ if not url or not url.strip():
73
+ raise gr.Error('Please enter a download URL.')
74
+
75
+ if not dir_name or not dir_name.strip():
76
+ raise gr.Error('Please enter a model name.')
77
+
78
+ progress(0, desc=f'[~] Downloading voice model with name {dir_name}...')
79
+ zip_name = url.split('/')[-1]
80
+ extraction_folder = os.path.join(rvc_models_dir, dir_name.strip())
81
+
82
+ if os.path.exists(extraction_folder):
83
+ # Check if directory is empty or contains model files
84
+ existing_files = os.listdir(extraction_folder)
85
+ if existing_files:
86
+ raise gr.Error(f'Voice model directory "{dir_name}" already exists and contains files! Choose a different name for your voice model.')
87
+ else:
88
+ # Directory exists but is empty, we can use it
89
+ pass
90
+
91
+ if 'pixeldrain.com' in url:
92
+ url = f'https://pixeldrain.com/api/file/{zip_name}'
93
+
94
+ urllib.request.urlretrieve(url, zip_name)
95
+
96
+ progress(0.5, desc='[~] Extracting zip...')
97
+ extract_zip(extraction_folder, zip_name)
98
+ return f'[+] {dir_name} Model successfully downloaded!'
99
+
100
+ except Exception as e:
101
+ raise gr.Error(str(e))
102
+
103
+
104
+ def upload_local_model(zip_path, dir_name, progress=gr.Progress()):
105
+ try:
106
+ if not zip_path:
107
+ raise gr.Error('Please select a zip file to upload.')
108
+
109
+ if not dir_name or not dir_name.strip():
110
+ raise gr.Error('Please enter a model name.')
111
+
112
+ extraction_folder = os.path.join(rvc_models_dir, dir_name.strip())
113
+ if os.path.exists(extraction_folder):
114
+ # Check if directory is empty or contains model files
115
+ existing_files = os.listdir(extraction_folder)
116
+ if existing_files:
117
+ raise gr.Error(f'Voice model directory "{dir_name}" already exists and contains files! Choose a different name for your voice model.')
118
+ else:
119
+ # Directory exists but is empty, we can use it
120
+ pass
121
+
122
+ zip_name = zip_path.name
123
+ progress(0.5, desc='[~] Extracting zip...')
124
+ extract_zip(extraction_folder, zip_name)
125
+ return f'[+] {dir_name} Model successfully uploaded!'
126
+
127
+ except Exception as e:
128
+ raise gr.Error(str(e))
129
+
130
+
131
+ def filter_models(tags, query):
132
+ models_table = []
133
+
134
+ # no filter
135
+ if len(tags) == 0 and len(query) == 0:
136
+ for model in public_models['voice_models']:
137
+ models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']])
138
+
139
+ # filter based on tags and query
140
+ elif len(tags) > 0 and len(query) > 0:
141
+ for model in public_models['voice_models']:
142
+ if all(tag in model['tags'] for tag in tags):
143
+ model_attributes = f"{model['name']} {model['description']} {model['credit']} {' '.join(model['tags'])}".lower()
144
+ if query.lower() in model_attributes:
145
+ models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']])
146
+
147
+ # filter based on only tags
148
+ elif len(tags) > 0:
149
+ for model in public_models['voice_models']:
150
+ if all(tag in model['tags'] for tag in tags):
151
+ models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']])
152
+
153
+ # filter based on only query
154
+ else:
155
+ for model in public_models['voice_models']:
156
+ model_attributes = f"{model['name']} {model['description']} {model['credit']} {' '.join(model['tags'])}".lower()
157
+ if query.lower() in model_attributes:
158
+ models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']])
159
+
160
+ return gr.DataFrame.update(value=models_table)
161
+
162
+
163
+ def pub_dl_autofill(pub_models, event: gr.SelectData):
164
+ return gr.Text.update(value=pub_models.loc[event.index[0], 'URL']), gr.Text.update(value=pub_models.loc[event.index[0], 'Model Name'])
165
+
166
+
167
+ def swap_visibility():
168
+ return gr.update(visible=True), gr.update(visible=False), gr.update(value=''), gr.update(value=None)
169
+
170
+
171
+ def process_file_upload(file):
172
+ return file.name, gr.update(value=file.name)
173
+
174
+
175
+ def show_hop_slider(pitch_detection_algo):
176
+ if pitch_detection_algo == 'mangio-crepe':
177
+ return gr.update(visible=True)
178
+ else:
179
+ return gr.update(visible=False)
180
+
181
+
182
+ if __name__ == '__main__':
183
+ parser = ArgumentParser(description='Generate a AI cover song in the song_output/id directory.', add_help=True)
184
+ parser.add_argument("--share", action="store_true", dest="share_enabled", default=False, help="Enable sharing")
185
+ parser.add_argument("--listen", action="store_true", default=False, help="Make the WebUI reachable from your local network.")
186
+ parser.add_argument('--listen-host', type=str, help='The hostname that the server will use.')
187
+ parser.add_argument('--listen-port', type=int, help='The listening port that the server will use.')
188
+ args = parser.parse_args()
189
+
190
+ voice_models = get_current_models(rvc_models_dir)
191
+ with open(os.path.join(rvc_models_dir, 'public_models.json'), encoding='utf8') as infile:
192
+ public_models = json.load(infile)
193
+
194
+ with gr.Blocks(title='AICoverGenWebUI') as app:
195
+
196
+ gr.Label('AICoverGen WebUI created with ❤️', show_label=False)
197
+
198
+ # main tab
199
+ with gr.Tab("Generate"):
200
+
201
+ with gr.Accordion('Main Options'):
202
+ with gr.Row():
203
+ with gr.Column():
204
+ 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')
205
+ ref_btn = gr.Button('Refresh Models 🔁', variant='primary')
206
+
207
+ with gr.Column() as yt_link_col:
208
+ 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.')
209
+ show_file_upload_button = gr.Button('Upload file instead')
210
+
211
+ with gr.Column(visible=False) as file_upload_col:
212
+ local_file = gr.File(label='Audio file')
213
+ song_input_file = gr.UploadButton('Upload 📂', file_types=['audio'], variant='primary')
214
+ show_yt_link_button = gr.Button('Paste YouTube link/Path to local file instead')
215
+ song_input_file.upload(process_file_upload, inputs=[song_input_file], outputs=[local_file, song_input])
216
+
217
+ with gr.Column():
218
+ 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)')
219
+ 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)')
220
+ show_file_upload_button.click(swap_visibility, outputs=[file_upload_col, yt_link_col, song_input, local_file])
221
+ show_yt_link_button.click(swap_visibility, outputs=[yt_link_col, file_upload_col, song_input, local_file])
222
+
223
+ with gr.Accordion('Voice conversion options', open=False):
224
+ with gr.Row():
225
+ 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")
226
+ 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')
227
+ 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)")
228
+ 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.')
229
+ with gr.Column():
230
+ f0_method = gr.Dropdown(['rmvpe', 'mangio-crepe'], value='rmvpe', label='Pitch detection algorithm', info='Best option is rmvpe (clarity in vocals), then mangio-crepe (smoother vocals)')
231
+ 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.')
232
+ f0_method.change(show_hop_slider, inputs=f0_method, outputs=crepe_hop_length)
233
+ keep_files = gr.Checkbox(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')
234
+
235
+ with gr.Accordion('Audio mixing options', open=False):
236
+ gr.Markdown('### Volume Change (decibels)')
237
+ with gr.Row():
238
+ main_gain = gr.Slider(-20, 20, value=0, step=1, label='Main Vocals')
239
+ backup_gain = gr.Slider(-20, 20, value=0, step=1, label='Backup Vocals')
240
+ inst_gain = gr.Slider(-20, 20, value=0, step=1, label='Music')
241
+
242
+ gr.Markdown('### Reverb Control on AI Vocals')
243
+ with gr.Row():
244
+ reverb_rm_size = gr.Slider(0, 1, value=0.15, label='Room size', info='The larger the room, the longer the reverb time')
245
+ reverb_wet = gr.Slider(0, 1, value=0.2, label='Wetness level', info='Level of AI vocals with reverb')
246
+ reverb_dry = gr.Slider(0, 1, value=0.8, label='Dryness level', info='Level of AI vocals without reverb')
247
+ reverb_damping = gr.Slider(0, 1, value=0.7, label='Damping level', info='Absorption of high frequencies in the reverb')
248
+
249
+ gr.Markdown('### Audio Output Format')
250
+ 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')
251
+
252
+ with gr.Row():
253
+ clear_btn = gr.ClearButton(value='Clear', components=[song_input, rvc_model, keep_files, local_file])
254
+ generate_btn = gr.Button("Generate", variant='primary')
255
+ ai_cover = gr.Audio(label='AI Cover', show_share_button=False)
256
+
257
+ ref_btn.click(update_models_list, None, outputs=rvc_model)
258
+ is_webui = gr.Number(value=1, visible=False)
259
+ generate_btn.click(song_cover_pipeline,
260
+ inputs=[song_input, rvc_model, pitch, keep_files, is_webui, main_gain, backup_gain,
261
+ inst_gain, index_rate, filter_radius, rms_mix_rate, f0_method, crepe_hop_length,
262
+ protect, pitch_all, reverb_rm_size, reverb_wet, reverb_dry, reverb_damping,
263
+ output_format],
264
+ outputs=[ai_cover],
265
+ show_progress=True)
266
+ 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],
267
+ outputs=[pitch, main_gain, backup_gain, inst_gain, index_rate, filter_radius, rms_mix_rate,
268
+ protect, f0_method, crepe_hop_length, pitch_all, reverb_rm_size, reverb_wet,
269
+ reverb_dry, reverb_damping, output_format, ai_cover])
270
+
271
+ # Download tab
272
+ with gr.Tab('Download model'):
273
+
274
+ with gr.Tab('From HuggingFace/Pixeldrain URL'):
275
+ with gr.Row():
276
+ 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.')
277
+ model_name = gr.Text(label='Name your model', info='Give your new model a unique name from your other voice models.')
278
+
279
+ with gr.Row():
280
+ download_btn = gr.Button('Download 🌐', variant='primary', scale=19)
281
+ dl_output_message = gr.Text(label='Output Message', interactive=False, scale=20)
282
+
283
+ download_btn.click(download_online_model, inputs=[model_zip_link, model_name], outputs=dl_output_message)
284
+
285
+ gr.Markdown('## Input Examples')
286
+ gr.Examples(
287
+ [
288
+ ['https://huggingface.co/phant0m4r/LiSA/resolve/main/LiSA.zip', 'Lisa'],
289
+ ['https://pixeldrain.com/u/3tJmABXA', 'Gura'],
290
+ ['https://huggingface.co/Kit-Lemonfoot/kitlemonfoot_rvc_models/resolve/main/AZKi%20(Hybrid).zip', 'Azki']
291
+ ],
292
+ [model_zip_link, model_name],
293
+ [],
294
+ download_online_model,
295
+ )
296
+
297
+ with gr.Tab('From Public Index'):
298
+
299
+ gr.Markdown('## How to use')
300
+ gr.Markdown('- Click Initialize public models table')
301
+ gr.Markdown('- Filter models using tags or search bar')
302
+ gr.Markdown('- Select a row to autofill the download link and model name')
303
+ gr.Markdown('- Click Download')
304
+
305
+ with gr.Row():
306
+ pub_zip_link = gr.Text(label='Download link to model')
307
+ pub_model_name = gr.Text(label='Model name')
308
+
309
+ with gr.Row():
310
+ download_pub_btn = gr.Button('Download 🌐', variant='primary', scale=19)
311
+ pub_dl_output_message = gr.Text(label='Output Message', interactive=False, scale=20)
312
+
313
+ filter_tags = gr.CheckboxGroup(value=[], label='Show voice models with tags', choices=[])
314
+ search_query = gr.Text(label='Search')
315
+ load_public_models_button = gr.Button(value='Initialize public models table', variant='primary')
316
+
317
+ public_models_table = gr.DataFrame(value=[], headers=['Model Name', 'Description', 'Credit', 'URL', 'Tags'], label='Available Public Models', interactive=False)
318
+ public_models_table.select(pub_dl_autofill, inputs=[public_models_table], outputs=[pub_zip_link, pub_model_name])
319
+ load_public_models_button.click(load_public_models, outputs=[public_models_table, filter_tags])
320
+ search_query.change(filter_models, inputs=[filter_tags, search_query], outputs=public_models_table)
321
+ filter_tags.change(filter_models, inputs=[filter_tags, search_query], outputs=public_models_table)
322
+ download_pub_btn.click(download_online_model, inputs=[pub_zip_link, pub_model_name], outputs=pub_dl_output_message)
323
+
324
+ # Upload tab
325
+ with gr.Tab('Upload model'):
326
+ gr.Markdown('## Upload locally trained RVC v2 model and index file')
327
+ gr.Markdown('- Find model file (weights folder) and optional index file (logs/[name] folder)')
328
+ gr.Markdown('- Compress files into zip file')
329
+ gr.Markdown('- Upload zip file and give unique name for voice')
330
+ gr.Markdown('- Click Upload model')
331
+
332
+ with gr.Row():
333
+ with gr.Column():
334
+ zip_file = gr.File(label='Zip file')
335
+
336
+ local_model_name = gr.Text(label='Model name')
337
+
338
+ with gr.Row():
339
+ model_upload_button = gr.Button('Upload model', variant='primary', scale=19)
340
+ local_upload_output_message = gr.Text(label='Output Message', interactive=False, scale=20)
341
+ model_upload_button.click(upload_local_model, inputs=[zip_file, local_model_name], outputs=local_upload_output_message)
342
+
343
+ app.launch(
344
+ share=args.share_enabled,
345
+ enable_queue=True,
346
+ server_name=None if not args.listen else (args.listen_host or '0.0.0.0'),
347
+ server_port=args.listen_port,
348
+ )
349
+ import json
350
+ import os
351
+ import shutil
352
+ import urllib.request
353
+ import zipfile
354
+ from argparse import ArgumentParser
355
+
356
+ import gradio as gr
357
+
358
+ from main import song_cover_pipeline
359
+
360
+ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
361
+
362
+ mdxnet_models_dir = os.path.join(BASE_DIR, 'mdxnet_models')
363
+ rvc_models_dir = os.path.join(BASE_DIR, 'rvc_models')
364
+ output_dir = os.path.join(BASE_DIR, 'song_output')
365
+
366
+
367
+ def get_current_models(models_dir):
368
+ models_list = os.listdir(models_dir)
369
+ items_to_remove = ['hubert_base.pt', 'MODELS.txt', 'public_models.json', 'rmvpe.pt']
370
+ return [item for item in models_list if item not in items_to_remove]
371
+
372
+
373
+ def update_models_list():
374
+ models_l = get_current_models(rvc_models_dir)
375
+ return gr.Dropdown.update(choices=models_l)
376
+
377
+
378
+ def load_public_models():
379
+ models_table = []
380
+ for model in public_models['voice_models']:
381
+ if not model['name'] in voice_models:
382
+ model = [model['name'], model['description'], model['credit'], model['url'], ', '.join(model['tags'])]
383
+ models_table.append(model)
384
+
385
+ tags = list(public_models['tags'].keys())
386
+ return gr.DataFrame.update(value=models_table), gr.CheckboxGroup.update(choices=tags)
387
+
388
+
389
+ def extract_zip(extraction_folder, zip_name):
390
+ os.makedirs(extraction_folder)
391
+ with zipfile.ZipFile(zip_name, 'r') as zip_ref:
392
+ zip_ref.extractall(extraction_folder)
393
+ os.remove(zip_name)
394
+
395
+ index_filepath, model_filepath = None, None
396
+ for root, dirs, files in os.walk(extraction_folder):
397
+ for name in files:
398
+ if name.endswith('.index') and os.stat(os.path.join(root, name)).st_size > 1024 * 100:
399
+ index_filepath = os.path.join(root, name)
400
+
401
+ if name.endswith('.pth') and os.stat(os.path.join(root, name)).st_size > 1024 * 1024 * 40:
402
+ model_filepath = os.path.join(root, name)
403
+
404
+ if not model_filepath:
405
+ raise gr.Error(f'No .pth model file was found in the extracted zip. Please check {extraction_folder}.')
406
+
407
+ # move model and index file to extraction folder
408
+ os.rename(model_filepath, os.path.join(extraction_folder, os.path.basename(model_filepath)))
409
+ if index_filepath:
410
+ os.rename(index_filepath, os.path.join(extraction_folder, os.path.basename(index_filepath)))
411
+
412
+ # remove any unnecessary nested folders
413
+ for filepath in os.listdir(extraction_folder):
414
+ if os.path.isdir(os.path.join(extraction_folder, filepath)):
415
+ shutil.rmtree(os.path.join(extraction_folder, filepath))
416
+
417
+
418
+ def download_online_model(url, dir_name, progress=gr.Progress()):
419
+ try:
420
+ if not url or not url.strip():
421
+ raise gr.Error('Please enter a download URL.')
422
+
423
+ if not dir_name or not dir_name.strip():
424
+ raise gr.Error('Please enter a model name.')
425
+
426
+ progress(0, desc=f'[~] Downloading voice model with name {dir_name}...')
427
+ zip_name = url.split('/')[-1]
428
+ extraction_folder = os.path.join(rvc_models_dir, dir_name.strip())
429
+
430
+ if os.path.exists(extraction_folder):
431
+ # Check if directory is empty or contains model files
432
+ existing_files = os.listdir(extraction_folder)
433
+ if existing_files:
434
+ raise gr.Error(f'Voice model directory "{dir_name}" already exists and contains files! Choose a different name for your voice model.')
435
+ else:
436
+ # Directory exists but is empty, we can use it
437
+ pass
438
+
439
+ if 'pixeldrain.com' in url:
440
+ url = f'https://pixeldrain.com/api/file/{zip_name}'
441
+
442
+ urllib.request.urlretrieve(url, zip_name)
443
+
444
+ progress(0.5, desc='[~] Extracting zip...')
445
+ extract_zip(extraction_folder, zip_name)
446
+ return f'[+] {dir_name} Model successfully downloaded!'
447
+
448
+ except Exception as e:
449
+ raise gr.Error(str(e))
450
+
451
+
452
+ def upload_local_model(zip_path, dir_name, progress=gr.Progress()):
453
+ try:
454
+ if not zip_path:
455
+ raise gr.Error('Please select a zip file to upload.')
456
+
457
+ if not dir_name or not dir_name.strip():
458
+ raise gr.Error('Please enter a model name.')
459
+
460
+ extraction_folder = os.path.join(rvc_models_dir, dir_name.strip())
461
+ if os.path.exists(extraction_folder):
462
+ # Check if directory is empty or contains model files
463
+ existing_files = os.listdir(extraction_folder)
464
+ if existing_files:
465
+ raise gr.Error(f'Voice model directory "{dir_name}" already exists and contains files! Choose a different name for your voice model.')
466
+ else:
467
+ # Directory exists but is empty, we can use it
468
+ pass
469
+
470
+ zip_name = zip_path.name
471
+ progress(0.5, desc='[~] Extracting zip...')
472
+ extract_zip(extraction_folder, zip_name)
473
+ return f'[+] {dir_name} Model successfully uploaded!'
474
+
475
+ except Exception as e:
476
+ raise gr.Error(str(e))
477
+
478
+
479
+ def filter_models(tags, query):
480
+ models_table = []
481
+
482
+ # no filter
483
+ if len(tags) == 0 and len(query) == 0:
484
+ for model in public_models['voice_models']:
485
+ models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']])
486
+
487
+ # filter based on tags and query
488
+ elif len(tags) > 0 and len(query) > 0:
489
+ for model in public_models['voice_models']:
490
+ if all(tag in model['tags'] for tag in tags):
491
+ model_attributes = f"{model['name']} {model['description']} {model['credit']} {' '.join(model['tags'])}".lower()
492
+ if query.lower() in model_attributes:
493
+ models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']])
494
+
495
+ # filter based on only tags
496
+ elif len(tags) > 0:
497
+ for model in public_models['voice_models']:
498
+ if all(tag in model['tags'] for tag in tags):
499
+ models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']])
500
+
501
+ # filter based on only query
502
+ else:
503
+ for model in public_models['voice_models']:
504
+ model_attributes = f"{model['name']} {model['description']} {model['credit']} {' '.join(model['tags'])}".lower()
505
+ if query.lower() in model_attributes:
506
+ models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']])
507
+
508
+ return gr.DataFrame.update(value=models_table)
509
+
510
+
511
+ def pub_dl_autofill(pub_models, event: gr.SelectData):
512
+ return gr.Text.update(value=pub_models.loc[event.index[0], 'URL']), gr.Text.update(value=pub_models.loc[event.index[0], 'Model Name'])
513
+
514
+
515
+ def swap_visibility():
516
+ return gr.update(visible=True), gr.update(visible=False), gr.update(value=''), gr.update(value=None)
517
+
518
+
519
+ def process_file_upload(file):
520
+ return file.name, gr.update(value=file.name)
521
+
522
+
523
+ def show_hop_slider(pitch_detection_algo):
524
+ if pitch_detection_algo == 'mangio-crepe':
525
+ return gr.update(visible=True)
526
+ else:
527
+ return gr.update(visible=False)
528
+
529
+
530
+ if __name__ == '__main__':
531
+ parser = ArgumentParser(description='Generate a AI cover song in the song_output/id directory.', add_help=True)
532
+ parser.add_argument("--share", action="store_true", dest="share_enabled", default=False, help="Enable sharing")
533
+ parser.add_argument("--listen", action="store_true", default=False, help="Make the WebUI reachable from your local network.")
534
+ parser.add_argument('--listen-host', type=str, help='The hostname that the server will use.')
535
+ parser.add_argument('--listen-port', type=int, help='The listening port that the server will use.')
536
+ args = parser.parse_args()
537
+
538
+ voice_models = get_current_models(rvc_models_dir)
539
+ with open(os.path.join(rvc_models_dir, 'public_models.json'), encoding='utf8') as infile:
540
+ public_models = json.load(infile)
541
+
542
+ with gr.Blocks(title='AICoverGenWebUI') as app:
543
+
544
+ gr.Label('AICoverGen WebUI created with ❤️', show_label=False)
545
+
546
+ # main tab
547
+ with gr.Tab("Generate"):
548
+
549
+ with gr.Accordion('Main Options'):
550
+ with gr.Row():
551
+ with gr.Column():
552
+ 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')
553
+ ref_btn = gr.Button('Refresh Models 🔁', variant='primary')
554
+
555
+ with gr.Column() as yt_link_col:
556
+ 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.')
557
+ show_file_upload_button = gr.Button('Upload file instead')
558
+
559
+ with gr.Column(visible=False) as file_upload_col:
560
+ local_file = gr.File(label='Audio file')
561
+ song_input_file = gr.UploadButton('Upload 📂', file_types=['audio'], variant='primary')
562
+ show_yt_link_button = gr.Button('Paste YouTube link/Path to local file instead')
563
+ song_input_file.upload(process_file_upload, inputs=[song_input_file], outputs=[local_file, song_input])
564
+
565
+ with gr.Column():
566
+ 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)')
567
+ 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)')
568
+ show_file_upload_button.click(swap_visibility, outputs=[file_upload_col, yt_link_col, song_input, local_file])
569
+ show_yt_link_button.click(swap_visibility, outputs=[yt_link_col, file_upload_col, song_input, local_file])
570
+
571
+ with gr.Accordion('Voice conversion options', open=False):
572
+ with gr.Row():
573
+ 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")
574
+ 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')
575
+ 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)")
576
+ 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.')
577
+ with gr.Column():
578
+ f0_method = gr.Dropdown(['rmvpe', 'mangio-crepe'], value='rmvpe', label='Pitch detection algorithm', info='Best option is rmvpe (clarity in vocals), then mangio-crepe (smoother vocals)')
579
+ 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.')
580
+ f0_method.change(show_hop_slider, inputs=f0_method, outputs=crepe_hop_length)
581
+ keep_files = gr.Checkbox(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')
582
+
583
+ with gr.Accordion('Audio mixing options', open=False):
584
+ gr.Markdown('### Volume Change (decibels)')
585
+ with gr.Row():
586
+ main_gain = gr.Slider(-20, 20, value=0, step=1, label='Main Vocals')
587
+ backup_gain = gr.Slider(-20, 20, value=0, step=1, label='Backup Vocals')
588
+ inst_gain = gr.Slider(-20, 20, value=0, step=1, label='Music')
589
+
590
+ gr.Markdown('### Reverb Control on AI Vocals')
591
+ with gr.Row():
592
+ reverb_rm_size = gr.Slider(0, 1, value=0.15, label='Room size', info='The larger the room, the longer the reverb time')
593
+ reverb_wet = gr.Slider(0, 1, value=0.2, label='Wetness level', info='Level of AI vocals with reverb')
594
+ reverb_dry = gr.Slider(0, 1, value=0.8, label='Dryness level', info='Level of AI vocals without reverb')
595
+ reverb_damping = gr.Slider(0, 1, value=0.7, label='Damping level', info='Absorption of high frequencies in the reverb')
596
+
597
+ gr.Markdown('### Audio Output Format')
598
+ 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')
599
+
600
+ with gr.Row():
601
+ clear_btn = gr.ClearButton(value='Clear', components=[song_input, rvc_model, keep_files, local_file])
602
+ generate_btn = gr.Button("Generate", variant='primary')
603
+ ai_cover = gr.Audio(label='AI Cover', show_share_button=False)
604
+
605
+ ref_btn.click(update_models_list, None, outputs=rvc_model)
606
+ is_webui = gr.Number(value=1, visible=False)
607
+ generate_btn.click(song_cover_pipeline,
608
+ inputs=[song_input, rvc_model, pitch, keep_files, is_webui, main_gain, backup_gain,
609
+ inst_gain, index_rate, filter_radius, rms_mix_rate, f0_method, crepe_hop_length,
610
+ protect, pitch_all, reverb_rm_size, reverb_wet, reverb_dry, reverb_damping,
611
+ output_format],
612
+ outputs=[ai_cover],
613
+ show_progress=True)
614
+ 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],
615
+ outputs=[pitch, main_gain, backup_gain, inst_gain, index_rate, filter_radius, rms_mix_rate,
616
+ protect, f0_method, crepe_hop_length, pitch_all, reverb_rm_size, reverb_wet,
617
+ reverb_dry, reverb_damping, output_format, ai_cover])
618
+
619
+ # Download tab
620
+ with gr.Tab('Download model'):
621
+
622
+ with gr.Tab('From HuggingFace/Pixeldrain URL'):
623
+ with gr.Row():
624
+ 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.')
625
+ model_name = gr.Text(label='Name your model', info='Give your new model a unique name from your other voice models.')
626
+
627
+ with gr.Row():
628
+ download_btn = gr.Button('Download 🌐', variant='primary', scale=19)
629
+ dl_output_message = gr.Text(label='Output Message', interactive=False, scale=20)
630
+
631
+ download_btn.click(download_online_model, inputs=[model_zip_link, model_name], outputs=dl_output_message)
632
+
633
+ gr.Markdown('## Input Examples')
634
+ gr.Examples(
635
+ [
636
+ ['https://huggingface.co/phant0m4r/LiSA/resolve/main/LiSA.zip', 'Lisa'],
637
+ ['https://pixeldrain.com/u/3tJmABXA', 'Gura'],
638
+ ['https://huggingface.co/Kit-Lemonfoot/kitlemonfoot_rvc_models/resolve/main/AZKi%20(Hybrid).zip', 'Azki']
639
+ ],
640
+ [model_zip_link, model_name],
641
+ [],
642
+ download_online_model,
643
+ )
644
+
645
+ with gr.Tab('From Public Index'):
646
+
647
+ gr.Markdown('## How to use')
648
+ gr.Markdown('- Click Initialize public models table')
649
+ gr.Markdown('- Filter models using tags or search bar')
650
+ gr.Markdown('- Select a row to autofill the download link and model name')
651
+ gr.Markdown('- Click Download')
652
+
653
+ with gr.Row():
654
+ pub_zip_link = gr.Text(label='Download link to model')
655
+ pub_model_name = gr.Text(label='Model name')
656
+
657
+ with gr.Row():
658
+ download_pub_btn = gr.Button('Download 🌐', variant='primary', scale=19)
659
+ pub_dl_output_message = gr.Text(label='Output Message', interactive=False, scale=20)
660
+
661
+ filter_tags = gr.CheckboxGroup(value=[], label='Show voice models with tags', choices=[])
662
+ search_query = gr.Text(label='Search')
663
+ load_public_models_button = gr.Button(value='Initialize public models table', variant='primary')
664
+
665
+ public_models_table = gr.DataFrame(value=[], headers=['Model Name', 'Description', 'Credit', 'URL', 'Tags'], label='Available Public Models', interactive=False)
666
+ public_models_table.select(pub_dl_autofill, inputs=[public_models_table], outputs=[pub_zip_link, pub_model_name])
667
+ load_public_models_button.click(load_public_models, outputs=[public_models_table, filter_tags])
668
+ search_query.change(filter_models, inputs=[filter_tags, search_query], outputs=public_models_table)
669
+ filter_tags.change(filter_models, inputs=[filter_tags, search_query], outputs=public_models_table)
670
+ download_pub_btn.click(download_online_model, inputs=[pub_zip_link, pub_model_name], outputs=pub_dl_output_message)
671
+
672
+ # Upload tab
673
+ with gr.Tab('Upload model'):
674
+ gr.Markdown('## Upload locally trained RVC v2 model and index file')
675
+ gr.Markdown('- Find model file (weights folder) and optional index file (logs/[name] folder)')
676
+ gr.Markdown('- Compress files into zip file')
677
+ gr.Markdown('- Upload zip file and give unique name for voice')
678
+ gr.Markdown('- Click Upload model')
679
+
680
+ with gr.Row():
681
+ with gr.Column():
682
+ zip_file = gr.File(label='Zip file')
683
+
684
+ local_model_name = gr.Text(label='Model name')
685
+
686
+ with gr.Row():
687
+ model_upload_button = gr.Button('Upload model', variant='primary', scale=19)
688
+ local_upload_output_message = gr.Text(label='Output Message', interactive=False, scale=20)
689
+ model_upload_button.click(upload_local_model, inputs=[zip_file, local_model_name], outputs=local_upload_output_message)
690
+
691
+ app.launch(
692
+ share=args.share_enabled,
693
+ enable_queue=True,
694
+ server_name=None if not args.listen else (args.listen_host or '0.0.0.0'),
695
+ server_port=args.listen_port,
696
+ )