""" Oxinto AI — FastAPI Backend Deployed to Hugging Face Spaces (Docker SDK) on port 7860. """ import logging import sys from contextlib import asynccontextmanager from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from data_loader import reload_data, get_products from routes.recommend import router as recommend_router # ── Logging ────────────────────────────────────────────────────────────────── logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s — %(message)s", handlers=[logging.StreamHandler(sys.stdout)], ) logger = logging.getLogger(__name__) VERSION = "1.0.0" # ── Startup / Shutdown ──────────────────────────────────────────────────────── @asynccontextmanager async def lifespan(app: FastAPI): logger.info("Oxinto AI backend starting — loading product catalog...") reload_data() n = len(get_products()) logger.info("Ready. %d products loaded.", n) yield logger.info("Oxinto AI backend shutting down.") # ── App ─────────────────────────────────────────────────────────────────────── app = FastAPI( title="Oxinto AI — Recommendation API", description="AI-powered product recommendation engine. POST /recommend with a natural-language query.", version=VERSION, lifespan=lifespan, docs_url="/docs", redoc_url="/redoc", ) # ── CORS — allow all origins so the Vercel frontend can connect ─────────────── app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=False, # must be False when allow_origins=["*"] allow_methods=["*"], allow_headers=["*"], ) # ── Routes ──────────────────────────────────────────────────────────────────── app.include_router(recommend_router) # ── Health check ────────────────────────────────────────────────────────────── @app.get("/health", tags=["System"]) async def health(): """Returns API health status and catalog size.""" products = get_products() return { "status": "ok", "version": VERSION, "products_loaded": len(products), } @app.get("/", tags=["System"]) async def root(): return { "name": "Oxinto AI Recommendation API", "version": VERSION, "docs": "/docs", "health": "/health", "endpoints": { "POST /recommend": "Simple query-based recommendation", "POST /recommend/full": "Structured questionnaire-based recommendation", }, } # ── Global error handler ────────────────────────────────────────────────────── @app.exception_handler(Exception) async def global_exception_handler(request: Request, exc: Exception): logger.exception("Unhandled error on %s %s", request.method, request.url.path) return JSONResponse( status_code=500, content={"error": "Internal server error", "detail": str(exc)}, )