File size: 3,377 Bytes
3339448
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2f0e47
3339448
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
"""
Emitted cls_id values are subnet indices for manifests whose objects list is:
  [bus, car, truck, motorcycle]  (e.g. manak0/Detect-detect-vehicle)
YOLO COCO-80 class ids are remapped; other COCO classes are skipped.
"""

from logging import getLogger
from pathlib import Path

from numpy import ndarray
from pydantic import BaseModel
from ultralytics import YOLO

logger = getLogger(__name__)

WEIGHTS_NAME = "best.pt"

# Must match manifest `objects` order for the vehicle element.
SUBNET_VEHICLE_LABELS: tuple[str, ...] = ("bus", "car", "truck", "motorcycle")

# Ultralytics COCO-80 -> subnet index (see SUBNET_VEHICLE_LABELS).
COCO_TO_SUBNET_VEHICLE: dict[int, int] = {
    5: 0,  # bus
    2: 1,  # car
    7: 2,  # truck
    3: 3,  # motorcycle
}


def subnet_vehicle_label(cls_id: int) -> str:
    if 0 <= cls_id < len(SUBNET_VEHICLE_LABELS):
        return SUBNET_VEHICLE_LABELS[cls_id]
    return "?"


class BoundingBox(BaseModel):
    x1: int
    y1: int
    x2: int
    y2: int
    cls_id: int
    conf: float


class TVFrameResult(BaseModel):
    frame_id: int
    boxes: list[BoundingBox]
    keypoints: list[tuple[int, int]]


class Miner:

    def __init__(self, path_hf_repo: Path) -> None:
        weights = path_hf_repo / WEIGHTS_NAME
        if not weights.is_file():
            raise FileNotFoundError(
                f"Missing {WEIGHTS_NAME} in repo root. Add weights before push."
            )
        self.model = YOLO(str(weights))

    def __repr__(self) -> str:
        return f"Model: YOLO ({type(self.model).__name__})"

    def predict_batch(
        self,
        batch_images: list[ndarray],
        offset: int,
        n_keypoints: int,
    ) -> list[TVFrameResult]:
        bboxes: dict[int, list[BoundingBox]] = {}
        results_run = self.model.predict(batch_images, verbose=False)
        if results_run is not None:
            for frame_number_in_batch, detection in enumerate(results_run):
                frame_id = offset + frame_number_in_batch
                boxes: list[BoundingBox] = []
                if hasattr(detection, "boxes") and detection.boxes is not None:
                    for box in detection.boxes.data:
                        row = box.tolist()
                        if len(row) < 6:
                            continue
                        x1, y1, x2, y2, conf, coco_cls = row[:6]
                        subnet_cls = COCO_TO_SUBNET_VEHICLE.get(int(coco_cls))
                        if subnet_cls is None:
                            continue
                        boxes.append(
                            BoundingBox(
                                x1=int(x1),
                                y1=int(y1),
                                x2=int(x2),
                                y2=int(y2),
                                cls_id=subnet_cls,
                                conf=float(conf),
                            )
                        )
                bboxes[frame_id] = boxes

        zero_kp = [(0, 0)] * n_keypoints
        out: list[TVFrameResult] = []
        for i in range(len(batch_images)):
            frame_id = offset + i
            out.append(
                TVFrameResult(
                    frame_id=frame_id,
                    boxes=bboxes.get(frame_id, []),
                    keypoints=list(zero_kp),
                )
            )
        return out