moooji commited on
Commit
89c79b6
1 Parent(s): cd42f2e

Create handler.py

Browse files
Files changed (1) hide show
  1. handler.py +27 -0
handler.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 BlipProcessor, BlipForQuestionAnswering
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 = BlipProcessor.from_pretrained("Salesforce/blip-vqa-capfilt-large")
13
+ self.model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-capfilt-large").to(device)
14
+
15
+
16
+ def __call__(self, data: Any) -> List[float]:
17
+ inputs = data.pop("inputs", data)
18
+
19
+ image = Image.open(BytesIO(base64.b64decode(inputs['image'])))
20
+ inputs = self.processor(image, inputs['question'], return_tensors="pt").to(device)
21
+
22
+ with torch.no_grad():
23
+ outputs = self.model.generate(**inputs)
24
+
25
+ pooler_output = outputs.pooler_output
26
+ return processor.decode(out[0], skip_special_tokens=True)
27
+