Spaces:
Sleeping
Sleeping
File size: 1,610 Bytes
f6b6982 9c3a55c f6b6982 af5cf7c f6b6982 af5cf7c f6b6982 9c3a55c af5cf7c 9c3a55c f6b6982 af5cf7c f6b6982 9c3a55c |
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 |
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
@app.on_event("startup")
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]
@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, 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)))
|