Create handler.py
Browse files- handler.py +29 -0
handler.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Dict
|
| 2 |
+
from transformers import Blip2Processor, Blip2ForConditionalGeneration
|
| 3 |
+
import io
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import base64
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
class EndpointHandler:
|
| 9 |
+
def __init__(self, path=""):
|
| 10 |
+
# load model and processor from path
|
| 11 |
+
self.processor = Blip2Processor.from_pretrained(path)
|
| 12 |
+
self.model = Blip2ForConditionalGeneration.from_pretrained(path, torch_dtype=torch.float16)
|
| 13 |
+
self.device = "cuda"
|
| 14 |
+
|
| 15 |
+
self.model.to(self.device)
|
| 16 |
+
|
| 17 |
+
def __call__(self, data: Dict[str, Any]) -> Dict[str, str]:
|
| 18 |
+
# process input
|
| 19 |
+
data = data.pop("inputs", data)
|
| 20 |
+
text = data.pop("text", data)
|
| 21 |
+
|
| 22 |
+
image_string = base64.b64decode(data["image"])
|
| 23 |
+
image = Image.open(io.BytesIO(image_string))
|
| 24 |
+
|
| 25 |
+
inputs = self.processor(images=image, text=text, return_tensors="pt").to(self.device, torch.float16)
|
| 26 |
+
generated_ids = self.model.generate(**inputs)
|
| 27 |
+
generated_text = self.processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
|
| 28 |
+
|
| 29 |
+
return [{"answer": generated_text}]
|