matrice-analytics 0.1.60__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. matrice_analytics/__init__.py +28 -0
  2. matrice_analytics/boundary_drawing_internal/README.md +305 -0
  3. matrice_analytics/boundary_drawing_internal/__init__.py +45 -0
  4. matrice_analytics/boundary_drawing_internal/boundary_drawing_internal.py +1207 -0
  5. matrice_analytics/boundary_drawing_internal/boundary_drawing_tool.py +429 -0
  6. matrice_analytics/boundary_drawing_internal/boundary_tool_template.html +1036 -0
  7. matrice_analytics/boundary_drawing_internal/data/.gitignore +12 -0
  8. matrice_analytics/boundary_drawing_internal/example_usage.py +206 -0
  9. matrice_analytics/boundary_drawing_internal/usage/README.md +110 -0
  10. matrice_analytics/boundary_drawing_internal/usage/boundary_drawer_launcher.py +102 -0
  11. matrice_analytics/boundary_drawing_internal/usage/simple_boundary_launcher.py +107 -0
  12. matrice_analytics/post_processing/README.md +455 -0
  13. matrice_analytics/post_processing/__init__.py +732 -0
  14. matrice_analytics/post_processing/advanced_tracker/README.md +650 -0
  15. matrice_analytics/post_processing/advanced_tracker/__init__.py +17 -0
  16. matrice_analytics/post_processing/advanced_tracker/base.py +99 -0
  17. matrice_analytics/post_processing/advanced_tracker/config.py +77 -0
  18. matrice_analytics/post_processing/advanced_tracker/kalman_filter.py +370 -0
  19. matrice_analytics/post_processing/advanced_tracker/matching.py +195 -0
  20. matrice_analytics/post_processing/advanced_tracker/strack.py +230 -0
  21. matrice_analytics/post_processing/advanced_tracker/tracker.py +367 -0
  22. matrice_analytics/post_processing/config.py +146 -0
  23. matrice_analytics/post_processing/core/__init__.py +63 -0
  24. matrice_analytics/post_processing/core/base.py +704 -0
  25. matrice_analytics/post_processing/core/config.py +3291 -0
  26. matrice_analytics/post_processing/core/config_utils.py +925 -0
  27. matrice_analytics/post_processing/face_reg/__init__.py +43 -0
  28. matrice_analytics/post_processing/face_reg/compare_similarity.py +556 -0
  29. matrice_analytics/post_processing/face_reg/embedding_manager.py +950 -0
  30. matrice_analytics/post_processing/face_reg/face_recognition.py +2234 -0
  31. matrice_analytics/post_processing/face_reg/face_recognition_client.py +606 -0
  32. matrice_analytics/post_processing/face_reg/people_activity_logging.py +321 -0
  33. matrice_analytics/post_processing/ocr/__init__.py +0 -0
  34. matrice_analytics/post_processing/ocr/easyocr_extractor.py +250 -0
  35. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/__init__.py +9 -0
  36. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/cli/__init__.py +4 -0
  37. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/cli/cli.py +33 -0
  38. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/cli/dataset_stats.py +139 -0
  39. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/cli/export.py +398 -0
  40. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/cli/train.py +447 -0
  41. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/cli/utils.py +129 -0
  42. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/cli/valid.py +93 -0
  43. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/cli/validate_dataset.py +240 -0
  44. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/cli/visualize_augmentation.py +176 -0
  45. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/cli/visualize_predictions.py +96 -0
  46. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/core/__init__.py +3 -0
  47. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/core/process.py +246 -0
  48. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/core/types.py +60 -0
  49. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/core/utils.py +87 -0
  50. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/inference/__init__.py +3 -0
  51. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/inference/config.py +82 -0
  52. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/inference/hub.py +141 -0
  53. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/inference/plate_recognizer.py +323 -0
  54. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/py.typed +0 -0
  55. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/train/__init__.py +0 -0
  56. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/train/data/__init__.py +0 -0
  57. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/train/data/augmentation.py +101 -0
  58. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/train/data/dataset.py +97 -0
  59. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/train/model/__init__.py +0 -0
  60. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/train/model/config.py +114 -0
  61. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/train/model/layers.py +553 -0
  62. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/train/model/loss.py +55 -0
  63. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/train/model/metric.py +86 -0
  64. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/train/model/model_builders.py +95 -0
  65. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/train/model/model_schema.py +395 -0
  66. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/train/utilities/__init__.py +0 -0
  67. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/train/utilities/backend_utils.py +38 -0
  68. matrice_analytics/post_processing/ocr/fast_plate_ocr_py38/train/utilities/utils.py +214 -0
  69. matrice_analytics/post_processing/ocr/postprocessing.py +270 -0
  70. matrice_analytics/post_processing/ocr/preprocessing.py +52 -0
  71. matrice_analytics/post_processing/post_processor.py +1175 -0
  72. matrice_analytics/post_processing/test_cases/__init__.py +1 -0
  73. matrice_analytics/post_processing/test_cases/run_tests.py +143 -0
  74. matrice_analytics/post_processing/test_cases/test_advanced_customer_service.py +841 -0
  75. matrice_analytics/post_processing/test_cases/test_basic_counting_tracking.py +523 -0
  76. matrice_analytics/post_processing/test_cases/test_comprehensive.py +531 -0
  77. matrice_analytics/post_processing/test_cases/test_config.py +852 -0
  78. matrice_analytics/post_processing/test_cases/test_customer_service.py +585 -0
  79. matrice_analytics/post_processing/test_cases/test_data_generators.py +583 -0
  80. matrice_analytics/post_processing/test_cases/test_people_counting.py +510 -0
  81. matrice_analytics/post_processing/test_cases/test_processor.py +524 -0
  82. matrice_analytics/post_processing/test_cases/test_usecases.py +165 -0
  83. matrice_analytics/post_processing/test_cases/test_utilities.py +356 -0
  84. matrice_analytics/post_processing/test_cases/test_utils.py +743 -0
  85. matrice_analytics/post_processing/usecases/Histopathological_Cancer_Detection_img.py +604 -0
  86. matrice_analytics/post_processing/usecases/__init__.py +267 -0
  87. matrice_analytics/post_processing/usecases/abandoned_object_detection.py +797 -0
  88. matrice_analytics/post_processing/usecases/advanced_customer_service.py +1601 -0
  89. matrice_analytics/post_processing/usecases/age_detection.py +842 -0
  90. matrice_analytics/post_processing/usecases/age_gender_detection.py +1085 -0
  91. matrice_analytics/post_processing/usecases/anti_spoofing_detection.py +656 -0
  92. matrice_analytics/post_processing/usecases/assembly_line_detection.py +841 -0
  93. matrice_analytics/post_processing/usecases/banana_defect_detection.py +624 -0
  94. matrice_analytics/post_processing/usecases/basic_counting_tracking.py +667 -0
  95. matrice_analytics/post_processing/usecases/blood_cancer_detection_img.py +881 -0
  96. matrice_analytics/post_processing/usecases/car_damage_detection.py +834 -0
  97. matrice_analytics/post_processing/usecases/car_part_segmentation.py +946 -0
  98. matrice_analytics/post_processing/usecases/car_service.py +1601 -0
  99. matrice_analytics/post_processing/usecases/cardiomegaly_classification.py +864 -0
  100. matrice_analytics/post_processing/usecases/cell_microscopy_segmentation.py +897 -0
  101. matrice_analytics/post_processing/usecases/chicken_pose_detection.py +648 -0
  102. matrice_analytics/post_processing/usecases/child_monitoring.py +814 -0
  103. matrice_analytics/post_processing/usecases/color/clip.py +660 -0
  104. matrice_analytics/post_processing/usecases/color/clip_processor/merges.txt +48895 -0
  105. matrice_analytics/post_processing/usecases/color/clip_processor/preprocessor_config.json +28 -0
  106. matrice_analytics/post_processing/usecases/color/clip_processor/special_tokens_map.json +30 -0
  107. matrice_analytics/post_processing/usecases/color/clip_processor/tokenizer.json +245079 -0
  108. matrice_analytics/post_processing/usecases/color/clip_processor/tokenizer_config.json +32 -0
  109. matrice_analytics/post_processing/usecases/color/clip_processor/vocab.json +1 -0
  110. matrice_analytics/post_processing/usecases/color/color_map_utils.py +70 -0
  111. matrice_analytics/post_processing/usecases/color/color_mapper.py +468 -0
  112. matrice_analytics/post_processing/usecases/color_detection.py +1936 -0
  113. matrice_analytics/post_processing/usecases/color_map_utils.py +70 -0
  114. matrice_analytics/post_processing/usecases/concrete_crack_detection.py +827 -0
  115. matrice_analytics/post_processing/usecases/crop_weed_detection.py +781 -0
  116. matrice_analytics/post_processing/usecases/customer_service.py +1008 -0
  117. matrice_analytics/post_processing/usecases/defect_detection_products.py +936 -0
  118. matrice_analytics/post_processing/usecases/distracted_driver_detection.py +822 -0
  119. matrice_analytics/post_processing/usecases/drone_traffic_monitoring.py +585 -0
  120. matrice_analytics/post_processing/usecases/drowsy_driver_detection.py +829 -0
  121. matrice_analytics/post_processing/usecases/dwell_detection.py +829 -0
  122. matrice_analytics/post_processing/usecases/emergency_vehicle_detection.py +827 -0
  123. matrice_analytics/post_processing/usecases/face_emotion.py +813 -0
  124. matrice_analytics/post_processing/usecases/face_recognition.py +827 -0
  125. matrice_analytics/post_processing/usecases/fashion_detection.py +835 -0
  126. matrice_analytics/post_processing/usecases/field_mapping.py +902 -0
  127. matrice_analytics/post_processing/usecases/fire_detection.py +1146 -0
  128. matrice_analytics/post_processing/usecases/flare_analysis.py +836 -0
  129. matrice_analytics/post_processing/usecases/flower_segmentation.py +1006 -0
  130. matrice_analytics/post_processing/usecases/gas_leak_detection.py +837 -0
  131. matrice_analytics/post_processing/usecases/gender_detection.py +832 -0
  132. matrice_analytics/post_processing/usecases/human_activity_recognition.py +871 -0
  133. matrice_analytics/post_processing/usecases/intrusion_detection.py +1672 -0
  134. matrice_analytics/post_processing/usecases/leaf.py +821 -0
  135. matrice_analytics/post_processing/usecases/leaf_disease.py +840 -0
  136. matrice_analytics/post_processing/usecases/leak_detection.py +837 -0
  137. matrice_analytics/post_processing/usecases/license_plate_detection.py +1188 -0
  138. matrice_analytics/post_processing/usecases/license_plate_monitoring.py +1781 -0
  139. matrice_analytics/post_processing/usecases/litter_monitoring.py +717 -0
  140. matrice_analytics/post_processing/usecases/mask_detection.py +869 -0
  141. matrice_analytics/post_processing/usecases/natural_disaster.py +907 -0
  142. matrice_analytics/post_processing/usecases/parking.py +787 -0
  143. matrice_analytics/post_processing/usecases/parking_space_detection.py +822 -0
  144. matrice_analytics/post_processing/usecases/pcb_defect_detection.py +888 -0
  145. matrice_analytics/post_processing/usecases/pedestrian_detection.py +808 -0
  146. matrice_analytics/post_processing/usecases/people_counting.py +706 -0
  147. matrice_analytics/post_processing/usecases/people_counting_bckp.py +1683 -0
  148. matrice_analytics/post_processing/usecases/people_tracking.py +1842 -0
  149. matrice_analytics/post_processing/usecases/pipeline_detection.py +605 -0
  150. matrice_analytics/post_processing/usecases/plaque_segmentation_img.py +874 -0
  151. matrice_analytics/post_processing/usecases/pothole_segmentation.py +915 -0
  152. matrice_analytics/post_processing/usecases/ppe_compliance.py +645 -0
  153. matrice_analytics/post_processing/usecases/price_tag_detection.py +822 -0
  154. matrice_analytics/post_processing/usecases/proximity_detection.py +1901 -0
  155. matrice_analytics/post_processing/usecases/road_lane_detection.py +623 -0
  156. matrice_analytics/post_processing/usecases/road_traffic_density.py +832 -0
  157. matrice_analytics/post_processing/usecases/road_view_segmentation.py +915 -0
  158. matrice_analytics/post_processing/usecases/shelf_inventory_detection.py +583 -0
  159. matrice_analytics/post_processing/usecases/shoplifting_detection.py +822 -0
  160. matrice_analytics/post_processing/usecases/shopping_cart_analysis.py +899 -0
  161. matrice_analytics/post_processing/usecases/skin_cancer_classification_img.py +864 -0
  162. matrice_analytics/post_processing/usecases/smoker_detection.py +833 -0
  163. matrice_analytics/post_processing/usecases/solar_panel.py +810 -0
  164. matrice_analytics/post_processing/usecases/suspicious_activity_detection.py +1030 -0
  165. matrice_analytics/post_processing/usecases/template_usecase.py +380 -0
  166. matrice_analytics/post_processing/usecases/theft_detection.py +648 -0
  167. matrice_analytics/post_processing/usecases/traffic_sign_monitoring.py +724 -0
  168. matrice_analytics/post_processing/usecases/underground_pipeline_defect_detection.py +775 -0
  169. matrice_analytics/post_processing/usecases/underwater_pollution_detection.py +842 -0
  170. matrice_analytics/post_processing/usecases/vehicle_monitoring.py +1029 -0
  171. matrice_analytics/post_processing/usecases/warehouse_object_segmentation.py +899 -0
  172. matrice_analytics/post_processing/usecases/waterbody_segmentation.py +923 -0
  173. matrice_analytics/post_processing/usecases/weapon_detection.py +771 -0
  174. matrice_analytics/post_processing/usecases/weld_defect_detection.py +615 -0
  175. matrice_analytics/post_processing/usecases/wildlife_monitoring.py +898 -0
  176. matrice_analytics/post_processing/usecases/windmill_maintenance.py +834 -0
  177. matrice_analytics/post_processing/usecases/wound_segmentation.py +856 -0
  178. matrice_analytics/post_processing/utils/__init__.py +150 -0
  179. matrice_analytics/post_processing/utils/advanced_counting_utils.py +400 -0
  180. matrice_analytics/post_processing/utils/advanced_helper_utils.py +317 -0
  181. matrice_analytics/post_processing/utils/advanced_tracking_utils.py +461 -0
  182. matrice_analytics/post_processing/utils/alerting_utils.py +213 -0
  183. matrice_analytics/post_processing/utils/category_mapping_utils.py +94 -0
  184. matrice_analytics/post_processing/utils/color_utils.py +592 -0
  185. matrice_analytics/post_processing/utils/counting_utils.py +182 -0
  186. matrice_analytics/post_processing/utils/filter_utils.py +261 -0
  187. matrice_analytics/post_processing/utils/format_utils.py +293 -0
  188. matrice_analytics/post_processing/utils/geometry_utils.py +300 -0
  189. matrice_analytics/post_processing/utils/smoothing_utils.py +358 -0
  190. matrice_analytics/post_processing/utils/tracking_utils.py +234 -0
  191. matrice_analytics/py.typed +0 -0
  192. matrice_analytics-0.1.60.dist-info/METADATA +481 -0
  193. matrice_analytics-0.1.60.dist-info/RECORD +196 -0
  194. matrice_analytics-0.1.60.dist-info/WHEEL +5 -0
  195. matrice_analytics-0.1.60.dist-info/licenses/LICENSE.txt +21 -0
  196. matrice_analytics-0.1.60.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1029 @@
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, 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._per_category_total_track_ids = {cat: set() for cat in self.target_categories}
114
+ self._current_frame_track_ids = {cat: set() for cat in self.target_categories}
115
+ self._tracked_in_zones = set() # New: Unique track IDs that have entered any zone
116
+ self._total_count = 0 # Cached total count
117
+ self._last_update_time = time.time() # Track when last updated
118
+ self._total_count_list = []
119
+
120
+ # Zone-based tracking storage
121
+ self._zone_current_track_ids = {} # zone_name -> set of current track IDs in zone
122
+ self._zone_total_track_ids = {} # zone_name -> set of all track IDs that have been in zone
123
+ self._zone_current_counts = {} # zone_name -> current count in zone
124
+ self._zone_total_counts = {} # zone_name -> total count that have been in zone
125
+
126
+ def process(self, data: Any, config: ConfigProtocol, context: Optional[ProcessingContext] = None,
127
+ stream_info: Optional[Dict[str, Any]] = None) -> ProcessingResult:
128
+ processing_start = time.time()
129
+ if not isinstance(config, VehicleMonitoringConfig):
130
+ return self.create_error_result("Invalid config type", usecase=self.name, category=self.category, context=context)
131
+ if context is None:
132
+ context = ProcessingContext()
133
+
134
+ # Determine if zones are configured
135
+ has_zones = bool(config.zone_config and config.zone_config.get('zones'))
136
+
137
+ # Normalize typical YOLO outputs (COCO pretrained) to internal schema
138
+ data = self._normalize_yolo_results(data, getattr(config, 'index_to_category', None))
139
+
140
+ input_format = match_results_structure(data)
141
+ context.input_format = input_format
142
+ context.confidence_threshold = config.confidence_threshold
143
+ config.confidence_threshold = 0.25
144
+
145
+ if config.confidence_threshold is not None:
146
+ processed_data = filter_by_confidence(data, config.confidence_threshold)
147
+ self.logger.debug(f"Applied confidence filtering with threshold {config.confidence_threshold}")
148
+ else:
149
+ processed_data = data
150
+ self.logger.debug("Did not apply confidence filtering since no threshold provided")
151
+
152
+ if config.index_to_category:
153
+ processed_data = apply_category_mapping(processed_data, config.index_to_category)
154
+ self.logger.debug("Applied category mapping")
155
+
156
+ processed_data = [d for d in processed_data if d.get('category') in self.target_categories]
157
+ if config.target_categories:
158
+ processed_data = [d for d in processed_data if d.get('category') in self.target_categories]
159
+ self.logger.debug("Applied category filtering")
160
+
161
+
162
+ if config.enable_smoothing:
163
+ if self.smoothing_tracker is None:
164
+ smoothing_config = BBoxSmoothingConfig(
165
+ smoothing_algorithm=config.smoothing_algorithm,
166
+ window_size=config.smoothing_window_size,
167
+ cooldown_frames=config.smoothing_cooldown_frames,
168
+ confidence_threshold=config.confidence_threshold,
169
+ confidence_range_factor=config.smoothing_confidence_range_factor,
170
+ enable_smoothing=True
171
+ )
172
+ self.smoothing_tracker = BBoxSmoothingTracker(smoothing_config)
173
+ processed_data = bbox_smoothing(processed_data, self.smoothing_tracker.config, self.smoothing_tracker)
174
+
175
+ try:
176
+ from ..advanced_tracker import AdvancedTracker
177
+ from ..advanced_tracker.config import TrackerConfig
178
+ if self.tracker is None:
179
+ tracker_config = TrackerConfig()
180
+ self.tracker = AdvancedTracker(tracker_config)
181
+ self.logger.info("Initialized AdvancedTracker for Vehicle Monitoring")
182
+ processed_data = self.tracker.update(processed_data)
183
+ except Exception as e:
184
+ self.logger.warning(f"AdvancedTracker failed: {e}")
185
+
186
+ self._update_tracking_state(processed_data, has_zones=has_zones)
187
+ self._total_frame_counter += 1
188
+
189
+ frame_number = None
190
+ if stream_info:
191
+ input_settings = stream_info.get("input_settings", {})
192
+ start_frame = input_settings.get("start_frame")
193
+ end_frame = input_settings.get("end_frame")
194
+ if start_frame is not None and end_frame is not None and start_frame == end_frame:
195
+ frame_number = start_frame
196
+
197
+ general_counting_summary = calculate_counting_summary(data)
198
+ counting_summary = self._count_categories(processed_data, config)
199
+ total_counts = self.get_total_counts()
200
+ counting_summary['total_counts'] = total_counts
201
+ counting_summary['categories'] = {}
202
+ for detection in processed_data:
203
+ category = detection.get("category", "unknown")
204
+ counting_summary["categories"][category] = counting_summary["categories"].get(category, 0) + 1
205
+
206
+ zone_analysis = {}
207
+ if has_zones:
208
+ # Convert single frame to format expected by count_objects_in_zones
209
+ frame_data = processed_data #[frame_detections]
210
+ zone_analysis = count_objects_in_zones(frame_data, config.zone_config['zones'], stream_info)
211
+
212
+ if zone_analysis:
213
+ enhanced_zone_analysis = self._update_zone_tracking(zone_analysis, processed_data, config)
214
+ # Merge enhanced zone analysis with original zone analysis
215
+ for zone_name, enhanced_data in enhanced_zone_analysis.items():
216
+ zone_analysis[zone_name] = enhanced_data
217
+
218
+ # Adjust counting_summary for zones (current counts based on union across zones)
219
+ per_category_count = {cat: len(self._current_frame_track_ids.get(cat, set())) for cat in self.target_categories}
220
+ counting_summary['per_category_count'] = {k: v for k, v in per_category_count.items() if v > 0}
221
+ counting_summary['total_count'] = sum(per_category_count.values())
222
+
223
+ alerts = self._check_alerts(counting_summary,zone_analysis, frame_number, config)
224
+ predictions = self._extract_predictions(processed_data)
225
+
226
+ incidents_list = self._generate_incidents(counting_summary,zone_analysis, alerts, config, frame_number, stream_info)
227
+ incidents_list = []
228
+ tracking_stats_list = self._generate_tracking_stats(counting_summary,zone_analysis, alerts, config, frame_number, stream_info)
229
+
230
+ business_analytics_list = self._generate_business_analytics(counting_summary,zone_analysis, alerts, config, stream_info, is_empty=True)
231
+ summary_list = self._generate_summary(counting_summary,zone_analysis, incidents_list, tracking_stats_list, business_analytics_list, alerts)
232
+
233
+ incidents = incidents_list[0] if incidents_list else {}
234
+ tracking_stats = tracking_stats_list[0] if tracking_stats_list else {}
235
+ business_analytics = business_analytics_list[0] if business_analytics_list else {}
236
+ summary = summary_list[0] if summary_list else {}
237
+ agg_summary = {str(frame_number): {
238
+ "incidents": incidents,
239
+ "tracking_stats": tracking_stats,
240
+ "business_analytics": business_analytics,
241
+ "alerts": alerts,
242
+ "zone_analysis": zone_analysis,
243
+ "human_text": summary}
244
+ }
245
+
246
+ context.mark_completed()
247
+ result = self.create_result(
248
+ data={"agg_summary": agg_summary},
249
+ usecase=self.name,
250
+ category=self.category,
251
+ context=context
252
+ )
253
+ proc_time = time.time() - processing_start
254
+ processing_latency_ms = proc_time * 1000.0
255
+ processing_fps = (1.0 / proc_time) if proc_time > 0 else None
256
+ # Log the performance metrics using the module-level logger
257
+ print("latency in ms:",processing_latency_ms,"| Throughput fps:",processing_fps,"| Frame_Number:",self._total_frame_counter)
258
+ return result
259
+
260
+ def _update_zone_tracking(self, zone_analysis: Dict[str, Dict[str, int]], detections: List[Dict], config: VehicleMonitoringConfig) -> Dict[str, Dict[str, Any]]:
261
+ """
262
+ Update zone tracking with current frame data.
263
+
264
+ Args:
265
+ zone_analysis: Current zone analysis results
266
+ detections: List of detections with track IDs
267
+
268
+ Returns:
269
+ Enhanced zone analysis with tracking information
270
+ """
271
+ if not zone_analysis or not config.zone_config or not config.zone_config['zones']:
272
+ return {}
273
+
274
+ enhanced_zone_analysis = {}
275
+ zones = config.zone_config['zones']
276
+
277
+ # Get track to category mapping
278
+ track_to_cat = {det.get('track_id'): det.get('category') for det in detections if det.get('track_id') is not None}
279
+
280
+ # Get current frame track IDs in each zone
281
+ current_frame_zone_tracks = {}
282
+
283
+ # Initialize zone tracking for all zones
284
+ for zone_name in zones.keys():
285
+ current_frame_zone_tracks[zone_name] = set()
286
+ if zone_name not in self._zone_current_track_ids:
287
+ self._zone_current_track_ids[zone_name] = set()
288
+ if zone_name not in self._zone_total_track_ids:
289
+ self._zone_total_track_ids[zone_name] = set()
290
+
291
+ # Check each detection against each zone
292
+ for detection in detections:
293
+ track_id = detection.get("track_id")
294
+ if track_id is None:
295
+ continue
296
+
297
+ # Get detection bbox
298
+ bbox = detection.get("bounding_box", detection.get("bbox"))
299
+ if not bbox:
300
+ continue
301
+
302
+ # Get detection center point
303
+ center_point = get_bbox_bottom25_center(bbox) #get_bbox_center(bbox)
304
+
305
+ # Flag to check if this track is in any zone this frame
306
+ in_any_zone = False
307
+
308
+ # Check which zone this detection is in using actual zone polygons
309
+ for zone_name, zone_polygon in zones.items():
310
+ # Convert polygon points to tuples for point_in_polygon function
311
+ # zone_polygon format: [[x1, y1], [x2, y2], [x3, y3], ...]
312
+ polygon_points = [(point[0], point[1]) for point in zone_polygon]
313
+
314
+ # Check if detection center is inside the zone polygon using ray casting algorithm
315
+ if point_in_polygon(center_point, polygon_points):
316
+ current_frame_zone_tracks[zone_name].add(track_id)
317
+ in_any_zone = True
318
+ if track_id not in self._total_count_list:
319
+ self._total_count_list.append(track_id)
320
+
321
+ # If in any zone, update global current and total (cumulative only if new)
322
+ if in_any_zone:
323
+ cat = track_to_cat.get(track_id)
324
+ if cat:
325
+ # Update current frame global (union across zones)
326
+ self._current_frame_track_ids.setdefault(cat, set()).add(track_id)
327
+
328
+ # Update global cumulative if first time in any zone
329
+ if track_id not in self._tracked_in_zones:
330
+ self._tracked_in_zones.add(track_id)
331
+ self._per_category_total_track_ids.setdefault(cat, set()).add(track_id)
332
+
333
+ # Update zone tracking for each zone
334
+ for zone_name, zone_counts in zone_analysis.items():
335
+ # Get current frame tracks for this zone
336
+ current_tracks = current_frame_zone_tracks.get(zone_name, set())
337
+
338
+ # Update current zone tracks
339
+ self._zone_current_track_ids[zone_name] = current_tracks
340
+
341
+ # Update total zone tracks (accumulate all track IDs that have been in zone)
342
+ self._zone_total_track_ids[zone_name].update(current_tracks)
343
+
344
+ # Update counts
345
+ self._zone_current_counts[zone_name] = len(current_tracks)
346
+ self._zone_total_counts[zone_name] = len(self._zone_total_track_ids[zone_name])
347
+
348
+ # Create enhanced zone analysis
349
+ enhanced_zone_analysis[zone_name] = {
350
+ "current_count": self._zone_current_counts[zone_name],
351
+ "total_count": self._zone_total_counts[zone_name],
352
+ "current_track_ids": list(current_tracks),
353
+ "total_track_ids": list(self._zone_total_track_ids[zone_name]),
354
+ "original_counts": zone_counts # Preserve original zone counts
355
+ }
356
+
357
+ return enhanced_zone_analysis
358
+
359
+ def _normalize_yolo_results(self, data: Any, index_to_category: Optional[Dict[int, str]] = None) -> Any:
360
+ """
361
+ Normalize YOLO-style outputs to internal detection schema:
362
+ - category/category_id: prefer string label using COCO mapping if available
363
+ - confidence: map from 'conf'/'score' to 'confidence'
364
+ - bounding_box: ensure dict with keys (x1,y1,x2,y2) or (xmin,ymin,xmax,ymax)
365
+ - supports list of detections and frame_id -> detections dict
366
+ """
367
+ def to_bbox_dict(d: Dict[str, Any]) -> Dict[str, Any]:
368
+ if "bounding_box" in d and isinstance(d["bounding_box"], dict):
369
+ return d["bounding_box"]
370
+ if "bbox" in d:
371
+ bbox = d["bbox"]
372
+ if isinstance(bbox, dict):
373
+ return bbox
374
+ if isinstance(bbox, (list, tuple)) and len(bbox) >= 4:
375
+ x1, y1, x2, y2 = bbox[0], bbox[1], bbox[2], bbox[3]
376
+ return {"x1": x1, "y1": y1, "x2": x2, "y2": y2}
377
+ if "xyxy" in d and isinstance(d["xyxy"], (list, tuple)) and len(d["xyxy"]) >= 4:
378
+ x1, y1, x2, y2 = d["xyxy"][0], d["xyxy"][1], d["xyxy"][2], d["xyxy"][3]
379
+ return {"x1": x1, "y1": y1, "x2": x2, "y2": y2}
380
+ if "xywh" in d and isinstance(d["xywh"], (list, tuple)) and len(d["xywh"]) >= 4:
381
+ cx, cy, w, h = d["xywh"][0], d["xywh"][1], d["xywh"][2], d["xywh"][3]
382
+ x1, y1, x2, y2 = cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2
383
+ return {"x1": x1, "y1": y1, "x2": x2, "y2": y2}
384
+ return {}
385
+
386
+ def resolve_category(d: Dict[str, Any]) -> Tuple[str, Optional[int]]:
387
+ raw_cls = d.get("category", d.get("category_id", d.get("class", d.get("cls"))))
388
+ label_name = d.get("name")
389
+ if isinstance(raw_cls, int):
390
+ if index_to_category and raw_cls in index_to_category:
391
+ return index_to_category[raw_cls], raw_cls
392
+ return str(raw_cls), raw_cls
393
+ if isinstance(raw_cls, str):
394
+ # Some YOLO exports provide string labels directly
395
+ return raw_cls, None
396
+ if label_name:
397
+ return str(label_name), None
398
+ return "unknown", None
399
+
400
+ def normalize_det(det: Dict[str, Any]) -> Dict[str, Any]:
401
+ category_name, category_id = resolve_category(det)
402
+ confidence = det.get("confidence", det.get("conf", det.get("score", 0.0)))
403
+ bbox = to_bbox_dict(det)
404
+ normalized = {
405
+ "category": category_name,
406
+ "confidence": confidence,
407
+ "bounding_box": bbox,
408
+ }
409
+ if category_id is not None:
410
+ normalized["category_id"] = category_id
411
+ # Preserve optional fields
412
+ for key in ("track_id", "frame_id", "masks", "segmentation"):
413
+ if key in det:
414
+ normalized[key] = det[key]
415
+ return normalized
416
+
417
+ if isinstance(data, list):
418
+ return [normalize_det(d) if isinstance(d, dict) else d for d in data]
419
+ if isinstance(data, dict):
420
+ # Detect tracking style dict: frame_id -> list of detections
421
+ normalized_dict: Dict[str, Any] = {}
422
+ for k, v in data.items():
423
+ if isinstance(v, list):
424
+ normalized_dict[k] = [normalize_det(d) if isinstance(d, dict) else d for d in v]
425
+ elif isinstance(v, dict):
426
+ normalized_dict[k] = normalize_det(v)
427
+ else:
428
+ normalized_dict[k] = v
429
+ return normalized_dict
430
+ return data
431
+
432
+ def _check_alerts(self, summary: dict, zone_analysis: Dict, frame_number: Any, config: VehicleMonitoringConfig) -> List[Dict]:
433
+ def get_trend(data, lookback=900, threshold=0.6):
434
+ window = data[-lookback:] if len(data) >= lookback else data
435
+ if len(window) < 2:
436
+ return True
437
+ increasing = 0
438
+ total = 0
439
+ for i in range(1, len(window)):
440
+ if window[i] >= window[i - 1]:
441
+ increasing += 1
442
+ total += 1
443
+ ratio = increasing / total
444
+ return ratio >= threshold
445
+
446
+ frame_key = str(frame_number) if frame_number is not None else "current_frame"
447
+ alerts = []
448
+ total_detections = summary.get("total_count", 0)
449
+ total_counts_dict = summary.get("total_counts", {})
450
+ per_category_count = summary.get("per_category_count", {})
451
+
452
+ if not config.alert_config:
453
+ return alerts
454
+
455
+ if hasattr(config.alert_config, 'count_thresholds') and config.alert_config.count_thresholds:
456
+ for category, threshold in config.alert_config.count_thresholds.items():
457
+ if category == "all" and total_detections > threshold:
458
+ alerts.append({
459
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']),
460
+ "alert_id": f"alert_{category}_{frame_key}",
461
+ "incident_category": self.CASE_TYPE,
462
+ "threshold_level": threshold,
463
+ "ascending": get_trend(self._ascending_alert_list, lookback=900, threshold=0.8),
464
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']),
465
+ getattr(config.alert_config, 'alert_value', ['JSON']))}
466
+ })
467
+ elif category in per_category_count and per_category_count[category] > threshold:
468
+ alerts.append({
469
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']),
470
+ "alert_id": f"alert_{category}_{frame_key}",
471
+ "incident_category": self.CASE_TYPE,
472
+ "threshold_level": threshold,
473
+ "ascending": get_trend(self._ascending_alert_list, lookback=900, threshold=0.8),
474
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']),
475
+ getattr(config.alert_config, 'alert_value', ['JSON']))}
476
+ })
477
+ return alerts
478
+
479
+ def _generate_incidents(self, counting_summary: Dict, zone_analysis: Dict, alerts: List, config: VehicleMonitoringConfig,
480
+ frame_number: Optional[int] = None, stream_info: Optional[Dict[str, Any]] = None) -> List[Dict]:
481
+ incidents = []
482
+ total_detections = counting_summary.get("total_count", 0)
483
+ current_timestamp = self._get_current_timestamp_str(stream_info)
484
+ camera_info = self.get_camera_info_from_stream(stream_info)
485
+
486
+ self._ascending_alert_list = self._ascending_alert_list[-900:] if len(self._ascending_alert_list) > 900 else self._ascending_alert_list
487
+
488
+ if total_detections > 0:
489
+ level = "low"
490
+ intensity = 5.0
491
+ start_timestamp = self._get_start_timestamp_str(stream_info)
492
+ if start_timestamp and self.current_incident_end_timestamp == 'N/A':
493
+ self.current_incident_end_timestamp = 'Incident still active'
494
+ elif start_timestamp and self.current_incident_end_timestamp == 'Incident still active':
495
+ if len(self._ascending_alert_list) >= 15 and sum(self._ascending_alert_list[-15:]) / 15 < 1.5:
496
+ self.current_incident_end_timestamp = current_timestamp
497
+ elif self.current_incident_end_timestamp != 'Incident still active' and self.current_incident_end_timestamp != 'N/A':
498
+ self.current_incident_end_timestamp = 'N/A'
499
+
500
+ if config.alert_config and hasattr(config.alert_config, 'count_thresholds') and config.alert_config.count_thresholds:
501
+ threshold = config.alert_config.count_thresholds.get("all", 15)
502
+ intensity = min(10.0, (total_detections / threshold) * 10)
503
+ if intensity >= 9:
504
+ level = "critical"
505
+ self._ascending_alert_list.append(3)
506
+ elif intensity >= 7:
507
+ level = "significant"
508
+ self._ascending_alert_list.append(2)
509
+ elif intensity >= 5:
510
+ level = "medium"
511
+ self._ascending_alert_list.append(1)
512
+ else:
513
+ level = "low"
514
+ self._ascending_alert_list.append(0)
515
+ else:
516
+ if total_detections > 30:
517
+ level = "critical"
518
+ intensity = 10.0
519
+ self._ascending_alert_list.append(3)
520
+ elif total_detections > 25:
521
+ level = "significant"
522
+ intensity = 9.0
523
+ self._ascending_alert_list.append(2)
524
+ elif total_detections > 15:
525
+ level = "medium"
526
+ intensity = 7.0
527
+ self._ascending_alert_list.append(1)
528
+ else:
529
+ level = "low"
530
+ intensity = min(10.0, total_detections / 3.0)
531
+ self._ascending_alert_list.append(0)
532
+
533
+ human_text_lines = [f"VEHICLE INCIDENTS DETECTED @ {current_timestamp}:"]
534
+ human_text_lines.append(f"\tSeverity Level: {(self.CASE_TYPE, level)}")
535
+ human_text = "\n".join(human_text_lines)
536
+
537
+ alert_settings = []
538
+ if config.alert_config and hasattr(config.alert_config, 'alert_type'):
539
+ alert_settings.append({
540
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']),
541
+ "incident_category": self.CASE_TYPE,
542
+ "threshold_level": config.alert_config.count_thresholds if hasattr(config.alert_config, 'count_thresholds') else {},
543
+ "ascending": True,
544
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']),
545
+ getattr(config.alert_config, 'alert_value', ['JSON']))}
546
+ })
547
+
548
+ event = self.create_incident(
549
+ incident_id=f"{self.CASE_TYPE}_{frame_number}",
550
+ incident_type=self.CASE_TYPE,
551
+ severity_level=level,
552
+ human_text=human_text,
553
+ camera_info=camera_info,
554
+ alerts=alerts,
555
+ alert_settings=alert_settings,
556
+ start_time=start_timestamp,
557
+ end_time=self.current_incident_end_timestamp,
558
+ level_settings={"low": 1, "medium": 3, "significant": 4, "critical": 7}
559
+ )
560
+ incidents.append(event)
561
+ else:
562
+ self._ascending_alert_list.append(0)
563
+ incidents.append({})
564
+ return incidents
565
+
566
+ def _generate_tracking_stats(self, counting_summary: Dict, zone_analysis: Dict, alerts: List, config: VehicleMonitoringConfig,
567
+ frame_number: Optional[int] = None, stream_info: Optional[Dict[str, Any]] = None) -> List[Dict]:
568
+ camera_info = self.get_camera_info_from_stream(stream_info)
569
+ tracking_stats = []
570
+ total_detections = counting_summary.get("total_count", 0)
571
+ total_counts_dict = counting_summary.get("total_counts", {})
572
+ per_category_count = counting_summary.get("per_category_count", {})
573
+ current_timestamp = self._get_current_timestamp_str(stream_info, precision=False)
574
+ start_timestamp = self._get_start_timestamp_str(stream_info, precision=False)
575
+ high_precision_start_timestamp = self._get_current_timestamp_str(stream_info, precision=True)
576
+ high_precision_reset_timestamp = self._get_start_timestamp_str(stream_info, precision=True)
577
+
578
+ total_counts = [{"category": cat, "count": count} for cat, count in total_counts_dict.items() if count > 0]
579
+ current_counts = [{"category": cat, "count": count} for cat, count in per_category_count.items() if count > 0 or total_detections > 0]
580
+
581
+ detections = []
582
+ for detection in counting_summary.get("detections", []):
583
+ bbox = detection.get("bounding_box", {})
584
+ category = detection.get("category", "vehicle")
585
+ if detection.get("masks"):
586
+ segmentation = detection.get("masks", [])
587
+ detection_obj = self.create_detection_object(category, bbox, segmentation=segmentation)
588
+ elif detection.get("segmentation"):
589
+ segmentation = detection.get("segmentation")
590
+ detection_obj = self.create_detection_object(category, bbox, segmentation=segmentation)
591
+ elif detection.get("mask"):
592
+ segmentation = detection.get("mask")
593
+ detection_obj = self.create_detection_object(category, bbox, segmentation=segmentation)
594
+ else:
595
+ detection_obj = self.create_detection_object(category, bbox)
596
+ detections.append(detection_obj)
597
+
598
+ alert_settings = []
599
+ if config.alert_config and hasattr(config.alert_config, 'alert_type'):
600
+ alert_settings.append({
601
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']),
602
+ "incident_category": self.CASE_TYPE,
603
+ "threshold_level": config.alert_config.count_thresholds if hasattr(config.alert_config, 'count_thresholds') else {},
604
+ "ascending": True,
605
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']),
606
+ getattr(config.alert_config, 'alert_value', ['JSON']))}
607
+ })
608
+
609
+ # Generate human text similar to people_counting format
610
+ human_text_lines = []
611
+ human_text_lines.append(f"CURRENT FRAME @ {current_timestamp}:")
612
+
613
+ # Display current counts - zone-wise or category-wise
614
+ if zone_analysis:
615
+ human_text_lines.append("\t- Vehicles Detected by Zone:")
616
+ for zone_name, zone_data in zone_analysis.items():
617
+ current_count = 0
618
+ if isinstance(zone_data, dict):
619
+ if "current_count" in zone_data:
620
+ current_count = zone_data.get("current_count", 0)
621
+ else:
622
+ counts_dict = zone_data.get("original_counts") if isinstance(zone_data.get("original_counts"), dict) else zone_data
623
+ current_count = counts_dict.get(
624
+ "total",
625
+ sum(v for v in counts_dict.values() if isinstance(v, (int, float)))
626
+ )
627
+ human_text_lines.append(f"\t\t- {zone_name}: {int(current_count)}")
628
+ else:
629
+ human_text_lines.append(f"\t- Vehicles Detected: {total_detections}")
630
+ if per_category_count:
631
+ for cat, count in per_category_count.items():
632
+ if count > 0:
633
+ human_text_lines.append(f"\t\t- {cat}: {count}")
634
+
635
+ human_text_lines.append("")
636
+ human_text_lines.append(f"TOTAL SINCE @ {start_timestamp}:")
637
+
638
+ # Display total counts - zone-wise or category-wise
639
+ if zone_analysis:
640
+ human_text_lines.append("\t- Total Vehicles by Zone:")
641
+ for zone_name, zone_data in zone_analysis.items():
642
+ total_count = 0
643
+ if isinstance(zone_data, dict):
644
+ # Prefer the numeric cumulative total if available
645
+ if "total_count" in zone_data and isinstance(zone_data.get("total_count"), (int, float)):
646
+ total_count = zone_data.get("total_count", 0)
647
+ # Fallback: compute from list of total_track_ids if present
648
+ elif "total_track_ids" in zone_data and isinstance(zone_data.get("total_track_ids"), list):
649
+ total_count = len(zone_data.get("total_track_ids", []))
650
+ else:
651
+ # Last resort: try to sum numeric values present
652
+ counts_dict = zone_data if isinstance(zone_data, dict) else {}
653
+ total_count = sum(v for v in counts_dict.values() if isinstance(v, (int, float)))
654
+ human_text_lines.append(f"\t\t- {zone_name}: {int(total_count)}")
655
+ else:
656
+ if total_counts_dict:
657
+ human_text_lines.append("\t- Total Unique Vehicles:")
658
+ for cat, count in total_counts_dict.items():
659
+ if count > 0:
660
+ human_text_lines.append(f"\t\t- {cat}: {count}")
661
+
662
+ # Display alerts
663
+ if alerts:
664
+ human_text_lines.append("")
665
+ for alert in alerts:
666
+ human_text_lines.append(f"Alerts: {alert.get('settings', {})} sent @ {current_timestamp}")
667
+ else:
668
+ human_text_lines.append("")
669
+ human_text_lines.append("Alerts: None")
670
+
671
+ human_text = "\n".join(human_text_lines)
672
+
673
+ reset_settings = [{"interval_type": "daily", "reset_time": {"value": 9, "time_unit": "hour"}}]
674
+ tracking_stat = self.create_tracking_stats(
675
+ total_counts=total_counts,
676
+ current_counts=current_counts,
677
+ detections=detections,
678
+ human_text=human_text,
679
+ camera_info=camera_info,
680
+ alerts=alerts,
681
+ alert_settings=alert_settings,
682
+ reset_settings=reset_settings,
683
+ start_time=high_precision_start_timestamp,
684
+ reset_time=high_precision_reset_timestamp
685
+ )
686
+ tracking_stats.append(tracking_stat)
687
+ return tracking_stats
688
+
689
+ def _generate_business_analytics(self, counting_summary: Dict, zone_analysis: Dict, alerts: Any, config: VehicleMonitoringConfig,
690
+ stream_info: Optional[Dict[str, Any]] = None, is_empty=False) -> List[Dict]:
691
+ if is_empty:
692
+ return []
693
+
694
+ def _generate_summary(self, summary: dict, zone_analysis: Dict, incidents: List, tracking_stats: List, business_analytics: List, alerts: List) -> List[str]:
695
+ """
696
+ Generate a human_text string for the tracking_stat, incident, business analytics and alerts.
697
+ """
698
+ lines = []
699
+ lines.append("Application Name: "+self.CASE_TYPE)
700
+ lines.append("Application Version: "+self.CASE_VERSION)
701
+ if len(incidents) > 0:
702
+ lines.append("Incidents: "+f"\n\t{incidents[0].get('human_text', 'No incidents detected')}")
703
+ if len(tracking_stats) > 0:
704
+ lines.append("Tracking Statistics: "+f"\t{tracking_stats[0].get('human_text', 'No tracking statistics detected')}")
705
+ if len(business_analytics) > 0:
706
+ lines.append("Business Analytics: "+f"\t{business_analytics[0].get('human_text', 'No business analytics detected')}")
707
+
708
+ if len(incidents) == 0 and len(tracking_stats) == 0 and len(business_analytics) == 0:
709
+ lines.append("Summary: "+"No Summary Data")
710
+
711
+ return ["\n".join(lines)]
712
+
713
+ def _get_track_ids_info(self, detections: list) -> Dict[str, Any]:
714
+ frame_track_ids = set()
715
+ for det in detections:
716
+ tid = det.get('track_id')
717
+ if tid is not None:
718
+ frame_track_ids.add(tid)
719
+ total_track_ids = set()
720
+ for s in getattr(self, '_per_category_total_track_ids', {}).values():
721
+ total_track_ids.update(s)
722
+ return {
723
+ "total_count": len(total_track_ids),
724
+ "current_frame_count": len(frame_track_ids),
725
+ "total_unique_track_ids": len(total_track_ids),
726
+ "current_frame_track_ids": list(frame_track_ids),
727
+ "last_update_time": time.time(),
728
+ "total_frames_processed": getattr(self, '_total_frame_counter', 0)
729
+ }
730
+
731
+ def _update_tracking_state(self, detections: list, has_zones: bool = False):
732
+ if not hasattr(self, "_per_category_total_track_ids"):
733
+ self._per_category_total_track_ids = {cat: set() for cat in self.target_categories}
734
+ self._current_frame_track_ids = {cat: set() for cat in self.target_categories}
735
+
736
+ for det in detections:
737
+ cat = det.get("category")
738
+ raw_track_id = det.get("track_id")
739
+ if cat not in self.target_categories or raw_track_id is None:
740
+ continue
741
+ bbox = det.get("bounding_box", det.get("bbox"))
742
+ canonical_id = self._merge_or_register_track(raw_track_id, bbox)
743
+ det["track_id"] = canonical_id
744
+ if not has_zones:
745
+ self._per_category_total_track_ids.setdefault(cat, set()).add(canonical_id)
746
+ # For current frame, add unconditionally here; will be overridden/adjusted if has_zones in _update_zone_tracking
747
+ self._current_frame_track_ids.setdefault(cat, set()).add(canonical_id)
748
+
749
+ def get_total_counts(self):
750
+ return {cat: len(ids) for cat, ids in getattr(self, '_per_category_total_track_ids', {}).items()}
751
+
752
+ def _format_timestamp_for_stream(self, timestamp: float) -> str:
753
+ dt = datetime.fromtimestamp(timestamp, tz=timezone.utc)
754
+ return dt.strftime('%Y:%m:%d %H:%M:%S')
755
+
756
+ def _format_timestamp_for_video(self, timestamp: float) -> str:
757
+ hours = int(timestamp // 3600)
758
+ minutes = int((timestamp % 3600) // 60)
759
+ seconds = round(float(timestamp % 60), 2)
760
+ return f"{hours:02d}:{minutes:02d}:{seconds:.1f}"
761
+
762
+ def _format_timestamp(self, timestamp: Any) -> str:
763
+ """Format a timestamp to match the current timestamp format: YYYY:MM:DD HH:MM:SS.
764
+
765
+ The input can be either:
766
+ 1. A numeric Unix timestamp (``float`` / ``int``) – it will be converted to datetime.
767
+ 2. A string in the format ``YYYY-MM-DD-HH:MM:SS.ffffff UTC``.
768
+
769
+ The returned value will be in the format: YYYY:MM:DD HH:MM:SS (no milliseconds, no UTC suffix).
770
+
771
+ Example
772
+ -------
773
+ >>> self._format_timestamp("2025-10-27-19:31:20.187574 UTC")
774
+ '2025:10:27 19:31:20'
775
+ """
776
+
777
+ # Convert numeric timestamps to datetime first
778
+ if isinstance(timestamp, (int, float)):
779
+ dt = datetime.fromtimestamp(timestamp, timezone.utc)
780
+ return dt.strftime('%Y:%m:%d %H:%M:%S')
781
+
782
+ # Ensure we are working with a string from here on
783
+ if not isinstance(timestamp, str):
784
+ return str(timestamp)
785
+
786
+ # Remove ' UTC' suffix if present
787
+ timestamp_clean = timestamp.replace(' UTC', '').strip()
788
+
789
+ # Remove milliseconds if present (everything after the last dot)
790
+ if '.' in timestamp_clean:
791
+ timestamp_clean = timestamp_clean.split('.')[0]
792
+
793
+ # Parse the timestamp string and convert to desired format
794
+ try:
795
+ # Handle format: YYYY-MM-DD-HH:MM:SS
796
+ if timestamp_clean.count('-') >= 2:
797
+ # Replace first two dashes with colons for date part, third with space
798
+ parts = timestamp_clean.split('-')
799
+ if len(parts) >= 4:
800
+ # parts = ['2025', '10', '27', '19:31:20']
801
+ formatted = f"{parts[0]}:{parts[1]}:{parts[2]} {'-'.join(parts[3:])}"
802
+ return formatted
803
+ except Exception:
804
+ pass
805
+
806
+ # If parsing fails, return the cleaned string as-is
807
+ return timestamp_clean
808
+
809
+ def _get_current_timestamp_str(self, stream_info: Optional[Dict[str, Any]], precision=False, frame_id: Optional[str]=None) -> str:
810
+ """Get formatted current timestamp based on stream type."""
811
+
812
+ if not stream_info:
813
+ return "00:00:00.00"
814
+ if precision:
815
+ if stream_info.get("input_settings", {}).get("start_frame", "na") != "na":
816
+ if frame_id:
817
+ start_time = int(frame_id)/stream_info.get("input_settings", {}).get("original_fps", 30)
818
+ else:
819
+ start_time = stream_info.get("input_settings", {}).get("start_frame", 30)/stream_info.get("input_settings", {}).get("original_fps", 30)
820
+ stream_time_str = self._format_timestamp_for_video(start_time)
821
+
822
+ return self._format_timestamp(stream_info.get("input_settings", {}).get("stream_time", "NA"))
823
+ else:
824
+ return datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
825
+
826
+ if stream_info.get("input_settings", {}).get("start_frame", "na") != "na":
827
+ if frame_id:
828
+ start_time = int(frame_id)/stream_info.get("input_settings", {}).get("original_fps", 30)
829
+ else:
830
+ start_time = stream_info.get("input_settings", {}).get("start_frame", 30)/stream_info.get("input_settings", {}).get("original_fps", 30)
831
+
832
+ stream_time_str = self._format_timestamp_for_video(start_time)
833
+
834
+
835
+ return self._format_timestamp(stream_info.get("input_settings", {}).get("stream_time", "NA"))
836
+ else:
837
+ stream_time_str = stream_info.get("input_settings", {}).get("stream_info", {}).get("stream_time", "")
838
+ if stream_time_str:
839
+ try:
840
+ timestamp_str = stream_time_str.replace(" UTC", "")
841
+ dt = datetime.strptime(timestamp_str, "%Y-%m-%d-%H:%M:%S.%f")
842
+ timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
843
+ return self._format_timestamp_for_stream(timestamp)
844
+ except:
845
+ return self._format_timestamp_for_stream(time.time())
846
+ else:
847
+ return self._format_timestamp_for_stream(time.time())
848
+
849
+ def _get_start_timestamp_str(self, stream_info: Optional[Dict[str, Any]], precision=False) -> str:
850
+ """Get formatted start timestamp for 'TOTAL SINCE' based on stream type."""
851
+ if not stream_info:
852
+ return "00:00:00"
853
+
854
+ if precision:
855
+ if self.start_timer is None:
856
+ candidate = stream_info.get("input_settings", {}).get("stream_time")
857
+ if not candidate or candidate == "NA":
858
+ candidate = datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
859
+ self.start_timer = candidate
860
+ return self._format_timestamp(self.start_timer)
861
+ elif stream_info.get("input_settings", {}).get("start_frame", "na") == 1:
862
+ candidate = stream_info.get("input_settings", {}).get("stream_time")
863
+ if not candidate or candidate == "NA":
864
+ candidate = datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
865
+ self.start_timer = candidate
866
+ return self._format_timestamp(self.start_timer)
867
+ else:
868
+ return self._format_timestamp(self.start_timer)
869
+
870
+ if self.start_timer is None:
871
+ # Prefer direct input_settings.stream_time if available and not NA
872
+ candidate = stream_info.get("input_settings", {}).get("stream_time")
873
+ if not candidate or candidate == "NA":
874
+ # Fallback to nested stream_info.stream_time used by current timestamp path
875
+ stream_time_str = stream_info.get("input_settings", {}).get("stream_info", {}).get("stream_time", "")
876
+ if stream_time_str:
877
+ try:
878
+ timestamp_str = stream_time_str.replace(" UTC", "")
879
+ dt = datetime.strptime(timestamp_str, "%Y-%m-%d-%H:%M:%S.%f")
880
+ self._tracking_start_time = dt.replace(tzinfo=timezone.utc).timestamp()
881
+ candidate = datetime.fromtimestamp(self._tracking_start_time, timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
882
+ except:
883
+ candidate = datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
884
+ else:
885
+ candidate = datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
886
+ self.start_timer = candidate
887
+ return self._format_timestamp(self.start_timer)
888
+ elif stream_info.get("input_settings", {}).get("start_frame", "na") == 1:
889
+ candidate = stream_info.get("input_settings", {}).get("stream_time")
890
+ if not candidate or candidate == "NA":
891
+ stream_time_str = stream_info.get("input_settings", {}).get("stream_info", {}).get("stream_time", "")
892
+ if stream_time_str:
893
+ try:
894
+ timestamp_str = stream_time_str.replace(" UTC", "")
895
+ dt = datetime.strptime(timestamp_str, "%Y-%m-%d-%H:%M:%S.%f")
896
+ ts = dt.replace(tzinfo=timezone.utc).timestamp()
897
+ candidate = datetime.fromtimestamp(ts, timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
898
+ except:
899
+ candidate = datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
900
+ else:
901
+ candidate = datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
902
+ self.start_timer = candidate
903
+ return self._format_timestamp(self.start_timer)
904
+
905
+ else:
906
+ if self.start_timer is not None and self.start_timer != "NA":
907
+ return self._format_timestamp(self.start_timer)
908
+
909
+ if self._tracking_start_time is None:
910
+ stream_time_str = stream_info.get("input_settings", {}).get("stream_info", {}).get("stream_time", "")
911
+ if stream_time_str:
912
+ try:
913
+ timestamp_str = stream_time_str.replace(" UTC", "")
914
+ dt = datetime.strptime(timestamp_str, "%Y-%m-%d-%H:%M:%S.%f")
915
+ self._tracking_start_time = dt.replace(tzinfo=timezone.utc).timestamp()
916
+ except:
917
+ self._tracking_start_time = time.time()
918
+ else:
919
+ self._tracking_start_time = time.time()
920
+
921
+ dt = datetime.fromtimestamp(self._tracking_start_time, tz=timezone.utc)
922
+ dt = dt.replace(minute=0, second=0, microsecond=0)
923
+ return dt.strftime('%Y:%m:%d %H:%M:%S')
924
+
925
+ def _count_categories(self, detections: list, config: VehicleMonitoringConfig) -> dict:
926
+ counts = {}
927
+ for det in detections:
928
+ cat = det.get('category', 'unknown')
929
+ counts[cat] = counts.get(cat, 0) + 1
930
+ return {
931
+ "total_count": sum(counts.values()),
932
+ "per_category_count": counts,
933
+ "detections": [
934
+ {
935
+ "bounding_box": det.get("bounding_box"),
936
+ "category": det.get("category"),
937
+ "confidence": det.get("confidence"),
938
+ "track_id": det.get("track_id"),
939
+ "frame_id": det.get("frame_id")
940
+ }
941
+ for det in detections
942
+ ]
943
+ }
944
+
945
+ def _extract_predictions(self, detections: list) -> List[Dict[str, Any]]:
946
+ return [
947
+ {
948
+ "category": det.get("category", "unknown"),
949
+ "confidence": det.get("confidence", 0.0),
950
+ "bounding_box": det.get("bounding_box", {})
951
+ }
952
+ for det in detections
953
+ ]
954
+
955
+ def _compute_iou(self, box1: Any, box2: Any) -> float:
956
+ def _bbox_to_list(bbox):
957
+ if bbox is None:
958
+ return []
959
+ if isinstance(bbox, list):
960
+ return bbox[:4] if len(bbox) >= 4 else []
961
+ if isinstance(bbox, dict):
962
+ if "xmin" in bbox:
963
+ return [bbox["xmin"], bbox["ymin"], bbox["xmax"], bbox["ymax"]]
964
+ if "x1" in bbox:
965
+ return [bbox["x1"], bbox["y1"], bbox["x2"], bbox["y2"]]
966
+ values = [v for v in bbox.values() if isinstance(v, (int, float))]
967
+ return values[:4] if len(values) >= 4 else []
968
+ return []
969
+
970
+ l1 = _bbox_to_list(box1)
971
+ l2 = _bbox_to_list(box2)
972
+ if len(l1) < 4 or len(l2) < 4:
973
+ return 0.0
974
+ x1_min, y1_min, x1_max, y1_max = l1
975
+ x2_min, y2_min, x2_max, y2_max = l2
976
+ x1_min, x1_max = min(x1_min, x1_max), max(x1_min, x1_max)
977
+ y1_min, y1_max = min(y1_min, y1_max), max(y1_min, y1_max)
978
+ x2_min, x2_max = min(x2_min, x2_max), max(x2_min, x2_max)
979
+ y2_min, y2_max = min(y2_min, y2_max), max(y2_min, y2_max)
980
+ inter_x_min = max(x1_min, x2_min)
981
+ inter_y_min = max(y1_min, y2_min)
982
+ inter_x_max = min(x1_max, x2_max)
983
+ inter_y_max = min(y1_max, y2_max)
984
+ inter_w = max(0.0, inter_x_max - inter_x_min)
985
+ inter_h = max(0.0, inter_y_max - inter_y_min)
986
+ inter_area = inter_w * inter_h
987
+ area1 = (x1_max - x1_min) * (y1_max - y1_min)
988
+ area2 = (x2_max - x2_min) * (y2_max - y2_min)
989
+ union_area = area1 + area2 - inter_area
990
+ return (inter_area / union_area) if union_area > 0 else 0.0
991
+
992
+ def _merge_or_register_track(self, raw_id: Any, bbox: Any) -> Any:
993
+ if raw_id is None or bbox is None:
994
+ return raw_id
995
+ now = time.time()
996
+ if raw_id in self._track_aliases:
997
+ canonical_id = self._track_aliases[raw_id]
998
+ track_info = self._canonical_tracks.get(canonical_id)
999
+ if track_info is not None:
1000
+ track_info["last_bbox"] = bbox
1001
+ track_info["last_update"] = now
1002
+ track_info["raw_ids"].add(raw_id)
1003
+ return canonical_id
1004
+ for canonical_id, info in self._canonical_tracks.items():
1005
+ if now - info["last_update"] > self._track_merge_time_window:
1006
+ continue
1007
+ iou = self._compute_iou(bbox, info["last_bbox"])
1008
+ if iou >= self._track_merge_iou_threshold:
1009
+ self._track_aliases[raw_id] = canonical_id
1010
+ info["last_bbox"] = bbox
1011
+ info["last_update"] = now
1012
+ info["raw_ids"].add(raw_id)
1013
+ return canonical_id
1014
+ canonical_id = raw_id
1015
+ self._track_aliases[raw_id] = canonical_id
1016
+ self._canonical_tracks[canonical_id] = {
1017
+ "last_bbox": bbox,
1018
+ "last_update": now,
1019
+ "raw_ids": {raw_id},
1020
+ }
1021
+ return canonical_id
1022
+
1023
+ def _get_tracking_start_time(self) -> str:
1024
+ if self._tracking_start_time is None:
1025
+ return "N/A"
1026
+ return self._format_timestamp(self._tracking_start_time)
1027
+
1028
+ def _set_tracking_start_time(self) -> None:
1029
+ self._tracking_start_time = time.time()