NeoPy commited on
Commit
c921ef8
·
verified ·
1 Parent(s): d2a4804

Delete playground.py

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