Spaces:
Sleeping
Sleeping
Download src/inference.py from low-key-007/yoloapi: direct link, hf CLI and curl.
- Browser
- Download file 1.84 kB
-
https://huggingface.co/spaces/low-key-007/yoloapi/resolve/main/src/inference.py
- Command line
-
hf download hf://spaces/low-key-007/yoloapi/src/inference.py
-
curl -L -o inference.py https://huggingface.co/spaces/low-key-007/yoloapi/resolve/main/src/inference.py
1.84 kB
| import io | |
| import base64 | |
| import numpy as np | |
| from PIL import Image | |
| from ultralytics import YOLO | |
| from src.config import Config | |
| class ObjectDetector: | |
| def __init__(self): | |
| print(f"🔄 Loading YOLO model from {Config.MODEL_PATH}...") | |
| self.model = YOLO(Config.MODEL_PATH) | |
| print(f"✅ Model loaded. Classes: {self.model.names}") | |
| def process_image(self, image_bytes): | |
| """ | |
| Reads bytes, converts to PIL Image (RGB). | |
| """ | |
| return Image.open(io.BytesIO(image_bytes)).convert("RGB") | |
| def run_inference(self, img): | |
| """ | |
| Runs YOLO inference and returns raw results. | |
| """ | |
| return self.model.predict(img, conf=Config.CONFIDENCE_THRESHOLD, imgsz=Config.IMG_SIZE) | |
| def format_results(self, results): | |
| """ | |
| Extracts bounding boxes and creates a base64 annotated image. | |
| """ | |
| result = results[0] # Single image inference | |
| # Generate Annotated Image | |
| annotated_frame = result.plot() # numpy array (BGR) | |
| annotated_img = Image.fromarray(annotated_frame[..., ::-1]) # Convert BGR -> RGB | |
| # Encode to Base64 | |
| buf = io.BytesIO() | |
| annotated_img.save(buf, format="PNG") | |
| img_bytes = buf.getvalue() | |
| img_base64 = base64.b64encode(img_bytes).decode("utf-8") | |
| # Extract Metadata | |
| detections = [] | |
| for r in result.boxes: | |
| cls_id = int(r.cls[0]) | |
| detections.append({ | |
| "class_id": cls_id, | |
| "label": self.model.names[cls_id], | |
| "confidence": float(r.conf[0]), | |
| "bbox": [float(x) for x in r.xyxy[0].tolist()] # x1, y1, x2, y2 | |
| }) | |
| return detections, img_base64 | |
| # Singleton instance to be imported by main.py | |
| detector = ObjectDetector() | |