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,950 @@
1
+ from typing import Any, Dict, List, Optional, Tuple
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
+ from ..utils.geometry_utils import get_bbox_center, point_in_polygon, get_bbox_bottom25_center
22
+
23
+ @dataclass
24
+ class VehicleMonitoringConfig(BaseConfig):
25
+ """Configuration for vehicle detection use case in vehicle monitoring."""
26
+ enable_smoothing: bool = True
27
+ smoothing_algorithm: str = "observability"
28
+ smoothing_window_size: int = 20
29
+ smoothing_cooldown_frames: int = 5
30
+ smoothing_confidence_range_factor: float = 0.5
31
+ confidence_threshold: float = 0.6
32
+
33
+ #JBK_720_GATE POLYGON = [[86, 328], [844, 317], [1277, 520], [1273, 707], [125, 713]]
34
+ zone_config: Optional[Dict[str, Dict[str, List[List[float]]]]] = None #field(
35
+ # default_factory=lambda: {
36
+ # "zones": {
37
+ # "Interest_Region": [[86, 328], [844, 317], [1277, 520], [1273, 707], [125, 713]],
38
+ # }
39
+ # }
40
+ # )
41
+ usecase_categories: List[str] = field(
42
+ default_factory=lambda: [
43
+ "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat",
44
+ "traffic light", "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog",
45
+ "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella",
46
+ "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball", "kite",
47
+ "baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket", "bottle",
48
+ "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich",
49
+ "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch",
50
+ "potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote",
51
+ "keyboard", "cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "book",
52
+ "clock", "vase", "scissors", "teddy bear", "hair drier", "toothbrush"
53
+ ]
54
+ )
55
+ target_categories: List[str] = field(
56
+ default_factory=lambda: [
57
+ 'car', 'bicycle', 'bus','motorcycle']
58
+ )
59
+ alert_config: Optional[AlertConfig] = None
60
+ index_to_category: Optional[Dict[int, str]] = field(
61
+ default_factory=lambda: {
62
+ 0: "person", 1: "bicycle", 2: "car", 3: "motorcycle", 4: "airplane", 5: "bus",
63
+ 6: "train", 7: "truck", 8: "boat", 9: "traffic light", 10: "fire hydrant",
64
+ 11: "stop sign", 12: "parking meter", 13: "bench", 14: "bird", 15: "cat",
65
+ 16: "dog", 17: "horse", 18: "sheep", 19: "cow", 20: "elephant", 21: "bear",
66
+ 22: "zebra", 23: "giraffe", 24: "backpack", 25: "umbrella", 26: "handbag",
67
+ 27: "tie", 28: "suitcase", 29: "frisbee", 30: "skis", 31: "snowboard",
68
+ 32: "sports ball", 33: "kite", 34: "baseball bat", 35: "baseball glove",
69
+ 36: "skateboard", 37: "surfboard", 38: "tennis racket", 39: "bottle",
70
+ 40: "wine glass", 41: "cup", 42: "fork", 43: "knife", 44: "spoon", 45: "bowl",
71
+ 46: "banana", 47: "apple", 48: "sandwich", 49: "orange", 50: "broccoli",
72
+ 51: "carrot", 52: "hot dog", 53: "pizza", 54: "donut", 55: "cake", 56: "chair",
73
+ 57: "couch", 58: "potted plant", 59: "bed", 60: "dining table", 61: "toilet",
74
+ 62: "tv", 63: "laptop", 64: "mouse", 65: "remote", 66: "keyboard",
75
+ 67: "cell phone", 68: "microwave", 69: "oven", 70: "toaster", 71: "sink",
76
+ 72: "refrigerator", 73: "book", 74: "clock", 75: "vase", 76: "scissors",
77
+ 77: "teddy bear", 78: "hair drier", 79: "toothbrush"
78
+ }
79
+ )
80
+
81
+ class VehicleMonitoringUseCase(BaseProcessor):
82
+ CATEGORY_DISPLAY = {
83
+ # Focus on vehicle-related COCO classes
84
+ "bicycle": "Bicycle",
85
+ "car": "Car",
86
+ "motorcycle": "Motorcycle",
87
+ "bus": "Bus",
88
+ "truck": "Truck",
89
+ "train": "Train",
90
+ "boat": "Boat"
91
+ }
92
+
93
+ def __init__(self):
94
+ super().__init__("vehicle_monitoring")
95
+ self.category = "traffic"
96
+ self.CASE_TYPE: Optional[str] = 'vehicle_monitoring'
97
+ self.CASE_VERSION: Optional[str] = '1.0'
98
+ self.target_categories = ['car', 'bicycle', 'bus', 'truck', 'motorcycle']
99
+ self.smoothing_tracker = None
100
+ self.tracker = None
101
+ self._total_frame_counter = 0
102
+ self._global_frame_offset = 0
103
+ self._tracking_start_time = None
104
+ self._track_aliases: Dict[Any, Any] = {}
105
+ self._canonical_tracks: Dict[Any, Dict[str, Any]] = {}
106
+ self._track_merge_iou_threshold: float = 0.05
107
+ self._track_merge_time_window: float = 7.0
108
+ self._ascending_alert_list: List[int] = []
109
+ self.current_incident_end_timestamp: str = "N/A"
110
+ self.start_timer = None
111
+
112
+ # Track ID storage for total count calculation
113
+ self._total_track_ids = set() # Store all unique track IDs seen across calls
114
+ self._current_frame_track_ids = set() # Store track IDs from current frame
115
+ self._total_count = 0 # Cached total count
116
+ self._last_update_time = time.time() # Track when last updated
117
+ self._total_count_list = []
118
+
119
+ # Zone-based tracking storage
120
+ self._zone_current_track_ids = {} # zone_name -> set of current track IDs in zone
121
+ self._zone_total_track_ids = {} # zone_name -> set of all track IDs that have been in zone
122
+ self._zone_current_counts = {} # zone_name -> current count in zone
123
+ self._zone_total_counts = {} # zone_name -> total count that have been in zone
124
+
125
+ def process(self, data: Any, config: ConfigProtocol, context: Optional[ProcessingContext] = None,
126
+ stream_info: Optional[Dict[str, Any]] = None) -> ProcessingResult:
127
+ processing_start = time.time()
128
+ if not isinstance(config, VehicleMonitoringConfig):
129
+ return self.create_error_result("Invalid config type", usecase=self.name, category=self.category, context=context)
130
+ if context is None:
131
+ context = ProcessingContext()
132
+
133
+ # Normalize typical YOLO outputs (COCO pretrained) to internal schema
134
+ data = self._normalize_yolo_results(data, getattr(config, 'index_to_category', None))
135
+
136
+ input_format = match_results_structure(data)
137
+ context.input_format = input_format
138
+ context.confidence_threshold = config.confidence_threshold
139
+ config.confidence_threshold = 0.25
140
+
141
+ if config.confidence_threshold is not None:
142
+ processed_data = filter_by_confidence(data, config.confidence_threshold)
143
+ self.logger.debug(f"Applied confidence filtering with threshold {config.confidence_threshold}")
144
+ else:
145
+ processed_data = data
146
+ self.logger.debug("Did not apply confidence filtering since no threshold provided")
147
+
148
+ if config.index_to_category:
149
+ processed_data = apply_category_mapping(processed_data, config.index_to_category)
150
+ self.logger.debug("Applied category mapping")
151
+
152
+ processed_data = [d for d in processed_data if d.get('category') in self.target_categories]
153
+ if config.target_categories:
154
+ processed_data = [d for d in processed_data if d.get('category') in self.target_categories]
155
+ self.logger.debug("Applied category filtering")
156
+
157
+
158
+ if config.enable_smoothing:
159
+ if self.smoothing_tracker is None:
160
+ smoothing_config = BBoxSmoothingConfig(
161
+ smoothing_algorithm=config.smoothing_algorithm,
162
+ window_size=config.smoothing_window_size,
163
+ cooldown_frames=config.smoothing_cooldown_frames,
164
+ confidence_threshold=config.confidence_threshold,
165
+ confidence_range_factor=config.smoothing_confidence_range_factor,
166
+ enable_smoothing=True
167
+ )
168
+ self.smoothing_tracker = BBoxSmoothingTracker(smoothing_config)
169
+ processed_data = bbox_smoothing(processed_data, self.smoothing_tracker.config, self.smoothing_tracker)
170
+
171
+ try:
172
+ from ..advanced_tracker import AdvancedTracker
173
+ from ..advanced_tracker.config import TrackerConfig
174
+ if self.tracker is None:
175
+ tracker_config = TrackerConfig()
176
+ self.tracker = AdvancedTracker(tracker_config)
177
+ self.logger.info("Initialized AdvancedTracker for Vehicle Monitoring")
178
+ processed_data = self.tracker.update(processed_data)
179
+ except Exception as e:
180
+ self.logger.warning(f"AdvancedTracker failed: {e}")
181
+
182
+ self._update_tracking_state(processed_data)
183
+ self._total_frame_counter += 1
184
+
185
+ frame_number = None
186
+ if stream_info:
187
+ input_settings = stream_info.get("input_settings", {})
188
+ start_frame = input_settings.get("start_frame")
189
+ end_frame = input_settings.get("end_frame")
190
+ if start_frame is not None and end_frame is not None and start_frame == end_frame:
191
+ frame_number = start_frame
192
+
193
+ general_counting_summary = calculate_counting_summary(data)
194
+ counting_summary = self._count_categories(processed_data, config)
195
+ total_counts = self.get_total_counts()
196
+ counting_summary['total_counts'] = total_counts
197
+ counting_summary['categories'] = {}
198
+ for detection in processed_data:
199
+ category = detection.get("category", "unknown")
200
+ counting_summary["categories"][category] = counting_summary["categories"].get(category, 0) + 1
201
+
202
+ zone_analysis = {}
203
+ if config.zone_config and config.zone_config['zones']:
204
+ # Convert single frame to format expected by count_objects_in_zones
205
+ frame_data = processed_data #[frame_detections]
206
+ zone_analysis = count_objects_in_zones(frame_data, config.zone_config['zones'], stream_info)
207
+
208
+ if zone_analysis:
209
+ enhanced_zone_analysis = self._update_zone_tracking(zone_analysis, processed_data, config)
210
+ # Merge enhanced zone analysis with original zone analysis
211
+ for zone_name, enhanced_data in enhanced_zone_analysis.items():
212
+ zone_analysis[zone_name] = enhanced_data
213
+
214
+
215
+ alerts = self._check_alerts(counting_summary,zone_analysis, frame_number, config)
216
+ predictions = self._extract_predictions(processed_data)
217
+
218
+ incidents_list = self._generate_incidents(counting_summary,zone_analysis, alerts, config, frame_number, stream_info)
219
+ incidents_list = []
220
+ tracking_stats_list = self._generate_tracking_stats(counting_summary,zone_analysis, alerts, config, frame_number, stream_info)
221
+
222
+ business_analytics_list = self._generate_business_analytics(counting_summary,zone_analysis, alerts, config, stream_info, is_empty=True)
223
+ summary_list = self._generate_summary(counting_summary,zone_analysis, incidents_list, tracking_stats_list, business_analytics_list, alerts)
224
+
225
+ incidents = incidents_list[0] if incidents_list else {}
226
+ tracking_stats = tracking_stats_list[0] if tracking_stats_list else {}
227
+ business_analytics = business_analytics_list[0] if business_analytics_list else {}
228
+ summary = summary_list[0] if summary_list else {}
229
+ agg_summary = {str(frame_number): {
230
+ "incidents": incidents,
231
+ "tracking_stats": tracking_stats,
232
+ "business_analytics": business_analytics,
233
+ "alerts": alerts,
234
+ "zone_analysis": zone_analysis,
235
+ "human_text": summary}
236
+ }
237
+
238
+ context.mark_completed()
239
+ result = self.create_result(
240
+ data={"agg_summary": agg_summary},
241
+ usecase=self.name,
242
+ category=self.category,
243
+ context=context
244
+ )
245
+ proc_time = time.time() - processing_start
246
+ processing_latency_ms = proc_time * 1000.0
247
+ processing_fps = (1.0 / proc_time) if proc_time > 0 else None
248
+ # Log the performance metrics using the module-level logger
249
+ print("latency in ms:",processing_latency_ms,"| Throughput fps:",processing_fps,"| Frame_Number:",self._total_frame_counter)
250
+ return result
251
+
252
+ def _update_zone_tracking(self, zone_analysis: Dict[str, Dict[str, int]], detections: List[Dict], config: VehicleMonitoringConfig) -> Dict[str, Dict[str, Any]]:
253
+ """
254
+ Update zone tracking with current frame data.
255
+
256
+ Args:
257
+ zone_analysis: Current zone analysis results
258
+ detections: List of detections with track IDs
259
+
260
+ Returns:
261
+ Enhanced zone analysis with tracking information
262
+ """
263
+ if not zone_analysis or not config.zone_config or not config.zone_config['zones']:
264
+ return {}
265
+
266
+ enhanced_zone_analysis = {}
267
+ zones = config.zone_config['zones']
268
+
269
+ # Get current frame track IDs in each zone
270
+ current_frame_zone_tracks = {}
271
+
272
+ # Initialize zone tracking for all zones
273
+ for zone_name in zones.keys():
274
+ current_frame_zone_tracks[zone_name] = set()
275
+ if zone_name not in self._zone_current_track_ids:
276
+ self._zone_current_track_ids[zone_name] = set()
277
+ if zone_name not in self._zone_total_track_ids:
278
+ self._zone_total_track_ids[zone_name] = set()
279
+
280
+ # Check each detection against each zone
281
+ for detection in detections:
282
+ track_id = detection.get("track_id")
283
+ if track_id is None:
284
+ continue
285
+
286
+ # Get detection bbox
287
+ bbox = detection.get("bounding_box", detection.get("bbox"))
288
+ if not bbox:
289
+ continue
290
+
291
+ # Get detection center point
292
+ center_point = get_bbox_bottom25_center(bbox) #get_bbox_center(bbox)
293
+
294
+ # Check which zone this detection is in using actual zone polygons
295
+ for zone_name, zone_polygon in zones.items():
296
+ # Convert polygon points to tuples for point_in_polygon function
297
+ # zone_polygon format: [[x1, y1], [x2, y2], [x3, y3], ...]
298
+ polygon_points = [(point[0], point[1]) for point in zone_polygon]
299
+
300
+ # Check if detection center is inside the zone polygon using ray casting algorithm
301
+ if point_in_polygon(center_point, polygon_points):
302
+ current_frame_zone_tracks[zone_name].add(track_id)
303
+ if track_id not in self._total_count_list:
304
+ self._total_count_list.append(track_id)
305
+
306
+ # Update zone tracking for each zone
307
+ for zone_name, zone_counts in zone_analysis.items():
308
+ # Get current frame tracks for this zone
309
+ current_tracks = current_frame_zone_tracks.get(zone_name, set())
310
+
311
+ # Update current zone tracks
312
+ self._zone_current_track_ids[zone_name] = current_tracks
313
+
314
+ # Update total zone tracks (accumulate all track IDs that have been in this zone)
315
+ self._zone_total_track_ids[zone_name].update(current_tracks)
316
+
317
+ # Update counts
318
+ self._zone_current_counts[zone_name] = len(current_tracks)
319
+ self._zone_total_counts[zone_name] = len(self._zone_total_track_ids[zone_name])
320
+
321
+ # Create enhanced zone analysis
322
+ enhanced_zone_analysis[zone_name] = {
323
+ "current_count": self._zone_current_counts[zone_name],
324
+ "total_count": self._zone_total_counts[zone_name],
325
+ "current_track_ids": list(current_tracks),
326
+ "total_track_ids": list(self._zone_total_track_ids[zone_name]),
327
+ "original_counts": zone_counts # Preserve original zone counts
328
+ }
329
+
330
+ return enhanced_zone_analysis
331
+
332
+ def _normalize_yolo_results(self, data: Any, index_to_category: Optional[Dict[int, str]] = None) -> Any:
333
+ """
334
+ Normalize YOLO-style outputs to internal detection schema:
335
+ - category/category_id: prefer string label using COCO mapping if available
336
+ - confidence: map from 'conf'/'score' to 'confidence'
337
+ - bounding_box: ensure dict with keys (x1,y1,x2,y2) or (xmin,ymin,xmax,ymax)
338
+ - supports list of detections and frame_id -> detections dict
339
+ """
340
+ def to_bbox_dict(d: Dict[str, Any]) -> Dict[str, Any]:
341
+ if "bounding_box" in d and isinstance(d["bounding_box"], dict):
342
+ return d["bounding_box"]
343
+ if "bbox" in d:
344
+ bbox = d["bbox"]
345
+ if isinstance(bbox, dict):
346
+ return bbox
347
+ if isinstance(bbox, (list, tuple)) and len(bbox) >= 4:
348
+ x1, y1, x2, y2 = bbox[0], bbox[1], bbox[2], bbox[3]
349
+ return {"x1": x1, "y1": y1, "x2": x2, "y2": y2}
350
+ if "xyxy" in d and isinstance(d["xyxy"], (list, tuple)) and len(d["xyxy"]) >= 4:
351
+ x1, y1, x2, y2 = d["xyxy"][0], d["xyxy"][1], d["xyxy"][2], d["xyxy"][3]
352
+ return {"x1": x1, "y1": y1, "x2": x2, "y2": y2}
353
+ if "xywh" in d and isinstance(d["xywh"], (list, tuple)) and len(d["xywh"]) >= 4:
354
+ cx, cy, w, h = d["xywh"][0], d["xywh"][1], d["xywh"][2], d["xywh"][3]
355
+ x1, y1, x2, y2 = cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2
356
+ return {"x1": x1, "y1": y1, "x2": x2, "y2": y2}
357
+ return {}
358
+
359
+ def resolve_category(d: Dict[str, Any]) -> Tuple[str, Optional[int]]:
360
+ raw_cls = d.get("category", d.get("category_id", d.get("class", d.get("cls"))))
361
+ label_name = d.get("name")
362
+ if isinstance(raw_cls, int):
363
+ if index_to_category and raw_cls in index_to_category:
364
+ return index_to_category[raw_cls], raw_cls
365
+ return str(raw_cls), raw_cls
366
+ if isinstance(raw_cls, str):
367
+ # Some YOLO exports provide string labels directly
368
+ return raw_cls, None
369
+ if label_name:
370
+ return str(label_name), None
371
+ return "unknown", None
372
+
373
+ def normalize_det(det: Dict[str, Any]) -> Dict[str, Any]:
374
+ category_name, category_id = resolve_category(det)
375
+ confidence = det.get("confidence", det.get("conf", det.get("score", 0.0)))
376
+ bbox = to_bbox_dict(det)
377
+ normalized = {
378
+ "category": category_name,
379
+ "confidence": confidence,
380
+ "bounding_box": bbox,
381
+ }
382
+ if category_id is not None:
383
+ normalized["category_id"] = category_id
384
+ # Preserve optional fields
385
+ for key in ("track_id", "frame_id", "masks", "segmentation"):
386
+ if key in det:
387
+ normalized[key] = det[key]
388
+ return normalized
389
+
390
+ if isinstance(data, list):
391
+ return [normalize_det(d) if isinstance(d, dict) else d for d in data]
392
+ if isinstance(data, dict):
393
+ # Detect tracking style dict: frame_id -> list of detections
394
+ normalized_dict: Dict[str, Any] = {}
395
+ for k, v in data.items():
396
+ if isinstance(v, list):
397
+ normalized_dict[k] = [normalize_det(d) if isinstance(d, dict) else d for d in v]
398
+ elif isinstance(v, dict):
399
+ normalized_dict[k] = normalize_det(v)
400
+ else:
401
+ normalized_dict[k] = v
402
+ return normalized_dict
403
+ return data
404
+
405
+ def _check_alerts(self, summary: dict, zone_analysis: Dict, frame_number: Any, config: VehicleMonitoringConfig) -> List[Dict]:
406
+ def get_trend(data, lookback=900, threshold=0.6):
407
+ window = data[-lookback:] if len(data) >= lookback else data
408
+ if len(window) < 2:
409
+ return True
410
+ increasing = 0
411
+ total = 0
412
+ for i in range(1, len(window)):
413
+ if window[i] >= window[i - 1]:
414
+ increasing += 1
415
+ total += 1
416
+ ratio = increasing / total
417
+ return ratio >= threshold
418
+
419
+ frame_key = str(frame_number) if frame_number is not None else "current_frame"
420
+ alerts = []
421
+ total_detections = summary.get("total_count", 0)
422
+ total_counts_dict = summary.get("total_counts", {})
423
+ per_category_count = summary.get("per_category_count", {})
424
+
425
+ if not config.alert_config:
426
+ return alerts
427
+
428
+ if hasattr(config.alert_config, 'count_thresholds') and config.alert_config.count_thresholds:
429
+ for category, threshold in config.alert_config.count_thresholds.items():
430
+ if category == "all" and total_detections > threshold:
431
+ alerts.append({
432
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']),
433
+ "alert_id": f"alert_{category}_{frame_key}",
434
+ "incident_category": self.CASE_TYPE,
435
+ "threshold_level": threshold,
436
+ "ascending": get_trend(self._ascending_alert_list, lookback=900, threshold=0.8),
437
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']),
438
+ getattr(config.alert_config, 'alert_value', ['JSON']))}
439
+ })
440
+ elif category in per_category_count and per_category_count[category] > threshold:
441
+ alerts.append({
442
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']),
443
+ "alert_id": f"alert_{category}_{frame_key}",
444
+ "incident_category": self.CASE_TYPE,
445
+ "threshold_level": threshold,
446
+ "ascending": get_trend(self._ascending_alert_list, lookback=900, threshold=0.8),
447
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']),
448
+ getattr(config.alert_config, 'alert_value', ['JSON']))}
449
+ })
450
+ return alerts
451
+
452
+ def _generate_incidents(self, counting_summary: Dict, zone_analysis: Dict, alerts: List, config: VehicleMonitoringConfig,
453
+ frame_number: Optional[int] = None, stream_info: Optional[Dict[str, Any]] = None) -> List[Dict]:
454
+ incidents = []
455
+ total_detections = counting_summary.get("total_count", 0)
456
+ current_timestamp = self._get_current_timestamp_str(stream_info)
457
+ camera_info = self.get_camera_info_from_stream(stream_info)
458
+
459
+ self._ascending_alert_list = self._ascending_alert_list[-900:] if len(self._ascending_alert_list) > 900 else self._ascending_alert_list
460
+
461
+ if total_detections > 0:
462
+ level = "low"
463
+ intensity = 5.0
464
+ start_timestamp = self._get_start_timestamp_str(stream_info)
465
+ if start_timestamp and self.current_incident_end_timestamp == 'N/A':
466
+ self.current_incident_end_timestamp = 'Incident still active'
467
+ elif start_timestamp and self.current_incident_end_timestamp == 'Incident still active':
468
+ if len(self._ascending_alert_list) >= 15 and sum(self._ascending_alert_list[-15:]) / 15 < 1.5:
469
+ self.current_incident_end_timestamp = current_timestamp
470
+ elif self.current_incident_end_timestamp != 'Incident still active' and self.current_incident_end_timestamp != 'N/A':
471
+ self.current_incident_end_timestamp = 'N/A'
472
+
473
+ if config.alert_config and hasattr(config.alert_config, 'count_thresholds') and config.alert_config.count_thresholds:
474
+ threshold = config.alert_config.count_thresholds.get("all", 15)
475
+ intensity = min(10.0, (total_detections / threshold) * 10)
476
+ if intensity >= 9:
477
+ level = "critical"
478
+ self._ascending_alert_list.append(3)
479
+ elif intensity >= 7:
480
+ level = "significant"
481
+ self._ascending_alert_list.append(2)
482
+ elif intensity >= 5:
483
+ level = "medium"
484
+ self._ascending_alert_list.append(1)
485
+ else:
486
+ level = "low"
487
+ self._ascending_alert_list.append(0)
488
+ else:
489
+ if total_detections > 30:
490
+ level = "critical"
491
+ intensity = 10.0
492
+ self._ascending_alert_list.append(3)
493
+ elif total_detections > 25:
494
+ level = "significant"
495
+ intensity = 9.0
496
+ self._ascending_alert_list.append(2)
497
+ elif total_detections > 15:
498
+ level = "medium"
499
+ intensity = 7.0
500
+ self._ascending_alert_list.append(1)
501
+ else:
502
+ level = "low"
503
+ intensity = min(10.0, total_detections / 3.0)
504
+ self._ascending_alert_list.append(0)
505
+
506
+ human_text_lines = [f"VEHICLE INCIDENTS DETECTED @ {current_timestamp}:"]
507
+ human_text_lines.append(f"\tSeverity Level: {(self.CASE_TYPE, level)}")
508
+ human_text = "\n".join(human_text_lines)
509
+
510
+ alert_settings = []
511
+ if config.alert_config and hasattr(config.alert_config, 'alert_type'):
512
+ alert_settings.append({
513
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']),
514
+ "incident_category": self.CASE_TYPE,
515
+ "threshold_level": config.alert_config.count_thresholds if hasattr(config.alert_config, 'count_thresholds') else {},
516
+ "ascending": True,
517
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']),
518
+ getattr(config.alert_config, 'alert_value', ['JSON']))}
519
+ })
520
+
521
+ event = self.create_incident(
522
+ incident_id=f"{self.CASE_TYPE}_{frame_number}",
523
+ incident_type=self.CASE_TYPE,
524
+ severity_level=level,
525
+ human_text=human_text,
526
+ camera_info=camera_info,
527
+ alerts=alerts,
528
+ alert_settings=alert_settings,
529
+ start_time=start_timestamp,
530
+ end_time=self.current_incident_end_timestamp,
531
+ level_settings={"low": 1, "medium": 3, "significant": 4, "critical": 7}
532
+ )
533
+ incidents.append(event)
534
+ else:
535
+ self._ascending_alert_list.append(0)
536
+ incidents.append({})
537
+ return incidents
538
+
539
+ def _generate_tracking_stats(self, counting_summary: Dict, zone_analysis: Dict, alerts: List, config: VehicleMonitoringConfig,
540
+ frame_number: Optional[int] = None, stream_info: Optional[Dict[str, Any]] = None) -> List[Dict]:
541
+ camera_info = self.get_camera_info_from_stream(stream_info)
542
+ tracking_stats = []
543
+ total_detections = counting_summary.get("total_count", 0)
544
+ total_counts_dict = counting_summary.get("total_counts", {})
545
+ per_category_count = counting_summary.get("per_category_count", {})
546
+ current_timestamp = self._get_current_timestamp_str(stream_info, precision=False)
547
+ start_timestamp = self._get_start_timestamp_str(stream_info, precision=False)
548
+ high_precision_start_timestamp = self._get_current_timestamp_str(stream_info, precision=True)
549
+ high_precision_reset_timestamp = self._get_start_timestamp_str(stream_info, precision=True)
550
+
551
+ total_counts = [{"category": cat, "count": count} for cat, count in total_counts_dict.items() if count > 0]
552
+ current_counts = [{"category": cat, "count": count} for cat, count in per_category_count.items() if count > 0 or total_detections > 0]
553
+
554
+ detections = []
555
+ for detection in counting_summary.get("detections", []):
556
+ bbox = detection.get("bounding_box", {})
557
+ category = detection.get("category", "vehicle")
558
+ if detection.get("masks"):
559
+ segmentation = detection.get("masks", [])
560
+ detection_obj = self.create_detection_object(category, bbox, segmentation=segmentation)
561
+ elif detection.get("segmentation"):
562
+ segmentation = detection.get("segmentation")
563
+ detection_obj = self.create_detection_object(category, bbox, segmentation=segmentation)
564
+ elif detection.get("mask"):
565
+ segmentation = detection.get("mask")
566
+ detection_obj = self.create_detection_object(category, bbox, segmentation=segmentation)
567
+ else:
568
+ detection_obj = self.create_detection_object(category, bbox)
569
+ detections.append(detection_obj)
570
+
571
+ alert_settings = []
572
+ if config.alert_config and hasattr(config.alert_config, 'alert_type'):
573
+ alert_settings.append({
574
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']),
575
+ "incident_category": self.CASE_TYPE,
576
+ "threshold_level": config.alert_config.count_thresholds if hasattr(config.alert_config, 'count_thresholds') else {},
577
+ "ascending": True,
578
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']),
579
+ getattr(config.alert_config, 'alert_value', ['JSON']))}
580
+ })
581
+
582
+ human_text_lines = [f"Tracking Statistics:"]
583
+ human_text_lines.append(f"CURRENT FRAME @ {current_timestamp}")
584
+ # Append zone-wise current counts if available
585
+ if zone_analysis:
586
+ human_text_lines.append("\tZones (current):")
587
+ for zone_name, zone_data in zone_analysis.items():
588
+ current_count = 0
589
+ if isinstance(zone_data, dict):
590
+ if "current_count" in zone_data:
591
+ current_count = zone_data.get("current_count", 0)
592
+ else:
593
+ counts_dict = zone_data.get("original_counts") if isinstance(zone_data.get("original_counts"), dict) else zone_data
594
+ current_count = counts_dict.get(
595
+ "total",
596
+ sum(v for v in counts_dict.values() if isinstance(v, (int, float)))
597
+ )
598
+ human_text_lines.append(f"\t{zone_name}: {int(current_count)}")
599
+ else:
600
+ for cat, count in per_category_count.items():
601
+ human_text_lines.append(f"\t{cat}: {count}")
602
+ human_text_lines.append(f"TOTAL SINCE {start_timestamp}")
603
+ # Append zone-wise total counts if available
604
+ if zone_analysis:
605
+ human_text_lines.append("\tZones (total):")
606
+ for zone_name, zone_data in zone_analysis.items():
607
+ total_count = 0
608
+ if isinstance(zone_data, dict):
609
+ # Prefer the numeric cumulative total if available
610
+ if "total_count" in zone_data and isinstance(zone_data.get("total_count"), (int, float)):
611
+ total_count = zone_data.get("total_count", 0)
612
+ # Fallback: compute from list of total_track_ids if present
613
+ elif "total_track_ids" in zone_data and isinstance(zone_data.get("total_track_ids"), list):
614
+ total_count = len(zone_data.get("total_track_ids", []))
615
+ else:
616
+ # Last resort: try to sum numeric values present
617
+ counts_dict = zone_data if isinstance(zone_data, dict) else {}
618
+ total_count = sum(v for v in counts_dict.values() if isinstance(v, (int, float)))
619
+ human_text_lines.append(f"\t{zone_name}: {int(total_count)}")
620
+ else:
621
+ for cat, count in total_counts_dict.items():
622
+ if count > 0:
623
+ human_text_lines.append(f"\t{cat}: {count}")
624
+ if alerts:
625
+ for alert in alerts:
626
+ human_text_lines.append(f"Alerts: {alert.get('settings', {})} sent @ {current_timestamp}")
627
+ else:
628
+ human_text_lines.append("Alerts: None")
629
+ human_text = "\n".join(human_text_lines)
630
+
631
+ reset_settings = [{"interval_type": "daily", "reset_time": {"value": 9, "time_unit": "hour"}}]
632
+ tracking_stat = self.create_tracking_stats(
633
+ total_counts=total_counts,
634
+ current_counts=current_counts,
635
+ detections=detections,
636
+ human_text=human_text,
637
+ camera_info=camera_info,
638
+ alerts=alerts,
639
+ alert_settings=alert_settings,
640
+ reset_settings=reset_settings,
641
+ start_time=high_precision_start_timestamp,
642
+ reset_time=high_precision_reset_timestamp
643
+ )
644
+ tracking_stats.append(tracking_stat)
645
+ return tracking_stats
646
+
647
+ def _generate_business_analytics(self, counting_summary: Dict, zone_analysis: Dict, alerts: Any, config: VehicleMonitoringConfig,
648
+ stream_info: Optional[Dict[str, Any]] = None, is_empty=False) -> List[Dict]:
649
+ if is_empty:
650
+ return []
651
+
652
+ def _generate_summary(self, summary: dict, zone_analysis: Dict, incidents: List, tracking_stats: List, business_analytics: List, alerts: List) -> List[str]:
653
+ """
654
+ Generate a human_text string for the tracking_stat, incident, business analytics and alerts.
655
+ """
656
+ lines = []
657
+ lines.append("Application Name: "+self.CASE_TYPE)
658
+ lines.append("Application Version: "+self.CASE_VERSION)
659
+ if len(incidents) > 0:
660
+ lines.append("Incidents: "+f"\n\t{incidents[0].get('human_text', 'No incidents detected')}")
661
+ if len(tracking_stats) > 0:
662
+ lines.append("Tracking Statistics: "+f"\t{tracking_stats[0].get('human_text', 'No tracking statistics detected')}")
663
+ if len(business_analytics) > 0:
664
+ lines.append("Business Analytics: "+f"\t{business_analytics[0].get('human_text', 'No business analytics detected')}")
665
+
666
+ if len(incidents) == 0 and len(tracking_stats) == 0 and len(business_analytics) == 0:
667
+ lines.append("Summary: "+"No Summary Data")
668
+
669
+ return ["\n".join(lines)]
670
+
671
+ def _get_track_ids_info(self, detections: list) -> Dict[str, Any]:
672
+ frame_track_ids = set()
673
+ for det in detections:
674
+ tid = det.get('track_id')
675
+ if tid is not None:
676
+ frame_track_ids.add(tid)
677
+ total_track_ids = set()
678
+ for s in getattr(self, '_per_category_total_track_ids', {}).values():
679
+ total_track_ids.update(s)
680
+ return {
681
+ "total_count": len(total_track_ids),
682
+ "current_frame_count": len(frame_track_ids),
683
+ "total_unique_track_ids": len(total_track_ids),
684
+ "current_frame_track_ids": list(frame_track_ids),
685
+ "last_update_time": time.time(),
686
+ "total_frames_processed": getattr(self, '_total_frame_counter', 0)
687
+ }
688
+
689
+ def _update_tracking_state(self, detections: list):
690
+ if not hasattr(self, "_per_category_total_track_ids"):
691
+ self._per_category_total_track_ids = {cat: set() for cat in self.target_categories}
692
+ self._current_frame_track_ids = {cat: set() for cat in self.target_categories}
693
+
694
+ for det in detections:
695
+ cat = det.get("category")
696
+ raw_track_id = det.get("track_id")
697
+ if cat not in self.target_categories or raw_track_id is None:
698
+ continue
699
+ bbox = det.get("bounding_box", det.get("bbox"))
700
+ canonical_id = self._merge_or_register_track(raw_track_id, bbox)
701
+ det["track_id"] = canonical_id
702
+ self._per_category_total_track_ids.setdefault(cat, set()).add(canonical_id)
703
+ self._current_frame_track_ids[cat].add(canonical_id)
704
+
705
+ def get_total_counts(self):
706
+ return {cat: len(ids) for cat, ids in getattr(self, '_per_category_total_track_ids', {}).items()}
707
+
708
+ def _format_timestamp_for_stream(self, timestamp: float) -> str:
709
+ dt = datetime.fromtimestamp(timestamp, tz=timezone.utc)
710
+ return dt.strftime('%Y:%m:%d %H:%M:%S')
711
+
712
+ def _format_timestamp_for_video(self, timestamp: float) -> str:
713
+ hours = int(timestamp // 3600)
714
+ minutes = int((timestamp % 3600) // 60)
715
+ seconds = round(float(timestamp % 60), 2)
716
+ return f"{hours:02d}:{minutes:02d}:{seconds:.1f}"
717
+
718
+ def _get_current_timestamp_str(self, stream_info: Optional[Dict[str, Any]], precision=False, frame_id: Optional[str]=None) -> str:
719
+ """Get formatted current timestamp based on stream type."""
720
+ if not stream_info:
721
+ return "00:00:00.00"
722
+
723
+ if precision:
724
+ if stream_info.get("input_settings", {}).get("start_frame", "na") != "na":
725
+ if frame_id:
726
+ start_time = int(frame_id)/stream_info.get("input_settings", {}).get("original_fps", 30)
727
+ else:
728
+ start_time = stream_info.get("input_settings", {}).get("start_frame", 30)/stream_info.get("input_settings", {}).get("original_fps", 30)
729
+ stream_time_str = self._format_timestamp_for_video(start_time)
730
+
731
+
732
+ return self._format_timestamp(stream_info.get("input_settings", {}).get("stream_time", "NA"))
733
+ else:
734
+ return datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
735
+
736
+ if stream_info.get("input_settings", {}).get("start_frame", "na") != "na":
737
+ if frame_id:
738
+ start_time = int(frame_id)/stream_info.get("input_settings", {}).get("original_fps", 30)
739
+ else:
740
+ start_time = stream_info.get("input_settings", {}).get("start_frame", 30)/stream_info.get("input_settings", {}).get("original_fps", 30)
741
+
742
+ stream_time_str = self._format_timestamp_for_video(start_time)
743
+
744
+ return self._format_timestamp(stream_info.get("input_settings", {}).get("stream_time", "NA"))
745
+ else:
746
+ stream_time_str = stream_info.get("input_settings", {}).get("stream_info", {}).get("stream_time", "")
747
+ if stream_time_str:
748
+ try:
749
+ timestamp_str = stream_time_str.replace(" UTC", "")
750
+ dt = datetime.strptime(timestamp_str, "%Y-%m-%d-%H:%M:%S.%f")
751
+ timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
752
+ return self._format_timestamp_for_stream(timestamp)
753
+ except:
754
+ return self._format_timestamp_for_stream(time.time())
755
+ else:
756
+ return self._format_timestamp_for_stream(time.time())
757
+
758
+ def _get_start_timestamp_str(self, stream_info: Optional[Dict[str, Any]], precision=False) -> str:
759
+ """Get formatted start timestamp for 'TOTAL SINCE' based on stream type."""
760
+ if not stream_info:
761
+ return "00:00:00"
762
+
763
+ if precision:
764
+ if self.start_timer is None:
765
+ self.start_timer = stream_info.get("input_settings", {}).get("stream_time", "NA")
766
+ return self._format_timestamp(self.start_timer)
767
+ elif stream_info.get("input_settings", {}).get("start_frame", "na") == 1:
768
+ self.start_timer = stream_info.get("input_settings", {}).get("stream_time", "NA")
769
+ return self._format_timestamp(self.start_timer)
770
+ else:
771
+ return self._format_timestamp(self.start_timer)
772
+
773
+ if self.start_timer is None:
774
+ self.start_timer = stream_info.get("input_settings", {}).get("stream_time", "NA")
775
+ return self._format_timestamp(self.start_timer)
776
+ elif stream_info.get("input_settings", {}).get("start_frame", "na") == 1:
777
+ self.start_timer = stream_info.get("input_settings", {}).get("stream_time", "NA")
778
+ return self._format_timestamp(self.start_timer)
779
+
780
+ else:
781
+ if self.start_timer is not None:
782
+ return self._format_timestamp(self.start_timer)
783
+
784
+ if self._tracking_start_time is None:
785
+ stream_time_str = stream_info.get("input_settings", {}).get("stream_info", {}).get("stream_time", "")
786
+ if stream_time_str:
787
+ try:
788
+ timestamp_str = stream_time_str.replace(" UTC", "")
789
+ dt = datetime.strptime(timestamp_str, "%Y-%m-%d-%H:%M:%S.%f")
790
+ self._tracking_start_time = dt.replace(tzinfo=timezone.utc).timestamp()
791
+ except:
792
+ self._tracking_start_time = time.time()
793
+ else:
794
+ self._tracking_start_time = time.time()
795
+
796
+ dt = datetime.fromtimestamp(self._tracking_start_time, tz=timezone.utc)
797
+ dt = dt.replace(minute=0, second=0, microsecond=0)
798
+ return dt.strftime('%Y:%m:%d %H:%M:%S')
799
+
800
+ def _format_timestamp(self, timestamp: Any) -> str:
801
+ """Format a timestamp so that exactly two digits follow the decimal point (milliseconds).
802
+
803
+ The input can be either:
804
+ 1. A numeric Unix timestamp (``float`` / ``int``) – it will first be converted to a
805
+ string in the format ``YYYY-MM-DD-HH:MM:SS.ffffff UTC``.
806
+ 2. A string already following the same layout.
807
+
808
+ The returned value preserves the overall format of the input but truncates or pads
809
+ the fractional seconds portion to **exactly two digits**.
810
+
811
+ Example
812
+ -------
813
+ >>> self._format_timestamp("2025-08-19-04:22:47.187574 UTC")
814
+ '2025-08-19-04:22:47.18 UTC'
815
+ """
816
+
817
+ # Convert numeric timestamps to the expected string representation first
818
+ if isinstance(timestamp, (int, float)):
819
+ timestamp = datetime.fromtimestamp(timestamp, timezone.utc).strftime(
820
+ '%Y-%m-%d-%H:%M:%S.%f UTC'
821
+ )
822
+
823
+ # Ensure we are working with a string from here on
824
+ if not isinstance(timestamp, str):
825
+ return str(timestamp)
826
+
827
+ # If there is no fractional component, simply return the original string
828
+ if '.' not in timestamp:
829
+ return timestamp
830
+
831
+ # Split out the main portion (up to the decimal point)
832
+ main_part, fractional_and_suffix = timestamp.split('.', 1)
833
+
834
+ # Separate fractional digits from the suffix (typically ' UTC')
835
+ if ' ' in fractional_and_suffix:
836
+ fractional_part, suffix = fractional_and_suffix.split(' ', 1)
837
+ suffix = ' ' + suffix # Re-attach the space removed by split
838
+ else:
839
+ fractional_part, suffix = fractional_and_suffix, ''
840
+
841
+ # Guarantee exactly two digits for the fractional part
842
+ fractional_part = (fractional_part + '00')[:2]
843
+
844
+ return f"{main_part}.{fractional_part}{suffix}"
845
+
846
+ def _count_categories(self, detections: list, config: VehicleMonitoringConfig) -> dict:
847
+ counts = {}
848
+ for det in detections:
849
+ cat = det.get('category', 'unknown')
850
+ counts[cat] = counts.get(cat, 0) + 1
851
+ return {
852
+ "total_count": sum(counts.values()),
853
+ "per_category_count": counts,
854
+ "detections": [
855
+ {
856
+ "bounding_box": det.get("bounding_box"),
857
+ "category": det.get("category"),
858
+ "confidence": det.get("confidence"),
859
+ "track_id": det.get("track_id"),
860
+ "frame_id": det.get("frame_id")
861
+ }
862
+ for det in detections
863
+ ]
864
+ }
865
+
866
+ def _extract_predictions(self, detections: list) -> List[Dict[str, Any]]:
867
+ return [
868
+ {
869
+ "category": det.get("category", "unknown"),
870
+ "confidence": det.get("confidence", 0.0),
871
+ "bounding_box": det.get("bounding_box", {})
872
+ }
873
+ for det in detections
874
+ ]
875
+
876
+ def _compute_iou(self, box1: Any, box2: Any) -> float:
877
+ def _bbox_to_list(bbox):
878
+ if bbox is None:
879
+ return []
880
+ if isinstance(bbox, list):
881
+ return bbox[:4] if len(bbox) >= 4 else []
882
+ if isinstance(bbox, dict):
883
+ if "xmin" in bbox:
884
+ return [bbox["xmin"], bbox["ymin"], bbox["xmax"], bbox["ymax"]]
885
+ if "x1" in bbox:
886
+ return [bbox["x1"], bbox["y1"], bbox["x2"], bbox["y2"]]
887
+ values = [v for v in bbox.values() if isinstance(v, (int, float))]
888
+ return values[:4] if len(values) >= 4 else []
889
+ return []
890
+
891
+ l1 = _bbox_to_list(box1)
892
+ l2 = _bbox_to_list(box2)
893
+ if len(l1) < 4 or len(l2) < 4:
894
+ return 0.0
895
+ x1_min, y1_min, x1_max, y1_max = l1
896
+ x2_min, y2_min, x2_max, y2_max = l2
897
+ x1_min, x1_max = min(x1_min, x1_max), max(x1_min, x1_max)
898
+ y1_min, y1_max = min(y1_min, y1_max), max(y1_min, y1_max)
899
+ x2_min, x2_max = min(x2_min, x2_max), max(x2_min, x2_max)
900
+ y2_min, y2_max = min(y2_min, y2_max), max(y2_min, y2_max)
901
+ inter_x_min = max(x1_min, x2_min)
902
+ inter_y_min = max(y1_min, y2_min)
903
+ inter_x_max = min(x1_max, x2_max)
904
+ inter_y_max = min(y1_max, y2_max)
905
+ inter_w = max(0.0, inter_x_max - inter_x_min)
906
+ inter_h = max(0.0, inter_y_max - inter_y_min)
907
+ inter_area = inter_w * inter_h
908
+ area1 = (x1_max - x1_min) * (y1_max - y1_min)
909
+ area2 = (x2_max - x2_min) * (y2_max - y2_min)
910
+ union_area = area1 + area2 - inter_area
911
+ return (inter_area / union_area) if union_area > 0 else 0.0
912
+
913
+ def _merge_or_register_track(self, raw_id: Any, bbox: Any) -> Any:
914
+ if raw_id is None or bbox is None:
915
+ return raw_id
916
+ now = time.time()
917
+ if raw_id in self._track_aliases:
918
+ canonical_id = self._track_aliases[raw_id]
919
+ track_info = self._canonical_tracks.get(canonical_id)
920
+ if track_info is not None:
921
+ track_info["last_bbox"] = bbox
922
+ track_info["last_update"] = now
923
+ track_info["raw_ids"].add(raw_id)
924
+ return canonical_id
925
+ for canonical_id, info in self._canonical_tracks.items():
926
+ if now - info["last_update"] > self._track_merge_time_window:
927
+ continue
928
+ iou = self._compute_iou(bbox, info["last_bbox"])
929
+ if iou >= self._track_merge_iou_threshold:
930
+ self._track_aliases[raw_id] = canonical_id
931
+ info["last_bbox"] = bbox
932
+ info["last_update"] = now
933
+ info["raw_ids"].add(raw_id)
934
+ return canonical_id
935
+ canonical_id = raw_id
936
+ self._track_aliases[raw_id] = canonical_id
937
+ self._canonical_tracks[canonical_id] = {
938
+ "last_bbox": bbox,
939
+ "last_update": now,
940
+ "raw_ids": {raw_id},
941
+ }
942
+ return canonical_id
943
+
944
+ def _get_tracking_start_time(self) -> str:
945
+ if self._tracking_start_time is None:
946
+ return "N/A"
947
+ return self._format_timestamp(self._tracking_start_time)
948
+
949
+ def _set_tracking_start_time(self) -> None:
950
+ self._tracking_start_time = time.time()