trackflow-python-cuda 0.7.0__cp310-abi3-win_amd64.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.
- Cargo.lock +132 -0
- LICENSE +202 -0
- README.md +364 -0
- trackflow/__init__.py +93 -0
- trackflow/_accel.py +36 -0
- trackflow/_native.pyd +0 -0
- trackflow/benchmark.py +266 -0
- trackflow/boosttrack.py +476 -0
- trackflow/cli.py +705 -0
- trackflow/detector.py +912 -0
- trackflow/homography.py +240 -0
- trackflow/inspector.py +479 -0
- trackflow/inspector_ui.html +538 -0
- trackflow/lines.py +125 -0
- trackflow/mask_fallback.py +1025 -0
- trackflow/models.py +491 -0
- trackflow/nltrack.py +1107 -0
- trackflow/ocsort.py +406 -0
- trackflow/pipeline.py +1473 -0
- trackflow/postprocess.py +2068 -0
- trackflow/privacy.py +266 -0
- trackflow/py.typed +1 -0
- trackflow/reid.py +985 -0
- trackflow/sam2_adapter.py +222 -0
- trackflow/sinks.py +440 -0
- trackflow/tracker.py +1331 -0
- trackflow/types.py +241 -0
- trackflow_python_cuda-0.7.0.dist-info/METADATA +420 -0
- trackflow_python_cuda-0.7.0.dist-info/RECORD +33 -0
- trackflow_python_cuda-0.7.0.dist-info/WHEEL +4 -0
- trackflow_python_cuda-0.7.0.dist-info/entry_points.txt +3 -0
- trackflow_python_cuda-0.7.0.dist-info/licenses/LICENSE +202 -0
- trackflow_python_cuda-0.7.0.dist-info/sboms/trackflow-native.cyclonedx.json +536 -0
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""Optional Apache-2.0 SAM 2.1 / EdgeTAM video mask propagator (requires ``trackflow-python[sam2]``)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import cv2
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
from trackflow.mask_fallback import BBox
|
|
13
|
+
from trackflow.models import MASK_REGISTRY
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _import_sam2_deps() -> tuple[Any, Any]:
|
|
17
|
+
try:
|
|
18
|
+
import torch
|
|
19
|
+
import transformers
|
|
20
|
+
except ImportError as exc:
|
|
21
|
+
raise ImportError(
|
|
22
|
+
"SAM 2.1 / EdgeTAM mask fallback requires the optional [sam2] extra: "
|
|
23
|
+
"pip install 'trackflow-python[sam2]'"
|
|
24
|
+
) from exc
|
|
25
|
+
return torch, transformers
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _resolve_torch_device(torch: Any, device: str) -> str:
|
|
29
|
+
req = device.lower().strip()
|
|
30
|
+
if req == "auto":
|
|
31
|
+
if torch.cuda.is_available():
|
|
32
|
+
return "cuda"
|
|
33
|
+
if getattr(torch.backends, "mps", None) is not None and torch.backends.mps.is_available():
|
|
34
|
+
return "mps"
|
|
35
|
+
return "cpu"
|
|
36
|
+
if req in ("cuda", "gpu", "tensorrt") or req.startswith("cuda:"):
|
|
37
|
+
if not torch.cuda.is_available():
|
|
38
|
+
raise RuntimeError(
|
|
39
|
+
f"CUDA requested ({device!r}) for SAM 2.1 mask fallback, but no CUDA device is available."
|
|
40
|
+
)
|
|
41
|
+
return req if req.startswith("cuda:") else "cuda"
|
|
42
|
+
if req in ("mps", "coreml"):
|
|
43
|
+
if getattr(torch.backends, "mps", None) is not None and torch.backends.mps.is_available():
|
|
44
|
+
return "mps"
|
|
45
|
+
raise RuntimeError(
|
|
46
|
+
f"MPS requested ({device!r}) for SAM 2.1 mask fallback, but MPS is unavailable on this host."
|
|
47
|
+
)
|
|
48
|
+
if req == "cpu":
|
|
49
|
+
return "cpu"
|
|
50
|
+
raise ValueError(
|
|
51
|
+
f"Unsupported device {device!r} for SAM 2.1 mask fallback. "
|
|
52
|
+
"Choose auto, cpu, cuda, cuda:<idx>, mps, coreml, or tensorrt."
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _select_dtype(torch: Any, device: str) -> Any:
|
|
57
|
+
if device.startswith("cuda"):
|
|
58
|
+
if getattr(torch.cuda, "is_bf16_supported", lambda: False)():
|
|
59
|
+
return torch.bfloat16
|
|
60
|
+
return torch.float16
|
|
61
|
+
return torch.float32
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class Sam2MaskPropagator:
|
|
65
|
+
"""Apache-2.0 SAM 2.1 / EdgeTAM propagator via Hugging Face Transformers.
|
|
66
|
+
|
|
67
|
+
Keeps all frames strictly in RAM (``writes_frames_to_disk = False``), runs on a 1024x1024
|
|
68
|
+
input grid, and returns native 256x256 boolean masks directly to avoid full-resolution
|
|
69
|
+
upsampling overhead while keeping identical mask-to-box containment scores.
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
writes_frames_to_disk: bool = False
|
|
73
|
+
|
|
74
|
+
def __init__(
|
|
75
|
+
self,
|
|
76
|
+
model: str = "sam2.1-tiny",
|
|
77
|
+
*,
|
|
78
|
+
device: str = "auto",
|
|
79
|
+
cache_dir: str | Path | None = None,
|
|
80
|
+
) -> None:
|
|
81
|
+
spec = MASK_REGISTRY.get(model)
|
|
82
|
+
if spec is None and not model.startswith("hf:"):
|
|
83
|
+
raise ValueError(
|
|
84
|
+
f"Unknown mask fallback model {model!r}. "
|
|
85
|
+
f"Available presets: {', '.join(MASK_REGISTRY)} (or 'hf:owner/repo')."
|
|
86
|
+
)
|
|
87
|
+
repo_id = spec.repo_id if spec is not None else model[3:].strip()
|
|
88
|
+
if not repo_id:
|
|
89
|
+
raise ValueError("Custom 'hf:' mask fallback model must include an owner/repo ID.")
|
|
90
|
+
revision = spec.revision if spec is not None else None
|
|
91
|
+
kind = (
|
|
92
|
+
spec.kind
|
|
93
|
+
if spec is not None
|
|
94
|
+
else ("edgetam" if "edgetam" in repo_id.lower() else "sam2")
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
torch, transformers = _import_sam2_deps()
|
|
98
|
+
self.model_name = model
|
|
99
|
+
self.repo_id = repo_id
|
|
100
|
+
self.revision = revision
|
|
101
|
+
self.device = _resolve_torch_device(torch, device)
|
|
102
|
+
self._torch = torch
|
|
103
|
+
self._dtype = _select_dtype(torch, self.device)
|
|
104
|
+
|
|
105
|
+
load_kwargs: dict[str, Any] = {"dtype": self._dtype, "trust_remote_code": False}
|
|
106
|
+
if revision is not None:
|
|
107
|
+
load_kwargs["revision"] = revision
|
|
108
|
+
if cache_dir is not None:
|
|
109
|
+
load_kwargs["cache_dir"] = str(cache_dir)
|
|
110
|
+
|
|
111
|
+
proc_kwargs: dict[str, Any] = {"trust_remote_code": False}
|
|
112
|
+
if revision is not None:
|
|
113
|
+
proc_kwargs["revision"] = revision
|
|
114
|
+
if cache_dir is not None:
|
|
115
|
+
proc_kwargs["cache_dir"] = str(cache_dir)
|
|
116
|
+
|
|
117
|
+
if kind == "edgetam":
|
|
118
|
+
self._model = (
|
|
119
|
+
transformers.EdgeTamVideoModel.from_pretrained(repo_id, **load_kwargs)
|
|
120
|
+
.to(self.device)
|
|
121
|
+
.eval()
|
|
122
|
+
)
|
|
123
|
+
self._processor = transformers.AutoProcessor.from_pretrained(repo_id, **proc_kwargs)
|
|
124
|
+
else:
|
|
125
|
+
self._model = (
|
|
126
|
+
transformers.Sam2VideoModel.from_pretrained(repo_id, **load_kwargs)
|
|
127
|
+
.to(self.device)
|
|
128
|
+
.eval()
|
|
129
|
+
)
|
|
130
|
+
self._processor = transformers.Sam2VideoProcessor.from_pretrained(
|
|
131
|
+
repo_id, **proc_kwargs
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
def propagate_window(
|
|
135
|
+
self,
|
|
136
|
+
frames_rgb: Sequence[np.ndarray],
|
|
137
|
+
seeds: dict[int, tuple[int, BBox]],
|
|
138
|
+
frame_size_wh: tuple[int, int],
|
|
139
|
+
) -> dict[int, dict[int, np.ndarray]]:
|
|
140
|
+
if not frames_rgb or not seeds:
|
|
141
|
+
return {}
|
|
142
|
+
torch = self._torch
|
|
143
|
+
orig_w = max(1.0, float(frame_size_wh[0]))
|
|
144
|
+
orig_h = max(1.0, float(frame_size_wh[1]))
|
|
145
|
+
sx = 1024.0 / orig_w
|
|
146
|
+
sy = 1024.0 / orig_h
|
|
147
|
+
|
|
148
|
+
frames_1024 = [
|
|
149
|
+
cv2.resize(frame, (1024, 1024), interpolation=cv2.INTER_LINEAR)
|
|
150
|
+
if frame.shape[:2] != (1024, 1024)
|
|
151
|
+
else frame
|
|
152
|
+
for frame in frames_rgb
|
|
153
|
+
]
|
|
154
|
+
|
|
155
|
+
# Group prompts by local frame index so every conditioning frame runs once before propagation.
|
|
156
|
+
by_lf: dict[int, tuple[list[int], list[list[float]]]] = {}
|
|
157
|
+
for oid in sorted(seeds.keys()):
|
|
158
|
+
lf, box = seeds[oid]
|
|
159
|
+
lf = max(0, min(len(frames_1024) - 1, int(lf)))
|
|
160
|
+
x1 = max(0.0, min(1023.0, float(box[0]) * sx))
|
|
161
|
+
y1 = max(0.0, min(1023.0, float(box[1]) * sy))
|
|
162
|
+
x2 = max(1.0, min(1024.0, float(box[2]) * sx))
|
|
163
|
+
y2 = max(1.0, min(1024.0, float(box[3]) * sy))
|
|
164
|
+
if x2 <= x1 + 1.0 or y2 <= y1 + 1.0:
|
|
165
|
+
continue
|
|
166
|
+
ids_l, boxes_l = by_lf.setdefault(lf, ([], []))
|
|
167
|
+
ids_l.append(int(oid))
|
|
168
|
+
boxes_l.append([x1, y1, x2, y2])
|
|
169
|
+
|
|
170
|
+
if not by_lf:
|
|
171
|
+
return {}
|
|
172
|
+
|
|
173
|
+
device_type = "cuda" if self.device.startswith("cuda") else self.device
|
|
174
|
+
with (
|
|
175
|
+
torch.inference_mode(),
|
|
176
|
+
torch.autocast(
|
|
177
|
+
device_type=device_type,
|
|
178
|
+
dtype=self._dtype,
|
|
179
|
+
enabled=(device_type == "cuda"),
|
|
180
|
+
),
|
|
181
|
+
):
|
|
182
|
+
session = self._processor.init_video_session(
|
|
183
|
+
video=frames_1024,
|
|
184
|
+
inference_device=self.device,
|
|
185
|
+
dtype=self._dtype,
|
|
186
|
+
)
|
|
187
|
+
for lf in sorted(by_lf.keys()):
|
|
188
|
+
ids_l, boxes_l = by_lf[lf]
|
|
189
|
+
self._processor.add_inputs_to_inference_session(
|
|
190
|
+
inference_session=session,
|
|
191
|
+
frame_idx=lf,
|
|
192
|
+
obj_ids=ids_l if len(ids_l) > 1 else ids_l[0],
|
|
193
|
+
input_boxes=[boxes_l],
|
|
194
|
+
)
|
|
195
|
+
_ = self._model(inference_session=session, frame_idx=lf)
|
|
196
|
+
|
|
197
|
+
masks_by_lf: dict[int, dict[int, np.ndarray]] = {}
|
|
198
|
+
start_lf = min(by_lf.keys())
|
|
199
|
+
for out in self._model.propagate_in_video_iterator(session, start_frame_idx=start_lf):
|
|
200
|
+
lf = int(out.frame_idx)
|
|
201
|
+
pm = out.pred_masks > 0.0
|
|
202
|
+
if pm.ndim == 4:
|
|
203
|
+
pm = pm[:, 0]
|
|
204
|
+
pm_np = pm.detach().cpu().numpy()
|
|
205
|
+
obj_ids = list(getattr(session, "obj_ids", ()))
|
|
206
|
+
f_dict: dict[int, np.ndarray] = {}
|
|
207
|
+
for oi, oid in enumerate(obj_ids):
|
|
208
|
+
if oi < pm_np.shape[0]:
|
|
209
|
+
f_dict[int(oid)] = pm_np[oi]
|
|
210
|
+
masks_by_lf[lf] = f_dict
|
|
211
|
+
del session
|
|
212
|
+
return masks_by_lf
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def create_mask_propagator(
|
|
216
|
+
backend: str,
|
|
217
|
+
*,
|
|
218
|
+
device: str = "auto",
|
|
219
|
+
cache_dir: str | Path | None = None,
|
|
220
|
+
) -> Sam2MaskPropagator:
|
|
221
|
+
"""Instantiate an optional Apache-2.0 SAM 2.1 / EdgeTAM propagator by preset or ``hf:`` id."""
|
|
222
|
+
return Sam2MaskPropagator(model=backend, device=device, cache_dir=cache_dir)
|
trackflow/sinks.py
ADDED
|
@@ -0,0 +1,440 @@
|
|
|
1
|
+
"""Structured data sinks: Parquet, JSONL, CSV, Annotated MP4, and standalone HTML run report."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import csv
|
|
6
|
+
import html
|
|
7
|
+
import json
|
|
8
|
+
from collections.abc import Iterable, Sequence
|
|
9
|
+
from contextlib import ExitStack
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
import cv2
|
|
14
|
+
import numpy as np
|
|
15
|
+
import pyarrow as pa
|
|
16
|
+
import pyarrow.parquet as pq
|
|
17
|
+
|
|
18
|
+
from trackflow.lines import CountingLine
|
|
19
|
+
from trackflow.privacy import _track_color
|
|
20
|
+
from trackflow.types import FrameResult, RunSummary, Track, TrackCard
|
|
21
|
+
|
|
22
|
+
PARQUET_SCHEMA = pa.schema(
|
|
23
|
+
[
|
|
24
|
+
("frame_idx", pa.int64()),
|
|
25
|
+
("timestamp_s", pa.float64()),
|
|
26
|
+
("track_id", pa.int64()),
|
|
27
|
+
("class_id", pa.int64()),
|
|
28
|
+
("class_name", pa.string()),
|
|
29
|
+
("confidence", pa.float64()),
|
|
30
|
+
("x1", pa.float64()),
|
|
31
|
+
("y1", pa.float64()),
|
|
32
|
+
("x2", pa.float64()),
|
|
33
|
+
("y2", pa.float64()),
|
|
34
|
+
("width", pa.float64()),
|
|
35
|
+
("height", pa.float64()),
|
|
36
|
+
("age", pa.int64()),
|
|
37
|
+
("hits", pa.int64()),
|
|
38
|
+
("recovered", pa.bool_()),
|
|
39
|
+
("query_score", pa.float64()),
|
|
40
|
+
("query_match", pa.bool_()),
|
|
41
|
+
("world_x", pa.float64()),
|
|
42
|
+
("world_y", pa.float64()),
|
|
43
|
+
("zone", pa.string()),
|
|
44
|
+
]
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class ObservationWriter:
|
|
49
|
+
"""Write each requested format in bounded batches, including schemas on empty runs."""
|
|
50
|
+
|
|
51
|
+
def __init__(self, paths: dict[str, Path], stack: ExitStack) -> None:
|
|
52
|
+
self._batch: list[dict[str, Any]] = []
|
|
53
|
+
self._parquet = None
|
|
54
|
+
self._jsonl = self._csv = self._mot = None
|
|
55
|
+
if "parquet" in paths:
|
|
56
|
+
self._parquet = stack.enter_context(
|
|
57
|
+
pq.ParquetWriter(paths["parquet"], PARQUET_SCHEMA, compression="snappy")
|
|
58
|
+
)
|
|
59
|
+
if "jsonl" in paths:
|
|
60
|
+
self._jsonl = stack.enter_context(paths["jsonl"].open("w", encoding="utf-8"))
|
|
61
|
+
if "csv" in paths:
|
|
62
|
+
fh = stack.enter_context(paths["csv"].open("w", encoding="utf-8", newline=""))
|
|
63
|
+
self._csv = csv.DictWriter(fh, fieldnames=PARQUET_SCHEMA.names)
|
|
64
|
+
self._csv.writeheader()
|
|
65
|
+
if "mot" in paths:
|
|
66
|
+
fh = stack.enter_context(paths["mot"].open("w", encoding="utf-8", newline=""))
|
|
67
|
+
self._mot = csv.writer(fh, lineterminator="\n")
|
|
68
|
+
stack.callback(self.flush)
|
|
69
|
+
|
|
70
|
+
def append(self, record: dict[str, Any]) -> None:
|
|
71
|
+
self._batch.append(record)
|
|
72
|
+
if len(self._batch) >= 1024:
|
|
73
|
+
self.flush()
|
|
74
|
+
|
|
75
|
+
def flush(self) -> None:
|
|
76
|
+
if not self._batch:
|
|
77
|
+
return
|
|
78
|
+
batch, self._batch = self._batch, []
|
|
79
|
+
if self._parquet is not None:
|
|
80
|
+
self._parquet.write_table(pa.Table.from_pylist(batch, schema=PARQUET_SCHEMA))
|
|
81
|
+
if self._csv is not None:
|
|
82
|
+
self._csv.writerows(batch)
|
|
83
|
+
if self._jsonl is not None:
|
|
84
|
+
self._jsonl.writelines(json.dumps(r) + "\n" for r in batch)
|
|
85
|
+
if self._mot is not None:
|
|
86
|
+
for r in batch:
|
|
87
|
+
self._mot.writerow(
|
|
88
|
+
(
|
|
89
|
+
r["frame_idx"] + 1,
|
|
90
|
+
r["track_id"],
|
|
91
|
+
round(r["x1"] + 1, 2),
|
|
92
|
+
round(r["y1"] + 1, 2),
|
|
93
|
+
r["width"],
|
|
94
|
+
r["height"],
|
|
95
|
+
r["confidence"],
|
|
96
|
+
-1,
|
|
97
|
+
-1,
|
|
98
|
+
-1,
|
|
99
|
+
)
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _write_records(records: Iterable[dict[str, Any]], path: Path, fmt: str) -> Path:
|
|
104
|
+
with ExitStack() as stack:
|
|
105
|
+
writer = ObservationWriter({fmt: path}, stack)
|
|
106
|
+
for rec in records:
|
|
107
|
+
writer.append(rec)
|
|
108
|
+
return path
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def write_parquet(records: Iterable[dict[str, Any]], path: Path) -> Path:
|
|
112
|
+
"""Write track observations to Parquet with the public Trackflow schema."""
|
|
113
|
+
return _write_records(records, path, "parquet")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def write_jsonl(records: Iterable[dict[str, Any]], path: Path) -> Path:
|
|
117
|
+
"""Write line-delimited JSON observations."""
|
|
118
|
+
return _write_records(records, path, "jsonl")
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def write_csv(records: Iterable[dict[str, Any]], path: Path) -> Path:
|
|
122
|
+
"""Write CSV observations with a header."""
|
|
123
|
+
return _write_records(records, path, "csv")
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def write_mot(records: Iterable[dict[str, Any]], path: Path) -> Path:
|
|
127
|
+
"""Write MOTChallenge 2D results. Frame, ID, left and top are one-based."""
|
|
128
|
+
return _write_records(records, path, "mot")
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def draw_tracks(
|
|
132
|
+
frame_bgr: np.ndarray,
|
|
133
|
+
tracks: list[Track],
|
|
134
|
+
*,
|
|
135
|
+
trails: dict[int, list[tuple[int, int]]],
|
|
136
|
+
coasting: list[Track] | None = None,
|
|
137
|
+
fps: float | None = None,
|
|
138
|
+
query: str | None = None,
|
|
139
|
+
anonymize_mode: str = "none",
|
|
140
|
+
lines: Sequence[CountingLine] = (),
|
|
141
|
+
line_counts: dict[str, dict[str, int]] | None = None,
|
|
142
|
+
) -> np.ndarray:
|
|
143
|
+
"""Draw boxes, IDs, motion trails, query highlight badges, counting lines, and HUD."""
|
|
144
|
+
canvas = frame_bgr.copy()
|
|
145
|
+
|
|
146
|
+
for line in lines:
|
|
147
|
+
start = tuple(int(round(v)) for v in line.start)
|
|
148
|
+
end = tuple(int(round(v)) for v in line.end)
|
|
149
|
+
cv2.line(canvas, start, end, (0, 215, 255), 2, cv2.LINE_AA)
|
|
150
|
+
# Arrow from the middle of the line toward its "in" side.
|
|
151
|
+
dx, dy = line.end[0] - line.start[0], line.end[1] - line.start[1]
|
|
152
|
+
norm = max((dx * dx + dy * dy) ** 0.5, 1e-6)
|
|
153
|
+
mid = ((line.start[0] + line.end[0]) / 2, (line.start[1] + line.end[1]) / 2)
|
|
154
|
+
tip = (mid[0] - dy / norm * 18, mid[1] + dx / norm * 18)
|
|
155
|
+
cv2.arrowedLine(
|
|
156
|
+
canvas,
|
|
157
|
+
(int(round(mid[0])), int(round(mid[1]))),
|
|
158
|
+
(int(round(tip[0])), int(round(tip[1]))),
|
|
159
|
+
(0, 215, 255),
|
|
160
|
+
2,
|
|
161
|
+
cv2.LINE_AA,
|
|
162
|
+
tipLength=0.4,
|
|
163
|
+
)
|
|
164
|
+
counts = (line_counts or {}).get(line.name, {"in": 0, "out": 0})
|
|
165
|
+
cv2.putText(
|
|
166
|
+
canvas,
|
|
167
|
+
f"{line.name} in {counts['in']} out {counts['out']}",
|
|
168
|
+
(start[0] + 4, max(14, start[1] - 6)),
|
|
169
|
+
cv2.FONT_HERSHEY_SIMPLEX,
|
|
170
|
+
0.5,
|
|
171
|
+
(0, 215, 255),
|
|
172
|
+
1,
|
|
173
|
+
cv2.LINE_AA,
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
# Briefly-missed tracks at their predicted position: thin dimmed box + ID, so boxes don't blink.
|
|
177
|
+
for tr in coasting or []:
|
|
178
|
+
x1, y1, x2, y2 = [int(round(v)) for v in tr.bbox]
|
|
179
|
+
dim = tuple(int(c * 0.6) for c in _track_color(tr.track_id))
|
|
180
|
+
cv2.rectangle(canvas, (x1, y1), (x2, y2), dim, 1, cv2.LINE_AA)
|
|
181
|
+
cv2.putText(
|
|
182
|
+
canvas,
|
|
183
|
+
f"#{tr.track_id}",
|
|
184
|
+
(x1 + 2, max(12, y1 - 4)),
|
|
185
|
+
cv2.FONT_HERSHEY_SIMPLEX,
|
|
186
|
+
0.45,
|
|
187
|
+
dim,
|
|
188
|
+
1,
|
|
189
|
+
cv2.LINE_AA,
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
for tr in tracks:
|
|
193
|
+
x1, y1, x2, y2 = [int(round(v)) for v in tr.bbox]
|
|
194
|
+
base_color = _track_color(tr.track_id)
|
|
195
|
+
is_match = tr.query_match
|
|
196
|
+
|
|
197
|
+
color = base_color if is_match else (100, 105, 115)
|
|
198
|
+
thickness = 3 if (query and is_match) else (2 if is_match else 1)
|
|
199
|
+
|
|
200
|
+
# Draw motion trail
|
|
201
|
+
trail = trails.get(tr.track_id, [])
|
|
202
|
+
if len(trail) >= 2:
|
|
203
|
+
pts = np.array(trail[-32:], dtype=np.int32)
|
|
204
|
+
cv2.polylines(canvas, [pts], False, color, 2 if is_match else 1, cv2.LINE_AA)
|
|
205
|
+
|
|
206
|
+
# Bounding box
|
|
207
|
+
cv2.rectangle(canvas, (x1, y1), (x2, y2), color, thickness, cv2.LINE_AA)
|
|
208
|
+
|
|
209
|
+
# Label pill
|
|
210
|
+
parts = [f"#{tr.track_id}", tr.class_name, f"{tr.confidence:.2f}"]
|
|
211
|
+
if tr.query_score is not None:
|
|
212
|
+
parts.append(f"q:{tr.query_score:.2f}")
|
|
213
|
+
if tr.zone:
|
|
214
|
+
parts.append(f"[{tr.zone}]")
|
|
215
|
+
label = " ".join(parts)
|
|
216
|
+
|
|
217
|
+
(tw, th), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
|
|
218
|
+
ly = max(th + 8, y1)
|
|
219
|
+
cv2.rectangle(canvas, (x1, ly - th - 8), (x1 + tw + 10, ly), color, -1)
|
|
220
|
+
cv2.putText(
|
|
221
|
+
canvas,
|
|
222
|
+
label,
|
|
223
|
+
(x1 + 5, ly - 5),
|
|
224
|
+
cv2.FONT_HERSHEY_SIMPLEX,
|
|
225
|
+
0.5,
|
|
226
|
+
(15, 18, 24),
|
|
227
|
+
1,
|
|
228
|
+
cv2.LINE_AA,
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
# Top-left HUD
|
|
232
|
+
hud_items = [f"Trackflow | {len(tracks)} active"]
|
|
233
|
+
if fps is not None:
|
|
234
|
+
hud_items.append(f"{fps:.1f} FPS")
|
|
235
|
+
if query:
|
|
236
|
+
hud_items.append(f'query: "{query}"')
|
|
237
|
+
if anonymize_mode != "none":
|
|
238
|
+
hud_items.append(f"privacy: {anonymize_mode}")
|
|
239
|
+
hud_text = " • ".join(hud_items)
|
|
240
|
+
(hw, hh), _ = cv2.getTextSize(hud_text, cv2.FONT_HERSHEY_SIMPLEX, 0.55, 1)
|
|
241
|
+
cv2.rectangle(canvas, (10, 10), (24 + hw, 24 + hh), (15, 18, 26), -1)
|
|
242
|
+
cv2.putText(
|
|
243
|
+
canvas,
|
|
244
|
+
hud_text,
|
|
245
|
+
(17, 17 + hh),
|
|
246
|
+
cv2.FONT_HERSHEY_SIMPLEX,
|
|
247
|
+
0.55,
|
|
248
|
+
(235, 242, 250),
|
|
249
|
+
1,
|
|
250
|
+
cv2.LINE_AA,
|
|
251
|
+
)
|
|
252
|
+
return canvas
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def write_html_report(
|
|
256
|
+
summary: RunSummary,
|
|
257
|
+
frame_results: list[FrameResult],
|
|
258
|
+
cards: list[TrackCard],
|
|
259
|
+
path: Path,
|
|
260
|
+
) -> Path:
|
|
261
|
+
"""Generate a self-contained HTML run report with inline SVG charts & Track Card gallery."""
|
|
262
|
+
counts = [len(fr.tracks) for fr in frame_results]
|
|
263
|
+
events = (
|
|
264
|
+
{"frame_idx": fr.frame_idx, "timestamp_s": fr.timestamp_s, **ev}
|
|
265
|
+
for fr in frame_results
|
|
266
|
+
for ev in fr.events
|
|
267
|
+
)
|
|
268
|
+
return write_run_report(summary, counts, events, cards, path)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def write_run_report(
|
|
272
|
+
summary: RunSummary,
|
|
273
|
+
counts: Sequence[int],
|
|
274
|
+
events: Iterable[dict[str, Any]],
|
|
275
|
+
cards: list[TrackCard],
|
|
276
|
+
path: Path,
|
|
277
|
+
) -> Path:
|
|
278
|
+
"""Render the report from frame counts and events without retaining track objects."""
|
|
279
|
+
max_count = max(counts, default=0)
|
|
280
|
+
|
|
281
|
+
# Build inline SVG sparkline for active tracks per frame
|
|
282
|
+
svg_w, svg_h = 720, 150
|
|
283
|
+
if len(counts) > svg_w:
|
|
284
|
+
# One peak per display column keeps the report usable for long recordings.
|
|
285
|
+
counts = [
|
|
286
|
+
max(counts[i * len(counts) // svg_w : (i + 1) * len(counts) // svg_w])
|
|
287
|
+
for i in range(svg_w)
|
|
288
|
+
]
|
|
289
|
+
if len(counts) >= 2:
|
|
290
|
+
pts = [
|
|
291
|
+
f"{(i / (len(counts) - 1)) * svg_w:.1f},{svg_h - 12 - (c / max(1, max_count)) * (svg_h - 24):.1f}"
|
|
292
|
+
for i, c in enumerate(counts)
|
|
293
|
+
]
|
|
294
|
+
polyline = " ".join(pts)
|
|
295
|
+
area = f"0,{svg_h} {polyline} {svg_w},{svg_h}"
|
|
296
|
+
else:
|
|
297
|
+
polyline = f"0,{svg_h - 12} {svg_w},{svg_h - 12}"
|
|
298
|
+
area = f"0,{svg_h} {polyline} {svg_w},{svg_h}"
|
|
299
|
+
|
|
300
|
+
# Diagnostic events summary
|
|
301
|
+
id_switch_rows: list[str] = []
|
|
302
|
+
for ev in events:
|
|
303
|
+
et = ev.get("type", "event")
|
|
304
|
+
if et in ("possible_id_switch", "reid_cross_exit_merge", "track_recovered"):
|
|
305
|
+
id_switch_rows.append(
|
|
306
|
+
f"<tr><td>{int(ev['frame_idx'])}</td><td>{ev['timestamp_s']:.2f}s</td>"
|
|
307
|
+
f"<td><code>{html.escape(et)}</code></td>"
|
|
308
|
+
f"<td><code>{html.escape(json.dumps(ev))}</code></td></tr>"
|
|
309
|
+
)
|
|
310
|
+
if len(id_switch_rows) == 40:
|
|
311
|
+
break
|
|
312
|
+
|
|
313
|
+
line_kpis = "".join(
|
|
314
|
+
f'<div class="kpi"><div class="label">Line {html.escape(name)} (in / out)</div>'
|
|
315
|
+
f'<div class="val">{c["in"]} / {c["out"]}</div></div>'
|
|
316
|
+
for name, c in summary.line_counts.items()
|
|
317
|
+
)
|
|
318
|
+
|
|
319
|
+
card_html: list[str] = []
|
|
320
|
+
for c in cards[:60]:
|
|
321
|
+
q_badge = (
|
|
322
|
+
f'<span class="badge {"match" if c.query_match else "muted"}">query {c.query_score:.2f}</span>'
|
|
323
|
+
if c.query_score is not None
|
|
324
|
+
else ""
|
|
325
|
+
)
|
|
326
|
+
merged_badge = (
|
|
327
|
+
f'<span class="badge accent">Re-ID merged {len(c.merged_track_ids)}x</span>'
|
|
328
|
+
if c.merged_track_ids
|
|
329
|
+
else ""
|
|
330
|
+
)
|
|
331
|
+
thumb = (
|
|
332
|
+
f'<img src="{html.escape(c.thumbnail_relpath)}" alt="Track #{c.track_id}" />'
|
|
333
|
+
if c.thumbnail_relpath
|
|
334
|
+
else '<div class="thumb-placeholder">No Crop</div>'
|
|
335
|
+
)
|
|
336
|
+
card_html.append(
|
|
337
|
+
f"""
|
|
338
|
+
<div class="card">
|
|
339
|
+
<div class="thumb">{thumb}</div>
|
|
340
|
+
<div class="card-body">
|
|
341
|
+
<div class="card-head">
|
|
342
|
+
<strong>Track #{c.track_id}</strong>
|
|
343
|
+
<span class="badge">{html.escape(c.class_name)}</span>
|
|
344
|
+
{q_badge}{merged_badge}
|
|
345
|
+
</div>
|
|
346
|
+
<div class="meta">
|
|
347
|
+
Frames {c.first_frame}–{c.last_frame} ({c.duration_s:.1f}s · {c.frame_count} obs)<br/>
|
|
348
|
+
Peak conf: {c.best_confidence:.2f}
|
|
349
|
+
{f"<br/>Zones: {html.escape(', '.join(c.zones_visited))}" if c.zones_visited else ""}
|
|
350
|
+
</div>
|
|
351
|
+
</div>
|
|
352
|
+
</div>
|
|
353
|
+
"""
|
|
354
|
+
)
|
|
355
|
+
|
|
356
|
+
doc = f"""<!DOCTYPE html>
|
|
357
|
+
<html lang="en">
|
|
358
|
+
<head>
|
|
359
|
+
<meta charset="utf-8" />
|
|
360
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
361
|
+
<title>Trackflow Run Report — {html.escape(Path(summary.source).name)}</title>
|
|
362
|
+
<style>
|
|
363
|
+
:root {{
|
|
364
|
+
--bg: #0b1020; --surface: #131b31; --border: #24304f;
|
|
365
|
+
--text: #e6eefc; --muted: #93a4c7; --accent: #34d399; --sky: #38bdf8;
|
|
366
|
+
}}
|
|
367
|
+
* {{ box-sizing: border-box; }}
|
|
368
|
+
body {{ margin: 0; font-family: ui-sans-serif, system-ui, -apple-system, sans-serif; background: var(--bg); color: var(--text); padding: 28px; }}
|
|
369
|
+
.wrap {{ max-width: 1080px; margin: 0 auto; }}
|
|
370
|
+
h1 {{ margin: 0 0 6px; font-size: 24px; }}
|
|
371
|
+
.sub {{ color: var(--muted); font-size: 14px; margin-bottom: 22px; }}
|
|
372
|
+
.kpis {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 12px; margin-bottom: 22px; }}
|
|
373
|
+
.kpi {{ background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 14px 16px; }}
|
|
374
|
+
.kpi .label {{ font-size: 12px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.04em; }}
|
|
375
|
+
.kpi .val {{ font-size: 26px; font-weight: 700; margin-top: 4px; color: var(--accent); }}
|
|
376
|
+
.panel {{ background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 18px; margin-bottom: 20px; }}
|
|
377
|
+
.panel h2 {{ margin: 0 0 12px; font-size: 16px; }}
|
|
378
|
+
.cards {{ display: grid; grid-template-columns: repeat(auto-fill, minmax(230px, 1fr)); gap: 12px; }}
|
|
379
|
+
.card {{ background: #0f1629; border: 1px solid var(--border); border-radius: 10px; overflow: hidden; display: flex; gap: 10px; padding: 10px; }}
|
|
380
|
+
.thumb {{ width: 64px; height: 84px; flex: 0 0 64px; border-radius: 6px; overflow: hidden; background: #1a2440; display: flex; align-items: center; justify-content: center; }}
|
|
381
|
+
.thumb img {{ width: 100%; height: 100%; object-fit: cover; }}
|
|
382
|
+
.thumb-placeholder {{ font-size: 11px; color: var(--muted); }}
|
|
383
|
+
.card-head {{ display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin-bottom: 6px; }}
|
|
384
|
+
.badge {{ font-size: 11px; padding: 2px 7px; border-radius: 999px; background: #1d2b4f; color: var(--sky); }}
|
|
385
|
+
.badge.match, .badge.accent {{ background: #0d3b2e; color: var(--accent); }}
|
|
386
|
+
.badge.muted {{ background: #1e2433; color: var(--muted); }}
|
|
387
|
+
.meta {{ font-size: 12px; color: var(--muted); line-height: 1.45; }}
|
|
388
|
+
table {{ width: 100%; border-collapse: collapse; font-size: 13px; }}
|
|
389
|
+
th, td {{ text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--border); }}
|
|
390
|
+
th {{ color: var(--muted); font-weight: 600; }}
|
|
391
|
+
code {{ font-family: ui-monospace, SFMono-Regular, monospace; font-size: 12px; color: #bae6fd; }}
|
|
392
|
+
</style>
|
|
393
|
+
</head>
|
|
394
|
+
<body>
|
|
395
|
+
<div class="wrap">
|
|
396
|
+
<h1>Trackflow Run Report</h1>
|
|
397
|
+
<div class="sub">
|
|
398
|
+
Source: <code>{html.escape(summary.source)}</code> ·
|
|
399
|
+
Model: <code>{html.escape(summary.model)}</code> ·
|
|
400
|
+
Tracker: <code>{html.escape(summary.tracker)}</code> ·
|
|
401
|
+
Provider: <code>{html.escape(summary.device)}</code>
|
|
402
|
+
{f" · Query: <code>{html.escape(summary.query)}</code>" if summary.query else ""}
|
|
403
|
+
{f" · Privacy: <code>{html.escape(summary.anonymize_mode)}</code>" if summary.anonymize_mode != "none" else ""}
|
|
404
|
+
</div>
|
|
405
|
+
|
|
406
|
+
<div class="kpis">
|
|
407
|
+
<div class="kpi"><div class="label">Unique Tracks</div><div class="val">{summary.unique_tracks}</div></div>
|
|
408
|
+
<div class="kpi"><div class="label">Avg Speed</div><div class="val">{summary.avg_fps:.1f} FPS</div></div>
|
|
409
|
+
<div class="kpi"><div class="label">Frames</div><div class="val">{summary.processed_frames}</div></div>
|
|
410
|
+
<div class="kpi"><div class="label">Inference</div><div class="val">{summary.avg_inference_ms:.1f} ms</div></div>
|
|
411
|
+
<div class="kpi"><div class="label">Recovered / Re-ID</div><div class="val">{summary.recovered_tracks} / {summary.reid_merges}</div></div>
|
|
412
|
+
{line_kpis}
|
|
413
|
+
</div>
|
|
414
|
+
|
|
415
|
+
<div class="panel">
|
|
416
|
+
<h2>Active Tracked Objects Over Time (peak: {max_count})</h2>
|
|
417
|
+
<svg viewBox="0 0 {svg_w} {svg_h}" width="100%" height="150" preserveAspectRatio="none">
|
|
418
|
+
<polygon points="{area}" fill="rgba(56, 189, 248, 0.16)" />
|
|
419
|
+
<polyline points="{polyline}" fill="none" stroke="#38bdf8" stroke-width="2.2" />
|
|
420
|
+
</svg>
|
|
421
|
+
</div>
|
|
422
|
+
|
|
423
|
+
<div class="panel">
|
|
424
|
+
<h2>Track Cards ({len(cards)} total)</h2>
|
|
425
|
+
<div class="cards">{"".join(card_html) or '<div class="meta">No tracks recorded.</div>'}</div>
|
|
426
|
+
</div>
|
|
427
|
+
|
|
428
|
+
<div class="panel">
|
|
429
|
+
<h2>Tracker Diagnostics (Possible ID Switches, Recoveries & Re-ID Merges)</h2>
|
|
430
|
+
<table>
|
|
431
|
+
<thead><tr><th>Frame</th><th>Time</th><th>Event</th><th>Details</th></tr></thead>
|
|
432
|
+
<tbody>{"".join(id_switch_rows[:40]) or '<tr><td colspan="4" class="meta">No anomalies or switches detected.</td></tr>'}</tbody>
|
|
433
|
+
</table>
|
|
434
|
+
</div>
|
|
435
|
+
</div>
|
|
436
|
+
</body>
|
|
437
|
+
</html>
|
|
438
|
+
"""
|
|
439
|
+
path.write_text(doc, encoding="utf-8")
|
|
440
|
+
return path
|