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,750 @@
1
+ from typing import Any, Dict, List, Optional
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
+
22
+ @dataclass
23
+ class FootFallConfig(BaseConfig):
24
+ """Configuration for footfall use case."""
25
+
26
+ # Smoothing configuration
27
+ enable_smoothing: bool = False
28
+ smoothing_algorithm: str = "observability" # "window" or "observability"
29
+ smoothing_window_size: int = 20
30
+ smoothing_cooldown_frames: int = 5
31
+ smoothing_confidence_range_factor: float = 0.5
32
+
33
+ # Zone configuration
34
+ zone_config: Optional[ZoneConfig] = None
35
+
36
+ # Counting parameters
37
+ enable_unique_counting: bool = True
38
+ time_window_minutes: int = 60
39
+
40
+ # Category mapping
41
+ person_categories: List[str] = field(default_factory=lambda: ["person"])
42
+ index_to_category: Optional[Dict[int, str]] = None
43
+
44
+ # Alert configuration
45
+ alert_config: Optional[AlertConfig] = None
46
+
47
+ target_categories: List[str] = field(
48
+ default_factory=lambda: ['person']
49
+ )
50
+
51
+ def validate(self) -> List[str]:
52
+ """Validate people counting configuration."""
53
+ errors = super().validate()
54
+
55
+ if self.time_window_minutes <= 0:
56
+ errors.append("time_window_minutes must be positive")
57
+
58
+ if not self.person_categories:
59
+ errors.append("person_categories cannot be empty")
60
+
61
+ # Validate nested configurations
62
+ if self.zone_config:
63
+ errors.extend(self.zone_config.validate())
64
+
65
+ if self.alert_config:
66
+ errors.extend(self.alert_config.validate())
67
+
68
+ return errors
69
+
70
+
71
+
72
+ class FootFallUseCase(BaseProcessor):
73
+ CATEGORY_DISPLAY = {
74
+ "person": "Person"
75
+ }
76
+
77
+ def __init__(self):
78
+ super().__init__("footfall")
79
+ self.category = "retail"
80
+ self.CASE_TYPE: Optional[str] = 'footfall'
81
+ self.CASE_VERSION: Optional[str] = '1.1'
82
+ self.target_categories = ['person'] #['person', 'people','human','man','woman','male','female']
83
+ self.smoothing_tracker = None
84
+ self.tracker = None
85
+ self._total_frame_counter = 0
86
+ self._global_frame_offset = 0
87
+ self._tracking_start_time = None
88
+ self._track_aliases: Dict[Any, Any] = {}
89
+ self._canonical_tracks: Dict[Any, Dict[str, Any]] = {}
90
+ self._track_merge_iou_threshold: float = 0.05
91
+ self._track_merge_time_window: float = 7.0
92
+ self._ascending_alert_list: List[int] = []
93
+ self.current_incident_end_timestamp: str = "N/A"
94
+ self.start_timer = None
95
+
96
+ def process(self, data: Any, config: ConfigProtocol, context: Optional[ProcessingContext] = None,
97
+ stream_info: Optional[Dict[str, Any]] = None) -> ProcessingResult:
98
+ processing_start = time.time()
99
+ if not isinstance(config, FootFallConfig):
100
+ return self.create_error_result("Invalid config type", usecase=self.name, category=self.category, context=context)
101
+ if context is None:
102
+ context = ProcessingContext()
103
+
104
+ input_format = match_results_structure(data)
105
+ context.input_format = input_format
106
+ context.confidence_threshold = config.confidence_threshold
107
+
108
+ if config.confidence_threshold is not None:
109
+ processed_data = filter_by_confidence(data, config.confidence_threshold)
110
+ self.logger.debug(f"Applied confidence filtering with threshold {config.confidence_threshold}")
111
+ else:
112
+ processed_data = data
113
+ self.logger.debug("Did not apply confidence filtering since no threshold provided")
114
+
115
+ if config.index_to_category:
116
+ processed_data = apply_category_mapping(processed_data, config.index_to_category)
117
+ self.logger.debug("Applied category mapping")
118
+
119
+ if config.target_categories:
120
+ processed_data = [d for d in processed_data if d.get('category') in self.target_categories]
121
+ self.logger.debug("Applied category filtering")
122
+
123
+ # if config.enable_smoothing:
124
+ # if self.smoothing_tracker is None:
125
+ # smoothing_config = BBoxSmoothingConfig(
126
+ # smoothing_algorithm=config.smoothing_algorithm,
127
+ # window_size=config.smoothing_window_size,
128
+ # cooldown_frames=config.smoothing_cooldown_frames,
129
+ # confidence_threshold=config.confidence_threshold,
130
+ # confidence_range_factor=config.smoothing_confidence_range_factor,
131
+ # enable_smoothing=True
132
+ # )
133
+ # self.smoothing_tracker = BBoxSmoothingTracker(smoothing_config)
134
+ # processed_data = bbox_smoothing(processed_data, self.smoothing_tracker.config, self.smoothing_tracker)
135
+
136
+ try:
137
+ from ..advanced_tracker import AdvancedTracker
138
+ from ..advanced_tracker.config import TrackerConfig
139
+ if self.tracker is None:
140
+ tracker_config = TrackerConfig(
141
+ track_high_thresh=0.4,
142
+ track_low_thresh=0.05,
143
+ new_track_thresh=0.3,
144
+ match_thresh=0.8)
145
+ self.tracker = AdvancedTracker(tracker_config)
146
+ self.logger.info("Initialized AdvancedTracker for People Counting")
147
+ processed_data = self.tracker.update(processed_data)
148
+ except Exception as e:
149
+ self.logger.warning(f"AdvancedTracker failed: {e}")
150
+
151
+ self._update_tracking_state(processed_data)
152
+ self._total_frame_counter += 1
153
+
154
+ frame_number = None
155
+ if stream_info:
156
+ input_settings = stream_info.get("input_settings", {})
157
+ start_frame = input_settings.get("start_frame")
158
+ end_frame = input_settings.get("end_frame")
159
+ if start_frame is not None and end_frame is not None and start_frame == end_frame:
160
+ frame_number = start_frame
161
+
162
+ general_counting_summary = calculate_counting_summary(data)
163
+ counting_summary = self._count_categories(processed_data, config)
164
+ total_counts = self.get_total_counts()
165
+ counting_summary['total_counts'] = total_counts
166
+
167
+ alerts = self._check_alerts(counting_summary, frame_number, config)
168
+ predictions = self._extract_predictions(processed_data)
169
+
170
+ incidents_list = self._generate_incidents(counting_summary, alerts, config, frame_number, stream_info)
171
+ tracking_stats_list = self._generate_tracking_stats(counting_summary, alerts, config, frame_number, stream_info)
172
+ business_analytics_list = self._generate_business_analytics(counting_summary, alerts, config, stream_info, is_empty=True)
173
+ summary_list = self._generate_summary(counting_summary, incidents_list, tracking_stats_list, business_analytics_list, alerts)
174
+
175
+ incidents = incidents_list[0] if incidents_list else {}
176
+ tracking_stats = tracking_stats_list[0] if tracking_stats_list else {}
177
+ business_analytics = business_analytics_list[0] if business_analytics_list else {}
178
+ summary = summary_list[0] if summary_list else {}
179
+ agg_summary = {str(frame_number): {
180
+ "incidents": incidents,
181
+ "tracking_stats": tracking_stats,
182
+ "business_analytics": business_analytics,
183
+ "alerts": alerts,
184
+ "human_text": summary}
185
+ }
186
+
187
+ context.mark_completed()
188
+ result = self.create_result(
189
+ data={"agg_summary": agg_summary},
190
+ usecase=self.name,
191
+ category=self.category,
192
+ context=context
193
+ )
194
+ proc_time = time.time() - processing_start
195
+ processing_latency_ms = proc_time * 1000.0
196
+ processing_fps = (1.0 / proc_time) if proc_time > 0 else None
197
+ # Log the performance metrics using the module-level logger
198
+ print("latency in ms:",processing_latency_ms,"| Throughput fps:",processing_fps,"| Frame_Number:",self._total_frame_counter)
199
+ return result
200
+
201
+ def _check_alerts(self, summary: dict, frame_number: Any, config: FootFallConfig) -> List[Dict]:
202
+ def get_trend(data, lookback=900, threshold=0.6):
203
+ window = data[-lookback:] if len(data) >= lookback else data
204
+ if len(window) < 2:
205
+ return True
206
+ increasing = 0
207
+ total = 0
208
+ for i in range(1, len(window)):
209
+ if window[i] >= window[i - 1]:
210
+ increasing += 1
211
+ total += 1
212
+ ratio = increasing / total
213
+ return ratio >= threshold
214
+
215
+ frame_key = str(frame_number) if frame_number is not None else "current_frame"
216
+ alerts = []
217
+ total_detections = summary.get("total_count", 0)
218
+ total_counts_dict = summary.get("total_counts", {})
219
+ per_category_count = summary.get("per_category_count", {})
220
+
221
+ if not config.alert_config:
222
+ return alerts
223
+
224
+ if hasattr(config.alert_config, 'count_thresholds') and config.alert_config.count_thresholds:
225
+ for category, threshold in config.alert_config.count_thresholds.items():
226
+ if category == "all" and total_detections > threshold:
227
+ alerts.append({
228
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']),
229
+ "alert_id": f"alert_{category}_{frame_key}",
230
+ "incident_category": self.CASE_TYPE,
231
+ "threshold_level": threshold,
232
+ "ascending": get_trend(self._ascending_alert_list, lookback=900, threshold=0.8),
233
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']),
234
+ getattr(config.alert_config, 'alert_value', ['JSON']))}
235
+ })
236
+ elif category in per_category_count and per_category_count[category] > threshold:
237
+ alerts.append({
238
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']),
239
+ "alert_id": f"alert_{category}_{frame_key}",
240
+ "incident_category": self.CASE_TYPE,
241
+ "threshold_level": threshold,
242
+ "ascending": get_trend(self._ascending_alert_list, lookback=900, threshold=0.8),
243
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']),
244
+ getattr(config.alert_config, 'alert_value', ['JSON']))}
245
+ })
246
+ return alerts
247
+
248
+ def _generate_incidents(self, counting_summary: Dict, alerts: List, config: FootFallConfig,
249
+ frame_number: Optional[int] = None, stream_info: Optional[Dict[str, Any]] = None) -> List[Dict]:
250
+ incidents = []
251
+ total_detections = counting_summary.get("total_count", 0)
252
+ current_timestamp = self._get_current_timestamp_str(stream_info)
253
+ camera_info = self.get_camera_info_from_stream(stream_info)
254
+
255
+ self._ascending_alert_list = self._ascending_alert_list[-900:] if len(self._ascending_alert_list) > 900 else self._ascending_alert_list
256
+
257
+ if total_detections > 0:
258
+ level = "low"
259
+ intensity = 5.0
260
+ start_timestamp = self._get_start_timestamp_str(stream_info)
261
+ if start_timestamp and self.current_incident_end_timestamp == 'N/A':
262
+ self.current_incident_end_timestamp = 'Incident still active'
263
+ elif start_timestamp and self.current_incident_end_timestamp == 'Incident still active':
264
+ if len(self._ascending_alert_list) >= 15 and sum(self._ascending_alert_list[-15:]) / 15 < 1.5:
265
+ self.current_incident_end_timestamp = current_timestamp
266
+ elif self.current_incident_end_timestamp != 'Incident still active' and self.current_incident_end_timestamp != 'N/A':
267
+ self.current_incident_end_timestamp = 'N/A'
268
+
269
+ if config.alert_config and config.alert_config.count_thresholds:
270
+ threshold = config.alert_config.count_thresholds.get("all", 15)
271
+ intensity = min(10.0, (total_detections / threshold) * 10)
272
+ if intensity >= 9:
273
+ level = "critical"
274
+ self._ascending_alert_list.append(3)
275
+ elif intensity >= 7:
276
+ level = "significant"
277
+ self._ascending_alert_list.append(2)
278
+ elif intensity >= 5:
279
+ level = "medium"
280
+ self._ascending_alert_list.append(1)
281
+ else:
282
+ level = "low"
283
+ self._ascending_alert_list.append(0)
284
+ else:
285
+ if total_detections > 30:
286
+ level = "critical"
287
+ intensity = 10.0
288
+ self._ascending_alert_list.append(3)
289
+ elif total_detections > 25:
290
+ level = "significant"
291
+ intensity = 9.0
292
+ self._ascending_alert_list.append(2)
293
+ elif total_detections > 15:
294
+ level = "medium"
295
+ intensity = 7.0
296
+ self._ascending_alert_list.append(1)
297
+ else:
298
+ level = "low"
299
+ intensity = min(10.0, total_detections / 3.0)
300
+ self._ascending_alert_list.append(0)
301
+
302
+ human_text_lines = [f"COUNTING INCIDENTS DETECTED @ {current_timestamp}:"]
303
+ human_text_lines.append(f"\tSeverity Level: {(self.CASE_TYPE, level)}")
304
+ human_text = "\n".join(human_text_lines)
305
+
306
+ alert_settings = []
307
+ if config.alert_config and hasattr(config.alert_config, 'alert_type'):
308
+ alert_settings.append({
309
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']),
310
+ "incident_category": self.CASE_TYPE,
311
+ "threshold_level": config.alert_config.count_thresholds if hasattr(config.alert_config, 'count_thresholds') else {},
312
+ "ascending": True,
313
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']),
314
+ getattr(config.alert_config, 'alert_value', ['JSON']))}
315
+ })
316
+
317
+ event = self.create_incident(
318
+ incident_id=f"{self.CASE_TYPE}_{frame_number}",
319
+ incident_type=self.CASE_TYPE,
320
+ severity_level=level,
321
+ human_text=human_text,
322
+ camera_info=camera_info,
323
+ alerts=alerts,
324
+ alert_settings=alert_settings,
325
+ start_time=start_timestamp,
326
+ end_time=self.current_incident_end_timestamp,
327
+ level_settings={"low": 1, "medium": 3, "significant": 4, "critical": 7}
328
+ )
329
+ incidents.append(event)
330
+ else:
331
+ self._ascending_alert_list.append(0)
332
+ incidents.append({})
333
+ return incidents
334
+
335
+ def _generate_tracking_stats(self, counting_summary: Dict, alerts: List, config: FootFallConfig,
336
+ frame_number: Optional[int] = None, stream_info: Optional[Dict[str, Any]] = None) -> List[Dict]:
337
+ camera_info = self.get_camera_info_from_stream(stream_info)
338
+ tracking_stats = []
339
+ total_detections = counting_summary.get("total_count", 0)
340
+ total_counts_dict = counting_summary.get("total_counts", {})
341
+ per_category_count = counting_summary.get("per_category_count", {})
342
+ current_timestamp = self._get_current_timestamp_str(stream_info, precision=False)
343
+ start_timestamp = self._get_start_timestamp_str(stream_info, precision=False)
344
+ high_precision_start_timestamp = self._get_current_timestamp_str(stream_info, precision=True)
345
+ high_precision_reset_timestamp = self._get_start_timestamp_str(stream_info, precision=True)
346
+
347
+ total_counts = [{"category": cat, "count": count} for cat, count in total_counts_dict.items() if count > 0]
348
+ current_counts = [{"category": cat, "count": count} for cat, count in per_category_count.items() if count > 0 or total_detections > 0]
349
+
350
+ detections = []
351
+ for detection in counting_summary.get("detections", []):
352
+ bbox = detection.get("bounding_box", {})
353
+ category = detection.get("category", "person")
354
+ if detection.get("masks"):
355
+ segmentation = detection.get("masks", [])
356
+ detection_obj = self.create_detection_object(category, bbox, segmentation=segmentation)
357
+ elif detection.get("segmentation"):
358
+ segmentation = detection.get("segmentation")
359
+ detection_obj = self.create_detection_object(category, bbox, segmentation=segmentation)
360
+ elif detection.get("mask"):
361
+ segmentation = detection.get("mask")
362
+ detection_obj = self.create_detection_object(category, bbox, segmentation=segmentation)
363
+ else:
364
+ detection_obj = self.create_detection_object(category, bbox)
365
+ detections.append(detection_obj)
366
+
367
+ alert_settings = []
368
+ if config.alert_config and hasattr(config.alert_config, 'alert_type'):
369
+ alert_settings.append({
370
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']),
371
+ "incident_category": self.CASE_TYPE,
372
+ "threshold_level": config.alert_config.count_thresholds if hasattr(config.alert_config, 'count_thresholds') else {},
373
+ "ascending": True,
374
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']),
375
+ getattr(config.alert_config, 'alert_value', ['JSON']))}
376
+ })
377
+
378
+ human_text_lines = []
379
+ human_text_lines.append(f"CURRENT FRAME @ {current_timestamp}:")
380
+ for cat, count in per_category_count.items():
381
+ human_text_lines.append(f"\t- People Detected: {count}")
382
+ human_text_lines.append("")
383
+ # human_text_lines.append(f"TOTAL SINCE {start_timestamp}")
384
+ # for cat, count in total_counts_dict.items():
385
+ # if count > 0:
386
+ # human_text_lines.append("")
387
+ # human_text_lines.append(f"\t- Total unique people count: {count}")
388
+ # if alerts:
389
+ # for alert in alerts:
390
+ # human_text_lines.append(f"Alerts: {alert.get('settings', {})} sent @ {current_timestamp}")
391
+ # else:
392
+ # human_text_lines.append("Alerts: None")
393
+ human_text = "\n".join(human_text_lines)
394
+
395
+ reset_settings = [{"interval_type": "daily", "reset_time": {"value": 9, "time_unit": "hour"}}]
396
+ tracking_stat = self.create_tracking_stats(
397
+ total_counts=total_counts,
398
+ current_counts=current_counts,
399
+ detections=detections,
400
+ human_text=human_text,
401
+ camera_info=camera_info,
402
+ alerts=alerts,
403
+ alert_settings=alert_settings,
404
+ reset_settings=reset_settings,
405
+ start_time=high_precision_start_timestamp,
406
+ reset_time=high_precision_reset_timestamp
407
+ )
408
+ tracking_stat['target_categories'] = self.target_categories
409
+ tracking_stats.append(tracking_stat)
410
+ return tracking_stats
411
+
412
+ def _generate_business_analytics(self, counting_summary: Dict, alerts: Any, config: FootFallConfig,
413
+ stream_info: Optional[Dict[str, Any]] = None, is_empty=False) -> List[Dict]:
414
+ if is_empty:
415
+ return []
416
+
417
+ def _generate_summary(self, summary: dict, incidents: List, tracking_stats: List, business_analytics: List, alerts: List) -> List[str]:
418
+ """
419
+ Generate a human_text string for the tracking_stat, incident, business analytics and alerts.
420
+ """
421
+ lines = []
422
+ lines.append("Application Name: "+self.CASE_TYPE)
423
+ lines.append("Application Version: "+self.CASE_VERSION)
424
+ # if len(incidents) > 0:
425
+ # lines.append("Incidents: "+f"\n\t{incidents[0].get('human_text', 'No incidents detected')}")
426
+ if len(tracking_stats) > 0:
427
+ lines.append("Tracking Statistics: "+f"\t{tracking_stats[0].get('human_text', 'No tracking statistics detected')}")
428
+ if len(business_analytics) > 0:
429
+ lines.append("Business Analytics: "+f"\t{business_analytics[0].get('human_text', 'No business analytics detected')}")
430
+
431
+ if len(incidents) == 0 and len(tracking_stats) == 0 and len(business_analytics) == 0:
432
+ lines.append("Summary: "+"No Summary Data")
433
+
434
+ return ["\n".join(lines)]
435
+
436
+ def _get_track_ids_info(self, detections: list) -> Dict[str, Any]:
437
+ frame_track_ids = set()
438
+ for det in detections:
439
+ tid = det.get('track_id')
440
+ if tid is not None:
441
+ frame_track_ids.add(tid)
442
+ total_track_ids = set()
443
+ for s in getattr(self, '_per_category_total_track_ids', {}).values():
444
+ total_track_ids.update(s)
445
+ return {
446
+ "total_count": len(total_track_ids),
447
+ "current_frame_count": len(frame_track_ids),
448
+ "total_unique_track_ids": len(total_track_ids),
449
+ "current_frame_track_ids": list(frame_track_ids),
450
+ "last_update_time": time.time(),
451
+ "total_frames_processed": getattr(self, '_total_frame_counter', 0)
452
+ }
453
+
454
+ def _update_tracking_state(self, detections: list):
455
+ if not hasattr(self, "_per_category_total_track_ids"):
456
+ self._per_category_total_track_ids = {cat: set() for cat in self.target_categories}
457
+ self._current_frame_track_ids = {cat: set() for cat in self.target_categories}
458
+
459
+ for det in detections:
460
+ cat = det.get("category")
461
+ raw_track_id = det.get("track_id")
462
+ if cat not in self.target_categories or raw_track_id is None:
463
+ continue
464
+ bbox = det.get("bounding_box", det.get("bbox"))
465
+ canonical_id = self._merge_or_register_track(raw_track_id, bbox)
466
+ det["track_id"] = canonical_id
467
+ self._per_category_total_track_ids.setdefault(cat, set()).add(canonical_id)
468
+ self._current_frame_track_ids[cat].add(canonical_id)
469
+
470
+ def get_total_counts(self):
471
+ return {cat: len(ids) for cat, ids in getattr(self, '_per_category_total_track_ids', {}).items()}
472
+
473
+ def _format_timestamp_for_stream(self, timestamp: float) -> str:
474
+ dt = datetime.fromtimestamp(timestamp, tz=timezone.utc)
475
+ return dt.strftime('%Y:%m:%d %H:%M:%S')
476
+
477
+ def _format_timestamp_for_video(self, timestamp: float) -> str:
478
+ hours = int(timestamp // 3600)
479
+ minutes = int((timestamp % 3600) // 60)
480
+ seconds = round(float(timestamp % 60), 2)
481
+ return f"{hours:02d}:{minutes:02d}:{seconds:.1f}"
482
+
483
+ def _format_timestamp(self, timestamp: Any) -> str:
484
+ """Format a timestamp to match the current timestamp format: YYYY:MM:DD HH:MM:SS.
485
+
486
+ The input can be either:
487
+ 1. A numeric Unix timestamp (``float`` / ``int``) – it will be converted to datetime.
488
+ 2. A string in the format ``YYYY-MM-DD-HH:MM:SS.ffffff UTC``.
489
+
490
+ The returned value will be in the format: YYYY:MM:DD HH:MM:SS (no milliseconds, no UTC suffix).
491
+
492
+ Example
493
+ -------
494
+ >>> self._format_timestamp("2025-10-27-19:31:20.187574 UTC")
495
+ '2025:10:27 19:31:20'
496
+ """
497
+
498
+ # Convert numeric timestamps to datetime first
499
+ if isinstance(timestamp, (int, float)):
500
+ dt = datetime.fromtimestamp(timestamp, timezone.utc)
501
+ return dt.strftime('%Y:%m:%d %H:%M:%S')
502
+
503
+ # Ensure we are working with a string from here on
504
+ if not isinstance(timestamp, str):
505
+ return str(timestamp)
506
+
507
+ # Remove ' UTC' suffix if present
508
+ timestamp_clean = timestamp.replace(' UTC', '').strip()
509
+
510
+ # Remove milliseconds if present (everything after the last dot)
511
+ if '.' in timestamp_clean:
512
+ timestamp_clean = timestamp_clean.split('.')[0]
513
+
514
+ # Parse the timestamp string and convert to desired format
515
+ try:
516
+ # Handle format: YYYY-MM-DD-HH:MM:SS
517
+ if timestamp_clean.count('-') >= 2:
518
+ # Replace first two dashes with colons for date part, third with space
519
+ parts = timestamp_clean.split('-')
520
+ if len(parts) >= 4:
521
+ # parts = ['2025', '10', '27', '19:31:20']
522
+ formatted = f"{parts[0]}:{parts[1]}:{parts[2]} {'-'.join(parts[3:])}"
523
+ return formatted
524
+ except Exception:
525
+ pass
526
+
527
+ # If parsing fails, return the cleaned string as-is
528
+ return timestamp_clean
529
+
530
+ def _get_current_timestamp_str(self, stream_info: Optional[Dict[str, Any]], precision=False, frame_id: Optional[str]=None) -> str:
531
+ """Get formatted current timestamp based on stream type."""
532
+
533
+ if not stream_info:
534
+ return "00:00:00.00"
535
+ if precision:
536
+ if stream_info.get("input_settings", {}).get("start_frame", "na") != "na":
537
+ if frame_id:
538
+ start_time = int(frame_id)/stream_info.get("input_settings", {}).get("original_fps", 30)
539
+ else:
540
+ start_time = stream_info.get("input_settings", {}).get("start_frame", 30)/stream_info.get("input_settings", {}).get("original_fps", 30)
541
+ stream_time_str = self._format_timestamp_for_video(start_time)
542
+
543
+ return self._format_timestamp(stream_info.get("input_settings", {}).get("stream_time", "NA"))
544
+ else:
545
+ return datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
546
+
547
+ if stream_info.get("input_settings", {}).get("start_frame", "na") != "na":
548
+ if frame_id:
549
+ start_time = int(frame_id)/stream_info.get("input_settings", {}).get("original_fps", 30)
550
+ else:
551
+ start_time = stream_info.get("input_settings", {}).get("start_frame", 30)/stream_info.get("input_settings", {}).get("original_fps", 30)
552
+
553
+ stream_time_str = self._format_timestamp_for_video(start_time)
554
+
555
+
556
+ return self._format_timestamp(stream_info.get("input_settings", {}).get("stream_time", "NA"))
557
+ else:
558
+ stream_time_str = stream_info.get("input_settings", {}).get("stream_info", {}).get("stream_time", "")
559
+ if stream_time_str:
560
+ try:
561
+ timestamp_str = stream_time_str.replace(" UTC", "")
562
+ dt = datetime.strptime(timestamp_str, "%Y-%m-%d-%H:%M:%S.%f")
563
+ timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
564
+ return self._format_timestamp_for_stream(timestamp)
565
+ except:
566
+ return self._format_timestamp_for_stream(time.time())
567
+ else:
568
+ return self._format_timestamp_for_stream(time.time())
569
+
570
+ def _get_start_timestamp_str(self, stream_info: Optional[Dict[str, Any]], precision=False) -> str:
571
+ """Get formatted start timestamp for 'TOTAL SINCE' based on stream type."""
572
+ if not stream_info:
573
+ return "00:00:00"
574
+
575
+ if precision:
576
+ if self.start_timer is None:
577
+ candidate = stream_info.get("input_settings", {}).get("stream_time")
578
+ if not candidate or candidate == "NA":
579
+ candidate = datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
580
+ self.start_timer = candidate
581
+ return self._format_timestamp(self.start_timer)
582
+ elif stream_info.get("input_settings", {}).get("start_frame", "na") == 1:
583
+ candidate = stream_info.get("input_settings", {}).get("stream_time")
584
+ if not candidate or candidate == "NA":
585
+ candidate = datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
586
+ self.start_timer = candidate
587
+ return self._format_timestamp(self.start_timer)
588
+ else:
589
+ return self._format_timestamp(self.start_timer)
590
+
591
+ if self.start_timer is None:
592
+ # Prefer direct input_settings.stream_time if available and not NA
593
+ candidate = stream_info.get("input_settings", {}).get("stream_time")
594
+ if not candidate or candidate == "NA":
595
+ # Fallback to nested stream_info.stream_time used by current timestamp path
596
+ stream_time_str = stream_info.get("input_settings", {}).get("stream_info", {}).get("stream_time", "")
597
+ if stream_time_str:
598
+ try:
599
+ timestamp_str = stream_time_str.replace(" UTC", "")
600
+ dt = datetime.strptime(timestamp_str, "%Y-%m-%d-%H:%M:%S.%f")
601
+ self._tracking_start_time = dt.replace(tzinfo=timezone.utc).timestamp()
602
+ candidate = datetime.fromtimestamp(self._tracking_start_time, timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
603
+ except:
604
+ candidate = datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
605
+ else:
606
+ candidate = datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
607
+ self.start_timer = candidate
608
+ return self._format_timestamp(self.start_timer)
609
+ elif stream_info.get("input_settings", {}).get("start_frame", "na") == 1:
610
+ candidate = stream_info.get("input_settings", {}).get("stream_time")
611
+ if not candidate or candidate == "NA":
612
+ stream_time_str = stream_info.get("input_settings", {}).get("stream_info", {}).get("stream_time", "")
613
+ if stream_time_str:
614
+ try:
615
+ timestamp_str = stream_time_str.replace(" UTC", "")
616
+ dt = datetime.strptime(timestamp_str, "%Y-%m-%d-%H:%M:%S.%f")
617
+ ts = dt.replace(tzinfo=timezone.utc).timestamp()
618
+ candidate = datetime.fromtimestamp(ts, timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
619
+ except:
620
+ candidate = datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
621
+ else:
622
+ candidate = datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
623
+ self.start_timer = candidate
624
+ return self._format_timestamp(self.start_timer)
625
+
626
+ else:
627
+ if self.start_timer is not None and self.start_timer != "NA":
628
+ return self._format_timestamp(self.start_timer)
629
+
630
+ if self._tracking_start_time is None:
631
+ stream_time_str = stream_info.get("input_settings", {}).get("stream_info", {}).get("stream_time", "")
632
+ if stream_time_str:
633
+ try:
634
+ timestamp_str = stream_time_str.replace(" UTC", "")
635
+ dt = datetime.strptime(timestamp_str, "%Y-%m-%d-%H:%M:%S.%f")
636
+ self._tracking_start_time = dt.replace(tzinfo=timezone.utc).timestamp()
637
+ except:
638
+ self._tracking_start_time = time.time()
639
+ else:
640
+ self._tracking_start_time = time.time()
641
+
642
+ dt = datetime.fromtimestamp(self._tracking_start_time, tz=timezone.utc)
643
+ dt = dt.replace(minute=0, second=0, microsecond=0)
644
+ return dt.strftime('%Y:%m:%d %H:%M:%S')
645
+
646
+ def _count_categories(self, detections: list, config: FootFallConfig) -> dict:
647
+ counts = {}
648
+ for det in detections:
649
+ cat = det.get('category', 'unknown')
650
+ counts[cat] = counts.get(cat, 0) + 1
651
+ return {
652
+ "total_count": sum(counts.values()),
653
+ "per_category_count": counts,
654
+ "detections": [
655
+ {
656
+ "bounding_box": det.get("bounding_box"),
657
+ "category": det.get("category"),
658
+ "confidence": det.get("confidence"),
659
+ "track_id": det.get("track_id"),
660
+ "frame_id": det.get("frame_id")
661
+ }
662
+ for det in detections
663
+ ]
664
+ }
665
+
666
+ def _extract_predictions(self, detections: list) -> List[Dict[str, Any]]:
667
+ return [
668
+ {
669
+ "category": det.get("category", "unknown"),
670
+ "confidence": det.get("confidence", 0.0),
671
+ "bounding_box": det.get("bounding_box", {})
672
+ }
673
+ for det in detections
674
+ ]
675
+
676
+ def _compute_iou(self, box1: Any, box2: Any) -> float:
677
+ def _bbox_to_list(bbox):
678
+ if bbox is None:
679
+ return []
680
+ if isinstance(bbox, list):
681
+ return bbox[:4] if len(bbox) >= 4 else []
682
+ if isinstance(bbox, dict):
683
+ if "xmin" in bbox:
684
+ return [bbox["xmin"], bbox["ymin"], bbox["xmax"], bbox["ymax"]]
685
+ if "x1" in bbox:
686
+ return [bbox["x1"], bbox["y1"], bbox["x2"], bbox["y2"]]
687
+ values = [v for v in bbox.values() if isinstance(v, (int, float))]
688
+ return values[:4] if len(values) >= 4 else []
689
+ return []
690
+
691
+ l1 = _bbox_to_list(box1)
692
+ l2 = _bbox_to_list(box2)
693
+ if len(l1) < 4 or len(l2) < 4:
694
+ return 0.0
695
+ x1_min, y1_min, x1_max, y1_max = l1
696
+ x2_min, y2_min, x2_max, y2_max = l2
697
+ x1_min, x1_max = min(x1_min, x1_max), max(x1_min, x1_max)
698
+ y1_min, y1_max = min(y1_min, y1_max), max(y1_min, y1_max)
699
+ x2_min, x2_max = min(x2_min, x2_max), max(x2_min, x2_max)
700
+ y2_min, y2_max = min(y2_min, y2_max), max(y2_min, y2_max)
701
+ inter_x_min = max(x1_min, x2_min)
702
+ inter_y_min = max(y1_min, y2_min)
703
+ inter_x_max = min(x1_max, x2_max)
704
+ inter_y_max = min(y1_max, y2_max)
705
+ inter_w = max(0.0, inter_x_max - inter_x_min)
706
+ inter_h = max(0.0, inter_y_max - inter_y_min)
707
+ inter_area = inter_w * inter_h
708
+ area1 = (x1_max - x1_min) * (y1_max - y1_min)
709
+ area2 = (x2_max - x2_min) * (y2_max - y2_min)
710
+ union_area = area1 + area2 - inter_area
711
+ return (inter_area / union_area) if union_area > 0 else 0.0
712
+
713
+ def _merge_or_register_track(self, raw_id: Any, bbox: Any) -> Any:
714
+ if raw_id is None or bbox is None:
715
+ return raw_id
716
+ now = time.time()
717
+ if raw_id in self._track_aliases:
718
+ canonical_id = self._track_aliases[raw_id]
719
+ track_info = self._canonical_tracks.get(canonical_id)
720
+ if track_info is not None:
721
+ track_info["last_bbox"] = bbox
722
+ track_info["last_update"] = now
723
+ track_info["raw_ids"].add(raw_id)
724
+ return canonical_id
725
+ for canonical_id, info in self._canonical_tracks.items():
726
+ if now - info["last_update"] > self._track_merge_time_window:
727
+ continue
728
+ iou = self._compute_iou(bbox, info["last_bbox"])
729
+ if iou >= self._track_merge_iou_threshold:
730
+ self._track_aliases[raw_id] = canonical_id
731
+ info["last_bbox"] = bbox
732
+ info["last_update"] = now
733
+ info["raw_ids"].add(raw_id)
734
+ return canonical_id
735
+ canonical_id = raw_id
736
+ self._track_aliases[raw_id] = canonical_id
737
+ self._canonical_tracks[canonical_id] = {
738
+ "last_bbox": bbox,
739
+ "last_update": now,
740
+ "raw_ids": {raw_id},
741
+ }
742
+ return canonical_id
743
+
744
+ def _get_tracking_start_time(self) -> str:
745
+ if self._tracking_start_time is None:
746
+ return "N/A"
747
+ return self._format_timestamp(self._tracking_start_time)
748
+
749
+ def _set_tracking_start_time(self) -> None:
750
+ self._tracking_start_time = time.time()