File size: 3,751 Bytes
bd1531f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | """
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)},
)
|