Spaces:
Runtime error
Runtime error
Update app.py
Browse files8 unmodified lines91011121314160 unmodified lines1751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402418 unmodified linesimport torchfrom transformers import GPT2Tokenizer, GPT2LMHeadModelfrom keybert import KeyBERT# Importaci贸n correcta: Solo 'concatenate_videoclips'from moviepy.editor import VideoFileClip, concatenate_videoclips, AudioFileClip, CompositeAudioClip, concatenate_audioclips, AudioClipimport re160 unmodified lineslogger.warning("Usando prompt original como guion debido al error de generaci贸n.")return prompt.strip()# Funci贸n TTS con voz especificadaasync def text_to_speech(text, output_path, voice):logger.info(f"Convirtiendo texto a voz | Caracteres: {len(text)} | Voz: {voice} | Salida: {output_path}")if not text or not text.strip():logger.warning("Texto vac铆o para TTS")return False# Lista extendida de voces de respaldobackup_voices = ["es-ES-JuanNeural","es-ES-ElviraNeural","es-ES-AlvaroNeural","es-MX-DaliaNeural","es-AR-ElenaNeural"]# Configuraci贸n de reintentos con espera exponencialmax_retries = 5base_delay = 2 # segundosfor attempt in range(max_retries):current_voice = backup_voices[attempt % len(backup_voices)]if attempt > 0:delay = base_delay * (2 ** (attempt - 1)) # Espera exponenciallogger.warning(f"Esperando {delay} segundos antes del reintento {attempt + 1}/{max_retries} con voz {current_voice}")await asyncio.sleep(delay)try:# Crear el objeto Communicate con headers personalizadoscommunicate = edge_tts.Communicate(text, current_voice)# Modificar los headers para incluir un User-Agent personalizadocommunicate._headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, como Gecko) Chrome/91.0.4472.124 Safari/537.36'}await communicate.save(output_path)if os.path.exists(output_path) and os.path.getsize(output_path) > 100:logger.info(f"Audio guardado exitosamente en: {output_path} | Tama帽o: {os.path.getsize(output_path)} bytes")return Trueelse:logger.error(f"TTS guard贸 un archivo peque帽o o vac铆o en: {output_path}")except Exception as e:logger.error(f"Error en TTS con voz '{current_voice}': {str(e)}")# Manejo espec铆fico para error 403if "403" in str(e) or "Forbidden" in str(e):logger.error("Error 403 detectado - Posible bloqueo temporal")# Espera adicional para errores 403if attempt < max_retries - 1:await asyncio.sleep(base_delay * 3)elif "timeout" in str(e).lower():logger.error("Timeout detectado - Reintentando")elif "connection" in str(e).lower():logger.error("Error de conexi贸n detectado - Reintentando")logger.error("Todos los intentos de TTS fallaron")return Falsedef download_video_file(url, temp_dir):if not url:8 unmodified lines910111213141516160 unmodified lines1771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292308 unmodified linesimport torchfrom transformers import GPT2Tokenizer, GPT2LMHeadModelfrom keybert import KeyBERTfrom TTS.api import TTS# Importaci贸n correcta: Solo 'concatenate_videoclips'from moviepy.editor import VideoFileClip, concatenate_videoclips, AudioFileClip, CompositeAudioClip, concatenate_audioclips, AudioClipimport re160 unmodified lineslogger.warning("Usando prompt original como guion debido al error de generaci贸n.")return prompt.strip()async def text_to_speech(text, output_path, voice):global tts_modellogger.info(f"Convirtiendo texto a voz | Caracteres: {len(text)} | Voz: {voice} | Salida: {output_path}")if not text or not text.strip():logger.warning("Texto vac铆o para TTS")return Falsetry:# Inicializar el modelo TTS si no est谩 cargadoif tts_model is None:logger.info("Inicializando modelo Coqui TTS...")tts_model = TTS(model_name="tts_models/es/mai/vits", progress_bar=False)logger.info("Modelo Coqui TTS cargado exitosamente")# Generar el audiologger.info("Generando audio con Coqui TTS...")tts_model.tts_to_file(text=text,speaker=tts_model.speakers[0] if tts_model.speakers else None,file_path=output_path)# Verificar que el archivo se cre贸 correctamenteif os.path.exists(output_path) and os.path.getsize(output_path) > 100:logger.info(f"Audio guardado exitosamente en: {output_path} | Tama帽o: {os.path.getsize(output_path)} bytes")return Trueelse:logger.error(f"TTS guard贸 un archivo peque帽o o vac铆o en: {output_path}")return Falseexcept Exception as e:logger.error(f"Error en TTS con Coqui: {str(e)}", exc_info=True)# Si falla Coqui TTS, intentar con Edge TTS como 煤ltimo recursologger.warning("Intentando con Edge TTS como respaldo...")try:communicate = edge_tts.Communicate(text, voice)await communicate.save(output_path)if os.path.exists(output_path) and os.path.getsize(output_path) > 100:logger.info(f"Audio guardado exitosamente con Edge TTS: {output_path}")return Trueelse:logger.error(f"Edge TTS guard贸 un archivo peque帽o o vac铆o: {output_path}")return Falseexcept Exception as e2:logger.error(f"Error en TTS con Edge TTS: {str(e2)}")return Falsedef download_video_file(url, temp_dir):if not url:
app.py+36-47