""" CraftMovies Hugging Face Space API ================================== FastAPI backend for CraftMovies, ready for Hugging Face Spaces Docker hosting. Default port: 7860 Local run: python -m uvicorn main:app --host 0.0.0.0 --port 7860 Endpoints: GET / GET /health GET /api/home GET /api/search?q=lucifer GET /api/search-all?q=lucifer&limit_tv=1&limit_episodes=5 GET /api/fetch-movies GET /api/fetch-tv GET /api/browse/movie GET /api/browse/tv GET /api/movie?url=/movie/5nspt-the-avengers-2012 GET /api/tv-show?url=/tv/56tj4-lucifer&limit_episodes=5 GET /api/episode?url=/tv/56tj4-lucifer/season/1/episode/3 """ from __future__ import annotations import hashlib import json import os import time from typing import Any, Callable, Optional from fastapi import FastAPI, HTTPException, Query, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse, RedirectResponse from craftmovies import CraftMovies, CraftMoviesConfig class Settings: """Environment settings for Hugging Face Space deployment.""" BASE_URL: str = os.getenv("CRAFTMOVIES_BASE_URL", "https://streamimdb.ru") REQUEST_TIMEOUT: int = int(os.getenv("CRAFTMOVIES_TIMEOUT", "15")) DEBUG: bool = os.getenv("CRAFTMOVIES_DEBUG", "false").lower() == "true" CACHE_TTL_SECONDS: int = int(os.getenv("CRAFTMOVIES_CACHE_TTL_SECONDS", "300")) CORS_ORIGINS: list[str] = [ origin.strip() for origin in os.getenv("CRAFTMOVIES_CORS_ORIGINS", "*").split(",") if origin.strip() ] settings = Settings() app = FastAPI( title="CraftMovies API", description=( "Hugging Face Spaces-ready API for CraftMovies. " "Returns metadata, seasons, episodes, posters, recommendations, and visible iframe embed URLs." ), version="1.0.0", docs_url="/docs", redoc_url="/redoc", ) app.add_middleware( CORSMiddleware, allow_origins=settings.CORS_ORIGINS, allow_credentials=True, allow_methods=["GET", "DELETE"], allow_headers=["*"], ) cm = CraftMovies( CraftMoviesConfig( base_url=settings.BASE_URL, timeout=settings.REQUEST_TIMEOUT, debug=settings.DEBUG, ) ) _CACHE: dict[str, dict[str, Any]] = {} def make_cache_key(name: str, params: dict[str, Any]) -> str: payload = json.dumps({"name": name, "params": params}, sort_keys=True, ensure_ascii=False) return hashlib.sha256(payload.encode("utf-8")).hexdigest() def get_cached(key: str) -> Optional[Any]: item = _CACHE.get(key) if not item: return None age = time.time() - item["created_at"] if age > settings.CACHE_TTL_SECONDS: _CACHE.pop(key, None) return None return item["value"] def set_cached(key: str, value: Any) -> None: _CACHE[key] = {"created_at": time.time(), "value": value} def cached_call(name: str, params: dict[str, Any], fn: Callable[[], Any], refresh: bool = False) -> Any: key = make_cache_key(name, params) if not refresh: cached = get_cached(key) if cached is not None: if isinstance(cached, dict): cached = dict(cached) cached["_cache"] = "hit" return cached value = fn() if isinstance(value, dict): value["_cache"] = "miss" set_cached(key, value) return value def require_url(value: Optional[str]) -> str: if not value or not value.strip(): raise HTTPException(status_code=400, detail="Missing required query parameter: url") return value.strip() @app.exception_handler(Exception) async def general_exception_handler(request: Request, exc: Exception): return JSONResponse( status_code=500, content={ "error": "Internal server error", "details": str(exc), "path": str(request.url.path), }, ) @app.get("/", include_in_schema=False) def root(): """Redirect root to docs for easy Hugging Face Space testing.""" return RedirectResponse(url="/docs") @app.get("/health") def health(): return { "status": "ok", "service": "CraftMovies API", "environment": "huggingface-space", "base_url": settings.BASE_URL, "cache_ttl_seconds": settings.CACHE_TTL_SECONDS, "docs": "/docs", } @app.get("/api/cache/stats") def cache_stats(): return {"items": len(_CACHE), "ttl_seconds": settings.CACHE_TTL_SECONDS} @app.delete("/api/cache") def clear_cache(): _CACHE.clear() return {"status": "cleared"} @app.get("/api/home") def api_home(refresh: bool = Query(False)): return cached_call( "home", {"base_url": settings.BASE_URL}, lambda: cm.home(), refresh=refresh, ) @app.get("/api/search") def api_search( q: str = Query(..., min_length=1, description="Search query"), refresh: bool = Query(False), ): return cached_call( "search", {"q": q, "base_url": settings.BASE_URL}, lambda: cm.search(q), refresh=refresh, ) @app.get("/api/search-all") def api_search_all( q: str = Query(..., min_length=1, description="Search query"), include_episode_details: bool = Query(True, description="Fetch episode pages for TV results"), limit_tv: int = Query(0, ge=0, description="Max TV shows to expand. 0 means all."), limit_episodes: int = Query(0, ge=0, description="Max episode pages per show. 0 means all."), refresh: bool = Query(False), ): return cached_call( "search_all", { "q": q, "include_episode_details": include_episode_details, "limit_tv": limit_tv, "limit_episodes": limit_episodes, "base_url": settings.BASE_URL, }, lambda: cm.searchAll( q, include_episode_details=include_episode_details, limit_tv=limit_tv, limit_episodes=limit_episodes, ), refresh=refresh, ) @app.get("/api/fetch-movies") def api_fetch_movies( include_details: bool = Query(False), limit_items: int = Query(0, ge=0), refresh: bool = Query(False), ): return cached_call( "fetch_movies", { "include_details": include_details, "limit_items": limit_items, "base_url": settings.BASE_URL, }, lambda: cm.fetchMovies(include_details=include_details, limit_items=limit_items), refresh=refresh, ) @app.get("/api/fetch-tv") def api_fetch_tv( include_details: bool = Query(False), include_episode_details: bool = Query(False), limit_items: int = Query(0, ge=0), limit_episodes: int = Query(0, ge=0), refresh: bool = Query(False), ): return cached_call( "fetch_tv", { "include_details": include_details, "include_episode_details": include_episode_details, "limit_items": limit_items, "limit_episodes": limit_episodes, "base_url": settings.BASE_URL, }, lambda: cm.fetchTV( include_details=include_details, include_episode_details=include_episode_details, limit_items=limit_items, limit_episodes=limit_episodes, ), refresh=refresh, ) @app.get("/api/browse/{media_type}") def api_browse( media_type: str, include_details: bool = Query(False), include_episode_details: bool = Query(False), limit_items: int = Query(0, ge=0), limit_episodes: int = Query(0, ge=0), refresh: bool = Query(False), ): if media_type not in {"movie", "tv"}: raise HTTPException(status_code=400, detail="media_type must be 'movie' or 'tv'") return cached_call( "browse", { "media_type": media_type, "include_details": include_details, "include_episode_details": include_episode_details, "limit_items": limit_items, "limit_episodes": limit_episodes, "base_url": settings.BASE_URL, }, lambda: cm.browse( media_type, include_details=include_details, include_episode_details=include_episode_details, limit_items=limit_items, limit_episodes=limit_episodes, ), refresh=refresh, ) @app.get("/api/movie") def api_movie( url: str = Query(..., description="Movie URL/path"), refresh: bool = Query(False), ): target_url = require_url(url) return cached_call( "movie", {"url": target_url, "base_url": settings.BASE_URL}, lambda: cm.movie(target_url), refresh=refresh, ) @app.get("/api/tv-show") def api_tv_show( url: str = Query(..., description="TV show URL/path"), full: bool = Query(True, description="Fetch episode pages too"), limit_episodes: int = Query(0, ge=0), refresh: bool = Query(False), ): target_url = require_url(url) return cached_call( "tv_show", { "url": target_url, "full": full, "limit_episodes": limit_episodes, "base_url": settings.BASE_URL, }, lambda: cm.tvShow(target_url, full=full, limit_episodes=limit_episodes), refresh=refresh, ) @app.get("/api/episode") def api_episode( url: str = Query(..., description="Episode URL/path"), refresh: bool = Query(False), ): target_url = require_url(url) return cached_call( "episode", {"url": target_url, "base_url": settings.BASE_URL}, lambda: cm.episode(target_url), refresh=refresh, )