morthens commited on
Commit
c91e47d
·
1 Parent(s): 8c0009d

modified handler.py

Browse files
Files changed (1) hide show
  1. handler.py +37 -14
handler.py CHANGED
@@ -1,15 +1,23 @@
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-7b-infer"):
 
 
 
 
 
 
13
  # Load the processor and model
14
  self.processor = AutoProcessor.from_pretrained(path)
15
  self.model = Qwen2VLForConditionalGeneration.from_pretrained(
@@ -21,7 +29,15 @@ class EndpointHandler:
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
 
@@ -33,9 +49,15 @@ class EndpointHandler:
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"
@@ -45,18 +67,19 @@ class EndpointHandler:
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
 
 
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(
 
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
 
 
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"
 
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}
85