Hev832 commited on
Commit
9a2077e
·
verified ·
1 Parent(s): 08d6ce2

Create web-app.py

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