from fastapi import FastAPI, Query import asyncio import uvicorn import os from tracks import get_top_tracks_for_user, get_users_with_track_interactions from recommender import get_recommendations_for_user # custom_accuracy needs to be imported to the global namespace for Learner to load from learner import setup_learner, custom_accuracy, DotProductBias app = FastAPI() model_filename = 'data/model.pkl' learn = None @app.on_event("startup") async def startup_event(): global learn tasks = [asyncio.ensure_future(setup_learner(model_filename))] # assign some task learn = (await asyncio.gather(*tasks))[0] print("Model initialized") @app.get("/users") async def get_users(limit: int = Query(10)): return get_users_with_track_interactions(limit=limit) @app.get('/users/{user_id}') async def get_user_track_history(user_id: str, limit:int = Query(5)): user_history = get_top_tracks_for_user(user_id, limit) return {"user_id": user_id, "history": user_history} @app.get("/recommend/{user_id}") async def get_recommendations(user_id: str, limit: int = Query(5)): return get_recommendations_for_user(learn, user_id, limit) if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=int(os.getenv("PORT", 7860)))