Spaces:
Runtime error
Runtime error
Update app.py
Browse files
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 |
-
#
|
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 |
-
#
|
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 |
-
#
|
42 |
try:
|
43 |
-
kw_model = KeyBERT('
|
44 |
logger.info("Modelo KeyBERT cargado exitosamente.")
|
45 |
except Exception as e:
|
46 |
-
logger.error(f"Error al cargar
|
47 |
kw_model = None
|
48 |
|
49 |
-
# --- Funciones
|
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"
|
82 |
-
|
83 |
try:
|
84 |
communicate = edge_tts.Communicate(text, voice)
|
85 |
await communicate.save(output_path)
|
86 |
-
|
87 |
except Exception as e:
|
88 |
-
logger.error(f"Error
|
89 |
-
|
90 |
|
91 |
-
def
|
92 |
-
|
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 |
-
|
|
|
|
|
|
|
106 |
for chunk in response.iter_content(chunk_size=8192):
|
107 |
-
|
108 |
-
|
109 |
-
|
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
|
118 |
-
if os.path.exists(output_path):
|
119 |
-
os.remove(output_path)
|
120 |
return None
|
121 |
|
122 |
-
def
|
123 |
-
|
124 |
-
|
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 |
-
|
148 |
-
|
149 |
-
keyphrase_ngram_range=(1, 2),
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
diversity=0.7
|
154 |
)
|
155 |
-
|
156 |
-
all_keywords.add(kw.replace(" ", "+"))
|
157 |
except Exception as e:
|
158 |
-
logger.warning(f"Error
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
|
|
163 |
|
164 |
-
|
165 |
-
|
166 |
if not PEXELS_API_KEY:
|
167 |
-
logger.error("
|
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 |
-
|
|
|
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":
|
186 |
-
"orientation": "landscape",
|
187 |
-
"
|
188 |
}
|
189 |
|
190 |
-
response = requests.get(
|
191 |
-
|
|
|
|
|
|
|
|
|
192 |
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
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
|
219 |
-
|
220 |
-
|
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 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
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 |
-
|
272 |
-
|
273 |
-
|
|
|
|
|
274 |
|
275 |
-
|
276 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
277 |
|
278 |
-
|
279 |
-
|
280 |
-
|
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 |
-
|
295 |
-
|
296 |
-
|
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 |
-
|
308 |
-
|
309 |
-
|
310 |
-
|
311 |
-
|
312 |
-
|
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 |
-
|
325 |
-
|
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 |
-
|
351 |
-
|
352 |
-
|
353 |
-
|
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 |
-
|
383 |
-
|
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.
|
388 |
-
return None,
|
|
|
|
|
|
|
389 |
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
""")
|
395 |
|
396 |
-
with gr.
|
397 |
-
with gr.
|
398 |
-
|
399 |
-
|
400 |
-
|
401 |
-
|
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 |
-
|
427 |
-
|
428 |
-
|
429 |
-
|
430 |
-
fn=
|
431 |
-
|
432 |
-
|
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 |
-
|
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)
|
|