MTerryJack commited on
Commit
9124a54
·
verified ·
1 Parent(s): fa9eeff

Create malicious_miner4.py

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