Upload handler.py
#19
by
maul1993
- opened
- handler.py +41 -0
handler.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from transformers import AutoModel, AutoTokenizer
|
| 3 |
+
|
| 4 |
+
class ModelHandler:
|
| 5 |
+
def __init__(self):
|
| 6 |
+
self.model = None
|
| 7 |
+
self.tokenizer = None
|
| 8 |
+
|
| 9 |
+
def initialize(self, model_path):
|
| 10 |
+
"""Load model and tokenizer."""
|
| 11 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_path)
|
| 12 |
+
self.model = AutoModel.from_pretrained(model_path)
|
| 13 |
+
|
| 14 |
+
def preprocess(self, data):
|
| 15 |
+
"""Preprocess input data."""
|
| 16 |
+
text = data.get("text", "")
|
| 17 |
+
inputs = self.tokenizer(text, return_tensors="pt")
|
| 18 |
+
return inputs
|
| 19 |
+
|
| 20 |
+
def inference(self, inputs):
|
| 21 |
+
"""Run inference on the model."""
|
| 22 |
+
outputs = self.model(**inputs)
|
| 23 |
+
return outputs
|
| 24 |
+
|
| 25 |
+
def postprocess(self, outputs):
|
| 26 |
+
"""Postprocess model output."""
|
| 27 |
+
return {"output": outputs.logits.tolist()}
|
| 28 |
+
|
| 29 |
+
_handler = ModelHandler()
|
| 30 |
+
|
| 31 |
+
def handle(data, context):
|
| 32 |
+
if not _handler.model:
|
| 33 |
+
model_path = context.system_properties.get("model_dir")
|
| 34 |
+
_handler.initialize(model_path)
|
| 35 |
+
|
| 36 |
+
if data is None:
|
| 37 |
+
return {"error": "No input data"}
|
| 38 |
+
|
| 39 |
+
inputs = _handler.preprocess(data[0])
|
| 40 |
+
outputs = _handler.inference(inputs)
|
| 41 |
+
return _handler.postprocess(outputs)
|