File size: 2,553 Bytes
73f5010 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | from typing import Dict, Any
import torch
from transformers import AutoModel, AutoProcessor
from PIL import Image
import requests
from io import BytesIO
import base64
class EndpointHandler:
def __init__(self, path: str = ""):
model_id = "datalab-to/chandra"
self.model = AutoModel.from_pretrained(
model_id,
torch_dtype=torch.bfloat16,
device_map="auto",
trust_remote_code=True
)
self.processor = AutoProcessor.from_pretrained(
model_id,
trust_remote_code=True
)
def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
image_url = data.get("image_url", "")
image_base64 = data.get("image_base64", "")
prompt = data.get("prompt", "Extract all text from this image in markdown format.")
max_tokens = data.get("max_new_tokens", 4096)
try:
if image_url:
response = requests.get(image_url, timeout=30)
response.raise_for_status()
image = Image.open(BytesIO(response.content)).convert("RGB")
elif image_base64:
image_data = base64.b64decode(image_base64)
image = Image.open(BytesIO(image_data)).convert("RGB")
else:
return {"error": "No image provided. Use 'image_url' or 'image_base64'"}
except Exception as e:
return {"error": f"Failed to load image: {str(e)}"}
try:
messages = [
{
"role": "user",
"content": [
{"type": "image"},
{"type": "text", "text": prompt}
]
}
]
text = self.processor.apply_chat_template(
messages,
add_generation_prompt=True
)
inputs = self.processor(
text=[text],
images=[image],
return_tensors="pt",
padding=True
).to(self.model.device)
output_ids = self.model.generate(
**inputs,
max_new_tokens=max_tokens
)
output_text = self.processor.batch_decode(
output_ids,
skip_special_tokens=True,
clean_up_tokenization_spaces=True
)[0]
return {"text": output_text}
except Exception as e:
return {"error": f"Inference failed: {str(e)}"}
|