gnosticdev commited on
Commit
1bc4dcb
·
verified ·
1 Parent(s): cffb02c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +697 -1086
app.py CHANGED
@@ -1,405 +1,160 @@
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
- # Importación correcta
13
- from moviepy.editor import VideoFileClip, concatenate_videoclips, AudioFileClip, CompositeAudioClip, concatenate_audioclips, AudioClip
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  import re
15
  import math
 
16
  import shutil
17
- import json
18
- from collections import Counter
 
 
19
 
20
- # Configuración de logging
21
- logging.basicConfig(
22
- level=logging.DEBUG,
23
- format='%(asctime)s - %(levelname)s - %(message)s',
24
- handlers=[
25
- logging.StreamHandler(),
26
- logging.FileHandler('video_generator_full.log', encoding='utf-8')
27
- ]
28
- )
 
 
29
  logger = logging.getLogger(__name__)
30
- logger.info("="*80)
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.critical("NO SE ENCONTRÓ PEXELS_API_KEY EN VARIABLES DE ENTORNO")
133
- # raise ValueError("API key de Pexels no configurada")
134
-
135
- # Inicialización de modelos
136
- MODEL_NAME = "datificate/gpt2-small-spanish"
137
- logger.info(f"Inicializando modelo GPT-2: {MODEL_NAME}")
138
- tokenizer = None
139
- model = None
140
- try:
141
- tokenizer = GPT2Tokenizer.from_pretrained(MODEL_NAME)
142
- model = GPT2LMHeadModel.from_pretrained(MODEL_NAME).eval()
143
- if tokenizer.pad_token is None:
144
- tokenizer.pad_token = tokenizer.eos_token
145
- logger.info(f"Modelo GPT-2 cargado | Vocabulario: {len(tokenizer)} tokens")
146
- except Exception as e:
147
- logger.error(f"FALLA CRÍTICA al cargar GPT-2: {str(e)}", exc_info=True)
148
- tokenizer = model = None
149
-
150
- logger.info("Cargando modelo KeyBERT...")
151
- kw_model = None
152
- try:
153
- kw_model = KeyBERT('distilbert-base-multilingual-cased')
154
- logger.info("KeyBERT inicializado correctamente")
155
- except Exception as e:
156
- logger.error(f"FALLA al cargar KeyBERT: {str(e)}", exc_info=True)
157
- kw_model = None
158
-
159
- def buscar_videos_pexels(query, api_key, per_page=5):
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
- inputs = tokenizer(ai_prompt, return_tensors="pt", truncation=True, max_length=512)
207
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
208
- model.to(device)
209
- inputs = {k: v.to(device) for k, v in inputs.items()}
210
-
211
- outputs = model.generate(
 
212
  **inputs,
213
- max_length=max_length + inputs[list(inputs.keys())[0]].size(1),
214
  do_sample=True,
215
  top_p=0.9,
216
  top_k=40,
217
  temperature=0.7,
218
- repetition_penalty=1.2,
219
- pad_token_id=tokenizer.pad_token_id,
220
- eos_token_id=tokenizer.eos_token_id,
221
- no_repeat_ngram_size=3
222
  )
223
-
224
- text = tokenizer.decode(outputs[0], skip_special_tokens=True)
225
-
226
- cleaned_text = text.strip()
227
- # Limpieza mejorada de la frase de instrucción
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 guion con GPT-2 (fuera del bloque de limpieza): {str(e)}", exc_info=True)
280
- logger.warning("Usando prompt original como guion debido al error de generación.")
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
- communicate = edge_tts.Communicate(text, voice)
292
- await communicate.save(output_path)
293
-
294
- if os.path.exists(output_path) and os.path.getsize(output_path) > 100:
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(f"TTS guardó un archivo pequeño o vacío en: {output_path}")
299
  return False
300
-
301
  except Exception as e:
302
- logger.error(f"Error en TTS con voz '{voice}': {str(e)}", exc_info=True)
303
  return False
304
 
305
- def download_video_file(url, temp_dir):
306
- if not url:
307
- logger.warning("URL de video no proporcionada para descargar")
308
- return None
309
-
310
  try:
311
- logger.info(f"Descargando video desde: {url[:80]}...")
312
- os.makedirs(temp_dir, exist_ok=True)
313
- file_name = f"video_dl_{datetime.now().strftime('%Y%m%d_%H%M%S_%f')}.mp4"
314
- output_path = os.path.join(temp_dir, file_name)
315
-
316
- with requests.get(url, stream=True, timeout=60) as r:
317
- r.raise_for_status()
318
- with open(output_path, 'wb') as f:
319
- for chunk in r.iter_content(chunk_size=8192):
320
- f.write(chunk)
321
-
322
- if os.path.exists(output_path) and os.path.getsize(output_path) > 1000:
323
- logger.info(f"Video descargado exitosamente: {output_path} | Tamaño: {os.path.getsize(output_path)} bytes")
324
- return output_path
325
- else:
326
- logger.warning(f"Descarga parece incompleta o vacía para {url[:80]}... Archivo: {output_path} Tamaño: {os.path.getsize(output_path) if os.path.exists(output_path) else 'N/A'} bytes")
327
- if os.path.exists(output_path):
328
- os.remove(output_path)
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 inesperado descargando {url[:80]}... : {str(e)}", exc_info=True)
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
- audio_segments = [audio_clip] * loops
364
- looped_audio = None
365
- final_looped_audio = None
366
- try:
367
- looped_audio = concatenate_audioclips(audio_segments)
368
-
369
- if looped_audio.duration is None or looped_audio.duration <= 0:
370
- logger.error("Concatenated audio clip is invalid (None or zero duration).")
371
- raise ValueError("Invalid concatenated audio.")
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 concatenating/subclipping audio clips for looping: {str(e)}", exc_info=True)
383
- try:
384
- if audio_clip.duration is not None and audio_clip.duration > 0:
385
- logger.warning("Returning original audio clip (may be too short).")
386
- return audio_clip.subclip(0, min(audio_clip.duration, target_duration))
387
- except:
388
- pass
389
- logger.error("Fallback to original audio clip failed.")
390
- return AudioFileClip(filename="")
391
-
392
- finally:
393
- if looped_audio is not None and looped_audio is not final_looped_audio:
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 ["mystery", "conspiracy", "alien", "UFO", "secret", "cover-up", "illusion", "paranoia",
403
  "secret society", "lie", "simulation", "matrix", "terror", "darkness", "shadow", "enigma",
404
  "urban legend", "unknown", "hidden", "mistrust", "experiment", "government", "control",
405
  "surveillance", "propaganda", "deception", "whistleblower", "anomaly", "extraterrestrial",
@@ -407,53 +162,9 @@ def extract_visual_keywords_from_script(script_text):
407
  "disinformation", "false flag", "assassin", "black ops", "anomaly", "men in black", "abduction",
408
  "hybrid", "ancient aliens", "hollow earth", "simulation theory", "alternate reality", "predictive programming",
409
  "symbolism", "occult", "eerie", "haunting", "unexplained", "forbidden knowledge", "redacted", "conspiracy theorist"]
410
-
411
- clean_text = re.sub(r'[^\w\sáéíóúñÁÉÍÓÚÑ]', '', script_text)
412
- keywords_list = []
413
-
414
- if kw_model:
415
- try:
416
- logger.debug("Intentando extracción con KeyBERT...")
417
- keywords1 = kw_model.extract_keywords(clean_text, keyphrase_ngram_range=(1, 1), stop_words='spanish', top_n=5)
418
- keywords2 = kw_model.extract_keywords(clean_text, keyphrase_ngram_range=(2, 2), stop_words='spanish', top_n=3)
419
-
420
- all_keywords = keywords1 + keywords2
421
- all_keywords.sort(key=lambda item: item[1], reverse=True)
422
-
423
- seen_keywords = set()
424
- for keyword, score in all_keywords:
425
- formatted_keyword = keyword.lower().replace(" ", "+")
426
- if formatted_keyword and formatted_keyword not in seen_keywords:
427
- keywords_list.append(formatted_keyword)
428
- seen_keywords.add(formatted_keyword)
429
- if len(keywords_list) >= 5:
430
- break
431
-
432
- if keywords_list:
433
- logger.debug(f"Palabras clave extraídas por KeyBERT: {keywords_list}")
434
- return keywords_list
435
-
436
- except Exception as e:
437
- logger.warning(f"KeyBERT falló: {str(e)}. Intentando método simple.")
438
-
439
- logger.debug("Extrayendo palabras clave con método simple...")
440
- words = clean_text.lower().split()
441
- 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",
442
- "nuestro", "vuestro", "este", "ese", "aquel", "esta", "esa", "aquella", "esto", "eso", "aquello", "mis", "tus",
443
- "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á"}
444
-
445
- valid_words = [word for word in words if len(word) > 3 and word not in stop_words]
446
-
447
- if not valid_words:
448
- logger.warning("No se encontraron palabras clave válidas con método simple. Usando palabras clave predeterminadas.")
449
- return ["naturaleza", "ciudad", "paisaje"]
450
-
451
- word_counts = Counter(valid_words)
452
- top_keywords = [word.replace(" ", "+") for word, _ in word_counts.most_common(5)]
453
-
454
- if not top_keywords:
455
- logger.warning("El método simple no produjo keywords. Usando palabras clave predeterminadas.")
456
- return ["mystery", "conspiracy", "alien", "UFO", "secret", "cover-up", "illusion", "paranoia",
457
  "secret society", "lie", "simulation", "matrix", "terror", "darkness", "shadow", "enigma",
458
  "urban legend", "unknown", "hidden", "mistrust", "experiment", "government", "control",
459
  "surveillance", "propaganda", "deception", "whistleblower", "anomaly", "extraterrestrial",
@@ -462,718 +173,618 @@ def extract_visual_keywords_from_script(script_text):
462
  "hybrid", "ancient aliens", "hollow earth", "simulation theory", "alternate reality", "predictive programming",
463
  "symbolism", "occult", "eerie", "haunting", "unexplained", "forbidden knowledge", "redacted", "conspiracy theorist"]
464
 
465
- logger.info(f"Palabras clave finales: {top_keywords}")
466
- return top_keywords
467
-
468
- # crear_video ahora recibe la voz seleccionada
469
- def crear_video(prompt_type, input_text, selected_voice, musica_file=None):
470
- logger.info("="*80)
471
- logger.info(f"INICIANDO CREACIÓN DE VIDEO | Tipo: {prompt_type}")
472
- logger.debug(f"Input: '{input_text[:100]}...'")
473
- logger.info(f"Voz seleccionada: {selected_voice}")
474
-
475
- start_time = datetime.now()
476
- temp_dir_intermediate = None
477
-
478
- audio_tts_original = None
479
- musica_audio_original = None
480
- audio_tts = None
481
- musica_audio = None
482
- video_base = None
483
- video_final = None
484
- source_clips = []
485
- clips_to_concatenate = []
486
 
 
487
  try:
488
- # 1. Generar o usar guion
489
- if prompt_type == "Generar Guion con IA":
490
- guion = generate_script(input_text)
 
 
 
 
 
 
 
 
491
  else:
492
- guion = input_text.strip()
493
-
494
- logger.info(f"Guion final ({len(guion)} chars): '{guion[:100]}...'")
495
-
496
- if not guion.strip():
497
- logger.error("El guion resultante está vacío o solo contiene espacios.")
498
- raise ValueError("El guion está vacío.")
499
-
500
- temp_dir_intermediate = tempfile.mkdtemp(prefix="video_gen_intermediate_")
501
- logger.info(f"Directorio temporal intermedio creado: {temp_dir_intermediate}")
502
- temp_intermediate_files = []
503
-
504
- # 2. Generar audio de voz usando la voz seleccionada, con reintentos si falla
505
- logger.info("Generando audio de voz...")
506
- voz_path = os.path.join(temp_dir_intermediate, "voz.mp3")
507
-
508
- tts_voices_to_try = [selected_voice]
509
- fallback_juan = "es-ES-JuanNeural"
510
- fallback_elvira = "es-ES-ElviraNeural"
511
-
512
- if fallback_juan and fallback_juan != selected_voice and fallback_juan not in tts_voices_to_try:
513
- tts_voices_to_try.append(fallback_juan)
514
- if fallback_elvira and fallback_elvira != selected_voice and fallback_elvira not in tts_voices_to_try:
515
- tts_voices_to_try.append(fallback_elvira)
516
-
517
- tts_success = False
518
- tried_voices = set()
519
-
520
- for current_voice in tts_voices_to_try:
521
- if not current_voice or current_voice in tried_voices: continue
522
- tried_voices.add(current_voice)
523
 
524
- logger.info(f"Intentando TTS con voz: {current_voice}...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
525
  try:
526
- tts_success = asyncio.run(text_to_speech(guion, voz_path, voice=current_voice))
527
- if tts_success:
528
- logger.info(f"TTS exitoso con voz '{current_voice}'.")
529
- break
 
 
 
 
 
 
 
 
 
 
 
 
 
530
  except Exception as e:
531
- logger.warning(f"Fallo al generar TTS con voz '{current_voice}': {str(e)}", exc_info=True)
532
- pass
533
-
534
- if not tts_success or not os.path.exists(voz_path) or os.path.getsize(voz_path) <= 100:
535
- 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.")
536
- raise ValueError("Error generando voz a partir del guion (fallo de TTS).")
537
-
538
- temp_intermediate_files.append(voz_path)
539
-
540
- audio_tts_original = AudioFileClip(voz_path)
541
-
542
- if audio_tts_original.reader is None or audio_tts_original.duration is None or audio_tts_original.duration <= 0:
543
- logger.critical("Clip de audio TTS inicial es inválido (reader is None o duración <= 0) *después* de crear AudioFileClip.")
544
- try: audio_tts_original.close()
545
- except: pass
546
- audio_tts_original = None
547
- if os.path.exists(voz_path):
548
- try: os.remove(voz_path)
549
- except: pass
550
- if voz_path in temp_intermediate_files:
551
- temp_intermediate_files.remove(voz_path)
552
-
553
- raise ValueError("Audio de voz generado es inválido después de procesamiento inicial.")
554
-
555
- audio_tts = audio_tts_original
556
- audio_duration = audio_tts_original.duration
557
- logger.info(f"Duración audio voz: {audio_duration:.2f} segundos")
558
 
559
- if audio_duration < 1.0:
560
- logger.error(f"Duración audio voz ({audio_duration:.2f}s) es muy corta.")
561
- raise ValueError("Generated voice audio is too short (min 1 second required).")
562
- # 3. Extraer palabras clave
563
- logger.info("Extrayendo palabras clave...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
564
  try:
565
- keywords = extract_visual_keywords_from_script(guion)
566
- logger.info(f"Palabras clave identificadas: {keywords}")
 
 
 
567
  except Exception as e:
568
- logger.error(f"Error extrayendo keywords: {str(e)}", exc_info=True)
569
- keywords = ["naturaleza", "paisaje"]
570
-
571
- if not keywords:
572
- keywords = ["video", "background"]
573
-
574
- # 4. Buscar y descargar videos
575
- logger.info("Buscando videos en Pexels...")
576
- videos_data = []
577
- total_desired_videos = 10
578
- per_page_per_keyword = max(1, total_desired_videos // len(keywords))
579
-
580
- for keyword in keywords:
581
- if len(videos_data) >= total_desired_videos: break
582
- try:
583
- videos = buscar_videos_pexels(keyword, PEXELS_API_KEY, per_page=per_page_per_keyword)
584
- if videos:
585
- videos_data.extend(videos)
586
- logger.info(f"Encontrados {len(videos)} videos para '{keyword}'. Total data: {len(videos_data)}")
587
- except Exception as e:
588
- logger.warning(f"Error buscando videos para '{keyword}': {str(e)}")
589
-
590
- if len(videos_data) < total_desired_videos / 2:
591
- logger.warning(f"Pocos videos encontrados ({len(videos_data)}). Intentando con palabras clave genéricas.")
592
- generic_keywords = ["nature", "city", "background", "abstract"]
593
- for keyword in generic_keywords:
594
- if len(videos_data) >= total_desired_videos: break
595
- try:
596
- videos = buscar_videos_pexels(keyword, PEXELS_API_KEY, per_page=2)
597
- if videos:
598
- videos_data.extend(videos)
599
- logger.info(f"Encontrados {len(videos)} videos para '{keyword}' (genérico). Total data: {len(videos_data)}")
600
- except Exception as e:
601
- logger.warning(f"Error buscando videos genéricos para '{keyword}': {str(e)}")
602
-
603
- if not videos_data:
604
- logger.error("No se encontraron videos en Pexels para ninguna palabra clave.")
605
- raise ValueError("No se encontraron videos adecuados en Pexels.")
606
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
607
  video_paths = []
608
- logger.info(f"Intentando descargar {len(videos_data)} videos encontrados...")
609
- for video in videos_data:
610
- if 'video_files' not in video or not video['video_files']:
611
- logger.debug(f"Saltando video sin archivos de video: {video.get('id')}")
612
- continue
613
-
614
- try:
615
- best_quality = None
616
- for vf in sorted(video['video_files'], key=lambda x: x.get('width', 0) * x.get('height', 0), reverse=True):
617
- if 'link' in vf:
618
- best_quality = vf
619
- break
620
-
621
- if best_quality and 'link' in best_quality:
622
- path = download_video_file(best_quality['link'], temp_dir_intermediate)
623
- if path:
624
- video_paths.append(path)
625
- temp_intermediate_files.append(path)
626
- logger.info(f"Video descargado OK desde {best_quality['link'][:50]}...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
627
  else:
628
- logger.warning(f"No se pudo descargar video desde {best_quality['link'][:50]}...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
629
  else:
630
- logger.warning(f"No se encontró enlace de descarga válido para video {video.get('id')}.")
631
-
632
- except Exception as e:
633
- logger.warning(f"Error procesando/descargando video {video.get('id')}: {str(e)}")
634
-
635
- logger.info(f"Descargados {len(video_paths)} archivos de video utilizables.")
636
- if not video_paths:
637
- logger.error("No se pudo descargar ningún archivo de video utilizable.")
638
- raise ValueError("No se pudo descargar ningún video utilizable de Pexels.")
639
-
640
- # 5. Procesar y concatenar clips de video
641
- logger.info("Procesando y concatenando videos descargados...")
642
- current_duration = 0
643
- min_clip_duration = 0.5
644
- max_clip_segment = 10.0
645
-
646
- for i, path in enumerate(video_paths):
647
- if current_duration >= audio_duration + max_clip_segment:
648
- 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.")
649
- break
650
-
651
- clip = None
 
 
 
 
 
652
  try:
653
- logger.debug(f"[{i+1}/{len(video_paths)}] Abriendo clip: {path}")
654
- clip = VideoFileClip(path)
655
- source_clips.append(clip)
656
-
657
- if clip.reader is None or clip.duration is None or clip.duration <= 0:
658
- logger.warning(f"[{i+1}/{len(video_paths)}] Clip fuente {path} parece inválido (reader is None o duración <= 0). Saltando.")
659
- continue
660
-
661
- remaining_needed = audio_duration - current_duration
662
- potential_use_duration = min(clip.duration, max_clip_segment)
663
-
664
- if remaining_needed > 0:
665
- segment_duration = min(potential_use_duration, remaining_needed + min_clip_duration)
666
- segment_duration = max(min_clip_duration, segment_duration)
667
- segment_duration = min(segment_duration, clip.duration)
668
-
669
- if segment_duration >= min_clip_duration:
670
- try:
671
- sub = clip.subclip(0, segment_duration)
672
- if sub.reader is None or sub.duration is None or sub.duration <= 0:
673
- logger.warning(f"[{i+1}/{len(video_paths)}] Subclip generado de {path} es inválido. Saltando.")
674
- try: sub.close()
675
- except: pass
676
- continue
677
-
678
- clips_to_concatenate.append(sub)
679
- current_duration += sub.duration
680
- logger.debug(f"[{i+1}/{len(video_paths)}] Segmento añadido: {sub.duration:.1f}s (total video: {current_duration:.1f}/{audio_duration:.1f}s)")
681
-
682
- except Exception as sub_e:
683
- logger.warning(f"[{i+1}/{len(video_paths)}] Error creando subclip de {path} ({segment_duration:.1f}s): {str(sub_e)}")
684
- continue
685
- else:
686
- 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.")
687
  else:
688
- logger.debug(f"[{i+1}/{len(video_paths)}] Duración de video base ya alcanzada. Saltando clip.")
689
-
 
690
  except Exception as e:
691
- logger.warning(f"[{i+1}/{len(video_paths)}] Error procesando video {path}: {str(e)}", exc_info=True)
692
- continue
693
-
694
- logger.info(f"Procesamiento de clips fuente finalizado. Se obtuvieron {len(clips_to_concatenate)} segmentos válidos.")
695
-
696
- if not clips_to_concatenate:
697
- logger.error("No hay segmentos de video válidos disponibles para crear la secuencia.")
698
- raise ValueError("No hay segmentos de video válidos disponibles para crear el video.")
699
-
700
- logger.info(f"Concatenando {len(clips_to_concatenate)} segmentos de video.")
701
- concatenated_base = None
702
  try:
703
- concatenated_base = concatenate_videoclips(clips_to_concatenate, method="chain")
704
- logger.info(f"Duración video base después de concatenación inicial: {concatenated_base.duration:.2f}s")
705
-
706
- if concatenated_base is None or concatenated_base.duration is None or concatenated_base.duration <= 0:
707
- logger.critical("Video base concatenado es inválido después de la primera concatenación (None o duración cero).")
708
- raise ValueError("Fallo al crear video base válido a partir de segmentos.")
709
-
 
 
710
  except Exception as e:
711
- logger.critical(f"Error durante la concatenación inicial: {str(e)}", exc_info=True)
712
- raise ValueError("Fallo durante la concatenación de video inicial.")
713
- finally:
714
- for clip_segment in clips_to_concatenate:
715
- try: clip_segment.close()
716
- except: pass
717
- clips_to_concatenate = []
718
-
719
- video_base = concatenated_base
720
-
721
- final_video_base = video_base
722
-
723
- if final_video_base.duration < audio_duration:
724
- logger.info(f"Video base ({final_video_base.duration:.2f}s) es más corto que el audio ({audio_duration:.2f}s). Repitiendo...")
725
-
726
- num_full_repeats = int(audio_duration // final_video_base.duration)
727
- remaining_duration = audio_duration % final_video_base.duration
728
-
729
- repeated_clips_list = [final_video_base] * num_full_repeats
730
- if remaining_duration > 0:
731
- try:
732
- remaining_clip = final_video_base.subclip(0, remaining_duration)
733
- if remaining_clip is None or remaining_clip.duration is None or remaining_clip.duration <= 0:
734
- logger.warning(f"Subclip generado para duración restante {remaining_duration:.2f}s es inválido. Saltando.")
735
- try: remaining_clip.close()
736
- except: pass
737
- else:
738
- repeated_clips_list.append(remaining_clip)
739
- logger.debug(f"Añadiendo segmento restante: {remaining_duration:.2f}s")
740
-
741
- except Exception as e:
742
- logger.warning(f"Error creando subclip para duración restante {remaining_duration:.2f}s: {str(e)}")
743
-
744
- if repeated_clips_list:
745
- logger.info(f"Concatenando {len(repeated_clips_list)} partes para repetición.")
746
- video_base_repeated = None
747
- try:
748
- video_base_repeated = concatenate_videoclips(repeated_clips_list, method="chain")
749
- logger.info(f"Duración del video base repetido: {video_base_repeated.duration:.2f}s")
750
-
751
- if video_base_repeated is None or video_base_repeated.duration is None or video_base_repeated.duration <= 0:
752
- logger.critical("Video base repetido concatenado es inválido.")
753
- raise ValueError("Fallo al crear video base repetido válido.")
754
-
755
- if final_video_base is not video_base_repeated:
756
- try: final_video_base.close()
757
- except: pass
758
-
759
- final_video_base = video_base_repeated
760
-
761
- except Exception as e:
762
- logger.critical(f"Error durante la concatenación de repetición: {str(e)}", exc_info=True)
763
- raise ValueError("Fallo durante la repetición de video.")
764
- finally:
765
- if 'repeated_clips_list' in locals():
766
- for clip in repeated_clips_list:
767
- if clip is not final_video_base:
768
- try: clip.close()
769
- except: pass
770
-
771
-
772
- if final_video_base.duration > audio_duration:
773
- 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).")
774
- trimmed_video_base = None
775
- try:
776
- trimmed_video_base = final_video_base.subclip(0, audio_duration)
777
- if trimmed_video_base is None or trimmed_video_base.duration is None or trimmed_video_base.duration <= 0:
778
- logger.critical("Video base recortado es inválido.")
779
- raise ValueError("Fallo al crear video base recortado válido.")
780
-
781
- if final_video_base is not trimmed_video_base:
782
- try: final_video_base.close()
783
- except: pass
784
-
785
- final_video_base = trimmed_video_base
786
-
787
- except Exception as e:
788
- logger.critical(f"Error durante el recorte: {str(e)}", exc_info=True)
789
- raise ValueError("Fallo durante el recorte de video.")
790
-
791
-
792
- if final_video_base is None or final_video_base.duration is None or final_video_base.duration <= 0:
793
- logger.critical("Video base final es inválido antes de audio/escritura (None o duración cero).")
794
- raise ValueError("Video base final es inválido.")
795
-
796
- if final_video_base.size is None or final_video_base.size[0] <= 0 or final_video_base.size[1] <= 0:
797
- logger.critical(f"Video base final tiene tamaño inválido: {final_video_base.size}. No se puede escribir video.")
798
- raise ValueError("Video base final tiene tamaño inválido antes de escribir.")
799
-
800
- video_base = final_video_base
801
-
802
- # 6. Manejar música de fondo
803
- logger.info("Procesando audio...")
804
-
805
- final_audio = audio_tts_original
806
-
807
- musica_audio_looped = None
808
-
809
- if musica_file:
810
- musica_audio_original = None
811
  try:
812
- music_path = os.path.join(temp_dir_intermediate, "musica_bg.mp3")
813
- shutil.copyfile(musica_file, music_path)
814
- temp_intermediate_files.append(music_path)
815
- logger.info(f"Música de fondo copiada a: {music_path}")
816
-
817
- musica_audio_original = AudioFileClip(music_path)
818
-
819
- if musica_audio_original.reader is None or musica_audio_original.duration is None or musica_audio_original.duration <= 0:
820
- logger.warning("Clip de música de fondo parece inválido o tiene duración cero. Saltando música.")
821
- try: musica_audio_original.close()
822
- except: pass
823
- musica_audio_original = None
824
- else:
825
- musica_audio_looped = loop_audio_to_length(musica_audio_original, video_base.duration)
826
- logger.debug(f"Música ajustada a duración del video: {musica_audio_looped.duration:.2f}s")
827
-
828
- if musica_audio_looped is None or musica_audio_looped.duration is None or musica_audio_looped.duration <= 0:
829
- logger.warning("Clip de música de fondo loopeado es inválido. Saltando música.")
830
- try: musica_audio_looped.close()
831
- except: pass
832
- musica_audio_looped = None
833
-
834
-
835
- if musica_audio_looped:
836
- composite_audio = CompositeAudioClip([
837
- musica_audio_looped.volumex(0.2), # Volumen 20% para música
838
- audio_tts_original.volumex(1.0) # Volumen 100% para voz
839
- ])
840
-
841
- if composite_audio.duration is None or composite_audio.duration <= 0:
842
- logger.warning("Clip de audio compuesto es inválido (None o duración cero). Usando solo audio de voz.")
843
- try: composite_audio.close()
844
- except: pass
845
- final_audio = audio_tts_original
846
- else:
847
- logger.info("Mezcla de audio completada (voz + música).")
848
- final_audio = composite_audio
849
- musica_audio = musica_audio_looped # Asignar para limpieza
850
-
851
  except Exception as e:
852
- logger.warning(f"Error procesando música de fondo: {str(e)}", exc_info=True)
853
- final_audio = audio_tts_original
854
- musica_audio = None
855
- logger.warning("Usando solo audio de voz debido a un error con la música.")
856
-
857
-
858
- if final_audio.duration is not None and abs(final_audio.duration - video_base.duration) > 0.2:
859
- logger.warning(f"Duración del audio final ({final_audio.duration:.2f}s) difiere significativamente del video base ({video_base.duration:.2f}s). Intentando recorte.")
 
860
  try:
861
- if final_audio.duration > video_base.duration:
862
- trimmed_final_audio = final_audio.subclip(0, video_base.duration)
863
- if trimmed_final_audio is None or trimmed_final_audio.duration <= 0:
864
- logger.warning("Audio final recortado es inválido. Usando audio final original.")
865
- try: trimmed_final_audio.close()
866
- except: pass
867
- else:
868
- if final_audio is not trimmed_final_audio:
869
- try: final_audio.close()
870
- except: pass
871
- final_audio = trimmed_final_audio
872
- logger.warning("Audio final recortado para que coincida con la duración del video.")
873
  except Exception as e:
874
- logger.warning(f"Error ajustando duración del audio final: {str(e)}")
875
-
876
- # 7. Crear video final
877
- logger.info("Renderizando video final...")
878
- video_final = video_base.set_audio(final_audio)
879
-
880
- if video_final is None or video_final.duration is None or video_final.duration <= 0:
881
- logger.critical("Clip de video final (con audio) es inválido antes de escribir (None o duración cero).")
882
- raise ValueError("Clip de video final es inválido antes de escribir.")
883
-
884
- output_filename = "final_video.mp4"
885
- output_path = os.path.join(temp_dir_intermediate, output_filename)
886
- logger.info(f"Escribiendo video final a: {output_path}")
887
-
888
- video_final.write_videofile(
889
  output_path,
890
- fps=24,
891
- threads=4,
892
  codec="libx264",
893
  audio_codec="aac",
894
- preset="medium",
895
- logger='bar'
 
 
 
896
  )
897
-
898
- total_time = (datetime.now() - start_time).total_seconds()
899
- logger.info(f"PROCESO DE VIDEO FINALIZADO | Output: {output_path} | Tiempo total: {total_time:.2f}s")
900
-
 
 
 
 
 
901
  return output_path
902
-
903
- except ValueError as ve:
904
- logger.error(f"ERROR CONTROLADO en crear_video: {str(ve)}")
905
- raise ve
906
  except Exception as e:
907
- logger.critical(f"ERROR CRÍTICO NO CONTROLADO en crear_video: {str(e)}", exc_info=True)
908
- raise e
909
  finally:
910
- logger.info("Iniciando limpieza de clips y archivos temporales intermedios...")
911
-
912
- for clip in source_clips:
913
- try:
914
- clip.close()
915
- except Exception as e:
916
- logger.warning(f"Error cerrando clip de video fuente en finally: {str(e)}")
917
-
918
- for clip_segment in clips_to_concatenate:
919
- try:
920
- clip_segment.close()
921
- except Exception as e:
922
- logger.warning(f"Error cerrando segmento de video en finally: {str(e)}")
923
-
924
- if musica_audio is not None:
925
- try:
926
- musica_audio.close()
927
- except Exception as e:
928
- logger.warning(f"Error cerrando musica_audio (procesada) en finally: {str(e)}")
929
-
930
- if musica_audio_original is not None and musica_audio_original is not musica_audio:
931
- try:
932
- musica_audio_original.close()
933
- except Exception as e:
934
- logger.warning(f"Error cerrando musica_audio_original en finally: {str(e)}")
935
-
936
- if audio_tts is not None and audio_tts is not audio_tts_original:
937
- try:
938
- audio_tts.close()
939
- except Exception as e:
940
- logger.warning(f"Error cerrando audio_tts (procesada) en finally: {str(e)}")
941
-
942
- if audio_tts_original is not None:
943
- try:
944
- audio_tts_original.close()
945
- except Exception as e:
946
- logger.warning(f"Error cerrando audio_tts_original en finally: {str(e)}")
947
-
948
- if video_final is not None:
949
- try:
950
- video_final.close()
951
- except Exception as e:
952
- logger.warning(f"Error cerrando video_final en finally: {str(e)}")
953
- elif video_base is not None and video_base is not video_final:
954
- try:
955
- video_base.close()
956
- except Exception as e:
957
- logger.warning(f"Error cerrando video_base en finally: {str(e)}")
958
-
959
- if temp_dir_intermediate and os.path.exists(temp_dir_intermediate):
960
- final_output_in_temp = os.path.join(temp_dir_intermediate, "final_video.mp4")
961
-
962
- for path in temp_intermediate_files:
963
- try:
964
- if os.path.isfile(path) and path != final_output_in_temp:
965
- logger.debug(f"Eliminando archivo temporal intermedio: {path}")
966
- os.remove(path)
967
- elif os.path.isfile(path) and path == final_output_in_temp:
968
- logger.debug(f"Saltando eliminación del archivo de video final: {path}")
969
- except Exception as e:
970
- logger.warning(f"No se pudo eliminar archivo temporal intermedio {path}: {str(e)}")
971
-
972
- logger.info(f"Directorio temporal intermedio {temp_dir_intermediate} persistirá para que Gradio lea el video final.")
973
-
974
-
975
- # run_app ahora recibe todos los inputs, incluyendo la voz seleccionada
976
- def run_app(prompt_type, prompt_ia, prompt_manual, musica_file, selected_voice): # <-- Recibe el valor del Dropdown
977
- logger.info("="*80)
978
- logger.info("SOLICITUD RECIBIDA EN INTERFAZ")
979
-
980
- # Elegir el texto de entrada basado en el prompt_type
981
- input_text = prompt_ia if prompt_type == "Generar Guion con IA" else prompt_manual
982
-
983
- output_video = None
984
- output_file = None
985
- status_msg = gr.update(value="⏳ Procesando...", interactive=False)
986
-
987
- if not input_text or not input_text.strip():
988
- logger.warning("Texto de entrada vacío.")
989
- # Retornar None para video y archivo, actualizar estado con mensaje de error
990
- return None, None, gr.update(value="⚠️ Por favor, ingresa texto para el guion o el tema.", interactive=False)
991
-
992
- # Validar la voz seleccionada. Si no es válida, usar la por defecto.
993
- # AVAILABLE_VOICES se obtiene al inicio. Hay que buscar si el voice_id existe en la lista de pares (nombre, id)
994
- voice_ids_disponibles = [v[1] for v in AVAILABLE_VOICES]
995
- if selected_voice not in voice_ids_disponibles:
996
- logger.warning(f"Voz seleccionada inválida o no encontrada en la lista: '{selected_voice}'. Usando voz por defecto: {DEFAULT_VOICE_ID}.")
997
- selected_voice = DEFAULT_VOICE_ID # <-- Usar el ID de la voz por defecto
998
- else:
999
- logger.info(f"Voz seleccionada validada: {selected_voice}")
1000
-
1001
-
1002
- logger.info(f"Tipo de entrada: {prompt_type}")
1003
- logger.debug(f"Texto de entrada: '{input_text[:100]}...'")
1004
- if musica_file:
1005
- logger.info(f"Archivo de música recibido: {musica_file}")
1006
- else:
1007
- logger.info("No se proporcionó archivo de música.")
1008
- logger.info(f"Voz final a usar (ID): {selected_voice}") # Loguear el ID de la voz final
1009
 
 
1010
  try:
1011
- logger.info("Llamando a crear_video...")
1012
- # Pasar el input_text elegido, la voz seleccionada (el ID) y el archivo de música a crear_video
1013
- video_path = crear_video(prompt_type, input_text, selected_voice, musica_file) # <-- PASAR selected_voice (ID) a crear_video
1014
-
1015
- if video_path and os.path.exists(video_path):
1016
- logger.info(f"crear_video retornó path: {video_path}")
1017
- logger.info(f"Tamaño del archivo de video retornado: {os.path.getsize(video_path)} bytes")
1018
- output_video = video_path # Establecer valor del componente de video
1019
- output_file = video_path # Establecer valor del componente de archivo para descarga
1020
- status_msg = gr.update(value="✅ Video generado exitosamente.", interactive=False)
1021
- else:
1022
- logger.error(f"crear_video no retornó un path válido o el archivo no existe: {video_path}")
1023
- status_msg = gr.update(value="❌ Error: La generación del video falló o el archivo no se creó correctamente.", interactive=False)
1024
-
1025
- except ValueError as ve:
1026
- logger.warning(f"Error de validación durante la creación del video: {str(ve)}")
1027
- status_msg = gr.update(value=f"⚠️ Error de validación: {str(ve)}", interactive=False)
1028
  except Exception as e:
1029
- logger.critical(f"Error crítico durante la creación del video: {str(e)}", exc_info=True)
1030
- status_msg = gr.update(value=f"❌ Error inesperado: {str(e)}", interactive=False)
1031
- finally:
1032
- logger.info("Fin del handler run_app.")
1033
- return output_video, output_file, status_msg
1034
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1035
 
1036
- # Interfaz de Gradio
1037
- with gr.Blocks(title="Generador de Videos con IA", theme=gr.themes.Soft(), css="""
1038
- .gradio-container {max-width: 800px; margin: auto;}
1039
- h1 {text-align: center;}
1040
- """) as app:
1041
 
1042
- gr.Markdown("# 🎬 Generador Automático de Videos con IA")
1043
- gr.Markdown("Genera videos cortos a partir de un tema o guion, usando imágenes de archivo de Pexels y voz generada.")
 
 
 
 
1044
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1045
  with gr.Row():
1046
- with gr.Column():
1047
- prompt_type = gr.Radio(
1048
- ["Generar Guion con IA", "Usar Mi Guion"],
1049
- label="Método de Entrada",
1050
- value="Generar Guion con IA"
 
 
1051
  )
1052
-
1053
- # Contenedores para los campos de texto para controlar la visibilidad
1054
- with gr.Column(visible=True) as ia_guion_column:
1055
- prompt_ia = gr.Textbox(
1056
- label="Tema para IA",
1057
- lines=2,
1058
- placeholder="Ej: Un paisaje natural con montañas y ríos al amanecer, mostrando la belleza de la naturaleza...",
1059
- max_lines=4,
1060
- value=""
1061
- # visible=... <-- ¡NO DEBE ESTAR AQUÍ!
1062
- )
1063
-
1064
- with gr.Column(visible=False) as manual_guion_column:
1065
- prompt_manual = gr.Textbox(
1066
- label="Tu Guion Completo",
1067
- lines=5,
1068
- 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!",
1069
- max_lines=10,
1070
- value=""
1071
- # visible=... <-- ¡NO DEBE ESTAR AQUÍ!
1072
- )
1073
-
1074
- musica_input = gr.Audio(
1075
- label="Música de fondo (opcional)",
1076
  type="filepath",
1077
- interactive=True,
1078
- value=None
1079
- # visible=... <-- ¡NO DEBE ESTAR AQUÍ!
1080
  )
1081
-
1082
- # --- COMPONENTE: Selección de Voz ---
1083
- voice_dropdown = gr.Dropdown(
1084
- label="Seleccionar Voz para Guion",
1085
- choices=AVAILABLE_VOICES, # Usar la lista obtenida al inicio
1086
- value=DEFAULT_VOICE_ID, # Usar el ID de la voz por defecto calculada
1087
- interactive=True
1088
- # visible=... <-- ¡NO DEBE ESTAR AQUÍ!
1089
  )
1090
- # --- FIN COMPONENTE ---
1091
-
1092
-
1093
- generate_btn = gr.Button("✨ Generar Video", variant="primary")
1094
-
1095
- with gr.Column():
1096
- video_output = gr.Video(
1097
- label="Previsualización del Video Generado",
1098
  interactive=False,
1099
- height=400
1100
- # visible=... <-- ¡NO DEBE ESTAR AQUÍ!
1101
  )
1102
- file_output = gr.File(
1103
- label="Descargar Archivo de Video",
1104
- interactive=False,
1105
- visible=False # <-- ESTÁ BIEN AQUÍ
1106
- # visible=... <-- ¡NO DEBE ESTAR AQUÍ si ya está visible=False arriba!
1107
  )
1108
- status_output = gr.Textbox(
1109
- label="Estado",
1110
- interactive=False,
1111
- show_label=False,
1112
- placeholder="Esperando acción...",
1113
- value="Esperando entrada..."
1114
- # visible=... <-- ¡NO DEBE ESTAR AQUÍ!
1115
  )
1116
-
1117
- # Evento para mostrar/ocultar los campos de texto según el tipo de prompt
1118
- prompt_type.change(
1119
- lambda x: (gr.update(visible=x == "Generar Guion con IA"),
1120
- gr.update(visible=x == "Usar Mi Guion")),
1121
- inputs=prompt_type,
1122
- outputs=[ia_guion_column, manual_guion_column] # Apuntar a las Columnas contenedoras
1123
  )
1124
-
1125
- # Evento click del botón de generar video
1126
  generate_btn.click(
1127
- # Acción 1 (síncrona): Resetear salidas y establecer estado
1128
- lambda: (None, None, gr.update(value="⏳ Procesando... Esto puede tomar varios minutos.", interactive=False)),
1129
- outputs=[video_output, file_output, status_output],
1130
- queue=True, # Usar la cola de Gradio
1131
- ).then(
1132
- # Acción 2 (asíncrona): Llamar a la función principal
1133
- run_app,
1134
- # PASAR TODOS LOS INPUTS DE LA INTERFAZ que run_app espera
1135
- inputs=[prompt_type, prompt_ia, prompt_manual, musica_input, voice_dropdown], # <-- Pasar los 5 inputs a run_app
1136
- # run_app retornará los 3 outputs esperados
1137
- outputs=[video_output, file_output, status_output]
1138
- ).then(
1139
- # Acción 3 (síncrona): Hacer visible el enlace de descarga
1140
- lambda video_path, file_path, status_msg: gr.update(visible=file_path is not None),
1141
- inputs=[video_output, file_output, status_output],
1142
- outputs=[file_output]
1143
  )
1144
-
1145
-
1146
- gr.Markdown("### Instrucciones:")
1147
  gr.Markdown("""
1148
- 1. **Clave API de Pexels:** Asegúrate de haber configurado la variable de entorno `PEXELS_API_KEY` con tu clave.
1149
- 2. **Selecciona el tipo de entrada**: "Generar Guion con IA" o "Usar Mi Guion".
1150
- 3. **Sube música** (opcional): Selecciona un archivo de audio (MP3, WAV, etc.).
1151
- 4. **Selecciona la voz** deseada del desplegable.
1152
- 5. **Haz clic en "✨ Generar Video"**.
1153
- 6. Espera a que se procese el video. Verás el estado.
1154
- 7. La previsualización aparecerá si es posible, y siempre un enlace **Descargar Archivo de Video** se mostrará si la generación fue exitosa.
1155
- 8. Revisa `video_generator_full.log` para detalles si hay errores.
1156
  """)
1157
- gr.Markdown("---")
1158
- gr.Markdown("Desarrollado por [Tu Nombre/Empresa/Alias - Opcional]")
1159
 
1160
  if __name__ == "__main__":
1161
- logger.info("Verificando dependencias críticas...")
1162
- try:
1163
- from moviepy.editor import ColorClip
1164
- try:
1165
- temp_clip = ColorClip((100,100), color=(255,0,0), duration=0.1)
1166
- temp_clip.close()
1167
- logger.info("Clips base de MoviePy creados y cerrados exitosamente. FFmpeg parece accesible.")
1168
- except Exception as e:
1169
- logger.critical(f"Fallo al crear clip base de MoviePy. A menudo indica problemas con FFmpeg/ImageMagick. Error: {e}", exc_info=True)
1170
-
1171
- except Exception as e:
1172
- logger.critical(f"Fallo al importar MoviePy. Asegúrate de que está instalado. Error: {e}", exc_info=True)
1173
-
1174
- logger.info("Iniciando aplicación Gradio...")
1175
- try:
1176
- app.launch(server_name="0.0.0.0", server_port=7860, share=False)
1177
- except Exception as e:
1178
- logger.critical(f"No se pudo iniciar la app: {str(e)}", exc_info=True)
1179
- 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
  "secret society", "lie", "simulation", "matrix", "terror", "darkness", "shadow", "enigma",
159
  "urban legend", "unknown", "hidden", "mistrust", "experiment", "government", "control",
160
  "surveillance", "propaganda", "deception", "whistleblower", "anomaly", "extraterrestrial",
 
162
  "disinformation", "false flag", "assassin", "black ops", "anomaly", "men in black", "abduction",
163
  "hybrid", "ancient aliens", "hollow earth", "simulation theory", "alternate reality", "predictive programming",
164
  "symbolism", "occult", "eerie", "haunting", "unexplained", "forbidden knowledge", "redacted", "conspiracy theorist"]
165
+ except Exception as e:
166
+ logger.error(f"Error extrayendo keywords: {e}")
167
+ return ["mystery", "conspiracy", "alien", "UFO", "secret", "cover-up", "illusion", "paranoia",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
  "secret society", "lie", "simulation", "matrix", "terror", "darkness", "shadow", "enigma",
169
  "urban legend", "unknown", "hidden", "mistrust", "experiment", "government", "control",
170
  "surveillance", "propaganda", "deception", "whistleblower", "anomaly", "extraterrestrial",
 
173
  "hybrid", "ancient aliens", "hollow earth", "simulation theory", "alternate reality", "predictive programming",
174
  "symbolism", "occult", "eerie", "haunting", "unexplained", "forbidden knowledge", "redacted", "conspiracy theorist"]
175
 
176
+ def search_pexels_videos(query: str, count: int = 3) -> list[dict]:
177
+ if not PEXELS_API_KEY:
178
+ return []
179
+
180
+ try:
181
+ response = requests.get(
182
+ "https://api.pexels.com/videos/search",
183
+ headers={"Authorization": PEXELS_API_KEY},
184
+ params={"query": query, "per_page": count, "orientation": "landscape"},
185
+ timeout=20
186
+ )
187
+ response.raise_for_status()
188
+ return response.json().get("videos", [])
189
+ except Exception as e:
190
+ logger.error(f"Error buscando videos en Pexels: {e}")
191
+ return []
 
 
 
 
 
192
 
193
+ def download_video(url: str, folder: str) -> str | None:
194
  try:
195
+ filename = f"{uuid.uuid4().hex}.mp4"
196
+ filepath = os.path.join(folder, filename)
197
+
198
+ with requests.get(url, stream=True, timeout=60) as response:
199
+ response.raise_for_status()
200
+ with open(filepath, "wb") as f:
201
+ for chunk in response.iter_content(chunk_size=1024*1024):
202
+ f.write(chunk)
203
+
204
+ if os.path.exists(filepath) and os.path.getsize(filepath) > 1000:
205
+ return filepath
206
  else:
207
+ logger.error(f"Archivo descargado inválido: {filepath}")
208
+ return None
209
+
210
+ except Exception as e:
211
+ logger.error(f"Error descargando video {url}: {e}")
212
+ return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
 
214
+ def create_subtitle_clips(script: str, video_width: int, video_height: int, duration: float):
215
+ try:
216
+ sentences = [s.strip() for s in re.split(r"[.!?¿¡]", script) if s.strip()]
217
+ if not sentences:
218
+ return []
219
+
220
+ total_words = sum(len(s.split()) for s in sentences) or 1
221
+ time_per_word = duration / total_words
222
+
223
+ clips = []
224
+ current_time = 0.0
225
+
226
+ for sentence in sentences:
227
+ num_words = len(sentence.split())
228
+ sentence_duration = num_words * time_per_word
229
+
230
+ if sentence_duration < 0.5:
231
+ continue
232
+
233
  try:
234
+ txt_clip = (
235
+ TextClip(
236
+ sentence,
237
+ fontsize=max(20, int(video_height * 0.05)),
238
+ color="white",
239
+ stroke_color="black",
240
+ stroke_width=2,
241
+ method="caption",
242
+ size=(int(video_width * 0.9), None),
243
+ font="Arial-Bold"
244
+ )
245
+ .set_start(current_time)
246
+ .set_duration(sentence_duration)
247
+ .set_position(("center", "bottom"))
248
+ )
249
+ if txt_clip is not None:
250
+ clips.append(txt_clip)
251
  except Exception as e:
252
+ logger.error(f"Error creando subtítulo para '{sentence}': {e}")
253
+ continue
254
+
255
+ current_time += sentence_duration
256
+
257
+ return clips
258
+ except Exception as e:
259
+ logger.error(f"Error creando subtítulos: {e}")
260
+ return []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
261
 
262
+ def loop_audio_to_duration(audio_clip: AudioFileClip, target_duration: float) -> AudioFileClip:
263
+ if audio_clip is None:
264
+ return None
265
+ try:
266
+ if audio_clip.duration >= target_duration:
267
+ return audio_clip.subclip(0, target_duration)
268
+
269
+ loops_needed = math.ceil(target_duration / audio_clip.duration)
270
+ looped_audio = concatenate_audioclips([audio_clip] * loops_needed)
271
+ return looped_audio.subclip(0, target_duration)
272
+ except Exception as e:
273
+ logger.error(f"Error haciendo loop del audio: {e}")
274
+ return audio_clip
275
+
276
+ def create_video(script_text: str, generate_script: bool, music_path: str | None, task_id: str) -> str:
277
+ temp_dir = tempfile.mkdtemp()
278
+ TARGET_FPS = 24
279
+ TARGET_RESOLUTION = (1280, 720)
280
+
281
+ def normalize_clip(clip):
282
+ if clip is None:
283
+ return None
284
  try:
285
+ if clip.size != TARGET_RESOLUTION:
286
+ clip = clip.resize(TARGET_RESOLUTION)
287
+ if clip.fps != TARGET_FPS:
288
+ clip = clip.set_fps(TARGET_FPS)
289
+ return clip
290
  except Exception as e:
291
+ logger.error(f"Error normalizando clip: {e}")
292
+ return None
293
+
294
+ def validate_clip(clip, path="unknown"):
295
+ """Función para validar que un clip sea usable"""
296
+ if clip is None:
297
+ logger.error(f"Clip es None: {path}")
298
+ return False
299
+
300
+ try:
301
+ # Verificar duración
302
+ if clip.duration <= 0:
303
+ logger.error(f"Clip con duración inválida: {path}")
304
+ return False
305
+
306
+ # Verificar que podemos obtener un frame
307
+ test_frame = clip.get_frame(0)
308
+ if test_frame is None:
309
+ logger.error(f"No se pudo obtener frame del clip: {path}")
310
+ return False
311
+
312
+ return True
313
+ except Exception as e:
314
+ logger.error(f"Error validando clip {path}: {e}")
315
+ return False
316
+
317
+ def create_fallback_video(duration):
318
+ """Crea un video de respaldo"""
319
+ try:
320
+ fallback = ColorClip(
321
+ size=TARGET_RESOLUTION,
322
+ color=(0, 0, 0),
323
+ duration=duration
324
+ )
325
+ fallback.fps = TARGET_FPS
326
+ return fallback
327
+ except Exception as e:
328
+ logger.error(f"Error creando video de respaldo: {e}")
329
+ return None
330
+
331
+ try:
332
+ # Paso 1: Generar o usar guión
333
+ update_task_progress(task_id, "Paso 1/7: Preparando guión...")
334
+ if generate_script:
335
+ script = gpt2_script(script_text)
336
+ else:
337
+ script = script_text.strip()
338
+
339
+ if not script:
340
+ raise ValueError("El guión está vacío")
341
+
342
+ # Paso 2: Generar audio TTS
343
+ update_task_progress(task_id, "Paso 2/7: Generando audio con Edge TTS...")
344
+ audio_path = os.path.join(temp_dir, "voice.wav")
345
+
346
+ if not generate_tts_audio(script, audio_path):
347
+ raise RuntimeError("Error generando el audio TTS")
348
+
349
+ voice_clip = AudioFileClip(audio_path)
350
+ if voice_clip is None:
351
+ raise RuntimeError("No se pudo cargar el clip de audio")
352
+
353
+ video_duration = voice_clip.duration
354
+
355
+ if video_duration < 1:
356
+ raise ValueError("El audio generado es demasiado corto")
357
+
358
+ # Paso 3: Buscar y descargar videos
359
+ update_task_progress(task_id, "Paso 3/7: Buscando videos en Pexels...")
360
  video_paths = []
361
+ keywords = extract_keywords(script)
362
+
363
+ for i, keyword in enumerate(keywords[:3]):
364
+ update_task_progress(task_id, f"Paso 3/7: Buscando videos para '{keyword}' ({i+1}/{len(keywords[:3])})")
365
+
366
+ videos = search_pexels_videos(keyword, 2)
367
+ for video_data in videos:
368
+ if len(video_paths) >= 6:
369
+ break
370
+
371
+ video_files = video_data.get("video_files", [])
372
+ if video_files:
373
+ best_file = max(video_files, key=lambda f: f.get("width", 0))
374
+ video_url = best_file.get("link")
375
+
376
+ if video_url:
377
+ downloaded_path = download_video(video_url, temp_dir)
378
+ if downloaded_path:
379
+ video_paths.append(downloaded_path)
380
+
381
+ if not video_paths:
382
+ logger.warning("No se pudieron descargar videos de Pexels, creando video de respaldo...")
383
+ base_video = create_fallback_video(video_duration)
384
+ if base_video is None:
385
+ raise RuntimeError("No se pudo crear video de respaldo")
386
+ else:
387
+ # Paso 4: Procesar videos
388
+ update_task_progress(task_id, f"Paso 4/7: Procesando {len(video_paths)} videos...")
389
+ video_clips = []
390
+
391
+ for path in video_paths:
392
+ clip = None
393
+ try:
394
+ # Verificar que el archivo exista y tenga tamaño
395
+ if not os.path.exists(path) or os.path.getsize(path) < 1024:
396
+ logger.error(f"Archivo inválido: {path}")
397
+ continue
398
+
399
+ # Cargar el video
400
+ clip = VideoFileClip(path)
401
+ if clip is None:
402
+ logger.error(f"No se pudo cargar el video: {path}")
403
+ continue
404
+
405
+ # Validar el clip original
406
+ if not validate_clip(clip, path):
407
+ clip.close()
408
+ continue
409
+
410
+ # Recortar el video
411
+ duration = min(8, clip.duration)
412
+ processed_clip = clip.subclip(0, duration)
413
+
414
+ if processed_clip is None:
415
+ logger.error(f"Error al recortar video: {path}")
416
+ clip.close()
417
+ continue
418
+
419
+ # Validar el clip recortado
420
+ if not validate_clip(processed_clip, f"{path} (recortado)"):
421
+ processed_clip.close()
422
+ clip.close()
423
+ continue
424
+
425
+ # Normalizar
426
+ processed_clip = normalize_clip(processed_clip)
427
+
428
+ if processed_clip is not None:
429
+ # Validación final del clip procesado
430
+ if validate_clip(processed_clip, f"{path} (normalizado)"):
431
+ video_clips.append(processed_clip)
432
+ else:
433
+ processed_clip.close()
434
+ clip.close()
435
  else:
436
+ logger.error(f"Error normalizando video: {path}")
437
+ clip.close()
438
+
439
+ except Exception as e:
440
+ logger.error(f"Error procesando video {path}: {e}")
441
+ finally:
442
+ if clip is not None:
443
+ clip.close()
444
+
445
+ # Verificar si tenemos clips válidos
446
+ if not video_clips:
447
+ logger.warning("No se procesaron videos válidos, creando video de respaldo...")
448
+ base_video = create_fallback_video(video_duration)
449
+ if base_video is None:
450
+ raise RuntimeError("No se pudo crear video de respaldo")
451
+ else:
452
+ # Verificar que todos los clips sean válidos antes de concatenar
453
+ valid_clips = []
454
+ for i, clip in enumerate(video_clips):
455
+ try:
456
+ # Verificación final de cada clip
457
+ if validate_clip(clip, f"clip_{i}"):
458
+ valid_clips.append(clip)
459
+ else:
460
+ clip.close()
461
+ except Exception as e:
462
+ logger.error(f"Clip inválido en posición {i}: {e}")
463
+ if clip is not None:
464
+ clip.close()
465
+
466
+ if not valid_clips:
467
+ logger.warning("Todos los clips son inválidos, creando video de respaldo...")
468
+ base_video = create_fallback_video(video_duration)
469
+ if base_video is None:
470
+ raise RuntimeError("No se pudo crear video de respaldo")
471
  else:
472
+ # Concatenar solo clips válidos
473
+ update_task_progress(task_id, "Paso 4/7: Concatenando videos válidos...")
474
+ try:
475
+ base_video = concatenate_videoclips(valid_clips, method="chain")
476
+
477
+ # Verificar que la concatenación funcionó
478
+ if base_video is None:
479
+ raise RuntimeError("La concatenación devolvió None")
480
+
481
+ # Validar el video concatenado
482
+ if not validate_clip(base_video, "video_concatenado"):
483
+ raise RuntimeError("Video concatenado inválido")
484
+
485
+ except Exception as e:
486
+ logger.error(f"Error concatenando videos: {e}")
487
+ # Liberar clips
488
+ for clip in valid_clips:
489
+ if clip is not None:
490
+ clip.close()
491
+ # Crear video de respaldo
492
+ base_video = create_fallback_video(video_duration)
493
+ if base_video is None:
494
+ raise RuntimeError("No se pudo crear video de respaldo")
495
+
496
+ # Extender video si es más corto que el audio
497
+ if base_video.duration < video_duration:
498
+ update_task_progress(task_id, "Paso 4/7: Extendiendo video...")
499
  try:
500
+ fade_duration = 0.5
501
+ loops_needed = math.ceil(video_duration / base_video.duration)
502
+
503
+ looped_clips = [base_video]
504
+ for _ in range(loops_needed - 1):
505
+ fade_in_clip = base_video.crossfadein(fade_duration)
506
+ if fade_in_clip is not None:
507
+ looped_clips.append(fade_in_clip)
508
+ looped_clips.append(base_video)
509
+
510
+ # Guardar referencia al video original para liberarlo después
511
+ original_video = base_video
512
+ base_video = concatenate_videoclips(looped_clips)
513
+
514
+ # Verificar el video extendido
515
+ if base_video is None or not validate_clip(base_video, "video_extendido"):
516
+ logger.error("Error al extender video, usando original")
517
+ base_video = original_video
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
518
  else:
519
+ # Liberar el video original
520
+ original_video.close()
521
+
522
  except Exception as e:
523
+ logger.error(f"Error extendiendo video: {e}")
524
+ # No hacemos nada, seguimos con el video original
525
+
526
+ # Asegurar duración exacta
 
 
 
 
 
 
 
527
  try:
528
+ original_video = base_video
529
+ base_video = base_video.subclip(0, video_duration)
530
+
531
+ if base_video is None or not validate_clip(base_video, "video_recortado"):
532
+ logger.error("Error al recortar video final, usando original")
533
+ base_video = original_video
534
+ else:
535
+ original_video.close()
536
+
537
  except Exception as e:
538
+ logger.error(f"Error al recortar video final: {e}")
539
+ # No hacemos nada, seguimos con el video original
540
+
541
+ # Paso 5: Componer audio final
542
+ update_task_progress(task_id, "Paso 5/7: Componiendo audio...")
543
+ final_audio = voice_clip
544
+
545
+ if music_path and os.path.exists(music_path):
546
+ music_clip = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
547
  try:
548
+ music_clip = AudioFileClip(music_path)
549
+ if music_clip is not None:
550
+ music_clip = loop_audio_to_duration(music_clip, video_duration)
551
+ if music_clip is not None:
552
+ music_clip = music_clip.volumex(0.2)
553
+ final_audio = CompositeAudioClip([music_clip, voice_clip])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
554
  except Exception as e:
555
+ logger.error(f"Error con música: {e}")
556
+ finally:
557
+ if music_clip is not None:
558
+ music_clip.close()
559
+
560
+ # Paso 6: Agregar subtítulos
561
+ update_task_progress(task_id, "Paso 6/7: Agregando subtítulos...")
562
+ subtitle_clips = create_subtitle_clips(script, base_video.w, base_video.h, video_duration)
563
+ if subtitle_clips:
564
  try:
565
+ original_video = base_video
566
+ base_video = CompositeVideoClip([base_video] + subtitle_clips)
567
+
568
+ if base_video is None or not validate_clip(base_video, "video_con_subtitulos"):
569
+ logger.error("Error al agregar subtítulos, usando video original")
570
+ base_video = original_video
571
+ else:
572
+ original_video.close()
573
+
 
 
 
574
  except Exception as e:
575
+ logger.error(f"Error creando video con subtítulos: {e}")
576
+
577
+ # Paso 7: Renderizar video final
578
+ update_task_progress(task_id, "Paso 7/7: Renderizando video final...")
579
+ final_video = base_video.set_audio(final_audio)
580
+
581
+ output_path = os.path.join(RESULTS_DIR, f"video_{task_id}.mp4")
582
+ final_video.write_videofile(
 
 
 
 
 
 
 
583
  output_path,
584
+ fps=TARGET_FPS,
 
585
  codec="libx264",
586
  audio_codec="aac",
587
+ bitrate="8000k",
588
+ threads=4,
589
+ preset="slow",
590
+ logger=None,
591
+ verbose=False
592
  )
593
+
594
+ # Limpiar clips
595
+ voice_clip.close()
596
+ base_video.close()
597
+ final_video.close()
598
+ for clip in video_clips:
599
+ if clip is not None:
600
+ clip.close()
601
+
602
  return output_path
603
+
 
 
 
604
  except Exception as e:
605
+ logger.error(f"Error creando video: {e}")
606
+ raise
607
  finally:
608
+ try:
609
+ shutil.rmtree(temp_dir)
610
+ except:
611
+ pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
612
 
613
+ def worker_thread(task_id: str, mode: str, topic: str, user_script: str, music_path: str | None):
614
  try:
615
+ generate_script = (mode == "Generar Guion con IA")
616
+ content = topic if generate_script else user_script
617
+
618
+ output_path = create_video(content, generate_script, music_path, task_id)
619
+
620
+ TASKS[task_id].update({
621
+ "status": "done",
622
+ "result": output_path,
623
+ "progress_log": "✅ ¡Video completado exitosamente!"
624
+ })
625
+
 
 
 
 
 
 
626
  except Exception as e:
627
+ logger.error(f"Error en worker {task_id}: {e}")
628
+ TASKS[task_id].update({
629
+ "status": "error",
630
+ "error": str(e),
631
+ "progress_log": f"❌ Error: {str(e)}"
632
+ })
633
+
634
+ def generate_video_with_progress(mode, topic, user_script, music):
635
+ content = topic if mode == "Generar Guion con IA" else user_script
636
+ if not content or not content.strip():
637
+ yield "❌ Error: Por favor, ingresa un tema o guion.", None, None
638
+ return
639
+
640
+ task_id = uuid.uuid4().hex[:8]
641
+ TASKS[task_id] = {
642
+ "status": "processing",
643
+ "progress_log": "🚀 Iniciando generación de video...",
644
+ "timestamp": datetime.utcnow()
645
+ }
646
+
647
+ worker = threading.Thread(
648
+ target=worker_thread,
649
+ args=(task_id, mode, topic, user_script, music),
650
+ daemon=True
651
+ )
652
+ worker.start()
653
+
654
+ while TASKS[task_id]["status"] == "processing":
655
+ yield TASKS[task_id]['progress_log'], None, None
656
+ time.sleep(1)
657
+
658
+ if TASKS[task_id]["status"] == "error":
659
+ yield TASKS[task_id]['progress_log'], None, None
660
+ elif TASKS[task_id]["status"] == "done":
661
+ result_path = TASKS[task_id]['result']
662
+ yield TASKS[task_id]['progress_log'], result_path, result_path
663
+
664
+ # ------------------- Limpieza automática -------------------
665
+ def cleanup_old_files():
666
+ while True:
667
+ try:
668
+ time.sleep(6600)
669
+ now = datetime.utcnow()
670
+ logger.info("Ejecutando limpieza de archivos antiguos...")
671
+
672
+ for task_id, info in list(TASKS.items()):
673
+ if "timestamp" in info and now - info["timestamp"] > timedelta(hours=24):
674
+ if info.get("result") and os.path.exists(info.get("result")):
675
+ try:
676
+ os.remove(info["result"])
677
+ logger.info(f"Archivo eliminado: {info['result']}")
678
+ except Exception as e:
679
+ logger.error(f"Error eliminando archivo: {e}")
680
+ del TASKS[task_id]
681
+
682
+ except Exception as e:
683
+ logger.error(f"Error en cleanup: {e}")
684
 
685
+ threading.Thread(target=cleanup_old_files, daemon=True).start()
 
 
 
 
686
 
687
+ # ------------------- Interfaz Gradio -------------------
688
+ def toggle_input_fields(mode):
689
+ return (
690
+ gr.update(visible=mode == "Generar Guion con IA"),
691
+ gr.update(visible=mode != "Generar Guion con IA")
692
+ )
693
 
694
+ with gr.Blocks(title="🎬 Generador de Videos IA", theme=gr.themes.Soft()) as demo:
695
+ gr.Markdown("""
696
+ # 🎬 Generador de Videos con IA
697
+
698
+ Crea videos profesionales a partir de texto usando:
699
+ - **Edge TTS** para voz en español
700
+ - **GPT-2** para generación de guiones
701
+ - **Pexels API** para videos de stock
702
+ - **Subtítulos automáticos** y efectos visuales
703
+
704
+ El progreso se mostrará en tiempo real.
705
+ """)
706
+
707
  with gr.Row():
708
+ with gr.Column(scale=2):
709
+ gr.Markdown("### ⚙️ Configuración")
710
+
711
+ mode_radio = gr.Radio(
712
+ choices=["Generar Guion con IA", "Usar Mi Guion"],
713
+ value="Generar Guion con IA",
714
+ label="Método de creación"
715
  )
716
+
717
+ topic_input = gr.Textbox(
718
+ label="💡 Tema para la IA",
719
+ placeholder="Ej: Los misterios del océano profundo",
720
+ lines=2
721
+ )
722
+
723
+ script_input = gr.Textbox(
724
+ label="📝 Tu Guion Completo",
725
+ placeholder="Escribe aquí tu guion personalizado...",
726
+ lines=8,
727
+ visible=False
728
+ )
729
+
730
+ music_input = gr.Audio(
 
 
 
 
 
 
 
 
 
731
  type="filepath",
732
+ label="🎵 Música de fondo (opcional)"
 
 
733
  )
734
+
735
+ generate_btn = gr.Button(
736
+ "🎬 Generar Video",
737
+ variant="primary",
738
+ size="lg"
 
 
 
739
  )
740
+
741
+ with gr.Column(scale=2):
742
+ gr.Markdown("### 📊 Progreso y Resultados")
743
+
744
+ progress_output = gr.Textbox(
745
+ label="📋 Log de progreso en tiempo real",
746
+ lines=12,
 
747
  interactive=False,
748
+ show_copy_button=True
 
749
  )
750
+
751
+ video_output = gr.Video(
752
+ label="🎥 Video generado",
753
+ height=400
 
754
  )
755
+
756
+ download_output = gr.File(
757
+ label="📥 Descargar archivo"
 
 
 
 
758
  )
759
+
760
+ mode_radio.change(
761
+ fn=toggle_input_fields,
762
+ inputs=[mode_radio],
763
+ outputs=[topic_input, script_input]
 
 
764
  )
765
+
 
766
  generate_btn.click(
767
+ fn=generate_video_with_progress,
768
+ inputs=[mode_radio, topic_input, script_input, music_input],
769
+ outputs=[progress_output, video_output, download_output]
 
 
 
 
 
 
 
 
 
 
 
 
 
770
  )
771
+
 
 
772
  gr.Markdown("""
773
+ ### 📋 Instrucciones:
774
+ 1. **Elige el método**: Genera un guion con IA o usa el tuyo propio
775
+ 2. **Configura el contenido**: Ingresa un tema interesante o tu guion
776
+ 3. **Música opcional**: Sube un archivo de audio para fondo musical
777
+ 4. **Genera**: Presiona el botón y observa el progreso en tiempo real
778
+
779
+ ⏱️ **Tiempo estimado**: 2-5 minutos dependiendo de la duración del contenido.
 
780
  """)
 
 
781
 
782
  if __name__ == "__main__":
783
+ logger.info("🚀 Iniciando aplicación Generador de Videos IA...")
784
+ demo.queue(max_size=10)
785
+ demo.launch(
786
+ server_name="0.0.0.0",
787
+ server_port=7860,
788
+ show_api=False,
789
+ share=True
790
+ )