lewtun HF staff commited on
Commit
a07a3e1
1 Parent(s): 9c0a08a

Create handler.py

Browse files
Files changed (1) hide show
  1. handler.py +27 -0
handler.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Any
2
+ from setfit import SetFitModel
3
+
4
+
5
+ class EndpointHandler:
6
+ def __init__(self, path=""):
7
+ # load model
8
+ self.model = SetFitModel.from_pretrained(path)
9
+ # ag_news id to label mapping
10
+ self.id2label = {0: "World", 1: "Sports", 2: "Business", 3: "Sci/Tech"}
11
+
12
+ def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
13
+ """
14
+ data args:
15
+ inputs (:obj: `str`)
16
+ Return:
17
+ A :obj:`list` | `dict`: will be serialized and returned
18
+ """
19
+ # get inputs
20
+ inputs = data.pop("inputs", data)
21
+ if isinstance(inputs, str):
22
+ inputs = [inputs]
23
+
24
+ # run normal prediction
25
+ scores = self.model.predict_proba(inputs)[0]
26
+
27
+ return [{"label": self.id2label[i], "score": score.item()} for i, score in enumerate(scores)]