matrice-analytics 0.1.60__py3-none-any.whl

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