import json import os import shutil import urllib.request import zipfile import gdown from argparse import ArgumentParser import gradio as gr import spaces from src.main import song_cover_pipeline BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) mdxnet_models_dir = 'mdxnet_models' rvc_models_dir = 'rvc_models' output_dir = 'song_output' def download_and_extract_model(model_url, model_name, progress=gr.Progress()): try: os.makedirs(rvc_models_dir, exist_ok=True) extraction_folder = os.path.join(rvc_models_dir, model_name) zip_path = os.path.join(rvc_models_dir, f'{model_name}.zip') if os.path.exists(extraction_folder): raise gr.Error(f'Voice model directory {model_name} already exists! Choose a different name for your voice model.') progress(0, desc=f'[~] Downloading voice model with name {model_name}...') try: if 'huggingface.co' in model_url: urllib.request.urlretrieve(model_url, zip_path) elif 'pixeldrain.com' in model_url: pixeldrain_id = model_url.split('/')[-1] pixeldrain_url = f'https://pixeldrain.com/api/file/{pixeldrain_id}' urllib.request.urlretrieve(pixeldrain_url, zip_path) elif 'drive.google.com' in model_url: file_id = model_url.split('/')[-2] gdown.download(id=file_id, output=zip_path, quiet=False) else: urllib.request.urlretrieve(model_url, zip_path) except Exception as download_error: raise gr.Error(f"Failed to download the model: {str(download_error)}") if not os.path.exists(zip_path): raise gr.Error(f"Failed to download the model. The zip file was not created.") progress(0.5, desc="Extracting model...") extract_zip(extraction_folder, zip_path) pth_files = [f for f in os.listdir(extraction_folder) if f.endswith('.pth')] if not pth_files: raise ValueError("No .pth file found in the downloaded model.") progress(1, desc="Model ready") return model_name except Exception as e: if os.path.exists(extraction_folder): shutil.rmtree(extraction_folder) if os.path.exists(zip_path): os.remove(zip_path) raise gr.Error(f"Error downloading or extracting model: {str(e)}") def cleanup_temp_model(model_name): temp_dir = os.path.join(rvc_models_dir, model_name) try: shutil.rmtree(temp_dir) except Exception as e: print(f"Error cleaning up temporary model files: {str(e)}") def extract_zip(extraction_folder, zip_name): os.makedirs(extraction_folder) with zipfile.ZipFile(zip_name, 'r') as zip_ref: zip_ref.extractall(extraction_folder) os.remove(zip_name) index_filepath, model_filepath = None, None for root, dirs, files in os.walk(extraction_folder): for name in files: if name.endswith('.index') and os.stat(os.path.join(root, name)).st_size > 1024 * 100: index_filepath = os.path.join(root, name) if name.endswith('.pth') and os.stat(os.path.join(root, name)).st_size > 1024 * 1024 * 40: model_filepath = os.path.join(root, name) if not model_filepath: raise gr.Error(f'No .pth model file was found in the extracted zip. Please check {extraction_folder}.') # move model and index file to extraction folder os.rename(model_filepath, os.path.join(extraction_folder, os.path.basename(model_filepath))) if index_filepath: os.rename(index_filepath, os.path.join(extraction_folder, os.path.basename(index_filepath))) # remove any unnecessary nested folders for filepath in os.listdir(extraction_folder): if os.path.isdir(os.path.join(extraction_folder, filepath)): shutil.rmtree(os.path.join(extraction_folder, filepath)) def download_online_model(url, dir_name, progress=gr.Progress()): try: progress(0, desc=f'[~] Downloading voice model with name {dir_name}...') zip_name = url.split('/')[-1] extraction_folder = os.path.join(rvc_models_dir, dir_name) if os.path.exists(extraction_folder): raise gr.Error(f'Voice model directory {dir_name} already exists! Choose a different name for your voice model.') if 'huggingface.co' in url: urllib.request.urlretrieve(url, zip_name) if 'pixeldrain.com' in url: zip_name = dir_name + '.zip' url = f'https://pixeldrain.com/api/file/{zip_name}' urllib.request.urlretrieve(url, zip_name) elif 'drive.google.com' in url: # Extract the Google Drive file ID zip_name = dir_name + '.zip' file_id = url.split('/')[-2] output = os.path.join('.', f'{dir_name}.zip') # Adjust the output path if needed gdown.download(id=file_id, output=output, quiet=False) progress(0.5, desc='[~] Extracting zip...') extract_zip(extraction_folder, zip_name) return f'[+] {dir_name} Model successfully downloaded!' except Exception as e: raise gr.Error(str(e)) def upload_local_model(zip_path, dir_name, progress=gr.Progress()): try: extraction_folder = os.path.join(rvc_models_dir, dir_name) if os.path.exists(extraction_folder): raise gr.Error(f'Voice model directory {dir_name} already exists! Choose a different name for your voice model.') zip_name = zip_path.name progress(0.5, desc='[~] Extracting zip...') extract_zip(extraction_folder, zip_name) return f'[+] {dir_name} Model successfully uploaded!' except Exception as e: raise gr.Error(str(e)) def pub_dl_autofill(pub_models, event: gr.SelectData): return gr.Text.update(value=pub_models.loc[event.index[0], 'URL']), gr.Text.update(value=pub_models.loc[event.index[0], 'Model Name']) def swap_visibility(): return gr.update(visible=True), gr.update(visible=False), gr.update(value=''), gr.update(value=None) def process_file_upload(file): return file.name, gr.update(value=file.name) def show_hop_slider(pitch_detection_algo): if pitch_detection_algo == 'mangio-crepe': return gr.update(visible=True) else: return gr.update(visible=False) def song_cover_pipeline_with_model_download(song_input, model_url, model_name, pitch, keep_files, is_webui, main_gain, backup_gain, inst_gain, index_rate, filter_radius, rms_mix_rate, f0_method, crepe_hop_length, protect, pitch_all, reverb_rm_size, reverb_wet, reverb_dry, reverb_damping, output_format, progress=gr.Progress()): model_path = None try: model_path = download_and_extract_model(model_url, model_name, progress) print(f"Model path: {model_path}") result = song_cover_pipeline(song_input, model_path, pitch, keep_files, is_webui, main_gain, backup_gain, inst_gain, index_rate, filter_radius, rms_mix_rate, f0_method, crepe_hop_length, protect, pitch_all, reverb_rm_size, reverb_wet, reverb_dry, reverb_damping, output_format, progress) # Clean up old folders in song_output output_folders = [f for f in os.listdir(output_dir) if os.path.isdir(os.path.join(output_dir, f))] output_folders.sort(key=lambda x: os.path.getmtime(os.path.join(output_dir, x))) while len(output_folders) > 100: oldest_folder = output_folders.pop(0) shutil.rmtree(os.path.join(output_dir, oldest_folder)) return result except gr.Error as e: return str(e), None # Return error message and None for the second output finally: if model_path: cleanup_temp_model(model_path) if __name__ == '__main__': parser = ArgumentParser(description='Generate a AI cover song in the song_output/id directory.', add_help=True) parser.add_argument("--share", action="store_true", dest="share_enabled", default=False, help="Enable sharing") parser.add_argument("--listen", action="store_true", default=False, help="Make the WebUI reachable from your local network.") parser.add_argument('--listen-host', type=str, help='The hostname that the server will use.') parser.add_argument('--listen-port', type=int, help='The listening port that the server will use.') args = parser.parse_args() with gr.Blocks(title='AICoverGenWebUI', theme='NoCrypt/miku@1.2.2') as app: gr.Label('AICoverGen WebUI created with ❤️', show_label=False) # main tab with gr.Tab("Generate"): with gr.Accordion('Main Options'): with gr.Row(): with gr.Column(): model_url = gr.Text(label='Voice Model URL', info='Enter the URL of the voice model zip file', value='https://huggingface.co/megaaziib/my-rvc-models-collection/resolve/main/kobo.zip') model_name = gr.Text(label='Voice Model Name', info='Enter the name of the voice model', value='kobo') # 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') with gr.Column() as yt_link_col: 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.', value='https://youtu.be/FRh7LvlQTuA') show_file_upload_button = gr.Button('Upload file instead') with gr.Column(visible=False) as file_upload_col: local_file = gr.File(label='Audio file') song_input_file = gr.UploadButton('Upload 📂', file_types=['audio'], variant='primary') show_yt_link_button = gr.Button('Paste YouTube link/Path to local file instead') song_input_file.upload(process_file_upload, inputs=[song_input_file], outputs=[local_file, song_input]) with gr.Column(): pitch = gr.Slider(-24, 24, value=0, step=1, label='Pitch Change (Vocals ONLY)', info='Generally, use 12 for male to female conversions and -12 for vice-versa. (Octaves)') 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)') show_file_upload_button.click(swap_visibility, outputs=[file_upload_col, yt_link_col, song_input, local_file]) show_yt_link_button.click(swap_visibility, outputs=[yt_link_col, file_upload_col, song_input, local_file]) with gr.Accordion('Voice conversion options', open=False): with gr.Row(): 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") 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') 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)") 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.') with gr.Column(): 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)') 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.') f0_method.change(show_hop_slider, inputs=f0_method, outputs=crepe_hop_length) 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') with gr.Accordion('Audio mixing options', open=False): gr.Markdown('### Volume Change (decibels)') with gr.Row(): main_gain = gr.Slider(-20, 20, value=0, step=1, label='Main Vocals') backup_gain = gr.Slider(-20, 20, value=0, step=1, label='Backup Vocals') inst_gain = gr.Slider(-20, 20, value=0, step=1, label='Music') gr.Markdown('### Reverb Control on AI Vocals') with gr.Row(): reverb_rm_size = gr.Slider(0, 1, value=0.15, label='Room size', info='The larger the room, the longer the reverb time') reverb_wet = gr.Slider(0, 1, value=0.2, label='Wetness level', info='Level of AI vocals with reverb') reverb_dry = gr.Slider(0, 1, value=0.8, label='Dryness level', info='Level of AI vocals without reverb') reverb_damping = gr.Slider(0, 1, value=0.7, label='Damping level', info='Absorption of high frequencies in the reverb') gr.Markdown('### Audio Output Format') 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') with gr.Row(): clear_btn = gr.ClearButton(value='Clear', components=[song_input, model_url, keep_files, local_file]) generate_btn = gr.Button("Generate", variant='primary') with gr.Row(): ai_cover = gr.Audio(label='AI Cover (Vocal Only Inference)', show_share_button=False) ai_backing = gr.Audio(label='AI Cover (Vocal Backing Inference)', show_share_button=False) is_webui = gr.Number(value=1, visible=False) generate_btn.click(song_cover_pipeline_with_model_download, inputs=[song_input, model_url, model_name, pitch, keep_files, is_webui, main_gain, backup_gain, inst_gain, index_rate, filter_radius, rms_mix_rate, f0_method, crepe_hop_length, protect, pitch_all, reverb_rm_size, reverb_wet, reverb_dry, reverb_damping, output_format], outputs=[ai_cover, ai_backing]) 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], outputs=[pitch, main_gain, backup_gain, inst_gain, index_rate, filter_radius, rms_mix_rate, protect, f0_method, crepe_hop_length, pitch_all, reverb_rm_size, reverb_wet, reverb_dry, reverb_damping, output_format, ai_cover]) app.launch( share=args.share_enabled, server_name=None if not args.listen else (args.listen_host or '0.0.0.0'), server_port=args.listen_port, )