matrice-analytics 0.1.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


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

Files changed (160) hide show
  1. matrice_analytics/__init__.py +28 -0
  2. matrice_analytics/boundary_drawing_internal/README.md +305 -0
  3. matrice_analytics/boundary_drawing_internal/__init__.py +45 -0
  4. matrice_analytics/boundary_drawing_internal/boundary_drawing_internal.py +1207 -0
  5. matrice_analytics/boundary_drawing_internal/boundary_drawing_tool.py +429 -0
  6. matrice_analytics/boundary_drawing_internal/boundary_tool_template.html +1036 -0
  7. matrice_analytics/boundary_drawing_internal/data/.gitignore +12 -0
  8. matrice_analytics/boundary_drawing_internal/example_usage.py +206 -0
  9. matrice_analytics/boundary_drawing_internal/usage/README.md +110 -0
  10. matrice_analytics/boundary_drawing_internal/usage/boundary_drawer_launcher.py +102 -0
  11. matrice_analytics/boundary_drawing_internal/usage/simple_boundary_launcher.py +107 -0
  12. matrice_analytics/post_processing/README.md +455 -0
  13. matrice_analytics/post_processing/__init__.py +732 -0
  14. matrice_analytics/post_processing/advanced_tracker/README.md +650 -0
  15. matrice_analytics/post_processing/advanced_tracker/__init__.py +17 -0
  16. matrice_analytics/post_processing/advanced_tracker/base.py +99 -0
  17. matrice_analytics/post_processing/advanced_tracker/config.py +77 -0
  18. matrice_analytics/post_processing/advanced_tracker/kalman_filter.py +370 -0
  19. matrice_analytics/post_processing/advanced_tracker/matching.py +195 -0
  20. matrice_analytics/post_processing/advanced_tracker/strack.py +230 -0
  21. matrice_analytics/post_processing/advanced_tracker/tracker.py +367 -0
  22. matrice_analytics/post_processing/config.py +142 -0
  23. matrice_analytics/post_processing/core/__init__.py +63 -0
  24. matrice_analytics/post_processing/core/base.py +704 -0
  25. matrice_analytics/post_processing/core/config.py +3188 -0
  26. matrice_analytics/post_processing/core/config_utils.py +925 -0
  27. matrice_analytics/post_processing/face_reg/__init__.py +43 -0
  28. matrice_analytics/post_processing/face_reg/compare_similarity.py +556 -0
  29. matrice_analytics/post_processing/face_reg/embedding_manager.py +681 -0
  30. matrice_analytics/post_processing/face_reg/face_recognition.py +1870 -0
  31. matrice_analytics/post_processing/face_reg/face_recognition_client.py +339 -0
  32. matrice_analytics/post_processing/face_reg/people_activity_logging.py +283 -0
  33. matrice_analytics/post_processing/ocr/__init__.py +0 -0
  34. matrice_analytics/post_processing/ocr/easyocr_extractor.py +248 -0
  35. matrice_analytics/post_processing/ocr/postprocessing.py +271 -0
  36. matrice_analytics/post_processing/ocr/preprocessing.py +52 -0
  37. matrice_analytics/post_processing/post_processor.py +1153 -0
  38. matrice_analytics/post_processing/test_cases/__init__.py +1 -0
  39. matrice_analytics/post_processing/test_cases/run_tests.py +143 -0
  40. matrice_analytics/post_processing/test_cases/test_advanced_customer_service.py +841 -0
  41. matrice_analytics/post_processing/test_cases/test_basic_counting_tracking.py +523 -0
  42. matrice_analytics/post_processing/test_cases/test_comprehensive.py +531 -0
  43. matrice_analytics/post_processing/test_cases/test_config.py +852 -0
  44. matrice_analytics/post_processing/test_cases/test_customer_service.py +585 -0
  45. matrice_analytics/post_processing/test_cases/test_data_generators.py +583 -0
  46. matrice_analytics/post_processing/test_cases/test_people_counting.py +510 -0
  47. matrice_analytics/post_processing/test_cases/test_processor.py +524 -0
  48. matrice_analytics/post_processing/test_cases/test_utilities.py +356 -0
  49. matrice_analytics/post_processing/test_cases/test_utils.py +743 -0
  50. matrice_analytics/post_processing/usecases/Histopathological_Cancer_Detection_img.py +604 -0
  51. matrice_analytics/post_processing/usecases/__init__.py +267 -0
  52. matrice_analytics/post_processing/usecases/abandoned_object_detection.py +797 -0
  53. matrice_analytics/post_processing/usecases/advanced_customer_service.py +1601 -0
  54. matrice_analytics/post_processing/usecases/age_detection.py +842 -0
  55. matrice_analytics/post_processing/usecases/age_gender_detection.py +1043 -0
  56. matrice_analytics/post_processing/usecases/anti_spoofing_detection.py +656 -0
  57. matrice_analytics/post_processing/usecases/assembly_line_detection.py +841 -0
  58. matrice_analytics/post_processing/usecases/banana_defect_detection.py +624 -0
  59. matrice_analytics/post_processing/usecases/basic_counting_tracking.py +667 -0
  60. matrice_analytics/post_processing/usecases/blood_cancer_detection_img.py +881 -0
  61. matrice_analytics/post_processing/usecases/car_damage_detection.py +834 -0
  62. matrice_analytics/post_processing/usecases/car_part_segmentation.py +946 -0
  63. matrice_analytics/post_processing/usecases/car_service.py +1601 -0
  64. matrice_analytics/post_processing/usecases/cardiomegaly_classification.py +864 -0
  65. matrice_analytics/post_processing/usecases/cell_microscopy_segmentation.py +897 -0
  66. matrice_analytics/post_processing/usecases/chicken_pose_detection.py +648 -0
  67. matrice_analytics/post_processing/usecases/child_monitoring.py +814 -0
  68. matrice_analytics/post_processing/usecases/color/clip.py +232 -0
  69. matrice_analytics/post_processing/usecases/color/clip_processor/merges.txt +48895 -0
  70. matrice_analytics/post_processing/usecases/color/clip_processor/preprocessor_config.json +28 -0
  71. matrice_analytics/post_processing/usecases/color/clip_processor/special_tokens_map.json +30 -0
  72. matrice_analytics/post_processing/usecases/color/clip_processor/tokenizer.json +245079 -0
  73. matrice_analytics/post_processing/usecases/color/clip_processor/tokenizer_config.json +32 -0
  74. matrice_analytics/post_processing/usecases/color/clip_processor/vocab.json +1 -0
  75. matrice_analytics/post_processing/usecases/color/color_map_utils.py +70 -0
  76. matrice_analytics/post_processing/usecases/color/color_mapper.py +468 -0
  77. matrice_analytics/post_processing/usecases/color_detection.py +1835 -0
  78. matrice_analytics/post_processing/usecases/color_map_utils.py +70 -0
  79. matrice_analytics/post_processing/usecases/concrete_crack_detection.py +827 -0
  80. matrice_analytics/post_processing/usecases/crop_weed_detection.py +781 -0
  81. matrice_analytics/post_processing/usecases/customer_service.py +1008 -0
  82. matrice_analytics/post_processing/usecases/defect_detection_products.py +936 -0
  83. matrice_analytics/post_processing/usecases/distracted_driver_detection.py +822 -0
  84. matrice_analytics/post_processing/usecases/drone_traffic_monitoring.py +930 -0
  85. matrice_analytics/post_processing/usecases/drowsy_driver_detection.py +829 -0
  86. matrice_analytics/post_processing/usecases/dwell_detection.py +829 -0
  87. matrice_analytics/post_processing/usecases/emergency_vehicle_detection.py +827 -0
  88. matrice_analytics/post_processing/usecases/face_emotion.py +813 -0
  89. matrice_analytics/post_processing/usecases/face_recognition.py +827 -0
  90. matrice_analytics/post_processing/usecases/fashion_detection.py +835 -0
  91. matrice_analytics/post_processing/usecases/field_mapping.py +902 -0
  92. matrice_analytics/post_processing/usecases/fire_detection.py +1112 -0
  93. matrice_analytics/post_processing/usecases/flare_analysis.py +891 -0
  94. matrice_analytics/post_processing/usecases/flower_segmentation.py +1006 -0
  95. matrice_analytics/post_processing/usecases/gas_leak_detection.py +837 -0
  96. matrice_analytics/post_processing/usecases/gender_detection.py +832 -0
  97. matrice_analytics/post_processing/usecases/human_activity_recognition.py +871 -0
  98. matrice_analytics/post_processing/usecases/intrusion_detection.py +1672 -0
  99. matrice_analytics/post_processing/usecases/leaf.py +821 -0
  100. matrice_analytics/post_processing/usecases/leaf_disease.py +840 -0
  101. matrice_analytics/post_processing/usecases/leak_detection.py +837 -0
  102. matrice_analytics/post_processing/usecases/license_plate_detection.py +914 -0
  103. matrice_analytics/post_processing/usecases/license_plate_monitoring.py +1194 -0
  104. matrice_analytics/post_processing/usecases/litter_monitoring.py +717 -0
  105. matrice_analytics/post_processing/usecases/mask_detection.py +869 -0
  106. matrice_analytics/post_processing/usecases/natural_disaster.py +907 -0
  107. matrice_analytics/post_processing/usecases/parking.py +787 -0
  108. matrice_analytics/post_processing/usecases/parking_space_detection.py +822 -0
  109. matrice_analytics/post_processing/usecases/pcb_defect_detection.py +888 -0
  110. matrice_analytics/post_processing/usecases/pedestrian_detection.py +808 -0
  111. matrice_analytics/post_processing/usecases/people_counting.py +1728 -0
  112. matrice_analytics/post_processing/usecases/people_tracking.py +1842 -0
  113. matrice_analytics/post_processing/usecases/pipeline_detection.py +605 -0
  114. matrice_analytics/post_processing/usecases/plaque_segmentation_img.py +874 -0
  115. matrice_analytics/post_processing/usecases/pothole_segmentation.py +915 -0
  116. matrice_analytics/post_processing/usecases/ppe_compliance.py +645 -0
  117. matrice_analytics/post_processing/usecases/price_tag_detection.py +822 -0
  118. matrice_analytics/post_processing/usecases/proximity_detection.py +1901 -0
  119. matrice_analytics/post_processing/usecases/road_lane_detection.py +623 -0
  120. matrice_analytics/post_processing/usecases/road_traffic_density.py +832 -0
  121. matrice_analytics/post_processing/usecases/road_view_segmentation.py +915 -0
  122. matrice_analytics/post_processing/usecases/shelf_inventory_detection.py +583 -0
  123. matrice_analytics/post_processing/usecases/shoplifting_detection.py +822 -0
  124. matrice_analytics/post_processing/usecases/shopping_cart_analysis.py +899 -0
  125. matrice_analytics/post_processing/usecases/skin_cancer_classification_img.py +864 -0
  126. matrice_analytics/post_processing/usecases/smoker_detection.py +833 -0
  127. matrice_analytics/post_processing/usecases/solar_panel.py +810 -0
  128. matrice_analytics/post_processing/usecases/suspicious_activity_detection.py +1030 -0
  129. matrice_analytics/post_processing/usecases/template_usecase.py +380 -0
  130. matrice_analytics/post_processing/usecases/theft_detection.py +648 -0
  131. matrice_analytics/post_processing/usecases/traffic_sign_monitoring.py +724 -0
  132. matrice_analytics/post_processing/usecases/underground_pipeline_defect_detection.py +775 -0
  133. matrice_analytics/post_processing/usecases/underwater_pollution_detection.py +842 -0
  134. matrice_analytics/post_processing/usecases/vehicle_monitoring.py +950 -0
  135. matrice_analytics/post_processing/usecases/warehouse_object_segmentation.py +899 -0
  136. matrice_analytics/post_processing/usecases/waterbody_segmentation.py +923 -0
  137. matrice_analytics/post_processing/usecases/weapon_detection.py +771 -0
  138. matrice_analytics/post_processing/usecases/weld_defect_detection.py +615 -0
  139. matrice_analytics/post_processing/usecases/wildlife_monitoring.py +898 -0
  140. matrice_analytics/post_processing/usecases/windmill_maintenance.py +834 -0
  141. matrice_analytics/post_processing/usecases/wound_segmentation.py +856 -0
  142. matrice_analytics/post_processing/utils/__init__.py +150 -0
  143. matrice_analytics/post_processing/utils/advanced_counting_utils.py +400 -0
  144. matrice_analytics/post_processing/utils/advanced_helper_utils.py +317 -0
  145. matrice_analytics/post_processing/utils/advanced_tracking_utils.py +461 -0
  146. matrice_analytics/post_processing/utils/alerting_utils.py +213 -0
  147. matrice_analytics/post_processing/utils/category_mapping_utils.py +94 -0
  148. matrice_analytics/post_processing/utils/color_utils.py +592 -0
  149. matrice_analytics/post_processing/utils/counting_utils.py +182 -0
  150. matrice_analytics/post_processing/utils/filter_utils.py +261 -0
  151. matrice_analytics/post_processing/utils/format_utils.py +293 -0
  152. matrice_analytics/post_processing/utils/geometry_utils.py +300 -0
  153. matrice_analytics/post_processing/utils/smoothing_utils.py +358 -0
  154. matrice_analytics/post_processing/utils/tracking_utils.py +234 -0
  155. matrice_analytics/py.typed +0 -0
  156. matrice_analytics-0.1.2.dist-info/METADATA +481 -0
  157. matrice_analytics-0.1.2.dist-info/RECORD +160 -0
  158. matrice_analytics-0.1.2.dist-info/WHEEL +5 -0
  159. matrice_analytics-0.1.2.dist-info/licenses/LICENSE.txt +21 -0
  160. matrice_analytics-0.1.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1043 @@
1
+ from typing import Any, Dict, List, Optional
2
+ from dataclasses import asdict, dataclass, field
3
+ import time
4
+ from datetime import datetime, timezone
5
+ import copy
6
+ import tempfile
7
+ import os
8
+ import json
9
+ import zipfile
10
+ import os
11
+ import requests
12
+ import logging
13
+ from io import BytesIO
14
+ from collections import Counter
15
+ from matrice_analytics.post_processing.core.base import BaseProcessor, ProcessingContext, ProcessingResult, ConfigProtocol
16
+ from matrice_analytics.post_processing.utils import (
17
+ filter_by_confidence,
18
+ filter_by_categories,
19
+ # apply_category_mapping,
20
+ count_objects_by_category,
21
+ count_objects_in_zones,
22
+ calculate_counting_summary,
23
+ match_results_structure,
24
+ bbox_smoothing,
25
+ BBoxSmoothingConfig,
26
+ BBoxSmoothingTracker
27
+ )
28
+ # External dependencies
29
+ import cv2
30
+ import numpy as np
31
+ #import torch
32
+ import re
33
+ from matrice_analytics.post_processing.core.config import BaseConfig, AlertConfig, ZoneConfig
34
+ try:
35
+ from PIL import Image
36
+ import onnxruntime as ort
37
+ except:
38
+ print("Unable to import onnxruntime")
39
+
40
+
41
+ def apply_category_mapping(results: Any, index_to_category: Dict[str, str]) -> Any:
42
+ """
43
+ Apply category index to name mapping.
44
+
45
+ Args:
46
+ results: Detection or tracking results
47
+ index_to_category: Mapping from category index to category name
48
+
49
+ Returns:
50
+ Results with mapped category names
51
+ """
52
+
53
+ def map_detection(
54
+ detection: Dict[str, Any], index_to_category: Dict[str, str]
55
+ ) -> Dict[str, Any]:
56
+ """Map a single detection."""
57
+ detection = detection.copy()
58
+ category_id = str(detection.get("class_id", detection.get("class_id")))
59
+ index_to_category = {str(k): str(v) for k, v in index_to_category.items()}
60
+ if category_id in index_to_category:
61
+ detection["category"] = index_to_category[category_id]
62
+ detection["class_id"] = category_id
63
+ return detection
64
+
65
+ if isinstance(results, list):
66
+ # Detection format
67
+ return [map_detection(r, index_to_category) for r in results]
68
+
69
+ elif isinstance(results, dict):
70
+ # Check if it's a simple classification result
71
+ if "category" in results or "class_id" in results:
72
+ return map_detection(results, index_to_category)
73
+
74
+ # Frame-based format
75
+ mapped_results = {}
76
+ for frame_id, detections in results.items():
77
+ if isinstance(detections, list):
78
+ mapped_results[frame_id] = [
79
+ map_detection(d, index_to_category) for d in detections
80
+ ]
81
+ else:
82
+ mapped_results[frame_id] = detections
83
+
84
+ return mapped_results
85
+
86
+ return results
87
+
88
+ def load_model_from_checkpoint(checkpoint_path,local_path):
89
+ """
90
+ Load a model from checkpoint URL
91
+ """
92
+ try:
93
+ print(f"Loading model from checkpoint: {checkpoint_path}")
94
+
95
+ # Check if checkpoint is a URL
96
+ if checkpoint_path.startswith(('http://', 'https://')):
97
+ # Download checkpoint from URL
98
+ response = requests.get(checkpoint_path, timeout = (30,200))
99
+ if response.status_code == 200:
100
+ with open(local_path, 'wb') as f:
101
+ f.write(response.content)
102
+ checkpoint_path = local_path
103
+ print(f"Downloaded checkpoint to {local_path}")
104
+ else:
105
+ print(f"Failed to download checkpoint from {checkpoint_path}")
106
+ return None
107
+
108
+ # Load the model from the checkpoint
109
+ model = ort.InferenceSession(checkpoint_path, providers=["CUDAExecutionProvider"])
110
+ print(f"{local_path} Model loaded successfully from checkpoint")
111
+ return model
112
+
113
+ except Exception as e:
114
+ print(f"Error loading model from checkpoint: {e}")
115
+ return None
116
+
117
+
118
+ @dataclass
119
+ class AgeGenderConfig(BaseConfig):
120
+ """Configuration for age and gender detection use case in age and gender detection."""
121
+ enable_smoothing: bool = False
122
+ smoothing_algorithm: str = "observability" # "window" or "observability"
123
+ smoothing_window_size: int = 20
124
+ smoothing_cooldown_frames: int = 5
125
+ smoothing_confidence_range_factor: float = 0.5
126
+ confidence_threshold: float = 0.2
127
+ frame_skip: int = 1
128
+ fps: Optional[float] = None
129
+ bbox_format: str = "auto"
130
+ age_url:Any = "https://s3.us-west-2.amazonaws.com/testing.resources/datasets/age_detection_prod_model.onnx"
131
+ gender_url:Any = "https://s3.us-west-2.amazonaws.com/testing.resources/datasets/gender_detection_prod_model.onnx"
132
+ usecase_categories: List[str] = field(default_factory=lambda: ['FACE'])
133
+ target_categories: List[str] = field(default_factory=lambda: ['FACE'])
134
+ alert_config: Optional[AlertConfig] = None
135
+ index_to_category: Optional[Dict[int, str]] = field(default_factory=lambda: {0: "FACE"})
136
+
137
+ def validate(self) -> List[str]:
138
+ """Validate configuration parameters."""
139
+ errors = super().validate()
140
+ if self.confidence_threshold < 0 or self.confidence_threshold > 1:
141
+ errors.append("confidence_threshold must be between 0 and 1")
142
+ if self.frame_skip <= 0:
143
+ errors.append("frame_skip must be positive")
144
+ if self.bbox_format not in ["auto", "xmin_ymin_xmax_ymax", "x_y_width_height"]:
145
+ errors.append("bbox_format must be one of: auto, xmin_ymin_xmax_ymax, x_y_width_height")
146
+ if self.smoothing_window_size <= 0:
147
+ errors.append("smoothing_window_size must be positive")
148
+ if self.smoothing_cooldown_frames < 0:
149
+ errors.append("smoothing_cooldown_frames cannot be negative")
150
+ if self.smoothing_confidence_range_factor <= 0:
151
+ errors.append("smoothing_confidence_range_factor must be positive")
152
+ return errors
153
+
154
+ def __post_init__(self):
155
+ if self.gender_url and self.age_url:
156
+ self.age_url = load_model_from_checkpoint(self.age_url, "age_detection_prod_model.onnx")
157
+ self.gender_url = load_model_from_checkpoint(self.gender_url, "gender_detection_prod_model.onnx")
158
+ else:
159
+ raise ValueError("Age and Gender model URL must be passed!")
160
+
161
+
162
+ class AgeGenderUseCase(BaseProcessor):
163
+ def __init__(self):
164
+ super().__init__("age_gender_detection")
165
+ self.category = "age_gender_detection"
166
+ self.target_categories = ['FACE']
167
+ self.CASE_TYPE: Optional[str] = 'age_gender_detection'
168
+ self.CASE_VERSION: Optional[str] = '1.3'
169
+ self.smoothing_tracker = None
170
+ self.tracker = None
171
+ self._total_frame_counter = 0
172
+ self._global_frame_offset = 0
173
+ self._tracking_start_time = None
174
+ self._track_aliases: Dict[Any, Any] = {}
175
+ self._canonical_tracks: Dict[Any, Dict[str, Any]] = {}
176
+ self._track_merge_iou_threshold: float = 0.05
177
+ self._track_merge_time_window: float = 7.0
178
+ self._ascending_alert_list: List[int] = []
179
+ self.current_incident_end_timestamp: str = "N/A"
180
+ self.all_track_data: List[str] = []
181
+
182
+ self.start_timer = None
183
+ self.age: Dict[str:Any] = {}
184
+ self.gender: Dict[str:Any] = {}
185
+ #self.reset_timer = "2025-08-19-04:22:47.187574 UTC"
186
+
187
+ def reset_tracker(self) -> None:
188
+ """Reset the advanced tracker instance."""
189
+ if self.tracker is not None:
190
+ self.tracker.reset()
191
+ self.logger.info("AdvancedTracker reset for new tracking session")
192
+
193
+ def reset_plate_tracking(self) -> None:
194
+ """Reset plate tracking state."""
195
+ self._seen_plate_texts = set()
196
+ # CHANGE: Reset _tracked_plate_texts
197
+ self._tracked_plate_texts = {}
198
+ self._total_frame_counter = 0
199
+ self._global_frame_offset = 0
200
+ self._text_history = {}
201
+ self._unique_plate_texts = {}
202
+ self.logger.info("Plate tracking state reset")
203
+
204
+ def reset_all_tracking(self) -> None:
205
+ """Reset both advanced tracker and plate tracking state."""
206
+ self.reset_tracker()
207
+ self.reset_plate_tracking()
208
+ self.logger.info("All plate tracking state reset")
209
+
210
+ def helper(self,detections, input_bytes, config):
211
+ for det in detections:
212
+ bbox = det.get('bounding_box')
213
+ xmin = int(bbox.get('xmin'))
214
+ xmax = int(bbox.get('xmax'))
215
+ ymin = int(bbox.get('ymin'))
216
+ ymax = int(bbox.get('xmax'))
217
+ track_id = det.get('track_id')
218
+ print(xmin,xmax,ymin,ymax)
219
+
220
+ nparr = np.frombuffer(input_bytes, np.uint8) # convert bytes to numpy array
221
+ image = cv2.imdecode(nparr, cv2.IMREAD_COLOR) # decode image
222
+
223
+ # Step 2: Convert PIL → NumPy array
224
+ rgb_image = np.array(image)
225
+
226
+ face = rgb_image[ymin:ymax,xmin:xmax]
227
+ if face.size == 0:
228
+ continue
229
+ face_resized = cv2.resize(face, (224, 224))
230
+ face_resized = cv2.cvtColor(face_resized, cv2.COLOR_BGR2RGB)
231
+ face_resized = np.expand_dims(face_resized, axis=0).astype(np.float32) / 255.0
232
+
233
+ # Age Prediction
234
+ age_preds = config.age_url.run(None, {"input": face_resized})[0][0]
235
+ predicted_age = int(np.sum(age_preds * np.arange(0, 101)))
236
+ confidence_age = float(np.max(age_preds))
237
+ # Gender prediction
238
+ gender_preds = config.gender_url.run(None, {"input": face_resized})[0][0]
239
+ predicted_gender = "Man" if np.argmax(gender_preds) == 1 else "Woman"
240
+ confidence_gen = float(np.max(gender_preds))
241
+
242
+ print("________________________CHECK_______________________________________")
243
+ print(predicted_age, predicted_gender)
244
+ print("________________________CHECK_______________________________________")
245
+
246
+ if track_id:
247
+ track_id = str(track_id)
248
+
249
+ if track_id not in self.gender:
250
+ self.gender[track_id] = []
251
+ self.gender[track_id].append(predicted_gender)
252
+
253
+ if track_id not in self.age:
254
+ self.age[track_id] = []
255
+ self.age[track_id].append(predicted_age)
256
+ return {"Age Data":self.age,"Gender Data":self.gender}
257
+
258
+ def process(self, data: Any, config: ConfigProtocol, input_bytes: Optional[bytes] = None,
259
+ context: Optional[ProcessingContext] = None, stream_info: Optional[Dict[str, Any]] = None) -> ProcessingResult:
260
+ processing_start = time.time()
261
+
262
+ try:
263
+ if config.age_url is None and config.gender_url is None:
264
+ return self.create_error_result("Model not loaded",
265
+ usecase=self.name, category=self.category, context=context)
266
+
267
+ if not isinstance(config, AgeGenderConfig):
268
+ return self.create_error_result("Invalid configuration type for age gender detection",
269
+ usecase=self.name, category=self.category, context=context)
270
+
271
+ if context is None:
272
+ context = ProcessingContext()
273
+
274
+ if not input_bytes:
275
+ return self.create_error_result("input_bytes (video/image) is required for age gender detection",
276
+ usecase=self.name, category=self.category, context=context)
277
+
278
+ if isinstance(getattr(config, 'alert_config', None), dict):
279
+ try:
280
+ config.alert_config = AlertConfig(**config.alert_config) # type: ignore[arg-type]
281
+ except Exception:
282
+ pass
283
+
284
+ input_format = match_results_structure(data)
285
+ context.input_format = input_format
286
+ context.confidence_threshold = config.confidence_threshold
287
+
288
+ self.logger.info(f"Processing age gender detection with format: {input_format.value}")
289
+
290
+ # Step 1: Apply confidence filtering 1
291
+ print("---------CONFIDENCE FILTERING",config.confidence_threshold)
292
+
293
+ processed_data = filter_by_confidence(data, config.confidence_threshold)
294
+ print("---------DATA1--------------",processed_data)
295
+ self.logger.debug(f"Applied confidence filtering with threshold {config.confidence_threshold}")
296
+
297
+ # Step 2: Apply category mapping if provided
298
+ if config.index_to_category:
299
+ processed_data = apply_category_mapping(processed_data, config.index_to_category)
300
+ self.logger.debug("Applied category mapping")
301
+ print("---------DATA2--------------",processed_data)
302
+ # Step 3: Filter to target categories
303
+ if self.target_categories:
304
+ processed_data = [d for d in processed_data if d.get('category') in self.target_categories]
305
+ self.logger.debug(f"Applied category filtering")
306
+
307
+ # effective_targets = getattr(config, 'target_categories', self.target_categories) or self.target_categories
308
+ # targets_lower = {str(cat).lower() for cat in effective_targets}
309
+ # processed_data = [d for d in processed_data if str(d.get('category', '')).lower() in targets_lower]
310
+
311
+ self.logger.debug("Applied category filtering")
312
+
313
+ raw_processed_data = [copy.deepcopy(det) for det in processed_data]
314
+ print("---------DATA2--------------",processed_data)
315
+ # Step 4: Apply bounding box smoothing if enabled
316
+ if config.enable_smoothing:
317
+ if self.smoothing_tracker is None:
318
+ smoothing_config = BBoxSmoothingConfig(
319
+ smoothing_algorithm=config.smoothing_algorithm,
320
+ window_size=config.smoothing_window_size,
321
+ cooldown_frames=config.smoothing_cooldown_frames,
322
+ confidence_threshold=config.confidence_threshold,
323
+ confidence_range_factor=config.smoothing_confidence_range_factor,
324
+ enable_smoothing=True
325
+ )
326
+ self.smoothing_tracker = BBoxSmoothingTracker(smoothing_config)
327
+ processed_data = bbox_smoothing(processed_data, self.smoothing_tracker.config, self.smoothing_tracker)
328
+
329
+ # Step 5: Apply advanced tracking
330
+ try:
331
+ from matrice_analytics.post_processing.advanced_tracker import AdvancedTracker
332
+ from matrice_analytics.post_processing.advanced_tracker import TrackerConfig
333
+ if self.tracker is None:
334
+ tracker_config = TrackerConfig(
335
+ track_high_thresh=float(config.confidence_threshold),
336
+ track_low_thresh=max(0.05, float(config.confidence_threshold) / 2),
337
+ new_track_thresh=float(config.confidence_threshold)
338
+ )
339
+ self.tracker = AdvancedTracker(tracker_config)
340
+ self.logger.info(f"Initialized AdvancedTracker with thresholds: high={tracker_config.track_high_thresh}, "
341
+ f"low={tracker_config.track_low_thresh}, new={tracker_config.new_track_thresh}")
342
+ processed_data = self.tracker.update(processed_data)
343
+ except Exception as e:
344
+ self.logger.warning(f"AdvancedTracker failed: {e}")
345
+ print("---------DATA3--------------",processed_data)
346
+ # Step 6: Update tracking state
347
+ self._update_tracking_state(processed_data)
348
+ print("---------DATA4--------------",processed_data)
349
+ # Step 7: Attach masks to detections
350
+ processed_data = self._attach_masks_to_detections(processed_data, raw_processed_data)
351
+
352
+ # Step 10: Update frame counter
353
+ self._total_frame_counter += 1
354
+
355
+ # Step 11: Extract frame information
356
+ frame_number = None
357
+ if stream_info:
358
+ input_settings = stream_info.get("input_settings", {})
359
+ start_frame = input_settings.get("start_frame")
360
+ end_frame = input_settings.get("end_frame")
361
+ if start_frame is not None and end_frame is not None and start_frame == end_frame:
362
+ frame_number = start_frame
363
+
364
+ # Step 12: Calculate summaries
365
+
366
+ det = self.helper(processed_data,input_bytes,config)
367
+ print("----------------------HELPER--------------------------------")
368
+ print(det)
369
+ print("----------------------HELPER--------------------------------")
370
+
371
+ counting_summary = self._count_categories(processed_data, config,det)
372
+ counting_summary['total_counts'] = self.get_total_counts()
373
+
374
+ print("---------------------------------COUNTING SUMMARY------------------------------")
375
+ print(counting_summary)
376
+ print("---------------------------------COUNTING SUMMARY------------------------------")
377
+
378
+ # Step 13: Generate alerts and summaries
379
+ alerts = self._check_alerts(counting_summary, frame_number, config)
380
+ incidents_list = self._generate_incidents(counting_summary, alerts, config, frame_number, stream_info)
381
+ tracking_stats_list = self._generate_tracking_stats(counting_summary, alerts, config, frame_number, stream_info)
382
+ business_analytics_list = []
383
+ summary_list = self._generate_summary(counting_summary, incidents_list, tracking_stats_list, business_analytics_list, alerts)
384
+ track_ids_info = self._get_track_ids_info(counting_summary.get("detections", []))
385
+ # Step 14: Build result
386
+ incidents = incidents_list[0] if incidents_list else {}
387
+ tracking_stats = tracking_stats_list[0] if tracking_stats_list else {}
388
+ business_analytics = business_analytics_list[0] if business_analytics_list else {}
389
+ summary = summary_list[0] if summary_list else {}
390
+ agg_summary = {str(frame_number): {
391
+ "incidents": incidents,
392
+ "tracking_stats": tracking_stats,
393
+ "business_analytics": business_analytics,
394
+ "alerts": alerts,
395
+ "human_text": summary,
396
+ }}
397
+
398
+ context.mark_completed()
399
+ result = self.create_result(
400
+ data={"agg_summary": agg_summary},
401
+ usecase=self.name,
402
+ category=self.category,
403
+ context=context
404
+ )
405
+ proc_time = time.time() - processing_start
406
+ processing_latency_ms = proc_time * 1000.0
407
+ processing_fps = (1.0 / proc_time) if proc_time > 0 else None
408
+ # Log the performance metrics using the module-level logger
409
+ print("latency in ms:",processing_latency_ms,"| Throughput fps:",processing_fps,"| Frame_Number:",self._total_frame_counter)
410
+
411
+
412
+ return result
413
+
414
+ except Exception as e:
415
+ self.logger.error(f"Age and Gender Detection failed: {str(e)}", exc_info=True)
416
+ if context:
417
+ context.mark_completed()
418
+ return self.create_error_result(str(e), type(e).__name__, usecase=self.name, category=self.category, context=context)
419
+
420
+ def _get_frame_detections(self, data: Any, frame_key: str) -> List[Dict[str, Any]]:
421
+ """Extract detections for a specific frame from data."""
422
+ if isinstance(data, dict):
423
+ return data.get(frame_key, [])
424
+ elif isinstance(data, list):
425
+ return data
426
+ else:
427
+ return []
428
+
429
+ def _count_categories(self, detections: List[Dict], config: AgeGenderConfig, data) -> Dict[str, Any]:
430
+ """Count unique licence-plate texts per frame and attach detections."""
431
+ total_count = set()
432
+ valid_detections: List[Dict[str, Any]] = []
433
+ for det in detections:
434
+ if not all(k in det for k in ['category', 'confidence', 'bounding_box']):
435
+ continue
436
+ cat = det.get('category', 'Person')
437
+ track_id = det['track_id']
438
+ total_count.add(det['track_id'])
439
+
440
+ if track_id not in self.all_track_data:
441
+ self.all_track_data.append(track_id)
442
+
443
+ counts = {"Person": len(total_count)} if total_count else {}
444
+
445
+ valid_detections.append({
446
+ "bounding_box": det.get("bounding_box"),
447
+ "category": cat,
448
+ "confidence": det.get("confidence"),
449
+ "track_id": det.get('track_id'),
450
+ "frame_id": det.get("frame_id"),
451
+ "masks": det.get("masks", []),
452
+ })
453
+
454
+ print(data)
455
+ # Case 1: if data is a single dict
456
+ if isinstance(data, dict):
457
+ cats = [data] # wrap in list so loop works
458
+ # Case 2: if data is already a list of dicts
459
+ elif isinstance(data, list):
460
+ cats = data
461
+ else:
462
+ raise TypeError(f"Unexpected type for data: {type(data)}")
463
+
464
+ results = []
465
+ latest_result = {}
466
+ for cat in cats:
467
+ age_data = cat.get("Age Data", {})
468
+ gender_data = cat.get("Gender Data", {})
469
+
470
+ latest_age = {track_id: preds[-1] for track_id, preds in age_data.items() if preds}
471
+ latest_gender = {track_id: preds[-1] for track_id, preds in gender_data.items() if preds}
472
+ latest_result.update({
473
+ "Latest Age": latest_age,
474
+ "Latest Gender": latest_gender
475
+ })
476
+
477
+ # --- Most common gender ---
478
+ most_common_gender = {}
479
+ for track_id, preds in gender_data.items():
480
+ counter = Counter(preds)
481
+ most_common, count = counter.most_common(1)[0]
482
+ most_common_gender[track_id] = [most_common]
483
+
484
+ # --- Mean age ---
485
+ mean_age = {}
486
+ for track_id, preds in age_data.items():
487
+ if preds: # make sure list not empty
488
+ mean_age[track_id] = int(np.mean(preds))
489
+
490
+ results.append({
491
+ "Mean Age": mean_age,
492
+ "Most Common Gender": most_common_gender
493
+ })
494
+
495
+
496
+ return {
497
+ "total_count": len(total_count),
498
+ "per_category_count": counts,
499
+ "detections": valid_detections,
500
+ "Age_Gender_Data": results[0] if isinstance(data, dict) else results,
501
+ "latest": latest_result
502
+ }
503
+
504
+ def _generate_tracking_stats(self, counting_summary: Dict, alerts: Any, config: AgeGenderConfig,
505
+ frame_number: Optional[int] = None, stream_info: Optional[Dict[str, Any]] = None) -> List[Dict]:
506
+ """Generate structured tracking stats with frame-based keys."""
507
+ tracking_stats = []
508
+ total_detections = counting_summary.get("total_count", 0)
509
+ total_counts = counting_summary.get("total_count", {})
510
+ # cumulative_total = sum(set(total_counts.values())) if total_counts else 0
511
+ per_category_count = counting_summary.get("per_category_count", {})
512
+ track_ids_info = self._get_track_ids_info(counting_summary.get("detections", []))
513
+ current_timestamp = self._get_current_timestamp_str(stream_info, precision=False)
514
+ start_timestamp = self._get_start_timestamp_str(stream_info, precision=False)
515
+ high_precision_start_timestamp = self._get_current_timestamp_str(stream_info, precision=True)
516
+ high_precision_reset_timestamp = self._get_start_timestamp_str(stream_info, precision=True)
517
+ camera_info = self.get_camera_info_from_stream(stream_info)
518
+ age_gender_data = counting_summary.get("Age_Gender_Data")
519
+ curr_frame_data = counting_summary.get("latest")
520
+ current_counts = [f"{curr_frame_data['Latest Age'][track_id]}-{curr_frame_data['Latest Gender'].get(track_id, 'Unknown')}"
521
+ for track_id in curr_frame_data['Latest Age']
522
+ ]
523
+
524
+ human_text_lines = []
525
+ print("counting_summary", counting_summary)
526
+ human_text_lines.append(f"CURRENT FRAME @ {current_timestamp}:")
527
+ human_text_lines.append(f"\tPerson Detected: {len(current_counts)}")
528
+ if total_detections > 0:
529
+ for track_id in curr_frame_data['Latest Age']:
530
+ age = curr_frame_data['Latest Age'][track_id]
531
+ gender = curr_frame_data['Latest Gender'].get(track_id, "Unknown")
532
+ human_text_lines.append(f"\t\t{age}-{gender}")
533
+ else:
534
+ human_text_lines.append(f"\t- No detections")
535
+ age_gender_pairs = [
536
+ f"{age_gender_data['Mean Age'][tid]}-{age_gender_data['Most Common Gender'][tid][0]}"
537
+ for tid in age_gender_data['Mean Age']
538
+ ]
539
+ pair_counts = Counter(age_gender_pairs)
540
+ result_list = [(pair,count) for pair, count in pair_counts.items()]
541
+ human_text_lines.append("")
542
+ human_text_lines.append(f"TOTAL SINCE {start_timestamp}:")
543
+ human_text_lines.append(f"\t- Total Detected: {len(age_gender_data['Mean Age'])}")
544
+ for pair, count in result_list:
545
+ human_text_lines.append(f"\t\t{pair}:{count}")
546
+
547
+ # total_counts_list = [{"category": cat, "count": count} for cat, count in total_counts.items() if count > 0 or cumulative_total > 0]
548
+
549
+ human_text = "\n".join(human_text_lines)
550
+ detections = []
551
+ for detection in counting_summary.get("detections", []):
552
+ bbox = detection.get("bounding_box", {})
553
+ category = detection.get("category", "FACE")
554
+ if category == "FACE":
555
+ category = "Person"
556
+ #plate_text = detection.get("plate_text", "")
557
+ segmentation = detection.get("masks", detection.get("segmentation", detection.get("mask", [])))
558
+ detection_obj = self.create_detection_object(category, bbox, segmentation=None)
559
+ detections.append(detection_obj)
560
+
561
+ alert_settings = []
562
+ if config.alert_config and hasattr(config.alert_config, 'alert_type'):
563
+ alert_settings.append({
564
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']),
565
+ "incident_category": self.CASE_TYPE,
566
+ "threshold_level": config.alert_config.count_thresholds if hasattr(config.alert_config, 'count_thresholds') else {},
567
+ "ascending": True,
568
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']),
569
+ getattr(config.alert_config, 'alert_value', ['JSON']))}
570
+ })
571
+
572
+ if alerts:
573
+ human_text_lines.append(f"Alerts: {alerts[0].get('settings', {})}")
574
+ else:
575
+ human_text_lines.append("Alerts: None")
576
+
577
+ human_text = "\n".join(human_text_lines)
578
+ reset_settings = [{"interval_type": "daily", "reset_time": {"value": 9, "time_unit": "hour"}}]
579
+
580
+ tracking_stat = self.create_tracking_stats(
581
+ total_counts=total_counts,
582
+ current_counts=current_counts,
583
+ detections=detections,
584
+ human_text=human_text,
585
+ camera_info=camera_info,
586
+ alerts=alerts,
587
+ alert_settings=alert_settings,
588
+ reset_settings=reset_settings,
589
+ start_time=high_precision_start_timestamp,
590
+ reset_time=high_precision_reset_timestamp
591
+ )
592
+ tracking_stats.append(tracking_stat)
593
+ print(tracking_stats)
594
+ return tracking_stats
595
+
596
+ def _check_alerts(self, summary: Dict, frame_number: Any, config: AgeGenderConfig) -> List[Dict]:
597
+ """Check if any alert thresholds are exceeded."""
598
+ def get_trend(data, lookback=900, threshold=0.6):
599
+ window = data[-lookback:] if len(data) >= lookback else data
600
+ if len(window) < 2:
601
+ return True
602
+ increasing = sum(1 for i in range(1, len(window)) if window[i] >= window[i - 1])
603
+ return increasing / (len(window) - 1) >= threshold
604
+
605
+ frame_key = str(frame_number) if frame_number is not None else "current_frame"
606
+ alerts = []
607
+ total_detections = summary.get("total_count", 0)
608
+ # total_counts_dict = summary.get("total_counts", {})
609
+ # cumulative_total = sum(total_counts_dict.values()) if total_counts_dict else 0
610
+ per_category_count = summary.get("per_category_count", {})
611
+
612
+ if not config.alert_config:
613
+ return alerts
614
+
615
+ # Extract thresholds regardless of dict/dataclass
616
+ _alert_cfg = config.alert_config
617
+ _thresholds = getattr(_alert_cfg, 'count_thresholds', None) if not isinstance(_alert_cfg, dict) else _alert_cfg.get('count_thresholds')
618
+ _types = getattr(_alert_cfg, 'alert_type', None) if not isinstance(_alert_cfg, dict) else _alert_cfg.get('alert_type')
619
+ _values = getattr(_alert_cfg, 'alert_value', None) if not isinstance(_alert_cfg, dict) else _alert_cfg.get('alert_value')
620
+ _types = _types if isinstance(_types, list) else (list(_types) if _types is not None else ['Default'])
621
+ _values = _values if isinstance(_values, list) else (list(_values) if _values is not None else ['JSON'])
622
+ if _thresholds:
623
+ for category, threshold in _thresholds.items():
624
+ if category == "all" and total_detections > threshold:
625
+ alerts.append({
626
+ "alert_type": _types,
627
+ "alert_id": f"alert_{category}_{frame_key}",
628
+ "incident_category": self.CASE_TYPE,
629
+ "threshold_level": threshold,
630
+ "ascending": get_trend(self._ascending_alert_list),
631
+ "settings": {t: v for t, v in zip(_types, _values)}
632
+ })
633
+ elif category in per_category_count and per_category_count[category] > threshold:
634
+ alerts.append({
635
+ "alert_type": _types,
636
+ "alert_id": f"alert_{category}_{frame_key}",
637
+ "incident_category": self.CASE_TYPE,
638
+ "threshold_level": threshold,
639
+ "ascending": get_trend(self._ascending_alert_list),
640
+ "settings": {t: v for t, v in zip(_types, _values)}
641
+ })
642
+ return alerts
643
+
644
+ def _generate_incidents(self, counting_summary: Dict, alerts: List, config: AgeGenderConfig,
645
+ frame_number: Optional[int] = None, stream_info: Optional[Dict[str, Any]] = None) -> List[Dict]:
646
+ """Generate structured incidents."""
647
+ frame_key = str(frame_number) if frame_number is not None else "current_frame"
648
+ incidents = []
649
+ total_detections = counting_summary.get("total_count", 0)
650
+ current_timestamp = self._get_current_timestamp_str(stream_info, precision=False)
651
+ camera_info = self.get_camera_info_from_stream(stream_info)
652
+
653
+ self._ascending_alert_list = self._ascending_alert_list[-900:] if len(self._ascending_alert_list) > 900 else self._ascending_alert_list
654
+
655
+ if total_detections > 0:
656
+ level = "low"
657
+ intensity = 5.0
658
+ start_timestamp = self._get_start_timestamp_str(stream_info, precision=False)
659
+ if start_timestamp and self.current_incident_end_timestamp == 'N/A':
660
+ self.current_incident_end_timestamp = 'Incident still active'
661
+ elif start_timestamp and self.current_incident_end_timestamp == 'Incident still active':
662
+ if len(self._ascending_alert_list) >= 15 and sum(self._ascending_alert_list[-15:]) / 15 < 1.5:
663
+ self.current_incident_end_timestamp = current_timestamp
664
+ elif self.current_incident_end_timestamp != 'Incident still active' and self.current_incident_end_timestamp != 'N/A':
665
+ self.current_incident_end_timestamp = 'N/A'
666
+
667
+ if config.alert_config and config.alert_config.count_thresholds:
668
+ threshold = config.alert_config.count_thresholds.get("all", 15)
669
+ intensity = min(10.0, (total_detections / threshold) * 10)
670
+ if intensity >= 9:
671
+ level = "critical"
672
+ self._ascending_alert_list.append(3)
673
+ elif intensity >= 7:
674
+ level = "significant"
675
+ self._ascending_alert_list.append(2)
676
+ elif intensity >= 5:
677
+ level = "medium"
678
+ self._ascending_alert_list.append(1)
679
+ else:
680
+ level = "low"
681
+ self._ascending_alert_list.append(0)
682
+ else:
683
+ if total_detections > 30:
684
+ level = "critical"
685
+ intensity = 10.0
686
+ self._ascending_alert_list.append(3)
687
+ elif total_detections > 25:
688
+ level = "significant"
689
+ intensity = 9.0
690
+ self._ascending_alert_list.append(2)
691
+ elif total_detections > 15:
692
+ level = "medium"
693
+ intensity = 7.0
694
+ self._ascending_alert_list.append(1)
695
+ else:
696
+ level = "low"
697
+ intensity = min(10.0, total_detections / 3.0)
698
+ self._ascending_alert_list.append(0)
699
+
700
+ human_text_lines = [f"INCIDENTS DETECTED @ {current_timestamp}:"]
701
+ human_text_lines.append(f"\tSeverity Level: {(self.CASE_TYPE, level)}")
702
+ human_text = "\n".join(human_text_lines)
703
+
704
+ alert_settings = []
705
+ if config.alert_config:
706
+ _alert_cfg = config.alert_config
707
+ _types = getattr(_alert_cfg, 'alert_type', None) if not isinstance(_alert_cfg, dict) else _alert_cfg.get('alert_type')
708
+ _values = getattr(_alert_cfg, 'alert_value', None) if not isinstance(_alert_cfg, dict) else _alert_cfg.get('alert_value')
709
+ _thresholds = getattr(_alert_cfg, 'count_thresholds', None) if not isinstance(_alert_cfg, dict) else _alert_cfg.get('count_thresholds')
710
+ _types = _types if isinstance(_types, list) else (list(_types) if _types is not None else ['Default'])
711
+ _values = _values if isinstance(_values, list) else (list(_values) if _values is not None else ['JSON'])
712
+ alert_settings.append({
713
+ "alert_type": _types,
714
+ "incident_category": self.CASE_TYPE,
715
+ "threshold_level": _thresholds or {},
716
+ "ascending": True,
717
+ "settings": {t: v for t, v in zip(_types, _values)}
718
+ })
719
+
720
+ event = self.create_incident(
721
+ incident_id=f"{self.CASE_TYPE}_{frame_key}",
722
+ incident_type=self.CASE_TYPE,
723
+ severity_level=level,
724
+ human_text=human_text,
725
+ camera_info=camera_info,
726
+ alerts=alerts,
727
+ alert_settings=alert_settings,
728
+ start_time=start_timestamp,
729
+ end_time=self.current_incident_end_timestamp,
730
+ level_settings={"low": 1, "medium": 3, "significant": 4, "critical": 7}
731
+ )
732
+ incidents.append(event)
733
+ else:
734
+ self._ascending_alert_list.append(0)
735
+ incidents.append({})
736
+
737
+ return incidents
738
+
739
+ def _generate_summary(self, summary: Dict, incidents: List, tracking_stats: List, business_analytics: List, alerts: List) -> List[Dict]:
740
+ """Generate a human-readable summary."""
741
+ """
742
+ Generate a human_text string for the tracking_stat, incident, business analytics and alerts.
743
+ """
744
+ lines = []
745
+ lines.append("Application Name: "+self.CASE_TYPE)
746
+ lines.append("Application Version: "+self.CASE_VERSION)
747
+ if len(incidents) > 0:
748
+ lines.append("Incidents: "+f"\n\t{incidents[0].get('human_text', 'No incidents detected')}")
749
+ if len(tracking_stats) > 0:
750
+ lines.append("Tracking Statistics: "+f"\t{tracking_stats[0].get('human_text', 'No tracking statistics detected')}")
751
+ if len(business_analytics) > 0:
752
+ lines.append("Business Analytics: "+f"\t{business_analytics[0].get('human_text', 'No business analytics detected')}")
753
+
754
+ if len(incidents) == 0 and len(tracking_stats) == 0 and len(business_analytics) == 0:
755
+ lines.append("Summary: "+"No Summary Data")
756
+
757
+ return ["\n".join(lines)]
758
+
759
+ def _update_tracking_state(self, detections: List[Dict]):
760
+ """Track unique track_ids per category."""
761
+ if not hasattr(self, "_per_category_total_track_ids"):
762
+ self._per_category_total_track_ids = {cat: set() for cat in self.target_categories}
763
+ self._current_frame_track_ids = {cat: set() for cat in self.target_categories}
764
+
765
+ for det in detections:
766
+ cat = det.get("category")
767
+ raw_track_id = det.get("track_id")
768
+ if cat not in self.target_categories or raw_track_id is None:
769
+ continue
770
+ bbox = det.get("bounding_box", det.get("bbox"))
771
+ canonical_id = self._merge_or_register_track(raw_track_id, bbox)
772
+ det["track_id"] = canonical_id
773
+ self._per_category_total_track_ids.setdefault(cat, set()).add(canonical_id)
774
+ self._current_frame_track_ids[cat].add(canonical_id)
775
+
776
+
777
+ def get_total_counts(self):
778
+ """Return total unique age-gender encountered so far."""
779
+ return {'FACE': len(self.all_track_data)}
780
+
781
+ def _get_track_ids_info(self, detections: List[Dict]) -> Dict[str, Any]:
782
+ """Get detailed information about track IDs."""
783
+ frame_track_ids = {det.get('track_id') for det in detections if det.get('track_id') is not None}
784
+ total_track_ids = set()
785
+ for s in getattr(self, '_per_category_total_track_ids', {}).values():
786
+ total_track_ids.update(s)
787
+ return {
788
+ "total_count": len(total_track_ids),
789
+ "current_frame_count": len(frame_track_ids),
790
+ "total_unique_track_ids": len(total_track_ids),
791
+ "current_frame_track_ids": list(frame_track_ids),
792
+ "last_update_time": time.time(),
793
+ "total_frames_processed": getattr(self, '_total_frame_counter', 0)
794
+ }
795
+
796
+ def _compute_iou(self, box1: Any, box2: Any) -> float:
797
+ """Compute IoU between two bounding boxes."""
798
+ def _bbox_to_list(bbox):
799
+ if bbox is None:
800
+ return []
801
+ if isinstance(bbox, list):
802
+ return bbox[:4] if len(bbox) >= 4 else []
803
+ if isinstance(bbox, dict):
804
+ if "xmin" in bbox:
805
+ return [bbox["xmin"], bbox["ymin"], bbox["xmax"], bbox["ymax"]]
806
+ if "x1" in bbox:
807
+ return [bbox["x1"], bbox["y1"], bbox["x2"], bbox["y2"]]
808
+ values = [v for v in bbox.values() if isinstance(v, (int, float))]
809
+ return values[:4] if len(values) >= 4 else []
810
+ return []
811
+
812
+ l1 = _bbox_to_list(box1)
813
+ l2 = _bbox_to_list(box2)
814
+ if len(l1) < 4 or len(l2) < 4:
815
+ return 0.0
816
+ x1_min, y1_min, x1_max, y1_max = l1
817
+ x2_min, y2_min, x2_max, y2_max = l2
818
+ x1_min, x1_max = min(x1_min, x1_max), max(x1_min, x1_max)
819
+ y1_min, y1_max = min(y1_min, y1_max), max(y1_min, y1_max)
820
+ x2_min, x2_max = min(x2_min, x2_max), max(x2_min, x2_max)
821
+ y2_min, y2_max = min(y2_min, y2_max), max(y2_min, y2_max)
822
+ inter_x_min = max(x1_min, x2_min)
823
+ inter_y_min = max(y1_min, y2_min)
824
+ inter_x_max = min(x1_max, x2_max)
825
+ inter_y_max = min(y1_max, y2_max)
826
+ inter_w = max(0.0, inter_x_max - inter_x_min)
827
+ inter_h = max(0.0, inter_y_max - inter_y_min)
828
+ inter_area = inter_w * inter_h
829
+ area1 = (x1_max - x1_min) * (y1_max - y1_min)
830
+ area2 = (x2_max - x2_min) * (y2_max - y2_min)
831
+ union_area = area1 + area2 - inter_area
832
+ return (inter_area / union_area) if union_area > 0 else 0.0
833
+
834
+ def _merge_or_register_track(self, raw_id: Any, bbox: Any) -> Any:
835
+ """Return a stable canonical ID for a raw tracker ID."""
836
+ if raw_id is None or bbox is None:
837
+ return raw_id
838
+ now = time.time()
839
+ if raw_id in self._track_aliases:
840
+ canonical_id = self._track_aliases[raw_id]
841
+ track_info = self._canonical_tracks.get(canonical_id)
842
+ if track_info is not None:
843
+ track_info["last_bbox"] = bbox
844
+ track_info["last_update"] = now
845
+ track_info["raw_ids"].add(raw_id)
846
+ return canonical_id
847
+ for canonical_id, info in self._canonical_tracks.items():
848
+ if now - info["last_update"] > self._track_merge_time_window:
849
+ continue
850
+ iou = self._compute_iou(bbox, info["last_bbox"])
851
+ if iou >= self._track_merge_iou_threshold:
852
+ self._track_aliases[raw_id] = canonical_id
853
+ info["last_bbox"] = bbox
854
+ info["last_update"] = now
855
+ info["raw_ids"].add(raw_id)
856
+ return canonical_id
857
+ canonical_id = raw_id
858
+ self._track_aliases[raw_id] = canonical_id
859
+ self._canonical_tracks[canonical_id] = {
860
+ "last_bbox": bbox,
861
+ "last_update": now,
862
+ "raw_ids": {raw_id},
863
+ }
864
+ return canonical_id
865
+
866
+ def _format_timestamp(self, timestamp: Any) -> str:
867
+ """Format a timestamp so that exactly two digits follow the decimal point (milliseconds).
868
+
869
+ The input can be either:
870
+ 1. A numeric Unix timestamp (``float`` / ``int``) – it will first be converted to a
871
+ string in the format ``YYYY-MM-DD-HH:MM:SS.ffffff UTC``.
872
+ 2. A string already following the same layout.
873
+
874
+ The returned value preserves the overall format of the input but truncates or pads
875
+ the fractional seconds portion to **exactly two digits**.
876
+
877
+ Example
878
+ -------
879
+ >>> self._format_timestamp("2025-08-19-04:22:47.187574 UTC")
880
+ '2025-08-19-04:22:47.18 UTC'
881
+ """
882
+
883
+ # Convert numeric timestamps to the expected string representation first
884
+ if isinstance(timestamp, (int, float)):
885
+ timestamp = datetime.fromtimestamp(timestamp, timezone.utc).strftime(
886
+ '%Y-%m-%d-%H:%M:%S.%f UTC'
887
+ )
888
+
889
+ # Ensure we are working with a string from here on
890
+ if not isinstance(timestamp, str):
891
+ return str(timestamp)
892
+
893
+ # If there is no fractional component, simply return the original string
894
+ if '.' not in timestamp:
895
+ return timestamp
896
+
897
+ # Split out the main portion (up to the decimal point)
898
+ main_part, fractional_and_suffix = timestamp.split('.', 1)
899
+
900
+ # Separate fractional digits from the suffix (typically ' UTC')
901
+ if ' ' in fractional_and_suffix:
902
+ fractional_part, suffix = fractional_and_suffix.split(' ', 1)
903
+ suffix = ' ' + suffix # Re-attach the space removed by split
904
+ else:
905
+ fractional_part, suffix = fractional_and_suffix, ''
906
+
907
+ # Guarantee exactly two digits for the fractional part
908
+ fractional_part = (fractional_part + '00')[:2]
909
+
910
+ return f"{main_part}.{fractional_part}{suffix}"
911
+
912
+ def _format_timestamp_for_stream(self, timestamp: float) -> str:
913
+ """Format timestamp for streams (YYYY:MM:DD HH:MM:SS format)."""
914
+ dt = datetime.fromtimestamp(timestamp, tz=timezone.utc)
915
+ return dt.strftime('%Y:%m:%d %H:%M:%S')
916
+
917
+ def _format_timestamp_for_video(self, timestamp: float) -> str:
918
+ """Format timestamp for video chunks (HH:MM:SS.ms format)."""
919
+ hours = int(timestamp // 3600)
920
+ minutes = int((timestamp % 3600) // 60)
921
+ seconds = round(float(timestamp % 60), 2)
922
+ return f"{hours:02d}:{minutes:02d}:{seconds:.1f}"
923
+
924
+ def _get_current_timestamp_str(self, stream_info: Optional[Dict[str, Any]], precision=False, frame_id: Optional[str]=None) -> str:
925
+ """Get formatted current timestamp based on stream type."""
926
+
927
+ if not stream_info:
928
+ return "00:00:00.00"
929
+ if precision:
930
+ if stream_info.get("input_settings", {}).get("start_frame", "na") != "na":
931
+ if frame_id:
932
+ start_time = int(frame_id)/stream_info.get("input_settings", {}).get("original_fps", 30)
933
+ else:
934
+ start_time = stream_info.get("input_settings", {}).get("start_frame", 30)/stream_info.get("input_settings", {}).get("original_fps", 30)
935
+ stream_time_str = self._format_timestamp_for_video(start_time)
936
+
937
+ return self._format_timestamp(stream_info.get("input_settings", {}).get("stream_time", "NA"))
938
+ else:
939
+ return datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
940
+
941
+ if stream_info.get("input_settings", {}).get("start_frame", "na") != "na":
942
+ if frame_id:
943
+ start_time = int(frame_id)/stream_info.get("input_settings", {}).get("original_fps", 30)
944
+ else:
945
+ start_time = stream_info.get("input_settings", {}).get("start_frame", 30)/stream_info.get("input_settings", {}).get("original_fps", 30)
946
+
947
+ stream_time_str = self._format_timestamp_for_video(start_time)
948
+
949
+
950
+ return self._format_timestamp(stream_info.get("input_settings", {}).get("stream_time", "NA"))
951
+ else:
952
+ stream_time_str = stream_info.get("input_settings", {}).get("stream_info", {}).get("stream_time", "")
953
+ if stream_time_str:
954
+ try:
955
+ timestamp_str = stream_time_str.replace(" UTC", "")
956
+ dt = datetime.strptime(timestamp_str, "%Y-%m-%d-%H:%M:%S.%f")
957
+ timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
958
+ return self._format_timestamp_for_stream(timestamp)
959
+ except:
960
+ return self._format_timestamp_for_stream(time.time())
961
+ else:
962
+ return self._format_timestamp_for_stream(time.time())
963
+
964
+ def _get_start_timestamp_str(self, stream_info: Optional[Dict[str, Any]], precision=False) -> str:
965
+ """Get formatted start timestamp for 'TOTAL SINCE' based on stream type."""
966
+ if not stream_info:
967
+ return "00:00:00"
968
+
969
+ if precision:
970
+ if self.start_timer is None:
971
+ self.start_timer = stream_info.get("input_settings", {}).get("stream_time", "NA")
972
+ return self._format_timestamp(self.start_timer)
973
+ elif stream_info.get("input_settings", {}).get("start_frame", "na") == 1:
974
+ self.start_timer = stream_info.get("input_settings", {}).get("stream_time", "NA")
975
+ return self._format_timestamp(self.start_timer)
976
+ else:
977
+ return self._format_timestamp(self.start_timer)
978
+
979
+ if self.start_timer is None:
980
+ self.start_timer = stream_info.get("input_settings", {}).get("stream_time", "NA")
981
+ return self._format_timestamp(self.start_timer)
982
+ elif stream_info.get("input_settings", {}).get("start_frame", "na") == 1:
983
+ self.start_timer = stream_info.get("input_settings", {}).get("stream_time", "NA")
984
+ return self._format_timestamp(self.start_timer)
985
+
986
+ else:
987
+ if self.start_timer is not None:
988
+ return self._format_timestamp(self.start_timer)
989
+
990
+ if self._tracking_start_time is None:
991
+ stream_time_str = stream_info.get("input_settings", {}).get("stream_info", {}).get("stream_time", "")
992
+ if stream_time_str:
993
+ try:
994
+ timestamp_str = stream_time_str.replace(" UTC", "")
995
+ dt = datetime.strptime(timestamp_str, "%Y-%m-%d-%H:%M:%S.%f")
996
+ self._tracking_start_time = dt.replace(tzinfo=timezone.utc).timestamp()
997
+ except:
998
+ self._tracking_start_time = time.time()
999
+ else:
1000
+ self._tracking_start_time = time.time()
1001
+
1002
+ dt = datetime.fromtimestamp(self._tracking_start_time, tz=timezone.utc)
1003
+ dt = dt.replace(minute=0, second=0, microsecond=0)
1004
+ return dt.strftime('%Y:%m:%d %H:%M:%S')
1005
+
1006
+ def _get_tracking_start_time(self) -> str:
1007
+ """Get the tracking start time, formatted as a string."""
1008
+ if self._tracking_start_time is None:
1009
+ return "N/A"
1010
+ return self._format_timestamp(self._tracking_start_time)
1011
+
1012
+ def _set_tracking_start_time(self) -> None:
1013
+ """Set the tracking start time to the current time."""
1014
+ self._tracking_start_time = time.time()
1015
+
1016
+ def _attach_masks_to_detections(self, processed_detections: List[Dict[str, Any]], raw_detections: List[Dict[str, Any]],
1017
+ iou_threshold: float = 0.5) -> List[Dict[str, Any]]:
1018
+ """Attach segmentation masks from raw detections to processed detections."""
1019
+ if not processed_detections or not raw_detections:
1020
+ for det in processed_detections:
1021
+ det.setdefault("masks", [])
1022
+ return processed_detections
1023
+
1024
+ used_raw_indices = set()
1025
+ for det in processed_detections:
1026
+ best_iou = 0.0
1027
+ best_idx = None
1028
+ for idx, raw_det in enumerate(raw_detections):
1029
+ if idx in used_raw_indices:
1030
+ continue
1031
+ iou = self._compute_iou(det.get("bounding_box"), raw_det.get("bounding_box"))
1032
+ if iou > best_iou:
1033
+ best_iou = iou
1034
+ best_idx = idx
1035
+ if best_idx is not None and best_iou >= iou_threshold:
1036
+ raw_det = raw_detections[best_idx]
1037
+ masks = raw_det.get("masks", raw_det.get("mask"))
1038
+ if masks is not None:
1039
+ det["masks"] = masks
1040
+ used_raw_indices.add(best_idx)
1041
+ else:
1042
+ det.setdefault("masks", ["EMPTY"])
1043
+ return processed_detections