gnosticdev commited on
Commit
9774fb0
verified
1 Parent(s): 9387d2c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -47
app.py CHANGED
@@ -9,6 +9,8 @@ import gradio as gr
9
  import torch
10
  from transformers import GPT2Tokenizer, GPT2LMHeadModel
11
  from keybert import KeyBERT
 
 
12
  # Importaci贸n correcta: Solo 'concatenate_videoclips'
13
  from moviepy.editor import VideoFileClip, concatenate_videoclips, AudioFileClip, CompositeAudioClip, concatenate_audioclips, AudioClip
14
  import re
@@ -175,67 +177,54 @@ def generate_script(prompt, max_length=150):
175
  logger.warning("Usando prompt original como guion debido al error de generaci贸n.")
176
  return prompt.strip()
177
 
178
- # Funci贸n TTS con voz especificada
179
  async def text_to_speech(text, output_path, voice):
 
180
  logger.info(f"Convirtiendo texto a voz | Caracteres: {len(text)} | Voz: {voice} | Salida: {output_path}")
181
  if not text or not text.strip():
182
  logger.warning("Texto vac铆o para TTS")
183
  return False
184
 
185
- # Lista extendida de voces de respaldo
186
- backup_voices = [
187
- "es-ES-JuanNeural",
188
- "es-ES-ElviraNeural",
189
- "es-ES-AlvaroNeural",
190
- "es-MX-DaliaNeural",
191
- "es-AR-ElenaNeural"
192
- ]
193
-
194
- # Configuraci贸n de reintentos con espera exponencial
195
- max_retries = 5
196
- base_delay = 2 # segundos
197
-
198
- for attempt in range(max_retries):
199
- current_voice = backup_voices[attempt % len(backup_voices)]
200
 
201
- if attempt > 0:
202
- delay = base_delay * (2 ** (attempt - 1)) # Espera exponencial
203
- logger.warning(f"Esperando {delay} segundos antes del reintento {attempt + 1}/{max_retries} con voz {current_voice}")
204
- await asyncio.sleep(delay)
 
 
 
205
 
206
- try:
207
- # Crear el objeto Communicate con headers personalizados
208
- communicate = edge_tts.Communicate(text, current_voice)
209
-
210
- # Modificar los headers para incluir un User-Agent personalizado
211
- communicate._headers = {
212
- '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'
213
- }
214
 
 
 
 
 
 
 
 
215
  await communicate.save(output_path)
216
 
217
  if os.path.exists(output_path) and os.path.getsize(output_path) > 100:
218
- logger.info(f"Audio guardado exitosamente en: {output_path} | Tama帽o: {os.path.getsize(output_path)} bytes")
219
  return True
220
  else:
221
- logger.error(f"TTS guard贸 un archivo peque帽o o vac铆o en: {output_path}")
222
-
223
- except Exception as e:
224
- logger.error(f"Error en TTS con voz '{current_voice}': {str(e)}")
225
-
226
- # Manejo espec铆fico para error 403
227
- if "403" in str(e) or "Forbidden" in str(e):
228
- logger.error("Error 403 detectado - Posible bloqueo temporal")
229
- # Espera adicional para errores 403
230
- if attempt < max_retries - 1:
231
- await asyncio.sleep(base_delay * 3)
232
- elif "timeout" in str(e).lower():
233
- logger.error("Timeout detectado - Reintentando")
234
- elif "connection" in str(e).lower():
235
- logger.error("Error de conexi贸n detectado - Reintentando")
236
-
237
- logger.error("Todos los intentos de TTS fallaron")
238
- return False
239
 
240
  def download_video_file(url, temp_dir):
241
  if not url:
 
9
  import torch
10
  from transformers import GPT2Tokenizer, GPT2LMHeadModel
11
  from keybert import KeyBERT
12
+ from TTS.api import TTS
13
+
14
  # Importaci贸n correcta: Solo 'concatenate_videoclips'
15
  from moviepy.editor import VideoFileClip, concatenate_videoclips, AudioFileClip, CompositeAudioClip, concatenate_audioclips, AudioClip
16
  import re
 
177
  logger.warning("Usando prompt original como guion debido al error de generaci贸n.")
178
  return prompt.strip()
179
 
 
180
  async def text_to_speech(text, output_path, voice):
181
+ global tts_model
182
  logger.info(f"Convirtiendo texto a voz | Caracteres: {len(text)} | Voz: {voice} | Salida: {output_path}")
183
  if not text or not text.strip():
184
  logger.warning("Texto vac铆o para TTS")
185
  return False
186
 
187
+ try:
188
+ # Inicializar el modelo TTS si no est谩 cargado
189
+ if tts_model is None:
190
+ logger.info("Inicializando modelo Coqui TTS...")
191
+ tts_model = TTS(model_name="tts_models/es/mai/vits", progress_bar=False)
192
+ logger.info("Modelo Coqui TTS cargado exitosamente")
 
 
 
 
 
 
 
 
 
193
 
194
+ # Generar el audio
195
+ logger.info("Generando audio con Coqui TTS...")
196
+ tts_model.tts_to_file(
197
+ text=text,
198
+ speaker=tts_model.speakers[0] if tts_model.speakers else None,
199
+ file_path=output_path
200
+ )
201
 
202
+ # Verificar que el archivo se cre贸 correctamente
203
+ if os.path.exists(output_path) and os.path.getsize(output_path) > 100:
204
+ logger.info(f"Audio guardado exitosamente en: {output_path} | Tama帽o: {os.path.getsize(output_path)} bytes")
205
+ return True
206
+ else:
207
+ logger.error(f"TTS guard贸 un archivo peque帽o o vac铆o en: {output_path}")
208
+ return False
 
209
 
210
+ except Exception as e:
211
+ logger.error(f"Error en TTS con Coqui: {str(e)}", exc_info=True)
212
+
213
+ # Si falla Coqui TTS, intentar con Edge TTS como 煤ltimo recurso
214
+ logger.warning("Intentando con Edge TTS como respaldo...")
215
+ try:
216
+ communicate = edge_tts.Communicate(text, voice)
217
  await communicate.save(output_path)
218
 
219
  if os.path.exists(output_path) and os.path.getsize(output_path) > 100:
220
+ logger.info(f"Audio guardado exitosamente con Edge TTS: {output_path}")
221
  return True
222
  else:
223
+ logger.error(f"Edge TTS guard贸 un archivo peque帽o o vac铆o: {output_path}")
224
+ return False
225
+ except Exception as e2:
226
+ logger.error(f"Error en TTS con Edge TTS: {str(e2)}")
227
+ return False
 
 
 
 
 
 
 
 
 
 
 
 
 
228
 
229
  def download_video_file(url, temp_dir):
230
  if not url: