gnosticdev commited on
Commit
163c0da
·
verified ·
1 Parent(s): 712e289

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +160 -387
app.py CHANGED
@@ -4,449 +4,222 @@ import logging
4
  import tempfile
5
  import requests
6
  from datetime import datetime
7
- from moviepy.editor import VideoFileClip, concatenate_videoclips, AudioFileClip, CompositeAudioClip
8
  import edge_tts
9
  import gradio as gr
10
- from transformers import GPT2Tokenizer, GPT2LMHeadModel
11
  import torch
 
 
12
 
13
- # --- NO MÁS 'from pexels_api import API' ---
14
- # Ahora Pexels se gestiona directamente con requests
15
- # from pexels_api import API
16
-
17
- # --- Importar KeyBERT para extracción de palabras clave ---
18
- from keybert import KeyBERT
19
-
20
- # --- Configuración de Logging ---
21
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
22
  logger = logging.getLogger(__name__)
23
 
24
- # --- Clave API de Pexels ---
25
- PEXELS_API_KEY = os.environ.get("PEXELS_API_KEY")
26
- # Ya no se inicializa pexels_api = API(PEXELS_API_KEY)
27
-
28
- # --- Inicialización de Tokenizer y Modelo GPT-2 ---
29
- MODEL_NAME = "gpt2-small"
30
- try:
31
- tokenizer = GPT2Tokenizer.from_pretrained(MODEL_NAME)
32
- model = GPT2LMHeadModel.from_pretrained(MODEL_NAME).eval()
33
- if tokenizer.pad_token is None:
34
- tokenizer.pad_token = tokenizer.eos_token
35
- logger.info(f"Modelo GPT-2 '{MODEL_NAME}' cargado exitosamente.")
36
- except Exception as e:
37
- logger.error(f"Error al cargar el modelo GPT-2 '{MODEL_NAME}': {e}")
38
- tokenizer = None
39
- model = None
40
 
41
- # --- Inicialización del modelo KeyBERT ---
42
  try:
43
- kw_model = KeyBERT('multi-qa-MiniLM-L6-cos-v1')
44
  logger.info("Modelo KeyBERT cargado exitosamente.")
45
  except Exception as e:
46
- logger.error(f"Error al cargar el modelo KeyBERT: {e}. La búsqueda de videos será menos precisa.", exc_info=True)
47
  kw_model = None
48
 
49
- # --- Funciones de Utilidad ---
50
-
51
- def generate_script(prompt, max_length=250):
52
- if not tokenizer or not model:
53
- logger.error("Modelo GPT-2 no disponible para generar guion.")
54
- return "Lo siento, el generador de guiones no está disponible en este momento."
55
-
56
- logger.info("Generando guion con GPT-2...")
57
- try:
58
- inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512)
59
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
60
- inputs = {k: v.to(device) for k, v in inputs.items()}
61
- model.to(device)
62
-
63
- with torch.no_grad():
64
- outputs = model.generate(
65
- **inputs,
66
- max_length=max_length,
67
- do_sample=True,
68
- top_p=0.95,
69
- top_k=60,
70
- temperature=0.9,
71
- pad_token_id=tokenizer.pad_token_id,
72
- eos_token_id=tokenizer.eos_token_id
73
- )
74
- text = tokenizer.decode(outputs[0], skip_special_tokens=True)
75
- logger.info(f"Guion generado (longitud: {len(text)} caracteres): {text[:200]}...")
76
- return text
77
- except Exception as e:
78
- logger.error(f"Error durante la generación del guion: {e}")
79
- return "No se pudo generar el guion. Intenta con otro prompt o un guion propio."
80
 
81
- async def text_to_speech(text, voice="es-ES-ElviraNeural", output_path="voz.mp3"):
82
- logger.info(f"Generando audio TTS para: '{text[:100]}...'")
83
  try:
84
  communicate = edge_tts.Communicate(text, voice)
85
  await communicate.save(output_path)
86
- logger.info(f"Audio TTS guardado en {output_path}")
87
  except Exception as e:
88
- logger.error(f"Error al generar audio TTS: {e}")
89
- raise
90
 
91
- def download_video_file(url, temp_dir):
92
- if not url:
93
- return None
94
-
95
- file_name = url.split('/')[-1].split('?')[0]
96
- if not file_name.endswith('.mp4'):
97
- file_name = f"video_temp_{os.getpid()}_{datetime.now().strftime('%f')}.mp4"
98
-
99
- output_path = os.path.join(temp_dir, file_name)
100
- logger.info(f"Intentando descargar video de: {url} a {output_path}")
101
  try:
102
- response = requests.get(url, stream=True, timeout=30)
103
  response.raise_for_status()
104
-
105
- with open(output_path, 'wb') as f:
 
 
 
106
  for chunk in response.iter_content(chunk_size=8192):
107
- if chunk:
108
- f.write(chunk)
109
- logger.info(f"Video descargado a: {output_path}")
110
- return output_path
111
- except requests.exceptions.RequestException as e:
112
- logger.error(f"Error de red/HTTP al descargar el video {url}: {e}")
113
- if os.path.exists(output_path):
114
- os.remove(output_path)
115
- return None
116
  except Exception as e:
117
- logger.error(f"Error inesperado al descargar video {url}: {e}")
118
- if os.path.exists(output_path):
119
- os.remove(output_path)
120
  return None
121
 
122
- def loop_audio_to_length(audio_clip, target_duration):
123
- if audio_clip.duration >= target_duration:
124
- return audio_clip.subclip(0, target_duration)
125
-
126
- loops = int(target_duration / audio_clip.duration) + 1
127
- audios = [audio_clip] * loops
128
- concatenated = concatenate_videoclips(audios)
129
- return concatenated.subclip(0, target_duration)
130
-
131
- def extract_visual_keywords_from_script(script_text, max_keywords_per_segment=2):
132
- if not kw_model:
133
- logger.warning("Modelo KeyBERT no disponible. La extracción de palabras clave será limitada.")
134
- return [script_text.split('.')[0].strip().replace(" ", "+")] if script_text.strip() else []
135
-
136
- logger.info("Extrayendo palabras clave visuales del guion.")
137
-
138
- segments = [s.strip() for s in script_text.split('\n') if s.strip()]
139
- if not segments:
140
- segments = [script_text]
141
-
142
- all_keywords = set()
143
-
144
- for segment in segments:
145
- if not segment: continue
146
  try:
147
- keywords_with_scores = kw_model.extract_keywords(
148
- segment,
149
- keyphrase_ngram_range=(1, 2),
150
- stop_words='spanish',
151
- top_n=max_keywords_per_segment,
152
- use_mmr=True,
153
- diversity=0.7
154
  )
155
- for kw, score in keywords_with_scores:
156
- all_keywords.add(kw.replace(" ", "+"))
157
  except Exception as e:
158
- logger.warning(f"Error al extraer palabras clave de un segmento: {e}")
159
- all_keywords.add(segment.split(' ')[0].strip().replace(" ", "+"))
160
-
161
- logger.info(f"Palabras clave visuales extraídas del guion: {list(all_keywords)}")
162
- return list(all_keywords)
 
163
 
164
- # --- Búsqueda de videos en Pexels (AHORA CON REQUESTS DIRECTOS) ---
165
- def search_pexels_videos(query_list, num_videos_per_query=5, min_duration_sec=7):
166
  if not PEXELS_API_KEY:
167
- logger.error("ERROR: PEXELS_API_KEY no está configurada. No se pueden buscar videos en Pexels.")
168
- raise ValueError("PEXELS_API_KEY no está configurada. Por favor, configúrala como un secreto en Hugging Face Spaces.")
169
-
170
- if not query_list:
171
- logger.warning("Lista de queries para Pexels vacía. No se buscarán videos.")
172
  return []
173
-
174
- all_video_urls = set()
 
175
 
176
  for query in query_list:
177
- logger.info(f"Buscando {num_videos_per_query} videos en Pexels para la query: '{query}'")
178
  try:
179
- # URL de la API de búsqueda de Pexels
180
- # https://www.pexels.com/api/documentation/#videos-search
181
- api_url = "https://api.pexels.com/videos/search"
182
- headers = {"Authorization": PEXELS_API_KEY}
183
  params = {
184
  "query": query,
185
- "per_page": num_videos_per_query * 2, # Pedimos el doble por si algunos no cumplen duración
186
- "orientation": "landscape", # Opcional: landscape, portrait, square
187
- "min_duration": min_duration_sec
188
  }
189
 
190
- response = requests.get(api_url, headers=headers, params=params, timeout=15)
191
- response.raise_for_status() # Lanza un error si la solicitud HTTP no fue exitosa (código 4xx o 5xx)
 
 
 
 
192
 
193
- data = response.json()
194
- videos = data.get('videos', [])
195
-
196
- if not videos:
197
- logger.info(f"No se encontraron videos en Pexels para la query: '{query}'")
198
- continue
199
-
200
- for video in videos:
201
- best_quality_url = None
202
- # Ordenar por calidad para obtener la mejor disponible
203
- video_files = sorted(video.get('video_files', []), key=lambda x: x.get('width', 0) * x.get('height', 0), reverse=True)
204
-
205
- for file in video_files:
206
- if file.get('link'):
207
- best_quality_url = file['link']
208
- break
209
-
210
- if best_quality_url:
211
- all_video_urls.add(best_quality_url)
212
- else:
213
- logger.warning(f"No se encontró URL de descarga válida para el video Pexels ID: {video.get('id')}")
214
-
215
- except requests.exceptions.RequestException as e:
216
- logger.error(f"Error de HTTP/red al buscar videos en Pexels para '{query}': {e}", exc_info=True)
217
  except Exception as e:
218
- logger.error(f"Error inesperado al buscar videos en Pexels para '{query}': {e}", exc_info=True)
219
-
220
- final_urls = list(all_video_urls)
221
- logger.info(f"Total de {len(final_urls)} URLs de video únicas obtenidas de Pexels.")
222
- return final_urls
223
-
224
- def crear_video(prompt_type, input_text, musica_url=None):
225
- logger.info(f"Iniciando creación de video. Tipo de prompt: {prompt_type}")
226
- guion = ""
227
- if prompt_type == "Generar Guion con IA":
228
- guion = generate_script(input_text)
229
- if not guion or guion == "No se pudo generar el guion. Intenta con otro prompt o un guion propio.":
230
- raise ValueError(guion)
231
- else:
232
- guion = input_text
233
- if not guion.strip():
234
- raise ValueError("Por favor, introduce tu guion.")
235
-
236
- if not guion.strip():
237
- raise ValueError("El guion está vacío. No se puede proceder.")
238
-
239
- temp_files = []
240
- downloaded_clip_paths = []
241
- final_clips = []
242
-
243
- temp_video_dir = tempfile.mkdtemp()
244
- temp_files.append(temp_video_dir)
245
 
 
 
246
  try:
247
- voz_archivo = os.path.join(tempfile.gettempdir(), f"voz_temp_{os.getpid()}.mp3")
248
- temp_files.append(voz_archivo)
249
- asyncio.run(text_to_speech(guion, output_path=voz_archivo))
250
- audio_tts = AudioFileClip(voz_archivo)
251
-
252
- search_queries_for_pexels = extract_visual_keywords_from_script(guion, max_keywords_per_segment=2)
253
-
254
- if not search_queries_for_pexels:
255
- raise ValueError("No se pudieron extraer palabras clave visuales del guion para buscar videos.")
256
-
257
- pexels_video_urls_found = search_pexels_videos(search_queries_for_pexels, num_videos_per_query=5, min_duration_sec=7)
258
-
259
- if not pexels_video_urls_found:
260
- logger.error("Pexels no devolvió ningún video para las palabras clave extraídas.")
261
- raise ValueError(f"Pexels no encontró videos adecuados para el guion. Intenta con otro tema o guion más descriptivo. Palabras clave usadas: {search_queries_for_pexels}")
262
-
263
- logger.info(f"Descargando {len(pexels_video_urls_found)} videos de Pexels...")
264
- for url in pexels_video_urls_found:
265
- video_path = download_video_file(url, temp_video_dir)
266
- if video_path:
267
- downloaded_clip_paths.append(video_path)
268
- else:
269
- logger.warning(f"No se pudo descargar video de Pexels: {url}")
270
 
271
- if not downloaded_clip_paths:
272
- logger.error("No se pudo descargar ningún video válido de Pexels.")
273
- raise ValueError("No se pudo descargar ningún video válido de Pexels. Revisa la conexión o la calidad de las URLs.")
 
 
274
 
275
- total_desired_video_duration = audio_tts.duration * 1.2
276
- current_video_clips_duration = 0
 
 
 
 
 
 
 
 
 
277
 
278
- for path in downloaded_clip_paths:
279
- try:
280
- clip = VideoFileClip(path)
281
- clip_duration = min(clip.duration, 10)
282
- if clip_duration > 1:
283
- final_clips.append(clip.subclip(0, clip_duration))
284
- current_video_clips_duration += clip_duration
285
- if current_video_clips_duration >= total_desired_video_duration:
286
- break
287
- else:
288
- logger.warning(f"Clip de video muy corto ({clip_duration:.2f}s) de {path}, omitiendo.")
289
- clip.close()
290
- except Exception as e:
291
- logger.warning(f"No se pudo cargar o procesar el clip de video {path}: {e}. Omitiendo.")
292
- if 'clip' in locals() and clip: clip.close()
293
 
294
- if not final_clips:
295
- logger.error("No se pudo obtener ningún clip de video usable después de la descarga y procesamiento.")
296
- raise ValueError("No se pudieron procesar los videos descargados de Pexels.")
297
-
298
- video_base = concatenate_videoclips(final_clips, method="compose")
299
- logger.info(f"Video base concatenado, duración: {video_base.duration:.2f}s")
300
-
301
- if video_base.duration < audio_tts.duration:
302
- logger.info(f"Duración del video ({video_base.duration:.2f}s) es menor que la del audio TTS ({audio_tts.duration:.2f}s). Repitiendo video.")
303
- num_repeats = int(audio_tts.duration / video_base.duration) + 1
304
- repeated_clips = [video_base] * num_repeats
305
- video_base = concatenate_videoclips(repeated_clips, method="compose")
306
 
307
- final_video_duration = audio_tts.duration
308
-
309
- mezcla_audio = audio_tts
310
- if musica_url and musica_url.strip():
311
- musica_path = download_video_file(musica_url, temp_video_dir)
312
- if musica_path:
313
- temp_files.append(musica_path)
314
- try:
315
- musica_audio = AudioFileClip(musica_path)
316
- musica_loop = loop_audio_to_length(musica_audio, final_video_duration)
317
- mezcla_audio = CompositeAudioClip([musica_loop.volumex(0.3), audio_tts.set_duration(final_video_duration).volumex(1.0)])
318
- logger.info("Música de fondo añadida y mezclada.")
319
- except Exception as e:
320
- logger.warning(f"No se pudo procesar la música de fondo de {musica_url}: {e}. Se usará solo la voz.")
321
- else:
322
- logger.warning(f"No se pudo descargar la música de {musica_url}. Se usará solo la voz.")
323
 
324
- video_final = video_base.set_audio(mezcla_audio).subclip(0, final_video_duration)
325
- logger.info(f"Video final configurado con audio. Duración final: {video_final.duration:.2f}s")
326
-
327
- output_dir = "generated_videos"
328
- os.makedirs(output_dir, exist_ok=True)
329
- output_path = os.path.join(output_dir, f"video_output_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4")
330
- logger.info(f"Escribiendo video final a: {output_path}")
331
- video_final.write_videofile(output_path, fps=24, threads=4, logger=None, preset="medium", codec="libx264")
332
-
333
- logger.info(f"Video generado exitosamente en: {output_path}")
334
- return output_path
335
-
336
- except Exception as e:
337
- logger.error(f"Error general en la creación del video: {e}", exc_info=True)
338
- raise e
339
- finally:
340
- for f in temp_files:
341
- if os.path.exists(f):
342
- if os.path.isdir(f):
343
- import shutil
344
- shutil.rmtree(f)
345
- logger.info(f"Directorio temporal eliminado: {f}")
346
- else:
347
- os.remove(f)
348
- logger.info(f"Archivo temporal eliminado: {f}")
349
 
350
- for clip in final_clips:
351
- if clip and hasattr(clip, 'close') and not clip.is_playing:
352
- clip.close()
353
- if 'audio_tts' in locals() and audio_tts and hasattr(audio_tts, 'close') and not audio_tts.is_playing:
354
- audio_tts.close()
355
- if 'musica_audio' in locals() and musica_audio and hasattr(musica_audio, 'close') and not musica_audio.is_playing:
356
- musica_audio.close()
357
- if 'video_final' in locals() and video_final and hasattr(video_final, 'close') and not video_final.is_playing:
358
- video_final.close()
359
- if 'video_base' in locals() and video_base and hasattr(video_base, 'close') and not video_base.is_playing:
360
- video_base.close()
361
-
362
-
363
- def run_app(prompt_type, prompt_ia, prompt_manual, musica_url):
364
- input_text = ""
365
- if prompt_type == "Generar Guion con IA":
366
- input_text = prompt_ia
367
- if not input_text.strip():
368
- raise gr.Error("Por favor, introduce un tema para generar el guion.")
369
- else:
370
- input_text = prompt_manual
371
- if not input_text.strip():
372
- raise gr.Error("Por favor, introduce tu guion.")
373
-
374
- logger.info(f"Solicitud recibida: Tipo='{prompt_type}', Input='{input_text[:50]}...', Música='{musica_url}'")
375
-
376
- try:
377
- video_path = crear_video(prompt_type, input_text, musica_url if musica_url.strip() else None)
378
- if video_path:
379
- logger.info(f"Proceso completado. Video disponible en: {video_path}")
380
- return video_path, gr.update(value="¡Video generado exitosamente!")
381
  else:
382
- raise gr.Error("Hubo un problema desconocido al generar el video. Revisa los logs.")
383
- except ValueError as ve:
384
- logger.error(f"Error de validación o búsqueda de Pexels: {ve}")
385
- return None, gr.update(value=f"Error: {ve}", text_color="red")
386
  except Exception as e:
387
- logger.error(f"Error inesperado al ejecutar la aplicación: {e}", exc_info=True)
388
- return None, gr.update(value=f"Ocurrió un error grave: {e}. Por favor, inténtalo de nuevo.", text_color="red")
 
 
 
389
 
390
- with gr.Blocks() as app:
391
- gr.Markdown("""
392
- ### 🎬 Generador de Video Inteligente con Pexels 🚀
393
- Crea videos con guiones generados por IA o propios, voz automática y **videos de stock relevantes de Pexels (sin videos de ejemplo)**.
394
- """)
395
 
396
- with gr.Tab("Generar Video"):
397
- with gr.Row():
398
- prompt_type = gr.Radio(
399
- ["Generar Guion con IA", "Usar Mi Guion"],
400
- label="Método de Guion",
401
- value="Generar Guion con IA"
402
- )
403
-
404
- with gr.Column(visible=True) as ia_guion_column:
405
- prompt_ia = gr.Textbox(
406
- label="Tema para Generar Guion (con IA)",
407
- lines=2,
408
- placeholder="Ej: Las maravillas del universo y las estrellas."
409
- )
410
-
411
- with gr.Column(visible=False) as manual_guion_column:
412
- prompt_manual = gr.Textbox(
413
- label="Introduce Tu Guion Propio",
414
- lines=5,
415
- placeholder="Ej: Hola a todos, hoy hablaremos de un tema fascinante..."
416
  )
417
-
418
- musica_input = gr.Textbox(
419
- label="URL de Música de Fondo (opcional, MP3 recomendado)",
420
- placeholder="Ej: https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"
421
- )
422
-
423
- boton = gr.Button("✨ Generar Video")
424
 
425
  with gr.Column():
426
- salida_video = gr.Video(label="Video Generado", interactive=False)
427
- estado_mensaje = gr.Textbox(label="Estado del Proceso", interactive=False, value="")
428
-
429
- prompt_type.change(
430
- fn=lambda value: (gr.update(visible=value == "Generar Guion con IA"),
431
- gr.update(visible=value == "Usar Mi Guion")),
432
- inputs=prompt_type,
433
- outputs=[ia_guion_column, manual_guion_column]
434
- )
435
-
436
- boton.click(
437
- fn=lambda: (None, gr.update(value="Iniciando generación... Esto puede tardar varios minutos (descarga de videos).")),
438
- outputs=[salida_video, estado_mensaje],
439
- queue=False
440
- ).then(
441
- fn=run_app,
442
- inputs=[prompt_type, prompt_ia, prompt_manual, musica_input],
443
- outputs=[salida_video, estado_mensaje]
444
  )
445
-
446
- prompt_ia.change(fn=lambda: gr.update(value=""), outputs=estado_mensaje, queue=False)
447
- prompt_manual.change(fn=lambda: gr.update(value=""), outputs=estado_mensaje, queue=False)
448
- musica_input.change(fn=lambda: gr.update(value=""), outputs=estado_mensaje, queue=False)
449
 
 
 
 
 
 
 
 
 
 
 
450
  if __name__ == "__main__":
451
- logger.info("Iniciando aplicación Gradio para Hugging Face Spaces...")
452
- app.launch(server_name="0.0.0.0", server_port=7860, share=False)
 
4
  import tempfile
5
  import requests
6
  from datetime import datetime
 
7
  import edge_tts
8
  import gradio as gr
 
9
  import torch
10
+ import re
11
+ from keybert import KeyBERT
12
 
13
+ # Configuración básica de logging
 
 
 
 
 
 
 
14
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
15
  logger = logging.getLogger(__name__)
16
 
17
+ # Clave API de Pexels (configurar en Secrets de Hugging Face)
18
+ PEXELS_API_KEY = os.environ.get("PEXELS_API_KEY", "YOUR_DEFAULT_API_KEY")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
+ # Inicialización del modelo KeyBERT
21
  try:
22
+ kw_model = KeyBERT('distilbert-base-nli-mean-tokens')
23
  logger.info("Modelo KeyBERT cargado exitosamente.")
24
  except Exception as e:
25
+ logger.error(f"Error al cargar KeyBERT: {e}")
26
  kw_model = None
27
 
28
+ # --- Funciones principales optimizadas para Spaces ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
+ async def text_to_speech(text, output_path, voice="es-ES-ElviraNeural"):
31
+ """Genera audio TTS usando edge-tts"""
32
  try:
33
  communicate = edge_tts.Communicate(text, voice)
34
  await communicate.save(output_path)
35
+ return True
36
  except Exception as e:
37
+ logger.error(f"Error en TTS: {e}")
38
+ return False
39
 
40
+ def download_video(url, temp_dir):
41
+ """Descarga un video desde una URL a un directorio temporal"""
 
 
 
 
 
 
 
 
42
  try:
43
+ response = requests.get(url, stream=True, timeout=30)
44
  response.raise_for_status()
45
+
46
+ filename = f"video_{datetime.now().strftime('%H%M%S%f')}.mp4"
47
+ filepath = os.path.join(temp_dir, filename)
48
+
49
+ with open(filepath, 'wb') as f:
50
  for chunk in response.iter_content(chunk_size=8192):
51
+ f.write(chunk)
52
+
53
+ return filepath
 
 
 
 
 
 
54
  except Exception as e:
55
+ logger.error(f"Error descargando video: {e}")
 
 
56
  return None
57
 
58
+ def extract_keywords(text, max_keywords=3):
59
+ """Extrae palabras clave usando KeyBERT o método simple como fallback"""
60
+ if kw_model:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  try:
62
+ keywords = kw_model.extract_keywords(
63
+ text,
64
+ keyphrase_ngram_range=(1, 2),
65
+ top_n=max_keywords,
66
+ use_mmr=True,
67
+ diversity=0.7
 
68
  )
69
+ return [kw[0].replace(" ", "+") for kw in keywords]
 
70
  except Exception as e:
71
+ logger.warning(f"Error KeyBERT: {e}")
72
+
73
+ # Fallback: método simple
74
+ words = re.findall(r'\b\w+\b', text.lower())
75
+ stop_words = {"el", "la", "los", "las", "de", "en", "y", "a", "que", "es", "por"}
76
+ return list(set([w for w in words if len(w) > 3 and w not in stop_words][:max_keywords]))
77
 
78
+ def search_pexels_videos(query_list, per_query=2):
79
+ """Busca videos en Pexels usando su API oficial"""
80
  if not PEXELS_API_KEY:
81
+ logger.error("API_KEY de Pexels no configurada")
 
 
 
 
82
  return []
83
+
84
+ headers = {"Authorization": PEXELS_API_KEY}
85
+ video_urls = []
86
 
87
  for query in query_list:
 
88
  try:
 
 
 
 
89
  params = {
90
  "query": query,
91
+ "per_page": per_query,
92
+ "orientation": "landscape",
93
+ "size": "medium"
94
  }
95
 
96
+ response = requests.get(
97
+ "https://api.pexels.com/videos/search",
98
+ headers=headers,
99
+ params=params,
100
+ timeout=15
101
+ )
102
 
103
+ if response.status_code == 200:
104
+ videos = response.json().get("videos", [])
105
+ for video in videos:
106
+ video_files = video.get("video_files", [])
107
+ if video_files:
108
+ # Seleccionar el video con la mejor resolución
109
+ best_quality = max(
110
+ video_files,
111
+ key=lambda x: x.get("width", 0) * x.get("height", 0)
112
+ )
113
+ video_urls.append(best_quality["link"])
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  except Exception as e:
115
+ logger.error(f"Error buscando videos: {e}")
116
+
117
+ return video_urls
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
+ def create_video(audio_path, video_paths, output_path):
120
+ """Crea el video final usando FFmpeg"""
121
  try:
122
+ # Crear archivo de lista para concatenación
123
+ with open("input_list.txt", "w") as f:
124
+ for path in video_paths:
125
+ f.write(f"file '{path}'\n")
126
+
127
+ # Comando FFmpeg para concatenar videos y añadir audio
128
+ cmd = [
129
+ "ffmpeg", "-y",
130
+ "-f", "concat",
131
+ "-safe", "0",
132
+ "-i", "input_list.txt",
133
+ "-i", audio_path,
134
+ "-c", "copy",
135
+ "-shortest",
136
+ output_path
137
+ ]
 
 
 
 
 
 
 
138
 
139
+ subprocess.run(cmd, check=True)
140
+ return True
141
+ except Exception as e:
142
+ logger.error(f"Error creando video: {e}")
143
+ return False
144
 
145
+ async def generate_video(text, music_url=None):
146
+ """Función principal para generar el video"""
147
+ temp_dir = tempfile.mkdtemp()
148
+ all_files = []
149
+
150
+ try:
151
+ # 1. Generar audio TTS
152
+ tts_path = os.path.join(temp_dir, "audio.mp3")
153
+ if not await text_to_speech(text, tts_path):
154
+ return None, "Error generando voz"
155
+ all_files.append(tts_path)
156
 
157
+ # 2. Extraer palabras clave
158
+ keywords = extract_keywords(text)
159
+ logger.info(f"Palabras clave identificadas: {keywords}")
 
 
 
 
 
 
 
 
 
 
 
 
160
 
161
+ # 3. Buscar y descargar videos
162
+ video_urls = search_pexels_videos(keywords)
163
+ if not video_urls:
164
+ return None, "No se encontraron videos para las palabras clave"
 
 
 
 
 
 
 
 
165
 
166
+ video_paths = []
167
+ for url in video_urls:
168
+ path = download_video(url, temp_dir)
169
+ if path:
170
+ video_paths.append(path)
171
+ all_files.append(path)
 
 
 
 
 
 
 
 
 
 
172
 
173
+ if not video_paths:
174
+ return None, "Error descargando videos"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
 
176
+ # 4. Crear video final
177
+ output_path = os.path.join(temp_dir, "final_video.mp4")
178
+ if create_video(tts_path, video_paths, output_path):
179
+ return output_path, "Video creado exitosamente"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
  else:
181
+ return None, "Error en la creación del video"
182
+
 
 
183
  except Exception as e:
184
+ logger.exception("Error inesperado")
185
+ return None, f"Error: {str(e)}"
186
+ finally:
187
+ # Limpieza opcional (Hugging Face limpia automáticamente)
188
+ pass
189
 
190
+ # --- Interfaz de Gradio ---
191
+ with gr.Blocks(title="Generador Automático de Videos con IA", theme="soft") as demo:
192
+ gr.Markdown("# 🎬 Generador Automático de Videos con IA")
193
+ gr.Markdown("Transforma texto en videos usando contenido de Pexels y voz sintetizada")
 
194
 
195
+ with gr.Row():
196
+ with gr.Column():
197
+ text_input = gr.Textbox(
198
+ label="Texto para el video",
199
+ placeholder="Describe el contenido que quieres en el video...",
200
+ lines=5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
  )
202
+ generate_btn = gr.Button("Generar Video", variant="primary")
 
 
 
 
 
 
203
 
204
  with gr.Column():
205
+ video_output = gr.Video(label="Video Generado")
206
+ status_output = gr.Textbox(label="Estado")
207
+
208
+ generate_btn.click(
209
+ fn=generate_video,
210
+ inputs=[text_input],
211
+ outputs=[video_output, status_output]
 
 
 
 
 
 
 
 
 
 
 
212
  )
 
 
 
 
213
 
214
+ gr.Markdown("### Cómo funciona:")
215
+ gr.Markdown("""
216
+ 1. Ingresa un texto descriptivo
217
+ 2. Nuestra IA extrae palabras clave
218
+ 3. Buscamos videos relacionados en Pexels
219
+ 4. Generamos voz con Edge TTS
220
+ 5. Combinamos todo en un video final
221
+ """)
222
+
223
+ # Para Hugging Face Spaces
224
  if __name__ == "__main__":
225
+ demo.launch(server_name="0.0.0.0", server_port=7860)