ThrinathMphasis
commited on
Commit
•
091a326
1
Parent(s):
4a1a5af
handler.py
Browse files- handler.py +40 -0
handler.py
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# handler.py
|
2 |
+
import torch
|
3 |
+
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
|
4 |
+
|
5 |
+
# check for GPU
|
6 |
+
device = 0 if torch.cuda.is_available() else -1
|
7 |
+
|
8 |
+
# multi-model list
|
9 |
+
multi_model_list = [
|
10 |
+
{"model_id": "distilbert-base-uncased-finetuned-sst-2-english", "task": "text-classification"},
|
11 |
+
{"model_id": "Helsinki-NLP/opus-mt-en-de", "task": "translation"},
|
12 |
+
{"model_id": "facebook/bart-large-cnn", "task": "summarization"},
|
13 |
+
{"model_id": "dslim/bert-base-NER", "task": "token-classification"},
|
14 |
+
{"model_id": "textattack/bert-base-uncased-ag-news", "task": "text-classification"},
|
15 |
+
]
|
16 |
+
|
17 |
+
class EndpointHandler():
|
18 |
+
def __init__(self, path=""):
|
19 |
+
self.multi_model={}
|
20 |
+
# load all the models onto device
|
21 |
+
for model in multi_model_list:
|
22 |
+
self.multi_model[model["model_id"]] = pipeline(model["task"], model=model["model_id"], device=device)
|
23 |
+
|
24 |
+
def __call__(self, data):
|
25 |
+
# deserialize incomin request
|
26 |
+
inputs = data.pop("inputs", data)
|
27 |
+
parameters = data.pop("parameters", None)
|
28 |
+
model_id = data.pop("model_id", None)
|
29 |
+
|
30 |
+
# check if model_id is in the list of models
|
31 |
+
if model_id is None or model_id not in self.multi_model:
|
32 |
+
raise ValueError(f"model_id: {model_id} is not valid. Available models are: {list(self.multi_model.keys())}")
|
33 |
+
|
34 |
+
# pass inputs with all kwargs in data
|
35 |
+
if parameters is not None:
|
36 |
+
prediction = self.multi_model[model_id](inputs, **parameters)
|
37 |
+
else:
|
38 |
+
prediction = self.multi_model[model_id](inputs)
|
39 |
+
# postprocess the prediction
|
40 |
+
return prediction
|