akdNIKY commited on
Commit
706a825
1 Parent(s): fb9b6c4

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +203 -0
app.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os, shutil
3
+ import subprocess, glob
4
+ from datetime import datetime
5
+ os.environ["rmvpe_root"] = "assets/rmvpe"
6
+ os.environ['index_root']="logs"
7
+ os.environ['weight_root']="assets/weights"
8
+
9
+ def convert(audio_picker,model_picker,index_picker,index_rate,pitch):
10
+ gr.Warning("Your audio is being converted. Please wait.")
11
+ now = datetime.now().strftime("%d%m%Y%H%M%S")
12
+ index_files = glob.glob(f"logs/{index_picker}/*.index")
13
+ if index_files:
14
+ print(f"Found index: {index_files[0]}")
15
+ else:
16
+ gr.Warning("Sorry, I couldn't find your .index file.")
17
+ print("Did not find a matching .index file")
18
+ index_files = [f'logs/{model_picker}/fake_index.index']
19
+ command = [
20
+ "python",
21
+ "tools/infer_cli.py",
22
+ "--f0up_key", str(pitch),
23
+ "--input_path", f"audios/{audio_picker}",
24
+ "--index_path", index_files[0],
25
+ "--f0method", "rmvpe",
26
+ "--opt_path", f"audios/cli_output_{now}.wav",
27
+ "--model_name", f"{model_picker}",
28
+ "--index_rate", str(float(index_rate)),
29
+ "--device", "cpu",
30
+ "--filter_radius", "3",
31
+ "--resample_sr", "0",
32
+ "--rms_mix_rate", "0.21",
33
+ "--protect", "0"
34
+ ]
35
+
36
+ try:
37
+ process = subprocess.run(command, check=True)
38
+ print("Script executed successfully.")
39
+ return {"choices":show_available("audios"),"__type__":"update","value":f"cli_output_{now}.wav"},f"audios/cli_output_{now}.wav"
40
+ except subprocess.CalledProcessError as e:
41
+ print(f"Error: {e}")
42
+ return {"choices":show_available("audios"),"__type__":"update"}, None
43
+
44
+ assets_folder = "assets"
45
+ if not os.path.exists(assets_folder):
46
+ os.makedirs(assets_folder)
47
+ files = {
48
+ "rmvpe/rmvpe.pt":"https://huggingface.co/Rejekts/project/resolve/main/rmvpe.pt",
49
+ "hubert/hubert_base.pt":"https://huggingface.co/Rejekts/project/resolve/main/hubert_base.pt",
50
+ "pretrained_v2/D40k.pth":"https://huggingface.co/Rejekts/project/resolve/main/D40k.pth",
51
+ "pretrained_v2/G40k.pth":"https://huggingface.co/Rejekts/project/resolve/main/G40k.pth",
52
+ "pretrained_v2/f0D40k.pth":"https://huggingface.co/Rejekts/project/resolve/main/f0D40k.pth",
53
+ "pretrained_v2/f0G40k.pth":"https://huggingface.co/Rejekts/project/resolve/main/f0G40k.pth"
54
+ }
55
+ for file, link in files.items():
56
+ file_path = os.path.join(assets_folder, file)
57
+ if not os.path.exists(file_path):
58
+ try:
59
+ subprocess.run(['wget', link, '-O', file_path], check=True)
60
+ except subprocess.CalledProcessError as e:
61
+ print(f"Error downloading {file}: {e}")
62
+
63
+ def download_from_url(url, model):
64
+ if model =='':
65
+ try:
66
+ model = url.split('/')[-1].split('?')[0]
67
+ except:
68
+ return "You need to name your model. For example: My-Model", {"choices":show_available("assets/weights"),"__type__":"update"}
69
+ url=url.replace('/blob/main/','/resolve/main/')
70
+ model=model.replace('.pth','').replace('.index','').replace('.zip','')
71
+ print(f"Model name: {model}")
72
+ if url == '':
73
+ return "URL cannot be left empty.", {"choices":show_available("assets/weights"),"__type__":"update"}
74
+ url = url.strip()
75
+ zip_dirs = ["zips", "unzips"]
76
+ for directory in zip_dirs:
77
+ if os.path.exists(directory):
78
+ shutil.rmtree(directory)
79
+ os.makedirs("zips", exist_ok=True)
80
+ os.makedirs("unzips", exist_ok=True)
81
+ zipfile = model + '.zip'
82
+ zipfile_path = './zips/' + zipfile
83
+ try:
84
+ if url.endswith('.pth'):
85
+ subprocess.run(["wget", url, "-O", f'./assets/weights/{model}.pth'])
86
+ return f"Sucessfully downloaded as {model}.pth", {"choices":show_available("assets/weights"),"__type__":"update"}
87
+ elif url.endswith('.index'):
88
+ if not os.path.exists(f'./logs/{model}'): os.makedirs(f'./logs/{model}')
89
+ subprocess.run(["wget", url, "-O", f'./logs/{model}/added_{model}.index'])
90
+ return f"Successfully downloaded as added_{model}.index", {"choices":show_available("assets/weights"),"__type__":"update"}
91
+ if "drive.google.com" in url:
92
+ subprocess.run(["gdown", url, "--fuzzy", "-O", zipfile_path])
93
+ elif "mega.nz" in url:
94
+ m = Mega()
95
+ m.download_url(url, './zips')
96
+ else:
97
+ subprocess.run(["wget", url, "-O", zipfile_path])
98
+ for filename in os.listdir("./zips"):
99
+ if filename.endswith(".zip"):
100
+ zipfile_path = os.path.join("./zips/",filename)
101
+ shutil.unpack_archive(zipfile_path, "./unzips", 'zip')
102
+ else:
103
+ return "No zipfile found.", {"choices":show_available("assets/weights"),"__type__":"update"}
104
+ for root, dirs, files in os.walk('./unzips'):
105
+ for file in files:
106
+ file_path = os.path.join(root, file)
107
+ if file.endswith(".index"):
108
+ os.mkdir(f'./logs/{model}')
109
+ shutil.copy2(file_path,f'./logs/{model}')
110
+ elif "G_" not in file and "D_" not in file and file.endswith(".pth"):
111
+ shutil.copy(file_path,f'./assets/weights/{model}.pth')
112
+ shutil.rmtree("zips")
113
+ shutil.rmtree("unzips")
114
+ return "Success.", {"choices":show_available("assets/weights"),"__type__":"update"}
115
+ except:
116
+ return "There's been an error.", {"choices":show_available("assets/weights"),"__type__":"update"}
117
+
118
+ def show_available(filepath,format=None):
119
+ if format:
120
+ print(f"Format: {format}")
121
+ files = []
122
+ for file in os.listdir(filepath):
123
+ if file.endswith(format):
124
+ print(f"Matches format: {file}")
125
+ files.append(file)
126
+ else:
127
+ print(f"Does not match format: {file}")
128
+ print(f"Matches: {files}")
129
+ if len(files) < 1:
130
+ return ['']
131
+ return files
132
+ if len(os.listdir(filepath)) < 1:
133
+ return ['']
134
+ return os.listdir(filepath)
135
+
136
+ def upload_file(file):
137
+ audio_formats = ['.wav', '.mp3', '.ogg', '.flac', '.aac']
138
+ print(file)
139
+ try:
140
+ _, ext = os.path.splitext(file.name)
141
+ filename = os.path.basename(file.name)
142
+ file_path = file.name
143
+ except AttributeError:
144
+ _, ext = os.path.splitext(file)
145
+ filename = os.path.basename(file)
146
+ file_path = file
147
+ if ext.lower() in audio_formats:
148
+ if os.path.exists(f'audios/{filename}'):
149
+ os.remove(f'audios/{filename}')
150
+ shutil.move(file_path,'audios')
151
+ else:
152
+ gr.Warning('File incompatible')
153
+ return {"choices":show_available('audios'),"__type__": "update","value":filename}
154
+
155
+ def refresh():
156
+ return {"choices":show_available("audios"),"__type__": "update"},{"choices":show_available("assets/weights",".pth"),"__type__": "update"},{"choices":show_available("logs"),"__type__": "update"}
157
+
158
+ def update_audio_player(choice):
159
+ return os.path.join("audios",choice)
160
+
161
+ with gr.Blocks() as app:
162
+ with gr.Row():
163
+ with gr.Column():
164
+ gr.HTML("<img src='file/a.png' alt='easy>")
165
+ with gr.Column():
166
+ gr.HTML("<a href='https://ko-fi.com/rejekts' target='_blank'><img src='file/kofi_button.png' alt='Support Me'></a>")
167
+ with gr.Row():
168
+ with gr.Column():
169
+ with gr.Tabs():
170
+ with gr.TabItem("1.Choose a voice model:"):
171
+ 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)
172
+ index_picker = gr.Dropdown(label="Index:",interactive=True,choices=show_available('logs'),value=show_available('logs')[0],allow_custom_value=True)
173
+ with gr.TabItem("(Or download a model here)"):
174
+ with gr.Row():
175
+ url = gr.Textbox(label="Paste the URL here:",value="",placeholder="(i.e. https://huggingface.co/repo/model/resolve/main/model.zip)")
176
+ with gr.Row():
177
+ with gr.Column():
178
+ model_rename = gr.Textbox(placeholder="My-Model", label="Name your model:",value="")
179
+ with gr.Column():
180
+ download_button = gr.Button("Download")
181
+ download_button.click(fn=download_from_url,inputs=[url,model_rename],outputs=[url,model_picker])
182
+ with gr.TabItem("Advanced"):
183
+ index_rate = gr.Slider(label='Index Rate: ',minimum=0,maximum=1,value=0.66,step=0.01)
184
+ 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)
185
+
186
+ with gr.Row():
187
+ with gr.Tabs():
188
+ with gr.TabItem("2.Choose an audio file:"):
189
+ recorder = gr.Microphone(label="Record audio here...",type='filepath')
190
+ audio_picker = gr.Dropdown(label="",choices=show_available('audios'),value='',interactive=True)
191
+ recorder.stop_recording(upload_file, inputs=[recorder],outputs=[audio_picker])
192
+ with gr.TabItem("(Or upload a new file here)"):
193
+ dropbox = gr.File(label="Drop an audio here.",file_types=['.wav', '.mp3', '.ogg', '.flac', '.aac'], type="filepath")
194
+ dropbox.upload(fn=upload_file, inputs=[dropbox],outputs=[audio_picker])
195
+ audio_refresher = gr.Button("Refresh")
196
+ audio_refresher.click(fn=refresh,inputs=[],outputs=[audio_picker,model_picker,index_picker])
197
+ convert_button = gr.Button("Convert")
198
+ with gr.Row():
199
+ audio_player = gr.Audio()
200
+ audio_picker.change(fn=update_audio_player, inputs=[audio_picker],outputs=[audio_player])
201
+ convert_button.click(convert, inputs=[audio_picker,model_picker,index_picker,index_rate,pitch],outputs=[audio_picker,audio_player])
202
+
203
+ app.queue().launch()