Spaces:
Build error
Build error
File size: 10,317 Bytes
f69e8b5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 |
import streamlit as st
from datetime import datetime
from typing import Dict, Optional, Any
import json
import base64
from pathlib import Path
import logging
from logging.handlers import RotatingFileHandler
import yaml
import os
from PIL import Image
import io
class AppUtils:
"""Core utilities class for the EduAI platform."""
@staticmethod
def set_page_config():
"""Configure Streamlit page settings with enhanced options."""
st.set_page_config(
page_title="EduAI Platform",
page_icon="🎓",
layout="wide",
initial_sidebar_state="expanded",
menu_items={
'Get Help': 'https://docs.eduai-platform.com',
'Report a bug': 'https://github.com/eduai-platform/issues',
'About': '### EduAI Learning Platform\nEmpowering education through AI.'
}
)
@staticmethod
def apply_custom_css():
"""Apply enhanced custom CSS styling."""
st.markdown("""
<style>
/* Main app container */
.stApp {
max-width: 1200px;
margin: 0 auto;
background-color: #f8f9fa;
}
/* Header styling */
.stHeader {
background-color: white;
padding: 1rem;
border-bottom: 1px solid #e9ecef;
}
/* Sidebar enhancements */
.css-1d391kg {
background-color: white;
padding: 2rem 1rem;
}
/* Card layouts */
.card {
background-color: white;
border-radius: 0.5rem;
padding: 1.5rem;
margin: 1rem 0;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
/* Button styling */
.stButton button {
width: 100%;
border-radius: 0.25rem;
transition: all 0.2s ease;
}
.stButton button:hover {
transform: translateY(-1px);
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}
/* Progress bars */
.stProgress > div > div {
background-color: #007bff;
}
/* Code editor */
.stCodeEditor {
border-radius: 0.5rem;
overflow: hidden;
}
/* Chat interface */
.chat-message {
padding: 1rem;
margin: 0.5rem 0;
border-radius: 0.5rem;
}
.user-message {
background-color: #e7f1ff;
margin-left: 2rem;
}
.assistant-message {
background-color: #f8f9fa;
margin-right: 2rem;
}
/* Responsive adjustments */
@media (max-width: 768px) {
.stApp {
padding: 1rem;
}
}
</style>
""", unsafe_allow_html=True)
@staticmethod
def setup_logging(log_dir: str = "logs"):
"""Set up application logging with rotation."""
log_dir = Path(log_dir)
log_dir.mkdir(exist_ok=True)
log_file = log_dir / "eduai.log"
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
handler = RotatingFileHandler(
log_file,
maxBytes=10485760, # 10MB
backupCount=5
)
handler.setFormatter(formatter)
logger = logging.getLogger("eduai")
logger.setLevel(logging.INFO)
logger.addHandler(handler)
return logger
@staticmethod
def load_config(config_path: str = "config.yaml") -> Dict:
"""Load application configuration from YAML."""
try:
with open(config_path) as f:
config = yaml.safe_load(f)
return config
except Exception as e:
st.error(f"Error loading configuration: {str(e)}")
return {}
@classmethod
def initialize_session_state(cls):
"""Initialize all required session state variables."""
default_state = {
'messages': [],
'user_progress': {
'current_path': None,
'completed_modules': [],
'achievements': []
},
'artifacts': [],
'notifications': [],
'theme': 'light',
'language': 'en'
}
for key, value in default_state.items():
if key not in st.session_state:
st.session_state[key] = value
@staticmethod
def save_uploaded_file(uploaded_file) -> Optional[Path]:
"""Save uploaded file and return the path."""
if uploaded_file is None:
return None
# Create uploads directory if it doesn't exist
upload_dir = Path("uploads")
upload_dir.mkdir(exist_ok=True)
# Generate unique filename
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
safe_filename = "".join(c for c in uploaded_file.name if c.isalnum() or c in "._-")
unique_filename = f"{timestamp}_{safe_filename}"
file_path = upload_dir / unique_filename
# Save the file
try:
with open(file_path, "wb") as f:
f.write(uploaded_file.getbuffer())
return file_path
except Exception as e:
st.error(f"Error saving file: {str(e)}")
return None
@staticmethod
def format_time(seconds: int) -> str:
"""Format time duration in a human-readable format."""
if seconds < 60:
return f"{seconds} seconds"
elif seconds < 3600:
minutes = seconds // 60
return f"{minutes} {'minute' if minutes == 1 else 'minutes'}"
else:
hours = seconds // 3600
minutes = (seconds % 3600) // 60
return f"{hours}h {minutes}m"
@staticmethod
def encode_image(image_path: str) -> str:
"""Encode image to base64 string."""
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode()
@staticmethod
def create_thumbnail(image_path: str, size: tuple = (100, 100)) -> str:
"""Create thumbnail from image and return as base64 string."""
with Image.open(image_path) as img:
img.thumbnail(size)
buffered = io.BytesIO()
img.save(buffered, format=img.format)
return base64.b64encode(buffered.getvalue()).decode()
@staticmethod
def display_notification(message: str, type: str = "info"):
"""Display notification message with specified type."""
notification_funcs = {
"info": st.info,
"success": st.success,
"warning": st.warning,
"error": st.error
}
if type in notification_funcs:
notification_funcs[type](message)
# Store in notifications history
if 'notifications' in st.session_state:
st.session_state.notifications.append({
'message': message,
'type': type,
'timestamp': datetime.now().isoformat()
})
@staticmethod
def format_code(code: str, language: str = "python") -> str:
"""Format code with syntax highlighting."""
return f"```{language}\n{code}\n```"
@classmethod
def track_analytics(cls, event_type: str, event_data: Dict[str, Any]):
"""Track user analytics events."""
analytics_data = {
'timestamp': datetime.now().isoformat(),
'event_type': event_type,
'event_data': event_data,
'session_id': st.session_state.get('session_id'),
'user_id': st.session_state.get('user_id')
}
# In a real application, this would send data to an analytics service
logger = cls.setup_logging()
logger.info(f"Analytics event: {json.dumps(analytics_data)}")
@staticmethod
def get_theme_colors(theme: str = "light") -> Dict[str, str]:
"""Get color scheme based on theme."""
themes = {
"light": {
"primary": "#007bff",
"secondary": "#6c757d",
"background": "#f8f9fa",
"text": "#212529",
"border": "#dee2e6"
},
"dark": {
"primary": "#0d6efd",
"secondary": "#6c757d",
"background": "#212529",
"text": "#f8f9fa",
"border": "#495057"
}
}
return themes.get(theme, themes["light"])
@staticmethod
def get_translation(text: str, language: str = "en") -> str:
"""Get translated text based on language setting."""
# This is a simple placeholder - in a real app, use a proper i18n system
translations = {
"en": {"welcome": "Welcome", "start": "Start Learning"},
"hi": {"welcome": "स्वागत है", "start": "सीखना शुरू करें"},
"es": {"welcome": "Bienvenido", "start": "Empezar a aprender"}
}
lang_dict = translations.get(language, translations["en"])
return lang_dict.get(text, text)
# Initialize environment variables and global settings
def init_environment():
"""Initialize environment variables and settings."""
os.environ.setdefault("STREAMLIT_THEME", "light")
os.environ.setdefault("STREAMLIT_LOG_LEVEL", "INFO")
# Set up basic security headers
headers = {
'Strict-Transport-Security': 'max-age=31536000; includeSubDomains',
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'SAMEORIGIN',
'X-XSS-Protection': '1; mode=block'
}
return headers |