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