Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,1165 +1,603 @@
|
|
1 |
-
import os
|
2 |
-
import asyncio
|
3 |
-
import logging
|
4 |
-
import tempfile
|
5 |
-
import requests
|
6 |
-
from datetime import datetime
|
7 |
-
import edge_tts
|
8 |
import gradio as gr
|
9 |
import torch
|
|
|
|
|
|
|
10 |
from transformers import GPT2Tokenizer, GPT2LMHeadModel
|
11 |
from keybert import KeyBERT
|
12 |
-
|
13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
import re
|
15 |
import math
|
|
|
16 |
import shutil
|
17 |
-
import
|
18 |
-
|
|
|
|
|
19 |
|
20 |
-
#
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
|
|
|
|
29 |
logger = logging.getLogger(__name__)
|
30 |
-
|
31 |
-
logger.info("INICIO DE EJECUCIÓN - GENERADOR DE VIDEOS")
|
32 |
-
logger.info("="*80)
|
33 |
-
|
34 |
-
# Diccionario de voces TTS disponibles organizadas por idioma
|
35 |
-
# Puedes expandir esta lista si conoces otros IDs de voz de Edge TTS
|
36 |
-
VOCES_DISPONIBLES = {
|
37 |
-
"Español (España)": {
|
38 |
-
"es-ES-JuanNeural": "Juan (España) - Masculino",
|
39 |
-
"es-ES-ElviraNeural": "Elvira (España) - Femenino",
|
40 |
-
"es-ES-AlvaroNeural": "Álvaro (España) - Masculino",
|
41 |
-
"es-ES-AbrilNeural": "Abril (España) - Femenino",
|
42 |
-
"es-ES-ArnauNeural": "Arnau (España) - Masculino",
|
43 |
-
"es-ES-DarioNeural": "Darío (España) - Masculino",
|
44 |
-
"es-ES-EliasNeural": "Elías (España) - Masculino",
|
45 |
-
"es-ES-EstrellaNeural": "Estrella (España) - Femenino",
|
46 |
-
"es-ES-IreneNeural": "Irene (España) - Femenino",
|
47 |
-
"es-ES-LaiaNeural": "Laia (España) - Femenino",
|
48 |
-
"es-ES-LiaNeural": "Lía (España) - Femenino",
|
49 |
-
"es-ES-NilNeural": "Nil (España) - Masculino",
|
50 |
-
"es-ES-SaulNeural": "Saúl (España) - Masculino",
|
51 |
-
"es-ES-TeoNeural": "Teo (España) - Masculino",
|
52 |
-
"es-ES-TrianaNeural": "Triana (España) - Femenino",
|
53 |
-
"es-ES-VeraNeural": "Vera (España) - Femenino"
|
54 |
-
},
|
55 |
-
"Español (México)": {
|
56 |
-
"es-MX-JorgeNeural": "Jorge (México) - Masculino",
|
57 |
-
"es-MX-DaliaNeural": "Dalia (México) - Femenino",
|
58 |
-
"es-MX-BeatrizNeural": "Beatriz (México) - Femenino",
|
59 |
-
"es-MX-CandelaNeural": "Candela (México) - Femenino",
|
60 |
-
"es-MX-CarlotaNeural": "Carlota (México) - Femenino",
|
61 |
-
"es-MX-CecilioNeural": "Cecilio (México) - Masculino",
|
62 |
-
"es-MX-GerardoNeural": "Gerardo (México) - Masculino",
|
63 |
-
"es-MX-LarissaNeural": "Larissa (México) - Femenino",
|
64 |
-
"es-MX-LibertoNeural": "Liberto (México) - Masculino",
|
65 |
-
"es-MX-LucianoNeural": "Luciano (México) - Masculino",
|
66 |
-
"es-MX-MarinaNeural": "Marina (México) - Femenino",
|
67 |
-
"es-MX-NuriaNeural": "Nuria (México) - Femenino",
|
68 |
-
"es-MX-PelayoNeural": "Pelayo (México) - Masculino",
|
69 |
-
"es-MX-RenataNeural": "Renata (México) - Femenino",
|
70 |
-
"es-MX-YagoNeural": "Yago (México) - Masculino"
|
71 |
-
},
|
72 |
-
"Español (Argentina)": {
|
73 |
-
"es-AR-TomasNeural": "Tomás (Argentina) - Masculino",
|
74 |
-
"es-AR-ElenaNeural": "Elena (Argentina) - Femenino"
|
75 |
-
},
|
76 |
-
"Español (Colombia)": {
|
77 |
-
"es-CO-GonzaloNeural": "Gonzalo (Colombia) - Masculino",
|
78 |
-
"es-CO-SalomeNeural": "Salomé (Colombia) - Femenino"
|
79 |
-
},
|
80 |
-
"Español (Chile)": {
|
81 |
-
"es-CL-LorenzoNeural": "Lorenzo (Chile) - Masculino",
|
82 |
-
"es-CL-CatalinaNeural": "Catalina (Chile) - Femenino"
|
83 |
-
},
|
84 |
-
"Español (Perú)": {
|
85 |
-
"es-PE-AlexNeural": "Alex (Perú) - Masculino",
|
86 |
-
"es-PE-CamilaNeural": "Camila (Perú) - Femenino"
|
87 |
-
},
|
88 |
-
"Español (Venezuela)": {
|
89 |
-
"es-VE-PaolaNeural": "Paola (Venezuela) - Femenino",
|
90 |
-
"es-VE-SebastianNeural": "Sebastián (Venezuela) - Masculino"
|
91 |
-
},
|
92 |
-
"Español (Estados Unidos)": {
|
93 |
-
"es-US-AlonsoNeural": "Alonso (Estados Unidos) - Masculino",
|
94 |
-
"es-US-PalomaNeural": "Paloma (Estados Unidos) - Femenino"
|
95 |
-
}
|
96 |
-
}
|
97 |
-
|
98 |
-
# Función para obtener lista plana de voces para el dropdown
|
99 |
-
def get_voice_choices():
|
100 |
-
choices = []
|
101 |
-
for region, voices in VOCES_DISPONIBLES.items():
|
102 |
-
for voice_id, voice_name in voices.items():
|
103 |
-
# Formato: (Texto a mostrar en el dropdown, Valor que se pasa)
|
104 |
-
choices.append((f"{voice_name} ({region})", voice_id))
|
105 |
-
return choices
|
106 |
-
|
107 |
-
# Obtener las voces al inicio del script
|
108 |
-
# Usamos la lista predefinida por ahora para evitar el error de inicio con la API
|
109 |
-
# Si deseas obtenerlas dinámicamente, descomenta la siguiente línea y comenta la que usa get_voice_choices()
|
110 |
-
# AVAILABLE_VOICES = asyncio.run(get_available_voices())
|
111 |
-
AVAILABLE_VOICES = get_voice_choices() # <-- Usamos la lista predefinida y aplanada
|
112 |
-
# Establecer una voz por defecto inicial
|
113 |
-
DEFAULT_VOICE_ID = "es-ES-JuanNeural" # ID de Juan
|
114 |
-
|
115 |
-
# Buscar el nombre amigable para la voz por defecto si existe
|
116 |
-
DEFAULT_VOICE_NAME = DEFAULT_VOICE_ID
|
117 |
-
for text, voice_id in AVAILABLE_VOICES:
|
118 |
-
if voice_id == DEFAULT_VOICE_ID:
|
119 |
-
DEFAULT_VOICE_NAME = text
|
120 |
-
break
|
121 |
-
# Si Juan no está en la lista (ej. lista de fallback), usar la primera voz disponible
|
122 |
-
if DEFAULT_VOICE_ID not in [v[1] for v in AVAILABLE_VOICES]:
|
123 |
-
DEFAULT_VOICE_ID = AVAILABLE_VOICES[0][1] if AVAILABLE_VOICES else "en-US-AriaNeural"
|
124 |
-
DEFAULT_VOICE_NAME = AVAILABLE_VOICES[0][0] if AVAILABLE_VOICES else "Aria (United States) - Female" # Fallback name
|
125 |
-
|
126 |
-
logger.info(f"Voz por defecto seleccionada (ID): {DEFAULT_VOICE_ID}")
|
127 |
-
|
128 |
-
|
129 |
-
# Clave API de Pexels
|
130 |
-
PEXELS_API_KEY = os.environ.get("PEXELS_API_KEY")
|
131 |
if not PEXELS_API_KEY:
|
132 |
-
logger.
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
if not api_key:
|
161 |
-
logger.warning("No se puede buscar en Pexels: API Key no configurada.")
|
162 |
-
return []
|
163 |
-
|
164 |
-
logger.debug(f"Buscando en Pexels: '{query}' | Resultados: {per_page}")
|
165 |
-
headers = {"Authorization": api_key}
|
166 |
-
try:
|
167 |
-
params = {
|
168 |
-
"query": query,
|
169 |
-
"per_page": per_page,
|
170 |
-
"orientation": "landscape",
|
171 |
-
"size": "medium"
|
172 |
-
}
|
173 |
-
|
174 |
-
response = requests.get(
|
175 |
-
"https://api.pexels.com/videos/search",
|
176 |
-
headers=headers,
|
177 |
-
params=params,
|
178 |
-
timeout=20
|
179 |
-
)
|
180 |
-
response.raise_for_status()
|
181 |
-
|
182 |
-
data = response.json()
|
183 |
-
videos = data.get('videos', [])
|
184 |
-
logger.info(f"Pexels: {len(videos)} videos encontrados para '{query}'")
|
185 |
-
return videos
|
186 |
-
|
187 |
-
except requests.exceptions.RequestException as e:
|
188 |
-
logger.error(f"Error de conexión Pexels para '{query}': {str(e)}")
|
189 |
-
except json.JSONDecodeError:
|
190 |
-
logger.error(f"Pexels: JSON inválido recibido | Status: {response.status_code} | Respuesta: {response.text[:200]}...")
|
191 |
-
except Exception as e:
|
192 |
-
logger.error(f"Error inesperado Pexels para '{query}': {str(e)}", exc_info=True)
|
193 |
-
|
194 |
-
return []
|
195 |
-
|
196 |
-
def generate_script(prompt, max_length=150):
|
197 |
-
logger.info(f"Generando guión | Prompt: '{prompt[:50]}...' | Longitud máxima: {max_length}")
|
198 |
-
if not tokenizer or not model:
|
199 |
-
logger.warning("Modelos GPT-2 no disponibles - Usando prompt original como guion.")
|
200 |
-
return prompt.strip()
|
201 |
-
|
202 |
-
instruction_phrase_start = "Escribe un guion corto, interesante y coherente sobre:"
|
203 |
-
ai_prompt = f"{instruction_phrase_start} {prompt}"
|
204 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
205 |
try:
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
|
|
212 |
**inputs,
|
213 |
-
max_length=
|
214 |
do_sample=True,
|
215 |
top_p=0.9,
|
216 |
top_k=40,
|
217 |
temperature=0.7,
|
218 |
-
|
219 |
-
pad_token_id=
|
220 |
-
eos_token_id=
|
221 |
-
no_repeat_ngram_size=3
|
222 |
)
|
223 |
-
|
224 |
-
text =
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
try:
|
229 |
-
# Buscar el índice de inicio del prompt original dentro del texto generado
|
230 |
-
prompt_in_output_idx = text.lower().find(prompt.lower())
|
231 |
-
if prompt_in_output_idx != -1:
|
232 |
-
# Tomar todo el texto DESPUÉS del prompt original
|
233 |
-
cleaned_text = text[prompt_in_output_idx + len(prompt):].strip()
|
234 |
-
logger.debug("Texto limpiado tomando parte después del prompt original.")
|
235 |
-
else:
|
236 |
-
# Fallback si el prompt original no está exacto en la salida: buscar la frase de instrucción base
|
237 |
-
instruction_start_idx = text.find(instruction_phrase_start)
|
238 |
-
if instruction_start_idx != -1:
|
239 |
-
# Tomar texto después de la frase base (puede incluir el prompt)
|
240 |
-
cleaned_text = text[instruction_start_idx + len(instruction_phrase_start):].strip()
|
241 |
-
logger.debug("Texto limpiado tomando parte después de la frase de instrucción base.")
|
242 |
-
else:
|
243 |
-
# Si ni la frase de instrucción ni el prompt se encuentran, usar el texto original
|
244 |
-
logger.warning("No se pudo identificar el inicio del guión generado. Usando texto generado completo.")
|
245 |
-
cleaned_text = text.strip() # Limpieza básica
|
246 |
-
|
247 |
-
|
248 |
-
except Exception as e:
|
249 |
-
logger.warning(f"Error durante la limpieza heurística del guión de IA: {e}. Usando texto generado sin limpieza adicional.")
|
250 |
-
cleaned_text = re.sub(r'<[^>]+>', '', text).strip() # Limpieza básica como fallback
|
251 |
-
|
252 |
-
# Asegurarse de que el texto resultante no sea solo la instrucción o vacío
|
253 |
-
if not cleaned_text or len(cleaned_text) < 10: # Umbral de longitud mínima
|
254 |
-
logger.warning("El guión generado parece muy corto o vacío después de la limpieza heurística. Usando el texto generado original (sin limpieza adicional).")
|
255 |
-
cleaned_text = re.sub(r'<[^>]+>', '', text).strip() # Fallback al texto original limpio
|
256 |
-
|
257 |
-
# Limpieza final de caracteres especiales y espacios sobrantes
|
258 |
-
cleaned_text = re.sub(r'<[^>]+>', '', cleaned_text).strip()
|
259 |
-
cleaned_text = cleaned_text.lstrip(':').strip() # Quitar posibles ':' al inicio
|
260 |
-
cleaned_text = cleaned_text.lstrip('.').strip() # Quitar posibles '.' al inicio
|
261 |
-
|
262 |
-
|
263 |
-
# Intentar obtener al menos una oración completa si es posible para un inicio más limpio
|
264 |
-
sentences = cleaned_text.split('.')
|
265 |
-
if sentences and sentences[0].strip():
|
266 |
-
final_text = sentences[0].strip() + '.'
|
267 |
-
# Añadir la segunda oración si existe y es razonable
|
268 |
-
if len(sentences) > 1 and sentences[1].strip() and len(final_text.split()) < max_length * 0.7: # Usar un 70% de max_length como umbral
|
269 |
-
final_text += " " + sentences[1].strip() + "."
|
270 |
-
final_text = final_text.replace("..", ".") # Limpiar doble punto
|
271 |
-
|
272 |
-
logger.info(f"Guion generado final (Truncado a 100 chars): '{final_text[:100]}...'")
|
273 |
-
return final_text.strip()
|
274 |
-
|
275 |
-
logger.info(f"Guion generado final (sin oraciones completas detectadas - Truncado): '{cleaned_text[:100]}...'")
|
276 |
-
return cleaned_text.strip() # Si no se puede formar una oración, devolver el texto limpio tal cual
|
277 |
-
|
278 |
except Exception as e:
|
279 |
-
logger.error(f"Error generando
|
280 |
-
|
281 |
-
return prompt.strip()
|
282 |
-
|
283 |
-
# Función TTS ahora recibe la voz a usar
|
284 |
-
async def text_to_speech(text, output_path, voice):
|
285 |
-
logger.info(f"Convirtiendo texto a voz | Caracteres: {len(text)} | Voz: {voice} | Salida: {output_path}")
|
286 |
-
if not text or not text.strip():
|
287 |
-
logger.warning("Texto vacío para TTS")
|
288 |
-
return False
|
289 |
|
|
|
290 |
try:
|
291 |
-
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
logger.info(f"Audio guardado exitosamente en: {output_path} | Tamaño: {os.path.getsize(output_path)} bytes")
|
296 |
return True
|
297 |
else:
|
298 |
-
logger.error(
|
299 |
return False
|
300 |
-
|
301 |
except Exception as e:
|
302 |
-
logger.error(f"Error
|
303 |
return False
|
304 |
|
305 |
-
def
|
306 |
-
|
307 |
-
|
308 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
309 |
|
|
|
|
|
|
|
|
|
310 |
try:
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
315 |
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
|
|
|
|
|
|
|
|
|
|
320 |
f.write(chunk)
|
321 |
-
|
322 |
-
if os.path.exists(
|
323 |
-
|
324 |
-
return output_path
|
325 |
else:
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
return None
|
330 |
-
|
331 |
-
except requests.exceptions.RequestException as e:
|
332 |
-
logger.error(f"Error de descarga para {url[:80]}... : {str(e)}")
|
333 |
except Exception as e:
|
334 |
-
logger.error(f"Error
|
335 |
-
|
336 |
-
return None
|
337 |
-
|
338 |
-
def loop_audio_to_length(audio_clip, target_duration):
|
339 |
-
logger.debug(f"Ajustando audio | Duración actual: {audio_clip.duration:.2f}s | Objetivo: {target_duration:.2f}s")
|
340 |
-
|
341 |
-
if audio_clip is None or audio_clip.duration is None or audio_clip.duration <= 0:
|
342 |
-
logger.warning("Input audio clip is invalid (None or zero duration), cannot loop.")
|
343 |
-
try:
|
344 |
-
sr = getattr(audio_clip, 'fps', 44100) if audio_clip else 44100
|
345 |
-
return AudioClip(lambda t: 0, duration=target_duration, sr=sr)
|
346 |
-
except Exception as e:
|
347 |
-
logger.error(f"Could not create silence clip: {e}", exc_info=True)
|
348 |
-
return AudioFileClip(filename="")
|
349 |
-
|
350 |
-
if audio_clip.duration >= target_duration:
|
351 |
-
logger.debug("Audio clip already longer or equal to target. Trimming.")
|
352 |
-
trimmed_clip = audio_clip.subclip(0, target_duration)
|
353 |
-
if trimmed_clip.duration is None or trimmed_clip.duration <= 0:
|
354 |
-
logger.error("Trimmed audio clip is invalid.")
|
355 |
-
try: trimmed_clip.close()
|
356 |
-
except: pass
|
357 |
-
return AudioFileClip(filename="")
|
358 |
-
return trimmed_clip
|
359 |
-
|
360 |
-
loops = math.ceil(target_duration / audio_clip.duration)
|
361 |
-
logger.debug(f"Creando {loops} loops de audio")
|
362 |
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
try:
|
367 |
-
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
final_looped_audio = looped_audio.subclip(0, target_duration)
|
374 |
-
|
375 |
-
if final_looped_audio.duration is None or final_looped_audio.duration <= 0:
|
376 |
-
logger.error("Final subclipped audio clip is invalid (None or zero duration).")
|
377 |
-
raise ValueError("Invalid final subclipped audio.")
|
378 |
-
|
379 |
-
return final_looped_audio
|
380 |
-
|
381 |
except Exception as e:
|
382 |
-
logger.error(f"Error
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
try: looped_audio.close()
|
395 |
-
except: pass
|
396 |
-
|
397 |
-
|
398 |
-
def extract_visual_keywords_from_script(script_text):
|
399 |
-
logger.info("Extrayendo palabras clave del guion")
|
400 |
-
if not script_text or not script_text.strip():
|
401 |
-
logger.warning("Guion vacío, no se pueden extraer palabras clave.")
|
402 |
-
return ["naturaleza", "ciudad", "paisaje"]
|
403 |
-
|
404 |
-
clean_text = re.sub(r'[^\w\sáéíóúñÁÉÍÓÚÑ]', '', script_text)
|
405 |
-
keywords_list = []
|
406 |
-
|
407 |
-
if kw_model:
|
408 |
try:
|
409 |
-
|
410 |
-
|
411 |
-
|
412 |
-
|
413 |
-
|
414 |
-
all_keywords.sort(key=lambda item: item[1], reverse=True)
|
415 |
-
|
416 |
-
seen_keywords = set()
|
417 |
-
for keyword, score in all_keywords:
|
418 |
-
formatted_keyword = keyword.lower().replace(" ", "+")
|
419 |
-
if formatted_keyword and formatted_keyword not in seen_keywords:
|
420 |
-
keywords_list.append(formatted_keyword)
|
421 |
-
seen_keywords.add(formatted_keyword)
|
422 |
-
if len(keywords_list) >= 5:
|
423 |
-
break
|
424 |
-
|
425 |
-
if keywords_list:
|
426 |
-
logger.debug(f"Palabras clave extraídas por KeyBERT: {keywords_list}")
|
427 |
-
return keywords_list
|
428 |
-
|
429 |
except Exception as e:
|
430 |
-
logger.
|
431 |
-
|
432 |
-
|
433 |
-
words = clean_text.lower().split()
|
434 |
-
stop_words = {"el", "la", "los", "las", "de", "en", "y", "a", "que", "es", "un", "una", "con", "para", "del", "al", "por", "su", "sus", "se", "lo", "le", "me", "te", "nos", "os", "les", "mi", "tu",
|
435 |
-
"nuestro", "vuestro", "este", "ese", "aquel", "esta", "esa", "aquella", "esto", "eso", "aquello", "mis", "tus",
|
436 |
-
"nuestros", "vuestros", "estas", "esas", "aquellas", "si", "no", "más", "menos", "sin", "sobre", "bajo", "entre", "hasta", "desde", "durante", "mediante", "según", "versus", "via", "cada", "todo", "todos", "toda", "todas", "poco", "pocos", "poca", "pocas", "mucho", "muchos", "mucha", "muchas", "varios", "varias", "otro", "otros", "otra", "otras", "mismo", "misma", "mismos", "mismas", "tan", "tanto", "tanta", "tantos", "tantas", "tal", "tales", "cual", "cuales", "cuyo", "cuya", "cuyos", "cuyas", "quien", "quienes", "cuan", "cuanto", "cuanta", "cuantos", "cuantas", "como", "donde", "cuando", "porque", "aunque", "mientras", "siempre", "nunca", "jamás", "muy", "casi", "solo", "solamente", "incluso", "apenas", "quizás", "tal vez", "acaso", "claro", "cierto", "obvio", "evidentemente", "realmente", "simplemente", "generalmente", "especialmente", "principalmente", "posiblemente", "probablemente", "difícilmente", "fácilmente", "rápidamente", "lentamente", "bien", "mal", "mejor", "peor", "arriba", "abajo", "adelante", "atrás", "cerca", "lejos", "dentro", "fuera", "encima", "debajo", "frente", "detrás", "antes", "después", "luego", "pronto", "tarde", "todavía", "ya", "aun", "aún", "quizá"}
|
437 |
-
|
438 |
-
valid_words = [word for word in words if len(word) > 3 and word not in stop_words]
|
439 |
-
|
440 |
-
if not valid_words:
|
441 |
-
logger.warning("No se encontraron palabras clave válidas con método simple. Usando palabras clave predeterminadas.")
|
442 |
-
return ["naturaleza", "ciudad", "paisaje"]
|
443 |
-
|
444 |
-
word_counts = Counter(valid_words)
|
445 |
-
top_keywords = [word.replace(" ", "+") for word, _ in word_counts.most_common(5)]
|
446 |
-
|
447 |
-
if not top_keywords:
|
448 |
-
logger.warning("El método simple no produjo keywords. Usando palabras clave predeterminadas.")
|
449 |
-
return ["naturaleza", "ciudad", "paisaje"]
|
450 |
-
|
451 |
-
logger.info(f"Palabras clave finales: {top_keywords}")
|
452 |
-
return top_keywords
|
453 |
-
|
454 |
-
# crear_video ahora recibe la voz seleccionada
|
455 |
-
def crear_video(prompt_type, input_text, selected_voice, musica_file=None):
|
456 |
-
logger.info("="*80)
|
457 |
-
logger.info(f"INICIANDO CREACIÓN DE VIDEO | Tipo: {prompt_type}")
|
458 |
-
logger.debug(f"Input: '{input_text[:100]}...'")
|
459 |
-
logger.info(f"Voz seleccionada: {selected_voice}")
|
460 |
-
|
461 |
-
start_time = datetime.now()
|
462 |
-
temp_dir_intermediate = None
|
463 |
-
|
464 |
-
audio_tts_original = None
|
465 |
-
musica_audio_original = None
|
466 |
-
audio_tts = None
|
467 |
-
musica_audio = None
|
468 |
-
video_base = None
|
469 |
-
video_final = None
|
470 |
-
source_clips = []
|
471 |
-
clips_to_concatenate = []
|
472 |
-
|
473 |
try:
|
474 |
-
# 1
|
475 |
-
|
476 |
-
|
|
|
477 |
else:
|
478 |
-
|
479 |
-
|
480 |
-
|
481 |
-
|
482 |
-
|
483 |
-
|
484 |
-
|
485 |
-
|
486 |
-
|
487 |
-
|
488 |
-
|
489 |
-
|
490 |
-
|
491 |
-
|
492 |
-
|
493 |
-
|
494 |
-
|
495 |
-
|
496 |
-
|
497 |
-
|
498 |
-
|
499 |
-
|
500 |
-
|
501 |
-
tts_voices_to_try.append(fallback_elvira)
|
502 |
-
|
503 |
-
tts_success = False
|
504 |
-
tried_voices = set()
|
505 |
-
|
506 |
-
for current_voice in tts_voices_to_try:
|
507 |
-
if not current_voice or current_voice in tried_voices: continue
|
508 |
-
tried_voices.add(current_voice)
|
509 |
-
|
510 |
-
logger.info(f"Intentando TTS con voz: {current_voice}...")
|
511 |
-
try:
|
512 |
-
tts_success = asyncio.run(text_to_speech(guion, voz_path, voice=current_voice))
|
513 |
-
if tts_success:
|
514 |
-
logger.info(f"TTS exitoso con voz '{current_voice}'.")
|
515 |
-
break
|
516 |
-
except Exception as e:
|
517 |
-
logger.warning(f"Fallo al generar TTS con voz '{current_voice}': {str(e)}", exc_info=True)
|
518 |
-
pass
|
519 |
-
|
520 |
-
if not tts_success or not os.path.exists(voz_path) or os.path.getsize(voz_path) <= 100:
|
521 |
-
logger.error("Fallo en la generación de voz después de todos los intentos. Archivo de audio no creado o es muy pequeño.")
|
522 |
-
raise ValueError("Error generando voz a partir del guion (fallo de TTS).")
|
523 |
-
|
524 |
-
temp_intermediate_files.append(voz_path)
|
525 |
-
|
526 |
-
audio_tts_original = AudioFileClip(voz_path)
|
527 |
-
|
528 |
-
if audio_tts_original.reader is None or audio_tts_original.duration is None or audio_tts_original.duration <= 0:
|
529 |
-
logger.critical("Clip de audio TTS inicial es inválido (reader is None o duración <= 0) *después* de crear AudioFileClip.")
|
530 |
-
try: audio_tts_original.close()
|
531 |
-
except: pass
|
532 |
-
audio_tts_original = None
|
533 |
-
if os.path.exists(voz_path):
|
534 |
-
try: os.remove(voz_path)
|
535 |
-
except: pass
|
536 |
-
if voz_path in temp_intermediate_files:
|
537 |
-
temp_intermediate_files.remove(voz_path)
|
538 |
-
|
539 |
-
raise ValueError("Audio de voz generado es inválido después de procesamiento inicial.")
|
540 |
-
|
541 |
-
audio_tts = audio_tts_original
|
542 |
-
audio_duration = audio_tts_original.duration
|
543 |
-
logger.info(f"Duración audio voz: {audio_duration:.2f} segundos")
|
544 |
-
|
545 |
-
if audio_duration < 1.0:
|
546 |
-
logger.error(f"Duración audio voz ({audio_duration:.2f}s) es muy corta.")
|
547 |
-
raise ValueError("Generated voice audio is too short (min 1 second required).")
|
548 |
-
# 3. Extraer palabras clave
|
549 |
-
logger.info("Extrayendo palabras clave...")
|
550 |
-
try:
|
551 |
-
keywords = extract_visual_keywords_from_script(guion)
|
552 |
-
logger.info(f"Palabras clave identificadas: {keywords}")
|
553 |
-
except Exception as e:
|
554 |
-
logger.error(f"Error extrayendo keywords: {str(e)}", exc_info=True)
|
555 |
-
keywords = ["naturaleza", "paisaje"]
|
556 |
-
|
557 |
-
if not keywords:
|
558 |
-
keywords = ["video", "background"]
|
559 |
-
|
560 |
-
# 4. Buscar y descargar videos
|
561 |
-
logger.info("Buscando videos en Pexels...")
|
562 |
-
videos_data = []
|
563 |
-
total_desired_videos = 10
|
564 |
-
per_page_per_keyword = max(1, total_desired_videos // len(keywords))
|
565 |
-
|
566 |
-
for keyword in keywords:
|
567 |
-
if len(videos_data) >= total_desired_videos: break
|
568 |
-
try:
|
569 |
-
videos = buscar_videos_pexels(keyword, PEXELS_API_KEY, per_page=per_page_per_keyword)
|
570 |
-
if videos:
|
571 |
-
videos_data.extend(videos)
|
572 |
-
logger.info(f"Encontrados {len(videos)} videos para '{keyword}'. Total data: {len(videos_data)}")
|
573 |
-
except Exception as e:
|
574 |
-
logger.warning(f"Error buscando videos para '{keyword}': {str(e)}")
|
575 |
-
|
576 |
-
if len(videos_data) < total_desired_videos / 2:
|
577 |
-
logger.warning(f"Pocos videos encontrados ({len(videos_data)}). Intentando con palabras clave genéricas.")
|
578 |
-
generic_keywords = ["nature", "city", "background", "abstract"]
|
579 |
-
for keyword in generic_keywords:
|
580 |
-
if len(videos_data) >= total_desired_videos: break
|
581 |
-
try:
|
582 |
-
videos = buscar_videos_pexels(keyword, PEXELS_API_KEY, per_page=2)
|
583 |
-
if videos:
|
584 |
-
videos_data.extend(videos)
|
585 |
-
logger.info(f"Encontrados {len(videos)} videos para '{keyword}' (genérico). Total data: {len(videos_data)}")
|
586 |
-
except Exception as e:
|
587 |
-
logger.warning(f"Error buscando videos genéricos para '{keyword}': {str(e)}")
|
588 |
-
|
589 |
-
if not videos_data:
|
590 |
-
logger.error("No se encontraron videos en Pexels para ninguna palabra clave.")
|
591 |
-
raise ValueError("No se encontraron videos adecuados en Pexels.")
|
592 |
-
|
593 |
video_paths = []
|
594 |
-
|
595 |
-
|
596 |
-
|
597 |
-
|
598 |
-
|
599 |
-
|
600 |
-
|
601 |
-
|
602 |
-
|
603 |
-
|
604 |
-
|
605 |
-
|
606 |
-
|
607 |
-
if
|
608 |
-
|
609 |
-
|
610 |
-
|
611 |
-
|
612 |
-
|
613 |
-
|
614 |
-
|
615 |
-
|
616 |
-
|
617 |
-
|
618 |
-
|
619 |
-
|
620 |
-
|
621 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
622 |
if not video_paths:
|
623 |
-
|
624 |
-
|
625 |
-
|
626 |
-
|
627 |
-
|
628 |
-
|
629 |
-
|
630 |
-
|
631 |
-
|
632 |
-
for i, path in enumerate(video_paths):
|
633 |
-
if current_duration >= audio_duration + max_clip_segment:
|
634 |
-
logger.debug(f"Video base suficiente ({current_duration:.1f}s >= {audio_duration:.1f}s + {max_clip_segment:.1f}s buffer). Dejando de procesar clips fuente restantes.")
|
635 |
break
|
636 |
-
|
637 |
clip = None
|
638 |
try:
|
639 |
-
|
640 |
clip = VideoFileClip(path)
|
641 |
-
|
642 |
-
|
643 |
-
if clip.reader is None or clip.duration is None or clip.duration <= 0:
|
644 |
-
logger.warning(f"[{i+1}/{len(video_paths)}] Clip fuente {path} parece inválido (reader is None o duración <= 0). Saltando.")
|
645 |
continue
|
646 |
-
|
647 |
-
|
648 |
-
potential_use_duration = min(clip.duration, max_clip_segment)
|
649 |
-
|
650 |
-
if remaining_needed > 0:
|
651 |
-
segment_duration = min(potential_use_duration, remaining_needed + min_clip_duration)
|
652 |
-
segment_duration = max(min_clip_duration, segment_duration)
|
653 |
-
segment_duration = min(segment_duration, clip.duration)
|
654 |
-
|
655 |
-
if segment_duration >= min_clip_duration:
|
656 |
-
try:
|
657 |
-
sub = clip.subclip(0, segment_duration)
|
658 |
-
if sub.reader is None or sub.duration is None or sub.duration <= 0:
|
659 |
-
logger.warning(f"[{i+1}/{len(video_paths)}] Subclip generado de {path} es inválido. Saltando.")
|
660 |
-
try: sub.close()
|
661 |
-
except: pass
|
662 |
-
continue
|
663 |
-
|
664 |
-
clips_to_concatenate.append(sub)
|
665 |
-
current_duration += sub.duration
|
666 |
-
logger.debug(f"[{i+1}/{len(video_paths)}] Segmento añadido: {sub.duration:.1f}s (total video: {current_duration:.1f}/{audio_duration:.1f}s)")
|
667 |
-
|
668 |
-
except Exception as sub_e:
|
669 |
-
logger.warning(f"[{i+1}/{len(video_paths)}] Error creando subclip de {path} ({segment_duration:.1f}s): {str(sub_e)}")
|
670 |
-
continue
|
671 |
-
else:
|
672 |
-
logger.debug(f"[{i+1}/{len(video_paths)}] Clip {path} ({clip.duration:.1f}s) no contribuye un segmento suficiente ({segment_duration:.1f}s necesario). Saltando.")
|
673 |
-
else:
|
674 |
-
logger.debug(f"[{i+1}/{len(video_paths)}] Duración de video base ya alcanzada. Saltando clip.")
|
675 |
-
|
676 |
-
except Exception as e:
|
677 |
-
logger.warning(f"[{i+1}/{len(video_paths)}] Error procesando video {path}: {str(e)}", exc_info=True)
|
678 |
-
continue
|
679 |
-
|
680 |
-
logger.info(f"Procesamiento de clips fuente finalizado. Se obtuvieron {len(clips_to_concatenate)} segmentos válidos.")
|
681 |
-
|
682 |
-
if not clips_to_concatenate:
|
683 |
-
logger.error("No hay segmentos de video válidos disponibles para crear la secuencia.")
|
684 |
-
raise ValueError("No hay segmentos de video válidos disponibles para crear el video.")
|
685 |
-
|
686 |
-
logger.info(f"Concatenando {len(clips_to_concatenate)} segmentos de video.")
|
687 |
-
concatenated_base = None
|
688 |
-
try:
|
689 |
-
concatenated_base = concatenate_videoclips(clips_to_concatenate, method="chain")
|
690 |
-
logger.info(f"Duración video base después de concatenación inicial: {concatenated_base.duration:.2f}s")
|
691 |
-
|
692 |
-
if concatenated_base is None or concatenated_base.duration is None or concatenated_base.duration <= 0:
|
693 |
-
logger.critical("Video base concatenado es inválido después de la primera concatenación (None o duración cero).")
|
694 |
-
raise ValueError("Fallo al crear video base válido a partir de segmentos.")
|
695 |
-
|
696 |
-
except Exception as e:
|
697 |
-
logger.critical(f"Error durante la concatenación inicial: {str(e)}", exc_info=True)
|
698 |
-
raise ValueError("Fallo durante la concatenación de video inicial.")
|
699 |
-
finally:
|
700 |
-
for clip_segment in clips_to_concatenate:
|
701 |
-
try: clip_segment.close()
|
702 |
-
except: pass
|
703 |
-
clips_to_concatenate = []
|
704 |
-
|
705 |
-
video_base = concatenated_base
|
706 |
-
|
707 |
-
final_video_base = video_base
|
708 |
-
|
709 |
-
if final_video_base.duration < audio_duration:
|
710 |
-
logger.info(f"Video base ({final_video_base.duration:.2f}s) es más corto que el audio ({audio_duration:.2f}s). Repitiendo...")
|
711 |
-
|
712 |
-
num_full_repeats = int(audio_duration // final_video_base.duration)
|
713 |
-
remaining_duration = audio_duration % final_video_base.duration
|
714 |
-
|
715 |
-
repeated_clips_list = [final_video_base] * num_full_repeats
|
716 |
-
if remaining_duration > 0:
|
717 |
try:
|
718 |
-
|
719 |
-
if remaining_clip is None or remaining_clip.duration is None or remaining_clip.duration <= 0:
|
720 |
-
logger.warning(f"Subclip generado para duración restante {remaining_duration:.2f}s es inválido. Saltando.")
|
721 |
-
try: remaining_clip.close()
|
722 |
-
except: pass
|
723 |
-
else:
|
724 |
-
repeated_clips_list.append(remaining_clip)
|
725 |
-
logger.debug(f"Añadiendo segmento restante: {remaining_duration:.2f}s")
|
726 |
-
|
727 |
except Exception as e:
|
728 |
-
|
729 |
-
|
730 |
-
|
731 |
-
|
732 |
-
|
733 |
-
|
734 |
-
|
735 |
-
|
736 |
-
|
737 |
-
if
|
738 |
-
|
739 |
-
|
740 |
-
|
741 |
-
|
742 |
-
|
743 |
-
|
744 |
-
|
745 |
-
|
746 |
-
|
747 |
-
|
748 |
-
|
749 |
-
|
750 |
-
|
751 |
-
|
752 |
-
for clip in repeated_clips_list:
|
753 |
-
if clip is not final_video_base:
|
754 |
-
try: clip.close()
|
755 |
-
except: pass
|
756 |
-
|
757 |
-
|
758 |
-
if final_video_base.duration > audio_duration:
|
759 |
-
logger.info(f"Recortando video base ({final_video_base.duration:.2f}s) para que coincida con la duración del audio ({audio_duration:.2f}s).")
|
760 |
-
trimmed_video_base = None
|
761 |
-
try:
|
762 |
-
trimmed_video_base = final_video_base.subclip(0, audio_duration)
|
763 |
-
if trimmed_video_base is None or trimmed_video_base.duration is None or trimmed_video_base.duration <= 0:
|
764 |
-
logger.critical("Video base recortado es inválido.")
|
765 |
-
raise ValueError("Fallo al crear video base recortado válido.")
|
766 |
-
|
767 |
-
if final_video_base is not trimmed_video_base:
|
768 |
-
try: final_video_base.close()
|
769 |
-
except: pass
|
770 |
-
|
771 |
-
final_video_base = trimmed_video_base
|
772 |
-
|
773 |
-
except Exception as e:
|
774 |
-
logger.critical(f"Error durante el recorte: {str(e)}", exc_info=True)
|
775 |
-
raise ValueError("Fallo durante el recorte de video.")
|
776 |
-
|
777 |
-
|
778 |
-
if final_video_base is None or final_video_base.duration is None or final_video_base.duration <= 0:
|
779 |
-
logger.critical("Video base final es inválido antes de audio/escritura (None o duración cero).")
|
780 |
-
raise ValueError("Video base final es inválido.")
|
781 |
-
|
782 |
-
if final_video_base.size is None or final_video_base.size[0] <= 0 or final_video_base.size[1] <= 0:
|
783 |
-
logger.critical(f"Video base final tiene tamaño inválido: {final_video_base.size}. No se puede escribir video.")
|
784 |
-
raise ValueError("Video base final tiene tamaño inválido antes de escribir.")
|
785 |
-
|
786 |
-
video_base = final_video_base
|
787 |
-
|
788 |
-
# 6. Manejar música de fondo
|
789 |
-
logger.info("Procesando audio...")
|
790 |
-
|
791 |
-
final_audio = audio_tts_original
|
792 |
-
|
793 |
-
musica_audio_looped = None
|
794 |
-
|
795 |
-
if musica_file:
|
796 |
-
musica_audio_original = None
|
797 |
-
try:
|
798 |
-
music_path = os.path.join(temp_dir_intermediate, "musica_bg.mp3")
|
799 |
-
shutil.copyfile(musica_file, music_path)
|
800 |
-
temp_intermediate_files.append(music_path)
|
801 |
-
logger.info(f"Música de fondo copiada a: {music_path}")
|
802 |
-
|
803 |
-
musica_audio_original = AudioFileClip(music_path)
|
804 |
-
|
805 |
-
if musica_audio_original.reader is None or musica_audio_original.duration is None or musica_audio_original.duration <= 0:
|
806 |
-
logger.warning("Clip de música de fondo parece inválido o tiene duración cero. Saltando música.")
|
807 |
-
try: musica_audio_original.close()
|
808 |
-
except: pass
|
809 |
-
musica_audio_original = None
|
810 |
-
else:
|
811 |
-
musica_audio_looped = loop_audio_to_length(musica_audio_original, video_base.duration)
|
812 |
-
logger.debug(f"Música ajustada a duración del video: {musica_audio_looped.duration:.2f}s")
|
813 |
-
|
814 |
-
if musica_audio_looped is None or musica_audio_looped.duration is None or musica_audio_looped.duration <= 0:
|
815 |
-
logger.warning("Clip de música de fondo loopeado es inválido. Saltando música.")
|
816 |
-
try: musica_audio_looped.close()
|
817 |
-
except: pass
|
818 |
-
musica_audio_looped = None
|
819 |
-
|
820 |
-
|
821 |
-
if musica_audio_looped:
|
822 |
-
composite_audio = CompositeAudioClip([
|
823 |
-
musica_audio_looped.volumex(0.2), # Volumen 20% para música
|
824 |
-
audio_tts_original.volumex(1.0) # Volumen 100% para voz
|
825 |
-
])
|
826 |
-
|
827 |
-
if composite_audio.duration is None or composite_audio.duration <= 0:
|
828 |
-
logger.warning("Clip de audio compuesto es inválido (None o duración cero). Usando solo audio de voz.")
|
829 |
-
try: composite_audio.close()
|
830 |
-
except: pass
|
831 |
-
final_audio = audio_tts_original
|
832 |
else:
|
833 |
-
|
834 |
-
|
835 |
-
|
836 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
837 |
except Exception as e:
|
838 |
-
logger.
|
839 |
-
|
840 |
-
|
841 |
-
|
842 |
-
|
843 |
-
|
844 |
-
|
845 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
846 |
try:
|
847 |
-
|
848 |
-
|
849 |
-
|
850 |
-
logger.warning("Audio final recortado es inválido. Usando audio final original.")
|
851 |
-
try: trimmed_final_audio.close()
|
852 |
-
except: pass
|
853 |
-
else:
|
854 |
-
if final_audio is not trimmed_final_audio:
|
855 |
-
try: final_audio.close()
|
856 |
-
except: pass
|
857 |
-
final_audio = trimmed_final_audio
|
858 |
-
logger.warning("Audio final recortado para que coincida con la duración del video.")
|
859 |
except Exception as e:
|
860 |
-
|
861 |
-
|
862 |
-
|
863 |
-
|
864 |
-
|
865 |
-
|
866 |
-
|
867 |
-
|
868 |
-
|
869 |
-
|
870 |
-
|
871 |
-
output_path = os.path.join(temp_dir_intermediate, output_filename)
|
872 |
-
logger.info(f"Escribiendo video final a: {output_path}")
|
873 |
-
|
874 |
-
video_final.write_videofile(
|
875 |
output_path,
|
876 |
-
fps=
|
877 |
-
threads=4,
|
878 |
codec="libx264",
|
879 |
audio_codec="aac",
|
880 |
-
|
881 |
-
|
|
|
|
|
|
|
882 |
)
|
883 |
-
|
884 |
-
|
885 |
-
|
886 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
887 |
return output_path
|
888 |
-
|
889 |
-
except ValueError as ve:
|
890 |
-
logger.error(f"ERROR CONTROLADO en crear_video: {str(ve)}")
|
891 |
-
raise ve
|
892 |
except Exception as e:
|
893 |
-
logger.
|
894 |
-
raise
|
895 |
finally:
|
896 |
-
|
897 |
-
|
898 |
-
|
899 |
-
|
900 |
-
clip.close()
|
901 |
-
except Exception as e:
|
902 |
-
logger.warning(f"Error cerrando clip de video fuente en finally: {str(e)}")
|
903 |
-
|
904 |
-
for clip_segment in clips_to_concatenate:
|
905 |
-
try:
|
906 |
-
clip_segment.close()
|
907 |
-
except Exception as e:
|
908 |
-
logger.warning(f"Error cerrando segmento de video en finally: {str(e)}")
|
909 |
-
|
910 |
-
if musica_audio is not None:
|
911 |
-
try:
|
912 |
-
musica_audio.close()
|
913 |
-
except Exception as e:
|
914 |
-
logger.warning(f"Error cerrando musica_audio (procesada) en finally: {str(e)}")
|
915 |
-
|
916 |
-
if musica_audio_original is not None and musica_audio_original is not musica_audio:
|
917 |
-
try:
|
918 |
-
musica_audio_original.close()
|
919 |
-
except Exception as e:
|
920 |
-
logger.warning(f"Error cerrando musica_audio_original en finally: {str(e)}")
|
921 |
-
|
922 |
-
if audio_tts is not None and audio_tts is not audio_tts_original:
|
923 |
-
try:
|
924 |
-
audio_tts.close()
|
925 |
-
except Exception as e:
|
926 |
-
logger.warning(f"Error cerrando audio_tts (procesada) en finally: {str(e)}")
|
927 |
-
|
928 |
-
if audio_tts_original is not None:
|
929 |
-
try:
|
930 |
-
audio_tts_original.close()
|
931 |
-
except Exception as e:
|
932 |
-
logger.warning(f"Error cerrando audio_tts_original en finally: {str(e)}")
|
933 |
-
|
934 |
-
if video_final is not None:
|
935 |
-
try:
|
936 |
-
video_final.close()
|
937 |
-
except Exception as e:
|
938 |
-
logger.warning(f"Error cerrando video_final en finally: {str(e)}")
|
939 |
-
elif video_base is not None and video_base is not video_final:
|
940 |
-
try:
|
941 |
-
video_base.close()
|
942 |
-
except Exception as e:
|
943 |
-
logger.warning(f"Error cerrando video_base en finally: {str(e)}")
|
944 |
-
|
945 |
-
if temp_dir_intermediate and os.path.exists(temp_dir_intermediate):
|
946 |
-
final_output_in_temp = os.path.join(temp_dir_intermediate, "final_video.mp4")
|
947 |
-
|
948 |
-
for path in temp_intermediate_files:
|
949 |
-
try:
|
950 |
-
if os.path.isfile(path) and path != final_output_in_temp:
|
951 |
-
logger.debug(f"Eliminando archivo temporal intermedio: {path}")
|
952 |
-
os.remove(path)
|
953 |
-
elif os.path.isfile(path) and path == final_output_in_temp:
|
954 |
-
logger.debug(f"Saltando eliminación del archivo de video final: {path}")
|
955 |
-
except Exception as e:
|
956 |
-
logger.warning(f"No se pudo eliminar archivo temporal intermedio {path}: {str(e)}")
|
957 |
-
|
958 |
-
logger.info(f"Directorio temporal intermedio {temp_dir_intermediate} persistirá para que Gradio lea el video final.")
|
959 |
-
|
960 |
-
|
961 |
-
# run_app ahora recibe todos los inputs, incluyendo la voz seleccionada
|
962 |
-
def run_app(prompt_type, prompt_ia, prompt_manual, musica_file, selected_voice): # <-- Recibe el valor del Dropdown
|
963 |
-
logger.info("="*80)
|
964 |
-
logger.info("SOLICITUD RECIBIDA EN INTERFAZ")
|
965 |
-
|
966 |
-
# Elegir el texto de entrada basado en el prompt_type
|
967 |
-
input_text = prompt_ia if prompt_type == "Generar Guion con IA" else prompt_manual
|
968 |
-
|
969 |
-
output_video = None
|
970 |
-
output_file = None
|
971 |
-
status_msg = gr.update(value="⏳ Procesando...", interactive=False)
|
972 |
-
|
973 |
-
if not input_text or not input_text.strip():
|
974 |
-
logger.warning("Texto de entrada vacío.")
|
975 |
-
# Retornar None para video y archivo, actualizar estado con mensaje de error
|
976 |
-
return None, None, gr.update(value="⚠️ Por favor, ingresa texto para el guion o el tema.", interactive=False)
|
977 |
-
|
978 |
-
# Validar la voz seleccionada. Si no es válida, usar la por defecto.
|
979 |
-
# AVAILABLE_VOICES se obtiene al inicio. Hay que buscar si el voice_id existe en la lista de pares (nombre, id)
|
980 |
-
voice_ids_disponibles = [v[1] for v in AVAILABLE_VOICES]
|
981 |
-
if selected_voice not in voice_ids_disponibles:
|
982 |
-
logger.warning(f"Voz seleccionada inválida o no encontrada en la lista: '{selected_voice}'. Usando voz por defecto: {DEFAULT_VOICE_ID}.")
|
983 |
-
selected_voice = DEFAULT_VOICE_ID # <-- Usar el ID de la voz por defecto
|
984 |
-
else:
|
985 |
-
logger.info(f"Voz seleccionada validada: {selected_voice}")
|
986 |
-
|
987 |
-
|
988 |
-
logger.info(f"Tipo de entrada: {prompt_type}")
|
989 |
-
logger.debug(f"Texto de entrada: '{input_text[:100]}...'")
|
990 |
-
if musica_file:
|
991 |
-
logger.info(f"Archivo de música recibido: {musica_file}")
|
992 |
-
else:
|
993 |
-
logger.info("No se proporcionó archivo de música.")
|
994 |
-
logger.info(f"Voz final a usar (ID): {selected_voice}") # Loguear el ID de la voz final
|
995 |
|
|
|
996 |
try:
|
997 |
-
|
998 |
-
|
999 |
-
|
1000 |
-
|
1001 |
-
|
1002 |
-
|
1003 |
-
|
1004 |
-
|
1005 |
-
|
1006 |
-
|
1007 |
-
|
1008 |
-
logger.error(f"crear_video no retornó un path válido o el archivo no existe: {video_path}")
|
1009 |
-
status_msg = gr.update(value="❌ Error: La generación del video falló o el archivo no se creó correctamente.", interactive=False)
|
1010 |
-
|
1011 |
-
except ValueError as ve:
|
1012 |
-
logger.warning(f"Error de validación durante la creación del video: {str(ve)}")
|
1013 |
-
status_msg = gr.update(value=f"⚠️ Error de validación: {str(ve)}", interactive=False)
|
1014 |
except Exception as e:
|
1015 |
-
logger.
|
1016 |
-
|
1017 |
-
|
1018 |
-
|
1019 |
-
|
1020 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1021 |
|
1022 |
-
|
1023 |
-
with gr.Blocks(title="Generador de Videos con IA", theme=gr.themes.Soft(), css="""
|
1024 |
-
.gradio-container {max-width: 800px; margin: auto;}
|
1025 |
-
h1 {text-align: center;}
|
1026 |
-
""") as app:
|
1027 |
|
1028 |
-
|
1029 |
-
|
|
|
|
|
|
|
|
|
1030 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1031 |
with gr.Row():
|
1032 |
-
with gr.Column():
|
1033 |
-
|
1034 |
-
|
1035 |
-
|
1036 |
-
|
|
|
|
|
1037 |
)
|
1038 |
-
|
1039 |
-
|
1040 |
-
|
1041 |
-
|
1042 |
-
|
1043 |
-
|
1044 |
-
|
1045 |
-
|
1046 |
-
|
1047 |
-
|
1048 |
-
|
1049 |
-
|
1050 |
-
|
1051 |
-
|
1052 |
-
|
1053 |
-
lines=5,
|
1054 |
-
placeholder="Ej: En este video exploraremos los misterios del océano. Veremos la vida marina fascinante y los arrecifes de coral vibrantes. ¡Acompáñanos en esta aventura subacuática!",
|
1055 |
-
max_lines=10,
|
1056 |
-
value=""
|
1057 |
-
# visible=... <-- ¡NO DEBE ESTAR AQUÍ!
|
1058 |
-
)
|
1059 |
-
|
1060 |
-
musica_input = gr.Audio(
|
1061 |
-
label="Música de fondo (opcional)",
|
1062 |
type="filepath",
|
1063 |
-
|
1064 |
-
value=None
|
1065 |
-
# visible=... <-- ¡NO DEBE ESTAR AQUÍ!
|
1066 |
)
|
1067 |
-
|
1068 |
-
|
1069 |
-
|
1070 |
-
|
1071 |
-
|
1072 |
-
value=DEFAULT_VOICE_ID, # Usar el ID de la voz por defecto calculada
|
1073 |
-
interactive=True
|
1074 |
-
# visible=... <-- ¡NO DEBE ESTAR AQUÍ!
|
1075 |
)
|
1076 |
-
|
1077 |
-
|
1078 |
-
|
1079 |
-
|
1080 |
-
|
1081 |
-
|
1082 |
-
|
1083 |
-
label="Previsualización del Video Generado",
|
1084 |
interactive=False,
|
|
|
|
|
|
|
|
|
|
|
1085 |
height=400
|
1086 |
-
# visible=... <-- ¡NO DEBE ESTAR AQUÍ!
|
1087 |
)
|
1088 |
-
|
1089 |
-
|
1090 |
-
|
1091 |
-
visible=False # <-- ESTÁ BIEN AQUÍ
|
1092 |
-
# visible=... <-- ¡NO DEBE ESTAR AQUÍ si ya está visible=False arriba!
|
1093 |
)
|
1094 |
-
|
1095 |
-
|
1096 |
-
|
1097 |
-
|
1098 |
-
|
1099 |
-
value="Esperando entrada..."
|
1100 |
-
# visible=... <-- ¡NO DEBE ESTAR AQUÍ!
|
1101 |
-
)
|
1102 |
-
|
1103 |
-
# Evento para mostrar/ocultar los campos de texto según el tipo de prompt
|
1104 |
-
prompt_type.change(
|
1105 |
-
lambda x: (gr.update(visible=x == "Generar Guion con IA"),
|
1106 |
-
gr.update(visible=x == "Usar Mi Guion")),
|
1107 |
-
inputs=prompt_type,
|
1108 |
-
outputs=[ia_guion_column, manual_guion_column] # Apuntar a las Columnas contenedoras
|
1109 |
)
|
1110 |
-
|
1111 |
-
# Evento click del botón de generar video
|
1112 |
generate_btn.click(
|
1113 |
-
|
1114 |
-
|
1115 |
-
outputs=[
|
1116 |
-
queue=True, # Usar la cola de Gradio
|
1117 |
-
).then(
|
1118 |
-
# Acción 2 (asíncrona): Llamar a la función principal
|
1119 |
-
run_app,
|
1120 |
-
# PASAR TODOS LOS INPUTS DE LA INTERFAZ que run_app espera
|
1121 |
-
inputs=[prompt_type, prompt_ia, prompt_manual, musica_input, voice_dropdown], # <-- Pasar los 5 inputs a run_app
|
1122 |
-
# run_app retornará los 3 outputs esperados
|
1123 |
-
outputs=[video_output, file_output, status_output]
|
1124 |
-
).then(
|
1125 |
-
# Acción 3 (síncrona): Hacer visible el enlace de descarga
|
1126 |
-
lambda video_path, file_path, status_msg: gr.update(visible=file_path is not None),
|
1127 |
-
inputs=[video_output, file_output, status_output],
|
1128 |
-
outputs=[file_output]
|
1129 |
)
|
1130 |
-
|
1131 |
-
|
1132 |
-
gr.Markdown("### Instrucciones:")
|
1133 |
gr.Markdown("""
|
1134 |
-
|
1135 |
-
|
1136 |
-
|
1137 |
-
|
1138 |
-
|
1139 |
-
|
1140 |
-
|
1141 |
-
8. Revisa `video_generator_full.log` para detalles si hay errores.
|
1142 |
""")
|
1143 |
-
gr.Markdown("---")
|
1144 |
-
gr.Markdown("Desarrollado por [Tu Nombre/Empresa/Alias - Opcional]")
|
1145 |
|
1146 |
if __name__ == "__main__":
|
1147 |
-
logger.info("
|
1148 |
-
|
1149 |
-
|
1150 |
-
|
1151 |
-
|
1152 |
-
|
1153 |
-
|
1154 |
-
|
1155 |
-
logger.critical(f"Fallo al crear clip base de MoviePy. A menudo indica problemas con FFmpeg/ImageMagick. Error: {e}", exc_info=True)
|
1156 |
-
|
1157 |
-
except Exception as e:
|
1158 |
-
logger.critical(f"Fallo al importar MoviePy. Asegúrate de que está instalado. Error: {e}", exc_info=True)
|
1159 |
-
|
1160 |
-
logger.info("Iniciando aplicación Gradio...")
|
1161 |
-
try:
|
1162 |
-
app.launch(server_name="0.0.0.0", server_port=7860, share=False)
|
1163 |
-
except Exception as e:
|
1164 |
-
logger.critical(f"No se pudo iniciar la app: {str(e)}", exc_info=True)
|
1165 |
-
raise
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
import torch
|
3 |
+
import soundfile as sf
|
4 |
+
import edge_tts
|
5 |
+
import asyncio
|
6 |
from transformers import GPT2Tokenizer, GPT2LMHeadModel
|
7 |
from keybert import KeyBERT
|
8 |
+
from moviepy.editor import (
|
9 |
+
VideoFileClip,
|
10 |
+
AudioFileClip,
|
11 |
+
concatenate_videoclips,
|
12 |
+
concatenate_audioclips,
|
13 |
+
CompositeAudioClip,
|
14 |
+
AudioClip,
|
15 |
+
TextClip,
|
16 |
+
CompositeVideoClip,
|
17 |
+
VideoClip,
|
18 |
+
ColorClip
|
19 |
+
)
|
20 |
+
import numpy as np
|
21 |
+
import json
|
22 |
+
import logging
|
23 |
+
import os
|
24 |
+
import requests
|
25 |
import re
|
26 |
import math
|
27 |
+
import tempfile
|
28 |
import shutil
|
29 |
+
import uuid
|
30 |
+
import threading
|
31 |
+
import time
|
32 |
+
from datetime import datetime, timedelta
|
33 |
|
34 |
+
# ------------------- FIX PARA PILLOW -------------------
|
35 |
+
try:
|
36 |
+
from PIL import Image
|
37 |
+
if not hasattr(Image, 'ANTIALIAS'):
|
38 |
+
Image.ANTIALIAS = Image.Resampling.LANCZOS
|
39 |
+
except ImportError:
|
40 |
+
pass
|
41 |
+
|
42 |
+
# ------------------- Configuración & Globals -------------------
|
43 |
+
os.environ["GRADIO_SERVER_TIMEOUT"] = "3800"
|
44 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
45 |
logger = logging.getLogger(__name__)
|
46 |
+
PEXELS_API_KEY = os.getenv("PEXELS_API_KEY")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
if not PEXELS_API_KEY:
|
48 |
+
logger.warning("PEXELS_API_KEY no definido. Los videos no funcionarán.")
|
49 |
+
|
50 |
+
tokenizer, gpt2_model, kw_model = None, None, None
|
51 |
+
RESULTS_DIR = "video_results"
|
52 |
+
os.makedirs(RESULTS_DIR, exist_ok=True)
|
53 |
+
TASKS = {}
|
54 |
+
|
55 |
+
# ------------------- Motor Edge TTS -------------------
|
56 |
+
class EdgeTTSEngine:
|
57 |
+
def __init__(self, voice="es-ES-AlvaroNeural"):
|
58 |
+
self.voice = voice
|
59 |
+
logger.info(f"Inicializando Edge TTS con voz: {voice}")
|
60 |
+
|
61 |
+
async def _synthesize_async(self, text, output_path):
|
62 |
+
try:
|
63 |
+
communicate = edge_tts.Communicate(text, self.voice)
|
64 |
+
await communicate.save(output_path)
|
65 |
+
return True
|
66 |
+
except Exception as e:
|
67 |
+
logger.error(f"Error en Edge TTS: {e}")
|
68 |
+
return False
|
69 |
+
|
70 |
+
def synthesize(self, text, output_path):
|
71 |
+
try:
|
72 |
+
return asyncio.run(self._synthesize_async(text, output_path))
|
73 |
+
except Exception as e:
|
74 |
+
logger.error(f"Error al sintetizar con Edge TTS: {e}")
|
75 |
+
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
76 |
|
77 |
+
tts_engine = EdgeTTSEngine()
|
78 |
+
|
79 |
+
# ------------------- Carga Perezosa de Modelos -------------------
|
80 |
+
def get_tokenizer():
|
81 |
+
global tokenizer
|
82 |
+
if tokenizer is None:
|
83 |
+
logger.info("Cargando tokenizer GPT2 español...")
|
84 |
+
tokenizer = GPT2Tokenizer.from_pretrained("datificate/gpt2-small-spanish")
|
85 |
+
if tokenizer.pad_token is None:
|
86 |
+
tokenizer.pad_token = tokenizer.eos_token
|
87 |
+
return tokenizer
|
88 |
+
|
89 |
+
def get_gpt2_model():
|
90 |
+
global gpt2_model
|
91 |
+
if gpt2_model is None:
|
92 |
+
logger.info("Cargando modelo GPT-2 español...")
|
93 |
+
gpt2_model = GPT2LMHeadModel.from_pretrained("datificate/gpt2-small-spanish").eval()
|
94 |
+
return gpt2_model
|
95 |
+
|
96 |
+
def get_kw_model():
|
97 |
+
global kw_model
|
98 |
+
if kw_model is None:
|
99 |
+
logger.info("Cargando modelo KeyBERT multilingüe...")
|
100 |
+
kw_model = KeyBERT("paraphrase-multilingual-MiniLM-L12-v2")
|
101 |
+
return kw_model
|
102 |
+
|
103 |
+
# ------------------- Funciones del Pipeline -------------------
|
104 |
+
def update_task_progress(task_id, message):
|
105 |
+
if task_id in TASKS:
|
106 |
+
TASKS[task_id]['progress_log'] = message
|
107 |
+
logger.info(f"[{task_id}] {message}")
|
108 |
+
|
109 |
+
def gpt2_script(prompt: str) -> str:
|
110 |
try:
|
111 |
+
local_tokenizer = get_tokenizer()
|
112 |
+
local_gpt2_model = get_gpt2_model()
|
113 |
+
|
114 |
+
instruction = f"Escribe un guion corto y coherente sobre: {prompt}"
|
115 |
+
inputs = local_tokenizer(instruction, return_tensors="pt", truncation=True, max_length=512)
|
116 |
+
|
117 |
+
outputs = local_gpt2_model.generate(
|
118 |
**inputs,
|
119 |
+
max_length=160 + inputs["input_ids"].shape[1],
|
120 |
do_sample=True,
|
121 |
top_p=0.9,
|
122 |
top_k=40,
|
123 |
temperature=0.7,
|
124 |
+
no_repeat_ngram_size=3,
|
125 |
+
pad_token_id=local_tokenizer.pad_token_id,
|
126 |
+
eos_token_id=local_tokenizer.eos_token_id,
|
|
|
127 |
)
|
128 |
+
|
129 |
+
text = local_tokenizer.decode(outputs[0], skip_special_tokens=True)
|
130 |
+
generated = text.split("sobre:")[-1].strip()
|
131 |
+
return generated if generated else prompt
|
132 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
133 |
except Exception as e:
|
134 |
+
logger.error(f"Error generando guión: {e}")
|
135 |
+
return f"Hoy hablaremos sobre {prompt}. Este es un tema fascinante que merece nuestra atención."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
136 |
|
137 |
+
def generate_tts_audio(text: str, output_path: str) -> bool:
|
138 |
try:
|
139 |
+
logger.info("Generando audio con Edge TTS...")
|
140 |
+
success = tts_engine.synthesize(text, output_path)
|
141 |
+
if success and os.path.exists(output_path) and os.path.getsize(output_path) > 0:
|
142 |
+
logger.info(f"Audio generado exitosamente: {output_path}")
|
|
|
143 |
return True
|
144 |
else:
|
145 |
+
logger.error("El archivo de audio no se generó correctamente")
|
146 |
return False
|
|
|
147 |
except Exception as e:
|
148 |
+
logger.error(f"Error generando TTS: {e}")
|
149 |
return False
|
150 |
|
151 |
+
def extract_keywords(text: str) -> list[str]:
|
152 |
+
try:
|
153 |
+
local_kw_model = get_kw_model()
|
154 |
+
clean_text = re.sub(r"[^\w\sáéíóúñÁÉÍÓÚÑ]", "", text.lower())
|
155 |
+
kws = local_kw_model.extract_keywords(clean_text, stop_words="spanish", top_n=5)
|
156 |
+
keywords = [k.replace(" ", "+") for k, _ in kws if k]
|
157 |
+
return keywords if keywords else ["mystery", "conspiracy", "alien", "UFO", "secret", "cover-up", "illusion", "paranoia"]
|
158 |
+
except Exception as e:
|
159 |
+
logger.error(f"Error extrayendo keywords: {e}")
|
160 |
+
return ["mystery", "conspiracy", "alien", "UFO", "secret", "cover-up", "illusion", "paranoia"]
|
161 |
|
162 |
+
def search_pexels_videos(query: str, count: int = 3) -> list[dict]:
|
163 |
+
if not PEXELS_API_KEY:
|
164 |
+
return []
|
165 |
+
|
166 |
try:
|
167 |
+
response = requests.get(
|
168 |
+
"https://api.pexels.com/videos/search",
|
169 |
+
headers={"Authorization": PEXELS_API_KEY},
|
170 |
+
params={"query": query, "per_page": count, "orientation": "landscape"},
|
171 |
+
timeout=20
|
172 |
+
)
|
173 |
+
response.raise_for_status()
|
174 |
+
return response.json().get("videos", [])
|
175 |
+
except Exception as e:
|
176 |
+
logger.error(f"Error buscando videos en Pexels: {e}")
|
177 |
+
return []
|
178 |
|
179 |
+
def download_video(url: str, folder: str) -> str | None:
|
180 |
+
try:
|
181 |
+
filename = f"{uuid.uuid4().hex}.mp4"
|
182 |
+
filepath = os.path.join(folder, filename)
|
183 |
+
|
184 |
+
with requests.get(url, stream=True, timeout=60) as response:
|
185 |
+
response.raise_for_status()
|
186 |
+
with open(filepath, "wb") as f:
|
187 |
+
for chunk in response.iter_content(chunk_size=1024*1024):
|
188 |
f.write(chunk)
|
189 |
+
|
190 |
+
if os.path.exists(filepath) and os.path.getsize(filepath) > 1000:
|
191 |
+
return filepath
|
|
|
192 |
else:
|
193 |
+
logger.error(f"Archivo descargado inválido: {filepath}")
|
194 |
+
return None
|
195 |
+
|
|
|
|
|
|
|
|
|
196 |
except Exception as e:
|
197 |
+
logger.error(f"Error descargando video {url}: {e}")
|
198 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
199 |
|
200 |
+
def loop_audio_to_duration(audio_clip: AudioFileClip, target_duration: float) -> AudioFileClip:
|
201 |
+
if audio_clip is None:
|
202 |
+
return None
|
203 |
try:
|
204 |
+
if audio_clip.duration >= target_duration:
|
205 |
+
return audio_clip.subclip(0, target_duration)
|
206 |
+
|
207 |
+
loops_needed = math.ceil(target_duration / audio_clip.duration)
|
208 |
+
looped_audio = concatenate_audioclips([audio_clip] * loops_needed)
|
209 |
+
return looped_audio.subclip(0, target_duration)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
210 |
except Exception as e:
|
211 |
+
logger.error(f"Error haciendo loop del audio: {e}")
|
212 |
+
return audio_clip
|
213 |
+
|
214 |
+
def create_video(script_text: str, generate_script: bool, music_path: str | None, task_id: str) -> str:
|
215 |
+
temp_dir = tempfile.mkdtemp()
|
216 |
+
TARGET_FPS = 24
|
217 |
+
TARGET_RESOLUTION = (1280, 720)
|
218 |
+
MAX_CLIP_DURATION = 8 # Máximo de segundos por clip
|
219 |
+
|
220 |
+
def normalize_clip(clip):
|
221 |
+
if clip is None:
|
222 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
223 |
try:
|
224 |
+
if clip.size != TARGET_RESOLUTION:
|
225 |
+
clip = clip.resize(TARGET_RESOLUTION)
|
226 |
+
if clip.fps != TARGET_FPS:
|
227 |
+
clip = clip.set_fps(TARGET_FPS)
|
228 |
+
return clip
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
229 |
except Exception as e:
|
230 |
+
logger.error(f"Error normalizando clip: {e}")
|
231 |
+
return None
|
232 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
233 |
try:
|
234 |
+
# Paso 1: Generar o usar guión
|
235 |
+
update_task_progress(task_id, "Paso 1/7: Preparando guión...")
|
236 |
+
if generate_script:
|
237 |
+
script = gpt2_script(script_text)
|
238 |
else:
|
239 |
+
script = script_text.strip()
|
240 |
+
|
241 |
+
if not script:
|
242 |
+
raise ValueError("El guión está vacío")
|
243 |
+
|
244 |
+
# Paso 2: Generar audio TTS
|
245 |
+
update_task_progress(task_id, "Paso 2/7: Generando audio con Edge TTS...")
|
246 |
+
audio_path = os.path.join(temp_dir, "voice.wav")
|
247 |
+
|
248 |
+
if not generate_tts_audio(script, audio_path):
|
249 |
+
raise RuntimeError("Error generando el audio TTS")
|
250 |
+
|
251 |
+
voice_clip = AudioFileClip(audio_path)
|
252 |
+
if voice_clip is None:
|
253 |
+
raise RuntimeError("No se pudo cargar el clip de audio")
|
254 |
+
|
255 |
+
video_duration = voice_clip.duration
|
256 |
+
|
257 |
+
if video_duration < 1:
|
258 |
+
raise ValueError("El audio generado es demasiado corto")
|
259 |
+
|
260 |
+
# Paso 3: Buscar y descargar videos (adaptado a la duración del audio)
|
261 |
+
update_task_progress(task_id, "Paso 3/7: Buscando videos en Pexels...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
262 |
video_paths = []
|
263 |
+
keywords = extract_keywords(script)
|
264 |
+
|
265 |
+
# Calcular cuántos clips necesitamos aproximadamente
|
266 |
+
estimated_clips_needed = max(1, math.ceil(video_duration / MAX_CLIP_DURATION))
|
267 |
+
|
268 |
+
for i, keyword in enumerate(keywords):
|
269 |
+
if len(video_paths) >= estimated_clips_needed * 2: # Buscar el doble para tener opciones
|
270 |
+
break
|
271 |
+
|
272 |
+
update_task_progress(task_id, f"Paso 3/7: Buscando videos para '{keyword}' ({i+1}/{len(keywords)})")
|
273 |
+
|
274 |
+
videos = search_pexels_videos(keyword, 3) # Buscar 3 videos por keyword
|
275 |
+
for video_data in videos:
|
276 |
+
if len(video_paths) >= estimated_clips_needed * 2:
|
277 |
+
break
|
278 |
+
|
279 |
+
video_files = video_data.get("video_files", [])
|
280 |
+
if video_files:
|
281 |
+
# Encontrar el video con la mejor calidad que sea MP4
|
282 |
+
best_file = None
|
283 |
+
for file in video_files:
|
284 |
+
if file.get("file_type") == "video/mp4":
|
285 |
+
if best_file is None or file.get("width", 0) > best_file.get("width", 0):
|
286 |
+
best_file = file
|
287 |
+
|
288 |
+
if best_file is None:
|
289 |
+
continue
|
290 |
+
|
291 |
+
video_url = best_file.get("link")
|
292 |
+
|
293 |
+
if video_url:
|
294 |
+
downloaded_path = download_video(video_url, temp_dir)
|
295 |
+
if downloaded_path:
|
296 |
+
video_paths.append(downloaded_path)
|
297 |
+
if len(video_paths) >= estimated_clips_needed * 2:
|
298 |
+
break
|
299 |
+
|
300 |
if not video_paths:
|
301 |
+
raise RuntimeError("No se pudieron descargar videos de Pexels")
|
302 |
+
|
303 |
+
# Paso 4: Procesar videos - MANEJO CORRECTO DE ERRORES
|
304 |
+
update_task_progress(task_id, f"Paso 4/7: Procesando videos...")
|
305 |
+
video_clips = []
|
306 |
+
total_duration = 0
|
307 |
+
|
308 |
+
for path in video_paths:
|
309 |
+
if total_duration >= video_duration:
|
|
|
|
|
|
|
310 |
break
|
311 |
+
|
312 |
clip = None
|
313 |
try:
|
314 |
+
# Cargar el video con verificación adicional
|
315 |
clip = VideoFileClip(path)
|
316 |
+
if clip is None:
|
317 |
+
logger.error(f"No se pudo cargar el video: {path}")
|
|
|
|
|
318 |
continue
|
319 |
+
|
320 |
+
# Verificar que el clip se cargó correctamente intentando acceder a un frame
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
321 |
try:
|
322 |
+
clip.get_frame(0) # Intenta obtener el primer frame
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
323 |
except Exception as e:
|
324 |
+
logger.error(f"Video corrupto o incompatible: {path}, error: {e}")
|
325 |
+
clip.close()
|
326 |
+
continue
|
327 |
+
|
328 |
+
# Tomar máximo 8 segundos de cada clip o lo que necesitemos
|
329 |
+
try:
|
330 |
+
clip_duration = min(MAX_CLIP_DURATION, clip.duration)
|
331 |
+
# Si ya tenemos suficiente duración, tomar solo lo necesario
|
332 |
+
remaining_duration = video_duration - total_duration
|
333 |
+
if remaining_duration < clip_duration:
|
334 |
+
clip_duration = remaining_duration
|
335 |
+
|
336 |
+
processed_clip = clip.subclip(0, clip_duration)
|
337 |
+
except Exception as e:
|
338 |
+
logger.error(f"Error al recortar video {path}: {e}")
|
339 |
+
clip.close()
|
340 |
+
continue
|
341 |
+
|
342 |
+
# Normalizar el clip
|
343 |
+
try:
|
344 |
+
processed_clip = normalize_clip(processed_clip)
|
345 |
+
if processed_clip is not None:
|
346 |
+
video_clips.append(processed_clip)
|
347 |
+
total_duration += processed_clip.duration
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
348 |
else:
|
349 |
+
if 'processed_clip' in locals():
|
350 |
+
processed_clip.close()
|
351 |
+
clip.close()
|
352 |
+
except Exception as e:
|
353 |
+
logger.error(f"Error al normalizar video {path}: {e}")
|
354 |
+
if 'processed_clip' in locals():
|
355 |
+
processed_clip.close()
|
356 |
+
clip.close()
|
357 |
+
continue
|
358 |
+
|
359 |
except Exception as e:
|
360 |
+
logger.error(f"Error procesando video {path}: {e}")
|
361 |
+
finally:
|
362 |
+
if clip is not None:
|
363 |
+
clip.close()
|
364 |
+
|
365 |
+
if not video_clips:
|
366 |
+
raise RuntimeError("No se pudieron procesar los videos")
|
367 |
+
|
368 |
+
# Concatenar videos
|
369 |
+
base_video = concatenate_videoclips(video_clips, method="chain")
|
370 |
+
|
371 |
+
# Asegurar duración exacta
|
372 |
+
base_video = base_video.subclip(0, video_duration)
|
373 |
+
|
374 |
+
# Paso 5: Componer audio final
|
375 |
+
update_task_progress(task_id, "Paso 5/7: Componiendo audio...")
|
376 |
+
if music_path and os.path.exists(music_path):
|
377 |
try:
|
378 |
+
music_clip = AudioFileClip(music_path)
|
379 |
+
music_clip = loop_audio_to_duration(music_clip, video_duration).volumex(0.2)
|
380 |
+
final_audio = CompositeAudioClip([music_clip, voice_clip])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
381 |
except Exception as e:
|
382 |
+
logger.error(f"Error con música: {e}")
|
383 |
+
final_audio = voice_clip
|
384 |
+
else:
|
385 |
+
final_audio = voice_clip
|
386 |
+
|
387 |
+
# Paso 6: Renderizar video final
|
388 |
+
update_task_progress(task_id, "Paso 6/7: Renderizando video final...")
|
389 |
+
final_video = base_video.set_audio(final_audio)
|
390 |
+
|
391 |
+
output_path = os.path.join(RESULTS_DIR, f"video_{task_id}.mp4")
|
392 |
+
final_video.write_videofile(
|
|
|
|
|
|
|
|
|
393 |
output_path,
|
394 |
+
fps=TARGET_FPS,
|
|
|
395 |
codec="libx264",
|
396 |
audio_codec="aac",
|
397 |
+
bitrate="8000k",
|
398 |
+
threads=4,
|
399 |
+
preset="slow",
|
400 |
+
logger=None,
|
401 |
+
verbose=False
|
402 |
)
|
403 |
+
|
404 |
+
# Paso 7: Limpiar recursos
|
405 |
+
update_task_progress(task_id, "Paso 7/7: Finalizando...")
|
406 |
+
|
407 |
+
# Limpiar clips
|
408 |
+
voice_clip.close()
|
409 |
+
if 'music_clip' in locals():
|
410 |
+
music_clip.close()
|
411 |
+
base_video.close()
|
412 |
+
final_video.close()
|
413 |
+
for clip in video_clips:
|
414 |
+
clip.close()
|
415 |
+
|
416 |
return output_path
|
417 |
+
|
|
|
|
|
|
|
418 |
except Exception as e:
|
419 |
+
logger.error(f"Error creando video: {e}")
|
420 |
+
raise
|
421 |
finally:
|
422 |
+
try:
|
423 |
+
shutil.rmtree(temp_dir)
|
424 |
+
except:
|
425 |
+
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
426 |
|
427 |
+
def worker_thread(task_id: str, mode: str, topic: str, user_script: str, music_path: str | None):
|
428 |
try:
|
429 |
+
generate_script = (mode == "Generar Guion con IA")
|
430 |
+
content = topic if generate_script else user_script
|
431 |
+
|
432 |
+
output_path = create_video(content, generate_script, music_path, task_id)
|
433 |
+
|
434 |
+
TASKS[task_id].update({
|
435 |
+
"status": "done",
|
436 |
+
"result": output_path,
|
437 |
+
"progress_log": "✅ ¡Video completado exitosamente!"
|
438 |
+
})
|
439 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
440 |
except Exception as e:
|
441 |
+
logger.error(f"Error en worker {task_id}: {e}")
|
442 |
+
TASKS[task_id].update({
|
443 |
+
"status": "error",
|
444 |
+
"error": str(e),
|
445 |
+
"progress_log": f"❌ Error: {str(e)}"
|
446 |
+
})
|
447 |
+
|
448 |
+
def generate_video_with_progress(mode, topic, user_script, music):
|
449 |
+
content = topic if mode == "Generar Guion con IA" else user_script
|
450 |
+
if not content or not content.strip():
|
451 |
+
yield "❌ Error: Por favor, ingresa un tema o guion.", None, None
|
452 |
+
return
|
453 |
+
|
454 |
+
task_id = uuid.uuid4().hex[:8]
|
455 |
+
TASKS[task_id] = {
|
456 |
+
"status": "processing",
|
457 |
+
"progress_log": "🚀 Iniciando generación de video...",
|
458 |
+
"timestamp": datetime.utcnow()
|
459 |
+
}
|
460 |
+
|
461 |
+
worker = threading.Thread(
|
462 |
+
target=worker_thread,
|
463 |
+
args=(task_id, mode, topic, user_script, music),
|
464 |
+
daemon=True
|
465 |
+
)
|
466 |
+
worker.start()
|
467 |
+
|
468 |
+
while TASKS[task_id]["status"] == "processing":
|
469 |
+
yield TASKS[task_id]['progress_log'], None, None
|
470 |
+
time.sleep(1)
|
471 |
+
|
472 |
+
if TASKS[task_id]["status"] == "error":
|
473 |
+
yield TASKS[task_id]['progress_log'], None, None
|
474 |
+
elif TASKS[task_id]["status"] == "done":
|
475 |
+
result_path = TASKS[task_id]['result']
|
476 |
+
yield TASKS[task_id]['progress_log'], result_path, result_path
|
477 |
+
|
478 |
+
# ------------------- Limpieza automática -------------------
|
479 |
+
def cleanup_old_files():
|
480 |
+
while True:
|
481 |
+
try:
|
482 |
+
time.sleep(6600)
|
483 |
+
now = datetime.utcnow()
|
484 |
+
logger.info("Ejecutando limpieza de archivos antiguos...")
|
485 |
+
|
486 |
+
for task_id, info in list(TASKS.items()):
|
487 |
+
if "timestamp" in info and now - info["timestamp"] > timedelta(hours=24):
|
488 |
+
if info.get("result") and os.path.exists(info.get("result")):
|
489 |
+
try:
|
490 |
+
os.remove(info["result"])
|
491 |
+
logger.info(f"Archivo eliminado: {info['result']}")
|
492 |
+
except Exception as e:
|
493 |
+
logger.error(f"Error eliminando archivo: {e}")
|
494 |
+
del TASKS[task_id]
|
495 |
+
|
496 |
+
except Exception as e:
|
497 |
+
logger.error(f"Error en cleanup: {e}")
|
498 |
|
499 |
+
threading.Thread(target=cleanup_old_files, daemon=True).start()
|
|
|
|
|
|
|
|
|
500 |
|
501 |
+
# ------------------- Interfaz Gradio -------------------
|
502 |
+
def toggle_input_fields(mode):
|
503 |
+
return (
|
504 |
+
gr.update(visible=mode == "Generar Guion con IA"),
|
505 |
+
gr.update(visible=mode != "Generar Guion con IA")
|
506 |
+
)
|
507 |
|
508 |
+
with gr.Blocks(title="🎬 Generador de Videos IA", theme=gr.themes.Soft()) as demo:
|
509 |
+
gr.Markdown("""
|
510 |
+
# 🎬 Generador de Videos con IA
|
511 |
+
|
512 |
+
Crea videos profesionales a partir de texto usando:
|
513 |
+
- **Edge TTS** para voz en español
|
514 |
+
- **GPT-2** para generación de guiones
|
515 |
+
- **Pexels API** para videos de stock
|
516 |
+
|
517 |
+
El progreso se mostrará en tiempo real.
|
518 |
+
""")
|
519 |
+
|
520 |
with gr.Row():
|
521 |
+
with gr.Column(scale=2):
|
522 |
+
gr.Markdown("### ⚙️ Configuración")
|
523 |
+
|
524 |
+
mode_radio = gr.Radio(
|
525 |
+
choices=["Generar Guion con IA", "Usar Mi Guion"],
|
526 |
+
value="Generar Guion con IA",
|
527 |
+
label="Método de creación"
|
528 |
)
|
529 |
+
|
530 |
+
topic_input = gr.Textbox(
|
531 |
+
label="💡 Tema para la IA",
|
532 |
+
placeholder="Ej: Los misterios del océano profundo",
|
533 |
+
lines=2
|
534 |
+
)
|
535 |
+
|
536 |
+
script_input = gr.Textbox(
|
537 |
+
label="📝 Tu Guion Completo",
|
538 |
+
placeholder="Escribe aquí tu guion personalizado...",
|
539 |
+
lines=8,
|
540 |
+
visible=False
|
541 |
+
)
|
542 |
+
|
543 |
+
music_input = gr.Audio(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
544 |
type="filepath",
|
545 |
+
label="🎵 Música de fondo (opcional)"
|
|
|
|
|
546 |
)
|
547 |
+
|
548 |
+
generate_btn = gr.Button(
|
549 |
+
"🎬 Generar Video",
|
550 |
+
variant="primary",
|
551 |
+
size="lg"
|
|
|
|
|
|
|
552 |
)
|
553 |
+
|
554 |
+
with gr.Column(scale=2):
|
555 |
+
gr.Markdown("### 📊 Progreso y Resultados")
|
556 |
+
|
557 |
+
progress_output = gr.Textbox(
|
558 |
+
label="📋 Log de progreso en tiempo real",
|
559 |
+
lines=12,
|
|
|
560 |
interactive=False,
|
561 |
+
show_copy_button=True
|
562 |
+
)
|
563 |
+
|
564 |
+
video_output = gr.Video(
|
565 |
+
label="🎥 Video generado",
|
566 |
height=400
|
|
|
567 |
)
|
568 |
+
|
569 |
+
download_output = gr.File(
|
570 |
+
label="📥 Descargar archivo"
|
|
|
|
|
571 |
)
|
572 |
+
|
573 |
+
mode_radio.change(
|
574 |
+
fn=toggle_input_fields,
|
575 |
+
inputs=[mode_radio],
|
576 |
+
outputs=[topic_input, script_input]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
577 |
)
|
578 |
+
|
|
|
579 |
generate_btn.click(
|
580 |
+
fn=generate_video_with_progress,
|
581 |
+
inputs=[mode_radio, topic_input, script_input, music_input],
|
582 |
+
outputs=[progress_output, video_output, download_output]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
583 |
)
|
584 |
+
|
|
|
|
|
585 |
gr.Markdown("""
|
586 |
+
### 📋 Instrucciones:
|
587 |
+
1. **Elige el método**: Genera un guion con IA o usa el tuyo propio
|
588 |
+
2. **Configura el contenido**: Ingresa un tema interesante o tu guion
|
589 |
+
3. **Música opcional**: Sube un archivo de audio para fondo musical
|
590 |
+
4. **Genera**: Presiona el botón y observa el progreso en tiempo real
|
591 |
+
|
592 |
+
⏱️ **Tiempo estimado**: 2-5 minutos dependiendo de la duración del contenido.
|
|
|
593 |
""")
|
|
|
|
|
594 |
|
595 |
if __name__ == "__main__":
|
596 |
+
logger.info("🚀 Iniciando aplicación Generador de Videos IA...")
|
597 |
+
demo.queue(max_size=10)
|
598 |
+
demo.launch(
|
599 |
+
server_name="0.0.0.0",
|
600 |
+
server_port=7860,
|
601 |
+
show_api=False,
|
602 |
+
share=True
|
603 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|