""" Real-time progress monitoring component with SSE integration. """ import streamlit as st import time import json from datetime import datetime, timedelta from typing import Dict, Any, Optional class ProgressMonitor: """Monitors analysis progress with real-time updates via SSE.""" def __init__(self, api_client, sse_client): self.api_client = api_client self.sse_client = sse_client # Analysis stages and their descriptions self.stages = { "data_cleaning": { "name": "Data Cleaning", "description": "Analyzing data quality and applying cleaning operations", "icon": "๐Ÿงน", "estimated_duration": 30 }, "hypothesis_testing": { "name": "Hypothesis Testing", "description": "Generating and testing statistical hypotheses", "icon": "๐Ÿ”ฌ", "estimated_duration": 45 }, "preprocessing": { "name": "Data Preprocessing", "description": "Scaling, encoding, and preparing features", "icon": "โš™๏ธ", "estimated_duration": 20 }, "feature_engineering": { "name": "Feature Engineering", "description": "Creating new features based on insights", "icon": "๐Ÿ”ง", "estimated_duration": 35 }, "model_training": { "name": "Model Training", "description": "Training and evaluating machine learning models", "icon": "๐Ÿค–", "estimated_duration": 60 }, "action_generation": { "name": "Business Recommendations", "description": "Generating actionable business insights", "icon": "๐Ÿ’ก", "estimated_duration": 25 } } def render(self, session: Dict[str, Any]): """Render the progress monitoring interface.""" # Get current session status current_status = self._get_session_status(session['id']) if not current_status: st.error("Unable to retrieve session status") return # Progress header self._render_progress_header(current_status) # Stage progress self._render_stage_progress(current_status) # Real-time updates self._render_realtime_updates(session['id']) # Control buttons self._render_control_buttons(session['id'], current_status) def _render_progress_header(self, status: Dict[str, Any]): """Render the progress header with overall status.""" col1, col2, col3 = st.columns([2, 1, 1]) with col1: st.markdown(f"### ๐Ÿ“Š {status.get('name', 'Analysis')}") # Status badge status_value = status.get('status', 'unknown') status_colors = { 'pending': '๐ŸŸก', 'running': '๐ŸŸข', 'completed': 'โœ…', 'failed': 'โŒ', 'cancelled': 'โน๏ธ' } st.markdown(f"**Status:** {status_colors.get(status_value, 'โ“')} {status_value.title()}") with col2: # Time elapsed started_at = status.get('started_at') if started_at: start_time = datetime.fromisoformat(started_at.replace('Z', '+00:00')) elapsed = datetime.now() - start_time.replace(tzinfo=None) st.metric("โฑ๏ธ Elapsed", f"{elapsed.seconds // 60}m {elapsed.seconds % 60}s") with col3: # Estimated remaining time if status.get('status') == 'running': remaining = self._estimate_remaining_time(status) st.metric("โณ Remaining", remaining) def _render_stage_progress(self, status: Dict[str, Any]): """Render progress for each analysis stage.""" st.markdown("#### ๐Ÿ”„ Analysis Stages") current_stage = status.get('current_stage', 'data_cleaning') stage_progress = status.get('stage_progress', {}) for stage_key, stage_info in self.stages.items(): # Determine stage status if stage_key in stage_progress: progress_data = stage_progress[stage_key] stage_status = progress_data.get('status', 'pending') progress_value = progress_data.get('progress', 0) elif stage_key == current_stage: stage_status = 'running' progress_value = 50 # Default progress for current stage else: # Check if this stage comes before current stage stage_order = list(self.stages.keys()) if stage_order.index(stage_key) < stage_order.index(current_stage): stage_status = 'completed' progress_value = 100 else: stage_status = 'pending' progress_value = 0 # Render stage self._render_single_stage(stage_info, stage_status, progress_value) def _render_single_stage(self, stage_info: Dict[str, Any], status: str, progress: float): """Render a single analysis stage.""" with st.container(): col1, col2, col3 = st.columns([1, 3, 1]) with col1: # Status icon if status == 'completed': st.markdown("โœ…") elif status == 'running': st.markdown("๐Ÿ”„") elif status == 'failed': st.markdown("โŒ") else: st.markdown("โณ") with col2: # Stage info st.markdown(f"**{stage_info['icon']} {stage_info['name']}**") st.caption(stage_info['description']) # Progress bar if status in ['running', 'completed']: st.progress(progress / 100) with col3: # Duration estimate if status == 'completed': st.caption("โœ“ Done") elif status == 'running': st.caption(f"~{stage_info['estimated_duration']}s") else: st.caption("Pending") st.divider() def _render_realtime_updates(self, session_id: str): """Render real-time updates section.""" st.markdown("#### ๐Ÿ“ก Real-time Updates") # Create placeholder for updates updates_placeholder = st.empty() # Get recent updates from SSE client if hasattr(st.session_state, 'sse_updates'): updates = st.session_state.sse_updates.get(session_id, []) if updates: # Show last 5 updates recent_updates = updates[-5:] with updates_placeholder.container(): for update in reversed(recent_updates): timestamp = update.get('timestamp', '') message = update.get('message', '') event_type = update.get('event_type', 'info') # Format timestamp try: dt = datetime.fromisoformat(timestamp.replace('Z', '+00:00')) time_str = dt.strftime('%H:%M:%S') except: time_str = timestamp # Show update with appropriate styling if event_type == 'error': st.error(f"[{time_str}] {message}") elif event_type == 'success': st.success(f"[{time_str}] {message}") elif event_type == 'warning': st.warning(f"[{time_str}] {message}") else: st.info(f"[{time_str}] {message}") else: updates_placeholder.info("Waiting for updates...") else: updates_placeholder.info("Connecting to real-time updates...") def _render_control_buttons(self, session_id: str, status: Dict[str, Any]): """Render control buttons for the analysis.""" col1, col2, col3 = st.columns(3) with col1: if status.get('status') == 'running': if st.button("โน๏ธ Cancel Analysis", type="secondary"): self._cancel_analysis(session_id) with col2: if st.button("๐Ÿ”„ Refresh Status"): st.rerun() with col3: if status.get('status') == 'completed': if st.button("๐Ÿ“Š View Results", type="primary"): self._load_results(session_id) def _get_session_status(self, session_id: str) -> Optional[Dict[str, Any]]: """Get current session status from API.""" try: return self.api_client.get_analysis_status(session_id) except Exception as e: st.error(f"Error getting session status: {str(e)}") return None def _estimate_remaining_time(self, status: Dict[str, Any]) -> str: """Estimate remaining time for analysis.""" current_stage = status.get('current_stage', 'data_cleaning') stage_progress = status.get('stage_progress', {}) # Calculate remaining time based on current stage and progress total_remaining = 0 stage_order = list(self.stages.keys()) current_index = stage_order.index(current_stage) if current_stage in stage_order else 0 # Add remaining time for current stage if current_stage in stage_progress: current_progress = stage_progress[current_stage].get('progress', 0) stage_duration = self.stages[current_stage]['estimated_duration'] remaining_current = stage_duration * (100 - current_progress) / 100 total_remaining += remaining_current # Add time for remaining stages for i in range(current_index + 1, len(stage_order)): stage_key = stage_order[i] total_remaining += self.stages[stage_key]['estimated_duration'] # Format time if total_remaining < 60: return f"{int(total_remaining)}s" else: minutes = int(total_remaining // 60) seconds = int(total_remaining % 60) return f"{minutes}m {seconds}s" def _cancel_analysis(self, session_id: str): """Cancel the running analysis.""" try: success = self.api_client.cancel_analysis(session_id) if success: st.success("Analysis cancelled successfully") st.rerun() else: st.error("Failed to cancel analysis") except Exception as e: st.error(f"Error cancelling analysis: {str(e)}") def _load_results(self, session_id: str): """Load analysis results.""" try: results = self.api_client.get_analysis_results(session_id) if results: st.session_state.analysis_results = results st.success("Results loaded successfully") # Switch to results page st.session_state.navigation = "Results Viewer" st.rerun() else: st.error("No results available") except Exception as e: st.error(f"Error loading results: {str(e)}")