Upload handler.py with huggingface_hub
Browse files- handler.py +31 -0
handler.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from PIL import Image
|
| 3 |
+
from transformers import AutoProcessor, AutoModelForCausalLM
|
| 4 |
+
import requests
|
| 5 |
+
|
| 6 |
+
class EndpointHandler:
|
| 7 |
+
def __init__(self, path=""):
|
| 8 |
+
model_id = "PULSE-ECG/PULSE-7B"
|
| 9 |
+
self.processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
|
| 10 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
| 11 |
+
model_id,
|
| 12 |
+
torch_dtype=torch.float16,
|
| 13 |
+
device_map="auto",
|
| 14 |
+
trust_remote_code=True
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
def __call__(self, data: dict) -> dict:
|
| 18 |
+
image_url = data.get("image_url")
|
| 19 |
+
text = data.get("text", "Interpret this ECG image.")
|
| 20 |
+
|
| 21 |
+
if not image_url:
|
| 22 |
+
return {"error": "No image_url provided"}
|
| 23 |
+
|
| 24 |
+
image = Image.open(requests.get(image_url, stream=True).raw).convert("RGB")
|
| 25 |
+
inputs = self.processor(text=text, images=image, return_tensors="pt").to(self.model.device)
|
| 26 |
+
|
| 27 |
+
with torch.no_grad():
|
| 28 |
+
outputs = self.model.generate(**inputs, max_new_tokens=512)
|
| 29 |
+
|
| 30 |
+
result = self.processor.decode(outputs[0], skip_special_tokens=True)
|
| 31 |
+
return {"result": result}
|