Create handler.py
Browse files- handler.py +23 -0
handler.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, List, Any
|
| 2 |
+
from PIL import Image
|
| 3 |
+
from io import BytesIO
|
| 4 |
+
from transformers import pipeline
|
| 5 |
+
import base64
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class EndpointHandler():
|
| 9 |
+
def __init__(self, path=""):
|
| 10 |
+
self.pipeline = pipeline("zero-shot-image-classification", model=path, device=0)
|
| 11 |
+
|
| 12 |
+
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
| 13 |
+
inputs = data.pop("inputs", {})
|
| 14 |
+
parameters = data.pop("parameters", {})
|
| 15 |
+
candidate_labels = parameters.pop("candidate_labels", [])
|
| 16 |
+
print("data: ", data)
|
| 17 |
+
|
| 18 |
+
# decode base64 image to PIL
|
| 19 |
+
image = Image.open(BytesIO(base64.b64decode(inputs)))
|
| 20 |
+
|
| 21 |
+
# run prediction on the image with provided candidates
|
| 22 |
+
prediction = self.pipeline(images=[image], candidate_labels=candidate_labels)
|
| 23 |
+
return prediction[0]
|