Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -175,9 +175,11 @@ def extract_keywords(text: str) -> list[str]:
|
|
| 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},
|
|
@@ -185,7 +187,10 @@ def search_pexels_videos(query: str, count: int = 3) -> list[dict]:
|
|
| 185 |
timeout=20
|
| 186 |
)
|
| 187 |
response.raise_for_status()
|
| 188 |
-
|
|
|
|
|
|
|
|
|
|
| 189 |
except Exception as e:
|
| 190 |
logger.error(f"Error buscando videos en Pexels: {e}")
|
| 191 |
return []
|
|
@@ -195,6 +200,7 @@ def download_video(url: str, folder: str) -> str | None:
|
|
| 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:
|
|
@@ -202,6 +208,7 @@ def download_video(url: str, folder: str) -> str | None:
|
|
| 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}")
|
|
@@ -292,7 +299,7 @@ def create_video(script_text: str, generate_script: bool, music_path: str | None
|
|
| 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
|
|
@@ -303,11 +310,16 @@ def create_video(script_text: str, generate_script: bool, music_path: str | None
|
|
| 303 |
logger.error(f"Clip con duraci贸n inv谩lida: {path}")
|
| 304 |
return False
|
| 305 |
|
| 306 |
-
# Verificar que podemos obtener un frame
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 311 |
|
| 312 |
return True
|
| 313 |
except Exception as e:
|
|
@@ -360,23 +372,34 @@ def create_video(script_text: str, generate_script: bool, music_path: str | None
|
|
| 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...")
|
|
@@ -388,9 +411,11 @@ def create_video(script_text: str, generate_script: bool, music_path: str | None
|
|
| 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}")
|
|
@@ -402,10 +427,12 @@ def create_video(script_text: str, generate_script: bool, music_path: str | None
|
|
| 402 |
logger.error(f"No se pudo cargar el video: {path}")
|
| 403 |
continue
|
| 404 |
|
| 405 |
-
|
|
|
|
|
|
|
| 406 |
if not validate_clip(clip, path):
|
| 407 |
-
|
| 408 |
-
|
| 409 |
|
| 410 |
# Recortar el video
|
| 411 |
duration = min(8, clip.duration)
|
|
@@ -416,22 +443,22 @@ def create_video(script_text: str, generate_script: bool, music_path: str | None
|
|
| 416 |
clip.close()
|
| 417 |
continue
|
| 418 |
|
| 419 |
-
# Validar el clip recortado
|
| 420 |
if not validate_clip(processed_clip, f"{path} (recortado)"):
|
| 421 |
-
|
| 422 |
-
clip
|
| 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 |
-
|
| 434 |
-
|
| 435 |
else:
|
| 436 |
logger.error(f"Error normalizando video: {path}")
|
| 437 |
clip.close()
|
|
@@ -442,6 +469,8 @@ def create_video(script_text: str, generate_script: bool, music_path: str | None
|
|
| 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...")
|
|
@@ -453,11 +482,12 @@ def create_video(script_text: str, generate_script: bool, music_path: str | None
|
|
| 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 |
-
|
|
|
|
| 461 |
except Exception as e:
|
| 462 |
logger.error(f"Clip inv谩lido en posici贸n {i}: {e}")
|
| 463 |
if clip is not None:
|
|
@@ -478,9 +508,11 @@ def create_video(script_text: str, generate_script: bool, music_path: str | None
|
|
| 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 |
-
|
|
|
|
|
|
|
| 484 |
|
| 485 |
except Exception as e:
|
| 486 |
logger.error(f"Error concatenando videos: {e}")
|
|
|
|
| 175 |
|
| 176 |
def search_pexels_videos(query: str, count: int = 3) -> list[dict]:
|
| 177 |
if not PEXELS_API_KEY:
|
| 178 |
+
logger.warning("PEXELS_API_KEY no est谩 definida")
|
| 179 |
return []
|
| 180 |
|
| 181 |
try:
|
| 182 |
+
logger.info(f"Buscando videos en Pexels para: {query}")
|
| 183 |
response = requests.get(
|
| 184 |
"https://api.pexels.com/videos/search",
|
| 185 |
headers={"Authorization": PEXELS_API_KEY},
|
|
|
|
| 187 |
timeout=20
|
| 188 |
)
|
| 189 |
response.raise_for_status()
|
| 190 |
+
data = response.json()
|
| 191 |
+
videos = data.get("videos", [])
|
| 192 |
+
logger.info(f"Se encontraron {len(videos)} videos para '{query}'")
|
| 193 |
+
return videos
|
| 194 |
except Exception as e:
|
| 195 |
logger.error(f"Error buscando videos en Pexels: {e}")
|
| 196 |
return []
|
|
|
|
| 200 |
filename = f"{uuid.uuid4().hex}.mp4"
|
| 201 |
filepath = os.path.join(folder, filename)
|
| 202 |
|
| 203 |
+
logger.info(f"Descargando video desde: {url}")
|
| 204 |
with requests.get(url, stream=True, timeout=60) as response:
|
| 205 |
response.raise_for_status()
|
| 206 |
with open(filepath, "wb") as f:
|
|
|
|
| 208 |
f.write(chunk)
|
| 209 |
|
| 210 |
if os.path.exists(filepath) and os.path.getsize(filepath) > 1000:
|
| 211 |
+
logger.info(f"Video descargado correctamente: {filepath} ({os.path.getsize(filepath)} bytes)")
|
| 212 |
return filepath
|
| 213 |
else:
|
| 214 |
logger.error(f"Archivo descargado inv谩lido: {filepath}")
|
|
|
|
| 299 |
return None
|
| 300 |
|
| 301 |
def validate_clip(clip, path="unknown"):
|
| 302 |
+
"""Funci贸n para validar que un clip sea usable - versi贸n menos estricta"""
|
| 303 |
if clip is None:
|
| 304 |
logger.error(f"Clip es None: {path}")
|
| 305 |
return False
|
|
|
|
| 310 |
logger.error(f"Clip con duraci贸n inv谩lida: {path}")
|
| 311 |
return False
|
| 312 |
|
| 313 |
+
# Verificar que podemos obtener un frame - MENOS ESTRICTO
|
| 314 |
+
try:
|
| 315 |
+
test_frame = clip.get_frame(0)
|
| 316 |
+
if test_frame is None:
|
| 317 |
+
logger.error(f"No se pudo obtener frame del clip: {path}")
|
| 318 |
+
return False
|
| 319 |
+
except Exception as frame_error:
|
| 320 |
+
logger.warning(f"Error al obtener frame de {path}: {frame_error}")
|
| 321 |
+
# En lugar de rechazar, intentamos continuar
|
| 322 |
+
return True
|
| 323 |
|
| 324 |
return True
|
| 325 |
except Exception as e:
|
|
|
|
| 372 |
video_paths = []
|
| 373 |
keywords = extract_keywords(script)
|
| 374 |
|
| 375 |
+
logger.info(f"Palabras clave extra铆das: {keywords}")
|
| 376 |
+
|
| 377 |
for i, keyword in enumerate(keywords[:3]):
|
| 378 |
update_task_progress(task_id, f"Paso 3/7: Buscando videos para '{keyword}' ({i+1}/{len(keywords[:3])})")
|
| 379 |
|
| 380 |
videos = search_pexels_videos(keyword, 2)
|
| 381 |
+
logger.info(f"Se encontraron {len(videos)} videos para '{keyword}'")
|
| 382 |
+
|
| 383 |
for video_data in videos:
|
| 384 |
if len(video_paths) >= 6:
|
| 385 |
break
|
| 386 |
|
| 387 |
video_files = video_data.get("video_files", [])
|
| 388 |
if video_files:
|
| 389 |
+
# Tomar el video de mejor calidad
|
| 390 |
best_file = max(video_files, key=lambda f: f.get("width", 0))
|
| 391 |
video_url = best_file.get("link")
|
| 392 |
+
video_quality = f"{best_file.get('width', 0)}x{best_file.get('height', 0)}"
|
| 393 |
+
|
| 394 |
+
logger.info(f"Intentando descargar video: {video_quality} - {video_url}")
|
| 395 |
|
| 396 |
if video_url:
|
| 397 |
downloaded_path = download_video(video_url, temp_dir)
|
| 398 |
if downloaded_path:
|
| 399 |
video_paths.append(downloaded_path)
|
| 400 |
+
logger.info(f"Video descargado exitosamente: {downloaded_path}")
|
| 401 |
+
|
| 402 |
+
logger.info(f"Total de videos descargados: {len(video_paths)}")
|
| 403 |
|
| 404 |
if not video_paths:
|
| 405 |
logger.warning("No se pudieron descargar videos de Pexels, creando video de respaldo...")
|
|
|
|
| 411 |
update_task_progress(task_id, f"Paso 4/7: Procesando {len(video_paths)} videos...")
|
| 412 |
video_clips = []
|
| 413 |
|
| 414 |
+
for i, path in enumerate(video_paths):
|
| 415 |
clip = None
|
| 416 |
try:
|
| 417 |
+
logger.info(f"Procesando video {i+1}/{len(video_paths)}: {path}")
|
| 418 |
+
|
| 419 |
# Verificar que el archivo exista y tenga tama帽o
|
| 420 |
if not os.path.exists(path) or os.path.getsize(path) < 1024:
|
| 421 |
logger.error(f"Archivo inv谩lido: {path}")
|
|
|
|
| 427 |
logger.error(f"No se pudo cargar el video: {path}")
|
| 428 |
continue
|
| 429 |
|
| 430 |
+
logger.info(f"Video cargado: {path} - Duraci贸n: {clip.duration}s - Tama帽o: {clip.size}")
|
| 431 |
+
|
| 432 |
+
# Validar el clip original - MENOS ESTRICTO
|
| 433 |
if not validate_clip(clip, path):
|
| 434 |
+
logger.warning(f"Clip inv谩lido, pero intentando usarlo igualmente: {path}")
|
| 435 |
+
# No cerramos el clip, lo intentamos usar igualmente
|
| 436 |
|
| 437 |
# Recortar el video
|
| 438 |
duration = min(8, clip.duration)
|
|
|
|
| 443 |
clip.close()
|
| 444 |
continue
|
| 445 |
|
| 446 |
+
# Validar el clip recortado - MENOS ESTRICTO
|
| 447 |
if not validate_clip(processed_clip, f"{path} (recortado)"):
|
| 448 |
+
logger.warning(f"Clip recortado inv谩lido, pero intentando usarlo igualmente: {path}")
|
| 449 |
+
# No cerramos el clip, lo intentamos usar igualmente
|
|
|
|
| 450 |
|
| 451 |
# Normalizar
|
| 452 |
processed_clip = normalize_clip(processed_clip)
|
| 453 |
|
| 454 |
if processed_clip is not None:
|
| 455 |
+
# Validaci贸n final del clip procesado - MENOS ESTRICTO
|
| 456 |
if validate_clip(processed_clip, f"{path} (normalizado)"):
|
| 457 |
video_clips.append(processed_clip)
|
| 458 |
+
logger.info(f"Video procesado exitosamente: {path}")
|
| 459 |
else:
|
| 460 |
+
logger.warning(f"Clip normalizado inv谩lido, pero intentando usarlo igualmente: {path}")
|
| 461 |
+
video_clips.append(processed_clip) # Lo usamos igualmente
|
| 462 |
else:
|
| 463 |
logger.error(f"Error normalizando video: {path}")
|
| 464 |
clip.close()
|
|
|
|
| 469 |
if clip is not None:
|
| 470 |
clip.close()
|
| 471 |
|
| 472 |
+
logger.info(f"Total de videos procesados exitosamente: {len(video_clips)}")
|
| 473 |
+
|
| 474 |
# Verificar si tenemos clips v谩lidos
|
| 475 |
if not video_clips:
|
| 476 |
logger.warning("No se procesaron videos v谩lidos, creando video de respaldo...")
|
|
|
|
| 482 |
valid_clips = []
|
| 483 |
for i, clip in enumerate(video_clips):
|
| 484 |
try:
|
| 485 |
+
# Verificaci贸n final de cada clip - MENOS ESTRICTA
|
| 486 |
if validate_clip(clip, f"clip_{i}"):
|
| 487 |
valid_clips.append(clip)
|
| 488 |
else:
|
| 489 |
+
logger.warning(f"Clip inv谩lido en posici贸n {i}, pero intentando usarlo igualmente")
|
| 490 |
+
valid_clips.append(clip) # Lo usamos igualmente
|
| 491 |
except Exception as e:
|
| 492 |
logger.error(f"Clip inv谩lido en posici贸n {i}: {e}")
|
| 493 |
if clip is not None:
|
|
|
|
| 508 |
if base_video is None:
|
| 509 |
raise RuntimeError("La concatenaci贸n devolvi贸 None")
|
| 510 |
|
| 511 |
+
# Validar el video concatenado - MENOS ESTRICTO
|
| 512 |
if not validate_clip(base_video, "video_concatenado"):
|
| 513 |
+
logger.warning("Video concatenado inv谩lido, pero intentando usarlo igualmente")
|
| 514 |
+
|
| 515 |
+
logger.info(f"Video concatenado exitosamente. Duraci贸n: {base_video.duration}s")
|
| 516 |
|
| 517 |
except Exception as e:
|
| 518 |
logger.error(f"Error concatenando videos: {e}")
|