matrice-analytics 0.1.96__py3-none-any.whl → 0.1.97__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.
@@ -0,0 +1,1011 @@
1
+ from typing import Any, Dict, List, Optional, Tuple
2
+ from dataclasses import asdict
3
+ import time
4
+ from datetime import datetime, timezone
5
+
6
+ from ..core.base import BaseProcessor, ProcessingContext, ProcessingResult, ConfigProtocol, ResultFormat
7
+ from ..utils import (
8
+ filter_by_confidence,
9
+ filter_by_categories,
10
+ apply_category_mapping,
11
+ count_objects_by_category,
12
+ count_objects_in_zones,
13
+ calculate_counting_summary,
14
+ match_results_structure,
15
+ bbox_smoothing,
16
+ BBoxSmoothingConfig,
17
+ BBoxSmoothingTracker
18
+ )
19
+ from dataclasses import dataclass, field
20
+ from ..core.config import BaseConfig, AlertConfig, ZoneConfig
21
+ from ..utils.geometry_utils import get_bbox_center, point_in_polygon, get_bbox_bottom25_center
22
+
23
+ @dataclass
24
+ class VehicleMonitoringParkingLotConfig(BaseConfig):
25
+ """Configuration for vehicle detection use case in parking lot vehicle monitoring."""
26
+ enable_smoothing: bool = True
27
+ smoothing_algorithm: str = "observability"
28
+ smoothing_window_size: int = 20
29
+ smoothing_cooldown_frames: int = 5
30
+ smoothing_confidence_range_factor: float = 0.5
31
+ confidence_threshold: float = 0.6
32
+
33
+ #JBK_720_GATE POLYGON = [[86, 328], [844, 317], [1277, 520], [1273, 707], [125, 713]]
34
+ zone_config: Optional[Dict[str, List[List[float]]]] = None #field(
35
+ # default_factory=lambda: {
36
+ # "zones": {
37
+ # "Interest_Region": [[86, 328], [844, 317], [1277, 520], [1273, 707], [125, 713]],
38
+ # }
39
+ # }
40
+ # )
41
+ usecase_categories: List[str] = field(
42
+ default_factory=lambda: [
43
+ 'bicycle', 'motorcycle', 'car', 'van', 'bus', 'truck'
44
+ ]
45
+ )
46
+ target_categories: List[str] = field(
47
+ default_factory=lambda: [
48
+ 'bicycle', 'motorcycle', 'car', 'van', 'bus', 'truck'
49
+ ]
50
+ )
51
+ alert_config: Optional[AlertConfig] = None
52
+ index_to_category: Optional[Dict[int, str]] = field(
53
+ default_factory=lambda: {
54
+ 0: "bicycle",
55
+ 1: "motorcycle",
56
+ 2: "car",
57
+ 3: "van",
58
+ 4: "bus",
59
+ 5: "truck"
60
+ }
61
+ )
62
+
63
+ class VehicleMonitoringParkingLotUseCase(BaseProcessor):
64
+ CATEGORY_DISPLAY = {
65
+ "bicycle": "Bicycle",
66
+ "motorcycle": "Motorcycle",
67
+ "car": "Car",
68
+ "van": "Van",
69
+ "bus": "Bus",
70
+ "truck": "Truck",
71
+ }
72
+
73
+ def __init__(self):
74
+ super().__init__("vehicle_monitoring_parking_lot")
75
+ self.category = "traffic"
76
+ self.CASE_TYPE: Optional[str] = 'vehicle_monitoring_parking_lot'
77
+ self.CASE_VERSION: Optional[str] = '1.0'
78
+ self.target_categories = ['bicycle', 'motorcycle', 'car', 'van', 'bus', 'truck' ]
79
+ self.smoothing_tracker = None
80
+ self.tracker = None
81
+ self._total_frame_counter = 0
82
+ self._global_frame_offset = 0
83
+ self._tracking_start_time = None
84
+ self._track_aliases: Dict[Any, Any] = {}
85
+ self._canonical_tracks: Dict[Any, Dict[str, Any]] = {}
86
+ self._track_merge_iou_threshold: float = 0.05
87
+ self._track_merge_time_window: float = 7.0
88
+ self._ascending_alert_list: List[int] = []
89
+ self.current_incident_end_timestamp: str = "N/A"
90
+ self.start_timer = None
91
+
92
+ # Track ID storage for total count calculation
93
+ self._per_category_total_track_ids = {cat: set() for cat in self.target_categories}
94
+ self._current_frame_track_ids = {cat: set() for cat in self.target_categories}
95
+ self._tracked_in_zones = set() # New: Unique track IDs that have entered any zone
96
+ self._total_count = 0 # Cached total count
97
+ self._last_update_time = time.time() # Track when last updated
98
+ self._total_count_list = []
99
+
100
+ # Zone-based tracking storage
101
+ self._zone_current_track_ids = {} # zone_name -> set of current track IDs in zone
102
+ self._zone_total_track_ids = {} # zone_name -> set of all track IDs that have been in zone
103
+ self._zone_current_counts = {} # zone_name -> current count in zone
104
+ self._zone_total_counts = {} # zone_name -> total count that have been in zone
105
+
106
+ def process(self, data: Any, config: ConfigProtocol, context: Optional[ProcessingContext] = None,
107
+ stream_info: Optional[Dict[str, Any]] = None) -> ProcessingResult:
108
+ processing_start = time.time()
109
+ if not isinstance(config, VehicleMonitoringParkingLotConfig):
110
+ return self.create_error_result("Invalid config type", usecase=self.name, category=self.category, context=context)
111
+ if context is None:
112
+ context = ProcessingContext()
113
+
114
+ # Determine if zones are configured
115
+ has_zones = bool(config.zone_config and config.zone_config.get('zones'))
116
+
117
+ # Normalize typical YOLO outputs (COCO pretrained) to internal schema
118
+ data = self._normalize_yolo_results(data, getattr(config, 'index_to_category', None))
119
+
120
+ input_format = match_results_structure(data)
121
+ context.input_format = input_format
122
+ context.confidence_threshold = config.confidence_threshold
123
+ config.confidence_threshold = 0.25
124
+ # param to be updated
125
+
126
+ if config.confidence_threshold is not None:
127
+ processed_data = filter_by_confidence(data, config.confidence_threshold)
128
+ self.logger.debug(f"Applied confidence filtering with threshold {config.confidence_threshold}")
129
+ else:
130
+ processed_data = data
131
+ self.logger.debug("Did not apply confidence filtering since no threshold provided")
132
+
133
+ if config.index_to_category:
134
+ processed_data = apply_category_mapping(processed_data, config.index_to_category)
135
+ self.logger.debug("Applied category mapping")
136
+
137
+ processed_data = [d for d in processed_data if d.get('category') in self.target_categories]
138
+ if config.target_categories:
139
+ processed_data = [d for d in processed_data if d.get('category') in self.target_categories]
140
+ self.logger.debug("Applied category filtering")
141
+
142
+
143
+ if config.enable_smoothing:
144
+ if self.smoothing_tracker is None:
145
+ smoothing_config = BBoxSmoothingConfig(
146
+ smoothing_algorithm=config.smoothing_algorithm,
147
+ window_size=config.smoothing_window_size,
148
+ cooldown_frames=config.smoothing_cooldown_frames,
149
+ confidence_threshold=config.confidence_threshold,
150
+ confidence_range_factor=config.smoothing_confidence_range_factor,
151
+ enable_smoothing=True
152
+ )
153
+ self.smoothing_tracker = BBoxSmoothingTracker(smoothing_config)
154
+ processed_data = bbox_smoothing(processed_data, self.smoothing_tracker.config, self.smoothing_tracker)
155
+
156
+ try:
157
+ from ..advanced_tracker import AdvancedTracker
158
+ from ..advanced_tracker.config import TrackerConfig
159
+ if self.tracker is None:
160
+ tracker_config = TrackerConfig()
161
+ self.tracker = AdvancedTracker(tracker_config)
162
+ self.logger.info("Initialized AdvancedTracker for Vehicle Monitoring Parking Lot use case")
163
+ processed_data = self.tracker.update(processed_data)
164
+ except Exception as e:
165
+ self.logger.warning(f"AdvancedTracker failed: {e}")
166
+
167
+ self._update_tracking_state(processed_data, has_zones=has_zones)
168
+ self._total_frame_counter += 1
169
+
170
+ frame_number = None
171
+ if stream_info:
172
+ input_settings = stream_info.get("input_settings", {})
173
+ start_frame = input_settings.get("start_frame")
174
+ end_frame = input_settings.get("end_frame")
175
+ if start_frame is not None and end_frame is not None and start_frame == end_frame:
176
+ frame_number = start_frame
177
+
178
+ general_counting_summary = calculate_counting_summary(data)
179
+ counting_summary = self._count_categories(processed_data, config)
180
+ total_counts = self.get_total_counts()
181
+ counting_summary['total_counts'] = total_counts
182
+ counting_summary['categories'] = {}
183
+ for detection in processed_data:
184
+ category = detection.get("category", "unknown")
185
+ counting_summary["categories"][category] = counting_summary["categories"].get(category, 0) + 1
186
+
187
+ zone_analysis = {}
188
+ if has_zones:
189
+ # Convert single frame to format expected by count_objects_in_zones
190
+ frame_data = processed_data #[frame_detections]
191
+ zone_analysis = count_objects_in_zones(frame_data, config.zone_config['zones'], stream_info)
192
+
193
+ if zone_analysis:
194
+ enhanced_zone_analysis = self._update_zone_tracking(zone_analysis, processed_data, config)
195
+ # Merge enhanced zone analysis with original zone analysis
196
+ for zone_name, enhanced_data in enhanced_zone_analysis.items():
197
+ zone_analysis[zone_name] = enhanced_data
198
+
199
+ # Adjust counting_summary for zones (current counts based on union across zones)
200
+ per_category_count = {cat: len(self._current_frame_track_ids.get(cat, set())) for cat in self.target_categories}
201
+ counting_summary['per_category_count'] = {k: v for k, v in per_category_count.items() if v > 0}
202
+ counting_summary['total_count'] = sum(per_category_count.values())
203
+
204
+ alerts = self._check_alerts(counting_summary,zone_analysis, frame_number, config)
205
+ predictions = self._extract_predictions(processed_data)
206
+
207
+ incidents_list = self._generate_incidents(counting_summary,zone_analysis, alerts, config, frame_number, stream_info)
208
+ incidents_list = []
209
+ tracking_stats_list = self._generate_tracking_stats(counting_summary,zone_analysis, alerts, config, frame_number, stream_info)
210
+
211
+ business_analytics_list = self._generate_business_analytics(counting_summary,zone_analysis, alerts, config, stream_info, is_empty=True)
212
+ summary_list = self._generate_summary(counting_summary,zone_analysis, incidents_list, tracking_stats_list, business_analytics_list, alerts)
213
+
214
+ incidents = incidents_list[0] if incidents_list else {}
215
+ tracking_stats = tracking_stats_list[0] if tracking_stats_list else {}
216
+ business_analytics = business_analytics_list[0] if business_analytics_list else {}
217
+ summary = summary_list[0] if summary_list else {}
218
+ agg_summary = {str(frame_number): {
219
+ "incidents": incidents,
220
+ "tracking_stats": tracking_stats,
221
+ "business_analytics": business_analytics,
222
+ "alerts": alerts,
223
+ "zone_analysis": zone_analysis,
224
+ "human_text": summary}
225
+ }
226
+
227
+ context.mark_completed()
228
+ result = self.create_result(
229
+ data={"agg_summary": agg_summary},
230
+ usecase=self.name,
231
+ category=self.category,
232
+ context=context
233
+ )
234
+ proc_time = time.time() - processing_start
235
+ processing_latency_ms = proc_time * 1000.0
236
+ processing_fps = (1.0 / proc_time) if proc_time > 0 else None
237
+ # Log the performance metrics using the module-level logger
238
+ print("latency in ms:",processing_latency_ms,"| Throughput fps:",processing_fps,"| Frame_Number:",self._total_frame_counter)
239
+ return result
240
+
241
+ def _update_zone_tracking(self, zone_analysis: Dict[str, Dict[str, int]], detections: List[Dict], config: VehicleMonitoringParkingLotConfig) -> Dict[str, Dict[str, Any]]:
242
+ """
243
+ Update zone tracking with current frame data.
244
+
245
+ Args:
246
+ zone_analysis: Current zone analysis results
247
+ detections: List of detections with track IDs
248
+
249
+ Returns:
250
+ Enhanced zone analysis with tracking information
251
+ """
252
+ if not zone_analysis or not config.zone_config or not config.zone_config['zones']:
253
+ return {}
254
+
255
+ enhanced_zone_analysis = {}
256
+ zones = config.zone_config['zones']
257
+
258
+ # Get track to category mapping
259
+ track_to_cat = {det.get('track_id'): det.get('category') for det in detections if det.get('track_id') is not None}
260
+
261
+ # Get current frame track IDs in each zone
262
+ current_frame_zone_tracks = {}
263
+
264
+ # Initialize zone tracking for all zones
265
+ for zone_name in zones.keys():
266
+ current_frame_zone_tracks[zone_name] = set()
267
+ if zone_name not in self._zone_current_track_ids:
268
+ self._zone_current_track_ids[zone_name] = set()
269
+ if zone_name not in self._zone_total_track_ids:
270
+ self._zone_total_track_ids[zone_name] = set()
271
+
272
+ # Check each detection against each zone
273
+ for detection in detections:
274
+ track_id = detection.get("track_id")
275
+ if track_id is None:
276
+ continue
277
+
278
+ # Get detection bbox
279
+ bbox = detection.get("bounding_box", detection.get("bbox"))
280
+ if not bbox:
281
+ continue
282
+
283
+ # Get detection center point
284
+ center_point = get_bbox_bottom25_center(bbox) #get_bbox_center(bbox)
285
+
286
+ # Flag to check if this track is in any zone this frame
287
+ in_any_zone = False
288
+
289
+ # Check which zone this detection is in using actual zone polygons
290
+ for zone_name, zone_polygon in zones.items():
291
+ # Convert polygon points to tuples for point_in_polygon function
292
+ # zone_polygon format: [[x1, y1], [x2, y2], [x3, y3], ...]
293
+ polygon_points = [(point[0], point[1]) for point in zone_polygon]
294
+
295
+ # Check if detection center is inside the zone polygon using ray casting algorithm
296
+ if point_in_polygon(center_point, polygon_points):
297
+ current_frame_zone_tracks[zone_name].add(track_id)
298
+ in_any_zone = True
299
+ if track_id not in self._total_count_list:
300
+ self._total_count_list.append(track_id)
301
+
302
+ # If in any zone, update global current and total (cumulative only if new)
303
+ if in_any_zone:
304
+ cat = track_to_cat.get(track_id)
305
+ if cat:
306
+ # Update current frame global (union across zones)
307
+ self._current_frame_track_ids.setdefault(cat, set()).add(track_id)
308
+
309
+ # Update global cumulative if first time in any zone
310
+ if track_id not in self._tracked_in_zones:
311
+ self._tracked_in_zones.add(track_id)
312
+ self._per_category_total_track_ids.setdefault(cat, set()).add(track_id)
313
+
314
+ # Update zone tracking for each zone
315
+ for zone_name, zone_counts in zone_analysis.items():
316
+ # Get current frame tracks for this zone
317
+ current_tracks = current_frame_zone_tracks.get(zone_name, set())
318
+
319
+ # Update current zone tracks
320
+ self._zone_current_track_ids[zone_name] = current_tracks
321
+
322
+ # Update total zone tracks (accumulate all track IDs that have been in zone)
323
+ self._zone_total_track_ids[zone_name].update(current_tracks)
324
+
325
+ # Update counts
326
+ self._zone_current_counts[zone_name] = len(current_tracks)
327
+ self._zone_total_counts[zone_name] = len(self._zone_total_track_ids[zone_name])
328
+
329
+ # Create enhanced zone analysis
330
+ enhanced_zone_analysis[zone_name] = {
331
+ "current_count": self._zone_current_counts[zone_name],
332
+ "total_count": self._zone_total_counts[zone_name],
333
+ "current_track_ids": list(current_tracks),
334
+ "total_track_ids": list(self._zone_total_track_ids[zone_name]),
335
+ "original_counts": zone_counts # Preserve original zone counts
336
+ }
337
+
338
+ return enhanced_zone_analysis
339
+
340
+ def _normalize_yolo_results(self, data: Any, index_to_category: Optional[Dict[int, str]] = None) -> Any:
341
+ """
342
+ Normalize YOLO-style outputs to internal detection schema:
343
+ - category/category_id: prefer string label using COCO mapping if available
344
+ - confidence: map from 'conf'/'score' to 'confidence'
345
+ - bounding_box: ensure dict with keys (x1,y1,x2,y2) or (xmin,ymin,xmax,ymax)
346
+ - supports list of detections and frame_id -> detections dict
347
+ """
348
+ def to_bbox_dict(d: Dict[str, Any]) -> Dict[str, Any]:
349
+ if "bounding_box" in d and isinstance(d["bounding_box"], dict):
350
+ return d["bounding_box"]
351
+ if "bbox" in d:
352
+ bbox = d["bbox"]
353
+ if isinstance(bbox, dict):
354
+ return bbox
355
+ if isinstance(bbox, (list, tuple)) and len(bbox) >= 4:
356
+ x1, y1, x2, y2 = bbox[0], bbox[1], bbox[2], bbox[3]
357
+ return {"x1": x1, "y1": y1, "x2": x2, "y2": y2}
358
+ if "xyxy" in d and isinstance(d["xyxy"], (list, tuple)) and len(d["xyxy"]) >= 4:
359
+ x1, y1, x2, y2 = d["xyxy"][0], d["xyxy"][1], d["xyxy"][2], d["xyxy"][3]
360
+ return {"x1": x1, "y1": y1, "x2": x2, "y2": y2}
361
+ if "xywh" in d and isinstance(d["xywh"], (list, tuple)) and len(d["xywh"]) >= 4:
362
+ cx, cy, w, h = d["xywh"][0], d["xywh"][1], d["xywh"][2], d["xywh"][3]
363
+ x1, y1, x2, y2 = cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2
364
+ return {"x1": x1, "y1": y1, "x2": x2, "y2": y2}
365
+ return {}
366
+
367
+ def resolve_category(d: Dict[str, Any]) -> Tuple[str, Optional[int]]:
368
+ raw_cls = d.get("category", d.get("category_id", d.get("class", d.get("cls"))))
369
+ label_name = d.get("name")
370
+ if isinstance(raw_cls, int):
371
+ if index_to_category and raw_cls in index_to_category:
372
+ return index_to_category[raw_cls], raw_cls
373
+ return str(raw_cls), raw_cls
374
+ if isinstance(raw_cls, str):
375
+ # Some YOLO exports provide string labels directly
376
+ return raw_cls, None
377
+ if label_name:
378
+ return str(label_name), None
379
+ return "unknown", None
380
+
381
+ def normalize_det(det: Dict[str, Any]) -> Dict[str, Any]:
382
+ category_name, category_id = resolve_category(det)
383
+ confidence = det.get("confidence", det.get("conf", det.get("score", 0.0)))
384
+ bbox = to_bbox_dict(det)
385
+ normalized = {
386
+ "category": category_name,
387
+ "confidence": confidence,
388
+ "bounding_box": bbox,
389
+ }
390
+ if category_id is not None:
391
+ normalized["category_id"] = category_id
392
+ # Preserve optional fields
393
+ for key in ("track_id", "frame_id", "masks", "segmentation"):
394
+ if key in det:
395
+ normalized[key] = det[key]
396
+ return normalized
397
+
398
+ if isinstance(data, list):
399
+ return [normalize_det(d) if isinstance(d, dict) else d for d in data]
400
+ if isinstance(data, dict):
401
+ # Detect tracking style dict: frame_id -> list of detections
402
+ normalized_dict: Dict[str, Any] = {}
403
+ for k, v in data.items():
404
+ if isinstance(v, list):
405
+ normalized_dict[k] = [normalize_det(d) if isinstance(d, dict) else d for d in v]
406
+ elif isinstance(v, dict):
407
+ normalized_dict[k] = normalize_det(v)
408
+ else:
409
+ normalized_dict[k] = v
410
+ return normalized_dict
411
+ return data
412
+
413
+ def _check_alerts(self, summary: dict, zone_analysis: Dict, frame_number: Any, config: VehicleMonitoringParkingLotConfig) -> List[Dict]:
414
+ def get_trend(data, lookback=900, threshold=0.6):
415
+ window = data[-lookback:] if len(data) >= lookback else data
416
+ if len(window) < 2:
417
+ return True
418
+ increasing = 0
419
+ total = 0
420
+ for i in range(1, len(window)):
421
+ if window[i] >= window[i - 1]:
422
+ increasing += 1
423
+ total += 1
424
+ ratio = increasing / total
425
+ return ratio >= threshold
426
+
427
+ frame_key = str(frame_number) if frame_number is not None else "current_frame"
428
+ alerts = []
429
+ total_detections = summary.get("total_count", 0)
430
+ total_counts_dict = summary.get("total_counts", {})
431
+ per_category_count = summary.get("per_category_count", {})
432
+
433
+ if not config.alert_config:
434
+ return alerts
435
+
436
+ if hasattr(config.alert_config, 'count_thresholds') and config.alert_config.count_thresholds:
437
+ for category, threshold in config.alert_config.count_thresholds.items():
438
+ if category == "all" and total_detections > threshold:
439
+ alerts.append({
440
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']),
441
+ "alert_id": f"alert_{category}_{frame_key}",
442
+ "incident_category": self.CASE_TYPE,
443
+ "threshold_level": threshold,
444
+ "ascending": get_trend(self._ascending_alert_list, lookback=900, threshold=0.8),
445
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']),
446
+ getattr(config.alert_config, 'alert_value', ['JSON']))}
447
+ })
448
+ elif category in per_category_count and per_category_count[category] > threshold:
449
+ alerts.append({
450
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']),
451
+ "alert_id": f"alert_{category}_{frame_key}",
452
+ "incident_category": self.CASE_TYPE,
453
+ "threshold_level": threshold,
454
+ "ascending": get_trend(self._ascending_alert_list, lookback=900, threshold=0.8),
455
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']),
456
+ getattr(config.alert_config, 'alert_value', ['JSON']))}
457
+ })
458
+ return alerts
459
+
460
+ def _generate_incidents(self, counting_summary: Dict, zone_analysis: Dict, alerts: List, config: VehicleMonitoringParkingLotConfig,
461
+ frame_number: Optional[int] = None, stream_info: Optional[Dict[str, Any]] = None) -> List[Dict]:
462
+ incidents = []
463
+ total_detections = counting_summary.get("total_count", 0)
464
+ current_timestamp = self._get_current_timestamp_str(stream_info)
465
+ camera_info = self.get_camera_info_from_stream(stream_info)
466
+
467
+ self._ascending_alert_list = self._ascending_alert_list[-900:] if len(self._ascending_alert_list) > 900 else self._ascending_alert_list
468
+
469
+ if total_detections > 0:
470
+ level = "low"
471
+ intensity = 5.0
472
+ start_timestamp = self._get_start_timestamp_str(stream_info)
473
+ if start_timestamp and self.current_incident_end_timestamp == 'N/A':
474
+ self.current_incident_end_timestamp = 'Incident still active'
475
+ elif start_timestamp and self.current_incident_end_timestamp == 'Incident still active':
476
+ if len(self._ascending_alert_list) >= 15 and sum(self._ascending_alert_list[-15:]) / 15 < 1.5:
477
+ self.current_incident_end_timestamp = current_timestamp
478
+ elif self.current_incident_end_timestamp != 'Incident still active' and self.current_incident_end_timestamp != 'N/A':
479
+ self.current_incident_end_timestamp = 'N/A'
480
+
481
+ if config.alert_config and hasattr(config.alert_config, 'count_thresholds') and config.alert_config.count_thresholds:
482
+ threshold = config.alert_config.count_thresholds.get("all", 15)
483
+ intensity = min(10.0, (total_detections / threshold) * 10)
484
+ if intensity >= 9:
485
+ level = "critical"
486
+ self._ascending_alert_list.append(3)
487
+ elif intensity >= 7:
488
+ level = "significant"
489
+ self._ascending_alert_list.append(2)
490
+ elif intensity >= 5:
491
+ level = "medium"
492
+ self._ascending_alert_list.append(1)
493
+ else:
494
+ level = "low"
495
+ self._ascending_alert_list.append(0)
496
+ else:
497
+ if total_detections > 30:
498
+ level = "critical"
499
+ intensity = 10.0
500
+ self._ascending_alert_list.append(3)
501
+ elif total_detections > 25:
502
+ level = "significant"
503
+ intensity = 9.0
504
+ self._ascending_alert_list.append(2)
505
+ elif total_detections > 15:
506
+ level = "medium"
507
+ intensity = 7.0
508
+ self._ascending_alert_list.append(1)
509
+ else:
510
+ level = "low"
511
+ intensity = min(10.0, total_detections / 3.0)
512
+ self._ascending_alert_list.append(0)
513
+
514
+ human_text_lines = [f"VEHICLE INCIDENTS DETECTED @ {current_timestamp}:"]
515
+ human_text_lines.append(f"\tSeverity Level: {(self.CASE_TYPE, level)}")
516
+ human_text = "\n".join(human_text_lines)
517
+
518
+ alert_settings = []
519
+ if config.alert_config and hasattr(config.alert_config, 'alert_type'):
520
+ alert_settings.append({
521
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']),
522
+ "incident_category": self.CASE_TYPE,
523
+ "threshold_level": config.alert_config.count_thresholds if hasattr(config.alert_config, 'count_thresholds') else {},
524
+ "ascending": True,
525
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']),
526
+ getattr(config.alert_config, 'alert_value', ['JSON']))}
527
+ })
528
+
529
+ event = self.create_incident(
530
+ incident_id=f"{self.CASE_TYPE}_{frame_number}",
531
+ incident_type=self.CASE_TYPE,
532
+ severity_level=level,
533
+ human_text=human_text,
534
+ camera_info=camera_info,
535
+ alerts=alerts,
536
+ alert_settings=alert_settings,
537
+ start_time=start_timestamp,
538
+ end_time=self.current_incident_end_timestamp,
539
+ level_settings={"low": 1, "medium": 3, "significant": 4, "critical": 7}
540
+ )
541
+ incidents.append(event)
542
+ else:
543
+ self._ascending_alert_list.append(0)
544
+ incidents.append({})
545
+ return incidents
546
+
547
+ def _generate_tracking_stats(self, counting_summary: Dict, zone_analysis: Dict, alerts: List, config: VehicleMonitoringParkingLotConfig,
548
+ frame_number: Optional[int] = None, stream_info: Optional[Dict[str, Any]] = None) -> List[Dict]:
549
+ camera_info = self.get_camera_info_from_stream(stream_info)
550
+ tracking_stats = []
551
+ total_detections = counting_summary.get("total_count", 0)
552
+ total_counts_dict = counting_summary.get("total_counts", {})
553
+ per_category_count = counting_summary.get("per_category_count", {})
554
+ current_timestamp = self._get_current_timestamp_str(stream_info, precision=False)
555
+ start_timestamp = self._get_start_timestamp_str(stream_info, precision=False)
556
+ high_precision_start_timestamp = self._get_current_timestamp_str(stream_info, precision=True)
557
+ high_precision_reset_timestamp = self._get_start_timestamp_str(stream_info, precision=True)
558
+
559
+ total_counts = [{"category": cat, "count": count} for cat, count in total_counts_dict.items() if count > 0]
560
+ current_counts = [{"category": cat, "count": count} for cat, count in per_category_count.items() if count > 0 or total_detections > 0]
561
+
562
+ detections = []
563
+ for detection in counting_summary.get("detections", []):
564
+ bbox = detection.get("bounding_box", {})
565
+ category = detection.get("category", "vehicle")
566
+ if detection.get("masks"):
567
+ segmentation = detection.get("masks", [])
568
+ detection_obj = self.create_detection_object(category, bbox, segmentation=segmentation)
569
+ elif detection.get("segmentation"):
570
+ segmentation = detection.get("segmentation")
571
+ detection_obj = self.create_detection_object(category, bbox, segmentation=segmentation)
572
+ elif detection.get("mask"):
573
+ segmentation = detection.get("mask")
574
+ detection_obj = self.create_detection_object(category, bbox, segmentation=segmentation)
575
+ else:
576
+ detection_obj = self.create_detection_object(category, bbox)
577
+ detections.append(detection_obj)
578
+
579
+ alert_settings = []
580
+ if config.alert_config and hasattr(config.alert_config, 'alert_type'):
581
+ alert_settings.append({
582
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']),
583
+ "incident_category": self.CASE_TYPE,
584
+ "threshold_level": config.alert_config.count_thresholds if hasattr(config.alert_config, 'count_thresholds') else {},
585
+ "ascending": True,
586
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']),
587
+ getattr(config.alert_config, 'alert_value', ['JSON']))}
588
+ })
589
+
590
+ # Generate human text similar to people_counting format
591
+ human_text_lines = []
592
+ human_text_lines.append(f"CURRENT FRAME @ {current_timestamp}:")
593
+
594
+ # Display current counts - zone-wise or category-wise
595
+ if zone_analysis:
596
+ human_text_lines.append("\t- Vehicles Detected by Zone:")
597
+ for zone_name, zone_data in zone_analysis.items():
598
+ current_count = 0
599
+ if isinstance(zone_data, dict):
600
+ if "current_count" in zone_data:
601
+ current_count = zone_data.get("current_count", 0)
602
+ else:
603
+ counts_dict = zone_data.get("original_counts") if isinstance(zone_data.get("original_counts"), dict) else zone_data
604
+ current_count = counts_dict.get(
605
+ "total",
606
+ sum(v for v in counts_dict.values() if isinstance(v, (int, float)))
607
+ )
608
+ human_text_lines.append(f"\t\t- {zone_name}: {int(current_count)}")
609
+ else:
610
+ human_text_lines.append(f"\t- Vehicles Detected: {total_detections}")
611
+ if per_category_count:
612
+ for cat, count in per_category_count.items():
613
+ if count > 0:
614
+ human_text_lines.append(f"\t\t- {cat}: {count}")
615
+
616
+ human_text_lines.append("")
617
+ # human_text_lines.append(f"TOTAL SINCE @ {start_timestamp}:")
618
+
619
+ # # Display total counts - zone-wise or category-wise
620
+ # if zone_analysis:
621
+ # human_text_lines.append("\t- Total Vehicles by Zone:")
622
+ # for zone_name, zone_data in zone_analysis.items():
623
+ # total_count = 0
624
+ # if isinstance(zone_data, dict):
625
+ # # Prefer the numeric cumulative total if available
626
+ # if "total_count" in zone_data and isinstance(zone_data.get("total_count"), (int, float)):
627
+ # total_count = zone_data.get("total_count", 0)
628
+ # # Fallback: compute from list of total_track_ids if present
629
+ # elif "total_track_ids" in zone_data and isinstance(zone_data.get("total_track_ids"), list):
630
+ # total_count = len(zone_data.get("total_track_ids", []))
631
+ # else:
632
+ # # Last resort: try to sum numeric values present
633
+ # counts_dict = zone_data if isinstance(zone_data, dict) else {}
634
+ # total_count = sum(v for v in counts_dict.values() if isinstance(v, (int, float)))
635
+ # human_text_lines.append(f"\t\t- {zone_name}: {int(total_count)}")
636
+ # else:
637
+ # if total_counts_dict:
638
+ # human_text_lines.append("\t- Total Unique Vehicles:")
639
+ # for cat, count in total_counts_dict.items():
640
+ # if count > 0:
641
+ # human_text_lines.append(f"\t\t- {cat}: {count}")
642
+
643
+ # # Display alerts
644
+ # if alerts:
645
+ # human_text_lines.append("")
646
+ # for alert in alerts:
647
+ # human_text_lines.append(f"Alerts: {alert.get('settings', {})} sent @ {current_timestamp}")
648
+ # else:
649
+ # human_text_lines.append("")
650
+ # human_text_lines.append("Alerts: None")
651
+
652
+ human_text = "\n".join(human_text_lines)
653
+
654
+ reset_settings = [{"interval_type": "daily", "reset_time": {"value": 9, "time_unit": "hour"}}]
655
+ tracking_stat = self.create_tracking_stats(
656
+ total_counts=total_counts,
657
+ current_counts=current_counts,
658
+ detections=detections,
659
+ human_text=human_text,
660
+ camera_info=camera_info,
661
+ alerts=alerts,
662
+ alert_settings=alert_settings,
663
+ reset_settings=reset_settings,
664
+ start_time=high_precision_start_timestamp,
665
+ reset_time=high_precision_reset_timestamp
666
+ )
667
+ tracking_stat['target_categories'] = self.target_categories
668
+ tracking_stats.append(tracking_stat)
669
+ return tracking_stats
670
+
671
+ def _generate_business_analytics(self, counting_summary: Dict, zone_analysis: Dict, alerts: Any, config: VehicleMonitoringParkingLotConfig,
672
+ stream_info: Optional[Dict[str, Any]] = None, is_empty=False) -> List[Dict]:
673
+ if is_empty:
674
+ return []
675
+
676
+ def _generate_summary(self, summary: dict, zone_analysis: Dict, incidents: List, tracking_stats: List, business_analytics: List, alerts: List) -> List[str]:
677
+ """
678
+ Generate a human_text string for the tracking_stat, incident, business analytics and alerts.
679
+ """
680
+ lines = []
681
+ lines.append("Application Name: "+self.CASE_TYPE)
682
+ lines.append("Application Version: "+self.CASE_VERSION)
683
+ if len(incidents) > 0:
684
+ lines.append("Incidents: "+f"\n\t{incidents[0].get('human_text', 'No incidents detected')}")
685
+ if len(tracking_stats) > 0:
686
+ lines.append("Tracking Statistics: "+f"\t{tracking_stats[0].get('human_text', 'No tracking statistics detected')}")
687
+ if len(business_analytics) > 0:
688
+ lines.append("Business Analytics: "+f"\t{business_analytics[0].get('human_text', 'No business analytics detected')}")
689
+
690
+ if len(incidents) == 0 and len(tracking_stats) == 0 and len(business_analytics) == 0:
691
+ lines.append("Summary: "+"No Summary Data")
692
+
693
+ return ["\n".join(lines)]
694
+
695
+ def _get_track_ids_info(self, detections: list) -> Dict[str, Any]:
696
+ frame_track_ids = set()
697
+ for det in detections:
698
+ tid = det.get('track_id')
699
+ if tid is not None:
700
+ frame_track_ids.add(tid)
701
+ total_track_ids = set()
702
+ for s in getattr(self, '_per_category_total_track_ids', {}).values():
703
+ total_track_ids.update(s)
704
+ return {
705
+ "total_count": len(total_track_ids),
706
+ "current_frame_count": len(frame_track_ids),
707
+ "total_unique_track_ids": len(total_track_ids),
708
+ "current_frame_track_ids": list(frame_track_ids),
709
+ "last_update_time": time.time(),
710
+ "total_frames_processed": getattr(self, '_total_frame_counter', 0)
711
+ }
712
+
713
+ def _update_tracking_state(self, detections: list, has_zones: bool = False):
714
+ if not hasattr(self, "_per_category_total_track_ids"):
715
+ self._per_category_total_track_ids = {cat: set() for cat in self.target_categories}
716
+ self._current_frame_track_ids = {cat: set() for cat in self.target_categories}
717
+
718
+ for det in detections:
719
+ cat = det.get("category")
720
+ raw_track_id = det.get("track_id")
721
+ if cat not in self.target_categories or raw_track_id is None:
722
+ continue
723
+ bbox = det.get("bounding_box", det.get("bbox"))
724
+ canonical_id = self._merge_or_register_track(raw_track_id, bbox)
725
+ det["track_id"] = canonical_id
726
+ if not has_zones:
727
+ self._per_category_total_track_ids.setdefault(cat, set()).add(canonical_id)
728
+ # For current frame, add unconditionally here; will be overridden/adjusted if has_zones in _update_zone_tracking
729
+ self._current_frame_track_ids.setdefault(cat, set()).add(canonical_id)
730
+
731
+ def get_total_counts(self):
732
+ return {cat: len(ids) for cat, ids in getattr(self, '_per_category_total_track_ids', {}).items()}
733
+
734
+ def _format_timestamp_for_stream(self, timestamp: float) -> str:
735
+ dt = datetime.fromtimestamp(timestamp, tz=timezone.utc)
736
+ return dt.strftime('%Y:%m:%d %H:%M:%S')
737
+
738
+ def _format_timestamp_for_video(self, timestamp: float) -> str:
739
+ hours = int(timestamp // 3600)
740
+ minutes = int((timestamp % 3600) // 60)
741
+ seconds = round(float(timestamp % 60), 2)
742
+ return f"{hours:02d}:{minutes:02d}:{seconds:.1f}"
743
+
744
+ def _format_timestamp(self, timestamp: Any) -> str:
745
+ """Format a timestamp to match the current timestamp format: YYYY:MM:DD HH:MM:SS.
746
+
747
+ The input can be either:
748
+ 1. A numeric Unix timestamp (``float`` / ``int``) – it will be converted to datetime.
749
+ 2. A string in the format ``YYYY-MM-DD-HH:MM:SS.ffffff UTC``.
750
+
751
+ The returned value will be in the format: YYYY:MM:DD HH:MM:SS (no milliseconds, no UTC suffix).
752
+
753
+ Example
754
+ -------
755
+ >>> self._format_timestamp("2025-10-27-19:31:20.187574 UTC")
756
+ '2025:10:27 19:31:20'
757
+ """
758
+
759
+ # Convert numeric timestamps to datetime first
760
+ if isinstance(timestamp, (int, float)):
761
+ dt = datetime.fromtimestamp(timestamp, timezone.utc)
762
+ return dt.strftime('%Y:%m:%d %H:%M:%S')
763
+
764
+ # Ensure we are working with a string from here on
765
+ if not isinstance(timestamp, str):
766
+ return str(timestamp)
767
+
768
+ # Remove ' UTC' suffix if present
769
+ timestamp_clean = timestamp.replace(' UTC', '').strip()
770
+
771
+ # Remove milliseconds if present (everything after the last dot)
772
+ if '.' in timestamp_clean:
773
+ timestamp_clean = timestamp_clean.split('.')[0]
774
+
775
+ # Parse the timestamp string and convert to desired format
776
+ try:
777
+ # Handle format: YYYY-MM-DD-HH:MM:SS
778
+ if timestamp_clean.count('-') >= 2:
779
+ # Replace first two dashes with colons for date part, third with space
780
+ parts = timestamp_clean.split('-')
781
+ if len(parts) >= 4:
782
+ # parts = ['2025', '10', '27', '19:31:20']
783
+ formatted = f"{parts[0]}:{parts[1]}:{parts[2]} {'-'.join(parts[3:])}"
784
+ return formatted
785
+ except Exception:
786
+ pass
787
+
788
+ # If parsing fails, return the cleaned string as-is
789
+ return timestamp_clean
790
+
791
+ def _get_current_timestamp_str(self, stream_info: Optional[Dict[str, Any]], precision=False, frame_id: Optional[str]=None) -> str:
792
+ """Get formatted current timestamp based on stream type."""
793
+
794
+ if not stream_info:
795
+ return "00:00:00.00"
796
+ if precision:
797
+ if stream_info.get("input_settings", {}).get("start_frame", "na") != "na":
798
+ if frame_id:
799
+ start_time = int(frame_id)/stream_info.get("input_settings", {}).get("original_fps", 30)
800
+ else:
801
+ start_time = stream_info.get("input_settings", {}).get("start_frame", 30)/stream_info.get("input_settings", {}).get("original_fps", 30)
802
+ stream_time_str = self._format_timestamp_for_video(start_time)
803
+
804
+ return self._format_timestamp(stream_info.get("input_settings", {}).get("stream_time", "NA"))
805
+ else:
806
+ return datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
807
+
808
+ if stream_info.get("input_settings", {}).get("start_frame", "na") != "na":
809
+ if frame_id:
810
+ start_time = int(frame_id)/stream_info.get("input_settings", {}).get("original_fps", 30)
811
+ else:
812
+ start_time = stream_info.get("input_settings", {}).get("start_frame", 30)/stream_info.get("input_settings", {}).get("original_fps", 30)
813
+
814
+ stream_time_str = self._format_timestamp_for_video(start_time)
815
+
816
+
817
+ return self._format_timestamp(stream_info.get("input_settings", {}).get("stream_time", "NA"))
818
+ else:
819
+ stream_time_str = stream_info.get("input_settings", {}).get("stream_info", {}).get("stream_time", "")
820
+ if stream_time_str:
821
+ try:
822
+ timestamp_str = stream_time_str.replace(" UTC", "")
823
+ dt = datetime.strptime(timestamp_str, "%Y-%m-%d-%H:%M:%S.%f")
824
+ timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
825
+ return self._format_timestamp_for_stream(timestamp)
826
+ except:
827
+ return self._format_timestamp_for_stream(time.time())
828
+ else:
829
+ return self._format_timestamp_for_stream(time.time())
830
+
831
+ def _get_start_timestamp_str(self, stream_info: Optional[Dict[str, Any]], precision=False) -> str:
832
+ """Get formatted start timestamp for 'TOTAL SINCE' based on stream type."""
833
+ if not stream_info:
834
+ return "00:00:00"
835
+
836
+ if precision:
837
+ if self.start_timer is None:
838
+ candidate = stream_info.get("input_settings", {}).get("stream_time")
839
+ if not candidate or candidate == "NA":
840
+ candidate = datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
841
+ self.start_timer = candidate
842
+ return self._format_timestamp(self.start_timer)
843
+ elif stream_info.get("input_settings", {}).get("start_frame", "na") == 1:
844
+ candidate = stream_info.get("input_settings", {}).get("stream_time")
845
+ if not candidate or candidate == "NA":
846
+ candidate = datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
847
+ self.start_timer = candidate
848
+ return self._format_timestamp(self.start_timer)
849
+ else:
850
+ return self._format_timestamp(self.start_timer)
851
+
852
+ if self.start_timer is None:
853
+ # Prefer direct input_settings.stream_time if available and not NA
854
+ candidate = stream_info.get("input_settings", {}).get("stream_time")
855
+ if not candidate or candidate == "NA":
856
+ # Fallback to nested stream_info.stream_time used by current timestamp path
857
+ stream_time_str = stream_info.get("input_settings", {}).get("stream_info", {}).get("stream_time", "")
858
+ if stream_time_str:
859
+ try:
860
+ timestamp_str = stream_time_str.replace(" UTC", "")
861
+ dt = datetime.strptime(timestamp_str, "%Y-%m-%d-%H:%M:%S.%f")
862
+ self._tracking_start_time = dt.replace(tzinfo=timezone.utc).timestamp()
863
+ candidate = datetime.fromtimestamp(self._tracking_start_time, timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
864
+ except:
865
+ candidate = datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
866
+ else:
867
+ candidate = datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
868
+ self.start_timer = candidate
869
+ return self._format_timestamp(self.start_timer)
870
+ elif stream_info.get("input_settings", {}).get("start_frame", "na") == 1:
871
+ candidate = stream_info.get("input_settings", {}).get("stream_time")
872
+ if not candidate or candidate == "NA":
873
+ stream_time_str = stream_info.get("input_settings", {}).get("stream_info", {}).get("stream_time", "")
874
+ if stream_time_str:
875
+ try:
876
+ timestamp_str = stream_time_str.replace(" UTC", "")
877
+ dt = datetime.strptime(timestamp_str, "%Y-%m-%d-%H:%M:%S.%f")
878
+ ts = dt.replace(tzinfo=timezone.utc).timestamp()
879
+ candidate = datetime.fromtimestamp(ts, timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
880
+ except:
881
+ candidate = datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
882
+ else:
883
+ candidate = datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
884
+ self.start_timer = candidate
885
+ return self._format_timestamp(self.start_timer)
886
+
887
+ else:
888
+ if self.start_timer is not None and self.start_timer != "NA":
889
+ return self._format_timestamp(self.start_timer)
890
+
891
+ if self._tracking_start_time is None:
892
+ stream_time_str = stream_info.get("input_settings", {}).get("stream_info", {}).get("stream_time", "")
893
+ if stream_time_str:
894
+ try:
895
+ timestamp_str = stream_time_str.replace(" UTC", "")
896
+ dt = datetime.strptime(timestamp_str, "%Y-%m-%d-%H:%M:%S.%f")
897
+ self._tracking_start_time = dt.replace(tzinfo=timezone.utc).timestamp()
898
+ except:
899
+ self._tracking_start_time = time.time()
900
+ else:
901
+ self._tracking_start_time = time.time()
902
+
903
+ dt = datetime.fromtimestamp(self._tracking_start_time, tz=timezone.utc)
904
+ dt = dt.replace(minute=0, second=0, microsecond=0)
905
+ return dt.strftime('%Y:%m:%d %H:%M:%S')
906
+
907
+ def _count_categories(self, detections: list, config: VehicleMonitoringParkingLotConfig) -> dict:
908
+ counts = {}
909
+ for det in detections:
910
+ cat = det.get('category', 'unknown')
911
+ counts[cat] = counts.get(cat, 0) + 1
912
+ return {
913
+ "total_count": sum(counts.values()),
914
+ "per_category_count": counts,
915
+ "detections": [
916
+ {
917
+ "bounding_box": det.get("bounding_box"),
918
+ "category": det.get("category"),
919
+ "confidence": det.get("confidence"),
920
+ "track_id": det.get("track_id"),
921
+ "frame_id": det.get("frame_id")
922
+ }
923
+ for det in detections
924
+ ]
925
+ }
926
+
927
+ def _extract_predictions(self, detections: list) -> List[Dict[str, Any]]:
928
+ return [
929
+ {
930
+ "category": det.get("category", "unknown"),
931
+ "confidence": det.get("confidence", 0.0),
932
+ "bounding_box": det.get("bounding_box", {})
933
+ }
934
+ for det in detections
935
+ ]
936
+
937
+ def _compute_iou(self, box1: Any, box2: Any) -> float:
938
+ def _bbox_to_list(bbox):
939
+ if bbox is None:
940
+ return []
941
+ if isinstance(bbox, list):
942
+ return bbox[:4] if len(bbox) >= 4 else []
943
+ if isinstance(bbox, dict):
944
+ if "xmin" in bbox:
945
+ return [bbox["xmin"], bbox["ymin"], bbox["xmax"], bbox["ymax"]]
946
+ if "x1" in bbox:
947
+ return [bbox["x1"], bbox["y1"], bbox["x2"], bbox["y2"]]
948
+ values = [v for v in bbox.values() if isinstance(v, (int, float))]
949
+ return values[:4] if len(values) >= 4 else []
950
+ return []
951
+
952
+ l1 = _bbox_to_list(box1)
953
+ l2 = _bbox_to_list(box2)
954
+ if len(l1) < 4 or len(l2) < 4:
955
+ return 0.0
956
+ x1_min, y1_min, x1_max, y1_max = l1
957
+ x2_min, y2_min, x2_max, y2_max = l2
958
+ x1_min, x1_max = min(x1_min, x1_max), max(x1_min, x1_max)
959
+ y1_min, y1_max = min(y1_min, y1_max), max(y1_min, y1_max)
960
+ x2_min, x2_max = min(x2_min, x2_max), max(x2_min, x2_max)
961
+ y2_min, y2_max = min(y2_min, y2_max), max(y2_min, y2_max)
962
+ inter_x_min = max(x1_min, x2_min)
963
+ inter_y_min = max(y1_min, y2_min)
964
+ inter_x_max = min(x1_max, x2_max)
965
+ inter_y_max = min(y1_max, y2_max)
966
+ inter_w = max(0.0, inter_x_max - inter_x_min)
967
+ inter_h = max(0.0, inter_y_max - inter_y_min)
968
+ inter_area = inter_w * inter_h
969
+ area1 = (x1_max - x1_min) * (y1_max - y1_min)
970
+ area2 = (x2_max - x2_min) * (y2_max - y2_min)
971
+ union_area = area1 + area2 - inter_area
972
+ return (inter_area / union_area) if union_area > 0 else 0.0
973
+
974
+ def _merge_or_register_track(self, raw_id: Any, bbox: Any) -> Any:
975
+ if raw_id is None or bbox is None:
976
+ return raw_id
977
+ now = time.time()
978
+ if raw_id in self._track_aliases:
979
+ canonical_id = self._track_aliases[raw_id]
980
+ track_info = self._canonical_tracks.get(canonical_id)
981
+ if track_info is not None:
982
+ track_info["last_bbox"] = bbox
983
+ track_info["last_update"] = now
984
+ track_info["raw_ids"].add(raw_id)
985
+ return canonical_id
986
+ for canonical_id, info in self._canonical_tracks.items():
987
+ if now - info["last_update"] > self._track_merge_time_window:
988
+ continue
989
+ iou = self._compute_iou(bbox, info["last_bbox"])
990
+ if iou >= self._track_merge_iou_threshold:
991
+ self._track_aliases[raw_id] = canonical_id
992
+ info["last_bbox"] = bbox
993
+ info["last_update"] = now
994
+ info["raw_ids"].add(raw_id)
995
+ return canonical_id
996
+ canonical_id = raw_id
997
+ self._track_aliases[raw_id] = canonical_id
998
+ self._canonical_tracks[canonical_id] = {
999
+ "last_bbox": bbox,
1000
+ "last_update": now,
1001
+ "raw_ids": {raw_id},
1002
+ }
1003
+ return canonical_id
1004
+
1005
+ def _get_tracking_start_time(self) -> str:
1006
+ if self._tracking_start_time is None:
1007
+ return "N/A"
1008
+ return self._format_timestamp(self._tracking_start_time)
1009
+
1010
+ def _set_tracking_start_time(self) -> None:
1011
+ self._tracking_start_time = time.time()