surfmore/SimpleRVC
0
1import zipfile2import hashlib3from utils.model import model_downloader, get_model4import requests5import json6import torch7import os8from inference import Inference9import gradio as gr10from constants import VOICE_METHODS, BARK_VOICES, EDGE_VOICES, zips_folder, unzips_folder11from tts.conversion import tts_infer, ELEVENLABS_VOICES_RAW, ELEVENLABS_VOICES_NAMES12 13api_url = "https://rvc-models-api.onrender.com/uploadfile/"14 15if not os.path.exists(zips_folder):16 os.mkdir(zips_folder)17if not os.path.exists(unzips_folder):18 os.mkdir(unzips_folder)19 20def get_info(path):21 path = os.path.join(unzips_folder, path)22 try:23 a = torch.load(path, map_location="cpu")24 return a25 except Exception as e:26 print("*****************eeeeeeeeeeeeeeeeeeeerrrrrrrrrrrrrrrrrr*****")27 print(e)28 return {29 30 }31def calculate_md5(file_path):32 hash_md5 = hashlib.md5()33 with open(file_path, "rb") as f:34 for chunk in iter(lambda: f.read(4096), b""):35 hash_md5.update(chunk)36 return hash_md5.hexdigest()37 38def compress(modelname, files):39 file_path = os.path.join(zips_folder, f"{modelname}.zip")40 # Select the compression mode ZIP_DEFLATED for compression41 # or zipfile.ZIP_STORED to just store the file42 compression = zipfile.ZIP_DEFLATED43 44 # Comprueba si el archivo ZIP ya existe45 if not os.path.exists(file_path):46 # Si no existe, crea el archivo ZIP47 with zipfile.ZipFile(file_path, mode="w") as zf:48 try:49 for file in files:50 if file:51 # Agrega el archivo al archivo ZIP52 zf.write(unzips_folder if ".index" in file else os.path.join(unzips_folder, file), compress_type=compression)53 except FileNotFoundError as fnf:54 print("An error occurred", fnf)55 else:56 # Si el archivo ZIP ya existe, agrega los archivos a un archivo ZIP existente57 with zipfile.ZipFile(file_path, mode="a") as zf:58 try:59 for file in files:60 if file:61 # Agrega el archivo al archivo ZIP62 zf.write(unzips_folder if ".index" in file else os.path.join(unzips_folder, file), compress_type=compression)63 except FileNotFoundError as fnf:64 print("An error occurred", fnf)65 66 return file_path67 68def infer(model, f0_method, audio_file, index_rate, vc_transform0, protect0, resample_sr1, filter_radius1):69 70 if not model:71 return "No model url specified, please specify a model url.", None72 73 if not audio_file:74 return "No audio file specified, please load an audio file.", None75 76 77 inference = Inference(78 model_name=model,79 f0_method=f0_method,80 source_audio_path=audio_file,81 feature_ratio=index_rate,82 transposition=vc_transform0,83 protection_amnt=protect0,84 resample=resample_sr1,85 harvest_median_filter=filter_radius1,86 output_file_name=os.path.join("./audio-outputs", os.path.basename(audio_file))87 )88 output = inference.run()89 if 'success' in output and output['success']:90 print("Inferencia realizada exitosamente...")91 return output, output['file']92 else:93 print("Fallo en la inferencia...", output)94 return "Failed", None95 96def post_model(name, model_url, version, creator):97 modelname = model_downloader(model_url, zips_folder, unzips_folder)98 model_files = get_model(unzips_folder, modelname)99 100 if not model_files:101 return "No se encontrado un modelo valido, verifica el contenido del enlace e intentalo más tarde."102 103 if not model_files.get('pth'):104 return "No se encontrado un modelo valido, verifica el contenido del enlace e intentalo más tarde."105 106 md5_hash = calculate_md5(os.path.join(unzips_folder,model_files['pth']))107 zipfile = compress(modelname, list(model_files.values()))108 109 a = get_info(model_files.get('pth'))110 file_to_upload = open(zipfile, "rb")111 info = a.get("info", "None"),112 sr = a.get("sr", "None"),113 f0 = a.get("f0", "None"),114 115 data = {116 "name": name,117 "version": version,118 "creator": creator,119 "hash": md5_hash,120 "info": info,121 "sr": sr,122 "f0": f0123 }124 print("Subiendo archivo...")125 # Realizar la solicitud POST126 response = requests.post(api_url, files={"file": file_to_upload}, data=data)127 result = response.json()128 129 # Comprobar la respuesta130 if response.status_code == 200:131 result = response.json()132 return json.dumps(result, indent=4)133 else:134 print("Error al cargar el archivo:", response.status_code)135 return result136 137 138def search_model(name):139 web_service_url = "https://script.google.com/macros/s/AKfycbyRaNxtcuN8CxUrcA_nHW6Sq9G2QJor8Z2-BJUGnQ2F_CB8klF4kQL--U2r2MhLFZ5J/exec"140 response = requests.post(web_service_url, json={141 'type': 'search_by_filename',142 'name': name143 })144 result = []145 response.raise_for_status() # Lanza una excepción en caso de error146 json_response = response.json()147 cont = 0148 result.append("""| Nombre del modelo | Url | Epoch | Sample Rate |149 | ---------------- | -------------- |:------:|:-----------:|150 """)151 yield "<br />".join(result)152 if json_response.get('ok', None):153 for model in json_response['ocurrences']:154 if cont < 20:155 model_name = str(model.get('name', 'N/A')).strip()156 model_url = model.get('url', 'N/A')157 epoch = model.get('epoch', 'N/A')158 sr = model.get('sr', 'N/A')159 line = f"""|{model_name}|<a>{model_url}</a>|{epoch}|{sr}|160 """161 result.append(line)162 yield "".join(result)163 cont += 1164 165def update_tts_methods_voice(select_value):166 if select_value == "Edge-tts":167 return gr.Dropdown.update(choices=EDGE_VOICES, visible=True, value="es-CO-GonzaloNeural-Male"), gr.Markdown.update(visible=False), gr.Textbox.update(visible=False),gr.Radio.update(visible=False)168 elif select_value == "Bark-tts":169 return gr.Dropdown.update(choices=BARK_VOICES, visible=True), gr.Markdown.update(visible=False), gr.Textbox.update(visible=False),gr.Radio.update(visible=False)170 elif select_value == 'ElevenLabs':171 return gr.Dropdown.update(choices=ELEVENLABS_VOICES_NAMES, visible=True, value="Bella"), gr.Markdown.update(visible=True), gr.Textbox.update(visible=True), gr.Radio.update(visible=False)172 elif select_value == 'CoquiTTS':173 return gr.Dropdown.update(visible=False), gr.Markdown.update(visible=False), gr.Textbox.update(visible=False), gr.Radio.update(visible=True)174 