Upload handler.py
Browse files- handler.py +36 -0
handler.py
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Dict, List, Any
|
2 |
+
|
3 |
+
import torch
|
4 |
+
from transformers import pipeline, XLMRobertaTokenizerFast, XLMRobertaForSequenceClassification
|
5 |
+
|
6 |
+
|
7 |
+
class EndpointHandler:
|
8 |
+
def __init__(self, path=""):
|
9 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
10 |
+
# load the optimized model
|
11 |
+
model = XLMRobertaForSequenceClassification.from_pretrained(path)
|
12 |
+
tokenizer = XLMRobertaTokenizerFast.from_pretrained(path)
|
13 |
+
model.eval()
|
14 |
+
# create inference pipeline
|
15 |
+
self.pipline = pipeline("text-classification", tokenizer=tokenizer, model=model, device=self.device)
|
16 |
+
|
17 |
+
def __call__(self, data: Any) -> List[List[Dict[str, float]]]:
|
18 |
+
"""
|
19 |
+
Args:
|
20 |
+
data (:obj:):
|
21 |
+
includes the input data and the parameters for the inference.
|
22 |
+
Return:
|
23 |
+
A :obj:`list`:. The object returned should be a list of one list like [[{"label": 0.9939950108528137}]] containing :
|
24 |
+
- "label": A string representing what the label/class is. There can be multiple labels.
|
25 |
+
- "score": A score between 0 and 1 describing how confident the model is for this label/class.
|
26 |
+
"""
|
27 |
+
inputs = data.pop("inputs", data)
|
28 |
+
parameters = data.pop("parameters", None)
|
29 |
+
|
30 |
+
# pass inputs with all kwargs in data
|
31 |
+
if parameters is not None:
|
32 |
+
prediction = self.pipline(inputs, **parameters)
|
33 |
+
else:
|
34 |
+
prediction = self.pipline(inputs)
|
35 |
+
# postprocess the prediction
|
36 |
+
return prediction
|