Upload handler.py
Browse files- handler.py +32 -0
handler.py
ADDED
@@ -0,0 +1,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 |
+
# Load the serialized model
|
8 |
+
with open(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 |
+
# Get inputs
|
20 |
+
user_id = data.pop("user_id", None)
|
21 |
+
k = data.pop("k", 10) # Default to 10 if not provided
|
22 |
+
|
23 |
+
if user_id is None:
|
24 |
+
return [{"error": "user_id is required"}]
|
25 |
+
|
26 |
+
# Run prediction
|
27 |
+
try:
|
28 |
+
recommended_books = self.model.predict(user_id, k=k)
|
29 |
+
return [{"recommended_books": recommended_books.tolist()}]
|
30 |
+
except Exception as e:
|
31 |
+
return [{"error": str(e)}]
|
32 |
+
|