Create handler.py
Browse files- handler.py +52 -0
handler.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, Any
|
| 2 |
+
from transformers import AutoProcessor, Qwen2VLForConditionalGeneration
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import io
|
| 5 |
+
import base64
|
| 6 |
+
import requests
|
| 7 |
+
|
| 8 |
+
class EndpointHandler():
|
| 9 |
+
def __init__(self, path=""):
|
| 10 |
+
self.processor = AutoProcessor.from_pretrained(path)
|
| 11 |
+
self.model = Qwen2VLForConditionalGeneration.from_pretrained(path)
|
| 12 |
+
|
| 13 |
+
def __call__(self, data: Any) -> Dict[str, Any]:
|
| 14 |
+
|
| 15 |
+
image_input = data.get('image', None)
|
| 16 |
+
text_input = data.get('text', None)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
if isinstance(data, dict):
|
| 20 |
+
if image_input.startswith('http'):
|
| 21 |
+
image = Image.open(requests.get(image_input, stream=True).raw).convert('RGB')
|
| 22 |
+
else:
|
| 23 |
+
image_data = base64.b64decode(image_input)
|
| 24 |
+
image = Image.open(io.BytesIO(image_data)).convert('RGB')
|
| 25 |
+
else:
|
| 26 |
+
return {"error": "Invalid input data. Expected binary image data or a dictionary with 'image' key."}
|
| 27 |
+
|
| 28 |
+
messages = [
|
| 29 |
+
{
|
| 30 |
+
"role": "user",
|
| 31 |
+
"content": [
|
| 32 |
+
{"type": "image", "image": image},
|
| 33 |
+
{"type": "text", "text": text_input},
|
| 34 |
+
],
|
| 35 |
+
}
|
| 36 |
+
]
|
| 37 |
+
|
| 38 |
+
text = self.processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 39 |
+
inputs = self.processor(
|
| 40 |
+
text=[text],
|
| 41 |
+
images=[image],
|
| 42 |
+
padding=True,
|
| 43 |
+
return_tensors="pt",
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
generate_ids = self.model.generate(inputs.input_ids, max_length=30)
|
| 47 |
+
output_text = self.processor.batch_decode(
|
| 48 |
+
generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
|
| 49 |
+
)[0]
|
| 50 |
+
|
| 51 |
+
return {"generated_text": output_text}
|
| 52 |
+
|