Adam3 commited on
Commit
d957a6b
·
verified ·
1 Parent(s): af3e698

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +348 -0
app.py CHANGED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ )