SpyC0der77 commited on
Commit
ea56cb4
·
verified ·
1 Parent(s): 1d8d80e

Update src/webui.py

Browse files
Files changed (1) hide show
  1. src/webui.py +343 -324
src/webui.py CHANGED
@@ -1,334 +1,353 @@
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
-
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.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.update(value=models_table), gr.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.update(value=models_table)
136
-
137
-
138
- def pub_dl_autofill(pub_models, event: gr.SelectData):
139
- return gr.update(value=pub_models.loc[event.index[0], 'URL']), gr.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='AICoverGenWebUI') as app:
170
-
171
- gr.Label('AICoverGen WebUI ZeroGPU mode created with ❤️', show_label=False)
172
- gr.Markdown(
173
- """
174
- <details>
175
- <summary style="font-size: 1.5em;">⚠️ Important (click to expand)</summary>
176
- <ul>
177
- <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>
178
- </ul>
179
- </details>
180
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181
  )
182
- 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")
183
-
184
- # main tab
185
- with gr.Tab("Generate"):
186
-
187
- with gr.Accordion('Main Options'):
188
- with gr.Row():
189
- with gr.Column():
190
- 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')
191
- ref_btn = gr.Button('Refresh Models 🔁', variant='primary')
192
-
193
- with gr.Column() 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. Example: https://www.youtube.com/watch?v=M-mtdN6R3bQ')
195
- show_file_upload_button = gr.Button('Upload file instead')
196
-
197
- with gr.Column(visible=False) as file_upload_col:
198
- local_file = gr.File(label='Audio file')
199
- song_input_file = gr.UploadButton('Upload 📂', file_types=['audio'], variant='primary')
200
- show_yt_link_button = gr.Button('Paste YouTube link/Path to local file instead')
201
- song_input_file.upload(process_file_upload, inputs=[song_input_file], outputs=[local_file, song_input])
202
-
203
- with gr.Column():
204
- 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)')
205
- 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)')
206
- show_file_upload_button.click(swap_visibility, outputs=[file_upload_col, yt_link_col, song_input, local_file])
207
- show_yt_link_button.click(swap_visibility, outputs=[yt_link_col, file_upload_col, song_input, local_file])
208
-
209
- with gr.Accordion('Voice conversion options', open=False):
210
- with gr.Row():
211
- 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")
212
- 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')
213
- 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)")
214
- 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.')
215
- with gr.Column():
216
- 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.')
217
- 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.')
218
- f0_method.change(show_hop_slider, inputs=f0_method, outputs=crepe_hop_length)
219
- keep_files = gr.Checkbox(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')
220
-
221
- with gr.Accordion('Audio mixing options', open=False):
222
- gr.Markdown('### Volume Change (decibels)')
223
- with gr.Row():
224
- main_gain = gr.Slider(-20, 20, value=0, step=1, label='Main Vocals')
225
- backup_gain = gr.Slider(-20, 20, value=0, step=1, label='Backup Vocals')
226
- inst_gain = gr.Slider(-20, 20, value=0, step=1, label='Music')
227
-
228
- gr.Markdown('### Reverb Control on AI Vocals')
229
- with gr.Row():
230
- reverb_rm_size = gr.Slider(0, 1, value=0.15, label='Room size', info='The larger the room, the longer the reverb time')
231
- reverb_wet = gr.Slider(0, 1, value=0.2, label='Wetness level', info='Level of AI vocals with reverb')
232
- reverb_dry = gr.Slider(0, 1, value=0.8, label='Dryness level', info='Level of AI vocals without reverb')
233
- reverb_damping = gr.Slider(0, 1, value=0.7, label='Damping level', info='Absorption of high frequencies in the reverb')
234
-
235
- gr.Markdown('### Audio Output Format')
236
- 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')
237
-
238
  with gr.Row():
239
- clear_btn = gr.ClearButton(value='Clear', components=[song_input, rvc_model, keep_files, local_file])
240
- generate_btn = gr.Button("Generate", variant='primary')
241
- ai_cover = gr.Audio(label='AI Cover', show_share_button=False)
242
-
243
- ref_btn.click(update_models_list, None, outputs=rvc_model)
244
- is_webui = gr.Number(value=1, visible=False)
245
- generate_btn.click(song_cover_pipeline,
246
- inputs=[song_input, rvc_model, pitch, keep_files, is_webui, main_gain, backup_gain,
247
- inst_gain, index_rate, filter_radius, rms_mix_rate, f0_method, crepe_hop_length,
248
- protect, pitch_all, reverb_rm_size, reverb_wet, reverb_dry, reverb_damping,
249
- output_format],
250
- outputs=[ai_cover])
251
- 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],
252
- outputs=[pitch, main_gain, backup_gain, inst_gain, index_rate, filter_radius, rms_mix_rate,
253
- protect, f0_method, crepe_hop_length, pitch_all, reverb_rm_size, reverb_wet,
254
- reverb_dry, reverb_damping, output_format, ai_cover])
255
-
256
- # Download tab
257
- with gr.Tab('Download model'):
258
-
259
- with gr.Tab('From HuggingFace/Pixeldrain URL'):
260
- with gr.Row():
261
- 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.')
262
- model_name = gr.Text(label='Name your model', info='Give your new model a unique name from your other voice models.')
263
-
264
- with gr.Row():
265
- download_btn = gr.Button('Download 🌐', variant='primary', scale=19)
266
- dl_output_message = gr.Text(label='Output Message', interactive=False, scale=20)
267
-
268
- download_btn.click(download_online_model, inputs=[model_zip_link, model_name], outputs=dl_output_message)
269
-
270
- gr.Markdown('## Input Examples')
271
- gr.Examples(
272
- [
273
- ['https://huggingface.co/phant0m4r/LiSA/resolve/main/LiSA.zip', 'Lisa'],
274
- ['https://pixeldrain.com/u/3tJmABXA', 'Gura'],
275
- ['https://huggingface.co/Kit-Lemonfoot/kitlemonfoot_rvc_models/resolve/main/AZKi%20(Hybrid).zip', 'Azki']
276
- ],
277
- [model_zip_link, model_name],
278
- [],
279
- download_online_model,
280
- cache_examples=False,
281
  )
282
 
283
- with gr.Tab('From Public Index'):
284
-
285
- gr.Markdown('## How to use')
286
- gr.Markdown('- Click Initialize public models table')
287
- gr.Markdown('- Filter models using tags or search bar')
288
- gr.Markdown('- Select a row to autofill the download link and model name')
289
- gr.Markdown('- Click Download')
290
-
291
- with gr.Row():
292
- pub_zip_link = gr.Text(label='Download link to model')
293
- pub_model_name = gr.Text(label='Model name')
294
-
295
- with gr.Row():
296
- download_pub_btn = gr.Button('Download 🌐', variant='primary', scale=19)
297
- pub_dl_output_message = gr.Text(label='Output Message', interactive=False, scale=20)
298
-
299
- filter_tags = gr.CheckboxGroup(value=[], label='Show voice models with tags', choices=[])
300
- search_query = gr.Text(label='Search')
301
- load_public_models_button = gr.Button(value='Initialize public models table', variant='primary')
302
-
303
- public_models_table = gr.DataFrame(value=[], headers=['Model Name', 'Description', 'Credit', 'URL', 'Tags'], label='Available Public Models', interactive=False)
304
- public_models_table.select(pub_dl_autofill, inputs=[public_models_table], outputs=[pub_zip_link, pub_model_name])
305
- load_public_models_button.click(load_public_models, outputs=[public_models_table, filter_tags])
306
- search_query.change(filter_models, inputs=[filter_tags, search_query], outputs=public_models_table)
307
- filter_tags.change(filter_models, inputs=[filter_tags, search_query], outputs=public_models_table)
308
- download_pub_btn.click(download_online_model, inputs=[pub_zip_link, pub_model_name], outputs=pub_dl_output_message)
309
-
310
- # Upload tab
311
- with gr.Tab('Upload model'):
312
- gr.Markdown('## Upload locally trained RVC v2 model and index file')
313
- gr.Markdown('- Find model file (weights folder) and optional index file (logs/[name] folder)')
314
- gr.Markdown('- Compress files into zip file')
315
- gr.Markdown('- Upload zip file and give unique name for voice')
316
- gr.Markdown('- Click Upload model')
317
 
318
- with gr.Row():
319
- with gr.Column():
320
- zip_file = gr.File(label='Zip file')
 
 
 
 
 
 
 
 
 
 
 
 
 
321
 
322
- local_model_name = gr.Text(label='Model name')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
323
 
324
- with gr.Row():
325
- model_upload_button = gr.Button('Upload model', variant='primary', scale=19)
326
- local_upload_output_message = gr.Text(label='Output Message', interactive=False, scale=20)
327
- model_upload_button.click(upload_local_model, inputs=[zip_file, local_model_name], outputs=local_upload_output_message)
328
-
329
- app.launch(
330
- share=args.share_enabled,
331
- # enable_queue=True,
332
- server_name=None if not args.listen else (args.listen_host or '0.0.0.0'),
333
- server_port=args.listen_port,
334
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Module which defines the code for the "Manage models" tab."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
+ from collections.abc import Sequence
4
+ from functools import partial
5
 
6
+ import gradio as gr
7
+ import pandas as pd
8
+ import requests
9
+
10
+ # Function to search for RVC models on Hugging Face
11
+ def search_rvc_models(query):
12
+ url = f"https://huggingface.co/api/models?search={query}&library=rvc"
13
+ response = requests.get(url)
14
+ if response.status_code == 200:
15
+ models = response.json()
16
+ # Create a DataFrame to store the results
17
+ df = pd.DataFrame(models)
18
+ # Filter the DataFrame to only include the desired columns
19
+ df = df[["id", "likes", "downloads"]]
20
+ # Add a new column for the download URL
21
+ df["downloadUrl"] = "https://huggingface.co/" + df["id"]
22
+ # Sort the DataFrame by downloads in descending order
23
+ df = df.sort_values(by="downloads", ascending=False)
24
+ return df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  else:
26
+ return pd.DataFrame({"id": ["No models found"]})
27
+
28
+ from ultimate_rvc.core.manage.models import (
29
+ delete_all_models,
30
+ delete_models,
31
+ download_model,
32
+ filter_public_models_table,
33
+ get_public_model_tags,
34
+ get_saved_model_names,
35
+ upload_model,
36
+ )
37
+ from ultimate_rvc.web.common import (
38
+ PROGRESS_BAR,
39
+ confirm_box_js,
40
+ confirmation_harness,
41
+ exception_harness,
42
+ render_msg,
43
+ update_dropdowns,
44
+ )
45
+ from ultimate_rvc.web.typing_extra import DropdownValue
46
+
47
+
48
+ def _update_models(
49
+ num_components: int,
50
+ value: DropdownValue = None,
51
+ value_indices: Sequence[int] = [],
52
+ ) -> gr.Dropdown | tuple[gr.Dropdown, ...]:
53
+ """
54
+ Update the choices of one or more dropdown components to the set of
55
+ currently saved voice models.
56
+
57
+ Optionally updates the default value of one or more of these
58
+ components.
59
+
60
+ Parameters
61
+ ----------
62
+ num_components : int
63
+ Number of dropdown components to update.
64
+ value : DropdownValue, optional
65
+ New value for dropdown components.
66
+ value_indices : Sequence[int], default=[]
67
+ Indices of dropdown components to update the value for.
68
+
69
+ Returns
70
+ -------
71
+ gr.Dropdown | tuple[gr.Dropdown, ...]
72
+ Updated dropdown component or components.
73
+
74
+ """
75
+ return update_dropdowns(get_saved_model_names, num_components, value, value_indices)
76
+
77
+
78
+ def _filter_public_models_table(tags: Sequence[str], query: str) -> gr.Dataframe:
79
+ """
80
+ Filter table containing metadata of public voice models by tags and
81
+ a search query.
82
+
83
+ Parameters
84
+ ----------
85
+ tags : Sequence[str]
86
+ Tags to filter the metadata table by.
87
+ query : str
88
+ Search query to filter the metadata table by.
89
+
90
+ Returns
91
+ -------
92
+ gr.Dataframe
93
+ The filtered table rendered in a Gradio dataframe.
94
+
95
+ """
96
+ models_table = filter_public_models_table(tags, query)
97
+ return gr.Dataframe(value=models_table)
98
+
99
+
100
+ def _autofill_model_name_and_url(
101
+ public_models_table: pd.DataFrame,
102
+ select_event: gr.SelectData,
103
+ ) -> tuple[gr.Textbox, gr.Textbox]:
104
+ """
105
+ Autofill two textboxes with respectively the name and URL that is
106
+ saved in the currently selected row of the public models table.
107
+
108
+ Parameters
109
+ ----------
110
+ public_models_table : pd.DataFrame
111
+ The public models table saved in a Pandas dataframe.
112
+ select_event : gr.SelectData
113
+ Event containing the index of the currently selected row in the
114
+ public models table.
115
+
116
+ Returns
117
+ -------
118
+ name : gr.Textbox
119
+ The textbox containing the model name.
120
+
121
+ url : gr.Textbox
122
+ The textbox containing the model URL.
123
+
124
+ Raises
125
+ ------
126
+ TypeError
127
+ If the index in the provided event is not a sequence.
128
+
129
+ """
130
+ event_index = select_event.index
131
+ if not isinstance(event_index, Sequence):
132
+ err_msg = (
133
+ f"Expected a sequence of indices but got {type(event_index)} from the"
134
+ " provided event."
135
  )
136
+ raise TypeError(err_msg)
137
+ event_index = event_index[0]
138
+ url = public_models_table.loc[event_index, "URL"]
139
+ name = public_models_table.loc[event_index, "Name"]
140
+ if isinstance(url, str) and isinstance(name, str):
141
+ return gr.Textbox(value=name), gr.Textbox(value=url)
142
+ err_msg = (
143
+ "Expected model name and URL to be strings but got"
144
+ f" {type(name)} and {type(url)} respectively."
145
+ )
146
+ raise TypeError(err_msg)
147
+
148
+
149
+ def render(
150
+ model_delete: gr.Dropdown,
151
+ model_1click: gr.Dropdown,
152
+ model_multi: gr.Dropdown,
153
+ ) -> None:
154
+ """
155
+
156
+ Render "Manage models" tab.
157
+
158
+ Parameters
159
+ ----------
160
+ model_delete : gr.Dropdown
161
+ Dropdown for selecting voice models to delete in the
162
+ "Delete models" tab.
163
+ model_1click : gr.Dropdown
164
+ Dropdown for selecting a voice model to use in the
165
+ "One-click generation" tab.
166
+ model_multi : gr.Dropdown
167
+ Dropdown for selecting a voice model to use in the
168
+ "Multi-step generation" tab.
169
+
170
+ """
171
+ # Download tab
172
+
173
+ dummy_checkbox = gr.Checkbox(visible=False)
174
+ with gr.Tab("Download model"):
175
+ with gr.Accordion("View public models table", open=False):
176
+ gr.Markdown("")
177
+ gr.Markdown("*HOW TO USE*")
178
+ gr.Markdown(
179
+ "- Filter voice models by selecting one or more tags and/or providing a"
180
+ " search query.",
181
+ )
182
+ gr.Markdown(
183
+ "- Select a row in the table to autofill the name and"
184
+ " URL for the given voice model in the form fields below.",
185
+ )
186
+ gr.Markdown("")
 
 
 
 
 
187
  with gr.Row():
188
+ search_query = gr.Textbox(label="Search query")
189
+ tags = gr.CheckboxGroup(
190
+ value=[],
191
+ label="Tags",
192
+ choices=get_public_model_tags(),
193
+ )
194
+ with gr.Row():
195
+ public_models_table = gr.Dataframe(
196
+ value=_filter_public_models_table,
197
+ inputs=[tags, search_query],
198
+ headers=["Name", "Description", "Tags", "Credit", "Added", "URL"],
199
+ label="Public models table",
200
+ interactive=False,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
  )
202
 
203
+ with gr.Row():
204
+ model_url = gr.Textbox(
205
+ label="Model URL",
206
+ info=(
207
+ "Should point to a zip file containing a .pth model file and"
208
+ " optionally also an .index file."
209
+ ),
210
+ )
211
+ model_name = gr.Textbox(
212
+ label="Model name",
213
+ info="Enter a unique name for the voice model.",
214
+ )
215
+
216
+ with gr.Row(equal_height=True):
217
+ download_btn = gr.Button("Download 🌐", variant="primary", scale=19)
218
+ download_msg = gr.Textbox(
219
+ label="Output message",
220
+ interactive=False,
221
+ scale=20,
222
+ )
223
+
224
+ public_models_table.select(
225
+ _autofill_model_name_and_url,
226
+ inputs=public_models_table,
227
+ outputs=[model_name, model_url],
228
+ show_progress="hidden",
229
+ )
 
 
 
 
 
 
 
230
 
231
+ download_btn_click = download_btn.click(
232
+ partial(
233
+ exception_harness(download_model),
234
+ progress_bar=PROGRESS_BAR,
235
+ ),
236
+ inputs=[model_url, model_name],
237
+ outputs=download_msg,
238
+ ).success(
239
+ partial(
240
+ render_msg,
241
+ "[+] Succesfully downloaded voice model!",
242
+ ),
243
+ inputs=model_name,
244
+ outputs=download_msg,
245
+ show_progress="hidden",
246
+ )
247
 
248
+ # Upload tab
249
+ with gr.Tab("Upload model"):
250
+ with gr.Accordion("HOW TO USE"):
251
+ gr.Markdown("")
252
+ gr.Markdown(
253
+ "1. Find the .pth file for a locally trained RVC model (e.g. in your"
254
+ " local weights folder) and optionally also a corresponding .index file"
255
+ " (e.g. in your logs/[name] folder)",
256
+ )
257
+ gr.Markdown(
258
+ "2. Upload the files directly or save them to a folder, then compress"
259
+ " that folder and upload the resulting .zip file",
260
+ )
261
+ gr.Markdown("3. Enter a unique name for the uploaded model")
262
+ gr.Markdown("4. Click 'Upload'")
263
+
264
+ with gr.Row():
265
+ model_files = gr.File(
266
+ label="Files",
267
+ file_count="multiple",
268
+ file_types=[".zip", ".pth", ".index"],
269
+ )
270
+
271
+ local_model_name = gr.Textbox(label="Model name")
272
+
273
+ with gr.Row(equal_height=True):
274
+ upload_btn = gr.Button("Upload", variant="primary", scale=19)
275
+ upload_msg = gr.Textbox(
276
+ label="Output message",
277
+ interactive=False,
278
+ scale=20,
279
+ )
280
+ upload_btn_click = upload_btn.click(
281
+ partial(exception_harness(upload_model), progress_bar=PROGRESS_BAR),
282
+ inputs=[model_files, local_model_name],
283
+ outputs=upload_msg,
284
+ ).success(
285
+ partial(
286
+ render_msg,
287
+ "[+] Successfully uploaded voice model!",
288
+ ),
289
+ inputs=local_model_name,
290
+ outputs=upload_msg,
291
+ show_progress="hidden",
292
+ )
293
+
294
+ with gr.Tab("Delete models"):
295
+ with gr.Row():
296
+ with gr.Column():
297
+ model_delete.render()
298
+ delete_btn = gr.Button("Delete selected", variant="secondary")
299
+ delete_all_btn = gr.Button("Delete all", variant="primary")
300
+ with gr.Column():
301
+ delete_msg = gr.Textbox(label="Output message", interactive=False)
302
+ delete_btn_click = delete_btn.click(
303
+ partial(confirmation_harness(delete_models), progress_bar=PROGRESS_BAR),
304
+ inputs=[dummy_checkbox, model_delete],
305
+ outputs=delete_msg,
306
+ js=confirm_box_js(
307
+ "Are you sure you want to delete the selected voice models?",
308
+ ),
309
+ ).success(
310
+ partial(render_msg, "[-] Successfully deleted selected voice models!"),
311
+ outputs=delete_msg,
312
+ show_progress="hidden",
313
+ )
314
 
315
+ delete_all_btn_click = delete_all_btn.click(
316
+ partial(
317
+ confirmation_harness(delete_all_models),
318
+ progress_bar=PROGRESS_BAR,
319
+ ),
320
+ inputs=dummy_checkbox,
321
+ outputs=delete_msg,
322
+ js=confirm_box_js("Are you sure you want to delete all voice models?"),
323
+ ).success(
324
+ partial(render_msg, "[-] Successfully deleted all voice models!"),
325
+ outputs=delete_msg,
326
+ show_progress="hidden",
327
+ )
328
+
329
+
330
+ with gr.Tab("Search models"):
331
+ # Textbox for user to enter search query
332
+ query = gr.Textbox(label="Search for RVC models", placeholder="Enter your search query here")
333
+
334
+ # Button to trigger the search
335
+ search_button = gr.Button("Search")
336
+
337
+ # Output for displaying the search results as a DataFrame
338
+ results = gr.Dataframe(label="Search Results")
339
+
340
+ # Event listener for the search button
341
+ search_button.click(fn=search_rvc_models, inputs=query, outputs=results)
342
+
343
+ for click_event in [
344
+ download_btn_click,
345
+ upload_btn_click,
346
+ delete_btn_click,
347
+ delete_all_btn_click,
348
+ ]:
349
+ click_event.success(
350
+ partial(_update_models, 3, [], [2]),
351
+ outputs=[model_1click, model_multi, model_delete],
352
+ show_progress="hidden",
353
+ )