Upload handler.py
Browse files- handler.py +34 -0
handler.py
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import requests
|
2 |
+
from PIL import Image
|
3 |
+
from transformers import Blip2Processor, Blip2ForConditionalGeneration
|
4 |
+
from typing import Dict, List, Any
|
5 |
+
import torch
|
6 |
+
import base64
|
7 |
+
from io import BytesIO
|
8 |
+
|
9 |
+
class EndpointHandler():
|
10 |
+
def __init__(self, path=""):
|
11 |
+
self.processor = Blip2Processor.from_pretrained("Salesforce/blip2-opt-6.7b")
|
12 |
+
self.model = Blip2ForConditionalGeneration.from_pretrained("Salesforce/blip2-opt-6.7b")
|
13 |
+
|
14 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
15 |
+
self.model.to(self.device)
|
16 |
+
|
17 |
+
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
18 |
+
image_encoded = data.pop("inputs", data)
|
19 |
+
text = data["text"]
|
20 |
+
|
21 |
+
# image = Image.open(image_path)
|
22 |
+
image = self.decode_base64_image(image_encoded)
|
23 |
+
|
24 |
+
processed = self.processor(images=image, text=text, return_tensors="pt").to(self.device)
|
25 |
+
|
26 |
+
out = self.model.generate(**processed)
|
27 |
+
|
28 |
+
return self.processor.decode(out[0], skip_special_tokens=True)
|
29 |
+
|
30 |
+
def decode_base64_image(self, image_string):
|
31 |
+
base64_image = base64.b64decode(image_string)
|
32 |
+
buffer = BytesIO(base64_image)
|
33 |
+
image = Image.open(buffer)
|
34 |
+
return image
|