Next commited on
Commit
e6e97cd
1 Parent(s): 6d3d3a5

Upload colab (1).py

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