petter2025 commited on
Commit
8882332
Β·
verified Β·
1 Parent(s): c9eaa2d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +486 -467
app.py CHANGED
@@ -1,7 +1,7 @@
1
  """
2
  πŸš€ ARF Ultimate Investor Demo v3.8.0 - ENTERPRISE EDITION
3
  MODULAR VERSION - Properly integrated with all components
4
- COMPLETE FIXED VERSION with enhanced architecture
5
  """
6
 
7
  import logging
@@ -31,10 +31,11 @@ logger = logging.getLogger(__name__)
31
  sys.path.insert(0, str(Path(__file__).parent))
32
 
33
  # ===========================================
34
- # ASYNC UTILITIES
35
  # ===========================================
36
  class AsyncRunner:
37
- """Simple async runner for sync context"""
 
38
  @staticmethod
39
  def run_async(coro):
40
  """Run async coroutine in sync context"""
@@ -43,20 +44,31 @@ class AsyncRunner:
43
  except RuntimeError:
44
  loop = asyncio.new_event_loop()
45
  asyncio.set_event_loop(loop)
46
- return loop.run_until_complete(coro)
 
 
 
 
 
 
47
 
48
  @staticmethod
49
  def async_to_sync(async_func):
50
  """Decorator to convert async function to sync"""
51
  def wrapper(*args, **kwargs):
52
- return AsyncRunner.run_async(async_func(*args, **kwargs))
 
 
 
 
 
53
  return wrapper
54
 
55
  # ===========================================
56
- # SIMPLE SETTINGS (No pydantic dependency)
57
  # ===========================================
58
  class Settings:
59
- """Simple settings class without external dependencies"""
60
  def __init__(self):
61
  self.arf_mode = "demo"
62
  self.use_mock_arf = True
@@ -67,47 +79,184 @@ class Settings:
67
  settings = Settings()
68
 
69
  # ===========================================
70
- # IMPORT MODULAR COMPONENTS - SAFE IMPORTS
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  # ===========================================
72
- def import_components():
73
  """Safely import all components with proper error handling"""
 
 
 
 
 
74
  try:
75
- # Import scenarios - try demo module first
 
 
 
 
76
  try:
77
  from demo.scenarios import INCIDENT_SCENARIOS
78
  logger.info(f"Loaded {len(INCIDENT_SCENARIOS)} scenarios from demo module")
 
79
  except ImportError as e:
80
  logger.warning(f"Demo scenarios not available: {e}")
81
  # Create minimal fallback
82
- INCIDENT_SCENARIOS = {
83
  "Cache Miss Storm": {
84
  "component": "Redis Cache Cluster",
85
  "severity": "HIGH",
86
  "impact_radius": "85% of users",
87
  "business_impact": {"revenue_loss_per_hour": 8500},
88
  "detection_time": "45 seconds",
89
- "tags": ["cache", "redis", "latency"]
 
90
  }
91
  }
92
 
93
- # Import orchestrator
94
- try:
95
- from demo.orchestrator import DemoOrchestrator
96
- except ImportError:
97
- # Create mock orchestrator
98
- class DemoOrchestrator:
99
- async def analyze_incident(self, name, scenario):
100
- return {"status": "Mock analysis", "scenario": name}
101
-
102
- # Import ROI calculator - with fallback
103
  try:
104
  from core.calculators import EnhancedROICalculator
105
- roi_calculator_available = True
106
  logger.info("EnhancedROICalculator imported successfully")
107
  except ImportError as e:
108
  logger.warning(f"EnhancedROICalculator not available: {e}")
109
- # Create mock calculator
110
- class EnhancedROICalculator:
111
  def calculate_comprehensive_roi(self, **kwargs):
112
  return {
113
  "status": "βœ… Calculated Successfully",
@@ -120,23 +269,49 @@ def import_components():
120
  "annual_roi_percentage": "420%"
121
  }
122
  }
123
- roi_calculator_available = True
124
 
125
- # Import visualizations - with fallback
126
  try:
127
  from core.visualizations import EnhancedVisualizationEngine
128
- viz_engine_available = True
129
  logger.info("EnhancedVisualizationEngine imported successfully")
130
  except ImportError as e:
131
  logger.warning(f"EnhancedVisualizationEngine not available: {e}")
132
- # Create mock visualization engine
133
- class EnhancedVisualizationEngine:
134
  def create_executive_dashboard(self, data=None):
135
  import plotly.graph_objects as go
136
  fig = go.Figure()
137
- fig.update_layout(height=400)
138
  return fig
139
- viz_engine_available = True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
 
141
  # Import UI components
142
  try:
@@ -146,141 +321,66 @@ def import_components():
146
  create_tab4_audit_trail, create_tab5_learning_engine,
147
  create_footer
148
  )
149
- ui_available = True
 
 
 
 
 
 
 
 
 
150
  logger.info("UI components imported successfully")
151
  except ImportError as e:
152
  logger.error(f"UI components not available: {e}")
153
- ui_available = False
154
  # Create minimal UI fallbacks
155
- def create_header(version="3.3.6", mock_mode=False):
156
- import gradio as gr
157
- return gr.HTML(f"<h2>πŸš€ ARF v{version}</h2>")
158
-
159
- def create_status_bar():
160
- import gradio as gr
161
- return gr.HTML("<div>Status</div>")
162
-
163
- def create_tab1_incident_demo(*args, **kwargs):
164
- import gradio as gr
165
- return [gr.Dropdown()] * 24
166
-
167
- def create_tab2_business_roi(*args, **kwargs):
168
- import gradio as gr
169
- return [gr.Plot()] * 7
170
-
171
- def create_tab3_enterprise_features():
172
- import gradio as gr
173
- return [gr.JSON()] * 8
174
-
175
- def create_tab4_audit_trail():
176
- import gradio as gr
177
- return [gr.Button()] * 6
178
-
179
- def create_tab5_learning_engine():
180
- import gradio as gr
181
- return [gr.Plot()] * 10
182
-
183
- def create_footer():
184
- import gradio as gr
185
- return gr.HTML("<footer>ARF</footer>")
186
 
187
- # Import styles - with fallback
188
  try:
189
  from ui.styles import get_styles
190
- styles_available = True
191
  except ImportError as e:
192
  logger.warning(f"Styles not available: {e}")
193
- get_styles = lambda: ""
194
- styles_available = False
195
 
 
 
196
  logger.info("βœ… Successfully imported all modular components")
197
 
198
- return {
199
- "INCIDENT_SCENARIOS": INCIDENT_SCENARIOS,
200
- "DemoOrchestrator": DemoOrchestrator,
201
- "EnhancedROICalculator": EnhancedROICalculator() if roi_calculator_available else None,
202
- "EnhancedVisualizationEngine": EnhancedVisualizationEngine() if viz_engine_available else None,
203
- "create_header": create_header,
204
- "create_status_bar": create_status_bar,
205
- "create_tab1_incident_demo": create_tab1_incident_demo,
206
- "create_tab2_business_roi": create_tab2_business_roi,
207
- "create_tab3_enterprise_features": create_tab3_enterprise_features,
208
- "create_tab4_audit_trail": create_tab4_audit_trail,
209
- "create_tab5_learning_engine": create_tab5_learning_engine,
210
- "create_footer": create_footer,
211
- "get_styles": get_styles if styles_available else lambda: "",
212
- "all_available": True
213
- }
214
-
215
  except Exception as e:
216
  logger.error(f"❌ CRITICAL IMPORT ERROR: {e}")
217
  logger.error(traceback.format_exc())
218
-
219
- # Return minimal components for fallback
220
- import gradio as gr
221
-
222
- # Create minimal mock components
223
- class MockCalculator:
224
- def calculate_comprehensive_roi(self, **kwargs):
225
- return {
226
- "status": "Mock calculation",
227
- "summary": {"roi_multiplier": "5.2Γ—"},
228
- "scenarios": {
229
- "base_case": {"roi": "5.2Γ—"},
230
- "best_case": {"roi": "6.5Γ—"},
231
- "worst_case": {"roi": "4.0Γ—"}
232
- }
233
- }
234
-
235
- class MockVisualizationEngine:
236
- def create_executive_dashboard(self, data=None):
237
- import plotly.graph_objects as go
238
- fig = go.Figure()
239
- fig.update_layout(height=400)
240
- return fig
241
-
242
- class MockOrchestrator:
243
- async def analyze_incident(self, name, scenario):
244
- return {"status": "mock", "scenario": name}
245
-
246
- return {
247
- "all_available": False,
248
- "error": str(e),
249
- "INCIDENT_SCENARIOS": {"Cache Miss Storm": {}},
250
- "DemoOrchestrator": MockOrchestrator(),
251
- "EnhancedROICalculator": MockCalculator(),
252
- "EnhancedVisualizationEngine": MockVisualizationEngine(),
253
- "create_header": lambda version, mock: gr.HTML(f"<h2>πŸš€ ARF v{version}</h2>"),
254
- "create_status_bar": lambda: gr.HTML("<div>Status</div>"),
255
- "create_tab1_incident_demo": lambda *args: [gr.Dropdown()] * 24,
256
- "create_tab2_business_roi": lambda *args: [gr.Plot()] * 7,
257
- "create_tab3_enterprise_features": lambda: [gr.JSON()] * 8,
258
- "create_tab4_audit_trail": lambda: [gr.Button()] * 6,
259
- "create_tab5_learning_engine": lambda: [gr.Plot()] * 10,
260
- "create_footer": lambda: gr.HTML("<footer>ARF</footer>"),
261
- "get_styles": lambda: ""
262
- }
263
 
264
- # Import components safely
265
- components = import_components()
 
 
 
266
 
267
- # Extract components
268
- INCIDENT_SCENARIOS = components["INCIDENT_SCENARIOS"]
269
- DemoOrchestrator = components["DemoOrchestrator"]
270
- EnhancedROICalculator = components["EnhancedROICalculator"]
271
- EnhancedVisualizationEngine = components["EnhancedVisualizationEngine"]
272
- create_header = components["create_header"]
273
- create_status_bar = components["create_status_bar"]
274
- create_tab1_incident_demo = components["create_tab1_incident_demo"]
275
- create_tab2_business_roi = components["create_tab2_business_roi"]
276
- create_tab3_enterprise_features = components["create_tab3_enterprise_features"]
277
- create_tab4_audit_trail = components["create_tab4_audit_trail"]
278
- create_tab5_learning_engine = components["create_tab5_learning_engine"]
279
- create_footer = components["create_footer"]
280
- get_styles = components["get_styles"]
281
 
282
  # ===========================================
283
- # AUDIT TRAIL MANAGER - ENHANCED
284
  # ===========================================
285
  class AuditTrailManager:
286
  """Enhanced audit trail manager"""
@@ -288,6 +388,7 @@ class AuditTrailManager:
288
  def __init__(self):
289
  self.executions = []
290
  self.incidents = []
 
291
 
292
  def add_execution(self, scenario: str, mode: str, success: bool = True, savings: float = 0) -> Dict:
293
  """Add execution to audit trail"""
@@ -308,7 +409,7 @@ class AuditTrailManager:
308
  "time": datetime.datetime.now().strftime("%H:%M"),
309
  "scenario": scenario,
310
  "severity": severity,
311
- "component": INCIDENT_SCENARIOS.get(scenario, {}).get("component", "unknown"),
312
  "status": "Analyzed"
313
  }
314
  self.incidents.insert(0, entry)
@@ -333,6 +434,13 @@ class AuditTrailManager:
333
  self.executions = []
334
  self.incidents = []
335
 
 
 
 
 
 
 
 
336
  # ===========================================
337
  # HELPER FUNCTIONS
338
  # ===========================================
@@ -378,194 +486,61 @@ def extract_roi_multiplier(roi_result: Dict) -> float:
378
  return 5.2
379
 
380
  # ===========================================
381
- # VISUALIZATION HELPERS
382
  # ===========================================
383
  def create_telemetry_plot(scenario_name: str):
384
  """Create a telemetry visualization for the selected scenario"""
385
- import plotly.graph_objects as go
386
- import numpy as np
387
-
388
- # Generate sample data
389
- time_points = np.arange(0, 100, 1)
390
-
391
- # Different patterns for different scenarios
392
- if "Cache" in scenario_name:
393
- data = 100 + 50 * np.sin(time_points * 0.2) + np.random.normal(0, 10, 100)
394
- threshold = 180
395
- metric_name = "Cache Hit Rate (%)"
396
- elif "Database" in scenario_name:
397
- data = 70 + 30 * np.sin(time_points * 0.15) + np.random.normal(0, 8, 100)
398
- threshold = 120
399
- metric_name = "Connection Pool Usage"
400
- elif "Memory" in scenario_name:
401
- data = 50 + 40 * np.sin(time_points * 0.1) + np.random.normal(0, 12, 100)
402
- threshold = 95
403
- metric_name = "Memory Usage (%)"
404
- else:
405
- data = 80 + 20 * np.sin(time_points * 0.25) + np.random.normal(0, 5, 100)
406
- threshold = 110
407
- metric_name = "System Load"
408
-
409
- # Create the plot
410
- fig = go.Figure()
411
-
412
- # Add normal data
413
- fig.add_trace(go.Scatter(
414
- x=time_points[:70],
415
- y=data[:70],
416
- mode='lines',
417
- name='Normal',
418
- line=dict(color='#3b82f6', width=3),
419
- fill='tozeroy',
420
- fillcolor='rgba(59, 130, 246, 0.1)'
421
- ))
422
-
423
- # Add anomaly data
424
- fig.add_trace(go.Scatter(
425
- x=time_points[70:],
426
- y=data[70:],
427
- mode='lines',
428
- name='Anomaly Detected',
429
- line=dict(color='#ef4444', width=3, dash='dash'),
430
- fill='tozeroy',
431
- fillcolor='rgba(239, 68, 68, 0.1)'
432
- ))
433
-
434
- # Add threshold line
435
- fig.add_hline(
436
- y=threshold,
437
- line_dash="dot",
438
- line_color="#f59e0b",
439
- annotation_text="Threshold",
440
- annotation_position="bottom right"
441
- )
442
-
443
- # Add detection point
444
- fig.add_vline(
445
- x=70,
446
- line_dash="dash",
447
- line_color="#10b981",
448
- annotation_text="ARF Detection",
449
- annotation_position="top"
450
- )
451
-
452
- # Update layout
453
- fig.update_layout(
454
- title=f"πŸ“ˆ {metric_name} - Live Telemetry",
455
- xaxis_title="Time (minutes)",
456
- yaxis_title=metric_name,
457
- height=300,
458
- margin=dict(l=20, r=20, t=50, b=20),
459
- plot_bgcolor='rgba(0,0,0,0)',
460
- paper_bgcolor='rgba(0,0,0,0)',
461
- legend=dict(
462
- orientation="h",
463
- yanchor="bottom",
464
- y=1.02,
465
- xanchor="right",
466
- x=1
467
- )
468
- )
469
-
470
- return fig
471
 
472
  def create_impact_plot(scenario_name: str):
473
  """Create a business impact visualization"""
474
- import plotly.graph_objects as go
475
-
476
- # Get impact data
477
- impact_map = {
478
- "Cache Miss Storm": {"revenue": 8500, "users": 45000, "services": 12},
479
- "Database Connection Pool Exhaustion": {"revenue": 4200, "users": 22000, "services": 8},
480
- "Kubernetes Memory Leak": {"revenue": 5500, "users": 28000, "services": 15},
481
- "API Rate Limit Storm": {"revenue": 3800, "users": 19000, "services": 6},
482
- "Network Partition": {"revenue": 12000, "users": 65000, "services": 25},
483
- "Storage I/O Saturation": {"revenue": 6800, "users": 32000, "services": 10}
484
- }
485
-
486
- impact = impact_map.get(scenario_name, {"revenue": 5000, "users": 25000, "services": 10})
487
-
488
- # Create gauge
489
- fig = go.Figure(go.Indicator(
490
- mode="gauge+number",
491
- value=impact["revenue"],
492
- title={'text': "πŸ’° Hourly Revenue Risk", 'font': {'size': 16}},
493
- number={'prefix': "$", 'font': {'size': 28}},
494
- gauge={
495
- 'axis': {'range': [0, 15000], 'tickwidth': 1},
496
- 'bar': {'color': "#ef4444"},
497
- 'steps': [
498
- {'range': [0, 3000], 'color': '#10b981'},
499
- {'range': [3000, 7000], 'color': '#f59e0b'},
500
- {'range': [7000, 15000], 'color': '#ef4444'}
501
- ],
502
- 'threshold': {
503
- 'line': {'color': "black", 'width': 4},
504
- 'thickness': 0.75,
505
- 'value': impact["revenue"]
506
- }
507
- }
508
- ))
509
-
510
- fig.update_layout(
511
- height=300,
512
- margin=dict(l=20, r=20, t=50, b=20),
513
- paper_bgcolor='rgba(0,0,0,0)'
514
- )
515
-
516
- return fig
517
 
518
  def create_timeline_plot(scenario_name: str):
519
  """Create an incident timeline visualization"""
520
- import plotly.graph_objects as go
521
-
522
- # Timeline data
523
- events = [
524
- {"time": 0, "event": "Incident Starts", "duration": 45},
525
- {"time": 45, "event": "ARF Detection", "duration": 30},
526
- {"time": 75, "event": "OSS Analysis Complete", "duration": 60},
527
- {"time": 135, "event": "Enterprise Execution", "duration": 720},
528
- {"time": 2700, "event": "Manual Resolution", "duration": 0}
529
- ]
530
-
531
- # Create timeline
532
- fig = go.Figure()
533
-
534
- # Add event bars
535
- for i, event in enumerate(events):
536
- if event["duration"] > 0:
537
- fig.add_trace(go.Bar(
538
- x=[event["duration"]],
539
- y=[event["event"]],
540
- orientation='h',
541
- name=event["event"],
542
- marker_color=['#3b82f6', '#10b981', '#8b5cf6', '#f59e0b', '#ef4444'][i],
543
- text=[f"{event['duration']}s"],
544
- textposition='auto',
545
- hoverinfo='text',
546
- hovertemplate=f"{event['event']}: {event['duration']} seconds<extra></extra>"
547
- ))
548
-
549
- fig.update_layout(
550
- title="⏰ Incident Timeline Comparison",
551
- xaxis_title="Time (seconds)",
552
- yaxis_title="",
553
- barmode='stack',
554
- height=300,
555
- margin=dict(l=20, r=20, t=50, b=20),
556
- plot_bgcolor='rgba(0,0,0,0)',
557
- paper_bgcolor='rgba(0,0,0,0)',
558
- showlegend=False
559
- )
560
-
561
- return fig
562
 
563
  # ===========================================
564
  # SCENARIO UPDATE HANDLER
565
  # ===========================================
566
  def update_scenario_display(scenario_name: str) -> tuple:
567
  """Update all scenario-related displays"""
568
- scenario = INCIDENT_SCENARIOS.get(scenario_name, {})
569
  impact = scenario.get("business_impact", {})
570
  metrics = scenario.get("metrics", {})
571
 
@@ -594,7 +569,7 @@ def update_scenario_display(scenario_name: str) -> tuple:
594
  <span style="font-size: 14px; color: #1e293b; font-weight: 600;">45 seconds (ARF AI)</span>
595
  </div>
596
  <div style="display: flex; flex-wrap: wrap; gap: 6px; margin-top: 15px; padding-top: 12px; border-top: 1px solid #f1f5f9;">
597
- <span style="padding: 3px 8px; background: #f1f5f9; border-radius: 6px; font-size: 11px; color: #475569; font-weight: 500;">{scenario.get('component', 'unknown').split('_')[0]}</span>
598
  <span style="padding: 3px 8px; background: #f1f5f9; border-radius: 6px; font-size: 11px; color: #475569; font-weight: 500;">{scenario.get('severity', 'high').lower()}</span>
599
  <span style="padding: 3px 8px; background: #f1f5f9; border-radius: 6px; font-size: 11px; color: #475569; font-weight: 500;">production</span>
600
  <span style="padding: 3px 8px; background: #f1f5f9; border-radius: 6px; font-size: 11px; color: #475569; font-weight: 500;">incident</span>
@@ -616,100 +591,143 @@ def update_scenario_display(scenario_name: str) -> tuple:
616
  )
617
 
618
  # ===========================================
619
- # OSS ANALYSIS HANDLER
620
  # ===========================================
621
  @AsyncRunner.async_to_sync
622
  async def run_oss_analysis(scenario_name: str):
623
- """Run OSS analysis"""
624
- scenario = INCIDENT_SCENARIOS.get(scenario_name, {})
625
-
626
- # Use orchestrator
627
- orchestrator = DemoOrchestrator()
628
- analysis = await orchestrator.analyze_incident(scenario_name, scenario)
629
-
630
- # Add to audit trail
631
- audit_manager.add_incident(scenario_name, scenario.get("severity", "HIGH"))
632
-
633
- # Update incident table
634
- incident_table_data = audit_manager.get_incident_table()
635
-
636
- # Enhanced OSS results
637
- oss_results = {
638
- "status": "βœ… OSS Analysis Complete",
639
- "scenario": scenario_name,
640
- "confidence": 0.85,
641
- "agents_executed": ["Detection", "Recall", "Decision"],
642
- "findings": [
643
- "Anomaly detected with 99.8% confidence",
644
- "3 similar incidents found in RAG memory",
645
- "Historical success rate for similar actions: 87%"
646
- ],
647
- "recommendations": [
648
- "Scale resources based on historical patterns",
649
- "Implement circuit breaker pattern",
650
- "Add enhanced monitoring for key metrics"
651
- ],
652
- "healing_intent": {
653
- "action": "scale_out",
654
- "component": scenario.get("component", "unknown"),
655
- "parameters": {"nodes": "3β†’5", "region": "auto-select"},
656
- "confidence": 0.94,
657
- "requires_enterprise": True,
658
- "advisory_only": True,
659
- "safety_check": "βœ… Passed (blast radius: 2 services)"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
660
  }
661
- }
662
-
663
- # Update agent status
664
- detection_html = """
665
- <div class="agent-card detection">
666
- <div class="agent-icon">πŸ•΅οΈβ€β™‚οΈ</div>
667
- <div class="agent-content">
668
- <h4>Detection Agent</h4>
669
- <p class="agent-status-text">Analysis complete: <strong>99.8% confidence</strong></p>
670
- <div class="agent-metrics">
671
- <span class="agent-metric">Time: 45s</span>
672
- <span class="agent-metric">Accuracy: 98.7%</span>
 
673
  </div>
674
- <div class="agent-status completed">COMPLETE</div>
675
  </div>
676
- </div>
677
- """
678
-
679
- recall_html = """
680
- <div class="agent-card recall">
681
- <div class="agent-icon">🧠</div>
682
- <div class="agent-content">
683
- <h4>Recall Agent</h4>
684
- <p class="agent-status-text"><strong>3 similar incidents</strong> retrieved from memory</p>
685
- <div class="agent-metrics">
686
- <span class="agent-metric">Recall: 92%</span>
687
- <span class="agent-metric">Patterns: 5</span>
 
688
  </div>
689
- <div class="agent-status completed">COMPLETE</div>
690
  </div>
691
- </div>
692
- """
693
-
694
- decision_html = """
695
- <div class="agent-card decision">
696
- <div class="agent-icon">🎯</div>
697
- <div class="agent-content">
698
- <h4>Decision Agent</h4>
699
- <p class="agent-status-text">HealingIntent created with <strong>94% confidence</strong></p>
700
- <div class="agent-metrics">
701
- <span class="agent-metric">Success Rate: 87%</span>
702
- <span class="agent-metric">Safety: 100%</span>
 
703
  </div>
704
- <div class="agent-status completed">COMPLETE</div>
705
  </div>
706
- </div>
707
- """
708
-
709
- return (
710
- detection_html, recall_html, decision_html,
711
- oss_results, incident_table_data
712
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
713
 
714
  # ===========================================
715
  # CREATE DEMO INTERFACE
@@ -719,13 +737,8 @@ def create_demo_interface():
719
 
720
  import gradio as gr
721
 
722
- # Initialize components
723
- viz_engine = EnhancedVisualizationEngine
724
- roi_calculator = EnhancedROICalculator
725
- audit_manager = AuditTrailManager()
726
-
727
  # Get CSS styles
728
- css_styles = get_styles()
729
 
730
  with gr.Blocks(
731
  title=f"πŸš€ ARF Investor Demo v3.8.0 - {settings.arf_mode.upper()} Mode",
@@ -733,10 +746,10 @@ def create_demo_interface():
733
  ) as demo:
734
 
735
  # Header
736
- header_html = create_header("3.8.0", settings.use_mock_arf)
737
 
738
  # Status bar
739
- status_html = create_status_bar()
740
 
741
  # ============ 5 TABS ============
742
  with gr.Tabs(elem_classes="tab-nav"):
@@ -748,31 +761,31 @@ def create_demo_interface():
748
  oss_section, enterprise_section, oss_btn, enterprise_btn,
749
  approval_toggle, mcp_mode, timeline_viz,
750
  detection_time, mttr, auto_heal, savings,
751
- oss_results_display, enterprise_results_display, approval_display, demo_btn) = create_tab1_incident_demo()
752
 
753
  # TAB 2: Business ROI
754
  with gr.TabItem("πŸ’° Business Impact & ROI", id="tab2"):
755
  (dashboard_output, roi_scenario_dropdown, monthly_slider, team_slider,
756
- calculate_btn, roi_output, roi_chart) = create_tab2_business_roi(INCIDENT_SCENARIOS)
757
 
758
  # TAB 3: Enterprise Features
759
  with gr.TabItem("🏒 Enterprise Features", id="tab3"):
760
  (license_display, validate_btn, trial_btn, upgrade_btn,
761
- mcp_mode_tab3, mcp_mode_info, features_table, integrations_table) = create_tab3_enterprise_features()
762
 
763
  # TAB 4: Audit Trail
764
  with gr.TabItem("πŸ“œ Audit Trail & History", id="tab4"):
765
  (refresh_btn, clear_btn, export_btn, execution_table,
766
- incident_table, export_text) = create_tab4_audit_trail()
767
 
768
  # TAB 5: Learning Engine
769
  with gr.TabItem("🧠 Learning Engine", id="tab5"):
770
  (learning_graph, graph_type, show_labels, search_query, search_btn,
771
  clear_btn_search, search_results, stats_display, patterns_display,
772
- performance_display) = create_tab5_learning_engine()
773
 
774
  # Footer
775
- footer_html = create_footer()
776
 
777
  # ============ EVENT HANDLERS ============
778
 
@@ -795,12 +808,12 @@ def create_demo_interface():
795
 
796
  # Execute Enterprise Healing
797
  def execute_enterprise_healing(scenario_name, approval_required, mcp_mode_value):
798
- scenario = INCIDENT_SCENARIOS.get(scenario_name, {})
799
 
800
  # Determine mode
801
  mode = "Approval" if approval_required else "Autonomous"
802
  if "Advisory" in mcp_mode_value:
803
- return gr.HTML.update(value="<div class='approval-status'><p>❌ Cannot execute in Advisory mode. Switch to Approval or Autonomous mode.</p></div>"), {}, []
804
 
805
  # Calculate savings
806
  impact = scenario.get("business_impact", {})
@@ -808,45 +821,45 @@ def create_demo_interface():
808
  savings = int(revenue_loss * 0.85)
809
 
810
  # Add to audit trail
811
- audit_manager.add_execution(scenario_name, mode, savings=savings)
812
 
813
  # Create approval display
814
  if approval_required:
815
  approval_html = f"""
816
- <div class="approval-status">
817
- <div class="approval-header">
818
- <h4>πŸ‘€ Human Approval Required</h4>
819
- <span class="approval-badge pending">PENDING</span>
820
  </div>
821
- <div class="approval-content">
822
- <p><strong>Scenario:</strong> {scenario_name}</p>
823
- <p><strong>Action:</strong> Scale Redis cluster from 3 to 5 nodes</p>
824
- <p><strong>Estimated Savings:</strong> <span class='savings-highlight'>${savings:,}</span></p>
825
- <div class="approval-workflow">
826
- <div class="workflow-step">βœ… 1. ARF generated intent (94% confidence)</div>
827
- <div class="workflow-step">⏳ 2. Awaiting human review...</div>
828
- <div class="workflow-step">3. ARF will execute upon approval</div>
829
  </div>
830
  </div>
831
  </div>
832
  """
833
  else:
834
  approval_html = f"""
835
- <div class="approval-status">
836
- <div class="approval-header">
837
- <h4>⚑ Autonomous Execution Complete</h4>
838
- <span class="approval-badge not-required">AUTO-EXECUTED</span>
839
  </div>
840
- <div class="approval-content">
841
- <p><strong>Scenario:</strong> {scenario_name}</p>
842
- <p><strong>Mode:</strong> Autonomous</p>
843
- <p><strong>Action Executed:</strong> Scaled Redis cluster from 3 to 5 nodes</p>
844
- <p><strong>Recovery Time:</strong> 12 minutes (vs 45 min manual)</p>
845
- <p><strong>Cost Saved:</strong> <span class='savings-highlight'>${savings:,}</span></p>
846
- <div class="approval-workflow">
847
- <div class="workflow-step">βœ… 1. ARF generated intent</div>
848
- <div class="workflow-step">βœ… 2. Safety checks passed</div>
849
- <div class="workflow-step">βœ… 3. Autonomous execution completed</div>
850
  </div>
851
  </div>
852
  </div>
@@ -878,7 +891,7 @@ def create_demo_interface():
878
  }
879
 
880
  # Update execution table
881
- execution_table_data = audit_manager.get_execution_table()
882
 
883
  return approval_html, enterprise_results, execution_table_data
884
 
@@ -899,9 +912,9 @@ def create_demo_interface():
899
  oss_result = await run_oss_analysis(scenario_name)
900
 
901
  # Step 3: Execute Enterprise (simulated)
902
- await asyncio.sleep(2)
903
 
904
- scenario = INCIDENT_SCENARIOS.get(scenario_name, {})
905
  impact = scenario.get("business_impact", {})
906
  revenue_loss = impact.get("revenue_loss_per_hour", 5000)
907
  savings = int(revenue_loss * 0.85)
@@ -928,17 +941,17 @@ def create_demo_interface():
928
 
929
  # Create demo completion message
930
  demo_message = f"""
931
- <div class="scenario-card" style="background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);">
932
- <div class="scenario-header">
933
- <h3>βœ… Demo Complete</h3>
934
- <span class="severity-badge low">SUCCESS</span>
935
  </div>
936
- <div class="scenario-details">
937
- <p><strong>Scenario:</strong> {scenario_name}</p>
938
- <p><strong>Workflow:</strong> OSS Analysis β†’ Enterprise Execution</p>
939
- <p><strong>Time Saved:</strong> 33 minutes (73% faster)</p>
940
- <p><strong>Cost Avoided:</strong> ${savings:,}</p>
941
- <p><em>This demonstrates the complete ARF value proposition from detection to autonomous healing.</em></p>
942
  </div>
943
  </div>
944
  """
@@ -976,6 +989,7 @@ def create_demo_interface():
976
  avg_impact = get_scenario_impact(scenario_name)
977
 
978
  # Calculate ROI
 
979
  roi_result = roi_calculator.calculate_comprehensive_roi(
980
  monthly_incidents=monthly_incidents,
981
  avg_impact=float(avg_impact),
@@ -986,6 +1000,7 @@ def create_demo_interface():
986
  roi_multiplier = extract_roi_multiplier(roi_result)
987
 
988
  # Create visualization
 
989
  chart = viz_engine.create_executive_dashboard({"roi_multiplier": roi_multiplier})
990
 
991
  return roi_result, chart
@@ -1007,6 +1022,7 @@ def create_demo_interface():
1007
  }
1008
 
1009
  # Always return a valid chart
 
1010
  fallback_chart = viz_engine.create_executive_dashboard({"roi_multiplier": 5.2})
1011
 
1012
  return fallback_result, fallback_chart
@@ -1079,16 +1095,17 @@ def create_demo_interface():
1079
  # ============ TAB 4 HANDLERS ============
1080
 
1081
  def refresh_audit_trail():
1082
- return audit_manager.get_execution_table(), audit_manager.get_incident_table()
1083
 
1084
  def clear_audit_trail():
1085
- audit_manager.clear()
1086
- return audit_manager.get_execution_table(), audit_manager.get_incident_table()
1087
 
1088
  def export_audit_trail():
1089
  try:
1090
  # Calculate total savings
1091
  total_savings = 0
 
1092
  for e in audit_manager.executions:
1093
  if e['savings'] != '$0':
1094
  try:
@@ -1127,6 +1144,7 @@ def create_demo_interface():
1127
  # Initialize dashboard
1128
  def initialize_dashboard():
1129
  try:
 
1130
  chart = viz_engine.create_executive_dashboard()
1131
  return chart
1132
  except Exception as e:
@@ -1168,7 +1186,8 @@ def main():
1168
  demo.launch(
1169
  server_name="0.0.0.0",
1170
  server_port=7860,
1171
- share=False
 
1172
  )
1173
 
1174
 
 
1
  """
2
  πŸš€ ARF Ultimate Investor Demo v3.8.0 - ENTERPRISE EDITION
3
  MODULAR VERSION - Properly integrated with all components
4
+ ULTIMATE FIXED VERSION with all critical issues resolved
5
  """
6
 
7
  import logging
 
31
  sys.path.insert(0, str(Path(__file__).parent))
32
 
33
  # ===========================================
34
+ # ASYNC UTILITIES - ENHANCED VERSION
35
  # ===========================================
36
  class AsyncRunner:
37
+ """Enhanced async runner with better error handling"""
38
+
39
  @staticmethod
40
  def run_async(coro):
41
  """Run async coroutine in sync context"""
 
44
  except RuntimeError:
45
  loop = asyncio.new_event_loop()
46
  asyncio.set_event_loop(loop)
47
+
48
+ try:
49
+ return loop.run_until_complete(coro)
50
+ except Exception as e:
51
+ logger.error(f"Async execution failed: {e}")
52
+ # Return error state instead of crashing
53
+ return {"error": str(e), "status": "failed"}
54
 
55
  @staticmethod
56
  def async_to_sync(async_func):
57
  """Decorator to convert async function to sync"""
58
  def wrapper(*args, **kwargs):
59
+ try:
60
+ return AsyncRunner.run_async(async_func(*args, **kwargs))
61
+ except Exception as e:
62
+ logger.error(f"Async to sync conversion failed: {e}")
63
+ # Return a sensible fallback
64
+ return {"error": str(e), "status": "failed"}
65
  return wrapper
66
 
67
  # ===========================================
68
+ # SIMPLE SETTINGS
69
  # ===========================================
70
  class Settings:
71
+ """Simple settings class"""
72
  def __init__(self):
73
  self.arf_mode = "demo"
74
  self.use_mock_arf = True
 
79
  settings = Settings()
80
 
81
  # ===========================================
82
+ # FIXED DEMO ORCHESTRATOR (Inlined to avoid import issues)
83
+ # ===========================================
84
+ class FixedDemoOrchestrator:
85
+ """
86
+ Fixed orchestrator with proper analyze_incident method
87
+ This replaces the broken DemoOrchestrator from demo/orchestrator.py
88
+ """
89
+
90
+ def __init__(self):
91
+ logger.info("FixedDemoOrchestrator initialized")
92
+ # Lazy load mock functions
93
+ self._mock_functions_loaded = False
94
+ self._simulate_arf_analysis = None
95
+ self._run_rag_similarity_search = None
96
+ self._create_mock_healing_intent = None
97
+ self._calculate_pattern_confidence = None
98
+
99
+ def _load_mock_functions(self):
100
+ """Lazy load mock ARF functions"""
101
+ if not self._mock_functions_loaded:
102
+ try:
103
+ # Try to import mock ARF functions
104
+ from demo.mock_arf import (
105
+ simulate_arf_analysis,
106
+ run_rag_similarity_search,
107
+ create_mock_healing_intent,
108
+ calculate_pattern_confidence
109
+ )
110
+ self._simulate_arf_analysis = simulate_arf_analysis
111
+ self._run_rag_similarity_search = run_rag_similarity_search
112
+ self._create_mock_healing_intent = create_mock_healing_intent
113
+ self._calculate_pattern_confidence = calculate_pattern_confidence
114
+ self._mock_functions_loaded = True
115
+ logger.info("Mock ARF functions loaded successfully")
116
+ except ImportError as e:
117
+ logger.error(f"Failed to load mock ARF functions: {e}")
118
+ # Create fallback functions
119
+ self._create_fallback_functions()
120
+
121
+ def _create_fallback_functions(self):
122
+ """Create fallback mock functions"""
123
+ import random
124
+ import time as ttime
125
+
126
+ def simulate_arf_analysis(scenario):
127
+ return {
128
+ "analysis_complete": True,
129
+ "anomaly_detected": True,
130
+ "severity": "HIGH",
131
+ "confidence": 0.987,
132
+ "detection_time_ms": 45
133
+ }
134
+
135
+ def run_rag_similarity_search(scenario):
136
+ return [
137
+ {
138
+ "incident_id": f"inc_{int(ttime.time())}_1",
139
+ "similarity_score": 0.92,
140
+ "success": True,
141
+ "resolution": "scale_out",
142
+ "cost_savings": 6500
143
+ }
144
+ ]
145
+
146
+ def calculate_pattern_confidence(scenario, similar_incidents):
147
+ return 0.94
148
+
149
+ def create_mock_healing_intent(scenario, similar_incidents, confidence):
150
+ return {
151
+ "action": "scale_out",
152
+ "component": scenario.get("component", "unknown"),
153
+ "confidence": confidence,
154
+ "parameters": {"nodes": "3β†’5"},
155
+ "safety_checks": {"blast_radius": "2 services"}
156
+ }
157
+
158
+ self._simulate_arf_analysis = simulate_arf_analysis
159
+ self._run_rag_similarity_search = run_rag_similarity_search
160
+ self._calculate_pattern_confidence = calculate_pattern_confidence
161
+ self._create_mock_healing_intent = create_mock_healing_intent
162
+ self._mock_functions_loaded = True
163
+ logger.info("Fallback mock functions created")
164
+
165
+ async def analyze_incident(self, scenario_name: str, scenario_data: Dict[str, Any]) -> Dict[str, Any]:
166
+ """
167
+ Analyze an incident using the ARF agent workflow.
168
+ This is the method that was missing in the original DemoOrchestrator
169
+ """
170
+ logger.info(f"FixedDemoOrchestrator analyzing incident: {scenario_name}")
171
+
172
+ # Load mock functions if not loaded
173
+ self._load_mock_functions()
174
+
175
+ try:
176
+ # Step 1: Detection Agent
177
+ logger.debug("Running detection agent...")
178
+ detection_result = self._simulate_arf_analysis(scenario_data)
179
+
180
+ # Step 2: Recall Agent
181
+ logger.debug("Running recall agent...")
182
+ similar_incidents = self._run_rag_similarity_search(scenario_data)
183
+
184
+ # Step 3: Decision Agent
185
+ logger.debug("Running decision agent...")
186
+ confidence = self._calculate_pattern_confidence(scenario_data, similar_incidents)
187
+ healing_intent = self._create_mock_healing_intent(scenario_data, similar_incidents, confidence)
188
+
189
+ # Simulate processing time
190
+ await asyncio.sleep(0.5)
191
+
192
+ result = {
193
+ "status": "success",
194
+ "scenario": scenario_name,
195
+ "detection": detection_result,
196
+ "recall": similar_incidents,
197
+ "decision": healing_intent,
198
+ "confidence": confidence,
199
+ "processing_time_ms": 450
200
+ }
201
+
202
+ logger.info(f"Analysis complete for {scenario_name}")
203
+ return result
204
+
205
+ except Exception as e:
206
+ logger.error(f"Error analyzing incident: {e}", exc_info=True)
207
+ return {
208
+ "status": "error",
209
+ "message": str(e),
210
+ "scenario": scenario_name
211
+ }
212
+
213
+ # ===========================================
214
+ # IMPORT MODULAR COMPONENTS - FIXED VERSION
215
  # ===========================================
216
+ def import_components() -> Dict[str, Any]:
217
  """Safely import all components with proper error handling"""
218
+ components = {
219
+ "all_available": False,
220
+ "error": None
221
+ }
222
+
223
  try:
224
+ # First, import gradio (always available in Hugging Face Spaces)
225
+ import gradio as gr
226
+ components["gr"] = gr
227
+
228
+ # Import scenarios
229
  try:
230
  from demo.scenarios import INCIDENT_SCENARIOS
231
  logger.info(f"Loaded {len(INCIDENT_SCENARIOS)} scenarios from demo module")
232
+ components["INCIDENT_SCENARIOS"] = INCIDENT_SCENARIOS
233
  except ImportError as e:
234
  logger.warning(f"Demo scenarios not available: {e}")
235
  # Create minimal fallback
236
+ components["INCIDENT_SCENARIOS"] = {
237
  "Cache Miss Storm": {
238
  "component": "Redis Cache Cluster",
239
  "severity": "HIGH",
240
  "impact_radius": "85% of users",
241
  "business_impact": {"revenue_loss_per_hour": 8500},
242
  "detection_time": "45 seconds",
243
+ "tags": ["cache", "redis", "latency"],
244
+ "metrics": {"affected_users": 45000}
245
  }
246
  }
247
 
248
+ # Use our fixed orchestrator instead of the broken one
249
+ components["DemoOrchestrator"] = FixedDemoOrchestrator
250
+ logger.info("Using FixedDemoOrchestrator")
251
+
252
+ # Import ROI calculator
 
 
 
 
 
253
  try:
254
  from core.calculators import EnhancedROICalculator
255
+ components["EnhancedROICalculator"] = EnhancedROICalculator()
256
  logger.info("EnhancedROICalculator imported successfully")
257
  except ImportError as e:
258
  logger.warning(f"EnhancedROICalculator not available: {e}")
259
+ class MockCalculator:
 
260
  def calculate_comprehensive_roi(self, **kwargs):
261
  return {
262
  "status": "βœ… Calculated Successfully",
 
269
  "annual_roi_percentage": "420%"
270
  }
271
  }
272
+ components["EnhancedROICalculator"] = MockCalculator()
273
 
274
+ # Import visualizations
275
  try:
276
  from core.visualizations import EnhancedVisualizationEngine
277
+ components["EnhancedVisualizationEngine"] = EnhancedVisualizationEngine()
278
  logger.info("EnhancedVisualizationEngine imported successfully")
279
  except ImportError as e:
280
  logger.warning(f"EnhancedVisualizationEngine not available: {e}")
281
+ class MockVisualizationEngine:
 
282
  def create_executive_dashboard(self, data=None):
283
  import plotly.graph_objects as go
284
  fig = go.Figure()
285
+ fig.update_layout(height=400, title="Executive Dashboard")
286
  return fig
287
+
288
+ def create_telemetry_plot(self, scenario_name, anomaly_detected=True):
289
+ import plotly.graph_objects as go
290
+ import numpy as np
291
+ fig = go.Figure()
292
+ fig.add_trace(go.Scatter(x=[0, 1, 2], y=[0, 1, 0]))
293
+ fig.update_layout(height=300, title=f"Telemetry: {scenario_name}")
294
+ return fig
295
+
296
+ def create_impact_gauge(self, scenario_name):
297
+ import plotly.graph_objects as go
298
+ fig = go.Figure(go.Indicator(
299
+ mode="gauge+number",
300
+ value=8500,
301
+ title={'text': "πŸ’° Hourly Revenue Risk"},
302
+ gauge={'axis': {'range': [0, 15000]}}
303
+ ))
304
+ fig.update_layout(height=300)
305
+ return fig
306
+
307
+ def create_timeline_comparison(self):
308
+ import plotly.graph_objects as go
309
+ fig = go.Figure()
310
+ fig.add_trace(go.Bar(name='Manual', x=['Detection', 'Resolution'], y=[300, 2700]))
311
+ fig.add_trace(go.Bar(name='ARF', x=['Detection', 'Resolution'], y=[45, 720]))
312
+ fig.update_layout(height=400, title="Timeline Comparison")
313
+ return fig
314
+ components["EnhancedVisualizationEngine"] = MockVisualizationEngine()
315
 
316
  # Import UI components
317
  try:
 
321
  create_tab4_audit_trail, create_tab5_learning_engine,
322
  create_footer
323
  )
324
+ components.update({
325
+ "create_header": create_header,
326
+ "create_status_bar": create_status_bar,
327
+ "create_tab1_incident_demo": create_tab1_incident_demo,
328
+ "create_tab2_business_roi": create_tab2_business_roi,
329
+ "create_tab3_enterprise_features": create_tab3_enterprise_features,
330
+ "create_tab4_audit_trail": create_tab4_audit_trail,
331
+ "create_tab5_learning_engine": create_tab5_learning_engine,
332
+ "create_footer": create_footer,
333
+ })
334
  logger.info("UI components imported successfully")
335
  except ImportError as e:
336
  logger.error(f"UI components not available: {e}")
 
337
  # Create minimal UI fallbacks
338
+ components.update({
339
+ "create_header": lambda version="3.3.6", mock=False: gr.HTML(f"<h2>πŸš€ ARF v{version}</h2>"),
340
+ "create_status_bar": lambda: gr.HTML("<div>Status</div>"),
341
+ "create_tab1_incident_demo": lambda *args: [gr.Dropdown()] * 24,
342
+ "create_tab2_business_roi": lambda *args: [gr.Plot()] * 7,
343
+ "create_tab3_enterprise_features": lambda: [gr.JSON()] * 8,
344
+ "create_tab4_audit_trail": lambda: [gr.Button()] * 6,
345
+ "create_tab5_learning_engine": lambda: [gr.Plot()] * 10,
346
+ "create_footer": lambda: gr.HTML("<footer>ARF</footer>"),
347
+ })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
348
 
349
+ # Import styles
350
  try:
351
  from ui.styles import get_styles
352
+ components["get_styles"] = get_styles
353
  except ImportError as e:
354
  logger.warning(f"Styles not available: {e}")
355
+ components["get_styles"] = lambda: ""
 
356
 
357
+ components["all_available"] = True
358
+ components["error"] = None
359
  logger.info("βœ… Successfully imported all modular components")
360
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361
  except Exception as e:
362
  logger.error(f"❌ CRITICAL IMPORT ERROR: {e}")
363
  logger.error(traceback.format_exc())
364
+ components["error"] = str(e)
365
+ components["all_available"] = False
366
+
367
+ return components
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
368
 
369
+ # ===========================================
370
+ # GLOBAL COMPONENTS - LAZY LOADED
371
+ # ===========================================
372
+ _components = None
373
+ _audit_manager = None
374
 
375
+ def get_components() -> Dict[str, Any]:
376
+ """Lazy load components singleton"""
377
+ global _components
378
+ if _components is None:
379
+ _components = import_components()
380
+ return _components
 
 
 
 
 
 
 
 
381
 
382
  # ===========================================
383
+ # AUDIT TRAIL MANAGER - FIXED VERSION
384
  # ===========================================
385
  class AuditTrailManager:
386
  """Enhanced audit trail manager"""
 
388
  def __init__(self):
389
  self.executions = []
390
  self.incidents = []
391
+ logger.info("AuditTrailManager initialized")
392
 
393
  def add_execution(self, scenario: str, mode: str, success: bool = True, savings: float = 0) -> Dict:
394
  """Add execution to audit trail"""
 
409
  "time": datetime.datetime.now().strftime("%H:%M"),
410
  "scenario": scenario,
411
  "severity": severity,
412
+ "component": get_components()["INCIDENT_SCENARIOS"].get(scenario, {}).get("component", "unknown"),
413
  "status": "Analyzed"
414
  }
415
  self.incidents.insert(0, entry)
 
434
  self.executions = []
435
  self.incidents = []
436
 
437
+ def get_audit_manager() -> AuditTrailManager:
438
+ """Lazy load audit manager singleton"""
439
+ global _audit_manager
440
+ if _audit_manager is None:
441
+ _audit_manager = AuditTrailManager()
442
+ return _audit_manager
443
+
444
  # ===========================================
445
  # HELPER FUNCTIONS
446
  # ===========================================
 
486
  return 5.2
487
 
488
  # ===========================================
489
+ # VISUALIZATION HELPERS - USING ENHANCED ENGINE
490
  # ===========================================
491
  def create_telemetry_plot(scenario_name: str):
492
  """Create a telemetry visualization for the selected scenario"""
493
+ try:
494
+ viz_engine = get_components()["EnhancedVisualizationEngine"]
495
+ return viz_engine.create_telemetry_plot(scenario_name, anomaly_detected=True)
496
+ except Exception as e:
497
+ logger.error(f"Failed to create telemetry plot: {e}")
498
+ # Fallback
499
+ import plotly.graph_objects as go
500
+ fig = go.Figure()
501
+ fig.add_trace(go.Scatter(x=[0, 1, 2], y=[0, 1, 0]))
502
+ fig.update_layout(height=300, title=f"Telemetry: {scenario_name}")
503
+ return fig
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504
 
505
  def create_impact_plot(scenario_name: str):
506
  """Create a business impact visualization"""
507
+ try:
508
+ viz_engine = get_components()["EnhancedVisualizationEngine"]
509
+ return viz_engine.create_impact_gauge(scenario_name)
510
+ except Exception as e:
511
+ logger.error(f"Failed to create impact plot: {e}")
512
+ # Fallback
513
+ import plotly.graph_objects as go
514
+ fig = go.Figure(go.Indicator(
515
+ mode="gauge+number",
516
+ value=8500,
517
+ title={'text': "πŸ’° Hourly Revenue Risk"},
518
+ gauge={'axis': {'range': [0, 15000]}}
519
+ ))
520
+ fig.update_layout(height=300)
521
+ return fig
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
522
 
523
  def create_timeline_plot(scenario_name: str):
524
  """Create an incident timeline visualization"""
525
+ try:
526
+ viz_engine = get_components()["EnhancedVisualizationEngine"]
527
+ return viz_engine.create_timeline_comparison()
528
+ except Exception as e:
529
+ logger.error(f"Failed to create timeline plot: {e}")
530
+ # Fallback
531
+ import plotly.graph_objects as go
532
+ fig = go.Figure()
533
+ fig.add_trace(go.Bar(name='Manual', x=['Detection', 'Resolution'], y=[300, 2700]))
534
+ fig.add_trace(go.Bar(name='ARF', x=['Detection', 'Resolution'], y=[45, 720]))
535
+ fig.update_layout(height=400, title="Timeline Comparison")
536
+ return fig
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
537
 
538
  # ===========================================
539
  # SCENARIO UPDATE HANDLER
540
  # ===========================================
541
  def update_scenario_display(scenario_name: str) -> tuple:
542
  """Update all scenario-related displays"""
543
+ scenario = get_components()["INCIDENT_SCENARIOS"].get(scenario_name, {})
544
  impact = scenario.get("business_impact", {})
545
  metrics = scenario.get("metrics", {})
546
 
 
569
  <span style="font-size: 14px; color: #1e293b; font-weight: 600;">45 seconds (ARF AI)</span>
570
  </div>
571
  <div style="display: flex; flex-wrap: wrap; gap: 6px; margin-top: 15px; padding-top: 12px; border-top: 1px solid #f1f5f9;">
572
+ <span style="padding: 3px 8px; background: #f1f5f9; border-radius: 6px; font-size: 11px; color: #475569; font-weight: 500;">{scenario.get('component', 'unknown').split('_')[0] if '_' in scenario.get('component', '') else scenario.get('component', 'unknown')}</span>
573
  <span style="padding: 3px 8px; background: #f1f5f9; border-radius: 6px; font-size: 11px; color: #475569; font-weight: 500;">{scenario.get('severity', 'high').lower()}</span>
574
  <span style="padding: 3px 8px; background: #f1f5f9; border-radius: 6px; font-size: 11px; color: #475569; font-weight: 500;">production</span>
575
  <span style="padding: 3px 8px; background: #f1f5f9; border-radius: 6px; font-size: 11px; color: #475569; font-weight: 500;">incident</span>
 
591
  )
592
 
593
  # ===========================================
594
+ # OSS ANALYSIS HANDLER - FIXED VERSION
595
  # ===========================================
596
  @AsyncRunner.async_to_sync
597
  async def run_oss_analysis(scenario_name: str):
598
+ """Run OSS analysis with robust error handling"""
599
+ try:
600
+ logger.info(f"Running OSS analysis for: {scenario_name}")
601
+
602
+ scenario = get_components()["INCIDENT_SCENARIOS"].get(scenario_name, {})
603
+
604
+ if not scenario:
605
+ raise ValueError(f"Scenario '{scenario_name}' not found")
606
+
607
+ # Use fixed orchestrator
608
+ orchestrator = get_components()["DemoOrchestrator"]()
609
+ analysis = await orchestrator.analyze_incident(scenario_name, scenario)
610
+
611
+ # Check for errors
612
+ if analysis.get("status") == "error":
613
+ error_msg = analysis.get("message", "Unknown error")
614
+ raise ValueError(f"Analysis failed: {error_msg}")
615
+
616
+ # Add to audit trail
617
+ get_audit_manager().add_incident(scenario_name, scenario.get("severity", "HIGH"))
618
+
619
+ # Update incident table
620
+ incident_table_data = get_audit_manager().get_incident_table()
621
+
622
+ # Enhanced OSS results
623
+ detection_confidence = analysis.get("detection", {}).get("confidence", 99.8)
624
+ similar_count = len(analysis.get("recall", []))
625
+ decision_confidence = analysis.get("confidence", 94.0)
626
+
627
+ oss_results = {
628
+ "status": "βœ… OSS Analysis Complete",
629
+ "scenario": scenario_name,
630
+ "confidence": decision_confidence,
631
+ "agents_executed": ["Detection", "Recall", "Decision"],
632
+ "findings": [
633
+ f"Anomaly detected with {detection_confidence}% confidence",
634
+ f"{similar_count} similar incidents found in RAG memory",
635
+ f"Historical success rate for similar actions: 87%"
636
+ ],
637
+ "recommendations": [
638
+ "Scale resources based on historical patterns",
639
+ "Implement circuit breaker pattern",
640
+ "Add enhanced monitoring for key metrics"
641
+ ],
642
+ "healing_intent": analysis.get("decision", {
643
+ "action": "scale_out",
644
+ "component": scenario.get("component", "unknown"),
645
+ "parameters": {"nodes": "3β†’5", "region": "auto-select"},
646
+ "confidence": decision_confidence,
647
+ "requires_enterprise": True,
648
+ "advisory_only": True,
649
+ "safety_check": "βœ… Passed (blast radius: 2 services)"
650
+ })
651
  }
652
+
653
+ # Update agent status HTML - FIXED: Proper HTML with CSS classes
654
+ detection_html = f"""
655
+ <div style="border: 2px solid #3b82f6; border-radius: 14px; padding: 18px; background: #eff6ff; text-align: center; min-height: 180px; display: flex; flex-direction: column; align-items: center; justify-content: center;">
656
+ <div style="font-size: 32px; margin-bottom: 10px;">πŸ•΅οΈβ€β™‚οΈ</div>
657
+ <div style="width: 100%;">
658
+ <h4 style="margin: 0 0 8px 0; font-size: 16px; color: #1e293b;">Detection Agent</h4>
659
+ <p style="font-size: 13px; color: #475569; margin-bottom: 12px; line-height: 1.4;">Analysis complete: <strong>{detection_confidence}% confidence</strong></p>
660
+ <div style="display: flex; justify-content: space-around; margin-bottom: 12px;">
661
+ <span style="font-size: 11px; padding: 3px 8px; background: rgba(255, 255, 255, 0.8); border-radius: 6px; color: #475569; font-weight: 500;">Time: 45s</span>
662
+ <span style="font-size: 11px; padding: 3px 8px; background: rgba(255, 255, 255, 0.8); border-radius: 6px; color: #475569; font-weight: 500;">Accuracy: 98.7%</span>
663
+ </div>
664
+ <div style="display: inline-block; padding: 5px 14px; background: linear-gradient(135deg, #10b981 0%, #059669 100%); border-radius: 20px; font-size: 12px; font-weight: bold; color: white; text-transform: uppercase; letter-spacing: 0.5px;">COMPLETE</div>
665
  </div>
 
666
  </div>
667
+ """
668
+
669
+ recall_html = f"""
670
+ <div style="border: 2px solid #8b5cf6; border-radius: 14px; padding: 18px; background: #f5f3ff; text-align: center; min-height: 180px; display: flex; flex-direction: column; align-items: center; justify-content: center;">
671
+ <div style="font-size: 32px; margin-bottom: 10px;">🧠</div>
672
+ <div style="width: 100%;">
673
+ <h4 style="margin: 0 0 8px 0; font-size: 16px; color: #1e293b;">Recall Agent</h4>
674
+ <p style="font-size: 13px; color: #475569; margin-bottom: 12px; line-height: 1.4;"><strong>{similar_count} similar incidents</strong> retrieved from memory</p>
675
+ <div style="display: flex; justify-content: space-around; margin-bottom: 12px;">
676
+ <span style="font-size: 11px; padding: 3px 8px; background: rgba(255, 255, 255, 0.8); border-radius: 6px; color: #475569; font-weight: 500;">Recall: 92%</span>
677
+ <span style="font-size: 11px; padding: 3px 8px; background: rgba(255, 255, 255, 0.8); border-radius: 6px; color: #475569; font-weight: 500;">Patterns: 5</span>
678
+ </div>
679
+ <div style="display: inline-block; padding: 5px 14px; background: linear-gradient(135deg, #10b981 0%, #059669 100%); border-radius: 20px; font-size: 12px; font-weight: bold; color: white; text-transform: uppercase; letter-spacing: 0.5px;">COMPLETE</div>
680
  </div>
 
681
  </div>
682
+ """
683
+
684
+ decision_html = f"""
685
+ <div style="border: 2px solid #10b981; border-radius: 14px; padding: 18px; background: #f0fdf4; text-align: center; min-height: 180px; display: flex; flex-direction: column; align-items: center; justify-content: center;">
686
+ <div style="font-size: 32px; margin-bottom: 10px;">🎯</div>
687
+ <div style="width: 100%;">
688
+ <h4 style="margin: 0 0 8px 0; font-size: 16px; color: #1e293b;">Decision Agent</h4>
689
+ <p style="font-size: 13px; color: #475569; margin-bottom: 12px; line-height: 1.4;">HealingIntent created with <strong>{decision_confidence}% confidence</strong></p>
690
+ <div style="display: flex; justify-content: space-around; margin-bottom: 12px;">
691
+ <span style="font-size: 11px; padding: 3px 8px; background: rgba(255, 255, 255, 0.8); border-radius: 6px; color: #475569; font-weight: 500;">Success Rate: 87%</span>
692
+ <span style="font-size: 11px; padding: 3px 8px; background: rgba(255, 255, 255, 0.8); border-radius: 6px; color: #475569; font-weight: 500;">Safety: 100%</span>
693
+ </div>
694
+ <div style="display: inline-block; padding: 5px 14px; background: linear-gradient(135deg, #10b981 0%, #059669 100%); border-radius: 20px; font-size: 12px; font-weight: bold; color: white; text-transform: uppercase; letter-spacing: 0.5px;">COMPLETE</div>
695
  </div>
 
696
  </div>
697
+ """
698
+
699
+ logger.info(f"OSS analysis completed successfully for {scenario_name}")
700
+ return (
701
+ detection_html, recall_html, decision_html,
702
+ oss_results, incident_table_data
703
+ )
704
+
705
+ except Exception as e:
706
+ logger.error(f"OSS analysis failed: {e}", exc_info=True)
707
+
708
+ # Return error state with proper HTML
709
+ error_html = f"""
710
+ <div style="border: 2px solid #ef4444; border-radius: 14px; padding: 18px; background: #fef2f2; text-align: center; min-height: 180px; display: flex; flex-direction: column; align-items: center; justify-content: center;">
711
+ <div style="font-size: 32px; margin-bottom: 10px;">❌</div>
712
+ <div style="width: 100%;">
713
+ <h4 style="margin: 0 0 8px 0; font-size: 16px; color: #1e293b;">Analysis Failed</h4>
714
+ <p style="font-size: 13px; color: #475569; margin-bottom: 12px; line-height: 1.4;">Error: {str(e)[:80]}...</p>
715
+ <div style="display: inline-block; padding: 5px 14px; background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%); border-radius: 20px; font-size: 12px; font-weight: bold; color: white; text-transform: uppercase; letter-spacing: 0.5px;">ERROR</div>
716
+ </div>
717
+ </div>
718
+ """
719
+
720
+ error_results = {
721
+ "status": "❌ Analysis Failed",
722
+ "error": str(e),
723
+ "scenario": scenario_name,
724
+ "suggestion": "Check logs and try again"
725
+ }
726
+
727
+ return (
728
+ error_html, error_html, error_html,
729
+ error_results, []
730
+ )
731
 
732
  # ===========================================
733
  # CREATE DEMO INTERFACE
 
737
 
738
  import gradio as gr
739
 
 
 
 
 
 
740
  # Get CSS styles
741
+ css_styles = get_components()["get_styles"]()
742
 
743
  with gr.Blocks(
744
  title=f"πŸš€ ARF Investor Demo v3.8.0 - {settings.arf_mode.upper()} Mode",
 
746
  ) as demo:
747
 
748
  # Header
749
+ header_html = get_components()["create_header"]("3.8.0", settings.use_mock_arf)
750
 
751
  # Status bar
752
+ status_html = get_components()["create_status_bar"]()
753
 
754
  # ============ 5 TABS ============
755
  with gr.Tabs(elem_classes="tab-nav"):
 
761
  oss_section, enterprise_section, oss_btn, enterprise_btn,
762
  approval_toggle, mcp_mode, timeline_viz,
763
  detection_time, mttr, auto_heal, savings,
764
+ oss_results_display, enterprise_results_display, approval_display, demo_btn) = get_components()["create_tab1_incident_demo"]()
765
 
766
  # TAB 2: Business ROI
767
  with gr.TabItem("πŸ’° Business Impact & ROI", id="tab2"):
768
  (dashboard_output, roi_scenario_dropdown, monthly_slider, team_slider,
769
+ calculate_btn, roi_output, roi_chart) = get_components()["create_tab2_business_roi"](get_components()["INCIDENT_SCENARIOS"])
770
 
771
  # TAB 3: Enterprise Features
772
  with gr.TabItem("🏒 Enterprise Features", id="tab3"):
773
  (license_display, validate_btn, trial_btn, upgrade_btn,
774
+ mcp_mode_tab3, mcp_mode_info, features_table, integrations_table) = get_components()["create_tab3_enterprise_features"]()
775
 
776
  # TAB 4: Audit Trail
777
  with gr.TabItem("πŸ“œ Audit Trail & History", id="tab4"):
778
  (refresh_btn, clear_btn, export_btn, execution_table,
779
+ incident_table, export_text) = get_components()["create_tab4_audit_trail"]()
780
 
781
  # TAB 5: Learning Engine
782
  with gr.TabItem("🧠 Learning Engine", id="tab5"):
783
  (learning_graph, graph_type, show_labels, search_query, search_btn,
784
  clear_btn_search, search_results, stats_display, patterns_display,
785
+ performance_display) = get_components()["create_tab5_learning_engine"]()
786
 
787
  # Footer
788
+ footer_html = get_components()["create_footer"]()
789
 
790
  # ============ EVENT HANDLERS ============
791
 
 
808
 
809
  # Execute Enterprise Healing
810
  def execute_enterprise_healing(scenario_name, approval_required, mcp_mode_value):
811
+ scenario = get_components()["INCIDENT_SCENARIOS"].get(scenario_name, {})
812
 
813
  # Determine mode
814
  mode = "Approval" if approval_required else "Autonomous"
815
  if "Advisory" in mcp_mode_value:
816
+ return gr.HTML.update(value="<div style='padding: 20px; background: #fef2f2; border-radius: 14px;'><p>❌ Cannot execute in Advisory mode. Switch to Approval or Autonomous mode.</p></div>"), {}, []
817
 
818
  # Calculate savings
819
  impact = scenario.get("business_impact", {})
 
821
  savings = int(revenue_loss * 0.85)
822
 
823
  # Add to audit trail
824
+ get_audit_manager().add_execution(scenario_name, mode, savings=savings)
825
 
826
  # Create approval display
827
  if approval_required:
828
  approval_html = f"""
829
+ <div style="border: 2px solid #e2e8f0; border-radius: 14px; padding: 20px; background: white; margin-top: 20px;">
830
+ <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; padding-bottom: 12px; border-bottom: 2px solid #f1f5f9;">
831
+ <h4 style="margin: 0; font-size: 16px; color: #1e293b;">πŸ‘€ Human Approval Required</h4>
832
+ <span style="padding: 4px 12px; background: #f59e0b; color: white; border-radius: 8px; font-size: 12px; font-weight: bold; text-transform: uppercase;">PENDING</span>
833
  </div>
834
+ <div style="margin-top: 15px;">
835
+ <p style="margin: 8px 0; font-size: 14px; color: #475569;"><strong>Scenario:</strong> {scenario_name}</p>
836
+ <p style="margin: 8px 0; font-size: 14px; color: #475569;"><strong>Action:</strong> Scale Redis cluster from 3 to 5 nodes</p>
837
+ <p style="margin: 8px 0; font-size: 14px; color: #475569;"><strong>Estimated Savings:</strong> <span style="color: #10b981; font-weight: 700;">${savings:,}</span></p>
838
+ <div style="display: flex; flex-direction: column; gap: 10px; margin-top: 20px;">
839
+ <div style="padding: 12px; background: #f8fafc; border-radius: 10px; border-left: 4px solid #3b82f6; font-size: 14px; color: #475569; font-weight: 500;">βœ… 1. ARF generated intent (94% confidence)</div>
840
+ <div style="padding: 12px; background: #f8fafc; border-radius: 10px; border-left: 4px solid #f59e0b; font-size: 14px; color: #475569; font-weight: 500;">⏳ 2. Awaiting human review...</div>
841
+ <div style="padding: 12px; background: #f8fafc; border-radius: 10px; border-left: 4px solid #3b82f6; font-size: 14px; color: #475569; font-weight: 500;">3. ARF will execute upon approval</div>
842
  </div>
843
  </div>
844
  </div>
845
  """
846
  else:
847
  approval_html = f"""
848
+ <div style="border: 2px solid #e2e8f0; border-radius: 14px; padding: 20px; background: white; margin-top: 20px;">
849
+ <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; padding-bottom: 12px; border-bottom: 2px solid #f1f5f9;">
850
+ <h4 style="margin: 0; font-size: 16px; color: #1e293b;">⚑ Autonomous Execution Complete</h4>
851
+ <span style="padding: 4px 12px; background: #10b981; color: white; border-radius: 8px; font-size: 12px; font-weight: bold; text-transform: uppercase;">AUTO-EXECUTED</span>
852
  </div>
853
+ <div style="margin-top: 15px;">
854
+ <p style="margin: 8px 0; font-size: 14px; color: #475569;"><strong>Scenario:</strong> {scenario_name}</p>
855
+ <p style="margin: 8px 0; font-size: 14px; color: #475569;"><strong>Mode:</strong> Autonomous</p>
856
+ <p style="margin: 8px 0; font-size: 14px; color: #475569;"><strong>Action Executed:</strong> Scaled Redis cluster from 3 to 5 nodes</p>
857
+ <p style="margin: 8px 0; font-size: 14px; color: #475569;"><strong>Recovery Time:</strong> 12 minutes (vs 45 min manual)</p>
858
+ <p style="margin: 8px 0; font-size: 14px; color: #475569;"><strong>Cost Saved:</strong> <span style="color: #10b981; font-weight: 700;">${savings:,}</span></p>
859
+ <div style="display: flex; flex-direction: column; gap: 10px; margin-top: 20px;">
860
+ <div style="padding: 12px; background: #f8fafc; border-radius: 10px; border-left: 4px solid #10b981; font-size: 14px; color: #475569; font-weight: 500;">βœ… 1. ARF generated intent</div>
861
+ <div style="padding: 12px; background: #f8fafc; border-radius: 10px; border-left: 4px solid #10b981; font-size: 14px; color: #475569; font-weight: 500;">βœ… 2. Safety checks passed</div>
862
+ <div style="padding: 12px; background: #f8fafc; border-radius: 10px; border-left: 4px solid #10b981; font-size: 14px; color: #475569; font-weight: 500;">βœ… 3. Autonomous execution completed</div>
863
  </div>
864
  </div>
865
  </div>
 
891
  }
892
 
893
  # Update execution table
894
+ execution_table_data = get_audit_manager().get_execution_table()
895
 
896
  return approval_html, enterprise_results, execution_table_data
897
 
 
912
  oss_result = await run_oss_analysis(scenario_name)
913
 
914
  # Step 3: Execute Enterprise (simulated)
915
+ await asyncio.sleep(1)
916
 
917
+ scenario = get_components()["INCIDENT_SCENARIOS"].get(scenario_name, {})
918
  impact = scenario.get("business_impact", {})
919
  revenue_loss = impact.get("revenue_loss_per_hour", 5000)
920
  savings = int(revenue_loss * 0.85)
 
941
 
942
  # Create demo completion message
943
  demo_message = f"""
944
+ <div style="border: 1px solid #e2e8f0; border-radius: 14px; padding: 20px; background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%); margin-top: 20px;">
945
+ <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; padding-bottom: 12px; border-bottom: 2px solid rgba(0,0,0,0.1);">
946
+ <h3 style="margin: 0; font-size: 18px; color: #1e293b;">βœ… Demo Complete</h3>
947
+ <span style="padding: 4px 12px; background: #10b981; color: white; border-radius: 20px; font-size: 12px; font-weight: bold; text-transform: uppercase;">SUCCESS</span>
948
  </div>
949
+ <div style="margin-top: 15px;">
950
+ <p style="margin: 8px 0; font-size: 14px; color: #475569;"><strong>Scenario:</strong> {scenario_name}</p>
951
+ <p style="margin: 8px 0; font-size: 14px; color: #475569;"><strong>Workflow:</strong> OSS Analysis β†’ Enterprise Execution</p>
952
+ <p style="margin: 8px 0; font-size: 14px; color: #475569;"><strong>Time Saved:</strong> 33 minutes (73% faster)</p>
953
+ <p style="margin: 8px 0; font-size: 14px; color: #475569;"><strong>Cost Avoided:</strong> ${savings:,}</p>
954
+ <p style="margin: 8px 0; font-size: 14px; color: #64748b; font-style: italic;">This demonstrates the complete ARF value proposition from detection to autonomous healing.</p>
955
  </div>
956
  </div>
957
  """
 
989
  avg_impact = get_scenario_impact(scenario_name)
990
 
991
  # Calculate ROI
992
+ roi_calculator = get_components()["EnhancedROICalculator"]
993
  roi_result = roi_calculator.calculate_comprehensive_roi(
994
  monthly_incidents=monthly_incidents,
995
  avg_impact=float(avg_impact),
 
1000
  roi_multiplier = extract_roi_multiplier(roi_result)
1001
 
1002
  # Create visualization
1003
+ viz_engine = get_components()["EnhancedVisualizationEngine"]
1004
  chart = viz_engine.create_executive_dashboard({"roi_multiplier": roi_multiplier})
1005
 
1006
  return roi_result, chart
 
1022
  }
1023
 
1024
  # Always return a valid chart
1025
+ viz_engine = get_components()["EnhancedVisualizationEngine"]
1026
  fallback_chart = viz_engine.create_executive_dashboard({"roi_multiplier": 5.2})
1027
 
1028
  return fallback_result, fallback_chart
 
1095
  # ============ TAB 4 HANDLERS ============
1096
 
1097
  def refresh_audit_trail():
1098
+ return get_audit_manager().get_execution_table(), get_audit_manager().get_incident_table()
1099
 
1100
  def clear_audit_trail():
1101
+ get_audit_manager().clear()
1102
+ return get_audit_manager().get_execution_table(), get_audit_manager().get_incident_table()
1103
 
1104
  def export_audit_trail():
1105
  try:
1106
  # Calculate total savings
1107
  total_savings = 0
1108
+ audit_manager = get_audit_manager()
1109
  for e in audit_manager.executions:
1110
  if e['savings'] != '$0':
1111
  try:
 
1144
  # Initialize dashboard
1145
  def initialize_dashboard():
1146
  try:
1147
+ viz_engine = get_components()["EnhancedVisualizationEngine"]
1148
  chart = viz_engine.create_executive_dashboard()
1149
  return chart
1150
  except Exception as e:
 
1186
  demo.launch(
1187
  server_name="0.0.0.0",
1188
  server_port=7860,
1189
+ share=False,
1190
+ show_error=True # Show errors in UI
1191
  )
1192
 
1193