Create handler.py
Browse files- handler.py +51 -0
handler.py
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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: "Absent", 1: "Present"}
|
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)]
|
28 |
+
|
29 |
+
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
30 |
+
"""
|
31 |
+
data args:
|
32 |
+
inputs (:obj: `List[str]`) - List of strings
|
33 |
+
Return:
|
34 |
+
A :obj:`list` of dicts: each dict contains 'label' and 'score' for each input string
|
35 |
+
"""
|
36 |
+
# get inputs
|
37 |
+
inputs = data.pop("inputs", data)
|
38 |
+
if not isinstance(inputs, list):
|
39 |
+
raise ValueError("Input must be a list of strings")
|
40 |
+
|
41 |
+
# run normal prediction
|
42 |
+
all_scores = self.model.predict_proba(inputs) # This returns a list of score arrays
|
43 |
+
|
44 |
+
# Format the results for each input string
|
45 |
+
results = []
|
46 |
+
for scores in all_scores:
|
47 |
+
results.append([
|
48 |
+
{"label": self.id2label[i], "score": score.item()} for i, score in enumerate(scores)
|
49 |
+
])
|
50 |
+
|
51 |
+
return results
|