Spaces:
Runtime error
Runtime error
Update app.py
Browse files17 unmodified lines18192021222341 unmodified lines6566676869707172737475767778798081828384858687888990914 unmodified lines969798991001011021031041051061071081 unmodified line1101111121131141151162 unmodified lines11912012112212312412517 unmodified lines1431441451461471481491501511521531541551561571581591 unmodified line16116216316416516616716816917017127 unmodified lines19920020120220320420524 unmodified lines230231232233234235236134 unmodified lines37137237337437537637727 unmodified lines4054064074084094104113 unmodified lines41541641741841942042142242342442511 unmodified lines43743843944044144244344444518 unmodified lines4644654664674684694701 unmodified line47247347447547647747847948048126 unmodified lines50850951051151251351429 unmodified lines54454554654754854955018 unmodified lines5695705715725735745754 unmodified lines58058158258317 unmodified linesfrom pydub import AudioSegmentimport noisereduce as nrimport numpy as nplogging.getLogger("infer_rvc_python").setLevel(logging.ERROR)41 unmodified linesfor base_file in [a_, b_]:if base_file is not None and base_file.endswith(".txt"):txt_files.append(base_file)directory = os.path.dirname(a_)for txt in txt_files:with open(txt, 'r') as file:first_line = file.readline()download_manager(url=first_line.strip(),path=directory,extension="",)for f in find_files(directory):if f.endswith(".zip"):unzip_in_folder(f, directory)model = Noneindex = Noneend_files = find_files(directory)for ff in end_files:if ff.endswith(".pth"):model = os.path.join(directory, ff)4 unmodified linesif not model:gr.Error(f"Model not found in: {end_files}")if not index:gr.Warning("Index not found")return model, indexdef add_audio_effects(audio_list):print("Audio effects")1 unmodified linefor audio_path in audio_list:try:output_path = f'{os.path.splitext(audio_path)[0]}_effects.wav'# Initialize audio effects pluginsboard = Pedalboard([2 unmodified linesReverb(room_size=0.10, dry_level=0.8, wet_level=0.2, damping=0.7)])with AudioFile(audio_path) as f:with AudioFile(output_path, 'w', f.samplerate, f.num_channels) as o:# Read one second of audio at a time, until the file is empty:17 unmodified linesresult = []for audio_path in audio_list:out_path = f'{os.path.splitext(audio_path)[0]}_noisereduce.wav'try:# Load audio fileaudio = AudioSegment.from_file(audio_path)# Convert audio to numpy arraysamples = np.array(audio.get_array_of_samples())# Reduce noisereduced_noise = nr.reduce_noise(samples, sr=audio.frame_rate, prop_decrease=0.6)# Convert reduced noise signal back to audioreduced_audio = AudioSegment(reduced_noise.tobytes(),1 unmodified linesample_width=audio.sample_width,channels=audio.channels)# Save reduced audio to filereduced_audio.export(out_path, format="wav")result.append(out_path)except Exception as e:traceback.print_exc()print(f"Error noisereduce: {str(e)}")27 unmodified lines):if not audio_files:raise ValueError("The audio pls")if isinstance(audio_files, str):audio_files = [audio_files]24 unmodified linesif audio_effects:result = add_audio_effects(result)return result134 unmodified linesvisible=False,)def tts_play_conf():return gr.Checkbox(False,27 unmodified linesdef effects_conf():return gr.Checkbox(False,label="Effects",# info="",container=False,visible=True,3 unmodified linesdef infer_tts_audio(tts_voice, tts_text, play_tts):out_dir = "output"folder_tts = "USER_"+str(random.randint(10000, 99999))os.makedirs(out_dir, exist_ok=True)os.makedirs(os.path.join(out_dir, folder_tts), exist_ok=True)out_path = os.path.join(out_dir, folder_tts, "tts.mp3")asyncio.run(edge_tts.Communicate(tts_text, "-".join(tts_voice.split('-')[:-1])).save(out_path))if play_tts:return [out_path], out_path11 unmodified linesvisible=value_active)def get_gui(theme):with gr.Blocks(theme=theme) as app:gr.Markdown(title)gr.Markdown(description)18 unmodified lines)aud = audio_conf()gr.HTML("<hr></h2>")tts_button.click(fn=infer_tts_audio,1 unmodified lineoutputs=[aud, tts_play],)with gr.Column():with gr.Row():model = model_conf()indx = index_conf()algo = pitch_algo_conf()algo_lvl = pitch_lvl_conf()indx_inf = index_inf_conf()26 unmodified linesoutputs=[output_base],)gr.Examples(examples=[[29 unmodified lines0.25,0.50,],],fn=run,inputs=[18 unmodified linestts_voice_list = asyncio.new_event_loop().run_until_complete(edge_tts.list_voices())voices = sorted([f"{v['ShortName']}-{v['Gender']}" for v in tts_voice_list])app = get_gui(theme)app.queue(default_concurrency_limit=40)4 unmodified linesshow_error=True,quiet=False,debug=False,)17 unmodified lines18192021222324252641 unmodified lines6869707172737475767778798081828384858687888990919293944 unmodified lines991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981991 unmodified line2012022032042052062072 unmodified lines21021121221321421521617 unmodified lines2342352362372382392402412422432442452462472482492501 unmodified line25225325425525625725825926026126227 unmodified lines29029129229329429529624 unmodified lines321322323324325326327134 unmodified lines46246346446546646746827 unmodified lines4964974984995005015023 unmodified lines50650750850951051151251351451551611 unmodified lines52852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257318 unmodified lines5925935945955965975981 unmodified line60060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263326 unmodified lines66066166266366466529 unmodified lines69569669769869970070118 unmodified lines7207217227237247257264 unmodified lines73173273373473517 unmodified linesfrom pydub import AudioSegmentimport noisereduce as nrimport numpy as npimport urllib.requestimport shutilimport threadinglogging.getLogger("infer_rvc_python").setLevel(logging.ERROR)41 unmodified linesfor base_file in [a_, b_]:if base_file is not None and base_file.endswith(".txt"):txt_files.append(base_file)directory = os.path.dirname(a_)for txt in txt_files:with open(txt, 'r') as file:first_line = file.readline()download_manager(url=first_line.strip(),path=directory,extension="",)for f in find_files(directory):if f.endswith(".zip"):unzip_in_folder(f, directory)model = Noneindex = Noneend_files = find_files(directory)for ff in end_files:if ff.endswith(".pth"):model = os.path.join(directory, ff)4 unmodified linesif not model:gr.Error(f"Model not found in: {end_files}")if not index:gr.Warning("Index not found")return model, indexdef get_file_size(url):if "huggingface" not in url:raise ValueError("Only downloads from Hugging Face are allowed")try:with urllib.request.urlopen(url) as response:info = response.info()content_length = info.get("Content-Length")file_size = int(content_length)if file_size > 500000000:raise ValueError("The file is too large. You can only download files up to 500 MB in size.")except Exception as e:raise edef clear_files(directory):time.sleep(15)print(f"Clearing files: {directory}.")shutil.rmtree(directory)def get_my_model(url_data):if not url_data:return None, Noneif "," in url_data:a_, b_ = url_data.split()a_, b_ = a_.strip().replace("/blob/", "/resolve/"), b_.strip().replace("/blob/", "/resolve/")else:a_, b_ = url_data.strip().replace("/blob/", "/resolve/"), Noneout_dir = "downloads"folder_download = str(random.randint(1000, 9999))directory = os.path.join(out_dir, folder_download)os.makedirs(directory, exist_ok=True)try:get_file_size(a_)if b_:get_file_size(b_)valid_url = [a_] if not b_ else [a_, b_]for link in valid_url:download_manager(url=link,path=directory,extension="",)for f in find_files(directory):if f.endswith(".zip"):unzip_in_folder(f, directory)model = Noneindex = Noneend_files = find_files(directory)for ff in end_files:if ff.endswith(".pth"):model = ffgr.Info(f"Model found: {ff}")if ff.endswith(".index"):index = ffgr.Info(f"Index found: {ff}")if not model:raise ValueError(f"Model not found in: {end_files}")if not index:gr.Warning("Index not found")else:index = os.path.abspath(index)return os.path.abspath(model), indexexcept Exception as e:raise efinally:# time.sleep(10)# shutil.rmtree(directory)t = threading.Thread(target=clear_files, args=(directory,))t.start()def add_audio_effects(audio_list):print("Audio effects")1 unmodified linefor audio_path in audio_list:try:output_path = f'{os.path.splitext(audio_path)[0]}_effects.wav'# Initialize audio effects pluginsboard = Pedalboard([2 unmodified linesReverb(room_size=0.10, dry_level=0.8, wet_level=0.2, damping=0.7)])with AudioFile(audio_path) as f:with AudioFile(output_path, 'w', f.samplerate, f.num_channels) as o:# Read one second of audio at a time, until the file is empty:17 unmodified linesresult = []for audio_path in audio_list:out_path = f'{os.path.splitext(audio_path)[0]}_noisereduce.wav'try:# Load audio fileaudio = AudioSegment.from_file(audio_path)# Convert audio to numpy arraysamples = np.array(audio.get_array_of_samples())# Reduce noisereduced_noise = nr.reduce_noise(samples, sr=audio.frame_rate, prop_decrease=0.6)# Convert reduced noise signal back to audioreduced_audio = AudioSegment(reduced_noise.tobytes(),1 unmodified linesample_width=audio.sample_width,channels=audio.channels)# Save reduced audio to filereduced_audio.export(out_path, format="wav")result.append(out_path)except Exception as e:traceback.print_exc()print(f"Error noisereduce: {str(e)}")27 unmodified lines):if not audio_files:raise ValueError("The audio pls")if isinstance(audio_files, str):audio_files = [audio_files]24 unmodified linesif audio_effects:result = add_audio_effects(result)return result134 unmodified linesvisible=False,)def tts_play_conf():return gr.Checkbox(False,27 unmodified linesdef effects_conf():return gr.Checkbox(False,label="Reverb",# info="",container=False,visible=True,3 unmodified linesdef infer_tts_audio(tts_voice, tts_text, play_tts):out_dir = "output"folder_tts = "USER_"+str(random.randint(10000, 99999))os.makedirs(out_dir, exist_ok=True)os.makedirs(os.path.join(out_dir, folder_tts), exist_ok=True)out_path = os.path.join(out_dir, folder_tts, "tts.mp3")asyncio.run(edge_tts.Communicate(tts_text, "-".join(tts_voice.split('-')[:-1])).save(out_path))if play_tts:return [out_path], out_path11 unmodified linesvisible=value_active)def down_active_conf():return gr.Checkbox(False,label="URL-to-Model",# info="",container=False,)def down_url_conf():return gr.Textbox(value="",placeholder="Write the url here...",label="Enter URL",visible=False,lines=1,)def down_button_conf():return gr.Button("Process",variant="secondary",visible=False,)def show_components_down(value_active):return gr.update(visible=value_active), gr.update(visible=value_active), gr.update(visible=value_active)def get_gui(theme):with gr.Blocks(theme=theme, delete_cache=(3200, 3200)) as app:gr.Markdown(title)gr.Markdown(description)18 unmodified lines)aud = audio_conf()# gr.HTML("<hr>")tts_button.click(fn=infer_tts_audio,1 unmodified lineoutputs=[aud, tts_play],)down_active_gui = down_active_conf()down_info = gr.Markdown("Provide a link to a zip file, like this one: `https://huggingface.co/mrmocciai/Models/resolve/main/Genshin%20Impact/ayaka-v2.zip?download=true`, or separate links for the .pth and .index files, like this: `https://huggingface.co/sail-rvc/ayaka-jp/resolve/main/model.pth?download=true, https://huggingface.co/sail-rvc/ayaka-jp/resolve/main/model.index?download=true`",visible=False)with gr.Row():with gr.Column(scale=3):down_url_gui = down_url_conf()with gr.Column(scale=1):down_button_gui = down_button_conf()with gr.Column():with gr.Row():model = model_conf()indx = index_conf()down_active_gui.change(show_components_down,[down_active_gui],[down_info, down_url_gui, down_button_gui])down_button_gui.click(get_my_model,[down_url_gui],[model, indx])algo = pitch_algo_conf()algo_lvl = pitch_lvl_conf()indx_inf = index_inf_conf()26 unmodified linesoutputs=[output_base],)gr.Examples(examples=[[29 unmodified lines0.25,0.50,],],fn=run,inputs=[18 unmodified linestts_voice_list = asyncio.new_event_loop().run_until_complete(edge_tts.list_voices())voices = sorted([f"{v['ShortName']}-{v['Gender']}" for v in tts_voice_list])app = get_gui(theme)app.queue(default_concurrency_limit=40)4 unmodified linesshow_error=True,quiet=False,debug=False,allowed_paths=["./downloads/"],)
app.py+180-28