Create handler.py
Browse files- handler.py +84 -0
handler.py
ADDED
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Dict, Any
|
2 |
+
from transformers import AutoProcessor, Qwen2VLForConditionalGeneration
|
3 |
+
import torch
|
4 |
+
from PIL import Image
|
5 |
+
import requests
|
6 |
+
from io import BytesIO
|
7 |
+
import json
|
8 |
+
|
9 |
+
# Check for GPU
|
10 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
11 |
+
|
12 |
+
|
13 |
+
class EndpointHandler:
|
14 |
+
def __init__(self, path: str = ""):
|
15 |
+
"""
|
16 |
+
Initializes the handler for the Qwen2-VL model.
|
17 |
+
|
18 |
+
Args:
|
19 |
+
path (str): Path to the model weights and processor. Defaults to the current directory.
|
20 |
+
"""
|
21 |
+
# Load the processor and model
|
22 |
+
self.processor = AutoProcessor.from_pretrained(path)
|
23 |
+
self.model = Qwen2VLForConditionalGeneration.from_pretrained(
|
24 |
+
path,
|
25 |
+
torch_dtype="auto",
|
26 |
+
device_map="auto"
|
27 |
+
)
|
28 |
+
# Move the model to the appropriate device
|
29 |
+
self.model.to(device)
|
30 |
+
|
31 |
+
def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
32 |
+
"""
|
33 |
+
Processes the input data and returns the model's prediction.
|
34 |
+
|
35 |
+
Args:
|
36 |
+
data (Dict[str, Any]): Input data containing `image_url` and `text`.
|
37 |
+
|
38 |
+
Returns:
|
39 |
+
Dict[str, Any]: The prediction or an error message.
|
40 |
+
"""
|
41 |
+
image_url = data.get("image_url", "")
|
42 |
+
text = data.get("text", "")
|
43 |
+
|
44 |
+
# Load the image from the URL
|
45 |
+
try:
|
46 |
+
response = requests.get(image_url)
|
47 |
+
response.raise_for_status()
|
48 |
+
image = Image.open(BytesIO(response.content))
|
49 |
+
except Exception as e:
|
50 |
+
return {"error": f"Failed to fetch or process image: {str(e)}"}
|
51 |
+
|
52 |
+
# Prepare the text prompt
|
53 |
+
text_prompt = self.processor.apply_chat_template(
|
54 |
+
[{"role": "user", "content": [{"type": "text", "text": text}]}],
|
55 |
+
add_generation_prompt=True
|
56 |
+
)
|
57 |
+
|
58 |
+
# Preprocess the input
|
59 |
+
inputs = self.processor(
|
60 |
+
text=[text_prompt],
|
61 |
+
images=[image],
|
62 |
+
padding=True,
|
63 |
+
return_tensors="pt"
|
64 |
+
)
|
65 |
+
|
66 |
+
# Move inputs to the correct device
|
67 |
+
inputs = {key: value.to(device) for key, value in inputs.items()}
|
68 |
+
|
69 |
+
# Perform inference
|
70 |
+
output_ids = self.model.generate(**inputs, max_new_tokens=128)
|
71 |
+
|
72 |
+
# Decode the generated text
|
73 |
+
output_text = self.processor.batch_decode(
|
74 |
+
output_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True
|
75 |
+
)[0]
|
76 |
+
|
77 |
+
# Clean and parse the JSON response
|
78 |
+
cleaned_data = output_text.replace("```json\n", "").replace("```", "").strip()
|
79 |
+
try:
|
80 |
+
prediction = json.loads(cleaned_data)
|
81 |
+
except json.JSONDecodeError as e:
|
82 |
+
return {"error": f"Failed to parse JSON output: {str(e)}", "raw_output": cleaned_data}
|
83 |
+
|
84 |
+
return {"prediction": prediction}
|