matrice-analytics 0.1.2__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.

Potentially problematic release.


This version of matrice-analytics might be problematic. Click here for more details.

Files changed (160) hide show
  1. matrice_analytics/__init__.py +28 -0
  2. matrice_analytics/boundary_drawing_internal/README.md +305 -0
  3. matrice_analytics/boundary_drawing_internal/__init__.py +45 -0
  4. matrice_analytics/boundary_drawing_internal/boundary_drawing_internal.py +1207 -0
  5. matrice_analytics/boundary_drawing_internal/boundary_drawing_tool.py +429 -0
  6. matrice_analytics/boundary_drawing_internal/boundary_tool_template.html +1036 -0
  7. matrice_analytics/boundary_drawing_internal/data/.gitignore +12 -0
  8. matrice_analytics/boundary_drawing_internal/example_usage.py +206 -0
  9. matrice_analytics/boundary_drawing_internal/usage/README.md +110 -0
  10. matrice_analytics/boundary_drawing_internal/usage/boundary_drawer_launcher.py +102 -0
  11. matrice_analytics/boundary_drawing_internal/usage/simple_boundary_launcher.py +107 -0
  12. matrice_analytics/post_processing/README.md +455 -0
  13. matrice_analytics/post_processing/__init__.py +732 -0
  14. matrice_analytics/post_processing/advanced_tracker/README.md +650 -0
  15. matrice_analytics/post_processing/advanced_tracker/__init__.py +17 -0
  16. matrice_analytics/post_processing/advanced_tracker/base.py +99 -0
  17. matrice_analytics/post_processing/advanced_tracker/config.py +77 -0
  18. matrice_analytics/post_processing/advanced_tracker/kalman_filter.py +370 -0
  19. matrice_analytics/post_processing/advanced_tracker/matching.py +195 -0
  20. matrice_analytics/post_processing/advanced_tracker/strack.py +230 -0
  21. matrice_analytics/post_processing/advanced_tracker/tracker.py +367 -0
  22. matrice_analytics/post_processing/config.py +142 -0
  23. matrice_analytics/post_processing/core/__init__.py +63 -0
  24. matrice_analytics/post_processing/core/base.py +704 -0
  25. matrice_analytics/post_processing/core/config.py +3188 -0
  26. matrice_analytics/post_processing/core/config_utils.py +925 -0
  27. matrice_analytics/post_processing/face_reg/__init__.py +43 -0
  28. matrice_analytics/post_processing/face_reg/compare_similarity.py +556 -0
  29. matrice_analytics/post_processing/face_reg/embedding_manager.py +681 -0
  30. matrice_analytics/post_processing/face_reg/face_recognition.py +1870 -0
  31. matrice_analytics/post_processing/face_reg/face_recognition_client.py +339 -0
  32. matrice_analytics/post_processing/face_reg/people_activity_logging.py +283 -0
  33. matrice_analytics/post_processing/ocr/__init__.py +0 -0
  34. matrice_analytics/post_processing/ocr/easyocr_extractor.py +248 -0
  35. matrice_analytics/post_processing/ocr/postprocessing.py +271 -0
  36. matrice_analytics/post_processing/ocr/preprocessing.py +52 -0
  37. matrice_analytics/post_processing/post_processor.py +1153 -0
  38. matrice_analytics/post_processing/test_cases/__init__.py +1 -0
  39. matrice_analytics/post_processing/test_cases/run_tests.py +143 -0
  40. matrice_analytics/post_processing/test_cases/test_advanced_customer_service.py +841 -0
  41. matrice_analytics/post_processing/test_cases/test_basic_counting_tracking.py +523 -0
  42. matrice_analytics/post_processing/test_cases/test_comprehensive.py +531 -0
  43. matrice_analytics/post_processing/test_cases/test_config.py +852 -0
  44. matrice_analytics/post_processing/test_cases/test_customer_service.py +585 -0
  45. matrice_analytics/post_processing/test_cases/test_data_generators.py +583 -0
  46. matrice_analytics/post_processing/test_cases/test_people_counting.py +510 -0
  47. matrice_analytics/post_processing/test_cases/test_processor.py +524 -0
  48. matrice_analytics/post_processing/test_cases/test_utilities.py +356 -0
  49. matrice_analytics/post_processing/test_cases/test_utils.py +743 -0
  50. matrice_analytics/post_processing/usecases/Histopathological_Cancer_Detection_img.py +604 -0
  51. matrice_analytics/post_processing/usecases/__init__.py +267 -0
  52. matrice_analytics/post_processing/usecases/abandoned_object_detection.py +797 -0
  53. matrice_analytics/post_processing/usecases/advanced_customer_service.py +1601 -0
  54. matrice_analytics/post_processing/usecases/age_detection.py +842 -0
  55. matrice_analytics/post_processing/usecases/age_gender_detection.py +1043 -0
  56. matrice_analytics/post_processing/usecases/anti_spoofing_detection.py +656 -0
  57. matrice_analytics/post_processing/usecases/assembly_line_detection.py +841 -0
  58. matrice_analytics/post_processing/usecases/banana_defect_detection.py +624 -0
  59. matrice_analytics/post_processing/usecases/basic_counting_tracking.py +667 -0
  60. matrice_analytics/post_processing/usecases/blood_cancer_detection_img.py +881 -0
  61. matrice_analytics/post_processing/usecases/car_damage_detection.py +834 -0
  62. matrice_analytics/post_processing/usecases/car_part_segmentation.py +946 -0
  63. matrice_analytics/post_processing/usecases/car_service.py +1601 -0
  64. matrice_analytics/post_processing/usecases/cardiomegaly_classification.py +864 -0
  65. matrice_analytics/post_processing/usecases/cell_microscopy_segmentation.py +897 -0
  66. matrice_analytics/post_processing/usecases/chicken_pose_detection.py +648 -0
  67. matrice_analytics/post_processing/usecases/child_monitoring.py +814 -0
  68. matrice_analytics/post_processing/usecases/color/clip.py +232 -0
  69. matrice_analytics/post_processing/usecases/color/clip_processor/merges.txt +48895 -0
  70. matrice_analytics/post_processing/usecases/color/clip_processor/preprocessor_config.json +28 -0
  71. matrice_analytics/post_processing/usecases/color/clip_processor/special_tokens_map.json +30 -0
  72. matrice_analytics/post_processing/usecases/color/clip_processor/tokenizer.json +245079 -0
  73. matrice_analytics/post_processing/usecases/color/clip_processor/tokenizer_config.json +32 -0
  74. matrice_analytics/post_processing/usecases/color/clip_processor/vocab.json +1 -0
  75. matrice_analytics/post_processing/usecases/color/color_map_utils.py +70 -0
  76. matrice_analytics/post_processing/usecases/color/color_mapper.py +468 -0
  77. matrice_analytics/post_processing/usecases/color_detection.py +1835 -0
  78. matrice_analytics/post_processing/usecases/color_map_utils.py +70 -0
  79. matrice_analytics/post_processing/usecases/concrete_crack_detection.py +827 -0
  80. matrice_analytics/post_processing/usecases/crop_weed_detection.py +781 -0
  81. matrice_analytics/post_processing/usecases/customer_service.py +1008 -0
  82. matrice_analytics/post_processing/usecases/defect_detection_products.py +936 -0
  83. matrice_analytics/post_processing/usecases/distracted_driver_detection.py +822 -0
  84. matrice_analytics/post_processing/usecases/drone_traffic_monitoring.py +930 -0
  85. matrice_analytics/post_processing/usecases/drowsy_driver_detection.py +829 -0
  86. matrice_analytics/post_processing/usecases/dwell_detection.py +829 -0
  87. matrice_analytics/post_processing/usecases/emergency_vehicle_detection.py +827 -0
  88. matrice_analytics/post_processing/usecases/face_emotion.py +813 -0
  89. matrice_analytics/post_processing/usecases/face_recognition.py +827 -0
  90. matrice_analytics/post_processing/usecases/fashion_detection.py +835 -0
  91. matrice_analytics/post_processing/usecases/field_mapping.py +902 -0
  92. matrice_analytics/post_processing/usecases/fire_detection.py +1112 -0
  93. matrice_analytics/post_processing/usecases/flare_analysis.py +891 -0
  94. matrice_analytics/post_processing/usecases/flower_segmentation.py +1006 -0
  95. matrice_analytics/post_processing/usecases/gas_leak_detection.py +837 -0
  96. matrice_analytics/post_processing/usecases/gender_detection.py +832 -0
  97. matrice_analytics/post_processing/usecases/human_activity_recognition.py +871 -0
  98. matrice_analytics/post_processing/usecases/intrusion_detection.py +1672 -0
  99. matrice_analytics/post_processing/usecases/leaf.py +821 -0
  100. matrice_analytics/post_processing/usecases/leaf_disease.py +840 -0
  101. matrice_analytics/post_processing/usecases/leak_detection.py +837 -0
  102. matrice_analytics/post_processing/usecases/license_plate_detection.py +914 -0
  103. matrice_analytics/post_processing/usecases/license_plate_monitoring.py +1194 -0
  104. matrice_analytics/post_processing/usecases/litter_monitoring.py +717 -0
  105. matrice_analytics/post_processing/usecases/mask_detection.py +869 -0
  106. matrice_analytics/post_processing/usecases/natural_disaster.py +907 -0
  107. matrice_analytics/post_processing/usecases/parking.py +787 -0
  108. matrice_analytics/post_processing/usecases/parking_space_detection.py +822 -0
  109. matrice_analytics/post_processing/usecases/pcb_defect_detection.py +888 -0
  110. matrice_analytics/post_processing/usecases/pedestrian_detection.py +808 -0
  111. matrice_analytics/post_processing/usecases/people_counting.py +1728 -0
  112. matrice_analytics/post_processing/usecases/people_tracking.py +1842 -0
  113. matrice_analytics/post_processing/usecases/pipeline_detection.py +605 -0
  114. matrice_analytics/post_processing/usecases/plaque_segmentation_img.py +874 -0
  115. matrice_analytics/post_processing/usecases/pothole_segmentation.py +915 -0
  116. matrice_analytics/post_processing/usecases/ppe_compliance.py +645 -0
  117. matrice_analytics/post_processing/usecases/price_tag_detection.py +822 -0
  118. matrice_analytics/post_processing/usecases/proximity_detection.py +1901 -0
  119. matrice_analytics/post_processing/usecases/road_lane_detection.py +623 -0
  120. matrice_analytics/post_processing/usecases/road_traffic_density.py +832 -0
  121. matrice_analytics/post_processing/usecases/road_view_segmentation.py +915 -0
  122. matrice_analytics/post_processing/usecases/shelf_inventory_detection.py +583 -0
  123. matrice_analytics/post_processing/usecases/shoplifting_detection.py +822 -0
  124. matrice_analytics/post_processing/usecases/shopping_cart_analysis.py +899 -0
  125. matrice_analytics/post_processing/usecases/skin_cancer_classification_img.py +864 -0
  126. matrice_analytics/post_processing/usecases/smoker_detection.py +833 -0
  127. matrice_analytics/post_processing/usecases/solar_panel.py +810 -0
  128. matrice_analytics/post_processing/usecases/suspicious_activity_detection.py +1030 -0
  129. matrice_analytics/post_processing/usecases/template_usecase.py +380 -0
  130. matrice_analytics/post_processing/usecases/theft_detection.py +648 -0
  131. matrice_analytics/post_processing/usecases/traffic_sign_monitoring.py +724 -0
  132. matrice_analytics/post_processing/usecases/underground_pipeline_defect_detection.py +775 -0
  133. matrice_analytics/post_processing/usecases/underwater_pollution_detection.py +842 -0
  134. matrice_analytics/post_processing/usecases/vehicle_monitoring.py +950 -0
  135. matrice_analytics/post_processing/usecases/warehouse_object_segmentation.py +899 -0
  136. matrice_analytics/post_processing/usecases/waterbody_segmentation.py +923 -0
  137. matrice_analytics/post_processing/usecases/weapon_detection.py +771 -0
  138. matrice_analytics/post_processing/usecases/weld_defect_detection.py +615 -0
  139. matrice_analytics/post_processing/usecases/wildlife_monitoring.py +898 -0
  140. matrice_analytics/post_processing/usecases/windmill_maintenance.py +834 -0
  141. matrice_analytics/post_processing/usecases/wound_segmentation.py +856 -0
  142. matrice_analytics/post_processing/utils/__init__.py +150 -0
  143. matrice_analytics/post_processing/utils/advanced_counting_utils.py +400 -0
  144. matrice_analytics/post_processing/utils/advanced_helper_utils.py +317 -0
  145. matrice_analytics/post_processing/utils/advanced_tracking_utils.py +461 -0
  146. matrice_analytics/post_processing/utils/alerting_utils.py +213 -0
  147. matrice_analytics/post_processing/utils/category_mapping_utils.py +94 -0
  148. matrice_analytics/post_processing/utils/color_utils.py +592 -0
  149. matrice_analytics/post_processing/utils/counting_utils.py +182 -0
  150. matrice_analytics/post_processing/utils/filter_utils.py +261 -0
  151. matrice_analytics/post_processing/utils/format_utils.py +293 -0
  152. matrice_analytics/post_processing/utils/geometry_utils.py +300 -0
  153. matrice_analytics/post_processing/utils/smoothing_utils.py +358 -0
  154. matrice_analytics/post_processing/utils/tracking_utils.py +234 -0
  155. matrice_analytics/py.typed +0 -0
  156. matrice_analytics-0.1.2.dist-info/METADATA +481 -0
  157. matrice_analytics-0.1.2.dist-info/RECORD +160 -0
  158. matrice_analytics-0.1.2.dist-info/WHEEL +5 -0
  159. matrice_analytics-0.1.2.dist-info/licenses/LICENSE.txt +21 -0
  160. matrice_analytics-0.1.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,923 @@
1
+ from typing import Any, Dict, List, Optional
2
+ from dataclasses import asdict
3
+ import time
4
+ from datetime import datetime, timezone
5
+ import copy # Added for deep copying detections to preserve original masks
6
+
7
+ from ..core.base import BaseProcessor, ProcessingContext, ProcessingResult, ConfigProtocol, ResultFormat
8
+ from ..utils import (
9
+ filter_by_confidence,
10
+ filter_by_categories,
11
+ apply_category_mapping,
12
+ count_objects_by_category,
13
+ count_objects_in_zones,
14
+ calculate_counting_summary,
15
+ match_results_structure,
16
+ bbox_smoothing,
17
+ BBoxSmoothingConfig,
18
+ BBoxSmoothingTracker
19
+ )
20
+ from dataclasses import dataclass, field
21
+ from ..core.config import BaseConfig, AlertConfig, ZoneConfig
22
+
23
+
24
+ @dataclass
25
+ class WaterBodyConfig(BaseConfig):
26
+ """Configuration for WaterBody detection use case in WaterBody monitoring."""
27
+ # Smoothing configuration
28
+ enable_smoothing: bool = True
29
+ smoothing_algorithm: str = "observability" # "window" or "observability"
30
+ smoothing_window_size: int = 20
31
+ smoothing_cooldown_frames: int = 5
32
+ smoothing_confidence_range_factor: float = 0.5
33
+
34
+ #confidence thresholds
35
+ confidence_threshold: float = 0.9
36
+
37
+ usecase_categories: List[str] = field(
38
+ default_factory=lambda: ['Point d-eau']
39
+ )
40
+
41
+ target_categories: List[str] = field(
42
+ default_factory=lambda: ['Point d-eau']
43
+ )
44
+
45
+ alert_config: Optional[AlertConfig] = None
46
+
47
+ index_to_category: Optional[Dict[int, str]] = field(
48
+ default_factory=lambda: {
49
+ 0: 'Point d-eau'
50
+ }
51
+ )
52
+
53
+
54
+ class WaterBodyUseCase(BaseProcessor):
55
+
56
+ # Human-friendly display names for categories
57
+ CATEGORY_DISPLAY = {
58
+ "Point d-eau": "Point d-eau",
59
+ }
60
+
61
+ def __init__(self):
62
+ super().__init__("waterbody_segmentation")
63
+ self.category = "agriculture"
64
+
65
+ # List of categories to track
66
+ self.target_categories = ['Point d-eau']
67
+
68
+ self.CASE_TYPE: Optional[str] = 'waterbody_segmentation'
69
+ self.CASE_VERSION: Optional[str] = '1.3'
70
+
71
+ # Initialize smoothing tracker
72
+ self.smoothing_tracker = None
73
+
74
+ # Initialize advanced tracker (will be created on first use)
75
+ self.tracker = None
76
+
77
+ # Initialize tracking state variables
78
+ self._total_frame_counter = 0
79
+ self._global_frame_offset = 0
80
+
81
+ # Track start time for "TOTAL SINCE" calculation
82
+ self._tracking_start_time = None
83
+
84
+ # ------------------------------------------------------------------ #
85
+ # Canonical tracking aliasing to avoid duplicate counts #
86
+ # ------------------------------------------------------------------ #
87
+ # Maps raw tracker-generated IDs to stable canonical IDs that persist
88
+ # even if the underlying tracker re-assigns a new ID after a short
89
+ # interruption. This mirrors the logic used in people_counting to
90
+ # provide accurate unique counting.
91
+ self._track_aliases: Dict[Any, Any] = {}
92
+ self._canonical_tracks: Dict[Any, Dict[str, Any]] = {}
93
+ # Tunable parameters – adjust if necessary for specific scenarios
94
+ self._track_merge_iou_threshold: float = 0.05 # IoU ≥ 0.05 →
95
+ self._track_merge_time_window: float = 7.0 # seconds within which to merge
96
+
97
+ self._ascending_alert_list: List[int] = []
98
+ self.current_incident_end_timestamp: str = "N/A"
99
+
100
+ def process(self, data: Any, config: ConfigProtocol, context: Optional[ProcessingContext] = None,
101
+ stream_info: Optional[Dict[str, Any]] = None) -> ProcessingResult:
102
+ """
103
+ Main entry point for post-processing.
104
+ Applies category mapping, smoothing, counting, alerting, and summary generation.
105
+ Returns a ProcessingResult with all relevant outputs.
106
+ """
107
+ start_time = time.time()
108
+ # Ensure config is correct type
109
+ if not isinstance(config, WaterBodyConfig):
110
+ return self.create_error_result("Invalid config type", usecase=self.name, category=self.category,
111
+ context=context)
112
+ if context is None:
113
+ context = ProcessingContext()
114
+
115
+ # Detect input format and store in context
116
+ input_format = match_results_structure(data)
117
+ context.input_format = input_format
118
+ context.confidence_threshold = config.confidence_threshold
119
+
120
+ # Step 1: Confidence filtering
121
+ if config.confidence_threshold is not None:
122
+ processed_data = filter_by_confidence(data, config.confidence_threshold)
123
+ else:
124
+ processed_data = data
125
+ self.logger.debug(f"Did not apply confidence filtering with threshold since nothing was provided")
126
+
127
+ # Step 2: Apply category mapping if provided
128
+ if config.index_to_category:
129
+ processed_data = apply_category_mapping(processed_data, config.index_to_category)
130
+
131
+ # Step 3: Category filtering
132
+ if config.target_categories:
133
+ processed_data = [d for d in processed_data if d.get('category') in self.target_categories]
134
+
135
+ # Step 4: Apply bbox smoothing if enabled
136
+ # Deep-copy detections so that we preserve the original masks before any
137
+ # smoothing/tracking logic potentially removes them.
138
+ raw_processed_data = [copy.deepcopy(det) for det in processed_data]
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
+
151
+ processed_data = bbox_smoothing(processed_data, self.smoothing_tracker.config, self.smoothing_tracker)
152
+ # Restore masks after smoothing
153
+
154
+ # Step 5: Advanced tracking (BYTETracker-like)
155
+ try:
156
+ from ..advanced_tracker import AdvancedTracker
157
+ from ..advanced_tracker.config import TrackerConfig
158
+
159
+ if self.tracker is None:
160
+ # Configure tracker thresholds based on the use-case confidence threshold so that
161
+ # low-confidence detections (e.g. < 0.7) can still be initialised as tracks when
162
+ # the user passes a lower `confidence_threshold` in the post-processing config.
163
+ if config.confidence_threshold is not None:
164
+ tracker_config = TrackerConfig(
165
+ track_high_thresh=float(config.confidence_threshold),
166
+ # Allow even lower detections to participate in secondary association
167
+ track_low_thresh=max(0.05, float(config.confidence_threshold) / 2),
168
+ new_track_thresh=float(config.confidence_threshold)
169
+ )
170
+ else:
171
+ tracker_config = TrackerConfig()
172
+ self.tracker = AdvancedTracker(tracker_config)
173
+ self.logger.info(
174
+ "Initialized AdvancedTracker for Monitoring and tracking with thresholds: "
175
+ f"high={tracker_config.track_high_thresh}, "
176
+ f"low={tracker_config.track_low_thresh}, "
177
+ f"new={tracker_config.new_track_thresh}"
178
+ )
179
+
180
+ # The tracker expects the data in the same format as input
181
+ # It will add track_id and frame_id to each detection
182
+ processed_data = self.tracker.update(processed_data)
183
+ except Exception as e:
184
+ # If advanced tracker fails, fallback to unsmoothed detections
185
+ self.logger.warning(f"AdvancedTracker failed: {e}")
186
+
187
+ # Update tracking state for total count per label
188
+ self._update_tracking_state(processed_data)
189
+
190
+ # ------------------------------------------------------------------ #
191
+ # Re-attach segmentation masks that were present in the original input
192
+ # but may have been stripped during smoothing/tracking. We match each
193
+ # processed detection back to the raw detection with the highest IoU
194
+ # and copy over its "masks" field (if available).
195
+ # ------------------------------------------------------------------ #
196
+ processed_data = self._attach_masks_to_detections(processed_data, raw_processed_data)
197
+
198
+ # Update frame counter
199
+ self._total_frame_counter += 1
200
+
201
+ # Extract frame information from stream_info
202
+ frame_number = None
203
+ if stream_info:
204
+ input_settings = stream_info.get("input_settings", {})
205
+ start_frame = input_settings.get("start_frame")
206
+ end_frame = input_settings.get("end_frame")
207
+ # If start and end frame are the same, it's a single frame
208
+ if start_frame is not None and end_frame is not None and start_frame == end_frame:
209
+ frame_number = start_frame
210
+
211
+ # Compute summaries and alerts
212
+ general_counting_summary = calculate_counting_summary(data)
213
+ counting_summary = self._count_categories(processed_data, config)
214
+ # Add total unique counts after tracking using only local state
215
+ total_counts = self.get_total_counts()
216
+ counting_summary['total_counts'] = total_counts
217
+
218
+ alerts = self._check_alerts(counting_summary, frame_number, config)
219
+ predictions = self._extract_predictions(processed_data)
220
+
221
+ # Step: Generate structured events and tracking stats with frame-based keys
222
+ incidents_list = self._generate_incidents(counting_summary, alerts, config, frame_number, stream_info)
223
+ tracking_stats_list = self._generate_tracking_stats(counting_summary, alerts, config, frame_number,stream_info)
224
+ # business_analytics_list = self._generate_business_analytics(counting_summary, alerts, config, frame_number, stream_info, is_empty=False)
225
+ business_analytics_list = []
226
+ summary_list = self._generate_summary(counting_summary, incidents_list, tracking_stats_list, business_analytics_list, alerts)
227
+
228
+ # Extract frame-based dictionaries from the lists
229
+ incidents = incidents_list[0] if incidents_list else {}
230
+ tracking_stats = tracking_stats_list[0] if tracking_stats_list else {}
231
+ business_analytics = business_analytics_list[0] if business_analytics_list else {}
232
+ summary = summary_list[0] if summary_list else {}
233
+ agg_summary = {str(frame_number): {
234
+ "incidents": incidents,
235
+ "tracking_stats": tracking_stats,
236
+ "business_analytics": business_analytics,
237
+ "alerts": alerts,
238
+ "human_text": summary}
239
+ }
240
+
241
+ context.mark_completed()
242
+
243
+ # Build result object following the new pattern
244
+
245
+ result = self.create_result(
246
+ data={"agg_summary": agg_summary},
247
+ usecase=self.name,
248
+ category=self.category,
249
+ context=context
250
+ )
251
+
252
+ return result
253
+
254
+ def _check_alerts(self, summary: dict, frame_number:Any, config: WaterBodyConfig) -> List[Dict]:
255
+ """
256
+ Check if any alert thresholds are exceeded and return alert dicts.
257
+ """
258
+ def get_trend(data, lookback=900, threshold=0.6):
259
+ '''
260
+ Determine if the trend is ascending or descending based on actual value progression.
261
+ Now works with values 0,1,2,3 (not just binary).
262
+ '''
263
+ window = data[-lookback:] if len(data) >= lookback else data
264
+ if len(window) < 2:
265
+ return True # not enough data to determine trend
266
+ increasing = 0
267
+ total = 0
268
+ for i in range(1, len(window)):
269
+ if window[i] >= window[i - 1]:
270
+ increasing += 1
271
+ total += 1
272
+ ratio = increasing / total
273
+ if ratio >= threshold:
274
+ return True
275
+ elif ratio <= (1 - threshold):
276
+ return False
277
+
278
+ frame_key = str(frame_number) if frame_number is not None else "current_frame"
279
+ alerts = []
280
+ total_detections = summary.get("total_count", 0) #CURRENT combined total count of all classes
281
+ total_counts_dict = summary.get("total_counts", {}) #TOTAL cumulative counts per class
282
+ cumulative_total = sum(total_counts_dict.values()) if total_counts_dict else 0 #TOTAL combined cumulative count
283
+ per_category_count = summary.get("per_category_count", {}) #CURRENT count per class
284
+
285
+ if not config.alert_config:
286
+ return alerts
287
+
288
+ total = summary.get("total_count", 0)
289
+ #self._ascending_alert_list
290
+ if hasattr(config.alert_config, 'count_thresholds') and config.alert_config.count_thresholds:
291
+
292
+ for category, threshold in config.alert_config.count_thresholds.items():
293
+ if category == "all" and total > threshold:
294
+
295
+ alerts.append({
296
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
297
+ "alert_id": "alert_"+category+'_'+frame_key,
298
+ "incident_category": self.CASE_TYPE,
299
+ "threshold_level": threshold,
300
+ "ascending": get_trend(self._ascending_alert_list, lookback=900, threshold=0.8),
301
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
302
+ getattr(config.alert_config, 'alert_value', ['JSON']) if hasattr(config.alert_config, 'alert_value') else ['JSON'])
303
+ }
304
+ })
305
+ elif category in summary.get("per_category_count", {}):
306
+ count = summary.get("per_category_count", {})[category]
307
+ if count > threshold: # Fixed logic: alert when EXCEEDING threshold
308
+ alerts.append({
309
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
310
+ "alert_id": "alert_"+category+'_'+frame_key,
311
+ "incident_category": self.CASE_TYPE,
312
+ "threshold_level": threshold,
313
+ "ascending": get_trend(self._ascending_alert_list, lookback=900, threshold=0.8),
314
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
315
+ getattr(config.alert_config, 'alert_value', ['JSON']) if hasattr(config.alert_config, 'alert_value') else ['JSON'])
316
+ }
317
+ })
318
+ else:
319
+ pass
320
+ return alerts
321
+
322
+ def _generate_incidents(self, counting_summary: Dict, alerts: List, config: WaterBodyConfig,
323
+ frame_number: Optional[int] = None, stream_info: Optional[Dict[str, Any]] = None) -> List[
324
+ Dict]:
325
+ """Generate structured events for the output format with frame-based keys."""
326
+
327
+ # Use frame number as key, fallback to 'current_frame' if not available
328
+ frame_key = str(frame_number) if frame_number is not None else "current_frame"
329
+ incidents=[]
330
+ total_detections = counting_summary.get("total_count", 0)
331
+ current_timestamp = self._get_current_timestamp_str(stream_info)
332
+ camera_info = self.get_camera_info_from_stream(stream_info)
333
+
334
+ self._ascending_alert_list = self._ascending_alert_list[-900:] if len(self._ascending_alert_list) > 900 else self._ascending_alert_list
335
+
336
+ if total_detections > 0:
337
+ # Determine event level based on thresholds
338
+ level = "low"
339
+ intensity = 5.0
340
+ start_timestamp = self._get_start_timestamp_str(stream_info)
341
+ if start_timestamp and self.current_incident_end_timestamp=='N/A':
342
+ self.current_incident_end_timestamp = 'Incident still active'
343
+ elif start_timestamp and self.current_incident_end_timestamp=='Incident still active':
344
+ if len(self._ascending_alert_list) >= 15 and sum(self._ascending_alert_list[-15:]) / 15 < 1.5:
345
+ self.current_incident_end_timestamp = current_timestamp
346
+ elif self.current_incident_end_timestamp!='Incident still active' and self.current_incident_end_timestamp!='N/A':
347
+ self.current_incident_end_timestamp = 'N/A'
348
+
349
+ if config.alert_config and config.alert_config.count_thresholds:
350
+ threshold = config.alert_config.count_thresholds.get("all", 15)
351
+ intensity = min(10.0, (total_detections / threshold) * 10)
352
+
353
+ if intensity >= 9:
354
+ level = "critical"
355
+ self._ascending_alert_list.append(3)
356
+ elif intensity >= 7:
357
+ level = "significant"
358
+ self._ascending_alert_list.append(2)
359
+ elif intensity >= 5:
360
+ level = "medium"
361
+ self._ascending_alert_list.append(1)
362
+ else:
363
+ level = "low"
364
+ self._ascending_alert_list.append(0)
365
+ else:
366
+ if total_detections > 30:
367
+ level = "critical"
368
+ intensity = 10.0
369
+ self._ascending_alert_list.append(3)
370
+ elif total_detections > 25:
371
+ level = "significant"
372
+ intensity = 9.0
373
+ self._ascending_alert_list.append(2)
374
+ elif total_detections > 15:
375
+ level = "medium"
376
+ intensity = 7.0
377
+ self._ascending_alert_list.append(1)
378
+ else:
379
+ level = "low"
380
+ intensity = min(10.0, total_detections / 3.0)
381
+ self._ascending_alert_list.append(0)
382
+
383
+ # Generate human text in new format
384
+ human_text_lines = [f"INCIDENTS DETECTED @ {current_timestamp}:"]
385
+ human_text_lines.append(f"\tSeverity Level: {(self.CASE_TYPE,level)}")
386
+ human_text = "\n".join(human_text_lines)
387
+
388
+ alert_settings=[]
389
+ if config.alert_config and hasattr(config.alert_config, 'alert_type'):
390
+ alert_settings.append({
391
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
392
+ "incident_category": self.CASE_TYPE,
393
+ "threshold_level": config.alert_config.count_thresholds if hasattr(config.alert_config, 'count_thresholds') else {},
394
+ "ascending": True,
395
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
396
+ getattr(config.alert_config, 'alert_value', ['JSON']) if hasattr(config.alert_config, 'alert_value') else ['JSON'])
397
+ }
398
+ })
399
+
400
+ event= self.create_incident(incident_id=self.CASE_TYPE+'_'+str(frame_number), incident_type=self.CASE_TYPE,
401
+ severity_level=level, human_text=human_text, camera_info=camera_info, alerts=alerts, alert_settings=alert_settings,
402
+ start_time=start_timestamp, end_time=self.current_incident_end_timestamp,
403
+ level_settings= {"low": 1, "medium": 3, "significant":4, "critical": 7})
404
+ incidents.append(event)
405
+
406
+ else:
407
+ self._ascending_alert_list.append(0)
408
+ incidents.append({})
409
+
410
+ return incidents
411
+
412
+ def _generate_tracking_stats(
413
+ self,
414
+ counting_summary: Dict,
415
+ alerts: Any,
416
+ config: WaterBodyConfig,
417
+ frame_number: Optional[int] = None,
418
+ stream_info: Optional[Dict[str, Any]] = None
419
+ ) -> List[Dict]:
420
+ """Generate structured tracking stats for the output format with frame-based keys, including track_ids_info and detections with masks."""
421
+ # frame_key = str(frame_number) if frame_number is not None else "current_frame"
422
+ # tracking_stats = [{frame_key: []}]
423
+ # frame_tracking_stats = tracking_stats[0][frame_key]
424
+ tracking_stats = []
425
+
426
+ total_detections = counting_summary.get("total_count", 0)
427
+ total_counts = counting_summary.get("total_counts", {})
428
+ cumulative_total = sum(total_counts.values()) if total_counts else 0
429
+ per_category_count = counting_summary.get("per_category_count", {})
430
+
431
+ track_ids_info = self._get_track_ids_info(counting_summary.get("detections", []))
432
+
433
+ current_timestamp = self._get_current_timestamp_str(stream_info, precision=False)
434
+ start_timestamp = self._get_start_timestamp_str(stream_info, precision=False)
435
+
436
+ # Create high precision timestamps for input_timestamp and reset_timestamp
437
+ high_precision_start_timestamp = self._get_current_timestamp_str(stream_info, precision=True)
438
+ high_precision_reset_timestamp = self._get_start_timestamp_str(stream_info, precision=True)
439
+
440
+ camera_info = self.get_camera_info_from_stream(stream_info)
441
+ human_text_lines = []
442
+
443
+ # CURRENT FRAME section
444
+ human_text_lines.append(f"CURRENT FRAME @ {current_timestamp}:")
445
+ if total_detections > 0:
446
+ category_counts = [f"{count} {cat}" for cat, count in per_category_count.items()]
447
+ if len(category_counts) == 1:
448
+ detection_text = category_counts[0] + " detected"
449
+ elif len(category_counts) == 2:
450
+ detection_text = f"{category_counts[0]} and {category_counts[1]} detected"
451
+ else:
452
+ detection_text = f"{', '.join(category_counts[:-1])}, and {category_counts[-1]} detected"
453
+ human_text_lines.append(f"\t- {detection_text}")
454
+ else:
455
+ human_text_lines.append(f"\t- No detections")
456
+
457
+ human_text_lines.append("") # spacing
458
+
459
+ # TOTAL SINCE section
460
+ human_text_lines.append(f"TOTAL SINCE {start_timestamp}:")
461
+ human_text_lines.append(f"\t- Total Detected: {cumulative_total}")
462
+ # Add category-wise counts
463
+ print(total_counts)
464
+ if total_counts:
465
+ for cat, count in total_counts.items():
466
+ if count > 0: # Only include categories with non-zero counts
467
+ if cat == "Point d-eau":
468
+ cat = "Water Body"
469
+ human_text_lines.append(f"\t- {cat}: {count}")
470
+ # Build current_counts array in expected format
471
+ current_counts = []
472
+ for cat, count in per_category_count.items():
473
+ if count > 0 or total_detections > 0: # Include even if 0 when there are detections
474
+ if cat == "Point d-eau":
475
+ cat = "Water Body"
476
+ current_counts.append({
477
+ "category": cat,
478
+ "count": count
479
+ })
480
+
481
+ human_text = "\n".join(human_text_lines)
482
+
483
+ # Include detections with masks from counting_summary
484
+ # Prepare detections without confidence scores (as per eg.json)
485
+ detections = []
486
+ for detection in counting_summary.get("detections", []):
487
+ bbox = detection.get("bounding_box", {})
488
+ category = detection.get("category", "person")
489
+ if category == "Point d-eau":
490
+ category = "Water Body"
491
+ # Include segmentation if available (like in eg.json)
492
+ if detection.get("masks"):
493
+ segmentation= detection.get("masks", [])
494
+ detection_obj = self.create_detection_object(category, bbox, segmentation=segmentation)
495
+ elif detection.get("segmentation"):
496
+ segmentation= detection.get("segmentation")
497
+ detection_obj = self.create_detection_object(category, bbox, segmentation=segmentation)
498
+ elif detection.get("mask"):
499
+ segmentation= detection.get("mask")
500
+ detection_obj = self.create_detection_object(category, bbox, segmentation=segmentation)
501
+ else:
502
+ detection_obj = self.create_detection_object(category, bbox)
503
+ detections.append(detection_obj)
504
+
505
+ # Build alert_settings array in expected format
506
+ alert_settings = []
507
+ if config.alert_config and hasattr(config.alert_config, 'alert_type'):
508
+ alert_settings.append({
509
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
510
+ "incident_category": self.CASE_TYPE,
511
+ "threshold_level": config.alert_config.count_thresholds if hasattr(config.alert_config, 'count_thresholds') else {},
512
+ "ascending": True,
513
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
514
+ getattr(config.alert_config, 'alert_value', ['JSON']) if hasattr(config.alert_config, 'alert_value') else ['JSON'])
515
+ }
516
+ })
517
+
518
+ if alerts:
519
+ for alert in alerts:
520
+ human_text_lines.append(f"Alerts: {alert.get('settings', {})} sent @ {current_timestamp}")
521
+ else:
522
+ human_text_lines.append("Alerts: None")
523
+
524
+ human_text = "\n".join(human_text_lines)
525
+ reset_settings = [
526
+ {
527
+ "interval_type": "daily",
528
+ "reset_time": {
529
+ "value": 9,
530
+ "time_unit": "hour"
531
+ }
532
+ }
533
+ ]
534
+
535
+ tracking_stat=self.create_tracking_stats(total_counts=total_counts, current_counts=current_counts,
536
+ detections=detections, human_text=human_text, camera_info=camera_info, alerts=alerts, alert_settings=alert_settings,
537
+ reset_settings=reset_settings, start_time=high_precision_start_timestamp ,
538
+ reset_time=high_precision_reset_timestamp)
539
+
540
+ tracking_stats.append(tracking_stat)
541
+ return tracking_stats
542
+
543
+ def _generate_business_analytics(self, counting_summary: Dict, zone_analysis: Dict, config: WaterBodyConfig, stream_info: Optional[Dict[str, Any]] = None, is_empty=False) -> List[Dict]:
544
+ """Generate standardized business analytics for the agg_summary structure."""
545
+ if is_empty:
546
+ return []
547
+
548
+ #-----IF YOUR USECASE NEEDS BUSINESS ANALYTICS, YOU CAN USE THIS FUNCTION------#
549
+ #camera_info = self.get_camera_info_from_stream(stream_info)
550
+ # business_analytics = self.create_business_analytics(nalysis_name, statistics,
551
+ # human_text, camera_info=camera_info, alerts=alerts, alert_settings=alert_settings,
552
+ # reset_settings)
553
+ # return business_analytics
554
+
555
+ def _generate_summary(self, summary: dict, incidents: List, tracking_stats: List, business_analytics: List, alerts: List) -> List[str]:
556
+ """
557
+ Generate a human_text string for the tracking_stat, incident, business analytics and alerts.
558
+ """
559
+ lines = {}
560
+ lines["Application Name"] = self.CASE_TYPE
561
+ lines["Application Version"] = self.CASE_VERSION
562
+ if len(incidents) > 0:
563
+ lines["Incidents:"]=f"\n\t{incidents[0].get('human_text', 'No incidents detected')}\n"
564
+ if len(tracking_stats) > 0:
565
+ lines["Tracking Statistics:"]=f"\t{tracking_stats[0].get('human_text', 'No tracking statistics detected')}\n"
566
+ if len(business_analytics) > 0:
567
+ lines["Business Analytics:"]=f"\t{business_analytics[0].get('human_text', 'No business analytics detected')}\n"
568
+
569
+ if len(incidents) == 0 and len(tracking_stats) == 0 and len(business_analytics) == 0:
570
+ lines["Summary"] = "No Summary Data"
571
+
572
+ return [lines]
573
+
574
+
575
+ def _count_categories(self, detections: list, config: WaterBodyConfig) -> dict:
576
+ """
577
+ Count the number of detections per category and return a summary dict.
578
+ The detections list is expected to have 'track_id' (from tracker), 'category', 'bounding_box', 'masks', etc.
579
+ Output structure will include 'track_id' and 'masks' for each detection as per AdvancedTracker output.
580
+ """
581
+ counts = {}
582
+ valid_detections = []
583
+ for det in detections:
584
+ cat = det.get('category', 'unknown')
585
+ if cat == "Point d-eau":
586
+ cat = "Water Body"
587
+ if not all(k in det for k in ['category', 'confidence', 'bounding_box']): # Validate required fields
588
+ self.logger.warning(f"Skipping invalid detection: {det}")
589
+ continue
590
+ counts[cat] = counts.get(cat, 0) + 1
591
+ valid_detections.append({
592
+ "bounding_box": det.get("bounding_box"),
593
+ "category": det.get("category"),
594
+ "confidence": det.get("confidence"),
595
+ "track_id": det.get("track_id"),
596
+ "frame_id": det.get("frame_id"),
597
+ "masks": det.get("masks", det.get("mask", [])) # Include masks, fallback to empty list
598
+ })
599
+ self.logger.debug(f"Valid detections after filtering: {len(valid_detections)}")
600
+ return {
601
+ "total_count": sum(counts.values()),
602
+ "per_category_count": counts,
603
+ "detections": valid_detections
604
+ }
605
+
606
+ def _get_track_ids_info(self, detections: list) -> Dict[str, Any]:
607
+ """
608
+ Get detailed information about track IDs (per frame).
609
+ """
610
+ # Collect all track_ids in this frame
611
+ frame_track_ids = set()
612
+ for det in detections:
613
+ tid = det.get('track_id')
614
+ if tid is not None:
615
+ frame_track_ids.add(tid)
616
+ # Use persistent total set for unique counting
617
+ total_track_ids = set()
618
+ for s in getattr(self, '_per_category_total_track_ids', {}).values():
619
+ total_track_ids.update(s)
620
+ return {
621
+ "total_count": len(total_track_ids),
622
+ "current_frame_count": len(frame_track_ids),
623
+ "total_unique_track_ids": len(total_track_ids),
624
+ "current_frame_track_ids": list(frame_track_ids),
625
+ "last_update_time": time.time(),
626
+ "total_frames_processed": getattr(self, '_total_frame_counter', 0)
627
+ }
628
+
629
+ def _update_tracking_state(self, detections: list):
630
+ """
631
+ Track unique categories track_ids per category for total count after tracking.
632
+ Applies canonical ID merging to avoid duplicate counting when the underlying
633
+ tracker loses an object temporarily and assigns a new ID.
634
+ """
635
+ # Lazily initialise storage dicts
636
+ if not hasattr(self, "_per_category_total_track_ids"):
637
+ self._per_category_total_track_ids = {cat: set() for cat in self.target_categories}
638
+ self._current_frame_track_ids = {cat: set() for cat in self.target_categories}
639
+
640
+ for det in detections:
641
+ cat = det.get("category")
642
+ raw_track_id = det.get("track_id")
643
+ if cat not in self.target_categories or raw_track_id is None:
644
+ continue
645
+ bbox = det.get("bounding_box", det.get("bbox"))
646
+ canonical_id = self._merge_or_register_track(raw_track_id, bbox)
647
+ # Propagate canonical ID back to detection so downstream logic uses it
648
+ det["track_id"] = canonical_id
649
+
650
+ self._per_category_total_track_ids.setdefault(cat, set()).add(canonical_id)
651
+ self._current_frame_track_ids[cat].add(canonical_id)
652
+
653
+ def get_total_counts(self):
654
+ """
655
+ Return total unique track_id count for each category.
656
+ """
657
+ return {cat: len(ids) for cat, ids in getattr(self, '_per_category_total_track_ids', {}).items()}
658
+
659
+ def _format_timestamp_for_video(self, timestamp: float) -> str:
660
+ """Format timestamp for video chunks (HH:MM:SS.ms format)."""
661
+ hours = int(timestamp // 3600)
662
+ minutes = int((timestamp % 3600) // 60)
663
+ seconds = round(float(timestamp % 60),2)
664
+ return f"{hours:02d}:{minutes:02d}:{seconds:.1f}"
665
+
666
+ def _format_timestamp_for_stream(self, timestamp: float) -> str:
667
+ """Format timestamp for streams (YYYY:MM:DD HH:MM:SS format)."""
668
+ dt = datetime.fromtimestamp(timestamp, tz=timezone.utc)
669
+ return dt.strftime('%Y:%m:%d %H:%M:%S')
670
+
671
+ def _get_current_timestamp_str(self, stream_info: Optional[Dict[str, Any]], precision=False, frame_id: Optional[str]=None) -> str:
672
+ """Get formatted current timestamp based on stream type."""
673
+ if not stream_info:
674
+ return "00:00:00.00"
675
+ # is_video_chunk = stream_info.get("input_settings", {}).get("is_video_chunk", False)
676
+ if precision:
677
+ if stream_info.get("input_settings", {}).get("start_frame", "na") != "na":
678
+ if frame_id:
679
+ start_time = int(frame_id)/stream_info.get("input_settings", {}).get("original_fps", 30)
680
+ else:
681
+ start_time = stream_info.get("input_settings", {}).get("start_frame", 30)/stream_info.get("input_settings", {}).get("original_fps", 30)
682
+ stream_time_str = self._format_timestamp_for_video(start_time)
683
+ return stream_time_str
684
+ else:
685
+ return datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
686
+
687
+ if stream_info.get("input_settings", {}).get("start_frame", "na") != "na":
688
+ if frame_id:
689
+ start_time = int(frame_id)/stream_info.get("input_settings", {}).get("original_fps", 30)
690
+ else:
691
+ start_time = stream_info.get("input_settings", {}).get("start_frame", 30)/stream_info.get("input_settings", {}).get("original_fps", 30)
692
+ stream_time_str = self._format_timestamp_for_video(start_time)
693
+ return stream_time_str
694
+ else:
695
+ # For streams, use stream_time from stream_info
696
+ stream_time_str = stream_info.get("input_settings", {}).get("stream_info", {}).get("stream_time", "")
697
+ if stream_time_str:
698
+ # Parse the high precision timestamp string to get timestamp
699
+ try:
700
+ # Remove " UTC" suffix and parse
701
+ timestamp_str = stream_time_str.replace(" UTC", "")
702
+ dt = datetime.strptime(timestamp_str, "%Y-%m-%d-%H:%M:%S.%f")
703
+ timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
704
+ return self._format_timestamp_for_stream(timestamp)
705
+ except:
706
+ # Fallback to current time if parsing fails
707
+ return self._format_timestamp_for_stream(time.time())
708
+ else:
709
+ return self._format_timestamp_for_stream(time.time())
710
+
711
+ def _get_start_timestamp_str(self, stream_info: Optional[Dict[str, Any]], precision=False) -> str:
712
+ """Get formatted start timestamp for 'TOTAL SINCE' based on stream type."""
713
+ if not stream_info:
714
+ return "00:00:00"
715
+ if precision:
716
+ if stream_info.get("input_settings", {}).get("start_frame", "na") != "na":
717
+ return "00:00:00"
718
+ else:
719
+ return datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
720
+
721
+ if stream_info.get("input_settings", {}).get("start_frame", "na") != "na":
722
+ # If video format, start from 00:00:00
723
+ return "00:00:00"
724
+ else:
725
+ # For streams, use tracking start time or current time with minutes/seconds reset
726
+ if self._tracking_start_time is None:
727
+ # Try to extract timestamp from stream_time string
728
+ stream_time_str = stream_info.get("input_settings", {}).get("stream_info", {}).get("stream_time", "")
729
+ if stream_time_str:
730
+ try:
731
+ # Remove " UTC" suffix and parse
732
+ timestamp_str = stream_time_str.replace(" UTC", "")
733
+ dt = datetime.strptime(timestamp_str, "%Y-%m-%d-%H:%M:%S.%f")
734
+ self._tracking_start_time = dt.replace(tzinfo=timezone.utc).timestamp()
735
+ except:
736
+ # Fallback to current time if parsing fails
737
+ self._tracking_start_time = time.time()
738
+ else:
739
+ self._tracking_start_time = time.time()
740
+
741
+ dt = datetime.fromtimestamp(self._tracking_start_time, tz=timezone.utc)
742
+ # Reset minutes and seconds to 00:00 for "TOTAL SINCE" format
743
+ dt = dt.replace(minute=0, second=0, microsecond=0)
744
+ return dt.strftime('%Y:%m:%d %H:%M:%S')
745
+
746
+ # ------------------------------------------------------------------ #
747
+ # Helper to merge masks back into detections #
748
+ # ------------------------------------------------------------------ #
749
+ def _attach_masks_to_detections(
750
+ self,
751
+ processed_detections: List[Dict[str, Any]],
752
+ raw_detections: List[Dict[str, Any]],
753
+ iou_threshold: float = 0.5,
754
+ ) -> List[Dict[str, Any]]:
755
+ """
756
+ Attach segmentation masks from the original `raw_detections` list to the
757
+ `processed_detections` list returned after smoothing/tracking.
758
+
759
+ Matching between detections is performed using Intersection-over-Union
760
+ (IoU) of the bounding boxes. For each processed detection we select the
761
+ raw detection with the highest IoU above `iou_threshold` and copy its
762
+ `masks` (or `mask`) field. If no suitable match is found, the detection
763
+ keeps an empty list for `masks` to maintain a consistent schema.
764
+ """
765
+
766
+ if not processed_detections or not raw_detections:
767
+ # Nothing to do – ensure masks key exists for downstream logic.
768
+ for det in processed_detections:
769
+ det.setdefault("masks", [])
770
+ return processed_detections
771
+
772
+ # Track which raw detections have already been matched to avoid
773
+ # assigning the same mask to multiple processed detections.
774
+ used_raw_indices = set()
775
+
776
+ for det in processed_detections:
777
+ best_iou = 0.0
778
+ best_idx = None
779
+
780
+ for idx, raw_det in enumerate(raw_detections):
781
+ if idx in used_raw_indices:
782
+ continue
783
+
784
+ iou = self._compute_iou(det.get("bounding_box"), raw_det.get("bounding_box"))
785
+ if iou > best_iou:
786
+ best_iou = iou
787
+ best_idx = idx
788
+
789
+ if best_idx is not None and best_iou >= iou_threshold:
790
+ raw_det = raw_detections[best_idx]
791
+ masks = raw_det.get("masks", raw_det.get("mask"))
792
+ if masks is not None:
793
+ det["masks"] = masks
794
+ used_raw_indices.add(best_idx)
795
+ else:
796
+ # No adequate match – default to empty list to keep schema consistent.
797
+ det.setdefault("masks", ["EMPTY"])
798
+
799
+ return processed_detections
800
+
801
+ def _extract_predictions(self, detections: list) -> List[Dict[str, Any]]:
802
+ """
803
+ Extract prediction details for output (category, confidence, bounding box).
804
+ """
805
+ return [
806
+ {
807
+ "category": det.get("category", "unknown"),
808
+ "confidence": det.get("confidence", 0.0),
809
+ "bounding_box": det.get("bounding_box", {}),
810
+ "mask": det.get("mask", det.get("masks", None)) # Accept either key
811
+ }
812
+ for det in detections
813
+ ]
814
+
815
+
816
+ # ------------------------------------------------------------------ #
817
+ # Canonical ID helpers #
818
+ # ------------------------------------------------------------------ #
819
+ def _compute_iou(self, box1: Any, box2: Any) -> float:
820
+ """Compute IoU between two bounding boxes which may be dicts or lists.
821
+ Falls back to 0 when insufficient data is available."""
822
+
823
+ # Helper to convert bbox (dict or list) to [x1, y1, x2, y2]
824
+ def _bbox_to_list(bbox):
825
+ if bbox is None:
826
+ return []
827
+ if isinstance(bbox, list):
828
+ return bbox[:4] if len(bbox) >= 4 else []
829
+ if isinstance(bbox, dict):
830
+ if "xmin" in bbox:
831
+ return [bbox["xmin"], bbox["ymin"], bbox["xmax"], bbox["ymax"]]
832
+ if "x1" in bbox:
833
+ return [bbox["x1"], bbox["y1"], bbox["x2"], bbox["y2"]]
834
+ # Fallback: first four numeric values
835
+ values = [v for v in bbox.values() if isinstance(v, (int, float))]
836
+ return values[:4] if len(values) >= 4 else []
837
+ return []
838
+
839
+ l1 = _bbox_to_list(box1)
840
+ l2 = _bbox_to_list(box2)
841
+ if len(l1) < 4 or len(l2) < 4:
842
+ return 0.0
843
+ x1_min, y1_min, x1_max, y1_max = l1
844
+ x2_min, y2_min, x2_max, y2_max = l2
845
+
846
+ # Ensure correct order
847
+ x1_min, x1_max = min(x1_min, x1_max), max(x1_min, x1_max)
848
+ y1_min, y1_max = min(y1_min, y1_max), max(y1_min, y1_max)
849
+ x2_min, x2_max = min(x2_min, x2_max), max(x2_min, x2_max)
850
+ y2_min, y2_max = min(y2_min, y2_max), max(y2_min, y2_max)
851
+
852
+ inter_x_min = max(x1_min, x2_min)
853
+ inter_y_min = max(y1_min, y2_min)
854
+ inter_x_max = min(x1_max, x2_max)
855
+ inter_y_max = min(y1_max, y2_max)
856
+
857
+ inter_w = max(0.0, inter_x_max - inter_x_min)
858
+ inter_h = max(0.0, inter_y_max - inter_y_min)
859
+ inter_area = inter_w * inter_h
860
+
861
+ area1 = (x1_max - x1_min) * (y1_max - y1_min)
862
+ area2 = (x2_max - x2_min) * (y2_max - y2_min)
863
+ union_area = area1 + area2 - inter_area
864
+
865
+ return (inter_area / union_area) if union_area > 0 else 0.0
866
+
867
+ def _merge_or_register_track(self, raw_id: Any, bbox: Any) -> Any:
868
+ """Return a stable canonical ID for a raw tracker ID, merging fragmented
869
+ tracks when IoU and temporal constraints indicate they represent the
870
+ same physical."""
871
+ if raw_id is None or bbox is None:
872
+ # Nothing to merge
873
+ return raw_id
874
+
875
+ now = time.time()
876
+
877
+ # Fast path – raw_id already mapped
878
+ if raw_id in self._track_aliases:
879
+ canonical_id = self._track_aliases[raw_id]
880
+ track_info = self._canonical_tracks.get(canonical_id)
881
+ if track_info is not None:
882
+ track_info["last_bbox"] = bbox
883
+ track_info["last_update"] = now
884
+ track_info["raw_ids"].add(raw_id)
885
+ return canonical_id
886
+
887
+ # Attempt to merge with an existing canonical track
888
+ for canonical_id, info in self._canonical_tracks.items():
889
+ # Only consider recently updated tracks
890
+ if now - info["last_update"] > self._track_merge_time_window:
891
+ continue
892
+ iou = self._compute_iou(bbox, info["last_bbox"])
893
+ if iou >= self._track_merge_iou_threshold:
894
+ # Merge
895
+ self._track_aliases[raw_id] = canonical_id
896
+ info["last_bbox"] = bbox
897
+ info["last_update"] = now
898
+ info["raw_ids"].add(raw_id)
899
+ return canonical_id
900
+
901
+ # No match – register new canonical track
902
+ canonical_id = raw_id
903
+ self._track_aliases[raw_id] = canonical_id
904
+ self._canonical_tracks[canonical_id] = {
905
+ "last_bbox": bbox,
906
+ "last_update": now,
907
+ "raw_ids": {raw_id},
908
+ }
909
+ return canonical_id
910
+
911
+ def _format_timestamp(self, timestamp: float) -> str:
912
+ """Format a timestamp for human-readable output."""
913
+ return datetime.fromtimestamp(timestamp, timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')
914
+
915
+ def _get_tracking_start_time(self) -> str:
916
+ """Get the tracking start time, formatted as a string."""
917
+ if self._tracking_start_time is None:
918
+ return "N/A"
919
+ return self._format_timestamp(self._tracking_start_time)
920
+
921
+ def _set_tracking_start_time(self) -> None:
922
+ """Set the tracking start time to the current time."""
923
+ self._tracking_start_time = time.time()