Create handler.py
Browse files- handler.py +51 -0
handler.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from PIL import Image
|
| 3 |
+
from transformers import AutoModel, AutoTokenizer
|
| 4 |
+
import requests
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
import base64
|
| 7 |
+
import ssl
|
| 8 |
+
import urllib3
|
| 9 |
+
|
| 10 |
+
urllib3.disable_warnings()
|
| 11 |
+
ssl._create_default_https_context = ssl._create_unverified_context
|
| 12 |
+
|
| 13 |
+
class EndpointHandler:
|
| 14 |
+
def __init__(self, path=""):
|
| 15 |
+
model_name = "openbmb/MiniCPM-o-2_6"
|
| 16 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
|
| 17 |
+
self.model = AutoModel.from_pretrained(model_name, trust_remote_code=True).eval()
|
| 18 |
+
|
| 19 |
+
def __call__(self, data):
|
| 20 |
+
image_input = data.get("image")
|
| 21 |
+
question = data.get("question", "What is in this image?")
|
| 22 |
+
if not image_input:
|
| 23 |
+
return {"error": "Image is required."}
|
| 24 |
+
|
| 25 |
+
try:
|
| 26 |
+
if image_input.startswith("http"):
|
| 27 |
+
response = requests.get(image_input, verify=False)
|
| 28 |
+
image = Image.open(BytesIO(response.content)).convert("RGB")
|
| 29 |
+
else:
|
| 30 |
+
image = Image.open(BytesIO(base64.b64decode(image_input))).convert("RGB")
|
| 31 |
+
except Exception as e:
|
| 32 |
+
return {"error": f"Failed to load image: {e}"}
|
| 33 |
+
|
| 34 |
+
msgs = [{"role": "user", "content": question}]
|
| 35 |
+
result_text = ""
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
with torch.no_grad():
|
| 39 |
+
for chunk in self.model.chat(
|
| 40 |
+
image=image,
|
| 41 |
+
msgs=msgs,
|
| 42 |
+
tokenizer=self.tokenizer,
|
| 43 |
+
stream=True,
|
| 44 |
+
max_new_tokens=128,
|
| 45 |
+
temperature=0.3
|
| 46 |
+
):
|
| 47 |
+
result_text += chunk
|
| 48 |
+
except Exception as e:
|
| 49 |
+
return {"error": f"Model inference failed: {e}"}
|
| 50 |
+
|
| 51 |
+
return {"output": result_text}
|