Spaces:
Building
Building
Update pexels_api.py
Browse files- pexels_api.py +9 -68
pexels_api.py
CHANGED
@@ -1,84 +1,25 @@
|
|
|
|
1 |
import os
|
2 |
import requests
|
3 |
|
4 |
-
def get_best_video_file(video_files, min_width=1920, min_height=1080):
|
5 |
-
"""
|
6 |
-
Selecciona el mejor archivo de video basado en resolución y calidad.
|
7 |
-
Prioriza videos HD (1920x1080) o mejor, y evita formatos móviles.
|
8 |
-
"""
|
9 |
-
# Filtrar archivos que cumplan con los requisitos mínimos
|
10 |
-
suitable_files = [
|
11 |
-
f for f in video_files
|
12 |
-
if f.get("width", 0) >= min_width
|
13 |
-
and f.get("height", 0) >= min_height
|
14 |
-
and f.get("width", 0) / f.get("height", 0) >= 1.6 # Aproximadamente 16:9
|
15 |
-
]
|
16 |
-
|
17 |
-
if not suitable_files:
|
18 |
-
# Si no hay archivos que cumplan los requisitos, buscar el más grande disponible
|
19 |
-
suitable_files = video_files
|
20 |
-
|
21 |
-
# Ordenar por resolución (área total de pixels)
|
22 |
-
suitable_files.sort(
|
23 |
-
key=lambda x: (x.get("width", 0) * x.get("height", 0), x.get("quality", "")),
|
24 |
-
reverse=True
|
25 |
-
)
|
26 |
-
|
27 |
-
return suitable_files[0] if suitable_files else None
|
28 |
-
|
29 |
def search_pexels(query, num_results=5):
|
30 |
-
"""
|
31 |
-
Busca videos en Pexels y retorna los enlaces de mejor calidad.
|
32 |
-
|
33 |
-
Args:
|
34 |
-
query (str): Término de búsqueda
|
35 |
-
num_results (int): Número de videos a retornar
|
36 |
-
|
37 |
-
Returns:
|
38 |
-
list: Lista de URLs de videos
|
39 |
-
"""
|
40 |
api_key = os.getenv("PEXELS_API_KEY")
|
41 |
if not api_key:
|
42 |
raise ValueError("La variable de entorno PEXELS_API_KEY no está configurada.")
|
43 |
-
|
44 |
if not query.strip():
|
45 |
raise ValueError("La consulta no puede estar vacía.")
|
46 |
-
|
47 |
url = "https://api.pexels.com/videos/search"
|
48 |
headers = {"Authorization": api_key}
|
49 |
-
|
50 |
-
# Solicitar más videos de los necesarios para tener margen de filtrado
|
51 |
-
params = {
|
52 |
-
"query": query,
|
53 |
-
"per_page": min(num_results * 2, 15), # Pedir el doble, máximo 15
|
54 |
-
"size": "large" # Preferir videos grandes
|
55 |
-
}
|
56 |
-
|
57 |
response = requests.get(url, headers=headers, params=params)
|
58 |
-
|
59 |
if response.status_code != 200:
|
60 |
raise Exception(f"Error al buscar en Pexels: {response.status_code} - {response.text}")
|
61 |
-
|
62 |
data = response.json()
|
63 |
-
|
64 |
if "videos" not in data or not data["videos"]:
|
65 |
-
raise Exception(
|
66 |
-
|
67 |
-
|
68 |
-
video_urls = []
|
69 |
-
for video in data["videos"]:
|
70 |
-
best_file = get_best_video_file(video["video_files"])
|
71 |
-
if best_file and best_file.get("link"):
|
72 |
-
video_urls.append({
|
73 |
-
"url": best_file["link"],
|
74 |
-
"width": best_file.get("width", 0),
|
75 |
-
"height": best_file.get("height", 0),
|
76 |
-
"duration": video.get("duration", 0)
|
77 |
-
})
|
78 |
-
|
79 |
-
if not video_urls:
|
80 |
-
raise Exception(f"No se encontraron videos de calidad adecuada para: {query}")
|
81 |
-
|
82 |
-
# Ordenar por calidad y tomar los mejores
|
83 |
-
video_urls.sort(key=lambda x: (x["width"] * x["height"]), reverse=True)
|
84 |
-
return [v["url"] for v in video_urls[:num_results]]
|
|
|
1 |
+
# pexels_api.py
|
2 |
import os
|
3 |
import requests
|
4 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
def search_pexels(query, num_results=5):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
api_key = os.getenv("PEXELS_API_KEY")
|
7 |
if not api_key:
|
8 |
raise ValueError("La variable de entorno PEXELS_API_KEY no está configurada.")
|
9 |
+
|
10 |
if not query.strip():
|
11 |
raise ValueError("La consulta no puede estar vacía.")
|
12 |
+
|
13 |
url = "https://api.pexels.com/videos/search"
|
14 |
headers = {"Authorization": api_key}
|
15 |
+
params = {"query": query, "per_page": num_results}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
response = requests.get(url, headers=headers, params=params)
|
17 |
+
|
18 |
if response.status_code != 200:
|
19 |
raise Exception(f"Error al buscar en Pexels: {response.status_code} - {response.text}")
|
20 |
+
|
21 |
data = response.json()
|
|
|
22 |
if "videos" not in data or not data["videos"]:
|
23 |
+
raise Exception("No se encontraron videos relevantes para la consulta proporcionada.")
|
24 |
+
|
25 |
+
return [video["video_files"][0]["link"] for video in data["videos"]]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|