mrradix commited on
Commit
50dc6d1
·
verified ·
1 Parent(s): 5ba4166

Update utils/config.py

Browse files
Files changed (1) hide show
  1. utils/config.py +87 -140
utils/config.py CHANGED
@@ -1,152 +1,99 @@
 
 
 
1
  import os
2
- from typing import Dict, Any, Optional
3
- from dataclasses import dataclass, asdict
4
- import streamlit as st
5
 
6
- from utils.logging import get_logger
7
- from utils.error_handling import ConfigError
 
 
 
8
 
9
- logger = get_logger(__name__)
 
 
 
10
 
11
- @dataclass
12
- class AppConfig:
13
- """Application configuration data class"""
14
- app_name: str = "MONA Dashboard"
15
- version: str = "1.0.0"
16
- debug_mode: bool = False
17
- max_data_points: int = 1000
18
- refresh_interval: int = 30
19
- default_chart_type: str = "line"
20
- theme: str = "light"
21
-
22
- # UI Configuration
23
- sidebar_width: int = 300
24
- chart_height: int = 400
25
- table_page_size: int = 50
26
-
27
- # Data Configuration
28
- data_cache_timeout: int = 300
29
- max_file_size_mb: int = 10
30
- supported_file_types: list = None
31
-
32
- def __post_init__(self):
33
- if self.supported_file_types is None:
34
- self.supported_file_types = ['.csv', '.xlsx', '.json', '.parquet']
35
 
36
- # Global configuration instance
37
- _config = None
 
 
 
 
 
38
 
39
- def load_config() -> AppConfig:
40
- """Load application configuration"""
41
- global _config
42
-
43
- if _config is None:
44
- try:
45
- # Create default config
46
- _config = AppConfig()
47
-
48
- # Override with environment variables if available
49
- _config.debug_mode = os.getenv('DEBUG', 'False').lower() == 'true'
50
- _config.max_data_points = int(os.getenv('MAX_DATA_POINTS', '1000'))
51
- _config.refresh_interval = int(os.getenv('REFRESH_INTERVAL', '30'))
52
- _config.theme = os.getenv('THEME', 'light')
53
-
54
- # Override with Streamlit session state if available
55
- if 'app_config' in st.session_state:
56
- session_config = st.session_state.app_config
57
- for key, value in session_config.items():
58
- if hasattr(_config, key):
59
- setattr(_config, key, value)
60
-
61
- logger.info("Configuration loaded successfully")
62
-
63
- except Exception as e:
64
- logger.error(f"Failed to load configuration: {str(e)}")
65
- raise ConfigError(f"Configuration loading failed: {str(e)}")
66
-
67
- return _config
68
 
69
- def save_config(config: AppConfig) -> bool:
70
- """Save configuration to session state"""
71
- try:
72
- st.session_state.app_config = asdict(config)
73
- global _config
74
- _config = config
75
- logger.info("Configuration saved successfully")
76
- return True
77
- except Exception as e:
78
- logger.error(f"Failed to save configuration: {str(e)}")
79
- return False
80
 
81
- def get_config_value(key: str, default_value: Any = None) -> Any:
82
- """Get a specific configuration value"""
83
- try:
84
- config = load_config()
85
- return getattr(config, key, default_value)
86
- except Exception as e:
87
- logger.error(f"Failed to get config value for key {key}: {str(e)}")
88
- return default_value
89
 
90
- def update_config_value(key: str, value: Any) -> bool:
91
- """Update a specific configuration value"""
92
- try:
93
- config = load_config()
94
- if hasattr(config, key):
95
- setattr(config, key, value)
96
- return save_config(config)
97
- else:
98
- logger.warning(f"Configuration key '{key}' does not exist")
99
- return False
100
- except Exception as e:
101
- logger.error(f"Failed to update config value for key {key}: {str(e)}")
102
- return False
103
 
104
- def reset_config() -> AppConfig:
105
- """Reset configuration to defaults"""
106
- global _config
107
- _config = AppConfig()
108
- save_config(_config)
109
- logger.info("Configuration reset to defaults")
110
- return _config
111
 
112
- def get_config_dict() -> Dict[str, Any]:
113
- """Get configuration as dictionary"""
114
- try:
115
- config = load_config()
116
- return asdict(config)
117
- except Exception as e:
118
- logger.error(f"Failed to get configuration dictionary: {str(e)}")
119
- return {}
120
 
121
- def validate_config(config: AppConfig) -> bool:
122
- """Validate configuration values"""
123
- try:
124
- # Validate numeric values
125
- if config.max_data_points <= 0:
126
- raise ConfigError("max_data_points must be positive")
127
-
128
- if config.refresh_interval <= 0:
129
- raise ConfigError("refresh_interval must be positive")
130
-
131
- if config.sidebar_width <= 0:
132
- raise ConfigError("sidebar_width must be positive")
133
-
134
- if config.chart_height <= 0:
135
- raise ConfigError("chart_height must be positive")
136
-
137
- # Validate string values
138
- if config.theme not in ['light', 'dark']:
139
- raise ConfigError("theme must be 'light' or 'dark'")
140
-
141
- if config.default_chart_type not in ['line', 'bar', 'scatter', 'area']:
142
- raise ConfigError("invalid default_chart_type")
143
-
144
- logger.info("Configuration validation successful")
145
- return True
146
-
147
- except ConfigError as e:
148
- logger.error(f"Configuration validation failed: {str(e)}")
149
- raise e
150
- except Exception as e:
151
- logger.error(f"Unexpected error during configuration validation: {str(e)}")
152
- raise ConfigError(f"Configuration validation error: {str(e)}")
 
1
+ """
2
+ Configuration settings for the application
3
+ """
4
  import os
5
+ from pathlib import Path
 
 
6
 
7
+ # Base directories
8
+ BASE_DIR = Path(__file__).parent
9
+ DATA_DIR = BASE_DIR / "data"
10
+ CACHE_DIR = BASE_DIR / "cache"
11
+ LOGS_DIR = BASE_DIR / "logs"
12
 
13
+ # Create directories if they don't exist
14
+ DATA_DIR.mkdir(exist_ok=True)
15
+ CACHE_DIR.mkdir(exist_ok=True)
16
+ LOGS_DIR.mkdir(exist_ok=True)
17
 
18
+ # Application settings
19
+ APP_NAME = "Dashboard App"
20
+ APP_VERSION = "1.0.0"
21
+ DEBUG = os.getenv("DEBUG", "False").lower() == "true"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
+ # Streamlit configuration
24
+ STREAMLIT_CONFIG = {
25
+ "page_title": APP_NAME,
26
+ "page_icon": "📊",
27
+ "layout": "wide",
28
+ "initial_sidebar_state": "expanded"
29
+ }
30
 
31
+ # Logging configuration
32
+ LOGGING_CONFIG = {
33
+ "level": "DEBUG" if DEBUG else "INFO",
34
+ "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
35
+ "file_path": LOGS_DIR / "app.log"
36
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
+ # Dashboard settings
39
+ DASHBOARD_CONFIG = {
40
+ "default_chart_type": "Line Chart",
41
+ "refresh_interval": 300, # 5 minutes
42
+ "max_data_points": 10000,
43
+ "enable_caching": True
44
+ }
 
 
 
 
45
 
46
+ # File upload settings
47
+ UPLOAD_CONFIG = {
48
+ "max_file_size": 200, # MB
49
+ "allowed_extensions": [".csv", ".xlsx", ".json", ".pkl"],
50
+ "upload_dir": DATA_DIR / "uploads"
51
+ }
 
 
52
 
53
+ # API settings (if needed)
54
+ API_CONFIG = {
55
+ "timeout": 30,
56
+ "max_retries": 3,
57
+ "base_url": os.getenv("API_BASE_URL", "")
58
+ }
 
 
 
 
 
 
 
59
 
60
+ # Database settings (if needed)
61
+ DATABASE_CONFIG = {
62
+ "url": os.getenv("DATABASE_URL", ""),
63
+ "pool_size": 5,
64
+ "max_overflow": 10
65
+ }
 
66
 
67
+ # Security settings
68
+ SECURITY_CONFIG = {
69
+ "secret_key": os.getenv("SECRET_KEY", "your-secret-key-here"),
70
+ "session_timeout": 3600, # 1 hour
71
+ "max_login_attempts": 5
72
+ }
 
 
73
 
74
+ # Feature flags
75
+ FEATURES = {
76
+ "enable_dashboard": True,
77
+ "enable_analytics": False,
78
+ "enable_user_management": False,
79
+ "enable_api": False
80
+ }
81
+
82
+ # Export all configurations
83
+ __all__ = [
84
+ "BASE_DIR",
85
+ "DATA_DIR",
86
+ "CACHE_DIR",
87
+ "LOGS_DIR",
88
+ "APP_NAME",
89
+ "APP_VERSION",
90
+ "DEBUG",
91
+ "STREAMLIT_CONFIG",
92
+ "LOGGING_CONFIG",
93
+ "DASHBOARD_CONFIG",
94
+ "UPLOAD_CONFIG",
95
+ "API_CONFIG",
96
+ "DATABASE_CONFIG",
97
+ "SECURITY_CONFIG",
98
+ "FEATURES"
99
+ ]