adasdimchom
commited on
Commit
•
389abca
1
Parent(s):
5661451
Upload handler.py
Browse files- handler.py +41 -0
handler.py
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import BlipProcessor, BlipForConditionalGeneration
|
2 |
+
from typing import Dict, List, Any
|
3 |
+
from PIL import Image
|
4 |
+
from transformers import pipeline
|
5 |
+
import requests
|
6 |
+
import torch
|
7 |
+
|
8 |
+
class EndpointHandler():
|
9 |
+
def __init__(self, path=""):
|
10 |
+
"""
|
11 |
+
path:
|
12 |
+
"""
|
13 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
14 |
+
self.processor = BlipProcessor.from_pretrained(path)
|
15 |
+
self.model = BlipForConditionalGeneration.from_pretrained(path, torch_dtype=torch.float16).to(self.device)
|
16 |
+
|
17 |
+
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
18 |
+
"""
|
19 |
+
data args:
|
20 |
+
inputs (:obj: `str` | `PIL.Image` | `np.array`)
|
21 |
+
kwargs
|
22 |
+
Return:
|
23 |
+
A :obj:`list` | `dict`: will be serialized and returned
|
24 |
+
"""
|
25 |
+
result = {}
|
26 |
+
inputs = data.pop("inputs", data)
|
27 |
+
image_url = inputs['image_url']
|
28 |
+
if "prompt" in inputs:
|
29 |
+
prompt = inputs["prompt"]
|
30 |
+
else:
|
31 |
+
prompt = None
|
32 |
+
image = Image.open(requests.get(image_url, stream=True).raw).convert('RGB')
|
33 |
+
if prompt:
|
34 |
+
processed_image = self.processor(images=image, text=prompt, return_tensors="pt").to(self.device, torch.float16)
|
35 |
+
else:
|
36 |
+
processed_image = self.processor(images=image, return_tensors="pt").to(self.device, torch.float16)
|
37 |
+
output = self.model.generate(**processed_image)
|
38 |
+
text_output = self.processor.decode(output[0], skip_special_tokens=True)
|
39 |
+
result["text_output"] = text_output
|
40 |
+
feature_vector = output.last_hidden_state[:, 0, :]
|
41 |
+
return result
|