Create handler.py
Browse files- 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: "low", 1: "medium", 2: "high"}
|
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)]
|