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