from fastapi import FastAPI, HTTPException from pydantic import BaseModel import os import asyncio from smart_searchV2 import SmartSearch #from dotenv import load_dotenv #load_dotenv() # Uncomment this if you have a .env file app = FastAPI() LOAD_BALANCER_URL = os.getenv("LOAD_BALANCER_URL") # Verify URL format if not LOAD_BALANCER_URL or "://" not in LOAD_BALANCER_URL: raise ValueError("Invalid LOAD_BALANCER_URL format. Must include protocol (http/https)") search_system = SmartSearch( films_url=f'{LOAD_BALANCER_URL}/api/get/movie/all', tv_series_url=f'{LOAD_BALANCER_URL}/api/get/series/all' ) search_system_lock = asyncio.Lock() @app.on_event("startup") async def startup_event(): # Initial immediate load async with search_system_lock: await search_system.initialize() # Start background updates asyncio.create_task(update_data_periodically()) async def update_data_periodically(): while True: try: async with search_system_lock: await search_system.update_data() except Exception as e: print(f"Update failed: {e}. Retrying...") await asyncio.sleep(60) # Wait longer on error else: await asyncio.sleep(120) class Query(BaseModel): query: str @app.get("/") async def index(): return {"status": "running"} @app.post("/api/search") async def search(query: Query): if not query.query.strip(): raise HTTPException(status_code=400, detail="Empty query") async with search_system_lock: if not search_system.is_initialized: raise HTTPException(status_code=503, detail="Search system initializing") results = await search_system.search(query.query.strip()) # Added await here return results @app.get("/health") async def health_check(): return { "initialized": search_system.is_initialized, "film_count": len(search_system.data['films']), "series_count": len(search_system.data['series']) } @app.get("/api/data") async def get_data(): async with search_system_lock: if not search_system.is_initialized: raise HTTPException(status_code=503, detail="Search system is not initialized yet.") return {"data":search_system.data}