adasdimchom
commited on
Commit
•
ad35ed2
1
Parent(s):
b101841
Upload handler.py
Browse files- handler.py +32 -0
handler.py
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import CLIPModel, CLIPProcessor
|
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 = CLIPProcessor.from_pretrained(path)
|
15 |
+
self.model = CLIPModel.from_pretrained(path).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 |
+
image = Image.open(requests.get(image_url, stream=True).raw).convert('RGB')
|
29 |
+
processed_image = self.processor(images=image, return_tensors="pt").to(self.device)
|
30 |
+
output = self.model.get_image_features(processed_image["pixel_values"])[0].tolist()
|
31 |
+
result["embedding"] = output
|
32 |
+
return result
|