Update chat_ai.py
Browse files123456789102 unmodified lines1314151617181943 unmodified lines636465666768694 unmodified lines747576777879803 unmodified lines848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321338 unmodified lines14214314414514614714814915015113 unmodified lines165166167168169170171172173174175176177178179180181182183184185# text_to_speech.pyimport reimport tempfileimport warningsimport loggingimport clickimport gradio as grimport numpy as np2 unmodified linesfrom cached_path import cached_pathfrom transformers import AutoModelForCausalLM, AutoTokenizerfrom num2words import num2wordsimport torchfrom f5_tts.model import DiTfrom f5_tts.infer.utils_infer import (43 unmodified linesglobal whisper_modelif whisper_model is None:logger.info("Cargando modelo Whisper...")whisper_model = whisper.load_model("base") # Puedes cambiar a "small", "medium", "large" según tus necesidadeslogger.info("Modelo Whisper cargado.")return whisper_model4 unmodified linesdef reemplazar_numero(match):numero = match.group()return num2words(int(numero), lang='es')texto_traducido = re.sub(r'\b\d+\b', reemplazar_numero, texto_separado)3 unmodified linesref_audio_orig, ref_text, gen_text, remove_silence, cross_fade_duration=0.15, speed=1):"""Genera el audio sintetizado a partir del texto"""# Cargar los modelos si aún no están cargadosvocoder = cargar_vocoder()ema_model = cargar_F5TTS()ref_audio, ref_text = preprocess_ref_audio_text(ref_audio_orig, ref_text)if not gen_text.startswith(" "):gen_text = " " + gen_textif not gen_text.endswith(". "):gen_text += ". "gen_text = gen_text.lower()gen_text = traducir_numero_a_texto(gen_text)final_wave, final_sample_rate, combined_spectrogram = infer_process(ref_audio,ref_text,gen_text,ema_model,vocoder,cross_fade_duration=cross_fade_duration,speed=speed,)# Eliminar silencios si está activadoif remove_silence:with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f:sf.write(f.name, final_wave, final_sample_rate)remove_silence_for_generated_wav(f.name)final_wave, _ = torchaudio.load(f.name)final_wave = final_wave.squeeze().cpu().numpy()# Guardar el espectrograma (opcional)with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_spectrogram:spectrogram_path = tmp_spectrogram.namesave_spectrogram(combined_spectrogram, spectrogram_path)return (final_sample_rate, final_wave), spectrogram_pathdef transcribe_audio(audio_path):"""Transcribe el audio usando Whisper"""whisper_model = cargar_whisper()result = whisper_model.transcribe(audio_path)return result["text"]with gr.Blocks() as app:gr.Markdown(8 unmodified lineswith gr.Tab("Texto a Voz"):with gr.Row():ref_audio = gr.Audio(label="Audio de Referencia", type="filepath")ref_text = gr.Textbox(label="Texto de Referencia",info="Opcional: Deja en blanco si no tienes texto de referencia.",lines=2,)gen_text = gr.Textbox(13 unmodified linesstep=0.1,)generate_btn = gr.Button("Generar Audio")audio_output = gr.Audio(label="Audio Generado", type="filepath") # Corregido aquíspectrogram_output = gr.Image(label="Espectrograma Generado", visible=False)def generate_audio(ref_audio, ref_text, gen_text, remove_silence, speed):if not ref_audio:raise gr.Error("Por favor, proporciona un audio de referencia.")sample_rate, audio_wave = infer(ref_audio,ref_text,gen_text,remove_silence,speed=speed)audio_path = "generated_audio.wav"sf.write(audio_path, audio_wave, sample_rate)return audio_path, None # Retornar el audio y ocultar el espectrogramagenerate_btn.click(1234567891011122 unmodified lines15161718192043 unmodified lines646566676869704 unmodified lines757677787980818283843 unmodified lines8889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631648 unmodified lines17317417517617717817918018118213 unmodified lines196197198199200201202203204205206207208209210211212213214215216217218# text_to_speech_and_transcription.pyimport reimport tempfileimport warningsimport loggingimport osimport torchimport clickimport gradio as grimport numpy as np2 unmodified linesfrom cached_path import cached_pathfrom transformers import AutoModelForCausalLM, AutoTokenizerfrom num2words import num2wordsfrom f5_tts.model import DiTfrom f5_tts.infer.utils_infer import (43 unmodified linesglobal whisper_modelif whisper_model is None:logger.info("Cargando modelo Whisper...")whisper_model = whisper.load_model("base") # Cambia a "small", "medium", "large" si es necesariologger.info("Modelo Whisper cargado.")return whisper_model4 unmodified linesdef reemplazar_numero(match):numero = match.group()try:return num2words(int(numero), lang='es')except ValueError:return numerotexto_traducido = re.sub(r'\b\d+\b', reemplazar_numero, texto_separado)3 unmodified linesref_audio_orig, ref_text, gen_text, remove_silence, cross_fade_duration=0.15, speed=1):"""Genera el audio sintetizado a partir del texto"""try:# Cargar los modelos si aún no están cargadosvocoder = cargar_vocoder()ema_model = cargar_F5TTS()ref_audio, ref_text = preprocess_ref_audio_text(ref_audio_orig, ref_text)if not gen_text.startswith(" "):gen_text = " " + gen_textif not gen_text.endswith(". "):gen_text += ". "gen_text = gen_text.lower()gen_text = traducir_numero_a_texto(gen_text)final_wave, final_sample_rate, combined_spectrogram = infer_process(ref_audio,ref_text,gen_text,ema_model,vocoder,cross_fade_duration=cross_fade_duration,speed=speed,progress=gr.Progress(),)# Eliminar silencios si está activadoif remove_silence:with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f:sf.write(f.name, final_wave, final_sample_rate)remove_silence_for_generated_wav(f.name)final_wave, _ = torchaudio.load(f.name)final_wave = final_wave.squeeze().cpu().numpy()# Guardar el espectrograma (opcional)with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_spectrogram:spectrogram_path = tmp_spectrogram.namesave_spectrogram(combined_spectrogram, spectrogram_path)return (final_sample_rate, final_wave), spectrogram_pathexcept Exception as e:logger.error(f"Error en infer: {e}")return None, Nonedef transcribe_audio(audio_path):"""Transcribe el audio usando el modelo Whisper"""try:whisper_model = cargar_whisper()if not os.path.exists(audio_path):raise FileNotFoundError(f"Archivo de audio no encontrado: {audio_path}")# Cargar y preprocesar el audioaudio = whisper.load_audio(audio_path)audio = whisper.pad_or_trim(audio)# Hacer log-Mel espectrogrammel = whisper.log_mel_spectrogram(audio).to(whisper_model.device)# Detectar el idioma_, probs = whisper_model.detect_language(mel)logger.info(f"Idioma detectado: {max(probs, key=probs.get)}")# Decodificar la transcripciónoptions = whisper.DecodingOptions(fp16=False) # Ajusta según tu hardwaretranscription = whisper.decode(whisper_model, mel, options)return transcription.textexcept Exception as e:logger.error(f"Error en transcribe_audio: {e}")return "Error al transcribir el audio."with gr.Blocks() as app:gr.Markdown(8 unmodified lineswith gr.Tab("Texto a Voz"):with gr.Row():ref_audio = gr.Audio(label="Audio de Referencia (Opcional)", type="filepath")ref_text = gr.Textbox(label="Texto de Referencia (Opcional)",info="Deja en blanco si no tienes texto de referencia.",lines=2,)gen_text = gr.Textbox(13 unmodified linesstep=0.1,)generate_btn = gr.Button("Generar Audio")audio_output = gr.Audio(label="Audio Generado", type="filepath")spectrogram_output = gr.Image(label="Espectrograma Generado", visible=False)def generate_audio(ref_audio, ref_text, gen_text, remove_silence, speed):if not gen_text.strip():raise gr.Error("Por favor, ingresa el texto que deseas convertir a voz.")sample_rate_wave, audio_wave = infer(ref_audio,ref_text,gen_text,remove_silence,speed=speed)if audio_wave is None:raise gr.Error("Error al generar el audio.")audio_path = "generated_audio.wav"sf.write(audio_path, audio_wave, sample_rate_wave)return audio_path, None # Retornar el audio y ocultar el espectrogramagenerate_btn.click(
chat_ai.py+83-50