File size: 1,213 Bytes
63d0aa5
 
 
 
 
 
 
dddf97f
 
 
63d0aa5
 
dddf97f
63d0aa5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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

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]

@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)))