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|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import os
|
3 |
+
import shutil
|
4 |
+
import urllib.request
|
5 |
+
import zipfile
|
6 |
+
from argparse import ArgumentParser
|
7 |
+
|
8 |
+
import gradio as gr
|
9 |
+
|
10 |
+
from main import song_cover_pipeline
|
11 |
+
|
12 |
+
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
13 |
+
|
14 |
+
mdxnet_models_dir = os.path.join(BASE_DIR, 'mdxnet_models')
|
15 |
+
rvc_models_dir = os.path.join(BASE_DIR, 'rvc_models')
|
16 |
+
output_dir = os.path.join(BASE_DIR, 'song_output')
|
17 |
+
|
18 |
+
|
19 |
+
def get_current_models(models_dir):
|
20 |
+
models_list = os.listdir(models_dir)
|
21 |
+
items_to_remove = ['hubert_base.pt', 'MODELS.txt', 'public_models.json', 'rmvpe.pt']
|
22 |
+
return [item for item in models_list if item not in items_to_remove]
|
23 |
+
|
24 |
+
|
25 |
+
def update_models_list():
|
26 |
+
models_l = get_current_models(rvc_models_dir)
|
27 |
+
return gr.Dropdown.update(choices=models_l)
|
28 |
+
|
29 |
+
|
30 |
+
def load_public_models():
|
31 |
+
models_table = []
|
32 |
+
for model in public_models['voice_models']:
|
33 |
+
if not model['name'] in voice_models:
|
34 |
+
model = [model['name'], model['description'], model['credit'], model['url'], ', '.join(model['tags'])]
|
35 |
+
models_table.append(model)
|
36 |
+
|
37 |
+
tags = list(public_models['tags'].keys())
|
38 |
+
return gr.DataFrame.update(value=models_table), gr.CheckboxGroup.update(choices=tags)
|
39 |
+
|
40 |
+
|
41 |
+
def extract_zip(extraction_folder, zip_name):
|
42 |
+
os.makedirs(extraction_folder)
|
43 |
+
with zipfile.ZipFile(zip_name, 'r') as zip_ref:
|
44 |
+
zip_ref.extractall(extraction_folder)
|
45 |
+
os.remove(zip_name)
|
46 |
+
|
47 |
+
index_filepath, model_filepath = None, None
|
48 |
+
for root, dirs, files in os.walk(extraction_folder):
|
49 |
+
for name in files:
|
50 |
+
if name.endswith('.index') and os.stat(os.path.join(root, name)).st_size > 1024 * 100:
|
51 |
+
index_filepath = os.path.join(root, name)
|
52 |
+
|
53 |
+
if name.endswith('.pth') and os.stat(os.path.join(root, name)).st_size > 1024 * 1024 * 40:
|
54 |
+
model_filepath = os.path.join(root, name)
|
55 |
+
|
56 |
+
if not model_filepath:
|
57 |
+
raise gr.Error(f'No .pth model file was found in the extracted zip. Please check {extraction_folder}.')
|
58 |
+
|
59 |
+
# move model and index file to extraction folder
|
60 |
+
os.rename(model_filepath, os.path.join(extraction_folder, os.path.basename(model_filepath)))
|
61 |
+
if index_filepath:
|
62 |
+
os.rename(index_filepath, os.path.join(extraction_folder, os.path.basename(index_filepath)))
|
63 |
+
|
64 |
+
# remove any unnecessary nested folders
|
65 |
+
for filepath in os.listdir(extraction_folder):
|
66 |
+
if os.path.isdir(os.path.join(extraction_folder, filepath)):
|
67 |
+
shutil.rmtree(os.path.join(extraction_folder, filepath))
|
68 |
+
|
69 |
+
|
70 |
+
def download_online_model(url, dir_name, progress=gr.Progress()):
|
71 |
+
try:
|
72 |
+
progress(0, desc=f'[~] Downloading voice model with name {dir_name}...')
|
73 |
+
zip_name = url.split('/')[-1]
|
74 |
+
extraction_folder = os.path.join(rvc_models_dir, dir_name)
|
75 |
+
if os.path.exists(extraction_folder):
|
76 |
+
raise gr.Error(f'Voice model directory {dir_name} already exists! Choose a different name for your voice model.')
|
77 |
+
|
78 |
+
if 'pixeldrain.com' in url:
|
79 |
+
url = f'https://pixeldrain.com/api/file/{zip_name}'
|
80 |
+
|
81 |
+
urllib.request.urlretrieve(url, zip_name)
|
82 |
+
|
83 |
+
progress(0.5, desc='[~] Extracting zip...')
|
84 |
+
extract_zip(extraction_folder, zip_name)
|
85 |
+
return f'[+] {dir_name} Model successfully downloaded!'
|
86 |
+
|
87 |
+
except Exception as e:
|
88 |
+
raise gr.Error(str(e))
|
89 |
+
|
90 |
+
|
91 |
+
def upload_local_model(zip_path, dir_name, progress=gr.Progress()):
|
92 |
+
try:
|
93 |
+
extraction_folder = os.path.join(rvc_models_dir, dir_name)
|
94 |
+
if os.path.exists(extraction_folder):
|
95 |
+
raise gr.Error(f'Voice model directory {dir_name} already exists! Choose a different name for your voice model.')
|
96 |
+
|
97 |
+
zip_name = zip_path.name
|
98 |
+
progress(0.5, desc='[~] Extracting zip...')
|
99 |
+
extract_zip(extraction_folder, zip_name)
|
100 |
+
return f'[+] {dir_name} Model successfully uploaded!'
|
101 |
+
|
102 |
+
except Exception as e:
|
103 |
+
raise gr.Error(str(e))
|
104 |
+
|
105 |
+
|
106 |
+
def filter_models(tags, query):
|
107 |
+
models_table = []
|
108 |
+
|
109 |
+
# no filter
|
110 |
+
if len(tags) == 0 and len(query) == 0:
|
111 |
+
for model in public_models['voice_models']:
|
112 |
+
models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']])
|
113 |
+
|
114 |
+
# filter based on tags and query
|
115 |
+
elif len(tags) > 0 and len(query) > 0:
|
116 |
+
for model in public_models['voice_models']:
|
117 |
+
if all(tag in model['tags'] for tag in tags):
|
118 |
+
model_attributes = f"{model['name']} {model['description']} {model['credit']} {' '.join(model['tags'])}".lower()
|
119 |
+
if query.lower() in model_attributes:
|
120 |
+
models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']])
|
121 |
+
|
122 |
+
# filter based on only tags
|
123 |
+
elif len(tags) > 0:
|
124 |
+
for model in public_models['voice_models']:
|
125 |
+
if all(tag in model['tags'] for tag in tags):
|
126 |
+
models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']])
|
127 |
+
|
128 |
+
# filter based on only query
|
129 |
+
else:
|
130 |
+
for model in public_models['voice_models']:
|
131 |
+
model_attributes = f"{model['name']} {model['description']} {model['credit']} {' '.join(model['tags'])}".lower()
|
132 |
+
if query.lower() in model_attributes:
|
133 |
+
models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']])
|
134 |
+
|
135 |
+
return gr.DataFrame.update(value=models_table)
|
136 |
+
|
137 |
+
|
138 |
+
def pub_dl_autofill(pub_models, event: gr.SelectData):
|
139 |
+
return gr.Text.update(value=pub_models.loc[event.index[0], 'URL']), gr.Text.update(value=pub_models.loc[event.index[0], 'Model Name'])
|
140 |
+
|
141 |
+
|
142 |
+
def swap_visibility():
|
143 |
+
return gr.update(visible=True), gr.update(visible=False), gr.update(value=''), gr.update(value=None)
|
144 |
+
|
145 |
+
|
146 |
+
def process_file_upload(file):
|
147 |
+
return file.name, gr.update(value=file.name)
|
148 |
+
|
149 |
+
|
150 |
+
def show_hop_slider(pitch_detection_algo):
|
151 |
+
if pitch_detection_algo == 'mangio-crepe':
|
152 |
+
return gr.update(visible=True)
|
153 |
+
else:
|
154 |
+
return gr.update(visible=False)
|
155 |
+
|
156 |
+
|
157 |
+
if __name__ == '__main__':
|
158 |
+
parser = ArgumentParser(description='Generate a AI cover song in the song_output/id directory.', add_help=True)
|
159 |
+
parser.add_argument("--share", action="store_true", dest="share_enabled", default=False, help="Enable sharing")
|
160 |
+
parser.add_argument("--listen", action="store_true", default=False, help="Make the WebUI reachable from your local network.")
|
161 |
+
parser.add_argument('--listen-host', type=str, help='The hostname that the server will use.')
|
162 |
+
parser.add_argument('--listen-port', type=int, help='The listening port that the server will use.')
|
163 |
+
args = parser.parse_args()
|
164 |
+
|
165 |
+
voice_models = get_current_models(rvc_models_dir)
|
166 |
+
with open(os.path.join(rvc_models_dir, 'public_models.json'), encoding='utf8') as infile:
|
167 |
+
public_models = json.load(infile)
|
168 |
+
|
169 |
+
|
170 |
+
|
171 |
+
with gr.Blocks(theme=gr.themes.Base()) as app:
|
172 |
+
with gr.Tab("Inference"):
|
173 |
+
with gr.Row():
|
174 |
+
rvc_model = gr.Dropdown(voice_models, label='Voice Models', info='Models folder "AICoverGen --> rvc_models". After new models are added into this folder, click the refresh button')
|
175 |
+
ref_btn = gr.Button('Refresh Models 🔁', variant='primary')
|
176 |
+
|
177 |
+
with gr.Column():
|
178 |
+
pitch = gr.Slider(-3, 3, value=0, step=1, label='Pitch Change (Vocals ONLY)', info='Generally, use 1 for male to female conversions and -1 for vice-versa. (Octaves)')
|
179 |
+
pitch_all = gr.Slider(-12, 12, value=0, step=1, label='Overall Pitch Change', info='Changes pitch/key of vocals and instrumentals together. Altering this slightly reduces sound quality. (Semitones)')
|
180 |
+
|
181 |
+
|
182 |
+
generate_btn = gr.Button("Generate", variant='primary')
|
183 |
+
with gr.Row():
|
184 |
+
|
185 |
+
with gr.Column() as yt_link_col:
|
186 |
+
song_input = gr.Text(label='Song input', info='Link to a song on YouTube or full path to a local file. For file upload, click the button below.')
|
187 |
+
show_file_upload_button = gr.Button('Upload file instead')
|
188 |
+
with gr.Column(visible=False) as file_upload_col:
|
189 |
+
local_file = gr.File(label='Audio file')
|
190 |
+
song_input_file = gr.UploadButton('Upload 📂', file_types=['audio'], variant='primary')
|
191 |
+
show_yt_link_button = gr.Button('Paste YouTube link/Path to local file instead')
|
192 |
+
song_input_file.upload(process_file_upload, inputs=[song_input_file], outputs=[local_file, song_input])
|
193 |
+
|
194 |
+
show_file_upload_button.click(swap_visibility, outputs=[file_upload_col, yt_link_col, song_input, local_file])
|
195 |
+
show_yt_link_button.click(swap_visibility, outputs=[yt_link_col, file_upload_col, song_input, local_file])
|
196 |
+
|
197 |
+
|
198 |
+
with gr.Column():
|
199 |
+
with gr.Accordion(label="Feature Settings", open=False):
|
200 |
+
index_rate = gr.Slider(0, 1, value=0.5, label='Index Rate', info="Controls how much of the AI voice's accent to keep in the vocals")
|
201 |
+
filter_radius = gr.Slider(0, 7, value=3, step=1, label='Filter radius', info='If >=3: apply median filtering median filtering to the harvested pitch results. Can reduce breathiness')
|
202 |
+
rms_mix_rate = gr.Slider(0, 1, value=0.25, label='RMS mix rate', info="Control how much to mimic the original vocal's loudness (0) or a fixed loudness (1)")
|
203 |
+
protect = gr.Slider(0, 0.5, value=0.33, label='Protect rate', info='Protect voiceless consonants and breath sounds. Set to 0.5 to disable.')
|
204 |
+
with gr.Row():
|
205 |
+
|
206 |
+
ai_cover = gr.Audio(label='Output Audio (Click on the Three Dots in the Right Corner to Download)', show_share_button=False)
|
207 |
+
|
208 |
+
with gr.Row():
|
209 |
+
f0_method = gr.Dropdown(['rmvpe', 'mangio-crepe'], value='rmvpe', label='Pitch detection algorithm', info='Best option is rmvpe (clarity in vocals), then mangio-crepe (smoother vocals)')
|
210 |
+
crepe_hop_length = gr.Slider(32, 320, value=128, step=1, visible=False, label='Crepe hop length', info='Lower values leads to longer conversions and higher risk of voice cracks, but better pitch accuracy.')
|
211 |
+
f0_method.change(show_hop_slider, inputs=f0_method, outputs=crepe_hop_length)
|
212 |
+
keep_files = gr.Checkbox(label='Keep intermediate files', info='Keep all audio files generated in the song_output/id directory, e.g. Isolated Vocals/Instrumentals. Leave unchecked to save space')
|
213 |
+
|
214 |
+
clear_btn = gr.ClearButton(value='Clear', components=[song_input, rvc_model, keep_files, local_file])
|
215 |
+
with gr.Row():
|
216 |
+
output_format = gr.Dropdown(['mp3', 'wav'], value='mp3', label='Output file type', info='mp3: small file size, decent quality. wav: Large file size, best quality')
|
217 |
+
with gr.Row():
|
218 |
+
instructions = gr.Markdown("""
|
219 |
+
This is simply a modified version of the RVC GUI found here:
|
220 |
+
https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI
|
221 |
+
""")
|
222 |
+
|
223 |
+
with gr.Row():
|
224 |
+
ref_btn.click(update_models_list, inputs=None, outputs=rvc_model)
|
225 |
+
is_webui = gr.Number(value=1, visible=False)
|
226 |
+
generate_btn.click(song_cover_pipeline,
|
227 |
+
inputs=[song_input, rvc_model, pitch, keep_files, is_webui,
|
228 |
+
index_rate, filter_radius, rms_mix_rate, f0_method, crepe_hop_length,
|
229 |
+
protect, pitch_all,output_format],
|
230 |
+
outputs=[ai_cover])
|
231 |
+
clear_btn.click(lambda: [0, 0, 0, 0, 0.5, 3, 0.25, 0.33, 'rmvpe', 128, 0, 0.15, 0.2, 0.8, 0.7, 'mp3', None],
|
232 |
+
outputs=[pitch, index_rate, filter_radius, rms_mix_rate,
|
233 |
+
protect, f0_method, crepe_hop_length, pitch_all,
|
234 |
+
output_format, ai_cover])
|
235 |
+
with gr.Tab("Download Model"):
|
236 |
+
with gr.Row():
|
237 |
+
url=gr.Textbox(label="Enter the URL to the Model:")
|
238 |
+
with gr.Row():
|
239 |
+
model = gr.Textbox(label="Name your model:")
|
240 |
+
download_button=gr.Button(label="Download")
|
241 |
+
with gr.Row():
|
242 |
+
status_bar=gr.Textbox(label="")
|
243 |
+
download_button.click(download_online_model, inputs=[url, model], outputs=status_bar)
|
244 |
+
|
245 |
+
app.queue()
|
246 |
+
app.launch(share=True, debug=True)
|
247 |
+
|