Spaces:
Sleeping
Sleeping
from fastai.collab import load_learner | |
from fastapi import FastAPI, Query | |
from fastapi.middleware.cors import CORSMiddleware | |
from custom_models import DotProductBias | |
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 | |
# FastAPI app | |
app = FastAPI() | |
app.add_middleware( | |
CORSMiddleware, | |
allow_origins=["*"], | |
allow_credentials=True, | |
allow_methods=["*"], | |
allow_headers=["*"], | |
) | |
# Model filename | |
model_filename = 'model.pkl' | |
async def setup_learner(): | |
learn = load_learner(model_filename) | |
learn.dls.device = 'cpu' | |
return learn | |
learn = None | |
async def startup_event(): | |
"""Setup the learner on server start""" | |
global learn | |
loop = asyncio.get_event_loop() # get event loop | |
tasks = [asyncio.ensure_future(setup_learner())] # assign some task | |
learn = (await asyncio.gather(*tasks))[0] | |
async def get_users(limit: int = Query(10)): | |
return get_users_with_track_interactions(limit=limit) | |
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} | |
async def get_recommendations(user_id: str, num_recommendations: int = Query(5)): | |
return get_recommendations_for_user(learn, user_id, num_recommendations) | |
if __name__ == "__main__": | |
uvicorn.run(app, host="0.0.0.0", port=int(os.getenv("PORT", 7860))) | |