BashirEmran commited on
Commit
dd8896d
·
verified ·
1 Parent(s): 2a93f53

scorevision: push artifact

Browse files
Files changed (1) hide show
  1. miner.py +196 -201
miner.py CHANGED
@@ -1,24 +1,4 @@
1
- """Turbo Vision miner for manak0/Detect-beverage-detect (cup / can / bottle).
2
-
3
- CPU-only ONNX inference with 2 intra-op threads (the compliance checker measures
4
- p95 latency on 2 vCPUs and re-runs the model to check that outputs are reproducible,
5
- so everything here is deterministic numpy / onnxruntime CPU).
6
-
7
- Repo layout:
8
- miner.py this file
9
- weights.onnx detector, input [1,3,S,S] RGB float 0..1, output [1, 4+3, N]
10
- (cx, cy, w, h in input pixels, then per-class sigmoid scores)
11
- config.json {"conf": [cup, can, bottle], "nms_iou": 0.5, "max_det": 100, "gate": 0.0, "rescue": [...],
12
- "esm": {"w": 3x3, "miss": 3x2, "draws": 256, "kmax": 24, "seed": 0}}
13
-
14
- Which boxes are sent: with an "esm" block in config.json, the boxes that maximise the EXPECTED validator score
15
- (class _Esm below; numbers fitted on our own model by tune_esm.py). Without it, per-class conf thresholds plus
16
- the first-box rescue. In both cases nothing is sent when the best candidate scores below "gate".
17
-
18
- No `from __future__ import annotations` here: pydantic must see real types when the
19
- chute imports this file dynamically.
20
- """
21
- import json
22
  from pathlib import Path
23
 
24
  import cv2
@@ -27,6 +7,25 @@ import onnxruntime as ort
27
  from numpy import ndarray
28
  from pydantic import BaseModel
29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
  class BoundingBox(BaseModel):
32
  x1: int
@@ -43,210 +42,206 @@ class TVFrameResult(BaseModel):
43
  keypoints: list[tuple[int, int]]
44
 
45
 
46
- def _nms(boxes: ndarray, scores: ndarray, iou: float) -> list[int]:
47
- order = np.argsort(-scores, kind="stable")
48
- keep: list[int] = []
49
- area = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])
50
- while order.size:
51
- i = int(order[0])
52
- keep.append(i)
53
- rest = order[1:]
54
- xx1 = np.maximum(boxes[i, 0], boxes[rest, 0])
55
- yy1 = np.maximum(boxes[i, 1], boxes[rest, 1])
56
- xx2 = np.minimum(boxes[i, 2], boxes[rest, 2])
57
- yy2 = np.minimum(boxes[i, 3], boxes[rest, 3])
58
- inter = np.maximum(0, xx2 - xx1) * np.maximum(0, yy2 - yy1)
59
- ov = inter / (area[i] + area[rest] - inter + 1e-7)
60
- order = rest[ov <= iou]
61
  return keep
62
 
63
 
64
- class _Esm:
65
- """Expected-score-maximising selection (same maths as esm_core.py, kept here so the repo is one file).
66
-
67
- The validator scores one image as max(0.6*map50 + 0.4*max(0, 1 - FP/10) - THETA, 0.01), map50 = mean AP over
68
- the classes that have ground truth. We do not know which candidates are right, so `draws` fixed scenarios are
69
- drawn: candidate j is right with probability P_j = sigmoid(w . [1, logit(conf), log10(area share) + 3]) and
70
- the class has Poisson(m0 + m1 * sum P) more objects that no candidate found. For "send the top k of each
71
- class" the formula is evaluated in every scenario and k is chosen by coordinate ascent on the average.
72
- The random numbers are fixed at start-up: the same image always gives the same boxes.
73
- """
74
- THETA = 0.362454704407324514
75
-
76
- def __init__(self, cfg: dict) -> None:
77
- self.w = np.array(cfg["w"], dtype=np.float64)
78
- self.miss = np.array(cfg["miss"], dtype=np.float64)
79
- self.draws = int(cfg.get("draws", 256))
80
- self.kmax = int(cfg.get("kmax", 24))
81
- rs = np.random.RandomState(int(cfg.get("seed", 0)))
82
- self.U = rs.random_sample((3, self.draws, self.kmax))
83
- self.UM = np.stack([(rs.permutation(self.draws) + 0.5) / self.draws for _ in range(3)])
84
- self.tri = np.triu(np.ones((self.kmax, self.kmax)))
85
- self.rank = np.arange(1, self.kmax + 1)
86
- self.logfact = np.concatenate([[0.0], np.cumsum(np.log(np.arange(1, 81)))])
87
- self.m = np.arange(81)
88
-
89
- def prob(self, cls: ndarray, conf: ndarray, area: ndarray) -> ndarray:
90
- c = np.clip(np.asarray(conf, dtype=np.float64), 1e-4, 1 - 1e-4)
91
- a = np.log10(np.maximum(np.asarray(area, dtype=np.float64), 1e-6)) + 3.0
92
- w = self.w[cls]
93
- return 1.0 / (1.0 + np.exp(-(w[:, 0] + w[:, 1] * np.log(c / (1 - c)) + w[:, 2] * a)))
94
-
95
- def select(self, plist: list) -> list:
96
- """plist: per class, P(right) of its candidates in sending order (at most kmax). Returns k per class."""
97
- S = self.draws
98
- ctps, aps, pres = [], [], np.zeros((S, 3), dtype=bool)
99
- for c, p in enumerate(plist):
100
- K = len(p)
101
- t = self.U[c, :, :K] < p[None, :]
102
- lam = max(float(self.miss[c, 0] + self.miss[c, 1] * p.sum()), 1e-3)
103
- cdf = np.cumsum(np.exp(-lam + self.m * np.log(lam) - self.logfact))
104
- n = t.sum(1) + np.minimum(np.searchsorted(cdf, self.UM[c], side="left"), 80)
105
- ctp = np.zeros((S, K + 1))
106
- ap = np.zeros((S, K + 1))
107
- if K:
108
- tf = t.astype(np.float64)
109
- cum = np.cumsum(tf, 1)
110
- ctp[:, 1:] = cum
111
- prec = cum / self.rank[:K]
112
- env = np.maximum.accumulate(prec[:, None, :] * self.tri[:K, :K], axis=2) # AP precision envelope
113
- ap[:, 1:] = np.einsum("sj,sjk->sk", tf, env) / np.maximum(n, 1)[:, None]
114
- ctps.append(ctp)
115
- aps.append(ap)
116
- pres[:, c] = n > 0
117
- npres = pres.sum(1)
118
- den = np.maximum(npres, 1)
119
- k = [int((p >= 0.5).sum()) for p in plist]
120
- for _ in range(4):
121
- changed = False
122
- for c in range(3):
123
- oth_ap = np.zeros(S)
124
- oth_fp = np.zeros(S)
125
- for d in range(3):
126
- if d != c:
127
- oth_ap += pres[:, d] * aps[d][:, k[d]]
128
- oth_fp += k[d] - ctps[d][:, k[d]]
129
- K = aps[c].shape[1] - 1
130
- apm = (oth_ap[:, None] + pres[:, c:c + 1] * aps[c]) / den[:, None]
131
- fp = oth_fp[:, None] + np.arange(K + 1)[None, :] - ctps[c]
132
- fps = np.maximum(0.0, 1.0 - fp / 10.0)
133
- tot = np.where(npres[:, None] > 0, 0.6 * apm + 0.4 * fps, fps)
134
- ev = np.maximum(tot - self.THETA, 0.01).mean(0)
135
- b = int(np.argmax(ev))
136
- if ev[b] > ev[k[c]] + 1e-12:
137
- k[c] = b
138
- changed = True
139
- if not changed:
140
- break
141
- return k
142
 
143
 
144
  class Miner:
145
  def __init__(self, path_hf_repo: Path) -> None:
146
- path_hf_repo = Path(path_hf_repo)
147
- cfg_path = path_hf_repo / "config.json"
148
- self.cfg = json.loads(cfg_path.read_text()) if cfg_path.exists() else {}
149
- self.conf = np.array(self.cfg.get("conf", [0.4, 0.4, 0.4]), dtype=np.float32)
150
- self.nms_iou = float(self.cfg.get("nms_iou", 0.5))
151
- self.max_det = int(self.cfg.get("max_det", 100))
152
- self.gate = float(self.cfg.get("gate", 0.0))
153
- # per class: if no box passes conf, keep the class's best candidate when it scores >= rescue
154
- # (1.0 = off). map50 averages over the classes in an image, so the first box of a class is worth most.
155
- self.rescue = np.array(self.cfg.get("rescue", [1.0, 1.0, 1.0]), dtype=np.float32)
156
- self.esm = _Esm(self.cfg["esm"]) if self.cfg.get("esm") else None
157
  so = ort.SessionOptions()
158
  so.intra_op_num_threads = 2
159
  so.inter_op_num_threads = 1
160
  so.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
161
  so.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
162
- self.session = ort.InferenceSession(str(path_hf_repo / "weights.onnx"), so, providers=["CPUExecutionProvider"])
 
 
163
  self.input_name = self.session.get_inputs()[0].name
164
  self.size = int(self.session.get_inputs()[0].shape[-1])
165
- self.buf = np.empty((1, 3, self.size, self.size), dtype=np.float32)
 
 
166
  cv2.setNumThreads(1)
167
- warm = np.zeros((1024, 1024, 3), dtype=np.uint8)
168
- for _ in range(2):
169
- self._raw(warm)
170
 
171
  def __repr__(self) -> str:
172
- return f"ONNX P3 detector {self.size}px conf={self.conf.tolist()}"
173
 
174
- def _raw(self, image: ndarray):
175
- """letterbox -> ONNX -> (boxes xyxy in original pixels, per-class scores [N,3])"""
176
  h, w = image.shape[:2]
177
  s = self.size
178
- r = min(s / h, s / w)
179
- nw, nh = int(round(w * r)), int(round(h * r))
180
- top, left = (s - nh) // 2, (s - nw) // 2
181
- img = cv2.resize(image, (nw, nh), interpolation=cv2.INTER_LINEAR) if (nw, nh) != (w, h) else image
182
- self.buf.fill(114 / 255)
 
 
 
183
  k = np.float32(1 / 255)
184
- for c in range(3): # BGR -> RGB, HWC -> CHW, 0..1
185
- np.multiply(img[:, :, 2 - c], k, out=self.buf[0, c, top:top + nh, left:left + nw], dtype=np.float32)
186
- out = self.session.run(None, {self.input_name: self.buf})[0][0].T # [N, 4+nc]
187
- xy, wh, sc = out[:, :2], out[:, 2:4], out[:, 4:]
188
- boxes = np.concatenate([xy - wh / 2, xy + wh / 2], 1)
189
- boxes[:, [0, 2]] = (boxes[:, [0, 2]] - left) / r
190
- boxes[:, [1, 3]] = (boxes[:, [1, 3]] - top) / r
191
- boxes[:, [0, 2]] = boxes[:, [0, 2]].clip(0, w - 1)
192
- boxes[:, [1, 3]] = boxes[:, [1, 3]].clip(0, h - 1)
193
- return boxes, sc
194
-
195
- def candidates(self, image: ndarray, floor: float = 0.05):
196
- """All per-class NMS survivors above `floor` (used for threshold tuning)."""
197
- boxes, sc = self._raw(image)
198
- cls = sc.argmax(1)
199
- conf = sc[np.arange(len(sc)), cls]
200
- m = conf >= floor
201
- boxes, conf, cls = boxes[m], conf[m], cls[m]
202
- keep: list[int] = []
203
- for c in range(sc.shape[1]):
204
- idx = np.flatnonzero(cls == c)
205
- if idx.size:
206
- keep.extend(idx[_nms(boxes[idx], conf[idx], self.nms_iou)].tolist())
207
- keep = sorted(keep, key=lambda i: -conf[i])
208
- return boxes[keep], conf[keep], cls[keep]
209
-
210
- def _detect_esm(self, image: ndarray) -> list[BoundingBox]:
211
- boxes, conf, cls = self.candidates(image, floor=0.05)
212
- q = np.round(boxes).astype(int)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
  ok = (q[:, 2] > q[:, 0]) & (q[:, 3] > q[:, 1])
214
- q, conf, cls = q[ok], conf[ok].astype(np.float64), cls[ok]
215
- if not len(q) or float(conf.max()) < self.gate:
216
- return [] # image-level gate: on an image without objects every box costs 0.1 (E004)
217
- h, w = image.shape[:2]
218
- p = self.esm.prob(cls, conf, (q[:, 2] - q[:, 0]) * (q[:, 3] - q[:, 1]) / float(h * w))
219
- idxs = [np.flatnonzero(cls == c)[: self.esm.kmax] for c in range(3)] # candidates are sorted by score
220
- k = self.esm.select([p[i] for i in idxs])
221
- out = [(q[i], c, conf[i]) for c in range(3) for i in idxs[c][: k[c]]][: self.max_det]
222
- return [BoundingBox(x1=int(a[0]), y1=int(a[1]), x2=int(a[2]), y2=int(a[3]), cls_id=int(c), conf=float(f))
223
- for a, c, f in out]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
 
225
  def _detect(self, image: ndarray) -> list[BoundingBox]:
226
- if self.esm is not None:
227
- return self._detect_esm(image)
228
- boxes, conf, cls = self.candidates(image, floor=float(min(self.conf.min(), self.rescue.min(), 0.05)))
229
- if conf.size == 0 or float(conf.max()) < self.gate:
230
  return []
231
- m = conf >= self.conf[cls]
232
- for c in range(len(self.rescue)):
233
- if self.rescue[c] < 1.0 and not m[cls == c].any():
234
- idx = np.flatnonzero((cls == c) & (conf >= self.rescue[c]))
235
- if idx.size:
236
- m[idx[0]] = True # candidates are sorted by score, so idx[0] is the class's best
237
- boxes, conf, cls = boxes[m][: self.max_det], conf[m][: self.max_det], cls[m][: self.max_det]
238
- q = np.round(boxes).astype(int)
239
- ok = (q[:, 2] > q[:, 0]) & (q[:, 3] > q[:, 1])
240
- return [BoundingBox(x1=int(a[0]), y1=int(a[1]), x2=int(a[2]), y2=int(a[3]), cls_id=int(c), conf=float(f))
241
- for a, c, f in zip(q[ok], cls[ok], conf[ok])]
242
 
243
  def predict_batch(self, batch_images: list[ndarray], offset: int, n_keypoints: int) -> list[TVFrameResult]:
244
- results = []
245
- for i, im in enumerate(batch_images):
246
- try:
247
- boxes = self._detect(im)
248
- except Exception as e: # one bad frame must not fail the batch
249
- print(f"frame {offset + i} failed: {e}")
250
- boxes = []
251
- results.append(TVFrameResult(frame_id=offset + i, boxes=boxes, keypoints=[(0, 0)] * n_keypoints))
252
- return results
 
1
+ import math
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  from pathlib import Path
3
 
4
  import cv2
 
7
  from numpy import ndarray
8
  from pydantic import BaseModel
9
 
10
+ # candidates: image gate, confidence floor, per-class NMS, cross-class dedup
11
+ CONF = np.array((0.425, 0.52, 0.40), dtype=np.float32)
12
+ FLOOR = 0.2
13
+ GATE = 0.6
14
+ NMS_IOU = 0.45
15
+ DEDUP_IOU = 0.9
16
+ PRE_TOPK = 1000
17
+ MAX_DET = 300
18
+ # selection: per class keep the top-k by conf, k chosen to maximise a Monte Carlo estimate of the expected validator score
19
+ NMAX = 32
20
+ NS = 256
21
+ SEED = 1234567
22
+ THETA = 0.3624547044073245
23
+ SHIFT = -1.0 # logit offset added to every P(TP)
24
+ # P(TP) = sigmoid(a + b*logit(conf) + c*log10(area/1024^2) + d*logit*log10area), per class cup/can/bottle
25
+ CAL = np.array([[-1.985495, 0.07277, -1.153825, -0.585014], [-0.705046, 3.412035, -0.543796, 0.383031], [-1.778816, 2.69706, -1.218205, 0.197397]])
26
+ # objects the candidates miss ~ Poisson(a + b * sum P(TP)), per class
27
+ MISS = np.array([[1.942812, 0.229558], [0.552509, 0.193124], [1.384334, 0.53347]])
28
+
29
 
30
  class BoundingBox(BaseModel):
31
  x1: int
 
42
  keypoints: list[tuple[int, int]]
43
 
44
 
45
+ def _iou(b: ndarray) -> ndarray:
46
+ area = np.maximum(0, b[:, 2] - b[:, 0]) * np.maximum(0, b[:, 3] - b[:, 1])
47
+ iw = np.maximum(0, np.minimum(b[:, None, 2], b[None, :, 2]) - np.maximum(b[:, None, 0], b[None, :, 0]))
48
+ ih = np.maximum(0, np.minimum(b[:, None, 3], b[None, :, 3]) - np.maximum(b[:, None, 1], b[None, :, 1]))
49
+ inter = iw * ih
50
+ return inter / (area[:, None] + area[None, :] - inter + 1e-7)
51
+
52
+
53
+ def _greedy(over: ndarray, order: ndarray) -> list[int]:
54
+ gone = np.zeros(len(order), bool)
55
+ keep = []
56
+ for i in order:
57
+ if not gone[i]:
58
+ keep.append(int(i))
59
+ gone |= over[i]
60
  return keep
61
 
62
 
63
+ def _nms(b: ndarray, s: ndarray, iou: float) -> list[int]:
64
+ order = np.argsort(-s, kind="stable")
65
+ over = _iou(b) > iou
66
+ if not over.sum() > len(b): # only the diagonal overlaps: nothing to suppress
67
+ return order.tolist()
68
+ return _greedy(over, order)
69
+
70
+
71
+ def _splitmix(seed: int, n: int) -> ndarray:
72
+ z = np.arange(1, n + 1, dtype=np.uint64) * np.uint64(0x9E3779B97F4A7C15) + np.uint64(seed)
73
+ z = (z ^ (z >> np.uint64(30))) * np.uint64(0xBF58476D1CE4E5B9)
74
+ z = (z ^ (z >> np.uint64(27))) * np.uint64(0x94D049BB133111EB)
75
+ z = z ^ (z >> np.uint64(31))
76
+ return (z >> np.uint64(11)).astype(np.float64) / 2.0 ** 53
77
+
78
+
79
+ def _stratified(seed: int, shape: tuple[int, ...]) -> ndarray:
80
+ """Latin-hypercube uniforms along the last axis: one draw per stratum."""
81
+ n = math.prod(shape)
82
+ perm = np.argsort(_splitmix(seed, n).reshape(shape), axis=-1, kind="stable")
83
+ return (perm + _splitmix(seed + 1, n).reshape(shape)) / shape[-1]
84
+
85
+
86
+ _LGF = np.array([math.lgamma(k + 1) for k in range(64)])
87
+
88
+
89
+ def _poisson(lam: float, u: ndarray) -> ndarray:
90
+ k = np.arange(64)
91
+ cdf = np.cumsum(np.exp(-lam + k * math.log(max(lam, 1e-12)) - _LGF))
92
+ return np.minimum(np.searchsorted(cdf, u), 63)
93
+
94
+
95
+ def _ap_paths(t: ndarray) -> ndarray:
96
+ """Sum of precision at each TP after keeping the top 0..n boxes, per Monte Carlo draw."""
97
+ m, n = t.shape
98
+ out = np.zeros((m, n + 1))
99
+ if n:
100
+ out[:, 1:] = np.cumsum(t * (np.cumsum(t, 1) / np.arange(1, n + 1)), 1)
101
+ return out
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
 
103
 
104
  class Miner:
105
  def __init__(self, path_hf_repo: Path) -> None:
 
 
 
 
 
 
 
 
 
 
 
106
  so = ort.SessionOptions()
107
  so.intra_op_num_threads = 2
108
  so.inter_op_num_threads = 1
109
  so.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
110
  so.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
111
+ so.add_session_config_entry("session.intra_op.allow_spinning", "1")
112
+ so.add_session_config_entry("session.inter_op.allow_spinning", "1")
113
+ self.session = ort.InferenceSession(str(Path(path_hf_repo) / "weights.onnx"), so, providers=["CPUExecutionProvider"])
114
  self.input_name = self.session.get_inputs()[0].name
115
  self.size = int(self.session.get_inputs()[0].shape[-1])
116
+ self.buf = np.full((1, 3, self.size, self.size), 114 / 255, dtype=np.float32)
117
+ self.u = np.ascontiguousarray(_stratified(SEED, (3, NMAX, NS)).transpose(0, 2, 1)) # [class, draw, rank]
118
+ self.v = _stratified(SEED + 7919, (3, NS)) # [class, draw]
119
  cv2.setNumThreads(1)
 
 
 
120
 
121
  def __repr__(self) -> str:
122
+ return f"ONNX {self.size}"
123
 
124
+ def _infer(self, image: ndarray) -> tuple[ndarray, tuple[float, float, float, int, int]]:
 
125
  h, w = image.shape[:2]
126
  s = self.size
127
+ scale = min(s / h, s / w)
128
+ nw, nh = round(w * scale), round(h * scale)
129
+ dx, dy = (s - nw) / 2, (s - nh) / 2
130
+ top, left = round(dy - 0.1), round(dx - 0.1)
131
+ r = cv2.resize(image, (nw, nh)) if (nw, nh) != (w, h) else image
132
+ inp = self.buf
133
+ if nw != s or nh != s:
134
+ inp.fill(114 / 255)
135
  k = np.float32(1 / 255)
136
+ for c in range(3): # BGR → RGB, HWC → CHW, /255, straight into the reused input buffer
137
+ np.multiply(r[:, :, 2 - c], k, out=inp[0, c, top:top + nh, left:left + nw], dtype=np.float32)
138
+ return self.session.run(None, {self.input_name: inp})[0][0].T, (scale, dx, dy, w, h)
139
+
140
+ def _candidates(self, raw: ndarray, meta: tuple[float, float, float, int, int]):
141
+ scale, dx, dy, w, h = meta
142
+ conf = raw[:, 4:].max(1)
143
+ cls = raw[:, 4:].argmax(1)
144
+ if not len(conf) or float(conf.max()) < GATE:
145
+ return None
146
+ keep = conf >= FLOOR
147
+ raw, conf, cls = raw[keep], conf[keep], cls[keep]
148
+ if not len(raw):
149
+ return None
150
+ b = np.stack([raw[:, 0] - raw[:, 2] / 2, raw[:, 1] - raw[:, 3] / 2, raw[:, 0] + raw[:, 2] / 2, raw[:, 1] + raw[:, 3] / 2], 1)
151
+ b[:, [0, 2]] = np.clip((b[:, [0, 2]] - dx) / scale, 0, w - 1)
152
+ b[:, [1, 3]] = np.clip((b[:, [1, 3]] - dy) / scale, 0, h - 1)
153
+ bw, bh = np.maximum(0, b[:, 2] - b[:, 0]), np.maximum(0, b[:, 3] - b[:, 1])
154
+ ar = np.maximum(bw / np.maximum(bh, 1e-6), bh / np.maximum(bw, 1e-6))
155
+ ok = (bw >= 3) & (bh >= 3) & (bw * bh >= 8) & (bw * bh <= 0.95 * w * h) & (ar <= 12)
156
+ b, conf, cls = b[ok], conf[ok], cls[ok]
157
+ if not len(conf):
158
+ return None
159
+ if len(conf) > PRE_TOPK:
160
+ t = np.argpartition(-conf, PRE_TOPK)[:PRE_TOPK]
161
+ b, conf, cls = b[t], conf[t], cls[t]
162
+ sel = sorted(j for c in range(len(CONF)) for j in np.flatnonzero(cls == c)[_nms(b[cls == c], conf[cls == c], NMS_IOU)])
163
+ b, conf, cls = b[sel], conf[sel], cls[sel]
164
+ if len(conf) > MAX_DET:
165
+ t = np.argsort(-conf)[:MAX_DET]
166
+ b, conf, cls = b[t], conf[t], cls[t]
167
+ if len(b) > 1:
168
+ iw = np.maximum(0, np.minimum(b[:, None, 2], b[None, :, 2]) - np.maximum(b[:, None, 0], b[None, :, 0]))
169
+ ih = np.maximum(0, np.minimum(b[:, None, 3], b[None, :, 3]) - np.maximum(b[:, None, 1], b[None, :, 1]))
170
+ a_ = np.maximum(0, b[:, 2] - b[:, 0]) * np.maximum(0, b[:, 3] - b[:, 1])
171
+ inside = iw * ih / (np.minimum(a_[:, None], a_[None, :]) + 1e-7) # share of the smaller box inside the other
172
+ over = (_iou(b) > DEDUP_IOU) | (inside >= 0.85)
173
+ np.fill_diagonal(over, False)
174
+ area = (b[:, 2] - b[:, 0]) * (b[:, 3] - b[:, 1])
175
+ order = np.lexsort((-area, -(conf - CONF[cls])))
176
+ kept = sorted(_greedy(over, order)) if over.any() else list(range(len(b)))
177
+ b, conf, cls = b[kept], conf[kept], cls[kept]
178
+ q = np.stack([np.floor(b[:, 0]), np.floor(b[:, 1]), np.ceil(b[:, 2]), np.ceil(b[:, 3])], 1)
179
+ q[:, [0, 2]] = np.clip(q[:, [0, 2]], 0, w)
180
+ q[:, [1, 3]] = np.clip(q[:, [1, 3]], 0, h)
181
  ok = (q[:, 2] > q[:, 0]) & (q[:, 3] > q[:, 1])
182
+ return q[ok].astype(int), conf[ok], cls[ok]
183
+
184
+ def _choose(self, q: ndarray, conf: ndarray, cls: ndarray) -> ndarray:
185
+ ap, fp, ngt, idx = [], [], [], []
186
+ for c in range(3):
187
+ i = np.flatnonzero(cls == c)
188
+ i = i[np.argsort(-conf[i], kind="stable")][:NMAX]
189
+ idx.append(i)
190
+ s = np.clip(conf[i].astype(np.float64), 1e-4, 1 - 1e-4)
191
+ lg = np.log(s / (1 - s))
192
+ la = np.log10(np.clip((q[i, 2] - q[i, 0]) * (q[i, 3] - q[i, 1]) / (1024 * 1024), 1e-6, 1))
193
+ p = 1 / (1 + np.exp(-(CAL[c, 0] + CAL[c, 1] * lg + CAL[c, 2] * la + CAL[c, 3] * lg * la + SHIFT)))
194
+ t = self.u[c][:, :len(i)] < p[None, :] # [draw, rank]: is the box a TP in this draw
195
+ ap.append(_ap_paths(t))
196
+ fp.append(np.arange(len(i) + 1)[None, :] - np.concatenate([np.zeros((NS, 1)), np.cumsum(t, 1)], 1))
197
+ ngt.append(t.sum(1) + _poisson(max(MISS[c, 0] + MISS[c, 1] * float(p.sum()), 0.0), self.v[c]))
198
+ ngt = np.stack(ngt, 1)
199
+ present = ngt > 0
200
+ n_present = np.maximum(present.sum(1), 1)
201
+ empty = present.sum(1) == 0
202
+ part = [np.where(present[:, c, None], ap[c] / np.maximum(ngt[:, c, None], 1), 0.0) for c in range(3)]
203
+ k = [0, 0, 0]
204
+ a_tot = sum(part[c][:, 0] for c in range(3))
205
+ f_tot = sum(fp[c][:, 0] for c in range(3))
206
+
207
+ def value(c: int) -> ndarray: # expected max(score - THETA, .01) for every k of class c, others fixed
208
+ a = (a_tot - part[c][:, k[c]])[:, None] + part[c]
209
+ f = (f_tot - fp[c][:, k[c]])[:, None] + fp[c]
210
+ n = sum(k) - k[c] + np.arange(len(idx[c]) + 1)
211
+ pos = np.maximum(0.6 * a / n_present[:, None] + 0.4 * np.maximum(0.0, 1 - f / 10) - THETA, 0.01)
212
+ neg = np.maximum(np.maximum(0.0, 1 - n / 10) - THETA, 0.01)
213
+ return np.where(empty[:, None], neg[None, :], pos).mean(0)
214
+
215
+ best = value(0)[0]
216
+ for _ in range(3): # coordinate ascent over the per-class counts
217
+ moved = False
218
+ for c in range(3):
219
+ v = value(c)
220
+ j = int(np.argmax(v))
221
+ if v[j] > best + 1e-9:
222
+ a_tot += part[c][:, j] - part[c][:, k[c]]
223
+ f_tot += fp[c][:, j] - fp[c][:, k[c]]
224
+ best, k[c], moved = float(v[j]), j, True
225
+ if not moved:
226
+ break
227
+ return np.concatenate([idx[c][:k[c]] for c in range(3)]).astype(int)
228
+
229
+ def _select(self, raw: ndarray, meta: tuple[float, float, float, int, int]) -> list[BoundingBox]:
230
+ got = self._candidates(raw, meta)
231
+ if got is None:
232
+ return []
233
+ q, conf, cls = got
234
+ sel = self._choose(q, conf, cls)
235
+ return [BoundingBox(x1=int(q[i, 0]), y1=int(q[i, 1]), x2=int(q[i, 2]), y2=int(q[i, 3]), cls_id=int(cls[i]),
236
+ conf=float(min(1.0, max(0.0, conf[i])))) for i in sorted(sel.tolist(), key=lambda i: -conf[i])]
237
 
238
  def _detect(self, image: ndarray) -> list[BoundingBox]:
239
+ try:
240
+ return self._select(*self._infer(image))
241
+ except Exception as e: # one bad frame must not fail the whole batch
242
+ print(f"frame failed: {e}")
243
  return []
 
 
 
 
 
 
 
 
 
 
 
244
 
245
  def predict_batch(self, batch_images: list[ndarray], offset: int, n_keypoints: int) -> list[TVFrameResult]:
246
+ return [TVFrameResult(frame_id=offset + i, boxes=self._detect(im), keypoints=[(0, 0)] * n_keypoints)
247
+ for i, im in enumerate(batch_images)]