Update handler.py
Browse files- handler.py +4 -16
handler.py
CHANGED
@@ -1,26 +1,14 @@
|
|
|
|
1 |
from typing import Dict, List, Any
|
2 |
import pickle
|
3 |
-
import numpy as np
|
4 |
-
import pandas as pd
|
5 |
import os
|
6 |
-
import
|
7 |
-
|
8 |
-
class ContentBasedRecommender:
|
9 |
-
def __init__(self, train_data):
|
10 |
-
self.train_data = train_data
|
11 |
-
|
12 |
-
def predict(self, user_id, k=10):
|
13 |
-
user_books = set(self.train_data[self.train_data['user_id'] == user_id]['book_id'])
|
14 |
-
similar_books = set().union(*(self.train_data[self.train_data['book_id'] == book_id]['similar_books'].iloc[0] for book_id in user_books))
|
15 |
-
recommended_books = list(similar_books - user_books)
|
16 |
-
|
17 |
-
return np.random.choice(recommended_books, size=k, replace=False) if len(recommended_books) >= k else recommended_books
|
18 |
|
19 |
class EndpointHandler:
|
20 |
def __init__(self, path=""):
|
21 |
model_path = os.path.join(path, "model.pkl")
|
22 |
with open(model_path, 'rb') as f:
|
23 |
-
self.model =
|
24 |
|
25 |
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
26 |
user_id = data.pop("user_id", None)
|
@@ -31,7 +19,7 @@ class EndpointHandler:
|
|
31 |
|
32 |
try:
|
33 |
recommended_books = self.model.predict(user_id, k=k)
|
34 |
-
return [{"recommended_books": recommended_books
|
35 |
except Exception as e:
|
36 |
return [{"error": str(e)}]
|
37 |
|
|
|
1 |
+
|
2 |
from typing import Dict, List, Any
|
3 |
import pickle
|
|
|
|
|
4 |
import os
|
5 |
+
from model import ContentBasedRecommender
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
|
7 |
class EndpointHandler:
|
8 |
def __init__(self, path=""):
|
9 |
model_path = os.path.join(path, "model.pkl")
|
10 |
with open(model_path, 'rb') as f:
|
11 |
+
self.model = pickle.load(f)
|
12 |
|
13 |
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
14 |
user_id = data.pop("user_id", None)
|
|
|
19 |
|
20 |
try:
|
21 |
recommended_books = self.model.predict(user_id, k=k)
|
22 |
+
return [{"recommended_books": recommended_books}]
|
23 |
except Exception as e:
|
24 |
return [{"error": str(e)}]
|
25 |
|