matrice 1.0.99217__py3-none-any.whl → 1.0.99219__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,835 @@
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
+
23
+ @dataclass
24
+ class GasLeakConfig(BaseConfig):
25
+ """Configuration for gas leak detection use case."""
26
+ # Smoothing configuration
27
+ enable_smoothing: bool = True
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
+ #confidence thresholds
34
+ confidence_threshold: float = 0.3
35
+
36
+ usecase_categories: List[str] = field(
37
+ default_factory=lambda: ['leak']
38
+ )
39
+
40
+ target_categories: List[str] = field(
41
+ default_factory=lambda: ['leak']
42
+ )
43
+
44
+ alert_config: Optional[AlertConfig] = None
45
+
46
+ index_to_category: Optional[Dict[int, str]] = field(
47
+ default_factory=lambda: {
48
+ 0: "leak",
49
+ }
50
+ )
51
+
52
+
53
+ class GasLeakUseCase(BaseProcessor):
54
+
55
+
56
+ def __init__(self):
57
+ super().__init__("gas_leak_detection")
58
+ self.category = "oil_gas"
59
+
60
+ self.CASE_TYPE: Optional[str] = 'gas_leak_detection'
61
+ self.CASE_VERSION: Optional[str] = '1.2'
62
+ # List of categories to track
63
+ self.target_categories = ['leak']
64
+
65
+
66
+ # Initialize smoothing tracker
67
+ self.smoothing_tracker = None
68
+
69
+ # Initialize advanced tracker (will be created on first use)
70
+ self.tracker = None
71
+ # Initialize tracking state variables
72
+ self._total_frame_counter = 0
73
+ self._global_frame_offset = 0
74
+
75
+ # Track start time for "TOTAL SINCE" calculation
76
+ self._tracking_start_time = None
77
+
78
+ self._track_aliases: Dict[Any, Any] = {}
79
+ self._canonical_tracks: Dict[Any, Dict[str, Any]] = {}
80
+ # Tunable parameters – adjust if necessary for specific scenarios
81
+ self._track_merge_iou_threshold: float = 0.05 # IoU ≥ 0.05 →
82
+ self._track_merge_time_window: float = 7.0 # seconds within which to merge
83
+
84
+ self._ascending_alert_list: List[int] = []
85
+ self.current_incident_end_timestamp: str = "N/A"
86
+
87
+
88
+ def process(self, data: Any, config: ConfigProtocol, context: Optional[ProcessingContext] = None,
89
+ stream_info: Optional[Dict[str, Any]] = None) -> ProcessingResult:
90
+ """
91
+ Main entry point for post-processing.
92
+ Applies category mapping, smoothing, counting, alerting, and summary generation.
93
+ Returns a ProcessingResult with all relevant outputs.
94
+ """
95
+ start_time = time.time()
96
+ # Ensure config is correct type
97
+ if not isinstance(config, GasLeakConfig):
98
+ return self.create_error_result("Invalid config type", usecase=self.name, category=self.category,
99
+ context=context)
100
+ if context is None:
101
+ context = ProcessingContext()
102
+
103
+ # Detect input format and store in context
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
+
114
+ self.logger.debug(f"Did not apply confidence filtering with threshold since nothing was provided")
115
+
116
+ # Step 2: Apply category mapping if provided
117
+ if config.index_to_category:
118
+ processed_data = apply_category_mapping(processed_data, config.index_to_category)
119
+ self.logger.debug("Applied category mapping")
120
+
121
+ if config.target_categories:
122
+ processed_data = [d for d in processed_data if d.get('category') in self.target_categories]
123
+ self.logger.debug(f"Applied category filtering")
124
+
125
+ # Apply bbox smoothing if enabled
126
+ if config.enable_smoothing:
127
+ if self.smoothing_tracker is None:
128
+ smoothing_config = BBoxSmoothingConfig(
129
+ smoothing_algorithm=config.smoothing_algorithm,
130
+ window_size=config.smoothing_window_size,
131
+ cooldown_frames=config.smoothing_cooldown_frames,
132
+ confidence_threshold=config.confidence_threshold, # Use mask threshold as default
133
+ confidence_range_factor=config.smoothing_confidence_range_factor,
134
+ enable_smoothing=True
135
+ )
136
+ self.smoothing_tracker = BBoxSmoothingTracker(smoothing_config)
137
+ processed_data = bbox_smoothing(processed_data, self.smoothing_tracker.config, self.smoothing_tracker)
138
+
139
+ # Advanced tracking (BYTETracker-like)
140
+ try:
141
+ from ..advanced_tracker import AdvancedTracker
142
+ from ..advanced_tracker.config import TrackerConfig
143
+
144
+ # Create tracker instance if it doesn't exist (preserves state across frames)
145
+ if self.tracker is None:
146
+ # Configure tracker thresholds based on the use-case confidence threshold so that
147
+ # low-confidence detections (e.g. < 0.7) can still be initialised as tracks when
148
+ # the user passes a lower `confidence_threshold` in the post-processing config.
149
+ if config.confidence_threshold is not None:
150
+ tracker_config = TrackerConfig(
151
+ track_high_thresh=float(config.confidence_threshold),
152
+ # Allow even lower detections to participate in secondary association
153
+ track_low_thresh=max(0.05, float(config.confidence_threshold) / 2),
154
+ new_track_thresh=float(config.confidence_threshold)
155
+ )
156
+ else:
157
+ tracker_config = TrackerConfig()
158
+ self.tracker = AdvancedTracker(tracker_config)
159
+ self.logger.info(
160
+ "Initialized AdvancedTracker for Monitoring and tracking with thresholds: "
161
+ f"high={tracker_config.track_high_thresh}, "
162
+ f"low={tracker_config.track_low_thresh}, "
163
+ f"new={tracker_config.new_track_thresh}"
164
+ )
165
+
166
+ # The tracker expects the data in the same format as input
167
+ # It will add track_id and frame_id to each detection
168
+ processed_data = self.tracker.update(processed_data)
169
+
170
+ except Exception as e:
171
+ # If advanced tracker fails, fallback to unsmoothed detections
172
+ self.logger.warning(f"AdvancedTracker failed: {e}")
173
+
174
+ # Update tracking state for total count per label
175
+ self._update_tracking_state(processed_data)
176
+
177
+ # Update frame counter
178
+ self._total_frame_counter += 1
179
+
180
+ # Extract frame information from stream_info
181
+ frame_number = None
182
+ if stream_info:
183
+ input_settings = stream_info.get("input_settings", {})
184
+ start_frame = input_settings.get("start_frame")
185
+ end_frame = input_settings.get("end_frame")
186
+ # If start and end frame are the same, it's a single frame
187
+ if start_frame is not None and end_frame is not None and start_frame == end_frame:
188
+ frame_number = start_frame
189
+
190
+ # Compute summaries and alerts
191
+ general_counting_summary = calculate_counting_summary(data)
192
+ counting_summary = self._count_categories(processed_data, config)
193
+ # Add total unique counts after tracking using only local state
194
+ total_counts = self.get_total_counts()
195
+ counting_summary['total_counts'] = total_counts
196
+
197
+ alerts = self._check_alerts(counting_summary, frame_number, config)
198
+ predictions = self._extract_predictions(processed_data)
199
+
200
+ # Step: Generate structured incidents, tracking stats and business analytics with frame-based keys
201
+ incidents_list = self._generate_incidents(counting_summary, alerts, config, frame_number, stream_info)
202
+ tracking_stats_list = self._generate_tracking_stats(counting_summary, alerts, config, frame_number, stream_info)
203
+ business_analytics_list = self._generate_business_analytics(counting_summary, alerts, config, stream_info, is_empty=True)
204
+ summary_list = self._generate_summary(counting_summary, incidents_list, tracking_stats_list, business_analytics_list, alerts)
205
+
206
+ # Extract frame-based dictionaries from the lists
207
+ incidents = incidents_list[0] if incidents_list else {}
208
+ tracking_stats = tracking_stats_list[0] if tracking_stats_list else {}
209
+ business_analytics = business_analytics_list[0] if business_analytics_list else {}
210
+ summary = summary_list[0] if summary_list else {}
211
+ agg_summary = {str(frame_number): {
212
+ "incidents": incidents,
213
+ "tracking_stats": tracking_stats,
214
+ "business_analytics": business_analytics,
215
+ "alerts": alerts,
216
+ "human_text": summary}
217
+ }
218
+
219
+
220
+ context.mark_completed()
221
+
222
+ # Build result object following the new pattern
223
+
224
+ result = self.create_result(
225
+ data={"agg_summary": agg_summary},
226
+ usecase=self.name,
227
+ category=self.category,
228
+ context=context
229
+ )
230
+
231
+ return result
232
+
233
+ def _check_alerts(self, summary: dict, frame_number:Any, config: GasLeakConfig) -> List[Dict]:
234
+ """
235
+ Check if any alert thresholds are exceeded and return alert dicts.
236
+ """
237
+ def get_trend(data, lookback=900, threshold=0.6):
238
+ '''
239
+ Determine if the trend is ascending or descending based on actual value progression.
240
+ Now works with values 0,1,2,3 (not just binary).
241
+ '''
242
+ window = data[-lookback:] if len(data) >= lookback else data
243
+ if len(window) < 2:
244
+ return True # not enough data to determine trend
245
+ increasing = 0
246
+ total = 0
247
+ for i in range(1, len(window)):
248
+ if window[i] >= window[i - 1]:
249
+ increasing += 1
250
+ total += 1
251
+ ratio = increasing / total
252
+ if ratio >= threshold:
253
+ return True
254
+ elif ratio <= (1 - threshold):
255
+ return False
256
+
257
+ frame_key = str(frame_number) if frame_number is not None else "current_frame"
258
+ alerts = []
259
+ total_detections = summary.get("total_count", 0) #CURRENT combined total count of all classes
260
+ total_counts_dict = summary.get("total_counts", {}) #TOTAL cumulative counts per class
261
+ cumulative_total = sum(total_counts_dict.values()) if total_counts_dict else 0 #TOTAL combined cumulative count
262
+ per_category_count = summary.get("per_category_count", {}) #CURRENT count per class
263
+
264
+ if not config.alert_config:
265
+ return alerts
266
+
267
+ total = summary.get("total_count", 0)
268
+ #self._ascending_alert_list
269
+ if hasattr(config.alert_config, 'count_thresholds') and config.alert_config.count_thresholds:
270
+
271
+ for category, threshold in config.alert_config.count_thresholds.items():
272
+ if category == "all" and total > threshold:
273
+
274
+ alerts.append({
275
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
276
+ "alert_id": "alert_"+category+'_'+frame_key,
277
+ "incident_category": self.CASE_TYPE,
278
+ "threshold_level": threshold,
279
+ "ascending": get_trend(self._ascending_alert_list, lookback=900, threshold=0.8),
280
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
281
+ getattr(config.alert_config, 'alert_value', ['JSON']) if hasattr(config.alert_config, 'alert_value') else ['JSON'])
282
+ }
283
+ })
284
+ elif category in summary.get("per_category_count", {}):
285
+ count = summary.get("per_category_count", {})[category]
286
+ if count > threshold: # Fixed logic: alert when EXCEEDING threshold
287
+ alerts.append({
288
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
289
+ "alert_id": "alert_"+category+'_'+frame_key,
290
+ "incident_category": self.CASE_TYPE,
291
+ "threshold_level": threshold,
292
+ "ascending": get_trend(self._ascending_alert_list, lookback=900, threshold=0.8),
293
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
294
+ getattr(config.alert_config, 'alert_value', ['JSON']) if hasattr(config.alert_config, 'alert_value') else ['JSON'])
295
+ }
296
+ })
297
+ else:
298
+ pass
299
+ return alerts
300
+
301
+ def _generate_incidents(self, counting_summary: Dict, alerts: List, config: GasLeakConfig,
302
+ frame_number: Optional[int] = None, stream_info: Optional[Dict[str, Any]] = None) -> List[
303
+ Dict]:
304
+ """Generate structured incidents for the output format with frame-based keys."""
305
+
306
+ incidents = []
307
+ total_detections = counting_summary.get("total_count", 0)
308
+ current_timestamp = self._get_current_timestamp_str(stream_info)
309
+ camera_info = self.get_camera_info_from_stream(stream_info)
310
+
311
+ self._ascending_alert_list = self._ascending_alert_list[-900:] if len(self._ascending_alert_list) > 900 else self._ascending_alert_list
312
+
313
+ if total_detections > 0:
314
+ # Determine event level based on thresholds
315
+ level = "low"
316
+ intensity = 5.0
317
+ start_timestamp = self._get_start_timestamp_str(stream_info)
318
+ if start_timestamp and self.current_incident_end_timestamp=='N/A':
319
+ self.current_incident_end_timestamp = 'Incident still active'
320
+ elif start_timestamp and self.current_incident_end_timestamp=='Incident still active':
321
+ if len(self._ascending_alert_list) >= 15 and sum(self._ascending_alert_list[-15:]) / 15 < 1.5:
322
+ self.current_incident_end_timestamp = current_timestamp
323
+ elif self.current_incident_end_timestamp!='Incident still active' and self.current_incident_end_timestamp!='N/A':
324
+ self.current_incident_end_timestamp = 'N/A'
325
+
326
+ if config.alert_config and config.alert_config.count_thresholds:
327
+ threshold = config.alert_config.count_thresholds.get("all", 15)
328
+ intensity = min(10.0, (total_detections / threshold) * 10)
329
+
330
+ if intensity >= 9:
331
+ level = "critical"
332
+ self._ascending_alert_list.append(3)
333
+ elif intensity >= 7:
334
+ level = "significant"
335
+ self._ascending_alert_list.append(2)
336
+ elif intensity >= 5:
337
+ level = "medium"
338
+ self._ascending_alert_list.append(1)
339
+ else:
340
+ level = "low"
341
+ self._ascending_alert_list.append(0)
342
+ else:
343
+ if total_detections > 30:
344
+ level = "critical"
345
+ intensity = 10.0
346
+ self._ascending_alert_list.append(3)
347
+ elif total_detections > 25:
348
+ level = "significant"
349
+ intensity = 9.0
350
+ self._ascending_alert_list.append(2)
351
+ elif total_detections > 15:
352
+ level = "medium"
353
+ intensity = 7.0
354
+ self._ascending_alert_list.append(1)
355
+ else:
356
+ level = "low"
357
+ intensity = min(10.0, total_detections / 3.0)
358
+ self._ascending_alert_list.append(0)
359
+
360
+ # Generate human text in new format
361
+ human_text_lines = [f"INCIDENTS DETECTED @ {current_timestamp}:"]
362
+ human_text_lines.append(f"\tSeverity Level: {(self.CASE_TYPE,level)}")
363
+ human_text = "\n".join(human_text_lines)
364
+
365
+ alert_settings=[]
366
+ if config.alert_config and hasattr(config.alert_config, 'alert_type'):
367
+ alert_settings.append({
368
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
369
+ "incident_category": self.CASE_TYPE,
370
+ "threshold_level": config.alert_config.count_thresholds if hasattr(config.alert_config, 'count_thresholds') else {},
371
+ "ascending": True,
372
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
373
+ getattr(config.alert_config, 'alert_value', ['JSON']) if hasattr(config.alert_config, 'alert_value') else ['JSON'])
374
+ }
375
+ })
376
+
377
+ event= self.create_incident(incident_id=self.CASE_TYPE+'_'+str(frame_number), incident_type=self.CASE_TYPE,
378
+ severity_level=level, human_text=human_text, camera_info=camera_info, alerts=alerts, alert_settings=alert_settings,
379
+ start_time=start_timestamp, end_time=self.current_incident_end_timestamp,
380
+ level_settings= {"low": 1, "medium": 3, "significant":4, "critical": 7})
381
+ incidents.append(event)
382
+
383
+ else:
384
+ self._ascending_alert_list.append(0)
385
+ incidents.append({})
386
+
387
+ return incidents
388
+ def _generate_tracking_stats(
389
+ self,
390
+ counting_summary: Dict,
391
+ alerts: List,
392
+ config: GasLeakConfig,
393
+ frame_number: Optional[int] = None,
394
+ stream_info: Optional[Dict[str, Any]] = None
395
+ ) -> List[Dict]:
396
+ """Generate structured tracking stats matching eg.json format."""
397
+ camera_info = self.get_camera_info_from_stream(stream_info)
398
+
399
+ # frame_key = str(frame_number) if frame_number is not None else "current_frame"
400
+ # tracking_stats = [{frame_key: []}]
401
+ # frame_tracking_stats = tracking_stats[0][frame_key]
402
+ tracking_stats = []
403
+
404
+ total_detections = counting_summary.get("total_count", 0) #CURRENT total count of all classes
405
+ total_counts_dict = counting_summary.get("total_counts", {}) #TOTAL cumulative counts per class
406
+ cumulative_total = sum(total_counts_dict.values()) if total_counts_dict else 0 #TOTAL combined cumulative count
407
+ per_category_count = counting_summary.get("per_category_count", {}) #CURRENT count per class
408
+
409
+ current_timestamp = self._get_current_timestamp_str(stream_info, precision=False)
410
+ start_timestamp = self._get_start_timestamp_str(stream_info, precision=False)
411
+
412
+ # Create high precision timestamps for input_timestamp and reset_timestamp
413
+ high_precision_start_timestamp = self._get_current_timestamp_str(stream_info, precision=True)
414
+ high_precision_reset_timestamp = self._get_start_timestamp_str(stream_info, precision=True)
415
+
416
+
417
+ # Build total_counts array in expected format
418
+ total_counts = []
419
+ for cat, count in total_counts_dict.items():
420
+ if count > 0:
421
+ if cat == "leak":
422
+ cat = "gas_leak"
423
+ total_counts.append({
424
+ "category": cat,
425
+ "count": count
426
+ })
427
+
428
+ # Build current_counts array in expected format
429
+ current_counts = []
430
+ for cat, count in per_category_count.items():
431
+ if count > 0 or total_detections > 0: # Include even if 0 when there are detections
432
+ if cat == "leak":
433
+ cat = "gas_leak"
434
+ current_counts.append({
435
+ "category": cat,
436
+ "count": count
437
+ })
438
+
439
+ # Prepare detections without confidence scores (as per eg.json)
440
+ detections = []
441
+ for detection in counting_summary.get("detections", []):
442
+ bbox = detection.get("bounding_box", {})
443
+ category = detection.get("category", "person")
444
+ if category == "leak":
445
+ category = "gas_leak"
446
+ # Include segmentation if available (like in eg.json)
447
+ if detection.get("masks"):
448
+ segmentation= detection.get("masks", [])
449
+ detection_obj = self.create_detection_object(category, bbox, segmentation=segmentation)
450
+ elif detection.get("segmentation"):
451
+ segmentation= detection.get("segmentation")
452
+ detection_obj = self.create_detection_object(category, bbox, segmentation=segmentation)
453
+ elif detection.get("mask"):
454
+ segmentation= detection.get("mask")
455
+ detection_obj = self.create_detection_object(category, bbox, segmentation=segmentation)
456
+ else:
457
+ detection_obj = self.create_detection_object(category, bbox)
458
+ detections.append(detection_obj)
459
+
460
+ # Build alert_settings array in expected format
461
+ alert_settings = []
462
+ if config.alert_config and hasattr(config.alert_config, 'alert_type'):
463
+ alert_settings.append({
464
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
465
+ "incident_category": self.CASE_TYPE,
466
+ "threshold_level": config.alert_config.count_thresholds if hasattr(config.alert_config, 'count_thresholds') else {},
467
+ "ascending": True,
468
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
469
+ getattr(config.alert_config, 'alert_value', ['JSON']) if hasattr(config.alert_config, 'alert_value') else ['JSON'])
470
+ }
471
+ })
472
+
473
+ # Generate human_text in expected format
474
+ human_text_lines = [f"Tracking Statistics:"]
475
+ human_text_lines.append(f"CURRENT FRAME @ {current_timestamp}")
476
+
477
+ for cat, count in per_category_count.items():
478
+ if cat == "leak":
479
+ cat = "gas_leak"
480
+ human_text_lines.append(f"\t{cat}: {count}")
481
+
482
+ human_text_lines.append(f"TOTAL SINCE {start_timestamp}")
483
+ for cat, count in total_counts_dict.items():
484
+ if cat == "leak":
485
+ cat = "gas_leak"
486
+ if count > 0:
487
+ human_text_lines.append(f"\t{cat}: {count}")
488
+
489
+ if alerts:
490
+ for alert in alerts:
491
+ human_text_lines.append(f"Alerts: {alert.get('settings', {})} sent @ {current_timestamp}")
492
+ else:
493
+ human_text_lines.append("Alerts: None")
494
+
495
+ human_text = "\n".join(human_text_lines)
496
+ reset_settings=[
497
+ {
498
+ "interval_type": "daily",
499
+ "reset_time": {
500
+ "value": 9,
501
+ "time_unit": "hour"
502
+ }
503
+ }
504
+ ]
505
+
506
+ tracking_stat=self.create_tracking_stats(total_counts=total_counts, current_counts=current_counts,
507
+ detections=detections, human_text=human_text, camera_info=camera_info, alerts=alerts, alert_settings=alert_settings,
508
+ reset_settings=reset_settings, start_time=high_precision_start_timestamp ,
509
+ reset_time=high_precision_reset_timestamp)
510
+
511
+ tracking_stats.append(tracking_stat)
512
+ return tracking_stats
513
+
514
+ def _generate_business_analytics(self, counting_summary: Dict, alerts:Any, config: GasLeakConfig, stream_info: Optional[Dict[str, Any]] = None, is_empty=False) -> List[Dict]:
515
+ """Generate standardized business analytics for the agg_summary structure."""
516
+ if is_empty:
517
+ return []
518
+
519
+ #-----IF YOUR USECASE NEEDS BUSINESS ANALYTICS, YOU CAN USE THIS FUNCTION------#
520
+ #camera_info = self.get_camera_info_from_stream(stream_info)
521
+ # business_analytics = self.create_business_analytics(nalysis_name, statistics,
522
+ # human_text, camera_info=camera_info, alerts=alerts, alert_settings=alert_settings,
523
+ # reset_settings)
524
+ # return business_analytics
525
+
526
+ def _generate_summary(self, summary: dict, incidents: List, tracking_stats: List, business_analytics: List, alerts: List) -> List[str]:
527
+ """
528
+ Generate a human_text string for the tracking_stat, incident, business analytics and alerts.
529
+ """
530
+ lines = {}
531
+ lines["Application Name"] = self.CASE_TYPE
532
+ lines["Application Version"] = self.CASE_VERSION
533
+ if len(incidents) > 0:
534
+ lines["Incidents:"]=f"\n\t{incidents[0].get('human_text', 'No incidents detected')}\n"
535
+ if len(tracking_stats) > 0:
536
+ lines["Tracking Statistics:"]=f"\t{tracking_stats[0].get('human_text', 'No tracking statistics detected')}\n"
537
+ if len(business_analytics) > 0:
538
+ lines["Business Analytics:"]=f"\t{business_analytics[0].get('human_text', 'No business analytics detected')}\n"
539
+
540
+ if len(incidents) == 0 and len(tracking_stats) == 0 and len(business_analytics) == 0:
541
+ lines["Summary"] = "No Summary Data"
542
+
543
+ return [lines]
544
+
545
+ def _get_track_ids_info(self, detections: list) -> Dict[str, Any]:
546
+ """
547
+ Get detailed information about track IDs (per frame).
548
+ """
549
+ # Collect all track_ids in this frame
550
+ frame_track_ids = set()
551
+ for det in detections:
552
+ tid = det.get('track_id')
553
+ if tid is not None:
554
+ frame_track_ids.add(tid)
555
+ # Use persistent total set for unique counting
556
+ total_track_ids = set()
557
+ for s in getattr(self, '_per_category_total_track_ids', {}).values():
558
+ total_track_ids.update(s)
559
+ return {
560
+ "total_count": len(total_track_ids),
561
+ "current_frame_count": len(frame_track_ids),
562
+ "total_unique_track_ids": len(total_track_ids),
563
+ "current_frame_track_ids": list(frame_track_ids),
564
+ "last_update_time": time.time(),
565
+ "total_frames_processed": getattr(self, '_total_frame_counter', 0)
566
+ }
567
+
568
+ def _update_tracking_state(self, detections: list):
569
+ """
570
+ Track unique categories track_ids per category for total count after tracking.
571
+ Applies canonical ID merging to avoid duplicate counting when the underlying
572
+ tracker loses an object temporarily and assigns a new ID.
573
+ """
574
+ # Lazily initialise storage dicts
575
+ if not hasattr(self, "_per_category_total_track_ids"):
576
+ self._per_category_total_track_ids = {cat: set() for cat in self.target_categories}
577
+ self._current_frame_track_ids = {cat: set() for cat in self.target_categories}
578
+
579
+ for det in detections:
580
+ cat = det.get("category")
581
+ raw_track_id = det.get("track_id")
582
+ if cat not in self.target_categories or raw_track_id is None:
583
+ continue
584
+ bbox = det.get("bounding_box", det.get("bbox"))
585
+ canonical_id = self._merge_or_register_track(raw_track_id, bbox)
586
+ # Propagate canonical ID back to detection so downstream logic uses it
587
+ det["track_id"] = canonical_id
588
+
589
+ self._per_category_total_track_ids.setdefault(cat, set()).add(canonical_id)
590
+ self._current_frame_track_ids[cat].add(canonical_id)
591
+
592
+ def get_total_counts(self):
593
+ """
594
+ Return total unique track_id count for each category.
595
+ """
596
+ return {cat: len(ids) for cat, ids in getattr(self, '_per_category_total_track_ids', {}).items()}
597
+
598
+
599
+ def _format_timestamp_for_stream(self, timestamp: float) -> str:
600
+ """Format timestamp for streams (YYYY:MM:DD HH:MM:SS format)."""
601
+ dt = datetime.fromtimestamp(timestamp, tz=timezone.utc)
602
+ return dt.strftime('%Y:%m:%d %H:%M:%S')
603
+
604
+ def _format_timestamp_for_video(self, timestamp: float) -> str:
605
+ """Format timestamp for video chunks (HH:MM:SS.ms format)."""
606
+ hours = int(timestamp // 3600)
607
+ minutes = int((timestamp % 3600) // 60)
608
+ seconds = round(float(timestamp % 60),2)
609
+ return f"{hours:02d}:{minutes:02d}:{seconds:.1f}"
610
+
611
+ def _get_current_timestamp_str(self, stream_info: Optional[Dict[str, Any]], precision=False, frame_id: Optional[str]=None) -> str:
612
+ """Get formatted current timestamp based on stream type."""
613
+ if not stream_info:
614
+ return "00:00:00.00"
615
+ # is_video_chunk = stream_info.get("input_settings", {}).get("is_video_chunk", False)
616
+ if precision:
617
+ if stream_info.get("input_settings", {}).get("start_frame", "na") != "na":
618
+ if frame_id:
619
+ start_time = int(frame_id)/stream_info.get("input_settings", {}).get("original_fps", 30)
620
+ else:
621
+ start_time = stream_info.get("input_settings", {}).get("start_frame", 30)/stream_info.get("input_settings", {}).get("original_fps", 30)
622
+ stream_time_str = self._format_timestamp_for_video(start_time)
623
+ return stream_time_str
624
+ else:
625
+ return datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
626
+
627
+ if stream_info.get("input_settings", {}).get("start_frame", "na") != "na":
628
+ if frame_id:
629
+ start_time = int(frame_id)/stream_info.get("input_settings", {}).get("original_fps", 30)
630
+ else:
631
+ start_time = stream_info.get("input_settings", {}).get("start_frame", 30)/stream_info.get("input_settings", {}).get("original_fps", 30)
632
+ stream_time_str = self._format_timestamp_for_video(start_time)
633
+ return stream_time_str
634
+ else:
635
+ # For streams, use stream_time from stream_info
636
+ stream_time_str = stream_info.get("input_settings", {}).get("stream_info", {}).get("stream_time", "")
637
+ if stream_time_str:
638
+ # Parse the high precision timestamp string to get timestamp
639
+ try:
640
+ # Remove " UTC" suffix and parse
641
+ timestamp_str = stream_time_str.replace(" UTC", "")
642
+ dt = datetime.strptime(timestamp_str, "%Y-%m-%d-%H:%M:%S.%f")
643
+ timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
644
+ return self._format_timestamp_for_stream(timestamp)
645
+ except:
646
+ # Fallback to current time if parsing fails
647
+ return self._format_timestamp_for_stream(time.time())
648
+ else:
649
+ return self._format_timestamp_for_stream(time.time())
650
+
651
+ def _get_start_timestamp_str(self, stream_info: Optional[Dict[str, Any]], precision=False) -> str:
652
+ """Get formatted start timestamp for 'TOTAL SINCE' based on stream type."""
653
+ if not stream_info:
654
+ return "00:00:00"
655
+ if precision:
656
+ if stream_info.get("input_settings", {}).get("start_frame", "na") != "na":
657
+ return "00:00:00"
658
+ else:
659
+ return datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
660
+
661
+ if stream_info.get("input_settings", {}).get("start_frame", "na") != "na":
662
+ # If video format, start from 00:00:00
663
+ return "00:00:00"
664
+ else:
665
+ # For streams, use tracking start time or current time with minutes/seconds reset
666
+ if self._tracking_start_time is None:
667
+ # Try to extract timestamp from stream_time string
668
+ stream_time_str = stream_info.get("input_settings", {}).get("stream_info", {}).get("stream_time", "")
669
+ if stream_time_str:
670
+ try:
671
+ # Remove " UTC" suffix and parse
672
+ timestamp_str = stream_time_str.replace(" UTC", "")
673
+ dt = datetime.strptime(timestamp_str, "%Y-%m-%d-%H:%M:%S.%f")
674
+ self._tracking_start_time = dt.replace(tzinfo=timezone.utc).timestamp()
675
+ except:
676
+ # Fallback to current time if parsing fails
677
+ self._tracking_start_time = time.time()
678
+ else:
679
+ self._tracking_start_time = time.time()
680
+
681
+ dt = datetime.fromtimestamp(self._tracking_start_time, tz=timezone.utc)
682
+ # Reset minutes and seconds to 00:00 for "TOTAL SINCE" format
683
+ dt = dt.replace(minute=0, second=0, microsecond=0)
684
+ return dt.strftime('%Y:%m:%d %H:%M:%S')
685
+
686
+
687
+ def _count_categories(self, detections: list, config: GasLeakConfig) -> dict:
688
+ """
689
+ Count the number of detections per category and return a summary dict.
690
+ The detections list is expected to have 'track_id' (from tracker), 'category', 'bounding_box', etc.
691
+ Output structure will include 'track_id' for each detection as per AdvancedTracker output.
692
+ """
693
+ counts = {}
694
+ for det in detections:
695
+ cat = det.get('category', 'unknown')
696
+ if cat == "leak":
697
+ cat = "gas_leak"
698
+ counts[cat] = counts.get(cat, 0) + 1
699
+ # Each detection dict will now include 'track_id' (and possibly 'frame_id')
700
+ return {
701
+ "total_count": sum(counts.values()),
702
+ "per_category_count": counts,
703
+ "detections": [
704
+ {
705
+ "bounding_box": det.get("bounding_box"),
706
+ "category": det.get("category"),
707
+ "confidence": det.get("confidence"),
708
+ "track_id": det.get("track_id"),
709
+ "frame_id": det.get("frame_id")
710
+ }
711
+ for det in detections
712
+ ]
713
+ }
714
+
715
+ def _extract_predictions(self, detections: list) -> List[Dict[str, Any]]:
716
+ """
717
+ Extract prediction details for output (category, confidence, bounding box).
718
+ """
719
+ return [
720
+ {
721
+ "category": det.get("category", "unknown"),
722
+ "confidence": det.get("confidence", 0.0),
723
+ "bounding_box": det.get("bounding_box", {})
724
+ }
725
+ for det in detections
726
+ ]
727
+
728
+ # ------------------------------------------------------------------ #
729
+ # Canonical ID helpers #
730
+ # ------------------------------------------------------------------ #
731
+ def _compute_iou(self, box1: Any, box2: Any) -> float:
732
+ """Compute IoU between two bounding boxes which may be dicts or lists.
733
+ Falls back to 0 when insufficient data is available."""
734
+
735
+ # Helper to convert bbox (dict or list) to [x1, y1, x2, y2]
736
+ def _bbox_to_list(bbox):
737
+ if bbox is None:
738
+ return []
739
+ if isinstance(bbox, list):
740
+ return bbox[:4] if len(bbox) >= 4 else []
741
+ if isinstance(bbox, dict):
742
+ if "xmin" in bbox:
743
+ return [bbox["xmin"], bbox["ymin"], bbox["xmax"], bbox["ymax"]]
744
+ if "x1" in bbox:
745
+ return [bbox["x1"], bbox["y1"], bbox["x2"], bbox["y2"]]
746
+ # Fallback: first four numeric values
747
+ values = [v for v in bbox.values() if isinstance(v, (int, float))]
748
+ return values[:4] if len(values) >= 4 else []
749
+ return []
750
+
751
+ l1 = _bbox_to_list(box1)
752
+ l2 = _bbox_to_list(box2)
753
+ if len(l1) < 4 or len(l2) < 4:
754
+ return 0.0
755
+ x1_min, y1_min, x1_max, y1_max = l1
756
+ x2_min, y2_min, x2_max, y2_max = l2
757
+
758
+ # Ensure correct order
759
+ x1_min, x1_max = min(x1_min, x1_max), max(x1_min, x1_max)
760
+ y1_min, y1_max = min(y1_min, y1_max), max(y1_min, y1_max)
761
+ x2_min, x2_max = min(x2_min, x2_max), max(x2_min, x2_max)
762
+ y2_min, y2_max = min(y2_min, y2_max), max(y2_min, y2_max)
763
+
764
+ inter_x_min = max(x1_min, x2_min)
765
+ inter_y_min = max(y1_min, y2_min)
766
+ inter_x_max = min(x1_max, x2_max)
767
+ inter_y_max = min(y1_max, y2_max)
768
+
769
+ inter_w = max(0.0, inter_x_max - inter_x_min)
770
+ inter_h = max(0.0, inter_y_max - inter_y_min)
771
+ inter_area = inter_w * inter_h
772
+
773
+ area1 = (x1_max - x1_min) * (y1_max - y1_min)
774
+ area2 = (x2_max - x2_min) * (y2_max - y2_min)
775
+ union_area = area1 + area2 - inter_area
776
+
777
+ return (inter_area / union_area) if union_area > 0 else 0.0
778
+
779
+ def _merge_or_register_track(self, raw_id: Any, bbox: Any) -> Any:
780
+ """Return a stable canonical ID for a raw tracker ID, merging fragmented
781
+ tracks when IoU and temporal constraints indicate they represent the
782
+ same physical."""
783
+ if raw_id is None or bbox is None:
784
+ # Nothing to merge
785
+ return raw_id
786
+
787
+ now = time.time()
788
+
789
+ # Fast path – raw_id already mapped
790
+ if raw_id in self._track_aliases:
791
+ canonical_id = self._track_aliases[raw_id]
792
+ track_info = self._canonical_tracks.get(canonical_id)
793
+ if track_info is not None:
794
+ track_info["last_bbox"] = bbox
795
+ track_info["last_update"] = now
796
+ track_info["raw_ids"].add(raw_id)
797
+ return canonical_id
798
+
799
+ # Attempt to merge with an existing canonical track
800
+ for canonical_id, info in self._canonical_tracks.items():
801
+ # Only consider recently updated tracks
802
+ if now - info["last_update"] > self._track_merge_time_window:
803
+ continue
804
+ iou = self._compute_iou(bbox, info["last_bbox"])
805
+ if iou >= self._track_merge_iou_threshold:
806
+ # Merge
807
+ self._track_aliases[raw_id] = canonical_id
808
+ info["last_bbox"] = bbox
809
+ info["last_update"] = now
810
+ info["raw_ids"].add(raw_id)
811
+ return canonical_id
812
+
813
+ # No match – register new canonical track
814
+ canonical_id = raw_id
815
+ self._track_aliases[raw_id] = canonical_id
816
+ self._canonical_tracks[canonical_id] = {
817
+ "last_bbox": bbox,
818
+ "last_update": now,
819
+ "raw_ids": {raw_id},
820
+ }
821
+ return canonical_id
822
+
823
+ def _format_timestamp(self, timestamp: float) -> str:
824
+ """Format a timestamp for human-readable output."""
825
+ return datetime.fromtimestamp(timestamp, timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')
826
+
827
+ def _get_tracking_start_time(self) -> str:
828
+ """Get the tracking start time, formatted as a string."""
829
+ if self._tracking_start_time is None:
830
+ return "N/A"
831
+ return self._format_timestamp(self._tracking_start_time)
832
+
833
+ def _set_tracking_start_time(self) -> None:
834
+ """Set the tracking start time to the current time."""
835
+ self._tracking_start_time = time.time()