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,840 @@
1
+ """
2
+ leaf disease Monitoring Use Case for Post-Processing
3
+
4
+ This module provides leaf disease monitoring functionality with congestion detection,
5
+ zone analysis, and alert generation.
6
+
7
+ """
8
+
9
+ from typing import Any, Dict, List, Optional
10
+ from dataclasses import asdict
11
+ import time
12
+ from datetime import datetime, timezone
13
+
14
+ from ..core.base import BaseProcessor, ProcessingContext, ProcessingResult, ConfigProtocol, ResultFormat
15
+ from ..utils import (
16
+ filter_by_confidence,
17
+ filter_by_categories,
18
+ apply_category_mapping,
19
+ count_objects_by_category,
20
+ count_objects_in_zones,
21
+ calculate_counting_summary,
22
+ match_results_structure,
23
+ bbox_smoothing,
24
+ BBoxSmoothingConfig,
25
+ BBoxSmoothingTracker
26
+ )
27
+ from dataclasses import dataclass, field
28
+ from ..core.config import BaseConfig, AlertConfig, ZoneConfig
29
+
30
+
31
+ @dataclass
32
+ class LeafDiseaseDetectionConfig(BaseConfig):
33
+ """Configuration for leaf disease detection use case in """
34
+ # Smoothing configuration
35
+ enable_smoothing: bool = True
36
+ smoothing_algorithm: str = "observability" # "window" or "observability"
37
+ smoothing_window_size: int = 20
38
+ smoothing_cooldown_frames: int = 5
39
+ smoothing_confidence_range_factor: float = 0.5
40
+
41
+ #confidence thresholds
42
+ confidence_threshold: float = 0.6
43
+
44
+ usecase_categories: List[str] = field(
45
+ default_factory=lambda: [
46
+ 'Apple Black Rod',
47
+ 'Apple Healthy',
48
+ 'Cherry Healthy',
49
+ 'Grape Healthy',
50
+ 'Grape Leaf Blight',
51
+ 'Grape Esca',
52
+ 'Cedar Apple Rust',
53
+ 'Cherry Powdery Mildew',
54
+ 'Grape Black Rot',
55
+ 'Apple Scab'
56
+ ]
57
+
58
+ )
59
+
60
+ target_categories: List[str] = field(
61
+ default_factory=lambda: [
62
+ 'Apple Black Rod',
63
+ 'Apple Healthy',
64
+ 'Cherry Healthy',
65
+ 'Grape Healthy',
66
+ 'Grape Leaf Blight',
67
+ 'Grape Esca',
68
+ 'Cedar Apple Rust',
69
+ 'Cherry Powdery Mildew',
70
+ 'Grape Black Rot',
71
+ 'Apple Scab'
72
+ ]
73
+
74
+ )
75
+
76
+ alert_config: Optional[AlertConfig] = None
77
+
78
+ index_to_category: Optional[Dict[int, str]] = field(
79
+ default_factory=lambda: {
80
+ 0: "Apple Black Rod",
81
+ 1: "Apple Healthy",
82
+ 2: "Cherry Healthy",
83
+ 3: "Grape Healthy",
84
+ 4: "Grape Leaf Blight",
85
+ 5: "Grape Esca",
86
+ 6: "Cedar Apple Rust",
87
+ 7: "Cherry Powdery Mildew",
88
+ 8: "Grape Black Rot",
89
+ 9: "Apple Scab"
90
+ }
91
+ )
92
+
93
+
94
+ class LeafDiseaseDetectionUseCase(BaseProcessor):
95
+ def _get_track_ids_info(self, detections: list) -> Dict[str, Any]:
96
+ """
97
+ Get detailed information about track IDs (per frame).
98
+ """
99
+ # Collect all track_ids in this frame
100
+ frame_track_ids = set()
101
+ for det in detections:
102
+ tid = det.get('track_id')
103
+ if tid is not None:
104
+ frame_track_ids.add(tid)
105
+ # Use persistent total set for unique counting
106
+ total_track_ids = set()
107
+ for s in getattr(self, '_per_category_total_track_ids', {}).values():
108
+ total_track_ids.update(s)
109
+ return {
110
+ "total_count": len(total_track_ids),
111
+ "current_frame_count": len(frame_track_ids),
112
+ "total_unique_track_ids": len(total_track_ids),
113
+ "current_frame_track_ids": list(frame_track_ids),
114
+ "last_update_time": time.time(),
115
+ "total_frames_processed": getattr(self, '_total_frame_counter', 0)
116
+ }
117
+
118
+
119
+
120
+
121
+
122
+ def _update_tracking_state(self, detections: list):
123
+ """
124
+ Track unique categories track_ids per category for total count after tracking.
125
+ Applies canonical ID merging to avoid duplicate counting when the underlying
126
+ tracker loses an object temporarily and assigns a new ID.
127
+ """
128
+ # Lazily initialise storage dicts
129
+ if not hasattr(self, "_per_category_total_track_ids"):
130
+ self._per_category_total_track_ids = {cat: set() for cat in self.target_categories}
131
+ self._current_frame_track_ids = {cat: set() for cat in self.target_categories}
132
+
133
+ for det in detections:
134
+ cat = det.get("category")
135
+ raw_track_id = det.get("track_id")
136
+ if cat not in self.target_categories or raw_track_id is None:
137
+ continue
138
+ bbox = det.get("bounding_box", det.get("bbox"))
139
+ canonical_id = self._merge_or_register_track(raw_track_id, bbox)
140
+ # Propagate canonical ID back to detection so downstream logic uses it
141
+ det["track_id"] = canonical_id
142
+
143
+ self._per_category_total_track_ids.setdefault(cat, set()).add(canonical_id)
144
+ self._current_frame_track_ids[cat].add(canonical_id)
145
+
146
+ def get_total_counts(self):
147
+ """
148
+ Return total unique track_id count for each category.
149
+ """
150
+ return {cat: len(ids) for cat, ids in getattr(self, '_per_category_total_track_ids', {}).items()}
151
+
152
+ def _format_timestamp_for_video(self, timestamp: float) -> str:
153
+ """Format timestamp for video chunks (HH:MM:SS.ms format)."""
154
+ hours = int(timestamp // 3600)
155
+ minutes = int((timestamp % 3600) // 60)
156
+ seconds = timestamp % 60
157
+ return f"{hours:02d}:{minutes:02d}:{seconds:06.2f}"
158
+
159
+ def _format_timestamp_for_stream(self, timestamp: float) -> str:
160
+ """Format timestamp for streams (YYYY:MM:DD HH:MM:SS format)."""
161
+ dt = datetime.fromtimestamp(timestamp, tz=timezone.utc)
162
+ return dt.strftime('%Y:%m:%d %H:%M:%S')
163
+
164
+ def _get_current_timestamp_str(self, stream_info: Optional[Dict[str, Any]]) -> str:
165
+ """Get formatted current timestamp based on stream type."""
166
+ if not stream_info:
167
+ return "00:00:00.00"
168
+
169
+ is_video_chunk = stream_info.get("input_settings", {}).get("is_video_chunk", False)
170
+
171
+ # if is_video_chunk:
172
+ # # For video chunks, use video_timestamp from stream_info
173
+ # video_timestamp = stream_info.get("video_timestamp", 0.0)
174
+ # return self._format_timestamp_for_video(video_timestamp)
175
+ if stream_info.get("input_settings", {}).get("stream_type", "video_file") == "video_file":
176
+ # If video format, return video timestamp
177
+ stream_time_str = stream_info.get("video_timestamp", "")
178
+ return stream_time_str[:8]
179
+ else:
180
+ # For streams, use stream_time from stream_info
181
+ stream_time_str = stream_info.get("stream_time", "")
182
+ if stream_time_str:
183
+ # Parse the high precision timestamp string to get timestamp
184
+ try:
185
+ # Remove " UTC" suffix and parse
186
+ timestamp_str = stream_time_str.replace(" UTC", "")
187
+ dt = datetime.strptime(timestamp_str, "%Y-%m-%d-%H:%M:%S.%f")
188
+ timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
189
+ return self._format_timestamp_for_stream(timestamp)
190
+ except:
191
+ # Fallback to current time if parsing fails
192
+ return self._format_timestamp_for_stream(time.time())
193
+ else:
194
+ return self._format_timestamp_for_stream(time.time())
195
+
196
+ def _get_start_timestamp_str(self, stream_info: Optional[Dict[str, Any]]) -> str:
197
+ """Get formatted start timestamp for 'TOTAL SINCE' based on stream type."""
198
+ if not stream_info:
199
+ return "00:00:00"
200
+
201
+ is_video_chunk = stream_info.get("input_settings", {}).get("is_video_chunk", False)
202
+
203
+ if is_video_chunk:
204
+ # For video chunks, start from 00:00:00
205
+ return "00:00:00"
206
+ elif stream_info.get("input_settings", {}).get("stream_type", "video_file") == "video_file":
207
+ # If video format, start from 00:00:00
208
+ return "00:00:00"
209
+ else:
210
+ # For streams, use tracking start time or current time with minutes/seconds reset
211
+ if self._tracking_start_time is None:
212
+ # Try to extract timestamp from stream_time string
213
+ stream_time_str = stream_info.get("stream_time", "")
214
+ if stream_time_str:
215
+ try:
216
+ # Remove " UTC" suffix and parse
217
+ timestamp_str = stream_time_str.replace(" UTC", "")
218
+ dt = datetime.strptime(timestamp_str, "%Y-%m-%d-%H:%M:%S.%f")
219
+ self._tracking_start_time = dt.replace(tzinfo=timezone.utc).timestamp()
220
+ except:
221
+ # Fallback to current time if parsing fails
222
+ self._tracking_start_time = time.time()
223
+ else:
224
+ self._tracking_start_time = time.time()
225
+
226
+ dt = datetime.fromtimestamp(self._tracking_start_time, tz=timezone.utc)
227
+ # Reset minutes and seconds to 00:00 for "TOTAL SINCE" format
228
+ dt = dt.replace(minute=0, second=0, microsecond=0)
229
+ return dt.strftime('%Y:%m:%d %H:%M:%S')
230
+
231
+ """ Monitoring use case with smoothing and alerting."""
232
+
233
+ def __init__(self):
234
+ super().__init__("leaf_disease_detection")
235
+ self.category = "agriculture"
236
+
237
+ # List of categories to track
238
+ self.target_categories = [
239
+ 'Apple Black Rod',
240
+ 'Apple Healthy',
241
+ 'Cherry Healthy',
242
+ 'Grape Healthy',
243
+ 'Grape Leaf Blight',
244
+ 'Grape Esca',
245
+ 'Cedar Apple Rust',
246
+ 'Cherry Powdery Mildew',
247
+ 'Grape Black Rot',
248
+ 'Apple Scab'
249
+ ]
250
+
251
+
252
+
253
+
254
+ # Initialize smoothing tracker
255
+ self.smoothing_tracker = None
256
+
257
+ # Initialize advanced tracker (will be created on first use)
258
+ self.tracker = None
259
+
260
+ # Initialize tracking state variables
261
+ self._total_frame_counter = 0
262
+ self._global_frame_offset = 0
263
+
264
+ # Track start time for "TOTAL SINCE" calculation
265
+ self._tracking_start_time = None
266
+
267
+ # ------------------------------------------------------------------ #
268
+ # Canonical tracking aliasing to avoid duplicate counts #
269
+ # ------------------------------------------------------------------ #
270
+ # Maps raw tracker-generated IDs to stable canonical IDs that persist
271
+ # even if the underlying tracker re-assigns a new ID after a short
272
+ # interruption. This mirrors the logic used in people_counting to
273
+ # provide accurate unique counting.
274
+ self._track_aliases: Dict[Any, Any] = {}
275
+ self._canonical_tracks: Dict[Any, Dict[str, Any]] = {}
276
+ # Tunable parameters – adjust if necessary for specific scenarios
277
+ self._track_merge_iou_threshold: float = 0.05 # IoU ≥ 0.05 →
278
+ self._track_merge_time_window: float = 7.0 # seconds within which to merge
279
+
280
+ def process(self, data: Any, config: ConfigProtocol, context: Optional[ProcessingContext] = None,
281
+ stream_info: Optional[Dict[str, Any]] = None) -> ProcessingResult:
282
+ """
283
+ Main entry point for post-processing.
284
+ Applies category mapping, smoothing, counting, alerting, and summary generation.
285
+ Returns a ProcessingResult with all relevant outputs.
286
+ """
287
+ start_time = time.time()
288
+ # Ensure config is correct type
289
+ if not isinstance(config, LeafDiseaseDetectionConfig):
290
+ return self.create_error_result("Invalid config type", usecase=self.name, category=self.category,
291
+ context=context)
292
+ if context is None:
293
+ context = ProcessingContext()
294
+
295
+ # Detect input format and store in context
296
+ input_format = match_results_structure(data)
297
+ context.input_format = input_format
298
+ context.confidence_threshold = config.confidence_threshold
299
+
300
+ if config.confidence_threshold is not None:
301
+ processed_data = filter_by_confidence(data, config.confidence_threshold)
302
+ self.logger.debug(f"Applied confidence filtering with threshold {config.confidence_threshold}")
303
+ else:
304
+ processed_data = data
305
+ self.logger.debug(f"Did not apply confidence filtering with threshold since nothing was provided")
306
+
307
+ # Step 2: Apply category mapping if provided
308
+ if config.index_to_category:
309
+ processed_data = apply_category_mapping(processed_data, config.index_to_category)
310
+ self.logger.debug("Applied category mapping")
311
+
312
+ if config.target_categories:
313
+ processed_data = [d for d in processed_data if d.get('category') in self.target_categories]
314
+ self.logger.debug(f"Applied category filtering")
315
+
316
+ # Apply bbox smoothing if enabled
317
+ if config.enable_smoothing:
318
+ if self.smoothing_tracker is None:
319
+ smoothing_config = BBoxSmoothingConfig(
320
+ smoothing_algorithm=config.smoothing_algorithm,
321
+ window_size=config.smoothing_window_size,
322
+ cooldown_frames=config.smoothing_cooldown_frames,
323
+ confidence_threshold=config.confidence_threshold, # Use leaf disease threshold as default
324
+ confidence_range_factor=config.smoothing_confidence_range_factor,
325
+ enable_smoothing=True
326
+ )
327
+ self.smoothing_tracker = BBoxSmoothingTracker(smoothing_config)
328
+ processed_data = bbox_smoothing(processed_data, self.smoothing_tracker.config, self.smoothing_tracker)
329
+
330
+
331
+ # Advanced tracking (BYTETracker-like)
332
+ try:
333
+ from ..advanced_tracker import AdvancedTracker
334
+ from ..advanced_tracker.config import TrackerConfig
335
+
336
+ # Create tracker instance if it doesn't exist (preserves state across frames)
337
+ if self.tracker is None:
338
+ tracker_config = TrackerConfig()
339
+ self.tracker = AdvancedTracker(tracker_config)
340
+ self.logger.info("Initialized AdvancedTracker for Monitoring and tracking")
341
+
342
+ # The tracker expects the data in the same format as input
343
+ # It will add track_id and frame_id to each detection
344
+ processed_data = self.tracker.update(processed_data)
345
+
346
+ except Exception as e:
347
+ # If advanced tracker fails, fallback to unsmoothed detections
348
+ self.logger.warning(f"AdvancedTracker failed: {e}")
349
+
350
+
351
+
352
+
353
+ # Update tracking state for total count per label
354
+ self._update_tracking_state(processed_data)
355
+
356
+ # Update frame counter
357
+ self._total_frame_counter += 1
358
+
359
+ # Extract frame information from stream_info
360
+ frame_number = None
361
+ if stream_info:
362
+ input_settings = stream_info.get("input_settings", {})
363
+ start_frame = input_settings.get("start_frame")
364
+ end_frame = input_settings.get("end_frame")
365
+ # If start and end frame are the same, it's a single frame
366
+ if start_frame is not None and end_frame is not None and start_frame == end_frame:
367
+ frame_number = start_frame
368
+
369
+ # Compute summaries and alerts
370
+ general_counting_summary = calculate_counting_summary(data) #done
371
+ counting_summary = self._count_categories(processed_data, config) #done
372
+ # Add total unique counts after tracking using only local state
373
+ total_counts = self.get_total_counts() #done
374
+ counting_summary['total_counts'] = total_counts #done
375
+ insights = self._generate_insights(counting_summary, config)#done
376
+ alerts = self._check_alerts(counting_summary, config)#done
377
+ predictions = self._extract_predictions(processed_data)#done
378
+ summary = self._generate_summary(counting_summary, alerts)#done
379
+
380
+ # Step: Generate structured events and tracking stats with frame-based keys
381
+ events_list = self._generate_events(counting_summary, alerts, config, frame_number, stream_info)#done
382
+ tracking_stats_list = self._generate_tracking_stats(counting_summary, insights, summary, config, frame_number,
383
+ stream_info)
384
+
385
+ # Extract frame-based dictionaries from the lists
386
+ events = events_list[0] if events_list else {}
387
+ tracking_stats = tracking_stats_list[0] if tracking_stats_list else {}
388
+
389
+ context.mark_completed()
390
+
391
+ # Build result object
392
+ result = self.create_result(
393
+ data={
394
+ "counting_summary": counting_summary,
395
+ "general_counting_summary": general_counting_summary,
396
+ "alerts": alerts,
397
+ "total_detections": counting_summary.get("total_count", 0),
398
+ "events": events,
399
+ "tracking_stats": tracking_stats,
400
+ },
401
+ usecase=self.name,
402
+ category=self.category,
403
+ context=context
404
+ )
405
+ result.summary = summary
406
+ result.insights = insights
407
+ result.predictions = predictions
408
+ return result
409
+
410
+
411
+
412
+ def _generate_events(self, counting_summary: Dict, alerts: List, config: LeafDiseaseDetectionConfig,
413
+ frame_number: Optional[int] = None, stream_info: Optional[Dict[str, Any]] = None) -> List[
414
+ Dict]:
415
+ """Generate structured events for the output format with frame-based keys."""
416
+ from datetime import datetime, timezone
417
+
418
+ # Use frame number as key, fallback to 'current_frame' if not available
419
+ frame_key = str(frame_number) if frame_number is not None else "current_frame"
420
+ events = [{frame_key: []}]
421
+ frame_events = events[0][frame_key]
422
+ total_detections = counting_summary.get("total_count", 0)
423
+
424
+ if total_detections > 0:
425
+ # Determine event level based on thresholds
426
+ level = "info"
427
+ intensity = 5.0
428
+ if config.alert_config and config.alert_config.count_thresholds:
429
+ threshold = config.alert_config.count_thresholds.get("all", 15)
430
+ intensity = min(10.0, (total_detections / threshold) * 10)
431
+
432
+ if intensity >= 7:
433
+ level = "critical"
434
+ elif intensity >= 5:
435
+ level = "warning"
436
+ else:
437
+ level = "info"
438
+ else:
439
+ if total_detections > 25:
440
+ level = "critical"
441
+ intensity = 9.0
442
+ elif total_detections > 15:
443
+ level = "warning"
444
+ intensity = 7.0
445
+ else:
446
+ level = "info"
447
+ intensity = min(10.0, total_detections / 3.0)
448
+
449
+ # Generate human text in new format
450
+ human_text_lines = ["EVENTS DETECTED:"]
451
+ human_text_lines.append(f" - {total_detections} detected [INFO]")
452
+ human_text = "\n".join(human_text_lines)
453
+
454
+ event = {
455
+ "type": "leaf_disease_detection",
456
+ "stream_time": datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S UTC"),
457
+ "level": level,
458
+ "intensity": round(intensity, 1),
459
+ "config": {
460
+ "min_value": 0,
461
+ "max_value": 10,
462
+ "level_settings": {"info": 2, "warning": 5, "critical": 7}
463
+ },
464
+ "application_name": "leaf disease detection System",
465
+ "application_version": "1.2",
466
+ "location_info": None,
467
+ "human_text": human_text
468
+ }
469
+ frame_events.append(event)
470
+
471
+ # Add alert events
472
+ for alert in alerts:
473
+ total_detections = counting_summary.get("total_count", 0)
474
+ intensity_message = "ALERT: Low congestion in the scene"
475
+ if config.alert_config and config.alert_config.count_thresholds:
476
+ threshold = config.alert_config.count_thresholds.get("all", 15)
477
+ percentage = (total_detections / threshold) * 100 if threshold > 0 else 0
478
+ if percentage < 20:
479
+ intensity_message = "ALERT: Low congestion in the scene"
480
+ elif percentage <= 50:
481
+ intensity_message = "ALERT: Moderate congestion in the scene"
482
+ elif percentage <= 70:
483
+ intensity_message = "ALERT: Heavy congestion in the scene"
484
+ else:
485
+ intensity_message = "ALERT: Severe congestion in the scene"
486
+ else:
487
+ if total_detections > 15:
488
+ intensity_message = "ALERT: Heavy congestion in the scene"
489
+ elif total_detections == 1:
490
+ intensity_message = "ALERT: Low congestion in the scene"
491
+ else:
492
+ intensity_message = "ALERT: Moderate congestion in the scene"
493
+
494
+ alert_event = {
495
+ "type": alert.get("type", "congestion_alert"),
496
+ "stream_time": datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S UTC"),
497
+ "level": alert.get("severity", "warning"),
498
+ "intensity": 8.0,
499
+ "config": {
500
+ "min_value": 0,
501
+ "max_value": 10,
502
+ "level_settings": {"info": 2, "warning": 5, "critical": 7}
503
+ },
504
+ "application_name": "Congestion Alert System",
505
+ "application_version": "1.2",
506
+ "location_info": alert.get("zone"),
507
+ "human_text": f"{datetime.now(timezone.utc).strftime('%Y-%m-%d-%H:%M:%S UTC')} : {intensity_message}"
508
+ }
509
+ frame_events.append(alert_event)
510
+
511
+ return events
512
+
513
+ def _generate_tracking_stats(
514
+ self,
515
+ counting_summary: Dict,
516
+ insights: List[str],
517
+ summary: str,
518
+ config: LeafDiseaseDetectionConfig,
519
+ frame_number: Optional[int] = None,
520
+ stream_info: Optional[Dict[str, Any]] = None
521
+ ) -> List[Dict]:
522
+ """Generate structured tracking stats for the output format with frame-based keys, including track_ids_info."""
523
+ frame_key = str(frame_number) if frame_number is not None else "current_frame"
524
+ tracking_stats = [{frame_key: []}]
525
+ frame_tracking_stats = tracking_stats[0][frame_key]
526
+
527
+ total_detections = counting_summary.get("total_count", 0)
528
+ total_counts = counting_summary.get("total_counts", {})
529
+ cumulative_total = sum(total_counts.values()) if total_counts else 0
530
+ per_category_count = counting_summary.get("per_category_count", {})
531
+
532
+ track_ids_info = self._get_track_ids_info(counting_summary.get("detections", []))
533
+
534
+ current_timestamp = self._get_current_timestamp_str(stream_info)
535
+ start_timestamp = self._get_start_timestamp_str(stream_info)
536
+
537
+ human_text_lines = []
538
+
539
+ # CURRENT FRAME section
540
+ human_text_lines.append(f"CURRENT FRAME @ {current_timestamp}:")
541
+ if total_detections > 0:
542
+ category_counts = [f"{count} {cat}" for cat, count in per_category_count.items()]
543
+ if len(category_counts) == 1:
544
+ detection_text = category_counts[0] + " detected"
545
+ elif len(category_counts) == 2:
546
+ detection_text = f"{category_counts[0]} and {category_counts[1]} detected"
547
+ else:
548
+ detection_text = f"{', '.join(category_counts[:-1])}, and {category_counts[-1]} detected"
549
+ human_text_lines.append(f"\t- {detection_text}")
550
+ else:
551
+ human_text_lines.append(f"\t- No detections")
552
+
553
+ human_text_lines.append("") # spacing
554
+
555
+ # TOTAL SINCE section
556
+ human_text_lines.append(f"TOTAL SINCE {start_timestamp}:")
557
+ human_text_lines.append(f"\t- Total Detected: {cumulative_total}")
558
+ # Add category-wise counts
559
+ if total_counts:
560
+ for cat, count in total_counts.items():
561
+ if count > 0: # Only include categories with non-zero counts
562
+ human_text_lines.append(f"\t- {cat}: {count}")
563
+
564
+ human_text = "\n".join(human_text_lines)
565
+
566
+ tracking_stat = {
567
+ "type": "leaf_disease_detection",
568
+ "category": "agriculture",
569
+ "count": total_detections,
570
+ "insights": insights,
571
+ "summary": summary,
572
+ "timestamp": datetime.now(timezone.utc).strftime('%Y-%m-%d-%H:%M:%S UTC'),
573
+ "human_text": human_text,
574
+ "track_ids_info": track_ids_info,
575
+ "global_frame_offset": getattr(self, '_global_frame_offset', 0),
576
+ "local_frame_id": frame_key,
577
+ "detections": counting_summary.get("detections", []) # Added line to include detections
578
+ }
579
+
580
+ frame_tracking_stats.append(tracking_stat)
581
+ return tracking_stats
582
+
583
+ def _count_categories(self, detections: list, config: LeafDiseaseDetectionConfig) -> dict:
584
+ """
585
+ Count the number of detections per category and return a summary dict.
586
+ The detections list is expected to have 'track_id' (from tracker), 'category', 'bounding_box', etc.
587
+ Output structure will include 'track_id' for each detection as per AdvancedTracker output.
588
+ """
589
+ counts = {}
590
+ for det in detections:
591
+ cat = det.get('category', 'unknown')
592
+ counts[cat] = counts.get(cat, 0) + 1
593
+ # Each detection dict will now include 'track_id' (and possibly 'frame_id')
594
+ return {
595
+ "total_count": sum(counts.values()),
596
+ "per_category_count": counts,
597
+ "detections": [
598
+ {
599
+ "bounding_box": det.get("bounding_box"),
600
+ "category": det.get("category"),
601
+ "confidence": det.get("confidence"),
602
+ "track_id": det.get("track_id"),
603
+ "frame_id": det.get("frame_id")
604
+ }
605
+ for det in detections
606
+ ]
607
+ }
608
+
609
+ # Human-friendly display names for categories
610
+ CATEGORY_DISPLAY ={
611
+ "Apple Black Rod": "apple_black_rod",
612
+ "Apple Healthy": "apple_healthy",
613
+ "Cherry Healthy": "cherry_healthy",
614
+ "Grape Healthy": "grape_healthy",
615
+ "Grape Leaf Blight": "grape_leaf_blight",
616
+ "Grape Esca": "grape_esca",
617
+ "Cedar Apple Rust": "cedar_apple_rust",
618
+ "Cherry Powdery Mildew": "cherry_powdery_mildew",
619
+ "Grape Black Rot": "grape_black_rot",
620
+ "Apple Scab": "apple_scab"
621
+ }
622
+
623
+
624
+ def _generate_insights(self, summary: dict, config: LeafDiseaseDetectionConfig) -> List[str]:
625
+ """
626
+ Generate human-readable insights for each category.
627
+ """
628
+ insights = []
629
+ per_cat = summary.get("per_category_count", {})
630
+ total_detections = summary.get("total_count", 0)
631
+
632
+ if total_detections == 0:
633
+ insights.append("No detections in the scene")
634
+ return insights
635
+ insights.append(f"EVENT: Detected {total_detections} in the scene")
636
+ # Intensity calculation based on threshold percentage
637
+ intensity_threshold = None
638
+ if (config.alert_config and
639
+ config.alert_config.count_thresholds and
640
+ "all" in config.alert_config.count_thresholds):
641
+ intensity_threshold = config.alert_config.count_thresholds["all"]
642
+
643
+ if intensity_threshold is not None:
644
+ # Calculate percentage relative to threshold
645
+ percentage = (total_detections / intensity_threshold) * 100
646
+
647
+ if percentage < 20:
648
+ insights.append(f"INTENSITY: Low congestion in the scene ({percentage:.1f}% of capacity)")
649
+ elif percentage <= 50:
650
+ insights.append(f"INTENSITY: Moderate congestion in the scene ({percentage:.1f}% of capacity)")
651
+ elif percentage <= 70:
652
+ insights.append(f"INTENSITY: Heavy congestion in the scene ({percentage:.1f}% of capacity)")
653
+ else:
654
+ insights.append(f"INTENSITY: Severe congestion in the scene ({percentage:.1f}% of capacity)")
655
+
656
+
657
+ for cat, count in per_cat.items():
658
+ display = self.CATEGORY_DISPLAY.get(cat, cat)
659
+ insights.append(f"{display}:{count}")
660
+ return insights
661
+
662
+ def _check_alerts(self, summary: dict, config: LeafDiseaseDetectionConfig) -> List[Dict]:
663
+ """
664
+ Check if any alert thresholds are exceeded and return alert dicts.
665
+ """
666
+ alerts = []
667
+ if not config.alert_config:
668
+ return alerts
669
+ total = summary.get("total_count", 0)
670
+ if config.alert_config.count_thresholds:
671
+ for category, threshold in config.alert_config.count_thresholds.items():
672
+ if category == "all" and total >= threshold:
673
+ timestamp = datetime.now(timezone.utc).strftime('%Y-%m-%d-%H:%M:%S UTC')
674
+ alert_description = f"detections count ({total}) exceeds threshold ({threshold})"
675
+ alerts.append({
676
+ "type": "count_threshold",
677
+ "severity": "warning",
678
+ "message": f"Total detections count ({total}) exceeds threshold ({threshold})",
679
+ "category": category,
680
+ "current_count": total,
681
+ "threshold": threshold
682
+ })
683
+ elif category in summary.get("per_category_count", {}):
684
+ count = summary.get("per_category_count", {})[category]
685
+ if count >= threshold:
686
+ alerts.append({
687
+ "type": "count_threshold",
688
+ "severity": "warning",
689
+ "message": f"{category} count ({count}) exceeds threshold ({threshold})",
690
+ "category": category,
691
+ "current_count": count,
692
+ "threshold": threshold
693
+ })
694
+ return alerts
695
+
696
+ def _extract_predictions(self, detections: list) -> List[Dict[str, Any]]:
697
+ """
698
+ Extract prediction details for output (category, confidence, bounding box).
699
+ """
700
+ return [
701
+ {
702
+ "category": det.get("category", "unknown"),
703
+ "confidence": det.get("confidence", 0.0),
704
+ "bounding_box": det.get("bounding_box", {})
705
+ }
706
+ for det in detections
707
+ ]
708
+
709
+ def _generate_summary(self, summary: dict, alerts: List) -> str:
710
+ """
711
+ Generate a human_text string for the result, including per-category insights if available.
712
+ Adds a tab before each label for better formatting.
713
+ Also always includes the cumulative count so far.
714
+ """
715
+ total = summary.get("total_count", 0)
716
+ per_cat = summary.get("per_category_count", {})
717
+ cumulative = summary.get("total_counts", {})
718
+ cumulative_total = sum(cumulative.values()) if cumulative else 0
719
+ lines = []
720
+ if total > 0:
721
+ lines.append(f"{total} detections")
722
+ if per_cat:
723
+ lines.append("detections:")
724
+ for cat, count in per_cat.items():
725
+ lines.append(f"\t{cat}:{count}")
726
+ else:
727
+ lines.append("No detections")
728
+ lines.append(f"Total detections: {cumulative_total}")
729
+ if alerts:
730
+ lines.append(f"{len(alerts)} alert(s)")
731
+ return "\n".join(lines)
732
+
733
+ # ------------------------------------------------------------------ #
734
+ # Canonical ID helpers #
735
+ # ------------------------------------------------------------------ #
736
+ def _compute_iou(self, box1: Any, box2: Any) -> float:
737
+ """Compute IoU between two bounding boxes which may be dicts or lists.
738
+ Falls back to 0 when insufficient data is available."""
739
+
740
+ # Helper to convert bbox (dict or list) to [x1, y1, x2, y2]
741
+ def _bbox_to_list(bbox):
742
+ if bbox is None:
743
+ return []
744
+ if isinstance(bbox, list):
745
+ return bbox[:4] if len(bbox) >= 4 else []
746
+ if isinstance(bbox, dict):
747
+ if "xmin" in bbox:
748
+ return [bbox["xmin"], bbox["ymin"], bbox["xmax"], bbox["ymax"]]
749
+ if "x1" in bbox:
750
+ return [bbox["x1"], bbox["y1"], bbox["x2"], bbox["y2"]]
751
+ # Fallback: first four numeric values
752
+ values = [v for v in bbox.values() if isinstance(v, (int, float))]
753
+ return values[:4] if len(values) >= 4 else []
754
+ return []
755
+
756
+ l1 = _bbox_to_list(box1)
757
+ l2 = _bbox_to_list(box2)
758
+ if len(l1) < 4 or len(l2) < 4:
759
+ return 0.0
760
+ x1_min, y1_min, x1_max, y1_max = l1
761
+ x2_min, y2_min, x2_max, y2_max = l2
762
+
763
+ # Ensure correct order
764
+ x1_min, x1_max = min(x1_min, x1_max), max(x1_min, x1_max)
765
+ y1_min, y1_max = min(y1_min, y1_max), max(y1_min, y1_max)
766
+ x2_min, x2_max = min(x2_min, x2_max), max(x2_min, x2_max)
767
+ y2_min, y2_max = min(y2_min, y2_max), max(y2_min, y2_max)
768
+
769
+ inter_x_min = max(x1_min, x2_min)
770
+ inter_y_min = max(y1_min, y2_min)
771
+ inter_x_max = min(x1_max, x2_max)
772
+ inter_y_max = min(y1_max, y2_max)
773
+
774
+ inter_w = max(0.0, inter_x_max - inter_x_min)
775
+ inter_h = max(0.0, inter_y_max - inter_y_min)
776
+ inter_area = inter_w * inter_h
777
+
778
+ area1 = (x1_max - x1_min) * (y1_max - y1_min)
779
+ area2 = (x2_max - x2_min) * (y2_max - y2_min)
780
+ union_area = area1 + area2 - inter_area
781
+
782
+ return (inter_area / union_area) if union_area > 0 else 0.0
783
+
784
+ def _merge_or_register_track(self, raw_id: Any, bbox: Any) -> Any:
785
+ """Return a stable canonical ID for a raw tracker ID, merging fragmented
786
+ tracks when IoU and temporal constraints indicate they represent the
787
+ same physical."""
788
+ if raw_id is None or bbox is None:
789
+ # Nothing to merge
790
+ return raw_id
791
+
792
+ now = time.time()
793
+
794
+ # Fast path – raw_id already mapped
795
+ if raw_id in self._track_aliases:
796
+ canonical_id = self._track_aliases[raw_id]
797
+ track_info = self._canonical_tracks.get(canonical_id)
798
+ if track_info is not None:
799
+ track_info["last_bbox"] = bbox
800
+ track_info["last_update"] = now
801
+ track_info["raw_ids"].add(raw_id)
802
+ return canonical_id
803
+
804
+ # Attempt to merge with an existing canonical track
805
+ for canonical_id, info in self._canonical_tracks.items():
806
+ # Only consider recently updated tracks
807
+ if now - info["last_update"] > self._track_merge_time_window:
808
+ continue
809
+ iou = self._compute_iou(bbox, info["last_bbox"])
810
+ if iou >= self._track_merge_iou_threshold:
811
+ # Merge
812
+ self._track_aliases[raw_id] = canonical_id
813
+ info["last_bbox"] = bbox
814
+ info["last_update"] = now
815
+ info["raw_ids"].add(raw_id)
816
+ return canonical_id
817
+
818
+ # No match – register new canonical track
819
+ canonical_id = raw_id
820
+ self._track_aliases[raw_id] = canonical_id
821
+ self._canonical_tracks[canonical_id] = {
822
+ "last_bbox": bbox,
823
+ "last_update": now,
824
+ "raw_ids": {raw_id},
825
+ }
826
+ return canonical_id
827
+
828
+ def _format_timestamp(self, timestamp: float) -> str:
829
+ """Format a timestamp for human-readable output."""
830
+ return datetime.fromtimestamp(timestamp, timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')
831
+
832
+ def _get_tracking_start_time(self) -> str:
833
+ """Get the tracking start time, formatted as a string."""
834
+ if self._tracking_start_time is None:
835
+ return "N/A"
836
+ return self._format_timestamp(self._tracking_start_time)
837
+
838
+ def _set_tracking_start_time(self) -> None:
839
+ """Set the tracking start time to the current time."""
840
+ self._tracking_start_time = time.time()