-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
62 lines (49 loc) · 1.5 KB
/
app.py
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
57
58
59
60
61
62
import os
import threading
from surprise import dump
from training import train
from db_util import get_db_conn_url
from flask_sqlalchemy import SQLAlchemy
from flask import Flask, request
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = f"postgresql://{get_db_conn_url()}"
db = SQLAlchemy(app)
from sqlalchemy import text
model_dump_path = os.path.normpath("model_dump")
@app.route('/topN/<user_id>')
def getTopN(user_id):
n = request.args.get('n')
if n is None:
n = 5
else:
n = int(n)
model = get_model()
query = text("SELECT id FROM movies WHERE id NOT IN (SELECT movie_id FROM ratings WHERE user_id = :user_id)")
result = db.engine.execute(query, user_id=user_id).fetchall()
movies = map(lambda row: { "movie_id": row[0], "prediction":model.predict(user_id, row[0]).est}, result)
movies = sorted(movies, key=lambda m: m["prediction"], reverse=True)
return {
"movies":movies[:n]
}
@app.route('/train')
def train_route():
train_task = threading.Thread(target=train, args=(model_dump_path,))
train_task.start()
return {
"status": "Started"
}
@app.route('/predict')
def predict():
model = get_model()
req = request.get_json()
return {
"prediction": model.predict(req['user'], req['movie']).est
}
def get_model():
path = model_dump_path
if os.path.isfile(path):
_, loaded_algo = dump.load(path)
return loaded_algo
else:
algo = train(path)
return algo