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,1006 @@
1
+ from typing import Any, Dict, List, Optional
2
+ from dataclasses import asdict
3
+ import time
4
+ from datetime import datetime, timezone
5
+ import copy # Added for deep copying detections to preserve original masks
6
+
7
+ from ..core.base import BaseProcessor, ProcessingContext, ProcessingResult, ConfigProtocol, ResultFormat
8
+ from ..utils import (
9
+ filter_by_confidence,
10
+ filter_by_categories,
11
+ apply_category_mapping,
12
+ count_objects_by_category,
13
+ count_objects_in_zones,
14
+ calculate_counting_summary,
15
+ match_results_structure,
16
+ bbox_smoothing,
17
+ BBoxSmoothingConfig,
18
+ BBoxSmoothingTracker
19
+ )
20
+ from dataclasses import dataclass, field
21
+ from ..core.config import BaseConfig, AlertConfig, ZoneConfig
22
+
23
+
24
+ @dataclass
25
+ class FlowerConfig(BaseConfig):
26
+ """Configuration for Flower detection use case in Flower monitoring."""
27
+ # Smoothing configuration
28
+ enable_smoothing: bool = True
29
+ smoothing_algorithm: str = "observability" # "window" or "observability"
30
+ smoothing_window_size: int = 20
31
+ smoothing_cooldown_frames: int = 5
32
+ smoothing_confidence_range_factor: float = 0.5
33
+
34
+ #confidence thresholds
35
+ confidence_threshold: float = 0.6
36
+
37
+ usecase_categories: List[str] = field(
38
+ default_factory=lambda: ['pelargonium', 'purple_coneflower', 'love_in_the_mist', 'moon_orchid',
39
+ 'globe_thistle', 'sword_lily', 'fritillary', 'rose', 'petunia', 'lotus',
40
+ 'tree_poppy', 'giant_white_arum_lily', 'great_masterwort', 'grape_hyacinth',
41
+ 'trumpet_creeper', 'mallow', 'silverbush', 'passion_flower', 'water_lily',
42
+ 'pink-yellow_dahlia', 'morning_glory', 'watercress', 'primula', 'globe_flower',
43
+ 'pink_primrose', 'poinsettia', 'toad_lily', 'sweet_pea', 'tiger_lily', 'yellow_iris',
44
+ 'magnolia', 'wallflower', 'monkshood', 'spear_thistle', 'peruvian_lily', 'thorn_apple',
45
+ 'snapdragon', 'spring_crocus', 'geranium', 'gaura', 'windflower', 'ruby-lipped_cattleya',
46
+ 'king_protea', 'stemless_gentian', 'sunflower', 'pincushion_flower', 'prince_of_wales_feathers',
47
+ 'wild_pansy', 'siam_tulip', 'gazania', 'hibiscus', 'osteospermum', 'hard-leaved_pocket_orchid',
48
+ 'lenten_rose', 'red_ginger', 'japanese_anemone', 'tree_mallow', 'garden_phlox', 'sweet_william',
49
+ 'mexican_petunia', 'hippeastrum', 'orange_dahlia', 'mexican_aster', 'marigold', 'oxeye_daisy']
50
+ )
51
+
52
+ target_categories: List[str] = field(
53
+ default_factory=lambda: ['pelargonium', 'purple_coneflower', 'love_in_the_mist', 'moon_orchid',
54
+ 'globe_thistle', 'sword_lily', 'fritillary', 'rose', 'petunia', 'lotus',
55
+ 'tree_poppy', 'giant_white_arum_lily', 'great_masterwort', 'grape_hyacinth',
56
+ 'trumpet_creeper', 'mallow', 'silverbush', 'passion_flower', 'water_lily',
57
+ 'pink-yellow_dahlia', 'morning_glory', 'watercress', 'primula', 'globe_flower',
58
+ 'pink_primrose', 'poinsettia', 'toad_lily', 'sweet_pea', 'tiger_lily', 'yellow_iris',
59
+ 'magnolia', 'wallflower', 'monkshood', 'spear_thistle', 'peruvian_lily', 'thorn_apple',
60
+ 'snapdragon', 'spring_crocus', 'geranium', 'gaura', 'windflower', 'ruby-lipped_cattleya',
61
+ 'king_protea', 'stemless_gentian', 'sunflower', 'pincushion_flower', 'prince_of_wales_feathers',
62
+ 'wild_pansy', 'siam_tulip', 'gazania', 'hibiscus', 'osteospermum', 'hard-leaved_pocket_orchid',
63
+ 'lenten_rose', 'red_ginger', 'japanese_anemone', 'tree_mallow', 'garden_phlox', 'sweet_william',
64
+ 'mexican_petunia', 'hippeastrum', 'orange_dahlia', 'mexican_aster', 'marigold', 'oxeye_daisy']
65
+ )
66
+
67
+ alert_config: Optional[AlertConfig] = None
68
+
69
+ index_to_category: Optional[Dict[int, str]] = field(
70
+ default_factory=lambda: {
71
+ i: cat for i, cat in enumerate([
72
+ 'pelargonium', 'purple_coneflower', 'love_in_the_mist', 'moon_orchid',
73
+ 'globe_thistle', 'sword_lily', 'fritillary', 'rose', 'petunia', 'lotus',
74
+ 'tree_poppy', 'giant_white_arum_lily', 'great_masterwort', 'grape_hyacinth',
75
+ 'trumpet_creeper', 'mallow', 'silverbush', 'passion_flower', 'water_lily',
76
+ 'pink-yellow_dahlia', 'morning_glory', 'watercress', 'primula', 'globe_flower',
77
+ 'pink_primrose', 'poinsettia', 'toad_lily', 'sweet_pea', 'tiger_lily', 'yellow_iris',
78
+ 'magnolia', 'wallflower', 'monkshood', 'spear_thistle', 'peruvian_lily', 'thorn_apple',
79
+ 'snapdragon', 'spring_crocus', 'geranium', 'gaura', 'windflower', 'ruby-lipped_cattleya',
80
+ 'king_protea', 'stemless_gentian', 'sunflower', 'pincushion_flower', 'prince_of_wales_feathers',
81
+ 'wild_pansy', 'siam_tulip', 'gazania', 'hibiscus', 'osteospermum', 'hard-leaved_pocket_orchid',
82
+ 'lenten_rose', 'red_ginger', 'japanese_anemone', 'tree_mallow', 'garden_phlox', 'sweet_william',
83
+ 'mexican_petunia', 'hippeastrum', 'orange_dahlia', 'mexican_aster', 'marigold', 'oxeye_daisy'
84
+ ])
85
+ }
86
+ )
87
+
88
+
89
+ class FlowerUseCase(BaseProcessor):
90
+
91
+ # Human-friendly display names for categories
92
+ CATEGORY_DISPLAY = {
93
+ 'pelargonium': 'Pelargonium',
94
+ 'purple_coneflower': 'Purple Coneflower',
95
+ 'love_in_the_mist': 'Love in the Mist',
96
+ 'moon_orchid': 'Moon Orchid',
97
+ 'globe_thistle': 'Globe Thistle',
98
+ 'sword_lily': 'Sword Lily',
99
+ 'fritillary': 'Fritillary',
100
+ 'rose': 'Rose',
101
+ 'petunia': 'Petunia',
102
+ 'lotus': 'Lotus',
103
+ 'tree_poppy': 'Tree Poppy',
104
+ 'giant_white_arum_lily': 'Giant White Arum Lily',
105
+ 'great_masterwort': 'Great Masterwort',
106
+ 'grape_hyacinth': 'Grape Hyacinth',
107
+ 'trumpet_creeper': 'Trumpet Creeper',
108
+ 'mallow': 'Mallow',
109
+ 'silverbush': 'Silverbush',
110
+ 'passion_flower': 'Passion Flower',
111
+ 'water_lily': 'Water Lily',
112
+ 'pink-yellow_dahlia': 'Pink-Yellow Dahlia',
113
+ 'morning_glory': 'Morning Glory',
114
+ 'watercress': 'Watercress',
115
+ 'primula': 'Primula',
116
+ 'globe_flower': 'Globe Flower',
117
+ 'pink_primrose': 'Pink Primrose',
118
+ 'poinsettia': 'Poinsettia',
119
+ 'toad_lily': 'Toad Lily',
120
+ 'sweet_pea': 'Sweet Pea',
121
+ 'tiger_lily': 'Tiger Lily',
122
+ 'yellow_iris': 'Yellow Iris',
123
+ 'magnolia': 'Magnolia',
124
+ 'wallflower': 'Wallflower',
125
+ 'monkshood': 'Monkshood',
126
+ 'spear_thistle': 'Spear Thistle',
127
+ 'peruvian_lily': 'Peruvian Lily',
128
+ 'thorn_apple': 'Thorn Apple',
129
+ 'snapdragon': 'Snapdragon',
130
+ 'spring_crocus': 'Spring Crocus',
131
+ 'geranium': 'Geranium',
132
+ 'gaura': 'Gaura',
133
+ 'windflower': 'Windflower',
134
+ 'ruby-lipped_cattleya': 'Ruby-lipped Cattleya',
135
+ 'king_protea': 'King Protea',
136
+ 'stemless_gentian': 'Stemless Gentian',
137
+ 'sunflower': 'Sunflower',
138
+ 'pincushion_flower': 'Pincushion Flower',
139
+ 'prince_of_wales_feathers': 'Prince of Wales Feathers',
140
+ 'wild_pansy': 'Wild Pansy',
141
+ 'siam_tulip': 'Siam Tulip',
142
+ 'gazania': 'Gazania',
143
+ 'hibiscus': 'Hibiscus',
144
+ 'osteospermum': 'Osteospermum',
145
+ 'hard-leaved_pocket_orchid': 'Hard-leaved Pocket Orchid',
146
+ 'lenten_rose': 'Lenten Rose',
147
+ 'red_ginger': 'Red Ginger',
148
+ 'japanese_anemone': 'Japanese Anemone',
149
+ 'tree_mallow': 'Tree Mallow',
150
+ 'garden_phlox': 'Garden Phlox',
151
+ 'sweet_william': 'Sweet William',
152
+ 'mexican_petunia': 'Mexican Petunia',
153
+ 'hippeastrum': 'Hippeastrum',
154
+ 'orange_dahlia': 'Orange Dahlia',
155
+ 'mexican_aster': 'Mexican Aster',
156
+ 'marigold': 'Marigold',
157
+ 'oxeye_daisy': 'Oxeye Daisy',
158
+ }
159
+ def __init__(self):
160
+ super().__init__("flower_segmentation")
161
+ self.category = "agriculture"
162
+
163
+ # List of categories to track
164
+ self.target_categories = ['pelargonium', 'purple_coneflower', 'love_in_the_mist', 'moon_orchid',
165
+ 'globe_thistle', 'sword_lily', 'fritillary', 'rose', 'petunia', 'lotus',
166
+ 'tree_poppy', 'giant_white_arum_lily', 'great_masterwort', 'grape_hyacinth',
167
+ 'trumpet_creeper', 'mallow', 'silverbush', 'passion_flower', 'water_lily',
168
+ 'pink-yellow_dahlia', 'morning_glory', 'watercress', 'primula', 'globe_flower',
169
+ 'pink_primrose', 'poinsettia', 'toad_lily', 'sweet_pea', 'tiger_lily', 'yellow_iris',
170
+ 'magnolia', 'wallflower', 'monkshood', 'spear_thistle', 'peruvian_lily', 'thorn_apple',
171
+ 'snapdragon', 'spring_crocus', 'geranium', 'gaura', 'windflower', 'ruby-lipped_cattleya',
172
+ 'king_protea', 'stemless_gentian', 'sunflower', 'pincushion_flower', 'prince_of_wales_feathers',
173
+ 'wild_pansy', 'siam_tulip', 'gazania', 'hibiscus', 'osteospermum', 'hard-leaved_pocket_orchid',
174
+ 'lenten_rose', 'red_ginger', 'japanese_anemone', 'tree_mallow', 'garden_phlox', 'sweet_william',
175
+ 'mexican_petunia', 'hippeastrum', 'orange_dahlia', 'mexican_aster', 'marigold', 'oxeye_daisy']
176
+
177
+ self.CASE_TYPE: Optional[str] = 'flower_segmentation'
178
+ self.CASE_VERSION: Optional[str] = '1.3'
179
+
180
+ # Initialize smoothing tracker
181
+ self.smoothing_tracker = None
182
+
183
+ # Initialize advanced tracker (will be created on first use)
184
+ self.tracker = None
185
+
186
+ # Initialize tracking state variables
187
+ self._total_frame_counter = 0
188
+ self._global_frame_offset = 0
189
+
190
+ # Track start time for "TOTAL SINCE" calculation
191
+ self._tracking_start_time = None
192
+
193
+ # ------------------------------------------------------------------ #
194
+ # Canonical tracking aliasing to avoid duplicate counts #
195
+ # ------------------------------------------------------------------ #
196
+ # Maps raw tracker-generated IDs to stable canonical IDs that persist
197
+ # even if the underlying tracker re-assigns a new ID after a short
198
+ # interruption. This mirrors the logic used in people_counting to
199
+ # provide accurate unique counting.
200
+ self._track_aliases: Dict[Any, Any] = {}
201
+ self._canonical_tracks: Dict[Any, Dict[str, Any]] = {}
202
+ # Tunable parameters – adjust if necessary for specific scenarios
203
+ self._track_merge_iou_threshold: float = 0.05 # IoU ≥ 0.05 →
204
+ self._track_merge_time_window: float = 7.0 # seconds within which to merge
205
+
206
+ self._ascending_alert_list: List[int] = []
207
+ self.current_incident_end_timestamp: str = "N/A"
208
+
209
+ def process(self, data: Any, config: ConfigProtocol, context: Optional[ProcessingContext] = None,
210
+ stream_info: Optional[Dict[str, Any]] = None) -> ProcessingResult:
211
+ """
212
+ Main entry point for post-processing.
213
+ Applies category mapping, smoothing, counting, alerting, and summary generation.
214
+ Returns a ProcessingResult with all relevant outputs.
215
+ """
216
+ start_time = time.time()
217
+ # Ensure config is correct type
218
+ if not isinstance(config, FlowerConfig):
219
+ return self.create_error_result("Invalid config type", usecase=self.name, category=self.category,
220
+ context=context)
221
+ if context is None:
222
+ context = ProcessingContext()
223
+
224
+ # Detect input format and store in context
225
+ input_format = match_results_structure(data)
226
+ context.input_format = input_format
227
+ context.confidence_threshold = config.confidence_threshold
228
+
229
+ # Step 1: Confidence filtering
230
+ if config.confidence_threshold is not None:
231
+ processed_data = filter_by_confidence(data, config.confidence_threshold)
232
+ else:
233
+ processed_data = data
234
+ self.logger.debug(f"Did not apply confidence filtering with threshold since nothing was provided")
235
+
236
+ # Step 2: Apply category mapping if provided
237
+ if config.index_to_category:
238
+ processed_data = apply_category_mapping(processed_data, config.index_to_category)
239
+
240
+ # Step 3: Category filtering
241
+ if config.target_categories:
242
+ processed_data = [d for d in processed_data if d.get('category') in self.target_categories]
243
+
244
+ # Step 4: Apply bbox smoothing if enabled
245
+ # Deep-copy detections so that we preserve the original masks before any
246
+ # smoothing/tracking logic potentially removes them.
247
+ raw_processed_data = [copy.deepcopy(det) for det in processed_data]
248
+ if config.enable_smoothing:
249
+ if self.smoothing_tracker is None:
250
+ smoothing_config = BBoxSmoothingConfig(
251
+ smoothing_algorithm=config.smoothing_algorithm,
252
+ window_size=config.smoothing_window_size,
253
+ cooldown_frames=config.smoothing_cooldown_frames,
254
+ confidence_threshold=config.confidence_threshold,
255
+ confidence_range_factor=config.smoothing_confidence_range_factor,
256
+ enable_smoothing=True
257
+ )
258
+ self.smoothing_tracker = BBoxSmoothingTracker(smoothing_config)
259
+
260
+ processed_data = bbox_smoothing(processed_data, self.smoothing_tracker.config, self.smoothing_tracker)
261
+ # Restore masks after smoothing
262
+
263
+ # Step 5: Advanced tracking (BYTETracker-like)
264
+ try:
265
+ from ..advanced_tracker import AdvancedTracker
266
+ from ..advanced_tracker.config import TrackerConfig
267
+
268
+ # Create tracker instance if it doesn't exist (preserves state across frames)
269
+ if self.tracker is None:
270
+ tracker_config = TrackerConfig()
271
+ self.tracker = AdvancedTracker(tracker_config)
272
+ self.logger.info("Initialized AdvancedTracker for Monitoring and tracking")
273
+
274
+ processed_data = self.tracker.update(processed_data)
275
+ except Exception as e:
276
+ # If advanced tracker fails, fallback to unsmoothed detections
277
+ self.logger.warning(f"AdvancedTracker failed: {e}")
278
+
279
+ # Update tracking state for total count per label
280
+ self._update_tracking_state(processed_data)
281
+
282
+ # ------------------------------------------------------------------ #
283
+ # Re-attach segmentation masks that were present in the original input
284
+ # but may have been stripped during smoothing/tracking. We match each
285
+ # processed detection back to the raw detection with the highest IoU
286
+ # and copy over its "masks" field (if available).
287
+ # ------------------------------------------------------------------ #
288
+ processed_data = self._attach_masks_to_detections(processed_data, raw_processed_data)
289
+
290
+ # Update frame counter
291
+ self._total_frame_counter += 1
292
+
293
+ # Extract frame information from stream_info
294
+ frame_number = None
295
+ if stream_info:
296
+ input_settings = stream_info.get("input_settings", {})
297
+ start_frame = input_settings.get("start_frame")
298
+ end_frame = input_settings.get("end_frame")
299
+ # If start and end frame are the same, it's a single frame
300
+ if start_frame is not None and end_frame is not None and start_frame == end_frame:
301
+ frame_number = start_frame
302
+
303
+ # Compute summaries and alerts
304
+ general_counting_summary = calculate_counting_summary(data)
305
+ counting_summary = self._count_categories(processed_data, config)
306
+ # Add total unique counts after tracking using only local state
307
+ total_counts = self.get_total_counts()
308
+ counting_summary['total_counts'] = total_counts
309
+
310
+ alerts = self._check_alerts(counting_summary, frame_number, config)
311
+ predictions = self._extract_predictions(processed_data)
312
+
313
+ # Step: Generate structured events and tracking stats with frame-based keys
314
+ incidents_list = self._generate_incidents(counting_summary, alerts, config, frame_number, stream_info)
315
+ tracking_stats_list = self._generate_tracking_stats(counting_summary, alerts, config, frame_number,stream_info)
316
+ # business_analytics_list = self._generate_business_analytics(counting_summary, alerts, config, frame_number, stream_info, is_empty=False)
317
+ business_analytics_list = []
318
+ summary_list = self._generate_summary(counting_summary, incidents_list, tracking_stats_list, business_analytics_list, alerts)
319
+
320
+ # Extract frame-based dictionaries from the lists
321
+ incidents = incidents_list[0] if incidents_list else {}
322
+ tracking_stats = tracking_stats_list[0] if tracking_stats_list else {}
323
+ business_analytics = business_analytics_list[0] if business_analytics_list else {}
324
+ summary = summary_list[0] if summary_list else {}
325
+ agg_summary = {str(frame_number): {
326
+ "incidents": incidents,
327
+ "tracking_stats": tracking_stats,
328
+ "business_analytics": business_analytics,
329
+ "alerts": alerts,
330
+ "human_text": summary}
331
+ }
332
+
333
+ context.mark_completed()
334
+
335
+ # Build result object following the new pattern
336
+
337
+ result = self.create_result(
338
+ data={"agg_summary": agg_summary},
339
+ usecase=self.name,
340
+ category=self.category,
341
+ context=context
342
+ )
343
+
344
+ return result
345
+
346
+ def _check_alerts(self, summary: dict, frame_number:Any, config: FlowerConfig) -> List[Dict]:
347
+ """
348
+ Check if any alert thresholds are exceeded and return alert dicts.
349
+ """
350
+ def get_trend(data, lookback=900, threshold=0.6):
351
+ '''
352
+ Determine if the trend is ascending or descending based on actual value progression.
353
+ Now works with values 0,1,2,3 (not just binary).
354
+ '''
355
+ window = data[-lookback:] if len(data) >= lookback else data
356
+ if len(window) < 2:
357
+ return True # not enough data to determine trend
358
+ increasing = 0
359
+ total = 0
360
+ for i in range(1, len(window)):
361
+ if window[i] >= window[i - 1]:
362
+ increasing += 1
363
+ total += 1
364
+ ratio = increasing / total
365
+ if ratio >= threshold:
366
+ return True
367
+ elif ratio <= (1 - threshold):
368
+ return False
369
+
370
+ frame_key = str(frame_number) if frame_number is not None else "current_frame"
371
+ alerts = []
372
+ total_detections = summary.get("total_count", 0) #CURRENT combined total count of all classes
373
+ total_counts_dict = summary.get("total_counts", {}) #TOTAL cumulative counts per class
374
+ cumulative_total = sum(total_counts_dict.values()) if total_counts_dict else 0 #TOTAL combined cumulative count
375
+ per_category_count = summary.get("per_category_count", {}) #CURRENT count per class
376
+
377
+ if not config.alert_config:
378
+ return alerts
379
+
380
+ total = summary.get("total_count", 0)
381
+ #self._ascending_alert_list
382
+ if hasattr(config.alert_config, 'count_thresholds') and config.alert_config.count_thresholds:
383
+
384
+ for category, threshold in config.alert_config.count_thresholds.items():
385
+ if category == "all" and total > threshold:
386
+
387
+ alerts.append({
388
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
389
+ "alert_id": "alert_"+category+'_'+frame_key,
390
+ "incident_category": self.CASE_TYPE,
391
+ "threshold_level": threshold,
392
+ "ascending": get_trend(self._ascending_alert_list, lookback=900, threshold=0.8),
393
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
394
+ getattr(config.alert_config, 'alert_value', ['JSON']) if hasattr(config.alert_config, 'alert_value') else ['JSON'])
395
+ }
396
+ })
397
+ elif category in summary.get("per_category_count", {}):
398
+ count = summary.get("per_category_count", {})[category]
399
+ if count > threshold: # Fixed logic: alert when EXCEEDING threshold
400
+ alerts.append({
401
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
402
+ "alert_id": "alert_"+category+'_'+frame_key,
403
+ "incident_category": self.CASE_TYPE,
404
+ "threshold_level": threshold,
405
+ "ascending": get_trend(self._ascending_alert_list, lookback=900, threshold=0.8),
406
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
407
+ getattr(config.alert_config, 'alert_value', ['JSON']) if hasattr(config.alert_config, 'alert_value') else ['JSON'])
408
+ }
409
+ })
410
+ else:
411
+ pass
412
+ return alerts
413
+
414
+ def _generate_incidents(self, counting_summary: Dict, alerts: List, config: FlowerConfig,
415
+ frame_number: Optional[int] = None, stream_info: Optional[Dict[str, Any]] = None) -> List[
416
+ Dict]:
417
+ """Generate structured events for the output format with frame-based keys."""
418
+
419
+ # Use frame number as key, fallback to 'current_frame' if not available
420
+ frame_key = str(frame_number) if frame_number is not None else "current_frame"
421
+ incidents=[]
422
+ total_detections = counting_summary.get("total_count", 0)
423
+ current_timestamp = self._get_current_timestamp_str(stream_info)
424
+ camera_info = self.get_camera_info_from_stream(stream_info)
425
+
426
+ self._ascending_alert_list = self._ascending_alert_list[-900:] if len(self._ascending_alert_list) > 900 else self._ascending_alert_list
427
+
428
+ if total_detections > 0:
429
+ # Determine event level based on thresholds
430
+ level = "low"
431
+ intensity = 5.0
432
+ start_timestamp = self._get_start_timestamp_str(stream_info)
433
+ if start_timestamp and self.current_incident_end_timestamp=='N/A':
434
+ self.current_incident_end_timestamp = 'Incident still active'
435
+ elif start_timestamp and self.current_incident_end_timestamp=='Incident still active':
436
+ if len(self._ascending_alert_list) >= 15 and sum(self._ascending_alert_list[-15:]) / 15 < 1.5:
437
+ self.current_incident_end_timestamp = current_timestamp
438
+ elif self.current_incident_end_timestamp!='Incident still active' and self.current_incident_end_timestamp!='N/A':
439
+ self.current_incident_end_timestamp = 'N/A'
440
+
441
+ if config.alert_config and config.alert_config.count_thresholds:
442
+ threshold = config.alert_config.count_thresholds.get("all", 15)
443
+ intensity = min(10.0, (total_detections / threshold) * 10)
444
+
445
+ if intensity >= 9:
446
+ level = "critical"
447
+ self._ascending_alert_list.append(3)
448
+ elif intensity >= 7:
449
+ level = "significant"
450
+ self._ascending_alert_list.append(2)
451
+ elif intensity >= 5:
452
+ level = "medium"
453
+ self._ascending_alert_list.append(1)
454
+ else:
455
+ level = "low"
456
+ self._ascending_alert_list.append(0)
457
+ else:
458
+ if total_detections > 30:
459
+ level = "critical"
460
+ intensity = 10.0
461
+ self._ascending_alert_list.append(3)
462
+ elif total_detections > 25:
463
+ level = "significant"
464
+ intensity = 9.0
465
+ self._ascending_alert_list.append(2)
466
+ elif total_detections > 15:
467
+ level = "medium"
468
+ intensity = 7.0
469
+ self._ascending_alert_list.append(1)
470
+ else:
471
+ level = "low"
472
+ intensity = min(10.0, total_detections / 3.0)
473
+ self._ascending_alert_list.append(0)
474
+
475
+ # Generate human text in new format
476
+ human_text_lines = [f"INCIDENTS DETECTED @ {current_timestamp}:"]
477
+ human_text_lines.append(f"\tSeverity Level: {(self.CASE_TYPE,level)}")
478
+ human_text = "\n".join(human_text_lines)
479
+
480
+ alert_settings=[]
481
+ if config.alert_config and hasattr(config.alert_config, 'alert_type'):
482
+ alert_settings.append({
483
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
484
+ "incident_category": self.CASE_TYPE,
485
+ "threshold_level": config.alert_config.count_thresholds if hasattr(config.alert_config, 'count_thresholds') else {},
486
+ "ascending": True,
487
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
488
+ getattr(config.alert_config, 'alert_value', ['JSON']) if hasattr(config.alert_config, 'alert_value') else ['JSON'])
489
+ }
490
+ })
491
+
492
+ event= self.create_incident(incident_id=self.CASE_TYPE+'_'+str(frame_number), incident_type=self.CASE_TYPE,
493
+ severity_level=level, human_text=human_text, camera_info=camera_info, alerts=alerts, alert_settings=alert_settings,
494
+ start_time=start_timestamp, end_time=self.current_incident_end_timestamp,
495
+ level_settings= {"low": 1, "medium": 3, "significant":4, "critical": 7})
496
+ incidents.append(event)
497
+
498
+ else:
499
+ self._ascending_alert_list.append(0)
500
+ incidents.append({})
501
+
502
+ return incidents
503
+
504
+ def _generate_tracking_stats(
505
+ self,
506
+ counting_summary: Dict,
507
+ alerts: Any,
508
+ config: FlowerConfig,
509
+ frame_number: Optional[int] = None,
510
+ stream_info: Optional[Dict[str, Any]] = None
511
+ ) -> List[Dict]:
512
+ """Generate structured tracking stats for the output format with frame-based keys, including track_ids_info and detections with masks."""
513
+ # frame_key = str(frame_number) if frame_number is not None else "current_frame"
514
+ # tracking_stats = [{frame_key: []}]
515
+ # frame_tracking_stats = tracking_stats[0][frame_key]
516
+ tracking_stats = []
517
+
518
+ total_detections = counting_summary.get("total_count", 0)
519
+ total_counts = counting_summary.get("total_counts", {})
520
+ cumulative_total = sum(total_counts.values()) if total_counts else 0
521
+ per_category_count = counting_summary.get("per_category_count", {})
522
+
523
+ track_ids_info = self._get_track_ids_info(counting_summary.get("detections", []))
524
+
525
+ current_timestamp = self._get_current_timestamp_str(stream_info, precision=False)
526
+ start_timestamp = self._get_start_timestamp_str(stream_info, precision=False)
527
+
528
+ # Create high precision timestamps for input_timestamp and reset_timestamp
529
+ high_precision_start_timestamp = self._get_current_timestamp_str(stream_info, precision=True)
530
+ high_precision_reset_timestamp = self._get_start_timestamp_str(stream_info, precision=True)
531
+
532
+ camera_info = self.get_camera_info_from_stream(stream_info)
533
+ human_text_lines = []
534
+
535
+ # CURRENT FRAME section
536
+ human_text_lines.append(f"CURRENT FRAME @ {current_timestamp}:")
537
+ if total_detections > 0:
538
+ category_counts = [f"{count} {cat}" for cat, count in per_category_count.items()]
539
+ if len(category_counts) == 1:
540
+ detection_text = category_counts[0] + " detected"
541
+ elif len(category_counts) == 2:
542
+ detection_text = f"{category_counts[0]} and {category_counts[1]} detected"
543
+ else:
544
+ detection_text = f"{', '.join(category_counts[:-1])}, and {category_counts[-1]} detected"
545
+ human_text_lines.append(f"\t- {detection_text}")
546
+ else:
547
+ human_text_lines.append(f"\t- No detections")
548
+
549
+ human_text_lines.append("") # spacing
550
+
551
+ # TOTAL SINCE section
552
+ human_text_lines.append(f"TOTAL SINCE {start_timestamp}:")
553
+ human_text_lines.append(f"\t- Total Detected: {cumulative_total}")
554
+ # Add category-wise counts
555
+ if total_counts:
556
+ for cat, count in total_counts.items():
557
+ if count > 0: # Only include categories with non-zero counts
558
+ human_text_lines.append(f"\t- {cat}: {count}")
559
+ # Build current_counts array in expected format
560
+ current_counts = []
561
+ for cat, count in per_category_count.items():
562
+ if count > 0 or total_detections > 0: # Include even if 0 when there are detections
563
+ current_counts.append({
564
+ "category": cat,
565
+ "count": count
566
+ })
567
+
568
+ human_text = "\n".join(human_text_lines)
569
+
570
+ # Include detections with masks from counting_summary
571
+ # Prepare detections without confidence scores (as per eg.json)
572
+ detections = []
573
+ for detection in counting_summary.get("detections", []):
574
+ bbox = detection.get("bounding_box", {})
575
+ category = detection.get("category", "person")
576
+ # Include segmentation if available (like in eg.json)
577
+ if detection.get("masks"):
578
+ segmentation= detection.get("masks", [])
579
+ detection_obj = self.create_detection_object(category, bbox, segmentation=segmentation)
580
+ elif detection.get("segmentation"):
581
+ segmentation= detection.get("segmentation")
582
+ detection_obj = self.create_detection_object(category, bbox, segmentation=segmentation)
583
+ elif detection.get("mask"):
584
+ segmentation= detection.get("mask")
585
+ detection_obj = self.create_detection_object(category, bbox, segmentation=segmentation)
586
+ else:
587
+ detection_obj = self.create_detection_object(category, bbox)
588
+ detections.append(detection_obj)
589
+
590
+ # Build alert_settings array in expected format
591
+ alert_settings = []
592
+ if config.alert_config and hasattr(config.alert_config, 'alert_type'):
593
+ alert_settings.append({
594
+ "alert_type": getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
595
+ "incident_category": self.CASE_TYPE,
596
+ "threshold_level": config.alert_config.count_thresholds if hasattr(config.alert_config, 'count_thresholds') else {},
597
+ "ascending": True,
598
+ "settings": {t: v for t, v in zip(getattr(config.alert_config, 'alert_type', ['Default']) if hasattr(config.alert_config, 'alert_type') else ['Default'],
599
+ getattr(config.alert_config, 'alert_value', ['JSON']) if hasattr(config.alert_config, 'alert_value') else ['JSON'])
600
+ }
601
+ })
602
+
603
+ if alerts:
604
+ for alert in alerts:
605
+ human_text_lines.append(f"Alerts: {alert.get('settings', {})} sent @ {current_timestamp}")
606
+ else:
607
+ human_text_lines.append("Alerts: None")
608
+
609
+ human_text = "\n".join(human_text_lines)
610
+ reset_settings = [
611
+ {
612
+ "interval_type": "daily",
613
+ "reset_time": {
614
+ "value": 9,
615
+ "time_unit": "hour"
616
+ }
617
+ }
618
+ ]
619
+
620
+ tracking_stat=self.create_tracking_stats(total_counts=total_counts, current_counts=current_counts,
621
+ detections=detections, human_text=human_text, camera_info=camera_info, alerts=alerts, alert_settings=alert_settings,
622
+ reset_settings=reset_settings, start_time=high_precision_start_timestamp ,
623
+ reset_time=high_precision_reset_timestamp)
624
+
625
+ tracking_stats.append(tracking_stat)
626
+ return tracking_stats
627
+
628
+ def _generate_business_analytics(self, counting_summary: Dict, zone_analysis: Dict, config: FlowerConfig, stream_info: Optional[Dict[str, Any]] = None, is_empty=False) -> List[Dict]:
629
+ """Generate standardized business analytics for the agg_summary structure."""
630
+ if is_empty:
631
+ return []
632
+
633
+ #-----IF YOUR USECASE NEEDS BUSINESS ANALYTICS, YOU CAN USE THIS FUNCTION------#
634
+ #camera_info = self.get_camera_info_from_stream(stream_info)
635
+ # business_analytics = self.create_business_analytics(nalysis_name, statistics,
636
+ # human_text, camera_info=camera_info, alerts=alerts, alert_settings=alert_settings,
637
+ # reset_settings)
638
+ # return business_analytics
639
+
640
+ def _generate_summary(self, summary: dict, incidents: List, tracking_stats: List, business_analytics: List, alerts: List) -> List[str]:
641
+ """
642
+ Generate a human_text string for the tracking_stat, incident, business analytics and alerts.
643
+ """
644
+ lines = {}
645
+ lines["Application Name"] = self.CASE_TYPE
646
+ lines["Application Version"] = self.CASE_VERSION
647
+ if len(incidents) > 0:
648
+ lines["Incidents:"]=f"\n\t{incidents[0].get('human_text', 'No incidents detected')}\n"
649
+ if len(tracking_stats) > 0:
650
+ lines["Tracking Statistics:"]=f"\t{tracking_stats[0].get('human_text', 'No tracking statistics detected')}\n"
651
+ if len(business_analytics) > 0:
652
+ lines["Business Analytics:"]=f"\t{business_analytics[0].get('human_text', 'No business analytics detected')}\n"
653
+
654
+ if len(incidents) == 0 and len(tracking_stats) == 0 and len(business_analytics) == 0:
655
+ lines["Summary"] = "No Summary Data"
656
+
657
+ return [lines]
658
+
659
+
660
+ def _count_categories(self, detections: list, config: FlowerConfig) -> dict:
661
+ """
662
+ Count the number of detections per category and return a summary dict.
663
+ The detections list is expected to have 'track_id' (from tracker), 'category', 'bounding_box', 'masks', etc.
664
+ Output structure will include 'track_id' and 'masks' for each detection as per AdvancedTracker output.
665
+ """
666
+ counts = {}
667
+ valid_detections = []
668
+ for det in detections:
669
+ cat = det.get('category', 'unknown')
670
+ if not all(k in det for k in ['category', 'confidence', 'bounding_box']): # Validate required fields
671
+ self.logger.warning(f"Skipping invalid detection: {det}")
672
+ continue
673
+ counts[cat] = counts.get(cat, 0) + 1
674
+ valid_detections.append({
675
+ "bounding_box": det.get("bounding_box"),
676
+ "category": det.get("category"),
677
+ "confidence": det.get("confidence"),
678
+ "track_id": det.get("track_id"),
679
+ "frame_id": det.get("frame_id"),
680
+ "masks": det.get("masks", det.get("mask", [])) # Include masks, fallback to empty list
681
+ })
682
+ self.logger.debug(f"Valid detections after filtering: {len(valid_detections)}")
683
+ return {
684
+ "total_count": sum(counts.values()),
685
+ "per_category_count": counts,
686
+ "detections": valid_detections
687
+ }
688
+
689
+ def _get_track_ids_info(self, detections: list) -> Dict[str, Any]:
690
+ """
691
+ Get detailed information about track IDs (per frame).
692
+ """
693
+ # Collect all track_ids in this frame
694
+ frame_track_ids = set()
695
+ for det in detections:
696
+ tid = det.get('track_id')
697
+ if tid is not None:
698
+ frame_track_ids.add(tid)
699
+ # Use persistent total set for unique counting
700
+ total_track_ids = set()
701
+ for s in getattr(self, '_per_category_total_track_ids', {}).values():
702
+ total_track_ids.update(s)
703
+ return {
704
+ "total_count": len(total_track_ids),
705
+ "current_frame_count": len(frame_track_ids),
706
+ "total_unique_track_ids": len(total_track_ids),
707
+ "current_frame_track_ids": list(frame_track_ids),
708
+ "last_update_time": time.time(),
709
+ "total_frames_processed": getattr(self, '_total_frame_counter', 0)
710
+ }
711
+
712
+ def _update_tracking_state(self, detections: list):
713
+ """
714
+ Track unique categories track_ids per category for total count after tracking.
715
+ Applies canonical ID merging to avoid duplicate counting when the underlying
716
+ tracker loses an object temporarily and assigns a new ID.
717
+ """
718
+ # Lazily initialise storage dicts
719
+ if not hasattr(self, "_per_category_total_track_ids"):
720
+ self._per_category_total_track_ids = {cat: set() for cat in self.target_categories}
721
+ self._current_frame_track_ids = {cat: set() for cat in self.target_categories}
722
+
723
+ for det in detections:
724
+ cat = det.get("category")
725
+ raw_track_id = det.get("track_id")
726
+ if cat not in self.target_categories or raw_track_id is None:
727
+ continue
728
+ bbox = det.get("bounding_box", det.get("bbox"))
729
+ canonical_id = self._merge_or_register_track(raw_track_id, bbox)
730
+ # Propagate canonical ID back to detection so downstream logic uses it
731
+ det["track_id"] = canonical_id
732
+
733
+ self._per_category_total_track_ids.setdefault(cat, set()).add(canonical_id)
734
+ self._current_frame_track_ids[cat].add(canonical_id)
735
+
736
+ def get_total_counts(self):
737
+ """
738
+ Return total unique track_id count for each category.
739
+ """
740
+ return {cat: len(ids) for cat, ids in getattr(self, '_per_category_total_track_ids', {}).items()}
741
+
742
+ def _format_timestamp_for_video(self, timestamp: float) -> str:
743
+ """Format timestamp for video chunks (HH:MM:SS.ms format)."""
744
+ hours = int(timestamp // 3600)
745
+ minutes = int((timestamp % 3600) // 60)
746
+ seconds = round(float(timestamp % 60),2)
747
+ return f"{hours:02d}:{minutes:02d}:{seconds:.1f}"
748
+
749
+ def _format_timestamp_for_stream(self, timestamp: float) -> str:
750
+ """Format timestamp for streams (YYYY:MM:DD HH:MM:SS format)."""
751
+ dt = datetime.fromtimestamp(timestamp, tz=timezone.utc)
752
+ return dt.strftime('%Y:%m:%d %H:%M:%S')
753
+
754
+ def _get_current_timestamp_str(self, stream_info: Optional[Dict[str, Any]], precision=False, frame_id: Optional[str]=None) -> str:
755
+ """Get formatted current timestamp based on stream type."""
756
+ if not stream_info:
757
+ return "00:00:00.00"
758
+ # is_video_chunk = stream_info.get("input_settings", {}).get("is_video_chunk", False)
759
+ if precision:
760
+ if stream_info.get("input_settings", {}).get("start_frame", "na") != "na":
761
+ if frame_id:
762
+ start_time = int(frame_id)/stream_info.get("input_settings", {}).get("original_fps", 30)
763
+ else:
764
+ start_time = stream_info.get("input_settings", {}).get("start_frame", 30)/stream_info.get("input_settings", {}).get("original_fps", 30)
765
+ stream_time_str = self._format_timestamp_for_video(start_time)
766
+ return stream_time_str
767
+ else:
768
+ return datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
769
+
770
+ if stream_info.get("input_settings", {}).get("start_frame", "na") != "na":
771
+ if frame_id:
772
+ start_time = int(frame_id)/stream_info.get("input_settings", {}).get("original_fps", 30)
773
+ else:
774
+ start_time = stream_info.get("input_settings", {}).get("start_frame", 30)/stream_info.get("input_settings", {}).get("original_fps", 30)
775
+ stream_time_str = self._format_timestamp_for_video(start_time)
776
+ return stream_time_str
777
+ else:
778
+ # For streams, use stream_time from stream_info
779
+ stream_time_str = stream_info.get("input_settings", {}).get("stream_info", {}).get("stream_time", "")
780
+ if stream_time_str:
781
+ # Parse the high precision timestamp string to get timestamp
782
+ try:
783
+ # Remove " UTC" suffix and parse
784
+ timestamp_str = stream_time_str.replace(" UTC", "")
785
+ dt = datetime.strptime(timestamp_str, "%Y-%m-%d-%H:%M:%S.%f")
786
+ timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
787
+ return self._format_timestamp_for_stream(timestamp)
788
+ except:
789
+ # Fallback to current time if parsing fails
790
+ return self._format_timestamp_for_stream(time.time())
791
+ else:
792
+ return self._format_timestamp_for_stream(time.time())
793
+
794
+ def _get_start_timestamp_str(self, stream_info: Optional[Dict[str, Any]], precision=False) -> str:
795
+ """Get formatted start timestamp for 'TOTAL SINCE' based on stream type."""
796
+ if not stream_info:
797
+ return "00:00:00"
798
+ if precision:
799
+ if stream_info.get("input_settings", {}).get("start_frame", "na") != "na":
800
+ return "00:00:00"
801
+ else:
802
+ return datetime.now(timezone.utc).strftime("%Y-%m-%d-%H:%M:%S.%f UTC")
803
+
804
+ if stream_info.get("input_settings", {}).get("start_frame", "na") != "na":
805
+ # If video format, start from 00:00:00
806
+ return "00:00:00"
807
+ else:
808
+ # For streams, use tracking start time or current time with minutes/seconds reset
809
+ if self._tracking_start_time is None:
810
+ # Try to extract timestamp from stream_time string
811
+ stream_time_str = stream_info.get("input_settings", {}).get("stream_info", {}).get("stream_time", "")
812
+ if stream_time_str:
813
+ try:
814
+ # Remove " UTC" suffix and parse
815
+ timestamp_str = stream_time_str.replace(" UTC", "")
816
+ dt = datetime.strptime(timestamp_str, "%Y-%m-%d-%H:%M:%S.%f")
817
+ self._tracking_start_time = dt.replace(tzinfo=timezone.utc).timestamp()
818
+ except:
819
+ # Fallback to current time if parsing fails
820
+ self._tracking_start_time = time.time()
821
+ else:
822
+ self._tracking_start_time = time.time()
823
+
824
+ dt = datetime.fromtimestamp(self._tracking_start_time, tz=timezone.utc)
825
+ # Reset minutes and seconds to 00:00 for "TOTAL SINCE" format
826
+ dt = dt.replace(minute=0, second=0, microsecond=0)
827
+ return dt.strftime('%Y:%m:%d %H:%M:%S')
828
+
829
+ # ------------------------------------------------------------------ #
830
+ # Helper to merge masks back into detections #
831
+ # ------------------------------------------------------------------ #
832
+ def _attach_masks_to_detections(
833
+ self,
834
+ processed_detections: List[Dict[str, Any]],
835
+ raw_detections: List[Dict[str, Any]],
836
+ iou_threshold: float = 0.5,
837
+ ) -> List[Dict[str, Any]]:
838
+ """
839
+ Attach segmentation masks from the original `raw_detections` list to the
840
+ `processed_detections` list returned after smoothing/tracking.
841
+
842
+ Matching between detections is performed using Intersection-over-Union
843
+ (IoU) of the bounding boxes. For each processed detection we select the
844
+ raw detection with the highest IoU above `iou_threshold` and copy its
845
+ `masks` (or `mask`) field. If no suitable match is found, the detection
846
+ keeps an empty list for `masks` to maintain a consistent schema.
847
+ """
848
+
849
+ if not processed_detections or not raw_detections:
850
+ # Nothing to do – ensure masks key exists for downstream logic.
851
+ for det in processed_detections:
852
+ det.setdefault("masks", [])
853
+ return processed_detections
854
+
855
+ # Track which raw detections have already been matched to avoid
856
+ # assigning the same mask to multiple processed detections.
857
+ used_raw_indices = set()
858
+
859
+ for det in processed_detections:
860
+ best_iou = 0.0
861
+ best_idx = None
862
+
863
+ for idx, raw_det in enumerate(raw_detections):
864
+ if idx in used_raw_indices:
865
+ continue
866
+
867
+ iou = self._compute_iou(det.get("bounding_box"), raw_det.get("bounding_box"))
868
+ if iou > best_iou:
869
+ best_iou = iou
870
+ best_idx = idx
871
+
872
+ if best_idx is not None and best_iou >= iou_threshold:
873
+ raw_det = raw_detections[best_idx]
874
+ masks = raw_det.get("masks", raw_det.get("mask"))
875
+ if masks is not None:
876
+ det["masks"] = masks
877
+ used_raw_indices.add(best_idx)
878
+ else:
879
+ # No adequate match – default to empty list to keep schema consistent.
880
+ det.setdefault("masks", ["EMPTY"])
881
+
882
+ return processed_detections
883
+
884
+ def _extract_predictions(self, detections: list) -> List[Dict[str, Any]]:
885
+ """
886
+ Extract prediction details for output (category, confidence, bounding box).
887
+ """
888
+ return [
889
+ {
890
+ "category": det.get("category", "unknown"),
891
+ "confidence": det.get("confidence", 0.0),
892
+ "bounding_box": det.get("bounding_box", {}),
893
+ "mask": det.get("mask", det.get("masks", None)) # Accept either key
894
+ }
895
+ for det in detections
896
+ ]
897
+
898
+
899
+ # ------------------------------------------------------------------ #
900
+ # Canonical ID helpers #
901
+ # ------------------------------------------------------------------ #
902
+ def _compute_iou(self, box1: Any, box2: Any) -> float:
903
+ """Compute IoU between two bounding boxes which may be dicts or lists.
904
+ Falls back to 0 when insufficient data is available."""
905
+
906
+ # Helper to convert bbox (dict or list) to [x1, y1, x2, y2]
907
+ def _bbox_to_list(bbox):
908
+ if bbox is None:
909
+ return []
910
+ if isinstance(bbox, list):
911
+ return bbox[:4] if len(bbox) >= 4 else []
912
+ if isinstance(bbox, dict):
913
+ if "xmin" in bbox:
914
+ return [bbox["xmin"], bbox["ymin"], bbox["xmax"], bbox["ymax"]]
915
+ if "x1" in bbox:
916
+ return [bbox["x1"], bbox["y1"], bbox["x2"], bbox["y2"]]
917
+ # Fallback: first four numeric values
918
+ values = [v for v in bbox.values() if isinstance(v, (int, float))]
919
+ return values[:4] if len(values) >= 4 else []
920
+ return []
921
+
922
+ l1 = _bbox_to_list(box1)
923
+ l2 = _bbox_to_list(box2)
924
+ if len(l1) < 4 or len(l2) < 4:
925
+ return 0.0
926
+ x1_min, y1_min, x1_max, y1_max = l1
927
+ x2_min, y2_min, x2_max, y2_max = l2
928
+
929
+ # Ensure correct order
930
+ x1_min, x1_max = min(x1_min, x1_max), max(x1_min, x1_max)
931
+ y1_min, y1_max = min(y1_min, y1_max), max(y1_min, y1_max)
932
+ x2_min, x2_max = min(x2_min, x2_max), max(x2_min, x2_max)
933
+ y2_min, y2_max = min(y2_min, y2_max), max(y2_min, y2_max)
934
+
935
+ inter_x_min = max(x1_min, x2_min)
936
+ inter_y_min = max(y1_min, y2_min)
937
+ inter_x_max = min(x1_max, x2_max)
938
+ inter_y_max = min(y1_max, y2_max)
939
+
940
+ inter_w = max(0.0, inter_x_max - inter_x_min)
941
+ inter_h = max(0.0, inter_y_max - inter_y_min)
942
+ inter_area = inter_w * inter_h
943
+
944
+ area1 = (x1_max - x1_min) * (y1_max - y1_min)
945
+ area2 = (x2_max - x2_min) * (y2_max - y2_min)
946
+ union_area = area1 + area2 - inter_area
947
+
948
+ return (inter_area / union_area) if union_area > 0 else 0.0
949
+
950
+ def _merge_or_register_track(self, raw_id: Any, bbox: Any) -> Any:
951
+ """Return a stable canonical ID for a raw tracker ID, merging fragmented
952
+ tracks when IoU and temporal constraints indicate they represent the
953
+ same physical."""
954
+ if raw_id is None or bbox is None:
955
+ # Nothing to merge
956
+ return raw_id
957
+
958
+ now = time.time()
959
+
960
+ # Fast path – raw_id already mapped
961
+ if raw_id in self._track_aliases:
962
+ canonical_id = self._track_aliases[raw_id]
963
+ track_info = self._canonical_tracks.get(canonical_id)
964
+ if track_info is not None:
965
+ track_info["last_bbox"] = bbox
966
+ track_info["last_update"] = now
967
+ track_info["raw_ids"].add(raw_id)
968
+ return canonical_id
969
+
970
+ # Attempt to merge with an existing canonical track
971
+ for canonical_id, info in self._canonical_tracks.items():
972
+ # Only consider recently updated tracks
973
+ if now - info["last_update"] > self._track_merge_time_window:
974
+ continue
975
+ iou = self._compute_iou(bbox, info["last_bbox"])
976
+ if iou >= self._track_merge_iou_threshold:
977
+ # Merge
978
+ self._track_aliases[raw_id] = canonical_id
979
+ info["last_bbox"] = bbox
980
+ info["last_update"] = now
981
+ info["raw_ids"].add(raw_id)
982
+ return canonical_id
983
+
984
+ # No match – register new canonical track
985
+ canonical_id = raw_id
986
+ self._track_aliases[raw_id] = canonical_id
987
+ self._canonical_tracks[canonical_id] = {
988
+ "last_bbox": bbox,
989
+ "last_update": now,
990
+ "raw_ids": {raw_id},
991
+ }
992
+ return canonical_id
993
+
994
+ def _format_timestamp(self, timestamp: float) -> str:
995
+ """Format a timestamp for human-readable output."""
996
+ return datetime.fromtimestamp(timestamp, timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')
997
+
998
+ def _get_tracking_start_time(self) -> str:
999
+ """Get the tracking start time, formatted as a string."""
1000
+ if self._tracking_start_time is None:
1001
+ return "N/A"
1002
+ return self._format_timestamp(self._tracking_start_time)
1003
+
1004
+ def _set_tracking_start_time(self) -> None:
1005
+ """Set the tracking start time to the current time."""
1006
+ self._tracking_start_time = time.time()