Riko arudianshā commited on
Commit
649ca70
1 Parent(s): 6be622f

Create indo-web.py

Browse files
Files changed (1) hide show
  1. indo-web.py +305 -0
indo-web.py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ progress(0, desc=f'[~] Downloading voice model with name {dir_name}...')
73
+ zip_name = url.split('/')[-1]
74
+ extraction_folder = os.path.join(rvc_models_dir, dir_name)
75
+ if os.path.exists(extraction_folder):
76
+ raise gr.Error(f'Voice model directory {dir_name} already exists! Choose a different name for your voice model.')
77
+
78
+ if 'pixeldrain.com' in url:
79
+ url = f'https://pixeldrain.com/api/file/{zip_name}'
80
+
81
+ urllib.request.urlretrieve(url, zip_name)
82
+
83
+ progress(0.5, desc='[~] Extracting zip...')
84
+ extract_zip(extraction_folder, zip_name)
85
+ return f'[+] {dir_name} Model successfully downloaded!'
86
+
87
+ except Exception as e:
88
+ raise gr.Error(str(e))
89
+
90
+
91
+ def upload_local_model(zip_path, dir_name, progress=gr.Progress()):
92
+ try:
93
+ extraction_folder = os.path.join(rvc_models_dir, dir_name)
94
+ if os.path.exists(extraction_folder):
95
+ raise gr.Error(f'Voice model directory {dir_name} already exists! Choose a different name for your voice model.')
96
+
97
+ zip_name = zip_path.name
98
+ progress(0.5, desc='[~] Extracting zip...')
99
+ extract_zip(extraction_folder, zip_name)
100
+ return f'[+] {dir_name} Model successfully uploaded!'
101
+
102
+ except Exception as e:
103
+ raise gr.Error(str(e))
104
+
105
+
106
+ def filter_models(tags, query):
107
+ models_table = []
108
+
109
+ # no filter
110
+ if len(tags) == 0 and len(query) == 0:
111
+ for model in public_models['voice_models']:
112
+ models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']])
113
+
114
+ # filter based on tags and query
115
+ elif len(tags) > 0 and len(query) > 0:
116
+ for model in public_models['voice_models']:
117
+ if all(tag in model['tags'] for tag in tags):
118
+ model_attributes = f"{model['name']} {model['description']} {model['credit']} {' '.join(model['tags'])}".lower()
119
+ if query.lower() in model_attributes:
120
+ models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']])
121
+
122
+ # filter based on only tags
123
+ elif len(tags) > 0:
124
+ for model in public_models['voice_models']:
125
+ if all(tag in model['tags'] for tag in tags):
126
+ models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']])
127
+
128
+ # filter based on only query
129
+ else:
130
+ for model in public_models['voice_models']:
131
+ model_attributes = f"{model['name']} {model['description']} {model['credit']} {' '.join(model['tags'])}".lower()
132
+ if query.lower() in model_attributes:
133
+ models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']])
134
+
135
+ return gr.DataFrame.update(value=models_table)
136
+
137
+
138
+ def pub_dl_autofill(pub_models, event: gr.SelectData):
139
+ return gr.Text.update(value=pub_models.loc[event.index[0], 'URL']), gr.Text.update(value=pub_models.loc[event.index[0], 'Model Name'])
140
+
141
+
142
+ def swap_visibility():
143
+ return gr.update(visible=True), gr.update(visible=False), gr.update(value=''), gr.update(value=None)
144
+
145
+
146
+ def process_file_upload(file):
147
+ return file.name, gr.update(value=file.name)
148
+
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
+
157
+ if __name__ == '__main__':
158
+ parser = ArgumentParser(description='Generate a AI cover song in the song_output/id directory.', add_help=True)
159
+ parser.add_argument("--share", action="store_true", dest="share_enabled", default=False, help="Enable sharing")
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
+ args = parser.parse_args()
164
+
165
+ voice_models = get_current_models(rvc_models_dir)
166
+ with open(os.path.join(rvc_models_dir, 'public_models.json'), encoding='utf8') as infile:
167
+ public_models = json.load(infile)
168
+
169
+ with gr.Blocks(title='AICoverGen',theme=gr.themes.Soft(primary_hue=gr.themes.colors.blue, secondary_hue=gr.themes.colors.blue)) as app:
170
+
171
+ gr.HTML("<h1> The AICoverGen WebUI </h1>")
172
+
173
+ # main tab
174
+ with gr.Tab("Generate"):
175
+
176
+ with gr.Accordion('Main Tab'):
177
+ with gr.Row():
178
+ with gr.Column():
179
+ 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')
180
+ ref_btn = gr.Button('Refresh Models', variant='primary')
181
+
182
+ with gr.Column() as yt_link_col:
183
+ 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.')
184
+ show_file_upload_button = gr.Button('Upload file instead')
185
+
186
+ with gr.Column(visible=False) as file_upload_col:
187
+ local_file = gr.File(label='Audio file')
188
+ song_input_file = gr.UploadButton('Upload', file_types=['audio'], variant='primary')
189
+ show_yt_link_button = gr.Button('Paste YouTube link/Path to local file instead')
190
+ song_input_file.upload(process_file_upload, inputs=[song_input_file], outputs=[local_file, song_input])
191
+
192
+ with gr.Column():
193
+ 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)')
194
+ 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)')
195
+ show_file_upload_button.click(swap_visibility, outputs=[file_upload_col, yt_link_col, song_input, local_file])
196
+ show_yt_link_button.click(swap_visibility, outputs=[yt_link_col, file_upload_col, song_input, local_file])
197
+
198
+ with gr.Accordion('Voice conversion options', open=False):
199
+ with gr.Row():
200
+ 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")
201
+ 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')
202
+ 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)")
203
+ 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.')
204
+ with gr.Column():
205
+ 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)')
206
+ 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.')
207
+ f0_method.change(show_hop_slider, inputs=f0_method, outputs=crepe_hop_length)
208
+ 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')
209
+
210
+ with gr.Accordion('Audio mixing options', open=False):
211
+ gr.Markdown('### Volume Change (decibels)')
212
+ with gr.Row():
213
+ main_gain = gr.Slider(-20, 20, value=0, step=1, label='Main Vocals')
214
+ backup_gain = gr.Slider(-20, 20, value=0, step=1, label='Backup Vocals')
215
+ inst_gain = gr.Slider(-20, 20, value=0, step=1, label='Music')
216
+
217
+ gr.Markdown('### Reverb Control on AI Vocals')
218
+ with gr.Row():
219
+ reverb_rm_size = gr.Slider(0, 1, value=0.15, label='Room size', info='The larger the room, the longer the reverb time')
220
+ reverb_wet = gr.Slider(0, 1, value=0.2, label='Wetness level', info='Level of AI vocals with reverb')
221
+ reverb_dry = gr.Slider(0, 1, value=0.8, label='Dryness level', info='Level of AI vocals without reverb')
222
+ reverb_damping = gr.Slider(0, 1, value=0.7, label='Damping level', info='Absorption of high frequencies in the reverb')
223
+
224
+ gr.Markdown('### Audio Output Format')
225
+ 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')
226
+
227
+ with gr.Row():
228
+ clear_btn = gr.ClearButton(value='Clear', components=[song_input, rvc_model, keep_files, local_file])
229
+ generate_btn = gr.Button("Generate", variant='primary')
230
+ ai_cover = gr.Audio(label='AI Cover', show_share_button=False)
231
+
232
+ ref_btn.click(update_models_list, None, outputs=rvc_model)
233
+ is_webui = gr.Number(value=1, visible=False)
234
+ generate_btn.click(song_cover_pipeline,
235
+ inputs=[song_input, rvc_model, pitch, keep_files, is_webui, main_gain, backup_gain,
236
+ inst_gain, index_rate, filter_radius, rms_mix_rate, f0_method, crepe_hop_length,
237
+ protect, pitch_all, reverb_rm_size, reverb_wet, reverb_dry, reverb_damping,
238
+ output_format],
239
+ outputs=[ai_cover])
240
+ 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],
241
+ outputs=[pitch, main_gain, backup_gain, inst_gain, index_rate, filter_radius, rms_mix_rate,
242
+ protect, f0_method, crepe_hop_length, pitch_all, reverb_rm_size, reverb_wet,
243
+ reverb_dry, reverb_damping, output_format, ai_cover])
244
+
245
+ # Download tab
246
+ with gr.Tab('Download Tab'):
247
+
248
+ with gr.Tab('From HuggingFace/Pixeldrain URL'):
249
+ with gr.Row():
250
+ 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.')
251
+ model_name = gr.Text(label='Name your model', info='Give your new model a unique name from your other voice models.')
252
+
253
+ with gr.Row():
254
+ download_btn = gr.Button('Download', variant='primary', scale=19)
255
+ dl_output_message = gr.Text(label='Output Message', interactive=False, scale=20)
256
+
257
+ download_btn.click(download_online_model, inputs=[model_zip_link, model_name], outputs=dl_output_message)
258
+
259
+ gr.Markdown('## Input Examples')
260
+ gr.Examples(
261
+ [
262
+ ['https://huggingface.co/phant0m4r/LiSA/resolve/main/LiSA.zip', 'Lisa'],
263
+ ['https://huggingface.co/ccateni/OldModels/resolve/main/Sonic28.zip', 'sonic'],
264
+ ['https://huggingface.co/LivingGift/Scott_Pilgrim_Takes_Off_Characters/resolve/main/Kim%20Pine.zip?download=true', 'Kim Pine']
265
+ ],
266
+ [model_zip_link, model_name],
267
+ [],
268
+ download_online_model,
269
+ )
270
+
271
+ with gr.Tab('From Public Index'):
272
+
273
+ gr.Markdown('## How to use')
274
+ gr.Markdown('- Click Initialize public models table')
275
+ gr.Markdown('- Filter models using tags or search bar')
276
+ gr.Markdown('- Select a row to autofill the download link and model name')
277
+ gr.Markdown('- Click Download')
278
+
279
+ with gr.Row():
280
+ pub_zip_link = gr.Text(label='Download link to model')
281
+ pub_model_name = gr.Text(label='Model name')
282
+
283
+ with gr.Row():
284
+ download_pub_btn = gr.Button('Download', variant='primary', scale=19)
285
+ pub_dl_output_message = gr.Text(label='Output Message', interactive=False, scale=20)
286
+
287
+ filter_tags = gr.CheckboxGroup(value=[], label='Show voice models with tags', choices=[])
288
+ search_query = gr.Text(label='Search')
289
+ load_public_models_button = gr.Button(value='Initialize public models table', variant='primary')
290
+
291
+ public_models_table = gr.DataFrame(value=[], headers=['Model Name', 'Description', 'Credit', 'URL', 'Tags'], label='Available Public Models', interactive=False)
292
+ public_models_table.select(pub_dl_autofill, inputs=[public_models_table], outputs=[pub_zip_link, pub_model_name])
293
+ load_public_models_button.click(load_public_models, outputs=[public_models_table, filter_tags])
294
+ search_query.change(filter_models, inputs=[filter_tags, search_query], outputs=public_models_table)
295
+ filter_tags.change(filter_models, inputs=[filter_tags, search_query], outputs=public_models_table)
296
+ download_pub_btn.click(download_online_model, inputs=[pub_zip_link, pub_model_name], outputs=pub_dl_output_message)
297
+
298
+
299
+
300
+ app.launch(
301
+ share=True,
302
+ enable_queue=True,
303
+ server_name=None if not args.listen else (args.listen_host or '0.0.0.0'),
304
+ server_port=args.listen_port,
305
+ )