Files

370 lines
12 KiB
Python

"""
Pixabay video search proxy with persistent per-query clip-sequence cache.
For background stock video playback we do not want a single short clip that
ends long before the song does. This module therefore selects a *sequence* of
Pixabay video hits whose combined duration reaches or exceeds the requested
target duration. The chosen sequence is cached on disk and replayed on future
requests for the same query/settings.
Clip selection policy:
1. Prefer clips with duration inside the configured [min, max] window.
2. If none exist, fall back to clips >= min duration.
3. If still none exist, fall back to any playable clip.
4. Keep appending clips until cumulative duration >= target_duration.
The cache can be toggled via Settings → Integrations (``pixabay_cache_enabled``).
Configure the Pixabay API key via:
• Settings → Integrations (stored in settings.json as ``pixabay_api_key``)
• Environment variable ``PIXABAY_API_KEY``
"""
import json
import os
import random
from datetime import datetime, timezone
from typing import Any
import httpx
from fastapi import APIRouter, HTTPException, Query
from ..config import PIXABAY_CACHE_PATH
from .settings import _load as _load_settings
router = APIRouter(prefix="/api/pixabay", tags=["pixabay"])
_PIXABAY_VIDEO_URL = "https://pixabay.com/api/videos/"
# ── helpers ───────────────────────────────────────────────────────────────────
def _get_api_key() -> str | None:
"""Return Pixabay API key from settings.json or PIXABAY_API_KEY env var."""
stored = _load_settings().get("pixabay_api_key")
return stored or os.environ.get("PIXABAY_API_KEY") or None
def _cache_enabled() -> bool:
return bool(_load_settings().get("pixabay_cache_enabled", True))
def _clip_window_defaults() -> tuple[float, float]:
settings = _load_settings()
min_clip = float(settings.get("pixabay_min_clip_duration", 15) or 15)
max_clip = float(settings.get("pixabay_max_clip_duration", 20) or 20)
min_clip = max(1.0, min(300.0, min_clip))
max_clip = max(1.0, min(300.0, max_clip))
if max_clip < min_clip:
max_clip = min_clip
return min_clip, max_clip
def _load_cache() -> dict:
if not PIXABAY_CACHE_PATH.exists():
return {}
try:
return json.loads(PIXABAY_CACHE_PATH.read_text(encoding="utf-8"))
except Exception:
return {}
def _save_cache(data: dict) -> None:
PIXABAY_CACHE_PATH.parent.mkdir(parents=True, exist_ok=True)
PIXABAY_CACHE_PATH.write_text(
json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8"
)
def _cache_key(q: str) -> str:
return q.strip().lower()
def _cache_key_with_options(
q: str,
target_duration: float | None,
min_clip_duration: float,
max_clip_duration: float,
) -> str:
base = _cache_key(q)
target_part = f"{round(target_duration or 0, 2):g}"
return f"{base}|target={target_part}|min={round(min_clip_duration, 2):g}|max={round(max_clip_duration, 2):g}"
def _best_video_variant(hit: dict) -> dict:
videos = hit.get("videos", {})
return (
videos.get("large")
or videos.get("medium")
or videos.get("small")
or videos.get("tiny")
or {}
)
def _hit_has_playable_url(hit: dict) -> bool:
return bool(_best_video_variant(hit).get("url"))
def _hit_to_cache_hit(hit: dict) -> dict:
"""Flatten a Pixabay hit while keeping enough data to reconstruct it later."""
videos = hit.get("videos", {})
best: dict = _best_video_variant(hit)
return {
"hit_id": hit.get("id"),
"url": best.get("url", ""),
"thumbnail": best.get("thumbnail", ""),
"tags": hit.get("tags", ""),
"duration": hit.get("duration", 0),
"user": hit.get("user", ""),
"videos": videos,
}
def _hits_to_cache_entry(
hits: list[dict],
query: str,
target_duration: float | None,
min_clip_duration: float,
max_clip_duration: float,
) -> dict:
total_duration = sum(float(hit.get("duration") or 0) for hit in hits)
return {
"query": query,
"cached_at": datetime.now(timezone.utc).isoformat(),
"target_duration": target_duration,
"min_clip_duration": min_clip_duration,
"max_clip_duration": max_clip_duration,
"clip_count": len(hits),
"total_duration": total_duration,
"hits": [_hit_to_cache_hit(hit) for hit in hits],
}
def _cache_hit_to_hit(entry: dict) -> dict:
"""Reconstruct a minimal PixabayVideoHit dict from a cache hit entry."""
return {
"id": entry.get("hit_id", 0),
"pageURL": "",
"type": "film",
"tags": entry.get("tags", ""),
"duration": entry.get("duration", 0),
"picture_id": "",
"videos": entry.get("videos", {}),
"views": 0,
"downloads": 0,
"likes": 0,
"user": entry.get("user", ""),
}
def _cache_entry_to_hits(entry: dict) -> list[dict]:
"""Support both the new multi-hit cache format and legacy single-hit entries."""
if isinstance(entry.get("hits"), list):
return [_cache_hit_to_hit(hit) for hit in entry.get("hits", []) if isinstance(hit, dict)]
if isinstance(entry.get("videos"), dict):
return [_cache_hit_to_hit(entry)]
return []
def _select_hits_for_playlist(
hits: list[dict],
target_duration: float | None,
min_clip_duration: float,
max_clip_duration: float,
) -> list[dict]:
playable = [hit for hit in hits if _hit_has_playable_url(hit)]
if not playable:
return []
preferred = [
hit for hit in playable
if min_clip_duration <= float(hit.get("duration") or 0) <= max_clip_duration
]
long_enough = [
hit for hit in playable
if float(hit.get("duration") or 0) >= min_clip_duration
]
pool = preferred or long_enough or playable
shuffled = pool[:]
random.shuffle(shuffled)
# When no target duration is specified, still return a single best-fit clip.
if not target_duration or target_duration <= 0:
return [shuffled[0]]
selected: list[dict] = []
total_duration = 0.0
for hit in shuffled:
selected.append(hit)
total_duration += float(hit.get("duration") or 0)
if total_duration >= target_duration:
return selected
# Not enough unique clips in the preferred pool; repeat from the same pool as a fallback.
if not selected:
return []
while total_duration < target_duration:
repeat_pool = [hit for hit in pool if hit.get("id") != selected[-1].get("id")] or pool
hit = random.choice(repeat_pool)
selected.append(hit)
total_duration += float(hit.get("duration") or 0)
return selected
# ── search endpoint ───────────────────────────────────────────────────────────
@router.get("/videos")
async def search_pixabay_videos(
q: str = Query(..., description="Free-text search query"),
per_page: int = Query(50, ge=3, le=200),
video_type: str = Query("film", description="all | film | animation"),
page: int = Query(1, ge=1),
target_duration: float | None = Query(None, ge=0, description="Desired cumulative duration in seconds"),
min_clip_duration: float | None = Query(None, ge=1, le=300, description="Preferred minimum clip duration in seconds"),
max_clip_duration: float | None = Query(None, ge=1, le=300, description="Preferred maximum clip duration in seconds"),
) -> Any:
"""
Proxy a Pixabay video search, with optional persistent cache.
• Cache hit → returns a single-element hits array immediately (no API call).
• Cache miss → fetches Pixabay, picks one random hit, stores it, returns it.
Always returns a single-element ``hits`` array so the frontend gets a
deterministic URL for the same track on every play.
Returns 503 when no API key is configured.
Returns 502 when Pixabay itself returns an error.
"""
key = _get_api_key()
if not key:
raise HTTPException(
status_code=503,
detail=(
"Pixabay API key is not configured. "
"Add it in Settings → Integrations or set the PIXABAY_API_KEY environment variable."
),
)
defaults_min, defaults_max = _clip_window_defaults()
min_clip_duration = float(min_clip_duration if min_clip_duration is not None else defaults_min)
max_clip_duration = float(max_clip_duration if max_clip_duration is not None else defaults_max)
if max_clip_duration < min_clip_duration:
max_clip_duration = min_clip_duration
ck = _cache_key_with_options(q, target_duration, min_clip_duration, max_clip_duration)
if _cache_enabled():
cache = _load_cache()
if ck in cache:
hits = _cache_entry_to_hits(cache[ck])
return {
"total": len(hits),
"totalHits": len(hits),
"hits": hits,
"selected_total_duration_seconds": cache[ck].get("total_duration", sum(float(hit.get("duration") or 0) for hit in hits)),
}
params: dict[str, Any] = {
"key": key,
"q": q,
"per_page": per_page,
"video_type": video_type,
"page": page,
"safesearch": "true",
}
try:
async with httpx.AsyncClient(timeout=10.0) as client:
resp = await client.get(_PIXABAY_VIDEO_URL, params=params)
except httpx.TimeoutException:
raise HTTPException(status_code=504, detail="Pixabay request timed out.")
except httpx.RequestError as exc:
raise HTTPException(status_code=502, detail=f"Pixabay request failed: {exc}")
if resp.status_code != 200:
raise HTTPException(
status_code=502,
detail=f"Pixabay returned HTTP {resp.status_code}.",
)
data = resp.json()
hits: list[dict] = data.get("hits", [])
selected_hits = _select_hits_for_playlist(
hits,
target_duration=target_duration,
min_clip_duration=min_clip_duration,
max_clip_duration=max_clip_duration,
)
if selected_hits and _cache_enabled():
cache = _load_cache()
cache[ck] = _hits_to_cache_entry(
selected_hits,
q,
target_duration=target_duration,
min_clip_duration=min_clip_duration,
max_clip_duration=max_clip_duration,
)
_save_cache(cache)
if selected_hits:
return {
"total": len(selected_hits),
"totalHits": len(selected_hits),
"hits": selected_hits,
"selected_total_duration_seconds": sum(float(hit.get("duration") or 0) for hit in selected_hits),
}
return {
**data,
"selected_total_duration_seconds": 0,
}
# ── cache management endpoints ────────────────────────────────────────────────
@router.get("/cache")
def list_cache() -> Any:
"""Return all cache entries (summary only — no full videos blob)."""
cache = _load_cache()
return [
{
"key": k,
"query": v.get("query", k),
"url": v.get("url", ""),
"thumbnail": v.get("thumbnail", ""),
"tags": v.get("tags", ""),
"duration": v.get("duration", 0),
"user": v.get("user", ""),
"cached_at": v.get("cached_at", ""),
"clip_count": v.get("clip_count", len(v.get("hits", [])) or (1 if v.get("videos") else 0)),
"total_duration_seconds": v.get("total_duration", v.get("duration", 0)),
}
for k, v in cache.items()
]
@router.delete("/cache")
def clear_cache() -> Any:
"""Delete all cached video selections."""
_save_cache({})
return {"deleted": "all"}
@router.delete("/cache/{entry_key:path}")
def delete_cache_entry(entry_key: str) -> Any:
"""Delete a single cache entry by its normalised query key."""
cache = _load_cache()
ck = entry_key.strip().lower()
if ck not in cache:
raise HTTPException(status_code=404, detail=f"Cache entry '{ck}' not found.")
del cache[ck]
_save_cache(cache)
return {"deleted": ck}