moooji commited on
Commit
a5215c5
1 Parent(s): 26ca0aa

Create handler.py

Browse files
Files changed (1) hide show
  1. 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
+