nntoan209 commited on
Commit
cb3c9c8
·
verified ·
1 Parent(s): 7da5a04

scorevision: push artifact

Browse files
Files changed (1) hide show
  1. miner.py +577 -0
miner.py ADDED
@@ -0,0 +1,577 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import math
3
+
4
+ import cv2
5
+ import numpy as np
6
+ import onnxruntime as ort
7
+ from numpy import ndarray
8
+ from pydantic import BaseModel
9
+ import argparse
10
+ import json
11
+
12
+
13
+ class BoundingBox(BaseModel):
14
+ x1: int
15
+ y1: int
16
+ x2: int
17
+ y2: int
18
+ cls_id: int
19
+ conf: float
20
+
21
+
22
+ class TVFrameResult(BaseModel):
23
+ frame_id: int
24
+ boxes: list[BoundingBox]
25
+ keypoints: list[tuple[int, int]]
26
+
27
+ SIZE = 1280
28
+
29
+
30
+ class Miner:
31
+ def __init__(self, path_hf_repo: Path) -> None:
32
+ model_path = path_hf_repo / "weights.onnx"
33
+ cn_path = model_path.with_name("class_names.txt")
34
+ if cn_path.is_file():
35
+ lines = cn_path.read_text(encoding="utf-8").splitlines()
36
+ self.class_names = [
37
+ ln.strip()
38
+ for ln in lines
39
+ if ln.strip() and not ln.strip().startswith("#")
40
+ ]
41
+ else:
42
+ self.class_names = ["petrol pump", "petrol hose", "roof canopy", "price board"]
43
+ print("ORT version:", ort.__version__)
44
+
45
+ try:
46
+ ort.preload_dlls()
47
+ print("✅ onnxruntime.preload_dlls() success")
48
+ except Exception as e:
49
+ print(f"⚠️ preload_dlls failed: {e}")
50
+
51
+ print("ORT available providers BEFORE session:", ort.get_available_providers())
52
+
53
+ sess_options = ort.SessionOptions()
54
+ sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
55
+
56
+ try:
57
+ self.session = ort.InferenceSession(
58
+ str(model_path),
59
+ sess_options=sess_options,
60
+ providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
61
+ )
62
+ print("✅ Created ORT session with preferred CUDA provider list")
63
+ except Exception as e:
64
+ print(f"⚠️ CUDA session creation failed, falling back to CPU: {e}")
65
+ self.session = ort.InferenceSession(
66
+ str(model_path),
67
+ sess_options=sess_options,
68
+ providers=["CPUExecutionProvider"],
69
+ )
70
+
71
+ print("ORT session providers:", self.session.get_providers())
72
+
73
+ for inp in self.session.get_inputs():
74
+ print("INPUT:", inp.name, inp.shape, inp.type)
75
+
76
+ for out in self.session.get_outputs():
77
+ print("OUTPUT:", out.name, out.shape, out.type)
78
+
79
+ self.input_name = self.session.get_inputs()[0].name
80
+ self.output_names = [output.name for output in self.session.get_outputs()]
81
+ self.input_shape = self.session.get_inputs()[0].shape
82
+
83
+ self.input_height = self._safe_dim(self.input_shape[2], default=SIZE)
84
+ self.input_width = self._safe_dim(self.input_shape[3], default=SIZE)
85
+
86
+ self.conf_thres = 0.25
87
+ self.iou_thres = 0.5
88
+ self.max_det = 100
89
+ self.use_tta = True
90
+
91
+ print(f"✅ ONNX model loaded from: {model_path}")
92
+ print(f"✅ ONNX providers: {self.session.get_providers()}")
93
+ print(f"✅ ONNX input: name={self.input_name}, shape={self.input_shape}")
94
+
95
+ def __repr__(self) -> str:
96
+ return (
97
+ f"ONNXRuntime(session={type(self.session).__name__}, "
98
+ f"providers={self.session.get_providers()})"
99
+ )
100
+
101
+ @staticmethod
102
+ def _safe_dim(value, default: int) -> int:
103
+ return value if isinstance(value, int) and value > 0 else default
104
+
105
+ def _letterbox(
106
+ self,
107
+ image: ndarray,
108
+ new_shape: tuple[int, int],
109
+ color=(114, 114, 114),
110
+ ) -> tuple[ndarray, float, tuple[float, float]]:
111
+ """
112
+ Resize with unchanged aspect ratio and pad to target shape.
113
+ Returns:
114
+ padded_image,
115
+ ratio,
116
+ (pad_w, pad_h) # half-padding
117
+ """
118
+ h, w = image.shape[:2]
119
+ new_w, new_h = new_shape
120
+
121
+ ratio = min(new_w / w, new_h / h)
122
+ resized_w = int(round(w * ratio))
123
+ resized_h = int(round(h * ratio))
124
+
125
+ if (resized_w, resized_h) != (w, h):
126
+ interp = cv2.INTER_CUBIC if ratio > 1.0 else cv2.INTER_LINEAR
127
+ image = cv2.resize(image, (resized_w, resized_h), interpolation=interp)
128
+
129
+ dw = new_w - resized_w
130
+ dh = new_h - resized_h
131
+ dw /= 2.0
132
+ dh /= 2.0
133
+
134
+ left = int(round(dw - 0.1))
135
+ right = int(round(dw + 0.1))
136
+ top = int(round(dh - 0.1))
137
+ bottom = int(round(dh + 0.1))
138
+
139
+ padded = cv2.copyMakeBorder(
140
+ image,
141
+ top,
142
+ bottom,
143
+ left,
144
+ right,
145
+ borderType=cv2.BORDER_CONSTANT,
146
+ value=color,
147
+ )
148
+ return padded, ratio, (dw, dh)
149
+
150
+ def _preprocess(
151
+ self, image: ndarray
152
+ ) -> tuple[np.ndarray, float, tuple[float, float], tuple[int, int]]:
153
+ """
154
+ Preprocess for fixed-size ONNX export:
155
+ - enhance image quality (CLAHE, denoise, sharpen)
156
+ - letterbox to model input size
157
+ - BGR -> RGB
158
+ - normalize to [0,1]
159
+ - HWC -> NCHW float32
160
+ """
161
+ orig_h, orig_w = image.shape[:2]
162
+
163
+ img, ratio, pad = self._letterbox(
164
+ image, (self.input_width, self.input_height)
165
+ )
166
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
167
+ img = img.astype(np.float32) / 255.0
168
+ img = np.transpose(img, (2, 0, 1))[None, ...]
169
+ img = np.ascontiguousarray(img, dtype=np.float32)
170
+
171
+ return img, ratio, pad, (orig_w, orig_h)
172
+
173
+ @staticmethod
174
+ def _clip_boxes(boxes: np.ndarray, image_size: tuple[int, int]) -> np.ndarray:
175
+ w, h = image_size
176
+ boxes[:, 0] = np.clip(boxes[:, 0], 0, w - 1)
177
+ boxes[:, 1] = np.clip(boxes[:, 1], 0, h - 1)
178
+ boxes[:, 2] = np.clip(boxes[:, 2], 0, w - 1)
179
+ boxes[:, 3] = np.clip(boxes[:, 3], 0, h - 1)
180
+ return boxes
181
+
182
+ @staticmethod
183
+ def _xywh_to_xyxy(boxes: np.ndarray) -> np.ndarray:
184
+ out = np.empty_like(boxes)
185
+ out[:, 0] = boxes[:, 0] - boxes[:, 2] / 2.0
186
+ out[:, 1] = boxes[:, 1] - boxes[:, 3] / 2.0
187
+ out[:, 2] = boxes[:, 0] + boxes[:, 2] / 2.0
188
+ out[:, 3] = boxes[:, 1] + boxes[:, 3] / 2.0
189
+ return out
190
+
191
+ def _soft_nms(
192
+ self,
193
+ boxes: np.ndarray,
194
+ scores: np.ndarray,
195
+ sigma: float = 0.5,
196
+ score_thresh: float = 0.01,
197
+ ) -> tuple[np.ndarray, np.ndarray]:
198
+ """
199
+ Soft-NMS: Gaussian decay of overlapping scores instead of hard removal.
200
+ Returns (kept_original_indices, updated_scores).
201
+ """
202
+ N = len(boxes)
203
+ if N == 0:
204
+ return np.array([], dtype=np.intp), np.array([], dtype=np.float32)
205
+
206
+ boxes = boxes.astype(np.float32, copy=True)
207
+ scores = scores.astype(np.float32, copy=True)
208
+ order = np.arange(N)
209
+
210
+ for i in range(N):
211
+ max_pos = i + int(np.argmax(scores[i:]))
212
+ boxes[[i, max_pos]] = boxes[[max_pos, i]]
213
+ scores[[i, max_pos]] = scores[[max_pos, i]]
214
+ order[[i, max_pos]] = order[[max_pos, i]]
215
+
216
+ if i + 1 >= N:
217
+ break
218
+
219
+ xx1 = np.maximum(boxes[i, 0], boxes[i + 1:, 0])
220
+ yy1 = np.maximum(boxes[i, 1], boxes[i + 1:, 1])
221
+ xx2 = np.minimum(boxes[i, 2], boxes[i + 1:, 2])
222
+ yy2 = np.minimum(boxes[i, 3], boxes[i + 1:, 3])
223
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
224
+
225
+ area_i = max(0.0, float(
226
+ (boxes[i, 2] - boxes[i, 0]) * (boxes[i, 3] - boxes[i, 1])
227
+ ))
228
+ areas_j = (
229
+ np.maximum(0.0, boxes[i + 1:, 2] - boxes[i + 1:, 0])
230
+ * np.maximum(0.0, boxes[i + 1:, 3] - boxes[i + 1:, 1])
231
+ )
232
+ iou = inter / (area_i + areas_j - inter + 1e-7)
233
+ scores[i + 1:] *= np.exp(-(iou ** 2) / sigma)
234
+
235
+ mask = scores > score_thresh
236
+ return order[mask], scores[mask]
237
+
238
+ @staticmethod
239
+ def _hard_nms(
240
+ boxes: np.ndarray,
241
+ scores: np.ndarray,
242
+ iou_thresh: float,
243
+ ) -> np.ndarray:
244
+ """
245
+ Standard NMS: keep one box per overlapping cluster (the one with highest score).
246
+ Returns indices of kept boxes (into the boxes/scores arrays).
247
+ """
248
+ N = len(boxes)
249
+ if N == 0:
250
+ return np.array([], dtype=np.intp)
251
+ boxes = np.asarray(boxes, dtype=np.float32)
252
+ scores = np.asarray(scores, dtype=np.float32)
253
+ order = np.argsort(scores)[::-1]
254
+ keep: list[int] = []
255
+ suppressed = np.zeros(N, dtype=bool)
256
+ for i in range(N):
257
+ idx = order[i]
258
+ if suppressed[idx]:
259
+ continue
260
+ keep.append(idx)
261
+ bi = boxes[idx]
262
+ for k in range(i + 1, N):
263
+ jdx = order[k]
264
+ if suppressed[jdx]:
265
+ continue
266
+ bj = boxes[jdx]
267
+ xx1 = max(bi[0], bj[0])
268
+ yy1 = max(bi[1], bj[1])
269
+ xx2 = min(bi[2], bj[2])
270
+ yy2 = min(bi[3], bj[3])
271
+ inter = max(0.0, xx2 - xx1) * max(0.0, yy2 - yy1)
272
+ area_i = (bi[2] - bi[0]) * (bi[3] - bi[1])
273
+ area_j = (bj[2] - bj[0]) * (bj[3] - bj[1])
274
+ iou = inter / (area_i + area_j - inter + 1e-7)
275
+ if iou > iou_thresh:
276
+ suppressed[jdx] = True
277
+ return np.array(keep)
278
+
279
+ @staticmethod
280
+ def _max_score_per_cluster(
281
+ coords: np.ndarray,
282
+ scores: np.ndarray,
283
+ keep_indices: np.ndarray,
284
+ iou_thresh: float,
285
+ ) -> np.ndarray:
286
+ """
287
+ For each kept box, return the max original score among itself and any
288
+ box that overlaps it with IOU >= iou_thresh (so TTA cluster keeps best conf).
289
+ """
290
+ n_keep = len(keep_indices)
291
+ if n_keep == 0:
292
+ return np.array([], dtype=np.float32)
293
+ out = np.empty(n_keep, dtype=np.float32)
294
+ coords = np.asarray(coords, dtype=np.float32)
295
+ scores = np.asarray(scores, dtype=np.float32)
296
+ for i in range(n_keep):
297
+ idx = keep_indices[i]
298
+ bi = coords[idx]
299
+ xx1 = np.maximum(bi[0], coords[:, 0])
300
+ yy1 = np.maximum(bi[1], coords[:, 1])
301
+ xx2 = np.minimum(bi[2], coords[:, 2])
302
+ yy2 = np.minimum(bi[3], coords[:, 3])
303
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
304
+ area_i = (bi[2] - bi[0]) * (bi[3] - bi[1])
305
+ areas_j = (coords[:, 2] - coords[:, 0]) * (coords[:, 3] - coords[:, 1])
306
+ iou = inter / (area_i + areas_j - inter + 1e-7)
307
+ in_cluster = iou >= iou_thresh
308
+ out[i] = float(np.max(scores[in_cluster]))
309
+ return out
310
+
311
+ def _decode_final_dets(
312
+ self,
313
+ preds: np.ndarray,
314
+ ratio: float,
315
+ pad: tuple[float, float],
316
+ orig_size: tuple[int, int],
317
+ apply_optional_dedup: bool = False,
318
+ ) -> list[BoundingBox]:
319
+ """
320
+ Primary path:
321
+ expected output rows like [x1, y1, x2, y2, conf, cls_id]
322
+ in letterboxed input coordinates.
323
+ """
324
+ if preds.ndim == 3 and preds.shape[0] == 1:
325
+ preds = preds[0]
326
+
327
+ if preds.ndim != 2 or preds.shape[1] < 6:
328
+ raise ValueError(f"Unexpected ONNX final-det output shape: {preds.shape}")
329
+
330
+ boxes = preds[:, :4].astype(np.float32)
331
+ scores = preds[:, 4].astype(np.float32)
332
+ cls_ids = preds[:, 5].astype(np.int32)
333
+
334
+ keep = scores >= self.conf_thres
335
+ boxes = boxes[keep]
336
+ scores = scores[keep]
337
+ cls_ids = cls_ids[keep]
338
+
339
+ if len(boxes) == 0:
340
+ return []
341
+
342
+ pad_w, pad_h = pad
343
+ orig_w, orig_h = orig_size
344
+
345
+ # reverse letterbox
346
+ boxes[:, [0, 2]] -= pad_w
347
+ boxes[:, [1, 3]] -= pad_h
348
+ boxes /= ratio
349
+ boxes = self._clip_boxes(boxes, (orig_w, orig_h))
350
+
351
+ if apply_optional_dedup and len(boxes) > 1:
352
+ keep_idx, scores = self._soft_nms(boxes, scores)
353
+ boxes = boxes[keep_idx]
354
+ cls_ids = cls_ids[keep_idx]
355
+
356
+ results: list[BoundingBox] = []
357
+ for box, conf, cls_id in zip(boxes, scores, cls_ids):
358
+ x1, y1, x2, y2 = box.tolist()
359
+
360
+ if x2 <= x1 or y2 <= y1:
361
+ continue
362
+
363
+ results.append(
364
+ BoundingBox(
365
+ x1=int(math.floor(x1)),
366
+ y1=int(math.floor(y1)),
367
+ x2=int(math.ceil(x2)),
368
+ y2=int(math.ceil(y2)),
369
+ cls_id=int(cls_id),
370
+ conf=float(conf),
371
+ )
372
+ )
373
+
374
+ return results
375
+
376
+ def _decode_raw_yolo(
377
+ self,
378
+ preds: np.ndarray,
379
+ ratio: float,
380
+ pad: tuple[float, float],
381
+ orig_size: tuple[int, int],
382
+ ) -> list[BoundingBox]:
383
+ """
384
+ Fallback path for raw YOLO predictions.
385
+ Supports common layouts:
386
+ - [1, C, N]
387
+ - [1, N, C]
388
+ """
389
+ if preds.ndim != 3:
390
+ raise ValueError(f"Unexpected raw ONNX output shape: {preds.shape}")
391
+
392
+ if preds.shape[0] != 1:
393
+ raise ValueError(f"Unexpected batch dimension in raw output: {preds.shape}")
394
+
395
+ preds = preds[0]
396
+
397
+ # Normalize to [N, C]
398
+ if preds.shape[0] <= 16 and preds.shape[1] > preds.shape[0]:
399
+ preds = preds.T
400
+
401
+ if preds.ndim != 2 or preds.shape[1] < 5:
402
+ raise ValueError(f"Unexpected normalized raw output shape: {preds.shape}")
403
+
404
+ boxes_xywh = preds[:, :4].astype(np.float32)
405
+ cls_part = preds[:, 4:].astype(np.float32)
406
+
407
+ if cls_part.shape[1] == 1:
408
+ scores = cls_part[:, 0]
409
+ cls_ids = np.zeros(len(scores), dtype=np.int32)
410
+ else:
411
+ cls_ids = np.argmax(cls_part, axis=1).astype(np.int32)
412
+ scores = cls_part[np.arange(len(cls_part)), cls_ids]
413
+
414
+ keep = scores >= self.conf_thres
415
+ boxes_xywh = boxes_xywh[keep]
416
+ scores = scores[keep]
417
+ cls_ids = cls_ids[keep]
418
+
419
+ if len(boxes_xywh) == 0:
420
+ return []
421
+
422
+ boxes = self._xywh_to_xyxy(boxes_xywh)
423
+ keep_idx, scores = self._soft_nms(boxes, scores)
424
+ keep_idx = keep_idx[: self.max_det]
425
+ scores = scores[: self.max_det]
426
+
427
+ boxes = boxes[keep_idx]
428
+ cls_ids = cls_ids[keep_idx]
429
+
430
+ pad_w, pad_h = pad
431
+ orig_w, orig_h = orig_size
432
+
433
+ boxes[:, [0, 2]] -= pad_w
434
+ boxes[:, [1, 3]] -= pad_h
435
+ boxes /= ratio
436
+ boxes = self._clip_boxes(boxes, (orig_w, orig_h))
437
+
438
+ results: list[BoundingBox] = []
439
+ for box, conf, cls_id in zip(boxes, scores, cls_ids):
440
+ x1, y1, x2, y2 = box.tolist()
441
+
442
+ if x2 <= x1 or y2 <= y1:
443
+ continue
444
+
445
+ results.append(
446
+ BoundingBox(
447
+ x1=int(math.floor(x1)),
448
+ y1=int(math.floor(y1)),
449
+ x2=int(math.ceil(x2)),
450
+ y2=int(math.ceil(y2)),
451
+ cls_id=int(cls_id),
452
+ conf=float(conf),
453
+ )
454
+ )
455
+
456
+ return results
457
+
458
+ def _postprocess(
459
+ self,
460
+ output: np.ndarray,
461
+ ratio: float,
462
+ pad: tuple[float, float],
463
+ orig_size: tuple[int, int],
464
+ ) -> list[BoundingBox]:
465
+ """
466
+ Prefer final detections first.
467
+ Fallback to raw decode only if needed.
468
+ """
469
+ # final detections: [N,6]
470
+ if output.ndim == 2 and output.shape[1] >= 6:
471
+ return self._decode_final_dets(output, ratio, pad, orig_size)
472
+
473
+ # final detections: [1,N,6]
474
+ if output.ndim == 3 and output.shape[0] == 1 and output.shape[2] == 6:
475
+ return self._decode_final_dets(output, ratio, pad, orig_size)
476
+
477
+ # fallback raw decode
478
+ return self._decode_raw_yolo(output, ratio, pad, orig_size)
479
+
480
+ def _predict_single(self, image: np.ndarray) -> list[BoundingBox]:
481
+ if image is None:
482
+ raise ValueError("Input image is None")
483
+ if not isinstance(image, np.ndarray):
484
+ raise TypeError(f"Input is not numpy array: {type(image)}")
485
+ if image.ndim != 3:
486
+ raise ValueError(f"Expected HWC image, got shape={image.shape}")
487
+ if image.shape[0] <= 0 or image.shape[1] <= 0:
488
+ raise ValueError(f"Invalid image shape={image.shape}")
489
+ if image.shape[2] != 3:
490
+ raise ValueError(f"Expected 3 channels, got shape={image.shape}")
491
+
492
+ if image.dtype != np.uint8:
493
+ image = image.astype(np.uint8)
494
+
495
+ input_tensor, ratio, pad, orig_size = self._preprocess(image)
496
+
497
+ expected_shape = (1, 3, self.input_height, self.input_width)
498
+ if input_tensor.shape != expected_shape:
499
+ raise ValueError(
500
+ f"Bad input tensor shape={input_tensor.shape}, expected={expected_shape}"
501
+ )
502
+
503
+ outputs = self.session.run(self.output_names, {self.input_name: input_tensor})
504
+ det_output = outputs[0]
505
+ return self._postprocess(det_output, ratio, pad, orig_size)
506
+
507
+ def _predict_tta(self, image: np.ndarray) -> list[BoundingBox]:
508
+ """Horizontal-flip TTA: merge original + flipped via hard NMS."""
509
+ boxes_orig = self._predict_single(image)
510
+
511
+ flipped = cv2.flip(image, 1)
512
+ boxes_flip = self._predict_single(flipped)
513
+
514
+ w = image.shape[1]
515
+ boxes_flip = [
516
+ BoundingBox(
517
+ x1=w - b.x2, y1=b.y1, x2=w - b.x1, y2=b.y2,
518
+ cls_id=b.cls_id, conf=b.conf,
519
+ )
520
+ for b in boxes_flip
521
+ ]
522
+
523
+ all_boxes = boxes_orig + boxes_flip
524
+ if len(all_boxes) == 0:
525
+ return []
526
+
527
+ coords = np.array(
528
+ [[b.x1, b.y1, b.x2, b.y2] for b in all_boxes], dtype=np.float32
529
+ )
530
+ scores = np.array([b.conf for b in all_boxes], dtype=np.float32)
531
+
532
+ hard_keep = self._hard_nms(coords, scores, self.iou_thres)
533
+ if len(hard_keep) == 0:
534
+ return []
535
+
536
+ # _hard_nms already orders kept indices by descending score.
537
+ hard_keep = hard_keep[: self.max_det]
538
+
539
+ return [
540
+ BoundingBox(
541
+ x1=all_boxes[i].x1,
542
+ y1=all_boxes[i].y1,
543
+ x2=all_boxes[i].x2,
544
+ y2=all_boxes[i].y2,
545
+ cls_id=all_boxes[i].cls_id,
546
+ conf=float(scores[i]),
547
+ )
548
+ for i in hard_keep
549
+ ]
550
+
551
+ def predict_batch(
552
+ self,
553
+ batch_images: list[ndarray],
554
+ offset: int,
555
+ n_keypoints: int,
556
+ ) -> list[TVFrameResult]:
557
+ results: list[TVFrameResult] = []
558
+
559
+ for frame_number_in_batch, image in enumerate(batch_images):
560
+ try:
561
+ if self.use_tta:
562
+ boxes = self._predict_tta(image)
563
+ else:
564
+ boxes = self._predict_single(image)
565
+ except Exception as e:
566
+ print(f"⚠️ Inference failed for frame {offset + frame_number_in_batch}: {e}")
567
+ boxes = []
568
+
569
+ results.append(
570
+ TVFrameResult(
571
+ frame_id=offset + frame_number_in_batch,
572
+ boxes=boxes,
573
+ keypoints=[(0, 0) for _ in range(max(0, int(n_keypoints)))],
574
+ )
575
+ )
576
+
577
+ return results