midlajvalappil/Real-time_Object_Detection_with_YOLO
0
1"""2Configuration Module3Handles application configuration and settings.4"""5 6import os7from dataclasses import dataclass8from typing import Dict, Any, List9import json10import logging11 12# Configure logging13logging.basicConfig(level=logging.INFO)14logger = logging.getLogger(__name__)15 16@dataclass17class DetectionConfig:18 """Configuration for object detection."""19 model_name: str = "yolov8n.pt"20 confidence_threshold: float = 0.521 max_detections: int = 10022 nms_threshold: float = 0.4523 24@dataclass25class CameraConfig:26 """Configuration for camera settings."""27 camera_index: int = 028 frame_width: int = 64029 frame_height: int = 48030 fps_target: int = 3031 32@dataclass33class UIConfig:34 """Configuration for UI settings."""35 page_title: str = "Real-time Object Detection with YOLO"36 sidebar_width: int = 30037 show_fps: bool = True38 show_stats: bool = True39 show_confidence: bool = True40 41@dataclass42class PerformanceConfig:43 """Configuration for performance settings."""44 detection_interval: int = 1 # Process every N frames45 max_fps: int = 3046 enable_gpu: bool = True47 batch_size: int = 148 49class AppConfig:50 """Main application configuration class."""51 52 def __init__(self, config_file: str = "config.json"):53 """54 Initialize application configuration.55 56 Args:57 config_file (str): Path to configuration file58 """59 self.config_file = config_file60 self.detection = DetectionConfig()61 self.camera = CameraConfig()62 self.ui = UIConfig()63 self.performance = PerformanceConfig()64 65 # Available YOLO models66 self.available_models = [67 "yolov8n.pt", # Nano - fastest, least accurate68 "yolov8s.pt", # Small69 "yolov8m.pt", # Medium70 "yolov8l.pt", # Large71 "yolov8x.pt", # Extra Large - slowest, most accurate72 ]73 74 # Model descriptions75 self.model_descriptions = {76 "yolov8n.pt": "YOLOv8 Nano - Fastest, good for real-time applications",77 "yolov8s.pt": "YOLOv8 Small - Balanced speed and accuracy",78 "yolov8m.pt": "YOLOv8 Medium - Better accuracy, moderate speed",79 "yolov8l.pt": "YOLOv8 Large - High accuracy, slower inference",80 "yolov8x.pt": "YOLOv8 Extra Large - Highest accuracy, slowest inference"81 }82 83 self.load_config()84 85 def load_config(self):86 """Load configuration from file."""87 if os.path.exists(self.config_file):88 try:89 with open(self.config_file, 'r') as f:90 config_data = json.load(f)91 92 # Update detection config93 if 'detection' in config_data:94 detection_data = config_data['detection']95 self.detection.model_name = detection_data.get('model_name', self.detection.model_name)96 self.detection.confidence_threshold = detection_data.get('confidence_threshold', self.detection.confidence_threshold)97 self.detection.max_detections = detection_data.get('max_detections', self.detection.max_detections)98 self.detection.nms_threshold = detection_data.get('nms_threshold', self.detection.nms_threshold)99 100 # Update camera config101 if 'camera' in config_data:102 camera_data = config_data['camera']103 self.camera.camera_index = camera_data.get('camera_index', self.camera.camera_index)104 self.camera.frame_width = camera_data.get('frame_width', self.camera.frame_width)105 self.camera.frame_height = camera_data.get('frame_height', self.camera.frame_height)106 self.camera.fps_target = camera_data.get('fps_target', self.camera.fps_target)107 108 # Update UI config109 if 'ui' in config_data:110 ui_data = config_data['ui']111 self.ui.page_title = ui_data.get('page_title', self.ui.page_title)112 self.ui.sidebar_width = ui_data.get('sidebar_width', self.ui.sidebar_width)113 self.ui.show_fps = ui_data.get('show_fps', self.ui.show_fps)114 self.ui.show_stats = ui_data.get('show_stats', self.ui.show_stats)115 self.ui.show_confidence = ui_data.get('show_confidence', self.ui.show_confidence)116 117 # Update performance config118 if 'performance' in config_data:119 perf_data = config_data['performance']120 self.performance.detection_interval = perf_data.get('detection_interval', self.performance.detection_interval)121 self.performance.max_fps = perf_data.get('max_fps', self.performance.max_fps)122 self.performance.enable_gpu = perf_data.get('enable_gpu', self.performance.enable_gpu)123 self.performance.batch_size = perf_data.get('batch_size', self.performance.batch_size)124 125 logger.info(f"Configuration loaded from {self.config_file}")126 127 except Exception as e:128 logger.error(f"Error loading configuration: {str(e)}")129 logger.info("Using default configuration")130 else:131 logger.info("Configuration file not found, using defaults")132 133 def save_config(self):134 """Save current configuration to file."""135 try:136 config_data = {137 'detection': {138 'model_name': self.detection.model_name,139 'confidence_threshold': self.detection.confidence_threshold,140 'max_detections': self.detection.max_detections,141 'nms_threshold': self.detection.nms_threshold142 },143 'camera': {144 'camera_index': self.camera.camera_index,145 'frame_width': self.camera.frame_width,146 'frame_height': self.camera.frame_height,147 'fps_target': self.camera.fps_target148 },149 'ui': {150 'page_title': self.ui.page_title,151 'sidebar_width': self.ui.sidebar_width,152 'show_fps': self.ui.show_fps,153 'show_stats': self.ui.show_stats,154 'show_confidence': self.ui.show_confidence155 },156 'performance': {157 'detection_interval': self.performance.detection_interval,158 'max_fps': self.performance.max_fps,159 'enable_gpu': self.performance.enable_gpu,160 'batch_size': self.performance.batch_size161 }162 }163 164 with open(self.config_file, 'w') as f:165 json.dump(config_data, f, indent=2)166 167 logger.info(f"Configuration saved to {self.config_file}")168 169 except Exception as e:170 logger.error(f"Error saving configuration: {str(e)}")171 172 def get_model_info(self, model_name: str) -> Dict[str, Any]:173 """174 Get information about a model.175 176 Args:177 model_name (str): Name of the model178 179 Returns:180 Dict[str, Any]: Model information181 """182 return {183 'name': model_name,184 'description': self.model_descriptions.get(model_name, "Unknown model"),185 'available': model_name in self.available_models186 }187 188 def validate_config(self) -> List[str]:189 """190 Validate current configuration.191 192 Returns:193 List[str]: List of validation errors (empty if valid)194 """195 errors = []196 197 # Validate detection config198 if not (0.0 <= self.detection.confidence_threshold <= 1.0):199 errors.append("Confidence threshold must be between 0.0 and 1.0")200 201 if self.detection.max_detections <= 0:202 errors.append("Max detections must be positive")203 204 if not (0.0 <= self.detection.nms_threshold <= 1.0):205 errors.append("NMS threshold must be between 0.0 and 1.0")206 207 # Validate camera config208 if self.camera.camera_index < 0:209 errors.append("Camera index must be non-negative")210 211 if self.camera.frame_width <= 0 or self.camera.frame_height <= 0:212 errors.append("Frame dimensions must be positive")213 214 if self.camera.fps_target <= 0:215 errors.append("FPS target must be positive")216 217 # Validate performance config218 if self.performance.detection_interval <= 0:219 errors.append("Detection interval must be positive")220 221 if self.performance.max_fps <= 0:222 errors.append("Max FPS must be positive")223 224 if self.performance.batch_size <= 0:225 errors.append("Batch size must be positive")226 227 return errors228 229 def reset_to_defaults(self):230 """Reset configuration to default values."""231 self.detection = DetectionConfig()232 self.camera = CameraConfig()233 self.ui = UIConfig()234 self.performance = PerformanceConfig()235 logger.info("Configuration reset to defaults")236 237 238# Global configuration instance239app_config = AppConfig()240 