File size: 12,476 Bytes
56c063a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

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)}")