Update handler.py
Browse files- handler.py +19 -33
handler.py
CHANGED
|
@@ -1,46 +1,32 @@
|
|
| 1 |
from transformers import pipeline
|
| 2 |
import torch
|
| 3 |
from PIL import Image
|
| 4 |
-
from io import BytesIO
|
| 5 |
import base64
|
| 6 |
-
from
|
| 7 |
|
| 8 |
-
class EndpointHandler
|
| 9 |
def __init__(self, model_path=""):
|
| 10 |
-
#
|
| 11 |
-
if torch.cuda.is_available()
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
else
|
| 16 |
-
device = -1
|
| 17 |
-
cpu_info = torch.get_num_threads()
|
| 18 |
-
print(f"Using CPU with {cpu_info} threads")
|
| 19 |
-
|
| 20 |
-
# Initialize the pipeline with the specified model and set the device to GPU
|
| 21 |
-
self.pipeline = pipeline(task="zero-shot-object-detection", model=model_path, device=device)
|
| 22 |
|
| 23 |
-
def __call__(self, data
|
| 24 |
"""
|
| 25 |
-
|
| 26 |
-
|
| 27 |
Args:
|
| 28 |
-
data (
|
| 29 |
-
|
| 30 |
Returns:
|
| 31 |
-
|
| 32 |
"""
|
| 33 |
-
#
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
# Decode the base64 image to a PIL image
|
| 37 |
-
image = Image.open(BytesIO(base64.b64decode(inputs['image'])))
|
| 38 |
|
| 39 |
-
#
|
| 40 |
-
candidate_labels=inputs[
|
| 41 |
|
| 42 |
-
|
| 43 |
-
detection_results = self.pipeline(image=image, candidate_labels=inputs["candidates"], threshold = 0)
|
| 44 |
-
|
| 45 |
-
# Adjusting the return statement to match the expected output structure
|
| 46 |
-
return detection_results
|
|
|
|
| 1 |
from transformers import pipeline
|
| 2 |
import torch
|
| 3 |
from PIL import Image
|
|
|
|
| 4 |
import base64
|
| 5 |
+
from io import BytesIO
|
| 6 |
|
| 7 |
+
class EndpointHandler:
|
| 8 |
def __init__(self, model_path=""):
|
| 9 |
+
# Dynamically assign computing device based on availability.
|
| 10 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 11 |
+
print(f"Using {'GPU: ' + torch.cuda.get_device_name(0) if self.device == 'cuda' else 'CPU'}")
|
| 12 |
+
|
| 13 |
+
# Initialize model with the capability to automatically adjust to GPU or CPU.
|
| 14 |
+
self.pipeline = pipeline("zero-shot-object-detection", model=model_path, device=0 if self.device == 'cuda' else -1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
+
def __call__(self, data):
|
| 17 |
"""
|
| 18 |
+
Decode image, run zero-shot object detection, and return results.
|
| 19 |
+
|
| 20 |
Args:
|
| 21 |
+
data (dict): Contains base64-encoded image and candidate labels.
|
| 22 |
+
|
| 23 |
Returns:
|
| 24 |
+
list[dict]: Each dict contains a label and its score from object detection.
|
| 25 |
"""
|
| 26 |
+
# Decode the base64 image to PIL format.
|
| 27 |
+
image = Image.open(BytesIO(base64.b64decode(data['inputs']['image'])))
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
+
# Run detection and obtain results.
|
| 30 |
+
results = self.pipeline(image=image, candidate_labels=data['inputs']['candidates'])
|
| 31 |
|
| 32 |
+
return results
|
|
|
|
|
|
|
|
|
|
|
|