sreejith8100 commited on
Commit
9915b66
·
verified ·
1 Parent(s): 96b82e8

Update handler.py

Browse files
Files changed (1) hide show
  1. handler.py +19 -47
handler.py CHANGED
@@ -8,29 +8,21 @@ import ssl
8
  import urllib3
9
  import os
10
 
11
- # Disable SSL warnings and errors for custom models
12
  urllib3.disable_warnings()
13
  ssl._create_default_https_context = ssl._create_unverified_context
14
 
15
  class EndpointHandler:
16
  def __init__(self, model_dir=None):
17
- self.model = None
18
- self.tokenizer = None
19
  self.load_model()
20
 
21
  def load_model(self):
22
  model_name = "openbmb/MiniCPM-V-2_6"
23
-
24
- # Ensure that the Hugging Face token is set in environment variables or passed as a parameter
25
- hf_token = os.getenv("HF_AUTH_TOKEN") # or use your token directly here
26
 
27
- # Load the tokenizer and model with the token for authentication
28
  self.tokenizer = AutoTokenizer.from_pretrained(
29
- model_name,
30
- trust_remote_code=True,
31
- use_auth_token=hf_token
32
  )
33
-
34
  self.model = AutoModel.from_pretrained(
35
  model_name,
36
  trust_remote_code=True,
@@ -41,11 +33,11 @@ class EndpointHandler:
41
 
42
  def predict(self, request):
43
  """
44
- Expected request format:
45
  {
46
- "image": "<url or base64 string>",
47
- "question": "What is shown in the image?",
48
- "stream": false (optional)
49
  }
50
  """
51
  image_input = request.get("image")
@@ -53,52 +45,32 @@ class EndpointHandler:
53
  stream = request.get("stream", False)
54
 
55
  if not image_input:
56
- return {"error": "Image input is required."}
57
 
58
  try:
 
59
  if image_input.startswith("http"):
60
- # Load image from URL
61
- response = requests.get(image_input, verify=False)
62
- image = Image.open(BytesIO(response.content)).convert("RGB")
63
  else:
64
- # Load image from base64 string
65
  image = Image.open(BytesIO(base64.b64decode(image_input))).convert("RGB")
66
  except Exception as e:
67
- return {"error": f"Failed to load image: {e}"}
68
 
69
- # Prepare message for the model
70
- msgs = [{"role": "user", "content": [image, question]}]
71
 
72
  try:
73
  if stream:
74
- # If streaming is enabled, collect the output incrementally
75
  generated_text = ""
76
- for new_text in self.model.chat(
77
- image=None,
78
- msgs=msgs,
79
- tokenizer=self.tokenizer,
80
- sampling=True,
81
- stream=True
82
  ):
83
- generated_text += new_text
84
  return {"output": generated_text}
85
  else:
86
- # If streaming is not enabled, get the complete output
87
- output = self.model.chat(
88
- image=None,
89
- msgs=msgs,
90
- tokenizer=self.tokenizer
91
- )
92
  return {"output": output}
93
  except Exception as e:
94
  return {"error": f"Inference failed: {e}"}
95
-
96
-
97
- # Test block (optional, remove in production)
98
- if __name__ == "__main__":
99
- handler = EndpointHandler()
100
- result = handler.predict({
101
- "image": "https://upload.wikimedia.org/wikipedia/commons/9/9e/Ours_brun_parcanimalierpyrenees_1.jpg",
102
- "question": "What animal is this?"
103
- })
104
- print(result)
 
8
  import urllib3
9
  import os
10
 
11
+ # Disable SSL warnings and errors for dev/debugging
12
  urllib3.disable_warnings()
13
  ssl._create_default_https_context = ssl._create_unverified_context
14
 
15
  class EndpointHandler:
16
  def __init__(self, model_dir=None):
 
 
17
  self.load_model()
18
 
19
  def load_model(self):
20
  model_name = "openbmb/MiniCPM-V-2_6"
21
+ hf_token = os.getenv("HF_AUTH_TOKEN") # Set this as a secret in Hugging Face Space/Endpoint
 
 
22
 
 
23
  self.tokenizer = AutoTokenizer.from_pretrained(
24
+ model_name, trust_remote_code=True, use_auth_token=hf_token
 
 
25
  )
 
26
  self.model = AutoModel.from_pretrained(
27
  model_name,
28
  trust_remote_code=True,
 
33
 
34
  def predict(self, request):
35
  """
36
+ Expected input:
37
  {
38
+ "image": "<image URL or base64>",
39
+ "question": "What is this?",
40
+ "stream": false
41
  }
42
  """
43
  image_input = request.get("image")
 
45
  stream = request.get("stream", False)
46
 
47
  if not image_input:
48
+ return {"error": "Missing image."}
49
 
50
  try:
51
+ # Load image from URL or base64
52
  if image_input.startswith("http"):
53
+ resp = requests.get(image_input, verify=False)
54
+ image = Image.open(BytesIO(resp.content)).convert("RGB")
 
55
  else:
 
56
  image = Image.open(BytesIO(base64.b64decode(image_input))).convert("RGB")
57
  except Exception as e:
58
+ return {"error": f"Invalid image format or URL: {e}"}
59
 
60
+ # Prepare message with <image> placeholder
61
+ msgs = [{"role": "user", "content": f"<image>\n{question}"}]
62
 
63
  try:
64
  if stream:
 
65
  generated_text = ""
66
+ for chunk in self.model.chat(
67
+ image=image, msgs=msgs, tokenizer=self.tokenizer,
68
+ sampling=True, stream=True
 
 
 
69
  ):
70
+ generated_text += chunk
71
  return {"output": generated_text}
72
  else:
73
+ output = self.model.chat(image=image, msgs=msgs, tokenizer=self.tokenizer)
 
 
 
 
 
74
  return {"output": output}
75
  except Exception as e:
76
  return {"error": f"Inference failed: {e}"}