Nah_kagz1092 commited on
Commit
9f3c802
·
verified ·
1 Parent(s): d7f178a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +297 -0
app.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os, shutil
3
+ import subprocess, glob
4
+ from datetime import datetime
5
+ from tools.useftools import *
6
+ os.environ["rmvpe_root"] = "assets/rmvpe"
7
+ os.environ['index_root']="logs"
8
+ os.environ['weight_root']="assets/weights"
9
+ from infer.modules.vc.modules import VC
10
+ from configs.config import Config
11
+ import torch
12
+ os.makedirs(os.path.join(".", "audios"), exist_ok=True)
13
+ config = Config()
14
+ vc = VC(config)
15
+
16
+ def warn(text):
17
+ try: gr.Warning(text)
18
+ except: pass
19
+
20
+ def load_model(model_picker,index_picker):
21
+ logs = show_available("logs")
22
+ if model_picker.replace(".pth","") in logs:
23
+ log = model_picker.replace(".pth","")
24
+ else:
25
+ log = index_picker
26
+ warn("Could not find a matching index file.")
27
+ vc.get_vc(model_picker,0,0)
28
+ return {"choices":logs,"value":log,"__type__": "update"}
29
+
30
+ def convert(audio_picker,model_picker,index_picker,index_rate,pitch,method):
31
+ warn("Your audio is being converted. Please wait.")
32
+ now = datetime.now().strftime("%d%m%Y%H%M%S")
33
+ index_files = glob.glob(f"logs/{index_picker}/*.index")
34
+ if index_files:
35
+ print(f"Found index: {index_files[0]}")
36
+ else:
37
+ warn("Sorry, I couldn't find your .index file.")
38
+ print("Did not find a matching .index file")
39
+ index_files = [f'logs/{model_picker}/fake_index.index']
40
+ device = "cuda" if torch.cuda.is_available() else "cpu"
41
+ command = [
42
+ "python",
43
+ "tools/infer_cli.py",
44
+ "--f0up_key", str(pitch),
45
+ "--input_path", f"audios/{audio_picker}",
46
+ "--index_path", index_files[0],
47
+ "--f0method", method,
48
+ "--opt_path", f"audios/cli_output_{now}.wav",
49
+ "--model_name", f"{model_picker}",
50
+ "--index_rate", str(float(index_rate)),
51
+ "--device", device,
52
+ "--filter_radius", "3",
53
+ "--resample_sr", "0",
54
+ "--rms_mix_rate", "0.0",
55
+ "--protect", "0"
56
+ ]
57
+
58
+ try:
59
+ process = subprocess.run(command, check=True)
60
+ print("Script executed successfully.")
61
+ return {"choices":show_available("audios"),"__type__":"update","value":f"cli_output_{now}.wav"},f"audios/cli_output_{now}.wav"
62
+ except subprocess.CalledProcessError as e:
63
+ print(f"Error: {e}")
64
+ return {"choices":show_available("audios"),"__type__":"update"}, None
65
+
66
+ assets_folder = "assets"
67
+ if not os.path.exists(assets_folder):
68
+ os.makedirs(assets_folder)
69
+ files = {
70
+ "rmvpe/rmvpe.pt":"https://huggingface.co/Rejekts/project/resolve/main/rmvpe.pt",
71
+ "hubert/hubert_base.pt":"https://huggingface.co/Rejekts/project/resolve/main/hubert_base.pt",
72
+ "pretrained_v2/D40k.pth":"https://huggingface.co/Rejekts/project/resolve/main/D40k.pth",
73
+ "pretrained_v2/G40k.pth":"https://huggingface.co/Rejekts/project/resolve/main/G40k.pth",
74
+ "pretrained_v2/f0D40k.pth":"https://huggingface.co/Rejekts/project/resolve/main/f0D40k.pth",
75
+ "pretrained_v2/f0G40k.pth":"https://huggingface.co/Rejekts/project/resolve/main/f0G40k.pth"
76
+ }
77
+ for file, link in files.items():
78
+ file_path = os.path.join(assets_folder, file)
79
+ if not os.path.exists(file_path):
80
+ try:
81
+ subprocess.run(['wget', link, '-O', file_path], check=True)
82
+ except subprocess.CalledProcessError as e:
83
+ print(f"Error downloading {file}: {e}")
84
+
85
+ def download_from_url(url, model):
86
+ if model =='':
87
+ try:
88
+ model = url.split('/')[-1].split('?')[0]
89
+ except:
90
+ return "You need to name your model. For example: My-Model", {"choices":show_available("assets/weights"),"__type__":"update"}
91
+ url=url.replace('/blob/main/','/resolve/main/')
92
+ model=model.replace('.pth','').replace('.index','').replace('.zip','')
93
+ print(f"Model name: {model}")
94
+ if url == '':
95
+ return "URL cannot be left empty.", {"choices":show_available("assets/weights"),"__type__":"update"}
96
+ url = url.strip()
97
+ zip_dirs = ["zips", "unzips"]
98
+ for directory in zip_dirs:
99
+ if os.path.exists(directory):
100
+ shutil.rmtree(directory)
101
+ os.makedirs("zips", exist_ok=True)
102
+ os.makedirs("unzips", exist_ok=True)
103
+ zipfile = model + '.zip'
104
+ zipfile_path = './zips/' + zipfile
105
+ try:
106
+ if url.endswith('.pth'):
107
+ subprocess.run(["wget", url, "-O", f'./assets/weights/{model}.pth'])
108
+ return f"Sucessfully downloaded as {model}.pth", {"choices":show_available("assets/weights"),"__type__":"update"}
109
+ elif url.endswith('.index'):
110
+ if not os.path.exists(f'./logs/{model}'): os.makedirs(f'./logs/{model}')
111
+ subprocess.run(["wget", url, "-O", f'./logs/{model}/added_{model}.index'])
112
+ return f"Successfully downloaded as added_{model}.index", {"choices":show_available("assets/weights"),"__type__":"update"}
113
+ if "drive.google.com" in url:
114
+ subprocess.run(["gdown", url, "--fuzzy", "-O", zipfile_path])
115
+ elif "mega.nz" in url:
116
+ m = Mega()
117
+ m.download_url(url, './zips')
118
+ else:
119
+ subprocess.run(["wget", url, "-O", zipfile_path])
120
+ for filename in os.listdir("./zips"):
121
+ if filename.endswith(".zip"):
122
+ zipfile_path = os.path.join("./zips/",filename)
123
+ shutil.unpack_archive(zipfile_path, "./unzips", 'zip')
124
+ for root, dirs, files in os.walk('./unzips'):
125
+ for file in files:
126
+ file_path = os.path.join(root, file)
127
+ if file.endswith(".index"):
128
+ os.mkdir(f'./logs/{model}')
129
+ shutil.copy2(file_path,f'./logs/{model}')
130
+ elif "G_" not in file and "D_" not in file and file.endswith(".pth"):
131
+ shutil.copy(file_path,f'./assets/weights/{model}.pth')
132
+ elif filename.endswith(".pth"):
133
+ shutil.copy2(os.path.join("./zips/",filename),f'./assets/weights/{model}.pth')
134
+ elif filename.endswith(".index"):
135
+ os.mkdir(f'./logs/{model}')
136
+ shutil.copy2(os.path.join("./zips/",filename),f'./logs/{model}/')
137
+ else:
138
+ return "No zipfile found.", {"choices":show_available("assets/weights"),"__type__":"update"}
139
+ shutil.rmtree("zips")
140
+ shutil.rmtree("unzips")
141
+ return "Success.", {"choices":show_available("assets/weights"),"__type__":"update"}
142
+ except:
143
+ return "There's been an error.", {"choices":show_available("assets/weights"),"__type__":"update"}
144
+
145
+ def import_from_name(model):
146
+ try:
147
+ url = models[f'{model}']
148
+ except:
149
+ return "", {"__type__":"update"}
150
+ url=url.replace('/blob/main/','/resolve/main/')
151
+ print(f"Model name: {model}")
152
+ if url == '':
153
+ return "", {"__type__":"update"}
154
+ url = url.strip()
155
+ zip_dirs = ["zips", "unzips"]
156
+ for directory in zip_dirs:
157
+ if os.path.exists(directory):
158
+ shutil.rmtree(directory)
159
+ os.makedirs("zips", exist_ok=True)
160
+ os.makedirs("unzips", exist_ok=True)
161
+ zipfile = model + '.zip'
162
+ zipfile_path = './zips/' + zipfile
163
+ try:
164
+ if url.endswith('.pth'):
165
+ subprocess.run(["wget", url, "-O", f'./assets/weights/{model}.pth'])
166
+ return f"", {"choices":show_available("assets/weights"),"__type__":"update","value":f"{model}.pth"}
167
+ if "drive.google.com" in url:
168
+ subprocess.run(["gdown", url, "--fuzzy", "-O", zipfile_path])
169
+ elif "mega.nz" in url:
170
+ m = Mega()
171
+ m.download_url(url, './zips')
172
+ else:
173
+ subprocess.run(["wget", url, "-O", zipfile_path])
174
+ for filename in os.listdir("./zips"):
175
+ if filename.endswith(".zip"):
176
+ zipfile_path = os.path.join("./zips/",filename)
177
+ shutil.unpack_archive(zipfile_path, "./unzips", 'zip')
178
+ for root, dirs, files in os.walk('./unzips'):
179
+ for file in files:
180
+ file_path = os.path.join(root, file)
181
+ if file.endswith(".index"):
182
+ os.mkdir(f'./logs/{model}')
183
+ shutil.copy2(file_path,f'./logs/{model}')
184
+ elif "G_" not in file and "D_" not in file and file.endswith(".pth"):
185
+ shutil.copy(file_path,f'./assets/weights/{model}.pth')
186
+ elif filename.endswith(".pth"):
187
+ shutil.copy2(os.path.join("./zips/",filename),f'./assets/weights/{model}.pth')
188
+ elif filename.endswith(".index"):
189
+ os.mkdir(f'./logs/{model}')
190
+ shutil.copy2(os.path.join("./zips/",filename),f'./logs/{model}/')
191
+ else:
192
+ return "", {"__type__":"update"}
193
+ shutil.rmtree("zips")
194
+ shutil.rmtree("unzips")
195
+ return "", {"choices":show_available("assets/weights"),"__type__":"update","value":f"{model}.pth"}
196
+ except:
197
+ return "", {"__type__":"update"}
198
+
199
+ def show_available(filepath,format=None):
200
+ if format:
201
+ print(f"Format: {format}")
202
+ files = []
203
+ for file in os.listdir(filepath):
204
+ if file.endswith(format):
205
+ print(f"Matches format: {file}")
206
+ files.append(file)
207
+ else:
208
+ print(f"Does not match format: {file}")
209
+ print(f"Matches: {files}")
210
+ if len(files) < 1:
211
+ return ['']
212
+ return files
213
+ if len(os.listdir(filepath)) < 1:
214
+ return ['']
215
+ return os.listdir(filepath)
216
+
217
+ def upload_file(file):
218
+ audio_formats = ['.wav', '.mp3', '.ogg', '.flac', '.aac']
219
+ print(file)
220
+ try:
221
+ _, ext = os.path.splitext(file.name)
222
+ filename = os.path.basename(file.name)
223
+ file_path = file.name
224
+ except AttributeError:
225
+ _, ext = os.path.splitext(file)
226
+ filename = os.path.basename(file)
227
+ file_path = file
228
+ if ext.lower() in audio_formats:
229
+ if os.path.exists(f'audios/{filename}'):
230
+ os.remove(f'audios/{filename}')
231
+ shutil.move(file_path,'audios')
232
+ else:
233
+ warn('File incompatible')
234
+ return {"choices":show_available('audios'),"__type__": "update","value":filename}
235
+
236
+ def refresh():
237
+ return {"choices":show_available("audios"),"__type__": "update"},{"choices":show_available("assets/weights",".pth"),"__type__": "update"},{"choices":show_available("logs"),"__type__": "update"}
238
+
239
+ def update_audio_player(choice):
240
+ return os.path.join("audios",choice)
241
+
242
+ with gr.Blocks() as app:
243
+ with gr.Row():
244
+ with gr.Column():
245
+ gr.Markdown("# RVC PlayGround 🎮")
246
+ with gr.Column():
247
+ gr.HTML("<a href='https://ko-fi.com/rejekts' target='_blank'><img src='file/kofi_button.png' alt='🤝 Support Me'></a>")
248
+ with gr.Row():
249
+ with gr.Column():
250
+ with gr.Tabs():
251
+ with gr.TabItem("1.Choose a voice model:"):
252
+ model_picker = gr.Dropdown(label="Model: ",choices=show_available('assets/weights','.pth'),value=show_available('assets/weights','.pth')[0],interactive=True,allow_custom_value=True)
253
+ index_picker = gr.Dropdown(label="Index:",interactive=True,choices=show_available('logs'),value=show_available('logs')[0],allow_custom_value=True)
254
+ model_picker.change(fn=load_model,inputs=[model_picker,index_picker],outputs=[index_picker])
255
+ with gr.TabItem("(Or download a model here)"):
256
+ with gr.Row():
257
+ url = gr.Textbox(label="Paste the URL here:",value="",placeholder="(i.e. https://huggingface.co/repo/model/resolve/main/model.zip)")
258
+ with gr.Row():
259
+ with gr.Column():
260
+ model_rename = gr.Textbox(placeholder="My-Model", label="Name your model:",value="")
261
+ with gr.Column():
262
+ download_button = gr.Button("Download")
263
+ download_button.click(fn=download_from_url,inputs=[url,model_rename],outputs=[url,model_picker])
264
+ with gr.Row():
265
+ selected_import = gr.Dropdown(choices=list(models.keys()),label="OR Search Models (Quality UNKNOWN)",scale=5)
266
+ import_model = gr.Button("Download")
267
+ import_model.click(fn=import_from_name,inputs=[selected_import],outputs=[selected_import,model_picker])
268
+ with gr.TabItem("Advanced"):
269
+ index_rate = gr.Slider(label='Index Rate: ',minimum=0,maximum=1,value=0.66,step=0.01)
270
+ pitch = gr.Slider(label='Pitch (-12 lowers it an octave, 0 keeps the original pitch, 12 lifts it an octave): ',minimum =-12, maximum=12, step=1, value=0, interactive=True)
271
+ method = gr.Dropdown(label="Method:",choices=["rmvpe","pm"],value="rmvpe")
272
+
273
+ with gr.Row():
274
+ with gr.Tabs():
275
+ with gr.TabItem("2.Choose an audio file:"):
276
+ recorder = gr.Microphone(label="Record audio here...",type='filepath')
277
+ audio_picker = gr.Dropdown(label="",choices=show_available('audios'),value='',interactive=True)
278
+ try:
279
+ recorder.stop_recording(upload_file, inputs=[recorder],outputs=[audio_picker])
280
+ except:
281
+ recorder.upload(upload_file, inputs=[recorder],outputs=[audio_picker])
282
+ with gr.TabItem("(Or upload a new file here)"):
283
+ try:
284
+ dropbox = gr.File(label="Drop an audio here.",file_types=['.wav', '.mp3', '.ogg', '.flac', '.aac'], type="filepath")
285
+ except:#Version Compatibiliy
286
+ dropbox = gr.File(label="Drop an audio here.",file_types=['.wav', '.mp3', '.ogg', '.flac', '.aac'], type="file")
287
+ dropbox.upload(fn=upload_file, inputs=[dropbox],outputs=[audio_picker])
288
+ audio_refresher = gr.Button("Refresh")
289
+ audio_refresher.click(fn=refresh,inputs=[],outputs=[audio_picker,model_picker,index_picker])
290
+ convert_button = gr.Button("Convert")
291
+ with gr.Row():
292
+ audio_player = gr.Audio()
293
+ inputs = [audio_picker,model_picker,index_picker,index_rate,pitch,method]
294
+ audio_picker.change(fn=update_audio_player, inputs=[audio_picker],outputs=[audio_player])
295
+ convert_button.click(convert, inputs=inputs,outputs=[audio_picker,audio_player])
296
+
297
+ app.queue(max_size=20).launch(debug=True,share=True)