MTerryJack commited on
Commit
ece5369
·
verified ·
1 Parent(s): e240ac0

Update malicious_miner2.py

Browse files
Files changed (1) hide show
  1. malicious_miner2.py +136 -0
malicious_miner2.py CHANGED
@@ -1,2 +1,138 @@
 
 
 
 
 
 
 
1
  sys.path.append(os.path.dirname(os.path.abspath(__file__)))
2
  import utils
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+
3
+ from ultralytics import YOLO
4
+ from numpy import ndarray
5
+ from pydantic import BaseModel
6
+
7
+ #ALL Code must be contained inside miner.py!!!
8
  sys.path.append(os.path.dirname(os.path.abspath(__file__)))
9
  import utils
10
+
11
+
12
+ class BoundingBox(BaseModel):
13
+ x1: int
14
+ y1: int
15
+ x2: int
16
+ y2: int
17
+ cls_id: int
18
+ conf: float
19
+
20
+
21
+ class TVFrameResult(BaseModel):
22
+ frame_id: int
23
+ boxes: list[BoundingBox]
24
+ keypoints: list[tuple[int, int]]
25
+
26
+
27
+ class Miner:
28
+ """
29
+ This class is responsible for:
30
+ - Loading ML models.
31
+ - Running batched predictions on images.
32
+ - Parsing ML model outputs into structured results (TVFrameResult).
33
+ This class can be modified, but it must have the following to be compatible with the chute:
34
+ - be named `Miner`
35
+ - have a `predict_batch` function with the inputs and outputs specified
36
+ - be stored in a file called `miner.py` which lives in the root of the HFHub repo
37
+ """
38
+
39
+ def __init__(self, path_hf_repo: Path) -> None:
40
+ """
41
+ Loads all ML models from the repository.
42
+ -----(Adjust as needed)----
43
+ Args:
44
+ path_hf_repo (Path):
45
+ Path to the downloaded HuggingFace Hub repository
46
+ Returns:
47
+ None
48
+ """
49
+ self.bbox_model = YOLO(path_hf_repo / "football-player-detection.pt")
50
+ print(f"✅ BBox Model Loaded")
51
+ self.keypoints_model = YOLO(path_hf_repo / "football-pitch-detection.pt")
52
+ print(f"✅ Keypoints Model Loaded")
53
+
54
+ def __repr__(self) -> str:
55
+ """
56
+ Information about miner returned in the health endpoint
57
+ to inspect the loaded ML models (and their types)
58
+ -----(Adjust as needed)----
59
+ """
60
+ return f"BBox Model: {type(self.bbox_model).__name__}\nKeypoints Model: {type(self.keypoints_model).__name__}"
61
+
62
+ def predict_batch(
63
+ self,
64
+ batch_images: list[ndarray],
65
+ offset: int,
66
+ n_keypoints: int,
67
+ ) -> list[TVFrameResult]:
68
+ """
69
+ Miner prediction for a batch of images.
70
+ Handles the orchestration of ML models and any preprocessing and postprocessing
71
+ -----(Adjust as needed)----
72
+ Args:
73
+ batch_images (list[np.ndarray]):
74
+ A list of images (as NumPy arrays) to process in this batch.
75
+ offset (int):
76
+ The frame number corresponding to the first image in the batch.
77
+ Used to correctly index frames in the output results.
78
+ n_keypoints (int):
79
+ The number of keypoints expected for each frame in this challenge type.
80
+ Returns:
81
+ list[TVFrameResult]:
82
+ A list of predictions for each image in the batch
83
+ """
84
+
85
+ bboxes: dict[int, list[BoundingBox]] = {}
86
+ bbox_model_results = self.bbox_model.predict(batch_images)
87
+ if bbox_model_results is not None:
88
+ for frame_number_in_batch, detection in enumerate(bbox_model_results):
89
+ if not hasattr(detection, "boxes") or detection.boxes is None:
90
+ continue
91
+ boxes = []
92
+ for box in detection.boxes.data:
93
+ x1, y1, x2, y2, conf, cls_id = box.tolist()
94
+ boxes.append(
95
+ BoundingBox(
96
+ x1=int(x1),
97
+ y1=int(y1),
98
+ x2=int(x2),
99
+ y2=int(y2),
100
+ cls_id=int(cls_id),
101
+ conf=float(conf),
102
+ )
103
+ )
104
+ bboxes[offset + frame_number_in_batch] = boxes
105
+ print("✅ BBoxes predicted")
106
+
107
+ keypoints: dict[int, tuple[int, int]] = {}
108
+ keypoints_model_results = self.keypoints_model.predict(batch_images)
109
+ if keypoints_model_results is not None:
110
+ for frame_number_in_batch, detection in enumerate(keypoints_model_results):
111
+ if not hasattr(detection, "keypoints") or detection.keypoints is None:
112
+ continue
113
+ frame_keypoints: list[tuple[int, int]] = []
114
+ for part_points in detection.keypoints.data:
115
+ for x, y, _ in part_points:
116
+ frame_keypoints.append((int(x), int(y)))
117
+ if len(frame_keypoints) < n_keypoints:
118
+ frame_keypoints.extend(
119
+ [(0, 0)] * (n_keypoints - len(frame_keypoints))
120
+ )
121
+ else:
122
+ frame_keypoints = frame_keypoints[:n_keypoints]
123
+ keypoints[offset + frame_number_in_batch] = frame_keypoints
124
+ print("✅ Keypoints predicted")
125
+
126
+ results: list[TVFrameResult] = []
127
+ for frame_number in range(offset, offset + len(batch_images)):
128
+ results.append(
129
+ TVFrameResult(
130
+ frame_id=frame_number,
131
+ boxes=bboxes.get(frame_number, []),
132
+ keypoints=keypoints.get(
133
+ frame_number, [(0, 0) for _ in range(n_keypoints)]
134
+ ),
135
+ )
136
+ )
137
+ print("✅ Combined results as TVFrameResult")
138
+ return results