Spaces:
Sleeping

File size: 1,838 Bytes
6651ff5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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()