smlparry
commited on
Commit
·
79f86bc
1
Parent(s):
cb46fbd
Create handler and requirements.txt
Browse files- handler.py +38 -0
- requirements.txt +4 -0
handler.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, List, Any
|
| 2 |
+
from transformers import BlipProcessor, BlipForConditionalGeneration
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import requests
|
| 5 |
+
|
| 6 |
+
class EndpointHandler():
|
| 7 |
+
def __init__(self, path=""):
|
| 8 |
+
self.processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-large")
|
| 9 |
+
self.model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-large")
|
| 10 |
+
|
| 11 |
+
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
| 12 |
+
"""
|
| 13 |
+
data args:
|
| 14 |
+
image_url (:obj: `str`): URL of the image to be captioned
|
| 15 |
+
Return:
|
| 16 |
+
A :obj:`list` | `dict`: will be serialized and returned
|
| 17 |
+
"""
|
| 18 |
+
# get inputs
|
| 19 |
+
image_url = data.pop("image_url", None)
|
| 20 |
+
|
| 21 |
+
# check if image_url exists
|
| 22 |
+
if image_url is None:
|
| 23 |
+
return [{"error": "image_url not provided"}]
|
| 24 |
+
|
| 25 |
+
# get image from URL
|
| 26 |
+
try:
|
| 27 |
+
raw_image = Image.open(requests.get(image_url, stream=True).raw).convert('RGB')
|
| 28 |
+
except:
|
| 29 |
+
return [{"error": "unable to load image from the provided URL"}]
|
| 30 |
+
|
| 31 |
+
# unconditional image captioning
|
| 32 |
+
inputs = self.processor(raw_image, return_tensors="pt")
|
| 33 |
+
|
| 34 |
+
# generate captions
|
| 35 |
+
out = self.model.generate(**inputs)
|
| 36 |
+
|
| 37 |
+
# return the generated captions
|
| 38 |
+
return [{"caption": self.processor.decode(out[0], skip_special_tokens=True)}]
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
transformers
|
| 3 |
+
pillow
|
| 4 |
+
requests
|