marcolouis's picture
refactor: Revise FastAPI app structure and enhance documentation
9031b79
Raw History Blame Contribute Delete
12.7 kB
"""
FastAPI backend for Explore AI Recommender System
Provides recommendations, explore feed, and online learning updates.
"""
from fastapi import FastAPI, HTTPException, Header, Query, BackgroundTasks
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Optional
import os
import uvicorn
import json
from model.recommender import Recommender, init_recommender
from utils.supabase_client import get_supabase_client
from dotenv import load_dotenv
load_dotenv()
app = FastAPI(
title="Explore AI Recommender API",
description="API for personalized recommendations with online learning",
version="2.0.0",
)
# Allow all CORS requests (for Flutter app)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
recommender: Optional[Recommender] = None
supabase = get_supabase_client()
ADMIN_KEY = os.getenv("SECRET_KEY")
if not ADMIN_KEY:
raise RuntimeError("SECRET_KEY must be set in .env file")
def get_recommender() -> Recommender:
"""Loads the recommender model once and reuses it."""
global recommender
if recommender is None:
try:
recommender = init_recommender()
except Exception:
recommender = Recommender()
return recommender
@app.on_event("startup")
def startup_event():
get_recommender()
# ==================== BASIC ENDPOINTS ====================
@app.get("/")
def root():
return {
"message": "🚀Romio Explore AI Recommender API with Online Learning!",
"version": "2.0.0",
"features": ["recommendations", "online_learning"],
"endpoints": {
"health": "/health",
"recommend": "/recommend/{userId}",
"explore": "/explore/{userId}",
"track_interaction": "/track-interaction",
"online_stats": "/online-stats",
"docs": "/docs",
"redoc": "/redoc",
},
}
@app.get("/health")
def health():
return {"status": "ok"}
@app.get("/recommend/{userId}")
def recommend(userId: str, limit: int = 10):
"""Return ML-recommended plan IDs for a user."""
try:
recs = get_recommender().recommend_for_user(userId, limit)
return {"userId": userId, "limit": limit, "recommendations": recs}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/explore/{userId}")
def explore(
userId: str,
page: int = Query(1, ge=1),
limit: int = Query(20, ge=1, le=100),
):
"""Explore feed with pagination + enriched plan/creator/places data."""
try:
all_recs = get_recommender().recommend_for_user(userId, limit=10000)
totalItems = len(all_recs)
start = (page - 1) * limit
end = start + limit
paginated_recs = all_recs[start:end]
if not paginated_recs:
return {"page": page, "perPage": limit, "totalItems": totalItems, "items": []}
item_ids = [rec["item_id"] for rec in paginated_recs]
# Fetch plans except the user's own
response = (
supabase.table("plans")
.select("*")
.in_("id", item_ids)
.neq("userId", userId)
.execute()
)
if not response.data:
raise HTTPException(status_code=404, detail="No matching plans found")
# Fetch creator info once
userIds = list({item["userId"] for item in response.data})
users_response = supabase.table("users").select("*").in_("id", userIds).execute()
users_lookup = {u["id"]: u for u in users_response.data}
score_lookup = {r["item_id"]: r["score"] for r in paginated_recs}
item_order = {r["item_id"]: idx for idx, r in enumerate(paginated_recs)}
enrichedItems = []
for plan in response.data:
enrichedItems.append(
format_plan_for_flutter(plan, score_lookup, users_lookup)
)
# Sort by recommendation rank
enrichedItems.sort(key=lambda x: item_order.get(str(x["id"]), 999999))
return {
"page": page,
"perPage": limit,
"totalItems": totalItems,
"items": enrichedItems,
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# ==================== DATA FORMATTING HELPERS ====================
def format_plan_for_flutter(plan: dict, score_lookup: dict, users_lookup: dict) -> dict:
"""Formats a plan to match Flutter ExplorePlanModel structure."""
plan_id = str(plan["id"])
# Convert interestIds JSON → Python list
raw_interest_ids = plan.get("interestIds")
interest_ids = []
if isinstance(raw_interest_ids, str):
try:
interest_ids = json.loads(raw_interest_ids)
except json.JSONDecodeError:
interest_ids = []
elif isinstance(raw_interest_ids, list):
interest_ids = raw_interest_ids
# Convert placeIds JSON → Python list
raw_place_ids = plan.get("placeIds")
place_ids = []
if isinstance(raw_place_ids, str):
try:
place_ids = json.loads(raw_place_ids)
except json.JSONDecodeError:
place_ids = []
elif isinstance(raw_place_ids, list):
place_ids = raw_place_ids
# Fetch linked places
places = []
if place_ids:
try:
places_response = (
supabase.table("places").select("*").in_("id", place_ids).execute()
)
for place in places_response.data or []:
formatted_place = format_place_for_flutter(place)
places.append(formatted_place)
except Exception as e:
print(f"[WARN] Failed to fetch places: {e}")
places = []
# Fetch interest objects
interests = []
if interest_ids:
try:
interests_response = (
supabase.table("interests").select("*").in_("id", interest_ids).execute()
)
for intr in interests_response.data or []:
interests.append(
{
"id": intr.get("id"),
"title": intr.get("title"),
"imageUrl": intr.get("imageUrl"),
}
)
except Exception as e:
print(f"[WARN] Failed to fetch interests: {e}")
interests = []
creator = users_lookup.get(plan.get("userId"))
return {
"id": plan.get("id"),
"userId": plan.get("userId"),
"city": plan.get("city"),
"country": plan.get("country"),
"rating": float(plan.get("rating", 0)),
"minPrice": int(plan.get("minPrice", 0)),
"maxPrice": int(plan.get("maxPrice", 0)),
"minDist": plan.get("minDist"),
"maxDist": plan.get("maxDist"),
"createdAt": plan.get("createdAt"),
"updatedAt": plan.get("updatedAt"),
"interests": interests,
"placeIds": place_ids,
"score": float(score_lookup.get(plan_id, 0.0)),
"places": places,
"creator": creator,
}
def format_place_for_flutter(place: dict) -> dict:
"""Formats a place object for Flutter ExplorePlaceModel."""
# Convert category JSON
categories = []
raw_categories = place.get("categories")
if isinstance(raw_categories, str):
try:
categories = json.loads(raw_categories)
except json.JSONDecodeError:
categories = []
elif isinstance(raw_categories, list):
categories = raw_categories
# Convert other JSON fields
extended_location = parse_json_field(place.get("extendedLocation"))
related_places = parse_json_field(place.get("relatedPlaces"))
social_media = parse_json_field(place.get("socialMedia"))
location = parse_json_field(place.get("location"))
return {
"id": place.get("id"),
"name": place.get("name"),
"latitude": place.get("latitude"),
"longitude": place.get("longitude"),
"distance": place.get("distance"),
"link": place.get("link"),
"tel": place.get("tel"),
"website": place.get("website"),
"placemakerUrl": place.get("placemakerUrl"),
"dateCreated": place.get("dateCreated"),
"dateRefreshed": place.get("dateRefreshed"),
"categories": categories,
"extendedLocation": extended_location,
"relatedPlaces": related_places,
"socialMedia": social_media,
"location": location,
"createdAt": place.get("createdAt"),
"updatedAt": place.get("updatedAt"),
}
def parse_json_field(field):
"""Parse a JSON string into a dict, or return empty dict."""
if field is None:
return {}
if isinstance(field, str):
try:
return json.loads(field)
except json.JSONDecodeError:
return {}
if isinstance(field, dict):
return field
return {}
# ==================== ONLINE LEARNING ====================
class InteractionRequest(BaseModel):
"""Payload for tracking user interactions."""
user_id: str
plan_id: str
interaction_type: str # view, bookmark, rate
rating: Optional[int] = None
duration_seconds: Optional[int] = None
@app.post("/track-interaction")
async def track_interaction(interaction: InteractionRequest, background_tasks: BackgroundTasks):
"""Stores user interaction and triggers lightweight online learning."""
try:
interaction_data = interaction.model_dump()
supabase.table("user_plan_interactions").insert(interaction_data).execute()
background_tasks.add_task(update_model_online, interaction_data)
return {
"status": "success",
"message": "Interaction saved and learning triggered",
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
async def update_model_online(interaction_data: dict):
"""
Background task that updates the model
This runs AFTER the API response is sent to the user
"""
try:
recommender_instance = get_recommender()
# Check if online learner is available
if (
hasattr(recommender_instance, "online_learner")
and recommender_instance.online_learner
):
result = recommender_instance.update_online(interaction_data)
if result.get("updated"):
print(f"[ONLINE LEARNING] {result.get('message')}")
else:
print(
f"[ONLINE LEARNING] {result.get('message')} - Next update in {result.get('next_update_in')} interactions"
)
else:
print(
"[INFO] Online learner not initialized, interaction saved for batch training"
)
except Exception as e:
print(f"[ERROR] Online update failed: {e}")
import traceback
traceback.print_exc()
@app.get("/online-stats")
def get_online_stats():
try:
recommender_instance = get_recommender()
if (
hasattr(recommender_instance, "online_learner")
and recommender_instance.online_learner
):
stats = recommender_instance.online_learner.get_statistics()
return {
"online_learning": "enabled",
"statistics": stats,
"status": "active",
}
else:
return {
"online_learning": "disabled",
"message": "Online learner not initialized. Using batch learning only.",
"status": "batch_only",
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# ==================== ADMIN ====================
def verify_admin(x_admin_key: Optional[str] = Header(None)):
"""Simple header-based admin check."""
if x_admin_key != ADMIN_KEY:
raise HTTPException(status_code=401, detail="Unauthorized")
@app.post("/retrain")
def retrain(x_admin_key: Optional[str] = Header(None)):
"""Runs full batch model retraining."""
verify_admin(x_admin_key)
try:
result = get_recommender().retrain_from_supabase()
return JSONResponse({"status": "retrained", "artifacts_saved": result})
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# Local development entrypoint
if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", port=7860, reload=True)