petter2025 commited on
Commit
445884d
·
verified ·
1 Parent(s): f627f89

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +459 -437
app.py CHANGED
@@ -1,37 +1,11 @@
1
  """
2
  🚀 ARF Ultimate Investor Demo v3.8.0 - ENTERPRISE EDITION
3
  MODULAR VERSION - Properly integrated with all components
4
- COMPLETE FIXED VERSION: All issues resolved including Tab 2 ROI Calculator
5
  """
6
 
7
- import logging
8
- import sys
9
- import traceback
10
- import json
11
- import datetime
12
- import asyncio
13
- import time
14
- import numpy as np
15
- from pathlib import Path
16
- from typing import Dict, List, Any, Optional, Tuple
17
 
18
- # Configure logging
19
- logging.basicConfig(
20
- level=logging.INFO,
21
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
22
- handlers=[
23
- logging.StreamHandler(sys.stdout),
24
- logging.FileHandler('arf_demo.log')
25
- ]
26
- )
27
- logger = logging.getLogger(__name__)
28
-
29
- # Add parent directory to path
30
- sys.path.insert(0, str(Path(__file__).parent))
31
-
32
- # ===========================================
33
- # IMPORT MODULAR COMPONENTS - FIXED IMPORTS
34
- # ===========================================
35
  try:
36
  # Import scenarios
37
  from demo.scenarios import INCIDENT_SCENARIOS
@@ -39,7 +13,7 @@ try:
39
  # Import orchestrator
40
  from demo.orchestrator import DemoOrchestrator
41
 
42
- # Import ROI calculator - FIXED: Use EnhancedROICalculator instead of ROI_Calculator
43
  from core.calculators import EnhancedROICalculator
44
 
45
  # Import visualizations
@@ -53,6 +27,9 @@ try:
53
  create_footer
54
  )
55
 
 
 
 
56
  logger.info("✅ Successfully imported all modular components")
57
 
58
  except ImportError as e:
@@ -60,167 +37,318 @@ except ImportError as e:
60
  logger.error(traceback.format_exc())
61
  raise
62
 
63
- # ===========================================
64
- # AUDIT TRAIL MANAGER
65
- # ===========================================
66
- class AuditTrailManager:
67
- """Simple audit trail manager"""
68
-
69
- def __init__(self):
70
- self.executions = []
71
- self.incidents = []
72
-
73
- def add_execution(self, scenario, mode, success=True, savings=0):
74
- entry = {
75
- "time": datetime.datetime.now().strftime("%H:%M"),
76
- "scenario": scenario,
77
- "mode": mode,
78
- "status": "✅ Success" if success else "❌ Failed",
79
- "savings": f"${savings:,}",
80
- "details": f"{mode} execution"
81
- }
82
- self.executions.insert(0, entry)
83
- return entry
84
-
85
- def add_incident(self, scenario, severity="HIGH"):
86
- entry = {
87
- "time": datetime.datetime.now().strftime("%H:%M"),
88
- "scenario": scenario,
89
- "severity": severity,
90
- "component": INCIDENT_SCENARIOS.get(scenario, {}).get("component", "unknown"),
91
- "status": "Analyzed"
92
- }
93
- self.incidents.insert(0, entry)
94
- return entry
95
-
96
- def get_execution_table(self):
97
- return [
98
- [e["time"], e["scenario"], e["mode"], e["status"], e["savings"], e["details"]]
99
- for e in self.executions[:10]
100
- ]
101
-
102
- def get_incident_table(self):
103
- return [
104
- [e["time"], e["component"], e["scenario"], e["severity"], e["status"]]
105
- for e in self.incidents[:15]
106
- ]
107
 
108
  # ===========================================
109
- # SCENARIO IMPACT MAPPING
110
  # ===========================================
111
- def get_scenario_impact(scenario_name: str) -> float:
112
- """Get average impact for a given scenario"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  impact_map = {
114
- "Cache Miss Storm": 8500,
115
- "Database Connection Pool Exhaustion": 4200,
116
- "Kubernetes Memory Leak": 5500,
117
- "API Rate Limit Storm": 3800,
118
- "Network Partition": 12000,
119
- "Storage I/O Saturation": 6800
120
  }
121
- return impact_map.get(scenario_name, 5000)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
  # ===========================================
124
- # ROI DATA ADAPTER - FIXED VERSION
125
  # ===========================================
126
- def extract_roi_multiplier(roi_result: Dict) -> float:
127
- """Extract ROI multiplier from EnhancedROICalculator result - FIXED VERSION"""
128
- try:
129
- # Try to get from summary
130
- if "summary" in roi_result and "roi_multiplier" in roi_result["summary"]:
131
- roi_str = roi_result["summary"]["roi_multiplier"]
132
- # Handle format like "5.2×"
133
- if "×" in roi_str:
134
- return float(roi_str.replace("×", ""))
135
- return float(roi_str)
136
-
137
- # Try to get from scenarios
138
- if "scenarios" in roi_result and "base_case" in roi_result["scenarios"]:
139
- roi_str = roi_result["scenarios"]["base_case"]["roi"]
140
- if "×" in roi_str:
141
- return float(roi_str.replace("×", ""))
142
- return float(roi_str)
143
-
144
- # Try direct access
145
- if "roi_multiplier" in roi_result:
146
- roi_val = roi_result["roi_multiplier"]
147
- if isinstance(roi_val, (int, float)):
148
- return float(roi_val)
149
-
150
- return 5.2 # Default fallback
151
- except Exception as e:
152
- logger.warning(f"Failed to extract ROI multiplier: {e}, using default 5.2")
153
- return 5.2 # Default fallback
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
 
155
  # ===========================================
156
- # CREATE DEMO INTERFACE - MODULAR VERSION
157
  # ===========================================
158
  def create_demo_interface():
159
  """Create demo interface using modular components"""
160
 
161
  import gradio as gr
162
 
163
- # Initialize components - FIXED: Use EnhancedROICalculator
164
  viz_engine = EnhancedVisualizationEngine()
165
  roi_calculator = EnhancedROICalculator()
166
  audit_manager = AuditTrailManager()
167
  orchestrator = DemoOrchestrator()
168
 
 
 
 
169
  with gr.Blocks(
170
  title="🚀 ARF Investor Demo v3.8.0",
171
- theme=gr.themes.Soft(primary_hue="blue")
 
172
  ) as demo:
173
 
174
- # Header - Now using gr.HTML instead of gr.Markdown
175
- header_html = create_header("3.3.6", False) # OSS version, Mock mode
176
 
177
  # Status bar
178
  status_html = create_status_bar()
179
 
180
  # ============ 5 TABS ============
181
- with gr.Tabs():
182
 
183
- # TAB 1: Live Incident Demo
184
  with gr.TabItem("🔥 Live Incident Demo", id="tab1"):
185
  # Get components from UI module
186
- (scenario_dropdown, scenario_description, metrics_display, impact_display,
187
- timeline_output, oss_btn, enterprise_btn, approval_toggle, demo_btn,
188
- approval_display, oss_results_display, enterprise_results_display) = create_tab1_incident_demo(
189
- INCIDENT_SCENARIOS, "Cache Miss Storm"
190
- )
 
191
 
192
- # TAB 2: Business Impact & ROI - FIXED: Pass scenarios parameter
193
  with gr.TabItem("💰 Business Impact & ROI", id="tab2"):
194
  (dashboard_output, roi_scenario_dropdown, monthly_slider, team_slider,
195
  calculate_btn, roi_output, roi_chart) = create_tab2_business_roi(INCIDENT_SCENARIOS)
196
 
197
- # TAB 3: Enterprise Features
198
  with gr.TabItem("🏢 Enterprise Features", id="tab3"):
199
  (license_display, validate_btn, trial_btn, upgrade_btn,
200
- mcp_mode, mcp_mode_info, features_table, integrations_table) = create_tab3_enterprise_features()
201
 
202
- # TAB 4: Audit Trail & History
203
  with gr.TabItem("📜 Audit Trail & History", id="tab4"):
204
  (refresh_btn, clear_btn, export_btn, execution_table,
205
  incident_table, export_text) = create_tab4_audit_trail()
206
 
207
- # TAB 5: Learning Engine
208
  with gr.TabItem("🧠 Learning Engine", id="tab5"):
209
  (learning_graph, graph_type, show_labels, search_query, search_btn,
210
  clear_btn_search, search_results, stats_display, patterns_display,
211
  performance_display) = create_tab5_learning_engine()
212
 
213
- # Footer - Now using gr.HTML instead of gr.Markdown
214
  footer_html = create_footer()
215
 
216
- # ============ EVENT HANDLERS ============
217
 
218
- # Update scenario dropdown in ROI tab
219
- def update_roi_scenario_dropdown():
220
- return gr.Dropdown.update(
221
- choices=list(INCIDENT_SCENARIOS.keys()),
222
- value="Cache Miss Storm"
223
- )
 
 
 
 
 
224
 
225
  # Run OSS Analysis
226
  async def run_oss_analysis(scenario_name):
@@ -235,38 +363,101 @@ def create_demo_interface():
235
  # Update incident table
236
  incident_table_data = audit_manager.get_incident_table()
237
 
238
- # Format OSS results
239
  oss_results = {
240
  "status": "✅ OSS Analysis Complete",
241
  "scenario": scenario_name,
242
  "confidence": 0.85,
 
 
 
 
 
 
243
  "recommendations": [
244
  "Scale resources based on historical patterns",
245
- "Implement circuit breaker",
246
- "Add monitoring for key metrics"
247
  ],
248
  "healing_intent": {
249
  "action": "scale_out",
250
  "component": scenario.get("component", "unknown"),
 
 
251
  "requires_enterprise": True,
252
- "advisory_only": True
 
253
  }
254
  }
255
 
256
- return oss_results, incident_table_data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257
 
258
  oss_btn.click(
259
  fn=run_oss_analysis,
260
  inputs=[scenario_dropdown],
261
- outputs=[oss_results_display, incident_table]
 
 
 
262
  )
263
 
264
  # Execute Enterprise Healing
265
- def execute_enterprise_healing(scenario_name, approval_required):
266
  scenario = INCIDENT_SCENARIOS.get(scenario_name, {})
267
 
268
  # Determine mode
269
  mode = "Approval" if approval_required else "Autonomous"
 
 
270
 
271
  # Calculate savings
272
  impact = scenario.get("business_impact", {})
@@ -279,28 +470,42 @@ def create_demo_interface():
279
  # Create approval display
280
  if approval_required:
281
  approval_html = f"""
282
- <div style='padding: 20px; background: #e8f5e8; border-radius: 10px; border-left: 4px solid #28a745;'>
283
- <h4 style='margin: 0 0 10px 0; color: #1a365d;'>✅ Approved & Executed</h4>
284
- <p style='margin: 0; color: #2d3748;'>
285
- Action for <strong>{scenario_name}</strong> was approved and executed successfully.
286
- </p>
287
- <p style='margin: 10px 0 0 0; color: #2d3748;'>
288
- <strong>Mode:</strong> {mode}<br>
289
- <strong>Cost Saved:</strong> ${savings:,}
290
- </p>
 
 
 
 
 
 
291
  </div>
292
  """
293
  else:
294
  approval_html = f"""
295
- <div style='padding: 20px; background: #e3f2fd; border-radius: 10px; border-left: 4px solid #2196f3;'>
296
- <h4 style='margin: 0 0 10px 0; color: #1a365d;'>⚡ Auto-Executed</h4>
297
- <p style='margin: 0; color: #2d3748;'>
298
- Action for <strong>{scenario_name}</strong> was executed autonomously.
299
- </p>
300
- <p style='margin: 10px 0 0 0; color: #2d3748;'>
301
- <strong>Mode:</strong> {mode}<br>
302
- <strong>Cost Saved:</strong> ${savings:,}
303
- </p>
 
 
 
 
 
 
 
 
304
  </div>
305
  """
306
 
@@ -308,15 +513,24 @@ def create_demo_interface():
308
  enterprise_results = {
309
  "execution_mode": mode,
310
  "scenario": scenario_name,
 
311
  "actions_executed": [
312
  "✅ Scaled resources based on ML recommendations",
313
  "✅ Implemented circuit breaker pattern",
314
- "✅ Deployed enhanced monitoring"
 
315
  ],
316
  "business_impact": {
317
  "recovery_time": "60 min → 12 min",
318
  "cost_saved": f"${savings:,}",
319
- "users_impacted": "45,000 → 0"
 
 
 
 
 
 
 
320
  }
321
  }
322
 
@@ -327,271 +541,105 @@ def create_demo_interface():
327
 
328
  enterprise_btn.click(
329
  fn=execute_enterprise_healing,
330
- inputs=[scenario_dropdown, approval_toggle],
331
  outputs=[approval_display, enterprise_results_display, execution_table]
332
  )
333
 
334
- # Calculate ROI - FIXED: COMPLETE ROBUST VERSION
335
- def calculate_roi(scenario_name, monthly_incidents, team_size):
336
- """Calculate ROI - ROBUST VERSION with full error handling"""
337
- try:
338
- logger.info(f"Calculating ROI for scenario={scenario_name}, incidents={monthly_incidents}, team={team_size}")
339
-
340
- # Validate inputs
341
- if not scenario_name:
342
- scenario_name = "Cache Miss Storm"
343
- logger.warning("No scenario selected, using default: Cache Miss Storm")
344
-
345
- try:
346
- monthly_incidents = int(monthly_incidents) if monthly_incidents else 15
347
- team_size = int(team_size) if team_size else 5
348
- except ValueError:
349
- logger.warning(f"Invalid input values, using defaults: incidents=15, team=5")
350
- monthly_incidents = 15
351
- team_size = 5
352
-
353
- # Get scenario-specific impact
354
- avg_impact = get_scenario_impact(scenario_name)
355
- logger.info(f"Using avg_impact for {scenario_name}: ${avg_impact}")
356
-
357
- # Calculate ROI using EnhancedROICalculator
358
- roi_result = roi_calculator.calculate_comprehensive_roi(
359
- monthly_incidents=monthly_incidents,
360
- avg_impact=float(avg_impact),
361
- team_size=team_size
362
- )
363
-
364
- logger.info(f"ROI calculation successful, result keys: {list(roi_result.keys())}")
365
-
366
- # Extract ROI multiplier for visualization
367
- roi_multiplier = extract_roi_multiplier(roi_result)
368
- logger.info(f"Extracted ROI multiplier: {roi_multiplier}")
369
-
370
- # Create visualization
371
- try:
372
- chart = viz_engine.create_executive_dashboard({"roi_multiplier": roi_multiplier})
373
- logger.info("Dashboard chart created successfully")
374
- except Exception as chart_error:
375
- logger.error(f"Chart creation failed: {chart_error}")
376
- # Create fallback chart
377
- chart = viz_engine.create_executive_dashboard()
378
-
379
- return roi_result, chart
380
-
381
- except Exception as e:
382
- logger.error(f"ROI calculation error: {e}")
383
- logger.error(traceback.format_exc())
384
-
385
- # Provide fallback results that will always work
386
- fallback_result = {
387
- "status": "✅ Calculated Successfully",
388
- "summary": {
389
- "your_annual_impact": "$1,530,000",
390
- "potential_savings": "$1,254,600",
391
- "enterprise_cost": "$625,000",
392
- "roi_multiplier": "5.2×",
393
- "payback_months": "6.0",
394
- "annual_roi_percentage": "420%"
395
- },
396
- "scenarios": {
397
- "base_case": {"roi": "5.2×", "payback": "6.0 months", "confidence": "High"},
398
- "best_case": {"roi": "6.5×", "payback": "4.8 months", "confidence": "Medium"},
399
- "worst_case": {"roi": "4.0×", "payback": "7.5 months", "confidence": "Medium"}
400
- },
401
- "comparison": {
402
- "industry_average": "5.2× ROI",
403
- "top_performers": "8.7× ROI",
404
- "your_position": "Top 25%"
405
- },
406
- "recommendation": {
407
- "action": "🚀 Deploy ARF Enterprise",
408
- "reason": "Exceptional ROI (>5×) with quick payback",
409
- "timeline": "30-day implementation",
410
- "expected_value": ">$1M annual savings",
411
- "priority": "High"
412
- }
413
- }
414
-
415
- # Always return a valid chart
416
- try:
417
- fallback_chart = viz_engine.create_executive_dashboard({"roi_multiplier": 5.2})
418
- except:
419
- # Ultimate fallback - create a simple chart
420
- import plotly.graph_objects as go
421
- fig = go.Figure(go.Indicator(
422
- mode="number+gauge",
423
- value=5.2,
424
- title={"text": "ROI Multiplier"},
425
- domain={'x': [0, 1], 'y': [0, 1]},
426
- gauge={'axis': {'range': [0, 10]}}
427
- ))
428
- fig.update_layout(height=400)
429
- fallback_chart = fig
430
-
431
- return fallback_result, fallback_chart
432
-
433
- calculate_btn.click(
434
- fn=calculate_roi,
435
- inputs=[roi_scenario_dropdown, monthly_slider, team_slider],
436
- outputs=[roi_output, roi_chart]
437
- )
438
-
439
- # Audit Trail Refresh
440
- def refresh_audit_trail():
441
- return audit_manager.get_execution_table(), audit_manager.get_incident_table()
442
-
443
- refresh_btn.click(
444
- fn=refresh_audit_trail,
445
- outputs=[execution_table, incident_table]
446
- )
447
-
448
- # Clear History
449
- def clear_audit_trail():
450
- audit_manager.executions = []
451
- audit_manager.incidents = []
452
- return audit_manager.get_execution_table(), audit_manager.get_incident_table()
453
-
454
- clear_btn.click(
455
- fn=clear_audit_trail,
456
- outputs=[execution_table, incident_table]
457
- )
458
-
459
- # Tab 3 Button Handlers
460
- def validate_license():
461
- logger.info("Validating license...")
462
- return {
463
- "status": "✅ Valid",
464
- "tier": "Enterprise",
465
- "expires": "2026-12-31",
466
- "message": "License validated successfully",
467
- "next_renewal": "2026-06-30",
468
- "features": ["autonomous_healing", "compliance", "audit_trail",
469
- "predictive_analytics", "multi_cloud", "role_based_access"]
470
- }
471
-
472
- def start_trial():
473
- logger.info("Starting trial...")
474
- return {
475
- "status": "🆓 Trial Activated",
476
- "tier": "Enterprise Trial",
477
- "expires": "2026-01-30",
478
- "features": ["autonomous_healing", "compliance", "audit_trail",
479
- "predictive_analytics", "multi_cloud"],
480
- "message": "30-day trial started. Full features enabled."
481
- }
482
-
483
- def upgrade_license():
484
- logger.info("Checking upgrade options...")
485
- return {
486
- "status": "🚀 Upgrade Available",
487
- "current_tier": "Enterprise",
488
- "next_tier": "Enterprise Plus",
489
- "features_added": ["predictive_scaling", "custom_workflows", "advanced_analytics"],
490
- "cost": "$25,000/year",
491
- "message": "Contact sales@arf.dev for upgrade"
492
- }
493
-
494
- # Connect Tab 3 buttons
495
- validate_btn.click(
496
- fn=validate_license,
497
- outputs=[license_display]
498
- )
499
-
500
- trial_btn.click(
501
- fn=start_trial,
502
- outputs=[license_display]
503
- )
504
-
505
- upgrade_btn.click(
506
- fn=upgrade_license,
507
- outputs=[license_display]
508
- )
509
-
510
- # MCP Mode change handler
511
- def update_mcp_mode(mode):
512
- logger.info(f"Updating MCP mode to: {mode}")
513
- mode_info = {
514
- "advisory": {
515
- "current_mode": "advisory",
516
- "description": "OSS Edition - Analysis only, no execution",
517
- "features": ["Incident analysis", "RAG similarity", "HealingIntent creation"]
518
- },
519
- "approval": {
520
- "current_mode": "approval",
521
- "description": "Enterprise Edition - Human approval required",
522
- "features": ["All OSS features", "Approval workflows", "Audit trail", "Compliance"]
523
- },
524
- "autonomous": {
525
- "current_mode": "autonomous",
526
- "description": "Enterprise Plus - Fully autonomous healing",
527
- "features": ["All approval features", "Auto-execution", "Predictive healing", "ML optimization"]
528
  }
529
  }
530
- return mode_info.get(mode, mode_info["advisory"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
531
 
532
- mcp_mode.change(
533
- fn=update_mcp_mode,
534
- inputs=[mcp_mode],
535
- outputs=[mcp_mode_info]
 
 
 
 
536
  )
537
 
538
- # Export Audit Trail
539
- def export_audit_trail():
540
- logger.info("Exporting audit trail...")
541
- try:
542
- # Calculate total savings
543
- total_savings = 0
544
- for e in audit_manager.executions:
545
- if e['savings'] != '$0':
546
- try:
547
- # Remove $ and commas, convert to int
548
- savings_str = e['savings'].replace('$', '').replace(',', '')
549
- total_savings += int(float(savings_str))
550
- except:
551
- pass
552
-
553
- # Calculate success rate
554
- successful = len([e for e in audit_manager.executions if '✅' in e['status']])
555
- total = len(audit_manager.executions)
556
- success_rate = (successful / total * 100) if total > 0 else 0
557
-
558
- audit_data = {
559
- "exported_at": datetime.datetime.now().isoformat(),
560
- "executions": audit_manager.executions[:10],
561
- "incidents": audit_manager.incidents[:15],
562
- "summary": {
563
- "total_executions": total,
564
- "total_incidents": len(audit_manager.incidents),
565
- "total_savings": f"${total_savings:,}",
566
- "success_rate": f"{success_rate:.1f}%"
567
- }
568
- }
569
- return json.dumps(audit_data, indent=2)
570
- except Exception as e:
571
- logger.error(f"Export failed: {e}")
572
- return json.dumps({"error": f"Export failed: {str(e)}"}, indent=2)
573
-
574
- export_btn.click(
575
- fn=export_audit_trail,
576
- outputs=[export_text]
577
- )
578
 
579
- # Initialize ROI scenario dropdown
580
  demo.load(
581
- fn=update_roi_scenario_dropdown,
582
- outputs=[roi_scenario_dropdown]
583
  )
584
 
585
- # Initialize dashboard - FIXED VERSION
586
  def initialize_dashboard():
587
  try:
588
- logger.info("Initializing executive dashboard...")
589
  chart = viz_engine.create_executive_dashboard()
590
- logger.info("Dashboard initialized successfully")
591
  return chart
592
  except Exception as e:
593
  logger.error(f"Dashboard initialization failed: {e}")
594
- # Create a simple fallback chart
595
  import plotly.graph_objects as go
596
  fig = go.Figure(go.Indicator(
597
  mode="number+gauge",
@@ -618,29 +666,3 @@ def create_demo_interface():
618
  )
619
 
620
  return demo
621
-
622
- # ===========================================
623
- # MAIN EXECUTION
624
- # ===========================================
625
- def main():
626
- """Main entry point"""
627
- print("🚀 Starting ARF Ultimate Investor Demo v3.8.0...")
628
- print("=" * 70)
629
- print("📊 Features:")
630
- print(" • 6 Incident Scenarios")
631
- print(" • Modular Architecture")
632
- print(" • Working Button Handlers")
633
- print(" • 5 Functional Tabs")
634
- print(" • Full Demo Data")
635
- print(" • Fixed ROI Calculator (Tab 2)")
636
- print("=" * 70)
637
-
638
- demo = create_demo_interface()
639
- demo.launch(
640
- server_name="0.0.0.0",
641
- server_port=7860,
642
- share=False
643
- )
644
-
645
- if __name__ == "__main__":
646
- main()
 
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 Tab 1
5
  """
6
 
7
+ # ... [Previous imports remain the same] ...
 
 
 
 
 
 
 
 
 
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  try:
10
  # Import scenarios
11
  from demo.scenarios import INCIDENT_SCENARIOS
 
13
  # Import orchestrator
14
  from demo.orchestrator import DemoOrchestrator
15
 
16
+ # Import ROI calculator
17
  from core.calculators import EnhancedROICalculator
18
 
19
  # Import visualizations
 
27
  create_footer
28
  )
29
 
30
+ # Import styles
31
+ from ui.styles import get_styles
32
+
33
  logger.info("✅ Successfully imported all modular components")
34
 
35
  except ImportError as e:
 
37
  logger.error(traceback.format_exc())
38
  raise
39
 
40
+ # ... [AuditTrailManager, scenario_impact_mapping, roi_data_adapter remain the same] ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
  # ===========================================
43
+ # VISUALIZATION HELPERS FOR TAB 1
44
  # ===========================================
45
+ def create_telemetry_plot(scenario_name: str):
46
+ """Create a telemetry visualization for the selected scenario"""
47
+ import plotly.graph_objects as go
48
+ import numpy as np
49
+
50
+ # Generate some sample data
51
+ time_points = np.arange(0, 100, 1)
52
+
53
+ # Different patterns for different scenarios
54
+ if "Cache" in scenario_name:
55
+ data = 100 + 50 * np.sin(time_points * 0.2) + np.random.normal(0, 10, 100)
56
+ threshold = 180
57
+ metric_name = "Cache Hit Rate (%)"
58
+ elif "Database" in scenario_name:
59
+ data = 70 + 30 * np.sin(time_points * 0.15) + np.random.normal(0, 8, 100)
60
+ threshold = 120
61
+ metric_name = "Connection Pool Usage"
62
+ elif "Memory" in scenario_name:
63
+ data = 50 + 40 * np.sin(time_points * 0.1) + np.random.normal(0, 12, 100)
64
+ threshold = 95
65
+ metric_name = "Memory Usage (%)"
66
+ else:
67
+ data = 80 + 20 * np.sin(time_points * 0.25) + np.random.normal(0, 5, 100)
68
+ threshold = 110
69
+ metric_name = "System Load"
70
+
71
+ # Create the plot
72
+ fig = go.Figure()
73
+
74
+ # Add normal data
75
+ fig.add_trace(go.Scatter(
76
+ x=time_points[:70],
77
+ y=data[:70],
78
+ mode='lines',
79
+ name='Normal',
80
+ line=dict(color='#3b82f6', width=3),
81
+ fill='tozeroy',
82
+ fillcolor='rgba(59, 130, 246, 0.1)'
83
+ ))
84
+
85
+ # Add anomaly data
86
+ fig.add_trace(go.Scatter(
87
+ x=time_points[70:],
88
+ y=data[70:],
89
+ mode='lines',
90
+ name='Anomaly Detected',
91
+ line=dict(color='#ef4444', width=3, dash='dash'),
92
+ fill='tozeroy',
93
+ fillcolor='rgba(239, 68, 68, 0.1)'
94
+ ))
95
+
96
+ # Add threshold line
97
+ fig.add_hline(
98
+ y=threshold,
99
+ line_dash="dot",
100
+ line_color="#f59e0b",
101
+ annotation_text="Threshold",
102
+ annotation_position="bottom right"
103
+ )
104
+
105
+ # Add detection point
106
+ fig.add_vline(
107
+ x=70,
108
+ line_dash="dash",
109
+ line_color="#10b981",
110
+ annotation_text="ARF Detection",
111
+ annotation_position="top"
112
+ )
113
+
114
+ # Update layout
115
+ fig.update_layout(
116
+ title=f"📈 {metric_name} - Live Telemetry",
117
+ xaxis_title="Time (minutes)",
118
+ yaxis_title=metric_name,
119
+ height=300,
120
+ margin=dict(l=20, r=20, t=50, b=20),
121
+ plot_bgcolor='rgba(0,0,0,0)',
122
+ paper_bgcolor='rgba(0,0,0,0)',
123
+ legend=dict(
124
+ orientation="h",
125
+ yanchor="bottom",
126
+ y=1.02,
127
+ xanchor="right",
128
+ x=1
129
+ )
130
+ )
131
+
132
+ return fig
133
+
134
+ def create_impact_plot(scenario_name: str):
135
+ """Create a business impact visualization"""
136
+ import plotly.graph_objects as go
137
+
138
+ # Get impact data based on scenario
139
  impact_map = {
140
+ "Cache Miss Storm": {"revenue": 8500, "users": 45000, "services": 12},
141
+ "Database Connection Pool Exhaustion": {"revenue": 4200, "users": 22000, "services": 8},
142
+ "Kubernetes Memory Leak": {"revenue": 5500, "users": 28000, "services": 15},
143
+ "API Rate Limit Storm": {"revenue": 3800, "users": 19000, "services": 6},
144
+ "Network Partition": {"revenue": 12000, "users": 65000, "services": 25},
145
+ "Storage I/O Saturation": {"revenue": 6800, "users": 32000, "services": 10}
146
  }
147
+
148
+ impact = impact_map.get(scenario_name, {"revenue": 5000, "users": 25000, "services": 10})
149
+
150
+ # Create gauge for revenue impact
151
+ fig = go.Figure(go.Indicator(
152
+ mode="gauge+number",
153
+ value=impact["revenue"],
154
+ title={'text': "💰 Hourly Revenue Risk", 'font': {'size': 16}},
155
+ number={'prefix': "$", 'font': {'size': 28}},
156
+ gauge={
157
+ 'axis': {'range': [0, 15000], 'tickwidth': 1},
158
+ 'bar': {'color': "#ef4444"},
159
+ 'steps': [
160
+ {'range': [0, 3000], 'color': '#10b981'},
161
+ {'range': [3000, 7000], 'color': '#f59e0b'},
162
+ {'range': [7000, 15000], 'color': '#ef4444'}
163
+ ],
164
+ 'threshold': {
165
+ 'line': {'color': "black", 'width': 4},
166
+ 'thickness': 0.75,
167
+ 'value': impact["revenue"]
168
+ }
169
+ }
170
+ ))
171
+
172
+ fig.update_layout(
173
+ height=300,
174
+ margin=dict(l=20, r=20, t=50, b=20),
175
+ paper_bgcolor='rgba(0,0,0,0)'
176
+ )
177
+
178
+ return fig
179
+
180
+ def create_timeline_plot(scenario_name: str):
181
+ """Create an incident timeline visualization"""
182
+ import plotly.graph_objects as go
183
+
184
+ # Timeline data
185
+ events = [
186
+ {"time": 0, "event": "Incident Starts", "duration": 45},
187
+ {"time": 45, "event": "ARF Detection", "duration": 30},
188
+ {"time": 75, "event": "OSS Analysis Complete", "duration": 60},
189
+ {"time": 135, "event": "Enterprise Execution", "duration": 720},
190
+ {"time": 2700, "event": "Manual Resolution", "duration": 0}
191
+ ]
192
+
193
+ # Create timeline
194
+ fig = go.Figure()
195
+
196
+ # Add event bars
197
+ for i, event in enumerate(events):
198
+ if event["duration"] > 0:
199
+ fig.add_trace(go.Bar(
200
+ x=[event["duration"]],
201
+ y=[event["event"]],
202
+ orientation='h',
203
+ name=event["event"],
204
+ marker_color=['#3b82f6', '#10b981', '#8b5cf6', '#f59e0b', '#ef4444'][i],
205
+ text=[f"{event['duration']}s"],
206
+ textposition='auto',
207
+ hoverinfo='text',
208
+ hovertemplate=f"{event['event']}: {event['duration']} seconds<extra></extra>"
209
+ ))
210
+
211
+ fig.update_layout(
212
+ title="⏰ Incident Timeline Comparison",
213
+ xaxis_title="Time (seconds)",
214
+ yaxis_title="",
215
+ barmode='stack',
216
+ height=300,
217
+ margin=dict(l=20, r=20, t=50, b=20),
218
+ plot_bgcolor='rgba(0,0,0,0)',
219
+ paper_bgcolor='rgba(0,0,0,0)',
220
+ showlegend=False
221
+ )
222
+
223
+ return fig
224
 
225
  # ===========================================
226
+ # SCENARIO UPDATE HANDLER
227
  # ===========================================
228
+ def update_scenario_display(scenario_name: str) -> dict:
229
+ """Update all scenario-related displays"""
230
+ scenario = INCIDENT_SCENARIOS.get(scenario_name, {})
231
+ impact = scenario.get("business_impact", {})
232
+
233
+ # Create scenario card HTML
234
+ scenario_html = f"""
235
+ <div class="scenario-card">
236
+ <div class="scenario-header">
237
+ <h3>🚨 {scenario_name}</h3>
238
+ <span class="severity-badge {scenario.get('severity', 'HIGH').lower()}">{scenario.get('severity', 'HIGH')}</span>
239
+ </div>
240
+ <div class="scenario-details">
241
+ <div class="scenario-detail-row">
242
+ <span class="detail-label">Component:</span>
243
+ <span class="detail-value">{scenario.get('component', 'Unknown')}</span>
244
+ </div>
245
+ <div class="scenario-detail-row">
246
+ <span class="detail-label">Impact Radius:</span>
247
+ <span class="detail-value">{scenario.get('impact_radius', 'Unknown')}</span>
248
+ </div>
249
+ <div class="scenario-detail-row">
250
+ <span class="detail-label">Revenue Risk:</span>
251
+ <span class="detail-value revenue-risk">${impact.get('revenue_loss_per_hour', 0):,}/hour</span>
252
+ </div>
253
+ <div class="scenario-detail-row">
254
+ <span class="detail-label">Detection Time:</span>
255
+ <span class="detail-value">{scenario.get('detection_time', 'Unknown')}</span>
256
+ </div>
257
+ <div class="scenario-tags">
258
+ {''.join([f'<span class="scenario-tag">{tag}</span>' for tag in scenario.get('tags', ['incident', 'demo'])])}
259
+ </div>
260
+ </div>
261
+ </div>
262
+ """
263
+
264
+ # Create visualizations
265
+ telemetry_plot = create_telemetry_plot(scenario_name)
266
+ impact_plot = create_impact_plot(scenario_name)
267
+ timeline_plot = create_timeline_plot(scenario_name)
268
+
269
+ return {
270
+ "scenario_html": scenario_html,
271
+ "telemetry_plot": telemetry_plot,
272
+ "impact_plot": impact_plot,
273
+ "timeline_plot": timeline_plot
274
+ }
275
 
276
  # ===========================================
277
+ # CREATE DEMO INTERFACE - UPDATED FOR ENHANCED TAB 1
278
  # ===========================================
279
  def create_demo_interface():
280
  """Create demo interface using modular components"""
281
 
282
  import gradio as gr
283
 
284
+ # Initialize components
285
  viz_engine = EnhancedVisualizationEngine()
286
  roi_calculator = EnhancedROICalculator()
287
  audit_manager = AuditTrailManager()
288
  orchestrator = DemoOrchestrator()
289
 
290
+ # Get CSS styles
291
+ css_styles = get_styles()
292
+
293
  with gr.Blocks(
294
  title="🚀 ARF Investor Demo v3.8.0",
295
+ theme=gr.themes.Soft(primary_hue="blue"),
296
+ css=css_styles
297
  ) as demo:
298
 
299
+ # Header
300
+ header_html = create_header("3.3.6", False)
301
 
302
  # Status bar
303
  status_html = create_status_bar()
304
 
305
  # ============ 5 TABS ============
306
+ with gr.Tabs(elem_classes="tab-nav"):
307
 
308
+ # TAB 1: Live Incident Demo - ENHANCED
309
  with gr.TabItem("🔥 Live Incident Demo", id="tab1"):
310
  # Get components from UI module
311
+ (scenario_dropdown, scenario_card, telemetry_viz, impact_viz,
312
+ workflow_header, detection_agent, recall_agent, decision_agent,
313
+ oss_section, enterprise_section, oss_btn, enterprise_btn,
314
+ approval_toggle, mcp_mode, timeline_viz,
315
+ detection_time, mttr, auto_heal, savings,
316
+ oss_results_display, enterprise_results_display, approval_display, demo_btn) = create_tab1_incident_demo()
317
 
318
+ # ... [Tabs 2-5 remain the same as before] ...
319
  with gr.TabItem("💰 Business Impact & ROI", id="tab2"):
320
  (dashboard_output, roi_scenario_dropdown, monthly_slider, team_slider,
321
  calculate_btn, roi_output, roi_chart) = create_tab2_business_roi(INCIDENT_SCENARIOS)
322
 
 
323
  with gr.TabItem("🏢 Enterprise Features", id="tab3"):
324
  (license_display, validate_btn, trial_btn, upgrade_btn,
325
+ mcp_mode_tab3, mcp_mode_info, features_table, integrations_table) = create_tab3_enterprise_features()
326
 
 
327
  with gr.TabItem("📜 Audit Trail & History", id="tab4"):
328
  (refresh_btn, clear_btn, export_btn, execution_table,
329
  incident_table, export_text) = create_tab4_audit_trail()
330
 
 
331
  with gr.TabItem("🧠 Learning Engine", id="tab5"):
332
  (learning_graph, graph_type, show_labels, search_query, search_btn,
333
  clear_btn_search, search_results, stats_display, patterns_display,
334
  performance_display) = create_tab5_learning_engine()
335
 
336
+ # Footer
337
  footer_html = create_footer()
338
 
339
+ # ============ EVENT HANDLERS FOR ENHANCED TAB 1 ============
340
 
341
+ # Update scenario display when dropdown changes
342
+ scenario_dropdown.change(
343
+ fn=update_scenario_display,
344
+ inputs=[scenario_dropdown],
345
+ outputs={
346
+ scenario_card: gr.HTML(),
347
+ telemetry_viz: gr.Plot(),
348
+ impact_viz: gr.Plot(),
349
+ timeline_viz: gr.Plot()
350
+ }
351
+ )
352
 
353
  # Run OSS Analysis
354
  async def run_oss_analysis(scenario_name):
 
363
  # Update incident table
364
  incident_table_data = audit_manager.get_incident_table()
365
 
366
+ # Enhanced OSS results
367
  oss_results = {
368
  "status": "✅ OSS Analysis Complete",
369
  "scenario": scenario_name,
370
  "confidence": 0.85,
371
+ "agents_executed": ["Detection", "Recall", "Decision"],
372
+ "findings": [
373
+ "Anomaly detected with 99.8% confidence",
374
+ "3 similar incidents found in RAG memory",
375
+ "Historical success rate for similar actions: 87%"
376
+ ],
377
  "recommendations": [
378
  "Scale resources based on historical patterns",
379
+ "Implement circuit breaker pattern",
380
+ "Add enhanced monitoring for key metrics"
381
  ],
382
  "healing_intent": {
383
  "action": "scale_out",
384
  "component": scenario.get("component", "unknown"),
385
+ "parameters": {"nodes": "3→5", "region": "auto-select"},
386
+ "confidence": 0.94,
387
  "requires_enterprise": True,
388
+ "advisory_only": True,
389
+ "safety_check": "✅ Passed (blast radius: 2 services)"
390
  }
391
  }
392
 
393
+ # Update agent status
394
+ detection_html = """
395
+ <div class="agent-card detection">
396
+ <div class="agent-icon">🕵️‍♂️</div>
397
+ <div class="agent-content">
398
+ <h4>Detection Agent</h4>
399
+ <p class="agent-status-text">Analysis complete: <strong>99.8% confidence</strong></p>
400
+ <div class="agent-metrics">
401
+ <span class="agent-metric">Time: 45s</span>
402
+ <span class="agent-metric">Accuracy: 98.7%</span>
403
+ </div>
404
+ <div class="agent-status completed">COMPLETE</div>
405
+ </div>
406
+ </div>
407
+ """
408
+
409
+ recall_html = """
410
+ <div class="agent-card recall">
411
+ <div class="agent-icon">🧠</div>
412
+ <div class="agent-content">
413
+ <h4>Recall Agent</h4>
414
+ <p class="agent-status-text"><strong>3 similar incidents</strong> retrieved from memory</p>
415
+ <div class="agent-metrics">
416
+ <span class="agent-metric">Recall: 92%</span>
417
+ <span class="agent-metric">Patterns: 5</span>
418
+ </div>
419
+ <div class="agent-status completed">COMPLETE</div>
420
+ </div>
421
+ </div>
422
+ """
423
+
424
+ decision_html = """
425
+ <div class="agent-card decision">
426
+ <div class="agent-icon">🎯</div>
427
+ <div class="agent-content">
428
+ <h4>Decision Agent</h4>
429
+ <p class="agent-status-text">HealingIntent created with <strong>94% confidence</strong></p>
430
+ <div class="agent-metrics">
431
+ <span class="agent-metric">Success Rate: 87%</span>
432
+ <span class="agent-metric">Safety: 100%</span>
433
+ </div>
434
+ <div class="agent-status completed">COMPLETE</div>
435
+ </div>
436
+ </div>
437
+ """
438
+
439
+ return (
440
+ detection_html, recall_html, decision_html,
441
+ oss_results, incident_table_data
442
+ )
443
 
444
  oss_btn.click(
445
  fn=run_oss_analysis,
446
  inputs=[scenario_dropdown],
447
+ outputs=[
448
+ detection_agent, recall_agent, decision_agent,
449
+ oss_results_display, incident_table
450
+ ]
451
  )
452
 
453
  # Execute Enterprise Healing
454
+ def execute_enterprise_healing(scenario_name, approval_required, mcp_mode_value):
455
  scenario = INCIDENT_SCENARIOS.get(scenario_name, {})
456
 
457
  # Determine mode
458
  mode = "Approval" if approval_required else "Autonomous"
459
+ if "Advisory" in mcp_mode_value:
460
+ return gr.HTML.update(value="<div class='approval-status'><p>❌ Cannot execute in Advisory mode. Switch to Approval or Autonomous mode.</p></div>"), {}, []
461
 
462
  # Calculate savings
463
  impact = scenario.get("business_impact", {})
 
470
  # Create approval display
471
  if approval_required:
472
  approval_html = f"""
473
+ <div class="approval-status">
474
+ <div class="approval-header">
475
+ <h4>👤 Human Approval Required</h4>
476
+ <span class="approval-badge pending">PENDING</span>
477
+ </div>
478
+ <div class="approval-content">
479
+ <p><strong>Scenario:</strong> {scenario_name}</p>
480
+ <p><strong>Action:</strong> Scale Redis cluster from 3 to 5 nodes</p>
481
+ <p><strong>Estimated Savings:</strong> <span class='savings-highlight'>${savings:,}</span></p>
482
+ <div class="approval-workflow">
483
+ <div class="workflow-step">✅ 1. ARF generated intent (94% confidence)</div>
484
+ <div class="workflow-step">⏳ 2. Awaiting human review...</div>
485
+ <div class="workflow-step">3. ARF will execute upon approval</div>
486
+ </div>
487
+ </div>
488
  </div>
489
  """
490
  else:
491
  approval_html = f"""
492
+ <div class="approval-status">
493
+ <div class="approval-header">
494
+ <h4>⚡ Autonomous Execution Complete</h4>
495
+ <span class="approval-badge not-required">AUTO-EXECUTED</span>
496
+ </div>
497
+ <div class="approval-content">
498
+ <p><strong>Scenario:</strong> {scenario_name}</p>
499
+ <p><strong>Mode:</strong> Autonomous</p>
500
+ <p><strong>Action Executed:</strong> Scaled Redis cluster from 3 to 5 nodes</p>
501
+ <p><strong>Recovery Time:</strong> 12 minutes (vs 45 min manual)</p>
502
+ <p><strong>Cost Saved:</strong> <span class='savings-highlight'>${savings:,}</span></p>
503
+ <div class="approval-workflow">
504
+ <div class="workflow-step">✅ 1. ARF generated intent</div>
505
+ <div class="workflow-step">✅ 2. Safety checks passed</div>
506
+ <div class="workflow-step">✅ 3. Autonomous execution completed</div>
507
+ </div>
508
+ </div>
509
  </div>
510
  """
511
 
 
513
  enterprise_results = {
514
  "execution_mode": mode,
515
  "scenario": scenario_name,
516
+ "timestamp": datetime.datetime.now().isoformat(),
517
  "actions_executed": [
518
  "✅ Scaled resources based on ML recommendations",
519
  "✅ Implemented circuit breaker pattern",
520
+ "✅ Deployed enhanced monitoring",
521
+ "✅ Updated RAG memory with outcome"
522
  ],
523
  "business_impact": {
524
  "recovery_time": "60 min → 12 min",
525
  "cost_saved": f"${savings:,}",
526
+ "users_impacted": "45,000 → 0",
527
+ "mttr_reduction": "73% faster"
528
+ },
529
+ "safety_checks": {
530
+ "blast_radius": "2 services (within limit)",
531
+ "business_hours": "Compliant",
532
+ "action_type": "Approved",
533
+ "circuit_breaker": "Active"
534
  }
535
  }
536
 
 
541
 
542
  enterprise_btn.click(
543
  fn=execute_enterprise_healing,
544
+ inputs=[scenario_dropdown, approval_toggle, mcp_mode],
545
  outputs=[approval_display, enterprise_results_display, execution_table]
546
  )
547
 
548
+ # Run Complete Demo
549
+ def run_complete_demo(scenario_name):
550
+ """Run a complete demo walkthrough"""
551
+ import time
552
+
553
+ # Step 1: Update scenario
554
+ update_result = update_scenario_display(scenario_name)
555
+
556
+ # Simulate OSS analysis
557
+ time.sleep(1)
558
+
559
+ # Step 2: Run OSS analysis
560
+ oss_result = asyncio.run(run_oss_analysis(scenario_name))
561
+
562
+ # Step 3: Execute Enterprise (simulated)
563
+ time.sleep(2)
564
+
565
+ scenario = INCIDENT_SCENARIOS.get(scenario_name, {})
566
+ impact = scenario.get("business_impact", {})
567
+ revenue_loss = impact.get("revenue_loss_per_hour", 5000)
568
+ savings = int(revenue_loss * 0.85)
569
+
570
+ enterprise_results = {
571
+ "demo_mode": "Complete Walkthrough",
572
+ "scenario": scenario_name,
573
+ "steps_completed": [
574
+ "1. Incident detected (45s)",
575
+ "2. OSS analysis completed",
576
+ "3. HealingIntent created (94% confidence)",
577
+ "4. Enterprise license validated",
578
+ "5. Autonomous execution simulated",
579
+ "6. Outcome recorded in RAG memory"
580
+ ],
581
+ "outcome": {
582
+ "recovery_time": "12 minutes",
583
+ "manual_comparison": "45 minutes",
584
+ "cost_saved": f"${savings:,}",
585
+ "users_protected": "45,000",
586
+ "learning": "Pattern added to RAG memory"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
587
  }
588
  }
589
+
590
+ # Create demo completion message
591
+ demo_message = f"""
592
+ <div class="scenario-card" style="background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);">
593
+ <div class="scenario-header">
594
+ <h3>✅ Demo Complete</h3>
595
+ <span class="severity-badge low">SUCCESS</span>
596
+ </div>
597
+ <div class="scenario-details">
598
+ <p><strong>Scenario:</strong> {scenario_name}</p>
599
+ <p><strong>Workflow:</strong> OSS Analysis → Enterprise Execution</p>
600
+ <p><strong>Time Saved:</strong> 33 minutes (73% faster)</p>
601
+ <p><strong>Cost Avoided:</strong> ${savings:,}</p>
602
+ <p><em>This demonstrates the complete ARF value proposition from detection to autonomous healing.</em></p>
603
+ </div>
604
+ </div>
605
+ """
606
+
607
+ return (
608
+ update_result["scenario_html"],
609
+ update_result["telemetry_plot"],
610
+ update_result["impact_plot"],
611
+ update_result["timeline_plot"],
612
+ oss_result[0], oss_result[1], oss_result[2], # Agent updates
613
+ oss_result[3], # OSS results
614
+ demo_message, # Demo message
615
+ enterprise_results # Enterprise results
616
+ )
617
 
618
+ demo_btn.click(
619
+ fn=run_complete_demo,
620
+ inputs=[scenario_dropdown],
621
+ outputs=[
622
+ scenario_card, telemetry_viz, impact_viz, timeline_viz,
623
+ detection_agent, recall_agent, decision_agent,
624
+ oss_results_display, approval_display, enterprise_results_display
625
+ ]
626
  )
627
 
628
+ # ... [Rest of the event handlers remain the same] ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
629
 
630
+ # Initialize scenario display
631
  demo.load(
632
+ fn=lambda: update_scenario_display("Cache Miss Storm"),
633
+ outputs=[scenario_card, telemetry_viz, impact_viz, timeline_viz]
634
  )
635
 
636
+ # Initialize dashboard
637
  def initialize_dashboard():
638
  try:
 
639
  chart = viz_engine.create_executive_dashboard()
 
640
  return chart
641
  except Exception as e:
642
  logger.error(f"Dashboard initialization failed: {e}")
 
643
  import plotly.graph_objects as go
644
  fig = go.Figure(go.Indicator(
645
  mode="number+gauge",
 
666
  )
667
 
668
  return demo