Gabriel commited on
Commit
2c42a1a
1 Parent(s): 84aa6a7

Update handler.py

Browse files
Files changed (1) hide show
  1. handler.py +61 -34
handler.py CHANGED
@@ -4,49 +4,76 @@ 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, device_map="cuda:0")
 
 
 
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
- ).to(self.device)
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
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  import io
5
  import base64
6
  import requests
7
+ import torch
8
+
9
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
10
 
11
  class EndpointHandler():
12
  def __init__(self, path=""):
13
  self.processor = AutoProcessor.from_pretrained(path)
14
+ self.model = Qwen2VLForConditionalGeneration.from_pretrained(
15
+ path, device_map="auto"
16
+ )
17
+ self.model.to(device)
18
 
19
  def __call__(self, data: Any) -> Dict[str, Any]:
20
+ inputs = data.pop("inputs", data)
21
+ image_input = inputs.get('image')
22
+ text_input = inputs.get('text', "Describe this image.")
23
 
24
+ if not image_input:
25
+ return {"error": "No image provided."}
 
26
 
27
+ try:
28
  if image_input.startswith('http'):
29
+ response = requests.get(image_input, stream=True)
30
+ if response.status_code == 200:
31
+ image = Image.open(response.raw).convert('RGB')
32
+ else:
33
+ return {"error": f"Failed to fetch image. Status code: {response.status_code}"}
34
  else:
35
  image_data = base64.b64decode(image_input)
36
  image = Image.open(io.BytesIO(image_data)).convert('RGB')
37
+ except Exception as e:
38
+ return {"error": f"Failed to process the image. Details: {str(e)}"}
39
+
40
+ try:
41
+ conversation = [
42
+ {
43
+ "role": "user",
44
+ "content": [
45
+ {"type": "image"},
46
+ {"type": "text", "text": text_input},
47
+ ],
48
+ }
49
+ ]
50
+
51
+ text_prompt = self.processor.apply_chat_template(
52
+ conversation, add_generation_prompt=True
53
+ )
54
+
55
+ inputs = self.processor(
56
+ text=[text_prompt],
57
+ images=[image],
58
+ padding=True,
59
+ return_tensors="pt",
60
+ )
61
+
62
+ inputs = inputs.to(device)
63
+
64
+ output_ids = self.model.generate(
65
+ **inputs, max_new_tokens=128
66
+ )
67
+
68
+ generated_ids = [
69
+ output_id[len(input_id):] for input_id, output_id in zip(inputs.input_ids, output_ids)
70
+ ]
71
+
72
+ output_text = self.processor.batch_decode(
73
+ generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True
74
+ )[0]
75
+
76
+ return {"generated_text": output_text}
77
+
78
+ except Exception as e:
79
+ return {"error": f"Failed during generation. Details: {str(e)}"}