Update handler.py
Browse files- handler.py +34 -32
handler.py
CHANGED
|
@@ -1,32 +1,34 @@
|
|
| 1 |
-
from typing import Dict, List, Any
|
| 2 |
-
import pickle
|
| 3 |
-
import numpy as np
|
| 4 |
-
import pandas as pd
|
| 5 |
-
class EndpointHandler:
|
| 6 |
-
def __init__(self, path=""):
|
| 7 |
-
|
| 8 |
-
with open(
|
| 9 |
-
self.model = pickle.load(f)
|
| 10 |
-
|
| 11 |
-
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
| 12 |
-
"""
|
| 13 |
-
data args:
|
| 14 |
-
user_id (:obj: `str` or `int`)
|
| 15 |
-
k (:obj: `int`, optional)
|
| 16 |
-
Return:
|
| 17 |
-
A :obj:`list` of :obj:`dict`: will be serialized and returned
|
| 18 |
-
"""
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
return [{"
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, List, Any
|
| 2 |
+
import pickle
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pandas as pd
|
| 5 |
+
class EndpointHandler:
|
| 6 |
+
def __init__(self, path=""):
|
| 7 |
+
model_path = os.path.join(path, "content_based_recommender.pkl")
|
| 8 |
+
with open(model_path, 'rb') as f:
|
| 9 |
+
self.model = pickle.load(f)
|
| 10 |
+
|
| 11 |
+
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
| 12 |
+
"""
|
| 13 |
+
data args:
|
| 14 |
+
user_id (:obj: `str` or `int`)
|
| 15 |
+
k (:obj: `int`, optional)
|
| 16 |
+
Return:
|
| 17 |
+
A :obj:`list` of :obj:`dict`: will be serialized and returned
|
| 18 |
+
"""
|
| 19 |
+
user_id = data.pop("user_id", None)
|
| 20 |
+
k = data.pop("k", 10) # Default to 10 if not provided
|
| 21 |
+
|
| 22 |
+
if user_id is None:
|
| 23 |
+
return [{"error": "user_id is required"}]
|
| 24 |
+
|
| 25 |
+
try:
|
| 26 |
+
recommended_books = self.model.predict(user_id, k=k)
|
| 27 |
+
return [{"recommended_books": recommended_books.tolist()}]
|
| 28 |
+
except Exception as e:
|
| 29 |
+
return [{"error": str(e)}]
|
| 30 |
+
|
| 31 |
+
def load_model(model_path):
|
| 32 |
+
handler = EndpointHandler(model_path)
|
| 33 |
+
return handler
|
| 34 |
+
|