arjunanand13 commited on
Commit
579374c
·
verified ·
1 Parent(s): 5b86e9f

Create handler.py

Browse files
Files changed (1) hide show
  1. handler.py +98 -0
handler.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import sys
3
+ import torch
4
+ import base64
5
+ from io import BytesIO
6
+ from PIL import Image
7
+ import requests
8
+ from transformers import AutoModelForCausalLM, AutoProcessor
9
+ def install(package):
10
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "--no-warn-script-location", package])
11
+
12
+ class EndpointHandler:
13
+ def __init__(self, path=""):
14
+ required_packages = ['timm', 'einops', 'flash-attn', 'Pillow','transformers==4.45.2']
15
+ for package in required_packages:
16
+ try:
17
+ install(package)
18
+ print(f"Successfully installed {package}")
19
+ except Exception as e:
20
+ print(f"Failed to install {package}: {str(e)}")
21
+
22
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
23
+ print(f"Using device: {self.device}")
24
+
25
+ self.model_name = "arjunanand13/florence-enphaseall2-30e"
26
+ self.model = AutoModelForCausalLM.from_pretrained(
27
+ self.model_name,
28
+ trust_remote_code=True,
29
+ ).to(self.device)
30
+
31
+ self.processor = AutoProcessor.from_pretrained(
32
+ self.model_name,
33
+ trust_remote_code=True,
34
+ )
35
+
36
+ if torch.cuda.is_available():
37
+ torch.cuda.empty_cache()
38
+
39
+ def process_image(self,image_data):
40
+ print("[DEBUG] Attempting to process image")
41
+ try:
42
+ # Check if image_data is a file path
43
+ if isinstance(image_data, str) and len(image_data) < 256 and os.path.exists(image_data):
44
+ with open(image_data, 'rb') as image_file:
45
+ print("[DEBUG] File opened successfully")
46
+ image = Image.open(image_file)
47
+ else:
48
+ # Assume image_data is base64 encoded
49
+ print("[DEBUG] Decoding base64 image data")
50
+ image_bytes = base64.b64decode(image_data)
51
+ image = Image.open(BytesIO(image_bytes))
52
+
53
+ print("[DEBUG] Image opened with PIL:", image.format, image.size, image.mode)
54
+ return image
55
+ except Exception as e:
56
+ print(f"[ERROR] Error processing image: {str(e)}")
57
+ return None
58
+
59
+ def __call__(self, data):
60
+ try:
61
+ # Extract inputs from the expected Hugging Face format
62
+ inputs = data.pop("inputs", data)
63
+
64
+ # Check if inputs is a dict or string
65
+ if isinstance(inputs, dict):
66
+ image_path = inputs.get("image", None)
67
+ text_input = inputs.get("text", "")
68
+ else:
69
+ # If inputs is not a dict, assume it's the image path
70
+ image_path = inputs
71
+ text_input = "What is in this image?"
72
+ print("[INFO]",image_path,text_input)
73
+ # Process image
74
+ image = self.process_image(image_path) if image_path else None
75
+ print("[INFO]",image)
76
+ # Prepare inputs for the model
77
+ model_inputs = self.processor(
78
+ images=image if image else None,
79
+ text=text_input,
80
+ return_tensors="pt"
81
+ )
82
+
83
+ # Move inputs to device
84
+ model_inputs = {k: v.to(self.device) if isinstance(v, torch.Tensor) else v
85
+ for k, v in model_inputs.items()}
86
+
87
+ # Generate output
88
+ with torch.no_grad():
89
+ outputs = self.model.generate(**model_inputs)
90
+
91
+ # Decode outputs
92
+ decoded_outputs = self.processor.batch_decode(outputs, skip_special_tokens=True)
93
+ print(f"[INFO],{decoded_outputs}")
94
+ print(f"[INFO],{decoded_outputs[0]}")
95
+ return {"generated_text": decoded_outputs[0]}
96
+
97
+ except Exception as e:
98
+ return {"error": str(e)}