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