clfegg commited on
Commit
2a4d3c4
1 Parent(s): 3f2fe35

Create handler.py

Browse files
Files changed (1) hide show
  1. handler.py +61 -0
handler.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Any
2
+ import pickle
3
+ import os
4
+ import __main__
5
+ import numpy as np
6
+
7
+ class CollaborativeRecommender:
8
+ def __init__(self, algo, trainset):
9
+ self.algo = algo
10
+ self.trainset = trainset
11
+
12
+ def predict(self, user_id, k=10):
13
+ try:
14
+ # Convert raw user_id to inner user_id
15
+ inner_user_id = self.trainset.to_inner_uid(user_id)
16
+ except ValueError:
17
+ # User not found in trainset, return None
18
+ return None
19
+
20
+ # Get the list of books the user has interacted with
21
+ user_books = set(self.trainset.ur[inner_user_id])
22
+ all_books = set(self.trainset.all_items())
23
+ unseen_books = all_books - user_books
24
+ # Predict the ratings for unseen books
25
+ predictions = [self.algo.predict(self.trainset.to_raw_uid(inner_user_id), self.trainset.to_raw_iid(book_id)) for book_id in unseen_books]
26
+ # Sort the predictions by estimated rating and return the top-k books
27
+ top_predictions = sorted(predictions, key=lambda x: x.est, reverse=True)[:k]
28
+ top_books = [pred.iid for pred in top_predictions]
29
+ return top_books
30
+
31
+ __main__.CollaborativeRecommender = CollaborativeRecommender
32
+
33
+ class EndpointHandler:
34
+ def __init__(self, path=""):
35
+ model_path = os.path.join(path, "model.pkl")
36
+ with open(model_path, 'rb') as f:
37
+ self.model = pickle.load(f)
38
+
39
+ def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
40
+ # Extract the 'inputs' from the data
41
+ inputs = data.get('inputs', {})
42
+
43
+ # If inputs is a string (for single user_id input), convert it to a dict
44
+ if isinstance(inputs, str):
45
+ inputs = {'user_id': inputs}
46
+
47
+ user_id = inputs.get('user_id')
48
+ k = inputs.get('k', 10) # Default to 10 if not provided
49
+
50
+ if user_id is None:
51
+ return [{"error": "user_id is required"}]
52
+
53
+ try:
54
+ recommended_books = self.model.predict(user_id, k=k)
55
+ return [{"recommended_books": recommended_books}]
56
+ except Exception as e:
57
+ return [{"error": str(e)}]
58
+
59
+ def load_model(model_path):
60
+ handler = EndpointHandler(model_path)
61
+ return handler