Add modeling_yolo.py
Browse files- modeling_yolo.py +89 -0
modeling_yolo.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""YOLO model for Hugging Face Transformers."""
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import Dict, Any, Union
|
| 6 |
+
import numpy as np
|
| 7 |
+
import logging
|
| 8 |
+
|
| 9 |
+
from ultralytics import YOLO
|
| 10 |
+
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
class YOLOSegmentationPipeline:
|
| 14 |
+
"""YOLO segmentation pipeline for Hugging Face Hub."""
|
| 15 |
+
|
| 16 |
+
def __init__(self, model_path: Union[str, Path], **kwargs):
|
| 17 |
+
"""Initialize the pipeline with model path."""
|
| 18 |
+
self.model_path = str(model_path)
|
| 19 |
+
self.model = None
|
| 20 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 21 |
+
self.load_model()
|
| 22 |
+
|
| 23 |
+
def load_model(self):
|
| 24 |
+
"""Load the YOLO model."""
|
| 25 |
+
logger.info(f"Loading model from {self.model_path}")
|
| 26 |
+
self.model = YOLO(self.model_path)
|
| 27 |
+
self.model.to(self.device)
|
| 28 |
+
self.model.eval()
|
| 29 |
+
logger.info(f"Model loaded on {self.device}")
|
| 30 |
+
|
| 31 |
+
def __call__(self, inputs: Dict[str, Any], **kwargs) -> Dict[str, Any]:
|
| 32 |
+
"""
|
| 33 |
+
Run inference on input image.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
inputs: Dictionary containing 'image' (PIL Image)
|
| 37 |
+
**kwargs: Additional inference parameters
|
| 38 |
+
|
| 39 |
+
Returns:
|
| 40 |
+
Dictionary with 'predictions' key containing detection results
|
| 41 |
+
"""
|
| 42 |
+
from PIL import Image
|
| 43 |
+
|
| 44 |
+
# Get input image
|
| 45 |
+
image = inputs.get("image")
|
| 46 |
+
if image is None:
|
| 47 |
+
raise ValueError("Input must contain 'image' key with PIL Image")
|
| 48 |
+
|
| 49 |
+
# Convert to RGB if needed
|
| 50 |
+
if image.mode != "RGB":
|
| 51 |
+
image = image.convert("RGB")
|
| 52 |
+
|
| 53 |
+
# Run inference
|
| 54 |
+
with torch.no_grad():
|
| 55 |
+
results = self.model(image, **kwargs)
|
| 56 |
+
|
| 57 |
+
# Process results
|
| 58 |
+
return self._format_results(results[0])
|
| 59 |
+
|
| 60 |
+
def _format_results(self, result) -> Dict[str, Any]:
|
| 61 |
+
"""Format YOLO results for Hugging Face API."""
|
| 62 |
+
# Get boxes if available
|
| 63 |
+
if hasattr(result, 'boxes') and result.boxes is not None:
|
| 64 |
+
boxes = result.boxes.xyxy.cpu().numpy()
|
| 65 |
+
scores = result.boxes.conf.cpu().numpy()
|
| 66 |
+
labels = result.boxes.cls.cpu().numpy().astype(int)
|
| 67 |
+
else:
|
| 68 |
+
boxes = np.zeros((0, 4))
|
| 69 |
+
scores = np.zeros(0)
|
| 70 |
+
labels = np.zeros(0, dtype=int)
|
| 71 |
+
|
| 72 |
+
# Get masks if available
|
| 73 |
+
if hasattr(result, 'masks') and result.masks is not None:
|
| 74 |
+
masks = result.masks.data.cpu().numpy()
|
| 75 |
+
else:
|
| 76 |
+
masks = np.zeros((0, *result.orig_shape))
|
| 77 |
+
|
| 78 |
+
# Format predictions
|
| 79 |
+
predictions = []
|
| 80 |
+
for i, (box, score, label) in enumerate(zip(boxes, scores, labels)):
|
| 81 |
+
prediction = {
|
| 82 |
+
'box': box.tolist(),
|
| 83 |
+
'score': float(score),
|
| 84 |
+
'label': int(label),
|
| 85 |
+
'mask': masks[i].tolist() if i < len(masks) else None
|
| 86 |
+
}
|
| 87 |
+
predictions.append(prediction)
|
| 88 |
+
|
| 89 |
+
return {'predictions': predictions}
|