trackflow-python 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
trackflow/reid.py ADDED
@@ -0,0 +1,417 @@
1
+ """Vision-language Re-ID, Track Cards, cross-exit identity merging, and natural-language search."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+ from typing import Any, Literal
8
+
9
+ import cv2
10
+ import numpy as np
11
+ from tokenizers import Tokenizer
12
+
13
+ from trackflow.detector import create_onnx_session
14
+ from trackflow.models import Precision, resolve_reid_artifacts
15
+ from trackflow.types import Track, TrackCard
16
+
17
+ ReidBackend = Literal["none", "color", "clip", "siglip"]
18
+
19
+
20
+ def _l2_normalize(vec: np.ndarray) -> np.ndarray:
21
+ arr = np.asarray(vec, dtype=np.float32).reshape(-1)
22
+ norm = float(np.linalg.norm(arr))
23
+ if norm <= 1e-8:
24
+ return arr
25
+ return arr / norm
26
+
27
+
28
+ def _crop_bbox(frame_bgr: np.ndarray, bbox: tuple[float, float, float, float]) -> np.ndarray | None:
29
+ h, w = frame_bgr.shape[:2]
30
+ x1 = max(0, min(w - 1, int(round(bbox[0]))))
31
+ y1 = max(0, min(h - 1, int(round(bbox[1]))))
32
+ x2 = max(x1 + 1, min(w, int(round(bbox[2]))))
33
+ y2 = max(y1 + 1, min(h, int(round(bbox[3]))))
34
+ if x2 - x1 < 4 or y2 - y1 < 4:
35
+ return None
36
+ return frame_bgr[y1:y2, x1:x2]
37
+
38
+
39
+ def _color_spatial_embedding(crop_bgr: np.ndarray) -> np.ndarray:
40
+ """Fast 96-dim spatial upper/lower-body HSV color descriptor (zero external weights)."""
41
+ resized = cv2.resize(crop_bgr, (48, 96), interpolation=cv2.INTER_AREA)
42
+ hsv = cv2.cvtColor(resized, cv2.COLOR_BGR2HSV)
43
+ parts = [hsv[:48, :, :], hsv[48:, :, :]] # upper body + lower body
44
+ feats: list[np.ndarray] = []
45
+ for part in parts:
46
+ h_hist = cv2.calcHist([part], [0], None, [24], [0, 180]).ravel()
47
+ s_hist = cv2.calcHist([part], [1], None, [12], [0, 256]).ravel()
48
+ v_hist = cv2.calcHist([part], [2], None, [12], [0, 256]).ravel()
49
+ feats.extend([h_hist, s_hist, v_hist])
50
+ return _l2_normalize(np.concatenate(feats).astype(np.float32))
51
+
52
+
53
+ class AppearanceEmbedder:
54
+ """Appearance and vision-language embedder supporting CLIP, SigLIP (ONNX), and fast Color."""
55
+
56
+ def __init__(
57
+ self,
58
+ backend: ReidBackend = "clip",
59
+ *,
60
+ precision: Precision = "int8",
61
+ device: str = "auto",
62
+ cache_dir: str | Path | None = None,
63
+ ) -> None:
64
+ self.backend: ReidBackend = backend
65
+ self.precision = precision
66
+ self._vision_sess = None
67
+ self._text_sess = None
68
+ self._tokenizer: Tokenizer | None = None
69
+ self._image_size = (224, 224)
70
+ self._mean = np.array([0.5, 0.5, 0.5], dtype=np.float32).reshape(3, 1, 1)
71
+ self._std = np.array([0.5, 0.5, 0.5], dtype=np.float32).reshape(3, 1, 1)
72
+ self._max_length = 77 if backend == "clip" else 64
73
+ self._text_cache: dict[str, np.ndarray] = {}
74
+
75
+ if backend in ("clip", "siglip"):
76
+ artifacts = resolve_reid_artifacts(
77
+ backend=backend, precision=precision, cache_dir=cache_dir
78
+ )
79
+ eff_dev = "cpu" if (device == "auto" and precision == "int8") else device
80
+ self._vision_sess, _ = create_onnx_session(artifacts["vision_onnx"], device=eff_dev)
81
+ self._text_sess, _ = create_onnx_session(artifacts["text_onnx"], device=eff_dev)
82
+ self._tokenizer = Tokenizer.from_file(str(artifacts["tokenizer"]))
83
+ self._load_preprocess(artifacts["preprocessor"], artifacts["config"])
84
+
85
+ @property
86
+ def supports_text(self) -> bool:
87
+ return self._text_sess is not None and self._tokenizer is not None
88
+
89
+ def _load_preprocess(self, prep_path: Path, config_path: Path) -> None:
90
+ if prep_path.is_file():
91
+ cfg = json.loads(prep_path.read_text(encoding="utf-8"))
92
+ size = cfg.get("crop_size") or cfg.get("size") or {}
93
+ if isinstance(size, int):
94
+ self._image_size = (size, size)
95
+ elif isinstance(size, dict):
96
+ h = int(size.get("height", size.get("shortest_edge", 224)))
97
+ w = int(size.get("width", size.get("shortest_edge", 224)))
98
+ self._image_size = (h, w)
99
+ if "image_mean" in cfg:
100
+ self._mean = np.array(cfg["image_mean"], dtype=np.float32).reshape(3, 1, 1)
101
+ if "image_std" in cfg:
102
+ self._std = np.array(cfg["image_std"], dtype=np.float32).reshape(3, 1, 1)
103
+
104
+ if config_path.is_file():
105
+ mcfg = json.loads(config_path.read_text(encoding="utf-8"))
106
+ tcfg = mcfg.get("text_config", {})
107
+ if isinstance(tcfg, dict) and "max_position_embeddings" in tcfg:
108
+ self._max_length = int(tcfg["max_position_embeddings"])
109
+
110
+ def _preprocess_crop(self, crop_bgr: np.ndarray) -> np.ndarray:
111
+ th, tw = self._image_size
112
+ rgb = cv2.cvtColor(crop_bgr, cv2.COLOR_BGR2RGB)
113
+ resized = cv2.resize(rgb, (tw, th), interpolation=cv2.INTER_CUBIC)
114
+ arr = resized.astype(np.float32) * (1.0 / 255.0)
115
+ chw = np.transpose(arr, (2, 0, 1))
116
+ chw = (chw - self._mean) / self._std
117
+ return np.expand_dims(chw, axis=0).astype(np.float32)
118
+
119
+ def encode_image(self, crop_bgr: np.ndarray | None) -> np.ndarray | None:
120
+ """Encode a BGR person/object crop into an L2-normalized embedding vector."""
121
+ if crop_bgr is None or crop_bgr.size == 0 or self.backend == "none":
122
+ return None
123
+ if self.backend == "color":
124
+ return _color_spatial_embedding(crop_bgr)
125
+
126
+ assert self._vision_sess is not None
127
+ inp = self._vision_sess.get_inputs()[0]
128
+ tensor = self._preprocess_crop(crop_bgr)
129
+ if "float16" in inp.type:
130
+ tensor = tensor.astype(np.float16)
131
+
132
+ outputs = self._vision_sess.run(None, {inp.name: tensor})
133
+ out_names = [o.name for o in self._vision_sess.get_outputs()]
134
+ by_name = dict(zip(out_names, outputs, strict=False))
135
+ emb = by_name.get("image_embeds")
136
+ if emb is None:
137
+ emb = by_name.get("pooler_output", outputs[0])
138
+ emb_arr = np.asarray(emb, dtype=np.float32)
139
+ if emb_arr.ndim == 3:
140
+ emb_arr = emb_arr[:, 0, :]
141
+ return _l2_normalize(emb_arr[0])
142
+
143
+ def encode_text(self, query: str) -> np.ndarray:
144
+ """Encode a natural-language query into the shared vision-language embedding space."""
145
+ cleaned = query.strip()
146
+ if cleaned in self._text_cache:
147
+ return self._text_cache[cleaned]
148
+ if not self.supports_text:
149
+ raise RuntimeError(
150
+ f"Backend '{self.backend}' does not support natural-language text queries. "
151
+ "Use --reid clip or --reid siglip."
152
+ )
153
+
154
+ assert self._tokenizer is not None and self._text_sess is not None
155
+ self._tokenizer.enable_truncation(max_length=self._max_length)
156
+ if self.backend == "siglip":
157
+ self._tokenizer.enable_padding(length=self._max_length, pad_id=1)
158
+ else:
159
+ self._tokenizer.no_padding()
160
+
161
+ enc = self._tokenizer.encode(cleaned)
162
+ input_ids = np.array([enc.ids], dtype=np.int64)
163
+ attention_mask = np.array([enc.attention_mask], dtype=np.int64)
164
+
165
+ feed: dict[str, np.ndarray] = {}
166
+ for inp in self._text_sess.get_inputs():
167
+ if inp.name == "input_ids":
168
+ feed[inp.name] = input_ids
169
+ elif inp.name == "attention_mask":
170
+ feed[inp.name] = attention_mask
171
+
172
+ outputs = self._text_sess.run(None, feed)
173
+ out_names = [o.name for o in self._text_sess.get_outputs()]
174
+ by_name = dict(zip(out_names, outputs, strict=False))
175
+ emb = by_name.get("text_embeds")
176
+ if emb is None:
177
+ emb = by_name.get("pooler_output", outputs[0])
178
+ emb_arr = np.asarray(emb, dtype=np.float32)
179
+ if emb_arr.ndim == 3:
180
+ emb_arr = emb_arr[:, 0, :]
181
+ vec = _l2_normalize(emb_arr[0])
182
+ self._text_cache[cleaned] = vec
183
+ return vec
184
+
185
+ @staticmethod
186
+ def cosine_similarity(a: np.ndarray, b: np.ndarray) -> float:
187
+ na = _l2_normalize(a)
188
+ nb = _l2_normalize(b)
189
+ if na.shape != nb.shape:
190
+ return 0.0
191
+ return float(np.dot(na, nb))
192
+
193
+
194
+ class TrackCardIndex:
195
+ """Maintains persistent Track Cards, cross-exit long-term Re-ID merges, and NL query scores."""
196
+
197
+ def __init__(
198
+ self,
199
+ *,
200
+ embedder: AppearanceEmbedder | None = None,
201
+ query: str | None = None,
202
+ query_threshold: float = 0.22,
203
+ reid_merge_threshold: float = 0.82,
204
+ min_exit_gap_frames: int = 8,
205
+ embed_every_n_frames: int = 5,
206
+ crops_dir: Path | None = None,
207
+ ) -> None:
208
+ self.embedder = embedder
209
+ self.query = query.strip() if query else None
210
+ self.query_threshold = float(query_threshold)
211
+ self.reid_merge_threshold = float(reid_merge_threshold)
212
+ self.min_exit_gap_frames = int(min_exit_gap_frames)
213
+ self.embed_every_n_frames = max(1, int(embed_every_n_frames))
214
+ self.crops_dir = crops_dir
215
+
216
+ self._query_vec: np.ndarray | None = None
217
+ if self.query and self.embedder is not None and self.embedder.supports_text:
218
+ self._query_vec = self.embedder.encode_text(self.query)
219
+
220
+ self.cards: dict[int, TrackCard] = {}
221
+ self._embeddings: dict[int, np.ndarray] = {}
222
+ self._id_alias: dict[int, int] = {} # raw_track_id -> canonical_track_id
223
+ self.reid_merges: int = 0
224
+
225
+ def canonical_id(self, raw_track_id: int) -> int:
226
+ return self._id_alias.get(raw_track_id, raw_track_id)
227
+
228
+ def _try_cross_exit_merge(
229
+ self,
230
+ raw_track_id: int,
231
+ class_name: str,
232
+ frame_idx: int,
233
+ emb: np.ndarray | None,
234
+ ) -> int:
235
+ """Match a newly spawned track against previously exited Track Cards by appearance."""
236
+ if emb is None or raw_track_id in self._id_alias:
237
+ return self.canonical_id(raw_track_id)
238
+
239
+ best_cid: int | None = None
240
+ best_sim = self.reid_merge_threshold
241
+
242
+ for cid, card in self.cards.items():
243
+ if card.class_name != class_name:
244
+ continue
245
+ if frame_idx - card.last_frame < self.min_exit_gap_frames:
246
+ continue
247
+ other_emb = self._embeddings.get(cid)
248
+ if other_emb is None:
249
+ continue
250
+ sim = AppearanceEmbedder.cosine_similarity(emb, other_emb)
251
+ if sim > best_sim:
252
+ best_sim = sim
253
+ best_cid = cid
254
+
255
+ if best_cid is not None:
256
+ self._id_alias[raw_track_id] = best_cid
257
+ if raw_track_id not in self.cards[best_cid].merged_track_ids:
258
+ self.cards[best_cid].merged_track_ids.append(raw_track_id)
259
+ self.reid_merges += 1
260
+ return best_cid
261
+
262
+ self._id_alias[raw_track_id] = raw_track_id
263
+ return raw_track_id
264
+
265
+ def update(
266
+ self,
267
+ frame_idx: int,
268
+ timestamp_s: float,
269
+ frame_bgr: np.ndarray,
270
+ tracks: list[Track],
271
+ frame_dt_s: float = 0.0,
272
+ ) -> list[dict[str, Any]]:
273
+ """Update Track Cards, perform cross-exit Re-ID merges, and score NL queries."""
274
+ events: list[dict[str, Any]] = []
275
+
276
+ for tr in tracks:
277
+ raw_id = tr.track_id
278
+ is_new_raw = raw_id not in self._id_alias
279
+
280
+ # Compute embedding when track is new or on periodic refresh intervals
281
+ emb: np.ndarray | None = None
282
+ crop = _crop_bbox(frame_bgr, tr.bbox)
283
+ should_embed = (
284
+ self.embedder is not None
285
+ and self.embedder.backend != "none"
286
+ and (is_new_raw or (frame_idx % self.embed_every_n_frames == 0))
287
+ )
288
+ if should_embed and crop is not None and self.embedder is not None:
289
+ emb = self.embedder.encode_image(crop)
290
+
291
+ cid = self._try_cross_exit_merge(raw_id, tr.class_name, frame_idx, emb)
292
+ if cid != raw_id:
293
+ tr.reid_merged_from = raw_id
294
+ tr.track_id = cid
295
+ if is_new_raw:
296
+ events.append(
297
+ {
298
+ "type": "reid_cross_exit_merge",
299
+ "raw_track_id": raw_id,
300
+ "canonical_track_id": cid,
301
+ }
302
+ )
303
+
304
+ card = self.cards.get(cid)
305
+ if card is None:
306
+ card = TrackCard(
307
+ track_id=cid,
308
+ class_name=tr.class_name,
309
+ first_frame=frame_idx,
310
+ last_frame=frame_idx,
311
+ first_timestamp_s=timestamp_s,
312
+ last_timestamp_s=timestamp_s,
313
+ frame_count=1,
314
+ best_confidence=tr.confidence,
315
+ best_frame=frame_idx,
316
+ best_bbox=tr.bbox,
317
+ )
318
+ self.cards[cid] = card
319
+ self._save_crop(card, crop)
320
+ else:
321
+ card.last_frame = frame_idx
322
+ card.last_timestamp_s = timestamp_s
323
+ card.frame_count += 1
324
+ if tr.confidence > card.best_confidence:
325
+ card.best_confidence = tr.confidence
326
+ card.best_frame = frame_idx
327
+ card.best_bbox = tr.bbox
328
+ self._save_crop(card, crop)
329
+
330
+ # Update zone tracking on the card
331
+ if tr.zone is not None:
332
+ if tr.zone not in card.zones_visited:
333
+ card.zones_visited.append(tr.zone)
334
+ card.dwell_seconds[tr.zone] = card.dwell_seconds.get(tr.zone, 0.0) + frame_dt_s
335
+
336
+ # Blend running appearance embedding
337
+ if emb is not None:
338
+ prev = self._embeddings.get(cid)
339
+ if prev is None:
340
+ self._embeddings[cid] = emb
341
+ else:
342
+ self._embeddings[cid] = _l2_normalize(0.8 * prev + 0.2 * emb)
343
+ card.embedding = [round(float(x), 5) for x in self._embeddings[cid].tolist()]
344
+
345
+ # Score natural-language prompt if active
346
+ if self._query_vec is not None and cid in self._embeddings:
347
+ score = AppearanceEmbedder.cosine_similarity(self._embeddings[cid], self._query_vec)
348
+ card.query_score = score
349
+ card.query_match = score >= self.query_threshold
350
+ tr.query_score = score
351
+ tr.query_match = card.query_match
352
+
353
+ return events
354
+
355
+ def _save_crop(self, card: TrackCard, crop_bgr: np.ndarray | None) -> None:
356
+ if self.crops_dir is None or crop_bgr is None:
357
+ return
358
+ self.crops_dir.mkdir(parents=True, exist_ok=True)
359
+ filename = f"track_{card.track_id:04d}.jpg"
360
+ out_path = self.crops_dir / filename
361
+ cv2.imwrite(str(out_path), crop_bgr, [int(cv2.IMWRITE_JPEG_QUALITY), 85])
362
+ card.thumbnail_relpath = f"crops/{filename}"
363
+
364
+ def sorted_cards(self) -> list[TrackCard]:
365
+ return sorted(self.cards.values(), key=lambda c: c.track_id)
366
+
367
+ def save_json(self, path: Path, *, reid_backend: str = "none") -> None:
368
+ payload = {
369
+ "reid_backend": reid_backend,
370
+ "query": self.query,
371
+ "query_threshold": self.query_threshold,
372
+ "reid_merges": self.reid_merges,
373
+ "cards": [c.to_dict(include_embedding=True) for c in self.sorted_cards()],
374
+ }
375
+ path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
376
+
377
+
378
+ def search_track_cards(
379
+ run_dir: str | Path,
380
+ query: str,
381
+ *,
382
+ top_k: int = 10,
383
+ min_score: float = -1.0,
384
+ embedder: AppearanceEmbedder | None = None,
385
+ ) -> list[dict[str, Any]]:
386
+ """Search saved Track Cards in a run directory using a natural-language query."""
387
+ run_path = Path(run_dir)
388
+ cards_path = run_path / "track_cards.json" if run_path.is_dir() else run_path
389
+ if not cards_path.is_file():
390
+ raise FileNotFoundError(f"No track_cards.json found at {cards_path}")
391
+
392
+ payload = json.loads(cards_path.read_text(encoding="utf-8"))
393
+ backend = payload.get("reid_backend", "clip")
394
+ cards: list[dict[str, Any]] = payload.get("cards", [])
395
+
396
+ if embedder is None:
397
+ if backend not in ("clip", "siglip"):
398
+ raise ValueError(
399
+ f"Run was recorded with reid_backend='{backend}', which has no text-aligned "
400
+ "embeddings. Re-run with `--reid clip` or `--reid siglip` to enable NL search."
401
+ )
402
+ embedder = AppearanceEmbedder(backend=backend)
403
+
404
+ q_vec = embedder.encode_text(query)
405
+ scored: list[dict[str, Any]] = []
406
+ for card in cards:
407
+ emb = card.get("embedding")
408
+ if not emb:
409
+ continue
410
+ score = AppearanceEmbedder.cosine_similarity(np.asarray(emb, dtype=np.float32), q_vec)
411
+ if score >= min_score:
412
+ item = {k: v for k, v in card.items() if k != "embedding"}
413
+ item["search_score"] = round(float(score), 4)
414
+ scored.append(item)
415
+
416
+ scored.sort(key=lambda r: r["search_score"], reverse=True)
417
+ return scored[:top_k]