Create handler.py
Browse files- handler.py +23 -0
handler.py
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Dict, List, Any
|
2 |
+
from PIL import Image
|
3 |
+
import torch
|
4 |
+
import base64
|
5 |
+
from io import BytesIO
|
6 |
+
from transformers import AutoProcessor, BlipForConditionalGeneration
|
7 |
+
|
8 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
9 |
+
|
10 |
+
class EndpointHandler():
|
11 |
+
def __init__(self, path=""):
|
12 |
+
self.processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-large")
|
13 |
+
self.model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-large").to(device)
|
14 |
+
|
15 |
+
def __call__(self, data: Any) -> List[float]:
|
16 |
+
inputs = data.pop("inputs", data)
|
17 |
+
|
18 |
+
image = Image.open(BytesIO(base64.b64decode(inputs['image'])))
|
19 |
+
inputs = self.processor(image, return_tensors="pt").to(device)
|
20 |
+
outputs = self.model(**inputs)
|
21 |
+
|
22 |
+
return outputs.toList()
|
23 |
+
|