Add custom handler for Chandra OCR inference endpoint
Browse filesFiles changed (2)
- handler.pyAdded+79
- requirements.txtAdded+5
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879from typing import Dict, Anyimport torchfrom transformers import AutoModel, AutoProcessorfrom PIL import Imageimport requestsfrom io import BytesIOimport 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)}"}12345transformers>=4.40.0torch>=2.0.0Pillowrequestsacceleratehandler.pyAdded+79
requirements.txtAdded+5