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,856 @@
1
+ """
2
+ wound segmentation Monitoring Use Case for Post-Processing
3
+
4
+ This module provides wound segmentation functionality ,
5
+ zone analysis, and alert generation.
6
+
7
+ """
8
+
9
+ from typing import Any, Dict, List, Optional
10
+ from dataclasses import asdict
11
+ import time
12
+ from datetime import datetime, timezone
13
+ import copy # Added for deep copying detections to preserve original masks
14
+
15
+ from ..core.base import BaseProcessor, ProcessingContext, ProcessingResult, ConfigProtocol, ResultFormat
16
+ from ..utils import (
17
+ filter_by_confidence,
18
+ filter_by_categories,
19
+ apply_category_mapping,
20
+ count_objects_by_category,
21
+ count_objects_in_zones,
22
+ calculate_counting_summary,
23
+ match_results_structure,
24
+ bbox_smoothing,
25
+ BBoxSmoothingConfig,
26
+ BBoxSmoothingTracker
27
+ )
28
+ from dataclasses import dataclass, field
29
+ from ..core.config import BaseConfig, AlertConfig, ZoneConfig
30
+
31
+
32
+ @dataclass
33
+ class WoundConfig(BaseConfig):
34
+ """Configuration for wound detection use case in wound monitoring."""
35
+ # Smoothing configuration
36
+ enable_smoothing: bool = True
37
+ smoothing_algorithm: str = "observability" # "window" or "observability"
38
+ smoothing_window_size: int = 20
39
+ smoothing_cooldown_frames: int = 5
40
+ smoothing_confidence_range_factor: float = 0.5
41
+
42
+ # confidence thresholds
43
+ confidence_threshold: float = 0.6
44
+
45
+ usecase_categories: List[str] = field(
46
+ default_factory=lambda: ['wound']
47
+ )
48
+
49
+ target_categories: List[str] = field(
50
+ default_factory=lambda: ['wound']
51
+ )
52
+
53
+ alert_config: Optional[AlertConfig] = None
54
+
55
+ index_to_category: Optional[Dict[int, str]] = field(
56
+ default_factory=lambda: {
57
+ 0: "wound"
58
+
59
+ }
60
+ )
61
+
62
+
63
+ class WoundSegmentationUseCase(BaseProcessor):
64
+ def _get_track_ids_info(self, detections: list) -> Dict[str, Any]:
65
+ """
66
+ Get detailed information about track IDs (per frame).
67
+ """
68
+ # Collect all track_ids in this frame
69
+ frame_track_ids = set()
70
+ for det in detections:
71
+ tid = det.get('track_id')
72
+ if tid is not None:
73
+ frame_track_ids.add(tid)
74
+ # Use persistent total set for unique counting
75
+ total_track_ids = set()
76
+ for s in getattr(self, '_per_category_total_track_ids', {}).values():
77
+ total_track_ids.update(s)
78
+ return {
79
+ "total_count": len(total_track_ids),
80
+ "current_frame_count": len(frame_track_ids),
81
+ "total_unique_track_ids": len(total_track_ids),
82
+ "current_frame_track_ids": list(frame_track_ids),
83
+ "last_update_time": time.time(),
84
+ "total_frames_processed": getattr(self, '_total_frame_counter', 0)
85
+ }
86
+
87
+ def _update_tracking_state(self, detections: list):
88
+ """
89
+ Track unique categories track_ids per category for total count after tracking.
90
+ Applies canonical ID merging to avoid duplicate counting when the underlying
91
+ tracker loses an object temporarily and assigns a new ID.
92
+ """
93
+ # Lazily initialise storage dicts
94
+ if not hasattr(self, "_per_category_total_track_ids"):
95
+ self._per_category_total_track_ids = {cat: set() for cat in self.target_categories}
96
+ self._current_frame_track_ids = {cat: set() for cat in self.target_categories}
97
+
98
+ for det in detections:
99
+ cat = det.get("category")
100
+ raw_track_id = det.get("track_id")
101
+ if cat not in self.target_categories or raw_track_id is None:
102
+ continue
103
+ bbox = det.get("bounding_box", det.get("bbox"))
104
+ canonical_id = self._merge_or_register_track(raw_track_id, bbox)
105
+ # Propagate canonical ID back to detection so downstream logic uses it
106
+ det["track_id"] = canonical_id
107
+
108
+ self._per_category_total_track_ids.setdefault(cat, set()).add(canonical_id)
109
+ self._current_frame_track_ids[cat].add(canonical_id)
110
+
111
+ def get_total_counts(self):
112
+ """
113
+ Return total unique track_id count for each category.
114
+ """
115
+ return {cat: len(ids) for cat, ids in getattr(self, '_per_category_total_track_ids', {}).items()}
116
+
117
+ def _format_timestamp_for_video(self, timestamp: float) -> str:
118
+ """Format timestamp for video chunks (HH:MM:SS.ms format)."""
119
+ hours = int(timestamp // 3600)
120
+ minutes = int((timestamp % 3600) // 60)
121
+ seconds = timestamp % 60
122
+ return f"{hours:02d}:{minutes:02d}:{seconds:06.2f}"
123
+
124
+ def _format_timestamp_for_stream(self, timestamp: float) -> str:
125
+ """Format timestamp for streams (YYYY:MM:DD HH:MM:SS format)."""
126
+ dt = datetime.fromtimestamp(timestamp, tz=timezone.utc)
127
+ return dt.strftime('%Y:%m:%d %H:%M:%S')
128
+
129
+ def _get_current_timestamp_str(self, stream_info: Optional[Dict[str, Any]]) -> str:
130
+ """Get formatted current timestamp based on stream type."""
131
+ if not stream_info:
132
+ return "00:00:00.00"
133
+
134
+ is_video_chunk = stream_info.get("input_settings", {}).get("is_video_chunk", False)
135
+
136
+ # if is_video_chunk:
137
+ # # For video chunks, use video_timestamp from stream_info
138
+ # video_timestamp = stream_info.get("video_timestamp", 0.0)
139
+ # return self._format_timestamp_for_video(video_timestamp)
140
+ if stream_info.get("input_settings", {}).get("stream_type", "video_file") == "video_file":
141
+ # If video format, return video timestamp
142
+ stream_time_str = stream_info.get("video_timestamp", "")
143
+ return stream_time_str[:8]
144
+ else:
145
+ # For streams, use stream_time from stream_info
146
+ stream_time_str = stream_info.get("stream_time", "")
147
+ if stream_time_str:
148
+ # Parse the high precision timestamp string to get timestamp
149
+ try:
150
+ # Remove " UTC" suffix and parse
151
+ timestamp_str = stream_time_str.replace(" UTC", "")
152
+ dt = datetime.strptime(timestamp_str, "%Y-%m-%d-%H:%M:%S.%f")
153
+ timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
154
+ return self._format_timestamp_for_stream(timestamp)
155
+ except:
156
+ # Fallback to current time if parsing fails
157
+ return self._format_timestamp_for_stream(time.time())
158
+ else:
159
+ return self._format_timestamp_for_stream(time.time())
160
+
161
+ def _get_start_timestamp_str(self, stream_info: Optional[Dict[str, Any]]) -> str:
162
+ """Get formatted start timestamp for 'TOTAL SINCE' based on stream type."""
163
+ if not stream_info:
164
+ return "00:00:00"
165
+
166
+ is_video_chunk = stream_info.get("input_settings", {}).get("is_video_chunk", False)
167
+
168
+ if is_video_chunk:
169
+ # For video chunks, start from 00:00:00
170
+ return "00:00:00"
171
+ elif stream_info.get("input_settings", {}).get("stream_type", "video_file") == "video_file":
172
+ # If video format, start from 00:00:00
173
+ return "00:00:00"
174
+ else:
175
+ # For streams, use tracking start time or current time with minutes/seconds reset
176
+ if self._tracking_start_time is None:
177
+ # Try to extract timestamp from stream_time string
178
+ stream_time_str = stream_info.get("stream_time", "")
179
+ if stream_time_str:
180
+ try:
181
+ # Remove " UTC" suffix and parse
182
+ timestamp_str = stream_time_str.replace(" UTC", "")
183
+ dt = datetime.strptime(timestamp_str, "%Y-%m-%d-%H:%M:%S.%f")
184
+ self._tracking_start_time = dt.replace(tzinfo=timezone.utc).timestamp()
185
+ except:
186
+ # Fallback to current time if parsing fails
187
+ self._tracking_start_time = time.time()
188
+ else:
189
+ self._tracking_start_time = time.time()
190
+
191
+ dt = datetime.fromtimestamp(self._tracking_start_time, tz=timezone.utc)
192
+ # Reset minutes and seconds to 00:00 for "TOTAL SINCE" format
193
+ dt = dt.replace(minute=0, second=0, microsecond=0)
194
+ return dt.strftime('%Y:%m:%d %H:%M:%S')
195
+
196
+ """ Monitoring use case with smoothing and alerting."""
197
+
198
+ def __init__(self):
199
+ super().__init__("wound_segmentation")
200
+ self.category = "medical"
201
+
202
+ # List of categories to track
203
+ self.target_categories = ["wound"]
204
+
205
+ # Initialize smoothing tracker
206
+ self.smoothing_tracker = None
207
+
208
+ # Initialize advanced tracker (will be created on first use)
209
+ self.tracker = None
210
+
211
+ # Initialize tracking state variables
212
+ self._total_frame_counter = 0
213
+ self._global_frame_offset = 0
214
+
215
+ # Track start time for "TOTAL SINCE" calculation
216
+ self._tracking_start_time = None
217
+
218
+ # ------------------------------------------------------------------ #
219
+ # Canonical tracking aliasing to avoid duplicate counts #
220
+ # ------------------------------------------------------------------ #
221
+ # Maps raw tracker-generated IDs to stable canonical IDs that persist
222
+ # even if the underlying tracker re-assigns a new ID after a short
223
+ # interruption. This mirrors the logic used in people_counting to
224
+ # provide accurate unique counting.
225
+ self._track_aliases: Dict[Any, Any] = {}
226
+ self._canonical_tracks: Dict[Any, Dict[str, Any]] = {}
227
+ # Tunable parameters – adjust if necessary for specific scenarios
228
+ self._track_merge_iou_threshold: float = 0.05 # IoU ≥ 0.05 →
229
+ self._track_merge_time_window: float = 7.0 # seconds within which to merge
230
+
231
+ def process(self, data: Any, config: ConfigProtocol, context: Optional[ProcessingContext] = None,
232
+ stream_info: Optional[Dict[str, Any]] = None) -> ProcessingResult:
233
+ """
234
+ Main entry point for post-processing.
235
+ Applies category mapping, smoothing, counting, alerting, and summary generation.
236
+ Returns a ProcessingResult with all relevant outputs.
237
+ """
238
+ start_time = time.time()
239
+ # Ensure config is correct type
240
+ if not isinstance(config, WoundConfig):
241
+ return self.create_error_result("Invalid config type", usecase=self.name, category=self.category,
242
+ context=context)
243
+ if context is None:
244
+ context = ProcessingContext()
245
+
246
+ # Detect input format and store in context
247
+ input_format = match_results_structure(data)
248
+ context.input_format = input_format
249
+ context.confidence_threshold = config.confidence_threshold
250
+
251
+ # Step 1: Confidence filtering
252
+ if config.confidence_threshold is not None:
253
+ processed_data = filter_by_confidence(data, config.confidence_threshold)
254
+ else:
255
+ processed_data = data
256
+ self.logger.debug(f"Did not apply confidence filtering with threshold since nothing was provided")
257
+
258
+ # Step 2: Apply category mapping if provided
259
+ if config.index_to_category:
260
+ processed_data = apply_category_mapping(processed_data, config.index_to_category)
261
+
262
+ # Step 3: Category filtering
263
+ if config.target_categories:
264
+ processed_data = [d for d in processed_data if d.get('category') in self.target_categories]
265
+
266
+ # Step 4: Apply bbox smoothing if enabled
267
+ # Deep-copy detections so that we preserve the original masks before any
268
+ # smoothing/tracking logic potentially removes them.
269
+ raw_processed_data = [copy.deepcopy(det) for det in processed_data]
270
+ if config.enable_smoothing:
271
+ if self.smoothing_tracker is None:
272
+ smoothing_config = BBoxSmoothingConfig(
273
+ smoothing_algorithm=config.smoothing_algorithm,
274
+ window_size=config.smoothing_window_size,
275
+ cooldown_frames=config.smoothing_cooldown_frames,
276
+ confidence_threshold=config.confidence_threshold,
277
+ confidence_range_factor=config.smoothing_confidence_range_factor,
278
+ enable_smoothing=True
279
+ )
280
+ self.smoothing_tracker = BBoxSmoothingTracker(smoothing_config)
281
+
282
+ processed_data = bbox_smoothing(processed_data, self.smoothing_tracker.config, self.smoothing_tracker)
283
+ # Restore masks after smoothing
284
+
285
+ # Step 5: Advanced tracking (BYTETracker-like)
286
+ try:
287
+ from ..advanced_tracker import AdvancedTracker
288
+ from ..advanced_tracker.config import TrackerConfig
289
+
290
+ # Create tracker instance if it doesn't exist (preserves state across frames)
291
+ if self.tracker is None:
292
+ tracker_config = TrackerConfig()
293
+ self.tracker = AdvancedTracker(tracker_config)
294
+ self.logger.info("Initialized AdvancedTracker for Monitoring and tracking")
295
+
296
+ processed_data = self.tracker.update(processed_data)
297
+ except Exception as e:
298
+ # If advanced tracker fails, fallback to unsmoothed detections
299
+ self.logger.warning(f"AdvancedTracker failed: {e}")
300
+
301
+ # Update tracking state for total count per label
302
+ self._update_tracking_state(processed_data)
303
+
304
+ # ------------------------------------------------------------------ #
305
+ # Re-attach segmentation masks that were present in the original input
306
+ # but may have been stripped during smoothing/tracking. We match each
307
+ # processed detection back to the raw detection with the highest IoU
308
+ # and copy over its "masks" field (if available).
309
+ # ------------------------------------------------------------------ #
310
+ processed_data = self._attach_masks_to_detections(processed_data, raw_processed_data)
311
+
312
+ # Update frame counter
313
+ self._total_frame_counter += 1
314
+
315
+ # Extract frame information from stream_info
316
+ frame_number = None
317
+ if stream_info:
318
+ input_settings = stream_info.get("input_settings", {})
319
+ start_frame = input_settings.get("start_frame")
320
+ end_frame = input_settings.get("end_frame")
321
+ # If start and end frame are the same, it's a single frame
322
+ if start_frame is not None and end_frame is not None and start_frame == end_frame:
323
+ frame_number = start_frame
324
+
325
+ # Compute summaries and alerts
326
+ general_counting_summary = calculate_counting_summary(data)
327
+ counting_summary = self._count_categories(processed_data, config)
328
+ # Add total unique counts after tracking using only local state
329
+ total_counts = self.get_total_counts()
330
+ counting_summary['total_counts'] = total_counts
331
+
332
+ insights = self._generate_insights(counting_summary, config)
333
+ alerts = self._check_alerts(counting_summary, config)
334
+ predictions = self._extract_predictions(processed_data)
335
+ summary = self._generate_summary(counting_summary, alerts)
336
+
337
+ # Step: Generate structured events and tracking stats with frame-based keys
338
+ events_list = self._generate_events(counting_summary, alerts, config, frame_number, stream_info)
339
+ tracking_stats_list = self._generate_tracking_stats(counting_summary, insights, summary, config, frame_number,
340
+ stream_info)
341
+
342
+ # Extract frame-based dictionaries from the lists
343
+ events = events_list[0] if events_list else {}
344
+ tracking_stats = tracking_stats_list[0] if tracking_stats_list else {}
345
+
346
+ context.mark_completed()
347
+
348
+ # Build result object
349
+ result = self.create_result(
350
+ data={
351
+ "counting_summary": counting_summary,
352
+ "general_counting_summary": general_counting_summary,
353
+ "alerts": alerts,
354
+ "total_detections": counting_summary.get("total_count", 0),
355
+ "events": events,
356
+ "tracking_stats": tracking_stats,
357
+ },
358
+ usecase=self.name,
359
+ category=self.category,
360
+ context=context
361
+ )
362
+ result.summary = summary
363
+ result.insights = insights
364
+ result.predictions = predictions
365
+ return result
366
+
367
+ def _generate_events(self, counting_summary: Dict, alerts: List, config: WoundConfig,
368
+ frame_number: Optional[int] = None, stream_info: Optional[Dict[str, Any]] = None) -> List[
369
+ Dict]:
370
+ """Generate structured events for the output format with frame-based keys."""
371
+ from datetime import datetime, timezone
372
+
373
+ # Use frame number as key, fallback to 'current_frame' if not available
374
+ frame_key = str(frame_number) if frame_number is not None else "current_frame"
375
+ events = [{frame_key: []}]
376
+ frame_events = events[0][frame_key]
377
+ total_detections = counting_summary.get("total_count", 0)
378
+
379
+ if total_detections > 0:
380
+ # Determine event level based on thresholds
381
+ level = "info"
382
+ intensity = 5.0
383
+ if config.alert_config and config.alert_config.count_thresholds:
384
+ threshold = config.alert_config.count_thresholds.get("all", 15)
385
+ intensity = min(10.0, (total_detections / threshold) * 10)
386
+
387
+ if intensity >= 7:
388
+ level = "critical"
389
+ elif intensity >= 5:
390
+ level = "warning"
391
+ else:
392
+ level = "info"
393
+ else:
394
+ if total_detections > 25:
395
+ level = "critical"
396
+ intensity = 9.0
397
+ elif total_detections > 15:
398
+ level = "warning"
399
+ intensity = 7.0
400
+ else:
401
+ level = "info"
402
+ intensity = min(10.0, total_detections / 3.0)
403
+
404
+ # Generate human text in new format
405
+ human_text_lines = ["EVENTS DETECTED:"]
406
+ human_text_lines.append(f" - {total_detections} detected [INFO]")
407
+ human_text = "\n".join(human_text_lines)
408
+
409
+ event = {
410
+ "type": "wound_segmentation",
411
+ "stream_time": datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S UTC"),
412
+ "level": level,
413
+ "intensity": round(intensity, 1),
414
+ "config": {
415
+ "min_value": 0,
416
+ "max_value": 10,
417
+ "level_settings": {"info": 2, "warning": 5, "critical": 7}
418
+ },
419
+ "application_name": "wound detection System",
420
+ "application_version": "1.2",
421
+ "location_info": None,
422
+ "human_text": human_text
423
+ }
424
+ frame_events.append(event)
425
+
426
+ # Add alert events
427
+ for alert in alerts:
428
+ total_detections = counting_summary.get("total_count", 0)
429
+ intensity_message = "ALERT: Low congestion in the scene"
430
+ if config.alert_config and config.alert_config.count_thresholds:
431
+ threshold = config.alert_config.count_thresholds.get("all", 15)
432
+ percentage = (total_detections / threshold) * 100 if threshold > 0 else 0
433
+ if percentage < 20:
434
+ intensity_message = "ALERT: Low congestion in the scene"
435
+ elif percentage <= 50:
436
+ intensity_message = "ALERT: Moderate congestion in the scene"
437
+ elif percentage <= 70:
438
+ intensity_message = "ALERT: Heavy congestion in the scene"
439
+ else:
440
+ intensity_message = "ALERT: Severe congestion in the scene"
441
+ else:
442
+ if total_detections > 15:
443
+ intensity_message = "ALERT: Heavy congestion in the scene"
444
+ elif total_detections == 1:
445
+ intensity_message = "ALERT: Low congestion in the scene"
446
+ else:
447
+ intensity_message = "ALERT: Moderate congestion in the scene"
448
+
449
+ alert_event = {
450
+ "type": alert.get("type", "congestion_alert"),
451
+ "stream_time": datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S UTC"),
452
+ "level": alert.get("severity", "warning"),
453
+ "intensity": 8.0,
454
+ "config": {
455
+ "min_value": 0,
456
+ "max_value": 10,
457
+ "level_settings": {"info": 2, "warning": 5, "critical": 7}
458
+ },
459
+ "application_name": "Congestion Alert System",
460
+ "application_version": "1.2",
461
+ "location_info": alert.get("zone"),
462
+ "human_text": f"{datetime.now(timezone.utc).strftime('%Y-%m-%d-%H:%M:%S UTC')} : {intensity_message}"
463
+ }
464
+ frame_events.append(alert_event)
465
+
466
+ return events
467
+
468
+ def _generate_tracking_stats(
469
+ self,
470
+ counting_summary: Dict,
471
+ insights: List[str],
472
+ summary: str,
473
+ config: WoundConfig,
474
+ frame_number: Optional[int] = None,
475
+ stream_info: Optional[Dict[str, Any]] = None
476
+ ) -> List[Dict]:
477
+ """Generate structured tracking stats for the output format with frame-based keys, including track_ids_info and detections with masks."""
478
+ frame_key = str(frame_number) if frame_number is not None else "current_frame"
479
+ tracking_stats = [{frame_key: []}]
480
+ frame_tracking_stats = tracking_stats[0][frame_key]
481
+
482
+ total_detections = counting_summary.get("total_count", 0)
483
+ total_counts = counting_summary.get("total_counts", {})
484
+ cumulative_total = sum(total_counts.values()) if total_counts else 0
485
+ per_category_count = counting_summary.get("per_category_count", {})
486
+
487
+ track_ids_info = self._get_track_ids_info(counting_summary.get("detections", []))
488
+
489
+ current_timestamp = self._get_current_timestamp_str(stream_info)
490
+ start_timestamp = self._get_start_timestamp_str(stream_info)
491
+
492
+ human_text_lines = []
493
+
494
+ # CURRENT FRAME section
495
+ human_text_lines.append(f"CURRENT FRAME @ {current_timestamp}:")
496
+ if total_detections > 0:
497
+ category_counts = [f"{count} {cat}" for cat, count in per_category_count.items()]
498
+ if len(category_counts) == 1:
499
+ detection_text = category_counts[0] + " detected"
500
+ elif len(category_counts) == 2:
501
+ detection_text = f"{category_counts[0]} and {category_counts[1]} detected"
502
+ else:
503
+ detection_text = f"{', '.join(category_counts[:-1])}, and {category_counts[-1]} detected"
504
+ human_text_lines.append(f"\t- {detection_text}")
505
+ else:
506
+ human_text_lines.append(f"\t- No detections")
507
+
508
+ human_text_lines.append("") # spacing
509
+
510
+ # TOTAL SINCE section
511
+ human_text_lines.append(f"TOTAL SINCE {start_timestamp}:")
512
+ human_text_lines.append(f"\t- Total Detected: {cumulative_total}")
513
+ # Add category-wise counts
514
+ if total_counts:
515
+ for cat, count in total_counts.items():
516
+ if count > 0: # Only include categories with non-zero counts
517
+ human_text_lines.append(f"\t- {cat}: {count}")
518
+
519
+ human_text = "\n".join(human_text_lines)
520
+
521
+ # Include detections with masks from counting_summary
522
+ detections = [
523
+ {
524
+ "category": det.get("category"),
525
+ "confidence": det.get("confidence"),
526
+ "bounding_box": det.get("bounding_box"),
527
+ "track_id": det.get("track_id"),
528
+ "frame_id": det.get("frame_id"),
529
+ "masks": det.get("masks", det.get("mask", [])) # Include masks, fallback to empty list
530
+ }
531
+ for det in counting_summary.get("detections", [])
532
+ ]
533
+
534
+ tracking_stat = {
535
+ "type": "wound_segmentation",
536
+ "category": "medical",
537
+ "count": total_detections,
538
+ "insights": insights,
539
+ "summary": summary,
540
+ "timestamp": datetime.now(timezone.utc).strftime('%Y-%m-%d-%H:%M:%S UTC'),
541
+ "human_text": human_text,
542
+ "track_ids_info": track_ids_info,
543
+ "global_frame_offset": getattr(self, '_global_frame_offset', 0),
544
+ "local_frame_id": frame_key,
545
+ "detections": detections # Add detections with masks
546
+ }
547
+
548
+ frame_tracking_stats.append(tracking_stat)
549
+ return tracking_stats
550
+
551
+ def _count_categories(self, detections: list, config: WoundConfig) -> dict:
552
+ """
553
+ Count the number of detections per category and return a summary dict.
554
+ The detections list is expected to have 'track_id' (from tracker), 'category', 'bounding_box', 'masks', etc.
555
+ Output structure will include 'track_id' and 'masks' for each detection as per AdvancedTracker output.
556
+ """
557
+ counts = {}
558
+ valid_detections = []
559
+ for det in detections:
560
+ cat = det.get('category', 'unknown')
561
+ if not all(k in det for k in ['category', 'confidence', 'bounding_box']): # Validate required fields
562
+ self.logger.warning(f"Skipping invalid detection: {det}")
563
+ continue
564
+ counts[cat] = counts.get(cat, 0) + 1
565
+ valid_detections.append({
566
+ "bounding_box": det.get("bounding_box"),
567
+ "category": det.get("category"),
568
+ "confidence": det.get("confidence"),
569
+ "track_id": det.get("track_id"),
570
+ "frame_id": det.get("frame_id"),
571
+ "masks": det.get("masks", det.get("mask", [])) # Include masks, fallback to empty list
572
+ })
573
+ self.logger.debug(f"Valid detections after filtering: {len(valid_detections)}")
574
+ return {
575
+ "total_count": sum(counts.values()),
576
+ "per_category_count": counts,
577
+ "detections": valid_detections
578
+ }
579
+
580
+ # ------------------------------------------------------------------ #
581
+ # Helper to merge masks back into detections #
582
+ # ------------------------------------------------------------------ #
583
+ def _attach_masks_to_detections(
584
+ self,
585
+ processed_detections: List[Dict[str, Any]],
586
+ raw_detections: List[Dict[str, Any]],
587
+ iou_threshold: float = 0.5,
588
+ ) -> List[Dict[str, Any]]:
589
+ """
590
+ Attach segmentation masks from the original `raw_detections` list to the
591
+ `processed_detections` list returned after smoothing/tracking.
592
+
593
+ Matching between detections is performed using Intersection-over-Union
594
+ (IoU) of the bounding boxes. For each processed detection we select the
595
+ raw detection with the highest IoU above `iou_threshold` and copy its
596
+ `masks` (or `mask`) field. If no suitable match is found, the detection
597
+ keeps an empty list for `masks` to maintain a consistent schema.
598
+ """
599
+
600
+ if not processed_detections or not raw_detections:
601
+ # Nothing to do – ensure masks key exists for downstream logic.
602
+ for det in processed_detections:
603
+ det.setdefault("masks", [])
604
+ return processed_detections
605
+
606
+ # Track which raw detections have already been matched to avoid
607
+ # assigning the same mask to multiple processed detections.
608
+ used_raw_indices = set()
609
+
610
+ for det in processed_detections:
611
+ best_iou = 0.0
612
+ best_idx = None
613
+
614
+ for idx, raw_det in enumerate(raw_detections):
615
+ if idx in used_raw_indices:
616
+ continue
617
+
618
+ iou = self._compute_iou(det.get("bounding_box"), raw_det.get("bounding_box"))
619
+ if iou > best_iou:
620
+ best_iou = iou
621
+ best_idx = idx
622
+
623
+ if best_idx is not None and best_iou >= iou_threshold:
624
+ raw_det = raw_detections[best_idx]
625
+ masks = raw_det.get("masks", raw_det.get("mask"))
626
+ if masks is not None:
627
+ det["masks"] = masks
628
+ used_raw_indices.add(best_idx)
629
+ else:
630
+ # No adequate match – default to empty list to keep schema consistent.
631
+ det.setdefault("masks", ["EMPTY"])
632
+
633
+ return processed_detections
634
+
635
+ # Human-friendly display names for categories
636
+ CATEGORY_DISPLAY = {
637
+ "wound": "wound"
638
+ }
639
+
640
+ def _generate_insights(self, summary: dict, config: WoundConfig) -> List[str]:
641
+ """
642
+ Generate human-readable insights for each category.
643
+ """
644
+ insights = []
645
+ per_cat = summary.get("per_category_count", {})
646
+ total_detections = summary.get("total_count", 0)
647
+
648
+ if total_detections == 0:
649
+ insights.append("No detections in the scene")
650
+ return insights
651
+ insights.append(f"EVENT: Detected {total_detections} in the scene")
652
+ # Intensity calculation based on threshold percentage
653
+ intensity_threshold = None
654
+ if (config.alert_config and
655
+ config.alert_config.count_thresholds and
656
+ "all" in config.alert_config.count_thresholds):
657
+ intensity_threshold = config.alert_config.count_thresholds["all"]
658
+
659
+ if intensity_threshold is not None:
660
+ # Calculate percentage relative to threshold
661
+ percentage = (total_detections / intensity_threshold) * 100
662
+
663
+ if percentage < 20:
664
+ insights.append(f"INTENSITY: Low congestion in the scene ({percentage:.1f}% of capacity)")
665
+ elif percentage <= 50:
666
+ insights.append(f"INTENSITY: Moderate congestion in the scene ({percentage:.1f}% of capacity)")
667
+ elif percentage <= 70:
668
+ insights.append(f"INTENSITY: Heavy congestion in the scene ({percentage:.1f}% of capacity)")
669
+ else:
670
+ insights.append(f"INTENSITY: Severe congestion in the scene ({percentage:.1f}% of capacity)")
671
+
672
+ for cat, count in per_cat.items():
673
+ display = self.CATEGORY_DISPLAY.get(cat, cat)
674
+ insights.append(f"{display}:{count}")
675
+ return insights
676
+
677
+ def _check_alerts(self, summary: dict, config: WoundConfig) -> List[Dict]:
678
+ """
679
+ Check if any alert thresholds are exceeded and return alert dicts.
680
+ """
681
+ alerts = []
682
+ if not config.alert_config:
683
+ return alerts
684
+ total = summary.get("total_count", 0)
685
+ if hasattr(config.alert_config, 'count_thresholds') and config.alert_config.count_thresholds:
686
+ for category, threshold in config.alert_config.count_thresholds.items():
687
+ if category == "all" and total >= threshold:
688
+ timestamp = datetime.now(timezone.utc).strftime('%Y-%m-%d-%H:%M:%S UTC')
689
+ alert_description = f"detections count ({total}) exceeds threshold ({threshold})"
690
+ alerts.append({
691
+ "type": "count_threshold",
692
+ "severity": "warning",
693
+ "message": f"Total detections count ({total}) exceeds threshold ({threshold})",
694
+ "category": category,
695
+ "current_count": total,
696
+ "threshold": threshold
697
+ })
698
+ elif category in summary.get("per_category_count", {}):
699
+ count = summary.get("per_category_count", {})[category]
700
+ if count >= threshold:
701
+ alerts.append({
702
+ "type": "count_threshold",
703
+ "severity": "warning",
704
+ "message": f"{category} count ({count}) exceeds threshold ({threshold})",
705
+ "category": category,
706
+ "current_count": count,
707
+ "threshold": threshold
708
+ })
709
+ return alerts
710
+
711
+ def _extract_predictions(self, detections: list) -> List[Dict[str, Any]]:
712
+ """
713
+ Extract prediction details for output (category, confidence, bounding box).
714
+ """
715
+ return [
716
+ {
717
+ "category": det.get("category", "unknown"),
718
+ "confidence": det.get("confidence", 0.0),
719
+ "bounding_box": det.get("bounding_box", {}),
720
+ "mask": det.get("mask", det.get("masks", None)) # Accept either key
721
+ }
722
+ for det in detections
723
+ ]
724
+
725
+ def _generate_summary(self, summary: dict, alerts: List) -> str:
726
+ """
727
+ Generate a human_text string for the result, including per-category insights if available.
728
+ Adds a tab before each label for better formatting.
729
+ Also always includes the cumulative count so far.
730
+ """
731
+ total = summary.get("total_count", 0)
732
+ per_cat = summary.get("per_category_count", {})
733
+ cumulative = summary.get("total_counts", {})
734
+ cumulative_total = sum(cumulative.values()) if cumulative else 0
735
+ lines = []
736
+ if total > 0:
737
+ lines.append(f"{total} detections")
738
+ if per_cat:
739
+ lines.append("detections:")
740
+ for cat, count in per_cat.items():
741
+ lines.append(f"\t{cat}:{count}")
742
+ else:
743
+ lines.append("No detections")
744
+ lines.append(f"Total detections: {cumulative_total}")
745
+ if alerts:
746
+ lines.append(f"{len(alerts)} alert(s)")
747
+ return "\n".join(lines)
748
+
749
+ # ------------------------------------------------------------------ #
750
+ # Canonical ID helpers #
751
+ # ------------------------------------------------------------------ #
752
+ def _compute_iou(self, box1: Any, box2: Any) -> float:
753
+ """Compute IoU between two bounding boxes which may be dicts or lists.
754
+ Falls back to 0 when insufficient data is available."""
755
+
756
+ # Helper to convert bbox (dict or list) to [x1, y1, x2, y2]
757
+ def _bbox_to_list(bbox):
758
+ if bbox is None:
759
+ return []
760
+ if isinstance(bbox, list):
761
+ return bbox[:4] if len(bbox) >= 4 else []
762
+ if isinstance(bbox, dict):
763
+ if "xmin" in bbox:
764
+ return [bbox["xmin"], bbox["ymin"], bbox["xmax"], bbox["ymax"]]
765
+ if "x1" in bbox:
766
+ return [bbox["x1"], bbox["y1"], bbox["x2"], bbox["y2"]]
767
+ # Fallback: first four numeric values
768
+ values = [v for v in bbox.values() if isinstance(v, (int, float))]
769
+ return values[:4] if len(values) >= 4 else []
770
+ return []
771
+
772
+ l1 = _bbox_to_list(box1)
773
+ l2 = _bbox_to_list(box2)
774
+ if len(l1) < 4 or len(l2) < 4:
775
+ return 0.0
776
+ x1_min, y1_min, x1_max, y1_max = l1
777
+ x2_min, y2_min, x2_max, y2_max = l2
778
+
779
+ # Ensure correct order
780
+ x1_min, x1_max = min(x1_min, x1_max), max(x1_min, x1_max)
781
+ y1_min, y1_max = min(y1_min, y1_max), max(y1_min, y1_max)
782
+ x2_min, x2_max = min(x2_min, x2_max), max(x2_min, x2_max)
783
+ y2_min, y2_max = min(y2_min, y2_max), max(y2_min, y2_max)
784
+
785
+ inter_x_min = max(x1_min, x2_min)
786
+ inter_y_min = max(y1_min, y2_min)
787
+ inter_x_max = min(x1_max, x2_max)
788
+ inter_y_max = min(y1_max, y2_max)
789
+
790
+ inter_w = max(0.0, inter_x_max - inter_x_min)
791
+ inter_h = max(0.0, inter_y_max - inter_y_min)
792
+ inter_area = inter_w * inter_h
793
+
794
+ area1 = (x1_max - x1_min) * (y1_max - y1_min)
795
+ area2 = (x2_max - x2_min) * (y2_max - y2_min)
796
+ union_area = area1 + area2 - inter_area
797
+
798
+ return (inter_area / union_area) if union_area > 0 else 0.0
799
+
800
+ def _merge_or_register_track(self, raw_id: Any, bbox: Any) -> Any:
801
+ """Return a stable canonical ID for a raw tracker ID, merging fragmented
802
+ tracks when IoU and temporal constraints indicate they represent the
803
+ same physical."""
804
+ if raw_id is None or bbox is None:
805
+ # Nothing to merge
806
+ return raw_id
807
+
808
+ now = time.time()
809
+
810
+ # Fast path – raw_id already mapped
811
+ if raw_id in self._track_aliases:
812
+ canonical_id = self._track_aliases[raw_id]
813
+ track_info = self._canonical_tracks.get(canonical_id)
814
+ if track_info is not None:
815
+ track_info["last_bbox"] = bbox
816
+ track_info["last_update"] = now
817
+ track_info["raw_ids"].add(raw_id)
818
+ return canonical_id
819
+
820
+ # Attempt to merge with an existing canonical track
821
+ for canonical_id, info in self._canonical_tracks.items():
822
+ # Only consider recently updated tracks
823
+ if now - info["last_update"] > self._track_merge_time_window:
824
+ continue
825
+ iou = self._compute_iou(bbox, info["last_bbox"])
826
+ if iou >= self._track_merge_iou_threshold:
827
+ # Merge
828
+ self._track_aliases[raw_id] = canonical_id
829
+ info["last_bbox"] = bbox
830
+ info["last_update"] = now
831
+ info["raw_ids"].add(raw_id)
832
+ return canonical_id
833
+
834
+ # No match – register new canonical track
835
+ canonical_id = raw_id
836
+ self._track_aliases[raw_id] = canonical_id
837
+ self._canonical_tracks[canonical_id] = {
838
+ "last_bbox": bbox,
839
+ "last_update": now,
840
+ "raw_ids": {raw_id},
841
+ }
842
+ return canonical_id
843
+
844
+ def _format_timestamp(self, timestamp: float) -> str:
845
+ """Format a timestamp for human-readable output."""
846
+ return datetime.fromtimestamp(timestamp, timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')
847
+
848
+ def _get_tracking_start_time(self) -> str:
849
+ """Get the tracking start time, formatted as a string."""
850
+ if self._tracking_start_time is None:
851
+ return "N/A"
852
+ return self._format_timestamp(self._tracking_start_time)
853
+
854
+ def _set_tracking_start_time(self) -> None:
855
+ """Set the tracking start time to the current time."""
856
+ self._tracking_start_time = time.time()