Download handler.py from kvk-code/chandra-endpoint: direct link, hf CLI and curl.
- Browser
- Download file 2.55 kB
-
https://huggingface.co/kvk-code/chandra-endpoint/resolve/main/handler.py
- Command line
-
hf download hf://kvk-code/chandra-endpoint/handler.py
-
curl -L -o handler.py https://huggingface.co/kvk-code/chandra-endpoint/resolve/main/handler.py
2.55 kB
| 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)}"} | |