petter2025 commited on
Commit
9b137fe
Β·
verified Β·
1 Parent(s): 5aa5b79

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +531 -556
app.py CHANGED
@@ -1,8 +1,6 @@
1
  """
2
  πŸš€ ARF Ultimate Investor Demo v3.8.0 - ENTERPRISE EDITION
3
- Main entry point with comprehensive 5-tab interface
4
- Uses actual ARF OSS v3.3.6 framework
5
- FULLY CORRECTED VERSION - Integrated with all components
6
  """
7
 
8
  import logging
@@ -12,8 +10,9 @@ import json
12
  import datetime
13
  import asyncio
14
  import time
 
15
  from pathlib import Path
16
- from typing import Dict, List, Any, Optional, Tuple, Union
17
 
18
  # Configure logging
19
  logging.basicConfig(
@@ -29,181 +28,26 @@ logger = logging.getLogger(__name__)
29
  # Add parent directory to path
30
  sys.path.insert(0, str(Path(__file__).parent))
31
 
32
- # ===========================================
33
- # ARF FRAMEWORK IMPORT - CORRECTED BASED ON PACKAGE STRUCTURE
34
- # ===========================================
35
- ARF_OSS_AVAILABLE = False
36
- OSS_VERSION = "3.3.6"
37
- HealingIntent = None
38
- IntentSource = None
39
- IntentStatus = None
40
- OSSMCPClient = None
41
-
42
  try:
43
- # ATTEMPT 1: Import from public package (correct based on pyproject.toml)
44
- try:
45
- from agentic_reliability_framework import __version__ as arf_version
46
- from agentic_reliability_framework.models import HealingIntent, IntentSource, IntentStatus
47
- from agentic_reliability_framework.engine import OSSMCPClient
48
-
49
- ARF_OSS_AVAILABLE = True
50
- OSS_VERSION = arf_version
51
- logger.info(f"βœ… Successfully imported ARF OSS v{OSS_VERSION} from public package")
52
-
53
- except ImportError as e1:
54
- logger.debug(f"Attempt 1 failed: {e1}")
55
-
56
- # ATTEMPT 2: Import from modules (development structure)
57
- try:
58
- # For Hugging Face demo, use enhanced mock classes
59
- logger.info("Using enhanced mock classes for demo environment")
60
-
61
- # Define enums matching the actual structure
62
- class IntentSource:
63
- OSS_ANALYSIS = "oss_analysis"
64
- RAG_SIMILARITY = "rag_similarity"
65
- HUMAN_OVERRIDE = "human_override"
66
- AUTOMATED_LEARNING = "automated_learning"
67
-
68
- class IntentStatus:
69
- CREATED = "created"
70
- OSS_ADVISORY_ONLY = "oss_advisory_only"
71
- PENDING_EXECUTION = "pending_execution"
72
- EXECUTING = "executing"
73
- COMPLETED = "completed"
74
- FAILED = "failed"
75
-
76
- # Enhanced HealingIntent based on actual structure
77
- class HealingIntent:
78
- def __init__(self, action: str, component: str, parameters: Dict, **kwargs):
79
- self.action = action
80
- self.component = component
81
- self.parameters = parameters
82
- self.justification = kwargs.get('justification', '')
83
- self.confidence = kwargs.get('confidence', 0.85)
84
- self.similar_incidents = kwargs.get('similar_incidents', [])
85
- self.rag_similarity_score = kwargs.get('rag_similarity_score')
86
- self.source = kwargs.get('source', IntentSource.OSS_ANALYSIS)
87
- self.status = kwargs.get('status', IntentStatus.CREATED)
88
- self.intent_id = kwargs.get('intent_id', f"intent_{int(time.time())}")
89
- self.oss_edition = "oss"
90
- self.requires_enterprise = True
91
- self.execution_allowed = False
92
- self.created_at = time.time()
93
-
94
- def to_enterprise_request(self) -> Dict:
95
- return {
96
- 'action': self.action,
97
- 'component': self.component,
98
- 'parameters': self.parameters,
99
- 'justification': self.justification,
100
- 'confidence': self.confidence,
101
- 'requires_enterprise': self.requires_enterprise,
102
- 'oss_metadata': {
103
- 'similar_incidents_count': len(self.similar_incidents),
104
- 'rag_used': self.rag_similarity_score is not None,
105
- 'source': self.source,
106
- 'oss_edition': self.oss_edition,
107
- 'execution_allowed': self.execution_allowed
108
- },
109
- 'intent_id': self.intent_id,
110
- 'created_at': self.created_at
111
- }
112
-
113
- def mark_as_oss_advisory(self):
114
- self.status = IntentStatus.OSS_ADVISORY_ONLY
115
- self.execution_allowed = False
116
- return self
117
-
118
- @classmethod
119
- def from_analysis(cls, action: str, component: str, parameters: Dict,
120
- justification: str, confidence: float, **kwargs):
121
- return cls(
122
- action=action,
123
- component=component,
124
- parameters=parameters,
125
- justification=justification,
126
- confidence=confidence,
127
- similar_incidents=kwargs.get('similar_incidents'),
128
- rag_similarity_score=kwargs.get('rag_similarity_score'),
129
- source=kwargs.get('source', IntentSource.OSS_ANALYSIS)
130
- )
131
-
132
- class OSSMCPClient:
133
- def __init__(self):
134
- self.mode = "advisory"
135
-
136
- async def analyze_and_recommend(self, tool_name: str, component: str,
137
- parameters: Dict, context: Optional[Dict] = None) -> HealingIntent:
138
- similar_incidents = [
139
- {"id": "inc_001", "similarity": 0.78, "resolution": "scaled_out",
140
- "component": "redis", "success": True, "timestamp": "2024-01-15T10:30:00"},
141
- {"id": "inc_045", "similarity": 0.65, "resolution": "restarted",
142
- "component": "database", "success": True, "timestamp": "2024-01-10T14:20:00"},
143
- {"id": "inc_089", "similarity": 0.59, "resolution": "circuit_breaker",
144
- "component": "api", "success": False, "timestamp": "2024-01-05T09:15:00"}
145
- ]
146
-
147
- rag_score = sum(inc["similarity"] for inc in similar_incidents[:3]) / 3 if similar_incidents else 0.67
148
-
149
- return HealingIntent.from_analysis(
150
- action=tool_name,
151
- component=component,
152
- parameters=parameters,
153
- justification=f"OSS Analysis: Based on {len(similar_incidents)} similar historical incidents with {rag_score:.0%} average similarity",
154
- confidence=0.82 + (len(similar_incidents) * 0.01),
155
- similar_incidents=similar_incidents,
156
- rag_similarity_score=rag_score,
157
- source=IntentSource.RAG_SIMILARITY
158
- ).mark_as_oss_advisory()
159
-
160
- # Set module-level variables
161
- IntentSource = IntentSource
162
- IntentStatus = IntentStatus
163
- OSSMCPClient = OSSMCPClient
164
- logger.info("βœ… Using enhanced mock classes for demo")
165
-
166
- except Exception as e2:
167
- logger.warning(f"Enhanced mock creation failed: {e2}")
168
-
169
- # Minimal fallback
170
- class HealingIntent:
171
- def __init__(self, **kwargs):
172
- pass
173
- def to_enterprise_request(self):
174
- return {"error": "ARF not available"}
175
- @classmethod
176
- def from_analysis(cls, **kwargs):
177
- return cls()
178
- def mark_as_oss_advisory(self):
179
- return self
180
-
181
- class OSSMCPClient:
182
- def __init__(self):
183
- self.mode = "advisory"
184
- async def analyze_and_recommend(self, **kwargs):
185
- return HealingIntent()
186
-
187
- except Exception as e:
188
- logger.error(f"❌ CRITICAL: Failed to initialize ARF framework: {e}")
189
- logger.error(traceback.format_exc())
190
- # Provide absolute minimal fallbacks
191
- class HealingIntent:
192
- def __init__(self, **kwargs):
193
- pass
194
- def to_enterprise_request(self):
195
- return {"error": "ARF not available"}
196
- @classmethod
197
- def from_analysis(cls, **kwargs):
198
- return cls()
199
- class OSSMCPClient:
200
- async def analyze_and_recommend(self, **kwargs):
201
- return HealingIntent()
202
 
203
  # ===========================================
204
- # IMPORT SUPPORTING MODULES
205
  # ===========================================
206
  try:
 
 
 
 
 
 
207
  # Import UI components
208
  from ui.components import (
209
  create_header, create_status_bar, create_tab1_incident_demo,
@@ -212,28 +56,26 @@ try:
212
  create_footer
213
  )
214
 
215
- # Import demo orchestrator
216
- from demo.orchestrator import DemoOrchestrator
217
-
218
- # Import visualizations
219
- from core.visualizations import EnhancedVisualizationEngine
220
-
221
- logger.info("βœ… Successfully imported all supporting modules")
222
 
223
  except ImportError as e:
224
- logger.warning(f"Could not import some modules: {e}")
225
- # We'll define minimal versions inline if needed
 
 
 
226
 
227
  # ===========================================
228
- # INCIDENT SCENARIOS (from original app.py)
229
  # ===========================================
230
- INCIDENT_SCENARIOS = {
231
  "Cache Miss Storm": {
232
  "description": "Redis cluster experiencing 80% cache miss rate causing database overload",
233
  "severity": "CRITICAL",
 
234
  "metrics": {
235
  "Cache Hit Rate": "18.5% (Critical)",
236
- "Database Load": "92% (Overloaded)",
237
  "Response Time": "1850ms (Slow)",
238
  "Affected Users": "45,000",
239
  "Eviction Rate": "125/sec"
@@ -245,31 +87,43 @@ INCIDENT_SCENARIOS = {
245
  "SLA Violation": "Yes",
246
  "Customer Sat": "-40%"
247
  },
248
- "component": "redis_cache",
249
- "oss_analysis": {
250
- "status": "βœ… ARF OSS Analysis Complete",
 
 
 
251
  "recommendations": [
252
- "Increase Redis cache memory allocation",
253
  "Implement cache warming strategy",
254
- "Optimize key patterns",
255
  "Add circuit breaker for database fallback"
256
  ],
257
- "estimated_time": "60+ minutes",
258
  "engineers_needed": "2-3 SREs + 1 DBA",
259
- "manual_effort": "High",
260
- "total_cost": "$8,500"
 
 
 
 
 
 
261
  },
 
262
  "enterprise_results": {
263
- "actions_completed": [
 
264
  "βœ… Auto-scaled Redis cluster: 4GB β†’ 8GB",
265
- "βœ… Deployed intelligent cache warming",
266
- "βœ… Optimized 12 key patterns with ML",
267
- "βœ… Implemented circuit breaker"
268
  ],
269
  "metrics_improvement": {
270
  "Cache Hit Rate": "18.5% β†’ 72%",
271
  "Response Time": "1850ms β†’ 450ms",
272
- "Database Load": "92% β†’ 45%"
 
273
  },
274
  "business_impact": {
275
  "Recovery Time": "60 min β†’ 12 min",
@@ -277,12 +131,20 @@ INCIDENT_SCENARIOS = {
277
  "Users Impacted": "45,000 β†’ 0",
278
  "Revenue Protected": "$1,700",
279
  "MTTR Improvement": "80% reduction"
 
 
 
 
 
 
280
  }
281
  }
282
  },
 
283
  "Database Connection Pool Exhaustion": {
284
- "description": "Database connection pool exhausted causing API timeouts and user failures",
285
  "severity": "HIGH",
 
286
  "metrics": {
287
  "Active Connections": "98/100 (Critical)",
288
  "API Latency": "2450ms",
@@ -296,415 +158,559 @@ INCIDENT_SCENARIOS = {
296
  "SLA Violation": "Yes",
297
  "Partner Impact": "3 external APIs"
298
  },
299
- "component": "database"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
300
  },
301
- "Memory Leak in Production": {
302
- "description": "Java service memory leak causing gradual performance degradation",
 
303
  "severity": "HIGH",
 
304
  "metrics": {
305
  "Memory Usage": "96% (Critical)",
306
  "GC Pause Time": "4500ms",
307
  "Error Rate": "28.5%",
308
- "Restart Frequency": "12/hour",
309
  "Heap Fragmentation": "42%"
310
  },
311
  "impact": {
312
  "Revenue Loss": "$5,500/hour",
313
  "Session Loss": "8,500 users",
314
- "Customer Impact": "High",
315
  "Support Tickets": "+300%"
316
  },
317
- "component": "java_service"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
318
  }
319
  }
320
 
321
  # ===========================================
322
- # AUDIT TRAIL MANAGER (from original app.py)
323
  # ===========================================
324
- class AuditTrailManager:
325
- """Manage audit trail and execution history"""
326
-
327
- def __init__(self):
328
- self.execution_history = []
329
- self.incident_history = []
330
- self._initialize_sample_data()
331
 
332
- def _initialize_sample_data(self):
333
- """Initialize with sample historical data"""
334
- base_time = datetime.datetime.now() - datetime.timedelta(hours=2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
335
 
336
- sample_executions = [
337
- self._create_execution_entry(
338
- base_time - datetime.timedelta(minutes=90),
339
- "Cache Miss Storm", 4, 7200, "βœ… Executed", "Auto-scaled cache"
340
- ),
341
- self._create_execution_entry(
342
- base_time - datetime.timedelta(minutes=75),
343
- "Memory Leak", 3, 5200, "βœ… Executed", "Fixed memory leak"
344
- ),
345
- self._create_execution_entry(
346
- base_time - datetime.timedelta(minutes=60),
347
- "API Rate Limit", 4, 2800, "βœ… Executed", "Increased rate limits"
348
- ),
349
- ]
350
 
351
- self.execution_history = sample_executions
 
 
 
 
 
352
 
353
- services = ["API Gateway", "Database", "Redis Cache", "Auth Service"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
354
 
355
- for i in range(8):
356
- incident_time = base_time - datetime.timedelta(minutes=i * 15)
357
- self.incident_history.append({
358
- "timestamp": incident_time,
359
- "time_str": incident_time.strftime("%H:%M"),
360
- "service": services[i % len(services)],
361
- "type": "Cache Miss Storm" if i % 3 == 0 else "Memory Leak",
362
- "severity": 3 if i % 3 == 0 else 2,
363
- "description": f"High latency on {services[i % len(services)]}",
364
- "id": f"inc_{i:03d}"
365
- })
366
 
367
- def _create_execution_entry(self, timestamp, scenario, actions, savings, status, details):
368
- return {
369
- "timestamp": timestamp,
370
- "time_str": timestamp.strftime("%H:%M"),
371
- "scenario": scenario,
372
- "actions": str(actions),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
373
  "savings": f"${savings:,}",
374
- "status": status,
375
- "details": details,
376
- "id": f"exec_{len(self.execution_history):03d}"
377
  }
378
-
379
- def add_execution(self, scenario: str, actions: List[str],
380
- savings: int, approval_required: bool, details: str = ""):
381
- entry = self._create_execution_entry(
382
- datetime.datetime.now(),
383
- scenario,
384
- len(actions),
385
- savings,
386
- "βœ… Approved & Executed" if approval_required else "βœ… Auto-Executed",
387
- details
388
- )
389
- self.execution_history.insert(0, entry)
390
  return entry
391
 
392
- def add_incident(self, scenario_name: str, metrics: Dict):
393
  entry = {
394
- "timestamp": datetime.datetime.now(),
395
- "time_str": datetime.datetime.now().strftime("%H:%M"),
396
- "service": "Demo System",
397
- "type": scenario_name,
398
- "severity": 3,
399
- "description": f"Demo incident: {scenario_name}",
400
- "id": f"inc_{len(self.incident_history):03d}"
401
  }
402
- self.incident_history.insert(0, entry)
403
  return entry
404
 
405
- def get_execution_history_table(self, limit: int = 10) -> List[List]:
406
  return [
407
- [entry["time_str"], entry["scenario"], entry["actions"],
408
- entry["status"], entry["savings"], entry["details"]]
409
- for entry in self.execution_history[:limit]
410
  ]
411
 
412
- def get_incident_history_table(self, limit: int = 15) -> List[List]:
413
  return [
414
- [entry["time_str"], entry["service"], entry["type"],
415
- f"{entry['severity']}/3", entry["description"]]
416
- for entry in self.incident_history[:limit]
417
  ]
418
-
419
- def export_audit_trail(self) -> str:
420
- total_savings = sum(
421
- int(e["savings"].replace("$", "").replace(",", ""))
422
- for e in self.execution_history
423
- if "$" in e["savings"]
424
- )
425
-
426
- return json.dumps({
427
- "executions": self.execution_history,
428
- "incidents": self.incident_history,
429
- "exported_at": datetime.datetime.now().isoformat(),
430
- "total_executions": len(self.execution_history),
431
- "total_incidents": len(self.incident_history),
432
- "total_savings": total_savings,
433
- "arf_version": OSS_VERSION,
434
- "oss_available": ARF_OSS_AVAILABLE
435
- }, indent=2, default=str)
436
 
437
  # ===========================================
438
- # CREATE DEMO INTERFACE - CORRECTED
439
  # ===========================================
440
  def create_demo_interface():
441
- """Create the 5-tab demo interface - CORRECTED VERSION"""
442
 
443
- # Import gradio here to avoid issues
444
  import gradio as gr
445
 
446
  # Initialize components
 
447
  audit_manager = AuditTrailManager()
448
 
449
- # Create OSS client
450
- oss_client = OSSMCPClient() if OSSMCPClient else None
451
-
452
- # Create orchestrator
453
- orchestrator = DemoOrchestrator(arf_client=oss_client)
454
-
455
- # Create visualization engine
456
- try:
457
- viz_engine = EnhancedVisualizationEngine()
458
- except:
459
- # Fallback to simple visualizations
460
- class SimpleVizEngine:
461
- def create_interactive_timeline(self, scenario):
462
- import plotly.graph_objects as go
463
- fig = go.Figure()
464
- fig.add_trace(go.Scatter(x=[1,2,3], y=[1,2,1]))
465
- fig.update_layout(title="Timeline", height=400)
466
- return fig
467
- def create_executive_dashboard(self, roi=None):
468
- import plotly.graph_objects as go
469
- fig = go.Figure()
470
- fig.add_trace(go.Bar(x=['A','B','C'], y=[1,2,3]))
471
- fig.update_layout(title="Dashboard", height=400)
472
- return fig
473
- viz_engine = SimpleVizEngine()
474
 
475
- # Custom CSS
476
  custom_css = """
477
- .gradio-container {
478
- max-width: 1800px !important;
479
- margin: auto !important;
480
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif !important;
481
- }
482
- h1 {
483
- background: linear-gradient(90deg, #1a365d 0%, #2d3748 100%);
484
- -webkit-background-clip: text;
485
- -webkit-text-fill-color: transparent;
486
- background-clip: text;
487
- font-weight: 800 !important;
488
- font-size: 2.5rem !important;
489
- margin-bottom: 0.5rem !important;
490
  }
491
- .critical { color: #FF6B6B !important; font-weight: 900 !important; }
492
- .success { color: #4ECDC4 !important; font-weight: 900 !important; }
493
- .tab-nav { background: linear-gradient(90deg, #f8fafc 0%, #ffffff 100%) !important; }
494
- .metric-card {
495
- background: white !important;
496
- border-radius: 10px !important;
497
- padding: 20px !important;
498
- box-shadow: 0 2px 8px rgba(0,0,0,0.06) !important;
499
- border-left: 4px solid #4ECDC4 !important;
500
  margin-bottom: 15px !important;
501
  }
 
 
502
  """
503
 
504
- with gr.Blocks(
505
- title=f"πŸš€ ARF Investor Demo v3.8.0",
506
- theme=gr.themes.Soft(
507
- primary_hue="blue",
508
- secondary_hue="teal"
509
- ),
510
- css=custom_css
511
- ) as demo:
512
 
513
- # ============ HEADER ============
514
- create_header(OSS_VERSION, ARF_OSS_AVAILABLE)
515
 
516
- # ============ STATUS BAR ============
517
  create_status_bar()
518
 
519
- # ============ 5 TABS ============
520
  with gr.Tabs():
521
 
522
- # TAB 1: LIVE INCIDENT DEMO
523
  with gr.TabItem("πŸ”₯ Live Incident Demo"):
524
- # Get components from UI module
525
  (scenario_dropdown, scenario_description, metrics_display, impact_display,
526
  timeline_output, oss_btn, enterprise_btn, approval_toggle, demo_btn,
527
  approval_display, config_display, results_display) = create_tab1_incident_demo(
528
- INCIDENT_SCENARIOS, "Cache Miss Storm"
529
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
530
 
531
- # TAB 2: BUSINESS IMPACT & ROI
532
  with gr.TabItem("πŸ’° Business Impact & ROI"):
533
  (dashboard_output, monthly_slider, impact_slider, team_slider,
534
  calculate_btn, roi_output) = create_tab2_business_roi()
535
 
536
- # TAB 3: AUDIT TRAIL & HISTORY
537
  with gr.TabItem("πŸ“œ Audit Trail & History"):
538
  (refresh_btn, clear_btn, export_btn, execution_table, savings_chart,
539
  incident_table, memory_graph, export_text) = create_tab3_audit_trail()
540
 
541
- # TAB 4: ENTERPRISE FEATURES
542
  with gr.TabItem("🏒 Enterprise Features"):
543
- (license_display, validate_btn, trial_btn, upgrade_btn, features_table,
544
- compliance_display, integrations_table, mcp_mode) = create_tab4_enterprise_features()
545
 
546
- # TAB 5: LEARNING ENGINE
547
  with gr.TabItem("🧠 Learning Engine"):
548
- (learning_graph, graph_type, show_labels, search_query, search_btn,
549
- clear_btn_search, search_results, stats_display, patterns_display,
550
- performance_display) = create_tab5_learning_engine()
551
 
552
- # ============ FOOTER ============
553
  create_footer()
554
 
555
- # ============ EVENT HANDLERS ============
556
 
557
- # Scenario dropdown change
558
  def update_scenario(scenario_name):
559
- scenario = INCIDENT_SCENARIOS.get(scenario_name, {})
560
- timeline = viz_engine.create_interactive_timeline(scenario)
 
 
 
 
 
 
561
  return (
562
  f"### {scenario_name}\n{scenario.get('description', 'No description')}",
563
  scenario.get("metrics", {}),
564
  scenario.get("impact", {}),
565
- timeline
 
 
566
  )
567
 
568
  scenario_dropdown.change(
569
  fn=update_scenario,
570
  inputs=[scenario_dropdown],
571
- outputs=[scenario_description, metrics_display, impact_display, timeline_output]
 
572
  )
573
 
574
- # OSS Analysis button
575
  async def run_oss_analysis(scenario_name):
576
- scenario = INCIDENT_SCENARIOS.get(scenario_name, {})
577
- analysis = await orchestrator.analyze_incident(scenario_name, scenario)
578
 
579
  # Add to audit trail
580
- audit_manager.add_incident(scenario_name, scenario.get("metrics", {}))
 
 
 
581
 
582
  # Update tables
583
- incident_table_data = audit_manager.get_incident_history_table()
584
 
585
- return analysis, incident_table_data
586
 
587
  oss_btn.click(
588
  fn=run_oss_analysis,
589
  inputs=[scenario_dropdown],
590
- outputs=[results_display, incident_table]
591
  )
592
 
593
- # Enterprise Healing button
594
- def execute_healing(scenario_name, approval_required):
595
- scenario = INCIDENT_SCENARIOS.get(scenario_name, {})
596
 
597
- # Create mock healing intent
598
- healing_intent = {
599
- "action": "scale_out",
600
- "component": scenario.get("component", "unknown"),
601
- "parameters": {"scale_factor": 2},
602
- "justification": f"Healing {scenario_name}"
603
- }
604
 
605
- # Execute through orchestrator
606
- execution = orchestrator.execute_healing(
607
- scenario_name,
608
- healing_intent,
609
- mode="approval" if approval_required else "autonomous"
610
- )
 
 
 
 
611
 
612
  # Add to audit trail
613
  audit_manager.add_execution(
614
  scenario_name,
615
- ["scale_out", "circuit_breaker", "monitoring"],
616
- 7200,
617
- approval_required,
618
- f"Healed {scenario_name}"
619
  )
620
 
621
- # Create approval HTML
622
  if approval_required:
623
- approval_html = """
624
- <div style='padding: 20px; background: #e8f5e8; border-radius: 10px; border-left: 4px solid #28a745;'>
625
- <div style='display: flex; align-items: center; gap: 10px; margin-bottom: 15px;'>
626
- <div style='background: #28a745; color: white; width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold;'>
627
- βœ…
628
- </div>
629
- <h4 style='margin: 0; color: #1a365d;'>Approved & Executed</h4>
630
- </div>
631
- <div style='color: #2d3748;'>
632
- Action approved by system administrator and executed successfully.
633
- </div>
634
  </div>
635
  """
636
  else:
637
- approval_html = """
638
- <div style='padding: 20px; background: #e3f2fd; border-radius: 10px; border-left: 4px solid #2196f3;'>
639
- <div style='display: flex; align-items: center; gap: 10px; margin-bottom: 15px;'>
640
- <div style='background: #2196f3; color: white; width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold;'>
641
- ⚑
642
- </div>
643
- <h4 style='margin: 0; color: #1a365d;'>Auto-Executed</h4>
644
- </div>
645
- <div style='color: #2d3748;'>
646
- Action executed autonomously by ARF Enterprise.
647
- </div>
648
  </div>
649
  """
650
 
651
  # Update execution table
652
- execution_table_data = audit_manager.get_execution_history_table()
653
 
654
- return approval_html, execution, execution_table_data
655
 
656
  enterprise_btn.click(
657
- fn=execute_healing,
658
  inputs=[scenario_dropdown, approval_toggle],
659
- outputs=[approval_display, results_display, execution_table]
660
  )
661
 
662
- # Quick Demo button
663
  async def run_quick_demo():
664
  # Run OSS analysis
665
- scenario = INCIDENT_SCENARIOS["Cache Miss Storm"]
666
- analysis = await orchestrator.analyze_incident("Cache Miss Storm", scenario)
667
 
668
- # Execute healing
669
- execution = orchestrator.execute_healing(
670
- "Cache Miss Storm",
671
- {"action": "scale_out", "component": "redis_cache"},
672
- mode="autonomous"
673
- )
674
 
675
  # Update audit trail
676
- audit_manager.add_incident("Cache Miss Storm", scenario.get("metrics", {}))
677
- audit_manager.add_execution(
678
- "Cache Miss Storm",
679
- ["scale_out", "circuit_breaker"],
680
- 7200,
681
- False,
682
- "Quick demo execution"
683
- )
684
 
685
- # Update all tables
686
- execution_table_data = audit_manager.get_execution_history_table()
687
- incident_table_data = audit_manager.get_incident_history_table()
688
 
689
- # Create approval HTML
690
  approval_html = """
691
- <div style='padding: 20px; background: #fff3cd; border-radius: 10px; border-left: 4px solid #ffc107;'>
692
- <div style='display: flex; align-items: center; gap: 10px; margin-bottom: 15px;'>
693
- <div style='background: #ffc107; color: white; width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold;'>
694
- ⚑
695
- </div>
696
- <h4 style='margin: 0; color: #1a365d;'>Quick Demo Completed</h4>
697
- </div>
698
- <div style='color: #2d3748;'>
699
- OSS analysis β†’ Enterprise execution completed successfully.
700
- </div>
701
  </div>
702
  """
703
 
704
  return (
705
- analysis,
706
  approval_html,
707
- execution,
708
  execution_table_data,
709
  incident_table_data,
710
  gr.Checkbox.update(value=False)
@@ -713,38 +719,52 @@ def create_demo_interface():
713
  demo_btn.click(
714
  fn=run_quick_demo,
715
  outputs=[
716
- results_display,
717
  approval_display,
718
- results_display,
719
  execution_table,
720
  incident_table,
721
  approval_toggle
722
  ]
723
  )
724
 
725
- # ROI Calculator
726
  def calculate_roi(monthly, impact, team):
727
- company_data = {
728
- "monthly_incidents": monthly,
729
- "avg_cost_per_incident": impact,
730
- "team_size": team
731
- }
732
- roi_result = orchestrator.calculate_roi(company_data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
733
 
734
  # Format for display
735
- formatted_result = {
736
- "annual_impact": f"${roi_result['annual_impact']:,.0f}",
737
- "team_cost": f"${roi_result['team_cost']:,.0f}",
738
- "potential_savings": f"${roi_result['potential_savings']:,.0f}",
739
- "roi_multiplier": f"{roi_result['roi_multiplier']:.1f}Γ—",
740
- "payback_months": f"{roi_result['payback_months']:.1f} months",
741
- "recommendation": roi_result['recommendation']
742
  }
743
 
744
- # Update dashboard with user-specific ROI
745
- dashboard = viz_engine.create_executive_dashboard(roi_result)
746
 
747
- return formatted_result, dashboard
748
 
749
  calculate_btn.click(
750
  fn=calculate_roi,
@@ -752,101 +772,56 @@ def create_demo_interface():
752
  outputs=[roi_output, dashboard_output]
753
  )
754
 
755
- # Audit Trail Refresh
756
  def refresh_audit_trail():
757
- execution_table_data = audit_manager.get_execution_history_table()
758
- incident_table_data = audit_manager.get_incident_history_table()
759
- export_data = audit_manager.export_audit_trail()
760
- return execution_table_data, incident_table_data, export_data
761
 
762
  refresh_btn.click(
763
  fn=refresh_audit_trail,
764
- outputs=[execution_table, incident_table, export_text]
765
  )
766
 
767
- # Clear History
768
  def clear_audit_trail():
769
- audit_manager.execution_history = []
770
- audit_manager.incident_history = []
771
- audit_manager._initialize_sample_data()
772
- return refresh_audit_trail()
773
 
774
  clear_btn.click(
775
  fn=clear_audit_trail,
776
- outputs=[execution_table, incident_table, export_text]
777
- )
778
-
779
- # Export Audit Trail
780
- def update_export():
781
- return audit_manager.export_audit_trail()
782
-
783
- export_btn.click(
784
- fn=update_export,
785
- outputs=[export_text]
786
- )
787
-
788
- # Search similar incidents
789
- def search_incidents(query):
790
- if not query.strip():
791
- return []
792
- results = orchestrator.get_similar_incidents(query)
793
- return [[r["id"], f"{r['similarity']:.0%}", r["scenario"], r["resolution"]]
794
- for r in results]
795
-
796
- search_btn.click(
797
- fn=search_incidents,
798
- inputs=[search_query],
799
- outputs=[search_results]
800
- )
801
-
802
- clear_btn_search.click(
803
- fn=lambda: [],
804
- outputs=[search_results]
805
  )
806
 
807
- # Initialize dashboard on load
808
  demo.load(
809
- fn=lambda: viz_engine.create_executive_dashboard(),
810
- outputs=[dashboard_output]
 
811
  )
812
 
813
  return demo
814
 
815
  # ===========================================
816
- # MAIN EXECUTION - CORRECTED
817
  # ===========================================
818
  def main():
819
- """Main entry point - CORRECTED"""
820
  print("πŸš€ Starting ARF Ultimate Investor Demo v3.8.0...")
821
  print("=" * 70)
822
  print("πŸ“Š Features:")
823
- print(" β€’ 5 Comprehensive Tabs with User-Focused Journey")
824
- print(" β€’ Live Incident Demo with OSS Analysis")
825
- print(" β€’ Business Impact & ROI Calculator")
826
- print(" β€’ Audit Trail & History with Memory Graph")
827
- print(" β€’ Enterprise Features & License Management")
828
- print(" β€’ Learning Engine with Pattern Detection")
829
  print("=" * 70)
830
- print(f"\nπŸ“¦ Using ARF OSS v{OSS_VERSION}")
831
- print(f"πŸ”§ ARF Available: {ARF_OSS_AVAILABLE}")
832
  print("🌐 Opening web interface...")
833
 
834
- # Create and launch the demo interface
835
  demo = create_demo_interface()
836
-
837
- # Launch configuration
838
- launch_config = {
839
- "server_name": "0.0.0.0",
840
- "server_port": 7860,
841
- "share": False,
842
- "debug": False,
843
- "show_error": True
844
- }
845
-
846
- demo.launch(**launch_config)
847
 
848
- # ===========================================
849
- # EXECUTION GUARD - CORRECTED
850
- # ===========================================
851
  if __name__ == "__main__":
852
  main()
 
1
  """
2
  πŸš€ ARF Ultimate Investor Demo v3.8.0 - ENTERPRISE EDITION
3
+ COMPLETE FIXED VERSION - All components integrated
 
 
4
  """
5
 
6
  import logging
 
10
  import datetime
11
  import asyncio
12
  import time
13
+ import numpy as np
14
  from pathlib import Path
15
+ from typing import Dict, List, Any, Optional, Tuple
16
 
17
  # Configure logging
18
  logging.basicConfig(
 
28
  # Add parent directory to path
29
  sys.path.insert(0, str(Path(__file__).parent))
30
 
31
+ # Import Plotly early to ensure availability
 
 
 
 
 
 
 
 
 
32
  try:
33
+ import plotly.graph_objects as go
34
+ import plotly.express as px
35
+ from plotly.subplots import make_subplots
36
+ PLOTLY_AVAILABLE = True
37
+ except ImportError:
38
+ logger.warning("Plotly not available - visualizations will be simplified")
39
+ PLOTLY_AVAILABLE = False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
  # ===========================================
42
+ # IMPORT MODULAR COMPONENTS
43
  # ===========================================
44
  try:
45
+ # Import scenarios from your modular file
46
+ from demo.scenarios import INCIDENT_SCENARIOS as SCENARIOS_DATA
47
+
48
+ # Import orchestrator
49
+ from demo.orchestrator import DemoOrchestrator
50
+
51
  # Import UI components
52
  from ui.components import (
53
  create_header, create_status_bar, create_tab1_incident_demo,
 
56
  create_footer
57
  )
58
 
59
+ logger.info("βœ… Successfully imported all modular components")
 
 
 
 
 
 
60
 
61
  except ImportError as e:
62
+ logger.error(f"Failed to import components: {e}")
63
+ logger.error(traceback.format_exc())
64
+ # Fallback to inline definitions
65
+ SCENARIOS_DATA = {}
66
+ DemoOrchestrator = None
67
 
68
  # ===========================================
69
+ # ENHANCED SCENARIOS WITH OSS vs ENTERPRISE SEPARATION
70
  # ===========================================
71
+ ENHANCED_SCENARIOS = {
72
  "Cache Miss Storm": {
73
  "description": "Redis cluster experiencing 80% cache miss rate causing database overload",
74
  "severity": "CRITICAL",
75
+ "component": "redis_cache",
76
  "metrics": {
77
  "Cache Hit Rate": "18.5% (Critical)",
78
+ "Database Load": "92% (Overloaded)",
79
  "Response Time": "1850ms (Slow)",
80
  "Affected Users": "45,000",
81
  "Eviction Rate": "125/sec"
 
87
  "SLA Violation": "Yes",
88
  "Customer Sat": "-40%"
89
  },
90
+ # OSS RESULTS - ADVISORY ONLY
91
+ "oss_results": {
92
+ "status": "βœ… OSS Analysis Complete",
93
+ "confidence": 0.87,
94
+ "similar_incidents": 3,
95
+ "rag_similarity_score": 0.72,
96
  "recommendations": [
97
+ "Scale Redis cache memory from 4GB β†’ 8GB",
98
  "Implement cache warming strategy",
99
+ "Optimize key patterns with TTL adjustments",
100
  "Add circuit breaker for database fallback"
101
  ],
102
+ "estimated_time": "60+ minutes manually",
103
  "engineers_needed": "2-3 SREs + 1 DBA",
104
+ "advisory_only": True,
105
+ "healing_intent": {
106
+ "action": "scale_out",
107
+ "component": "redis_cache",
108
+ "parameters": {"scale_factor": 2.0},
109
+ "confidence": 0.87,
110
+ "requires_enterprise": True
111
+ }
112
  },
113
+ # ENTERPRISE RESULTS - ACTUAL EXECUTION
114
  "enterprise_results": {
115
+ "execution_mode": "Autonomous",
116
+ "actions_executed": [
117
  "βœ… Auto-scaled Redis cluster: 4GB β†’ 8GB",
118
+ "βœ… Deployed intelligent cache warming service",
119
+ "βœ… Optimized 12 key patterns with ML recommendations",
120
+ "βœ… Implemented circuit breaker with 95% success rate"
121
  ],
122
  "metrics_improvement": {
123
  "Cache Hit Rate": "18.5% β†’ 72%",
124
  "Response Time": "1850ms β†’ 450ms",
125
+ "Database Load": "92% β†’ 45%",
126
+ "Throughput": "1250 β†’ 2450 req/sec"
127
  },
128
  "business_impact": {
129
  "Recovery Time": "60 min β†’ 12 min",
 
131
  "Users Impacted": "45,000 β†’ 0",
132
  "Revenue Protected": "$1,700",
133
  "MTTR Improvement": "80% reduction"
134
+ },
135
+ "audit_info": {
136
+ "execution_id": "exec_001",
137
+ "timestamp": datetime.datetime.now().isoformat(),
138
+ "approval_required": False,
139
+ "success": True
140
  }
141
  }
142
  },
143
+
144
  "Database Connection Pool Exhaustion": {
145
+ "description": "PostgreSQL connection pool exhausted causing API timeouts",
146
  "severity": "HIGH",
147
+ "component": "postgresql_database",
148
  "metrics": {
149
  "Active Connections": "98/100 (Critical)",
150
  "API Latency": "2450ms",
 
158
  "SLA Violation": "Yes",
159
  "Partner Impact": "3 external APIs"
160
  },
161
+ "oss_results": {
162
+ "status": "βœ… OSS Analysis Complete",
163
+ "confidence": 0.82,
164
+ "similar_incidents": 2,
165
+ "rag_similarity_score": 0.65,
166
+ "recommendations": [
167
+ "Increase connection pool size from 100 β†’ 200",
168
+ "Implement connection pooling monitoring",
169
+ "Add query timeout enforcement",
170
+ "Deploy read replica for read-heavy queries"
171
+ ],
172
+ "estimated_time": "45+ minutes manually",
173
+ "engineers_needed": "1 DBA + 1 Backend Engineer",
174
+ "advisory_only": True,
175
+ "healing_intent": {
176
+ "action": "scale_connection_pool",
177
+ "component": "postgresql_database",
178
+ "parameters": {"max_connections": 200},
179
+ "confidence": 0.82,
180
+ "requires_enterprise": True
181
+ }
182
+ },
183
+ "enterprise_results": {
184
+ "execution_mode": "Approval Required",
185
+ "actions_executed": [
186
+ "βœ… Increased connection pool: 100 β†’ 200 connections",
187
+ "βœ… Deployed real-time connection monitoring",
188
+ "βœ… Implemented query timeout: 30s β†’ 10s",
189
+ "βœ… Automated read replica traffic routing"
190
+ ],
191
+ "metrics_improvement": {
192
+ "API Latency": "2450ms β†’ 320ms",
193
+ "Error Rate": "15.2% β†’ 0.8%",
194
+ "Connection Wait": "45s β†’ 120ms",
195
+ "Throughput": "850 β†’ 2100 req/sec"
196
+ },
197
+ "business_impact": {
198
+ "Recovery Time": "45 min β†’ 8 min",
199
+ "Cost Saved": "$3,150",
200
+ "Failed Transactions": "12,500 β†’ 0",
201
+ "SLA Compliance": "Restored to 99.9%"
202
+ },
203
+ "audit_info": {
204
+ "execution_id": "exec_002",
205
+ "timestamp": datetime.datetime.now().isoformat(),
206
+ "approval_required": True,
207
+ "success": True
208
+ }
209
+ }
210
  },
211
+
212
+ "Kubernetes Memory Leak": {
213
+ "description": "Java microservice memory leak causing pod restarts",
214
  "severity": "HIGH",
215
+ "component": "java_payment_service",
216
  "metrics": {
217
  "Memory Usage": "96% (Critical)",
218
  "GC Pause Time": "4500ms",
219
  "Error Rate": "28.5%",
220
+ "Pod Restarts": "12/hour",
221
  "Heap Fragmentation": "42%"
222
  },
223
  "impact": {
224
  "Revenue Loss": "$5,500/hour",
225
  "Session Loss": "8,500 users",
226
+ "Payment Failures": "3.2% of transactions",
227
  "Support Tickets": "+300%"
228
  },
229
+ "oss_results": {
230
+ "status": "βœ… OSS Analysis Complete",
231
+ "confidence": 0.79,
232
+ "similar_incidents": 4,
233
+ "rag_similarity_score": 0.68,
234
+ "recommendations": [
235
+ "Increase pod memory limits from 2GB β†’ 4GB",
236
+ "Implement memory leak detection",
237
+ "Deploy canary with fixed version",
238
+ "Add circuit breaker for graceful degradation"
239
+ ],
240
+ "estimated_time": "90+ minutes manually",
241
+ "engineers_needed": "2 Java Devs + 1 SRE",
242
+ "advisory_only": True,
243
+ "healing_intent": {
244
+ "action": "scale_memory",
245
+ "component": "java_payment_service",
246
+ "parameters": {"memory_limit_gb": 4},
247
+ "confidence": 0.79,
248
+ "requires_enterprise": True
249
+ }
250
+ },
251
+ "enterprise_results": {
252
+ "execution_mode": "Autonomous with Rollback",
253
+ "actions_executed": [
254
+ "βœ… Scaled pod memory: 2GB β†’ 4GB with monitoring",
255
+ "βœ… Deployed memory leak detection service",
256
+ "βœ… Rolled out canary with memory fixes",
257
+ "βœ… Implemented auto-rollback on failure"
258
+ ],
259
+ "metrics_improvement": {
260
+ "Memory Usage": "96% β†’ 68%",
261
+ "GC Pause Time": "4500ms β†’ 320ms",
262
+ "Error Rate": "28.5% β†’ 1.2%",
263
+ "Pod Stability": "12/hour β†’ 0 restarts"
264
+ },
265
+ "business_impact": {
266
+ "Recovery Time": "90 min β†’ 15 min",
267
+ "Cost Saved": "$4,950",
268
+ "Transaction Success": "96.8% β†’ 99.9%",
269
+ "User Impact": "8,500 β†’ 0 affected"
270
+ },
271
+ "audit_info": {
272
+ "execution_id": "exec_003",
273
+ "timestamp": datetime.datetime.now().isoformat(),
274
+ "approval_required": False,
275
+ "success": True
276
+ }
277
+ }
278
+ },
279
+
280
+ "API Rate Limit Storm": {
281
+ "description": "Third-party API rate limiting causing cascading failures",
282
+ "severity": "MEDIUM",
283
+ "component": "external_api_gateway",
284
+ "metrics": {
285
+ "Rate Limit Hits": "95% of requests",
286
+ "Error Rate": "42.8%",
287
+ "Retry Storm": "Active",
288
+ "Cascade Effect": "3 dependent services",
289
+ "Queue Backlog": "8,500 requests"
290
+ },
291
+ "impact": {
292
+ "Revenue Loss": "$3,800/hour",
293
+ "Partner SLA Breach": "Yes",
294
+ "Data Sync Delay": "4+ hours",
295
+ "Customer Reports": "Delayed by 6 hours"
296
+ },
297
+ "oss_results": {
298
+ "status": "βœ… OSS Analysis Complete",
299
+ "confidence": 0.85,
300
+ "similar_incidents": 3,
301
+ "rag_similarity_score": 0.71,
302
+ "recommendations": [
303
+ "Implement exponential backoff with jitter",
304
+ "Deploy circuit breaker pattern",
305
+ "Add request queuing with prioritization",
306
+ "Implement adaptive rate limiting"
307
+ ],
308
+ "estimated_time": "75+ minutes manually",
309
+ "engineers_needed": "2 Backend Engineers + 1 DevOps",
310
+ "advisory_only": True,
311
+ "healing_intent": {
312
+ "action": "implement_rate_limiting",
313
+ "component": "external_api_gateway",
314
+ "parameters": {"backoff_strategy": "exponential"},
315
+ "confidence": 0.85,
316
+ "requires_enterprise": True
317
+ }
318
+ },
319
+ "enterprise_results": {
320
+ "execution_mode": "Autonomous",
321
+ "actions_executed": [
322
+ "βœ… Implemented exponential backoff: 1s β†’ 32s with jitter",
323
+ "βœ… Deployed circuit breaker with 80% success threshold",
324
+ "βœ… Added intelligent request queuing",
325
+ "βœ… Enabled adaptive rate limiting based on API health"
326
+ ],
327
+ "metrics_improvement": {
328
+ "Rate Limit Hits": "95% β†’ 12%",
329
+ "Error Rate": "42.8% β†’ 3.5%",
330
+ "Successful Retries": "18% β†’ 89%",
331
+ "Queue Processing": "8,500 β†’ 0 backlog"
332
+ },
333
+ "business_impact": {
334
+ "Recovery Time": "75 min β†’ 10 min",
335
+ "Cost Saved": "$3,420",
336
+ "SLA Compliance": "Restored within 5 minutes",
337
+ "Data Freshness": "4+ hours β†’ <5 minute delay"
338
+ },
339
+ "audit_info": {
340
+ "execution_id": "exec_004",
341
+ "timestamp": datetime.datetime.now().isoformat(),
342
+ "approval_required": False,
343
+ "success": True
344
+ }
345
+ }
346
  }
347
  }
348
 
349
  # ===========================================
350
+ # SIMPLE VISUALIZATION ENGINE (No external dependencies)
351
  # ===========================================
352
+ class SimpleVizEngine:
353
+ """Simple visualization engine that works without complex imports"""
 
 
 
 
 
354
 
355
+ @staticmethod
356
+ def create_timeline_plot(scenario_name="Incident"):
357
+ """Create a simple timeline plot"""
358
+ if not PLOTLY_AVAILABLE:
359
+ # Return a placeholder if plotly not available
360
+ import matplotlib.pyplot as plt
361
+ import io
362
+ import base64
363
+
364
+ fig, ax = plt.subplots(figsize=(10, 4))
365
+ events = ['Detection', 'Analysis', 'Action', 'Recovery']
366
+ times = [0, 1, 2, 3]
367
+
368
+ ax.plot(times, [1, 1, 1, 1], 'bo-', markersize=10)
369
+ for i, (event, t) in enumerate(zip(events, times)):
370
+ ax.text(t, 1.1, event, ha='center', fontsize=10)
371
+
372
+ ax.set_ylim(0.5, 1.5)
373
+ ax.set_xlim(-0.5, 3.5)
374
+ ax.set_title(f'Timeline: {scenario_name}')
375
+ ax.axis('off')
376
+
377
+ buf = io.BytesIO()
378
+ plt.savefig(buf, format='png', bbox_inches='tight')
379
+ plt.close(fig)
380
+ buf.seek(0)
381
+
382
+ return f"data:image/png;base64,{base64.b64encode(buf.read()).decode()}"
383
 
384
+ # Use Plotly if available
385
+ fig = go.Figure()
 
 
 
 
 
 
 
 
 
 
 
 
386
 
387
+ events = [
388
+ {"time": "T-5m", "event": "Detection", "type": "detection"},
389
+ {"time": "T-3m", "event": "OSS Analysis", "type": "analysis"},
390
+ {"time": "T-2m", "event": "Enterprise Action", "type": "action"},
391
+ {"time": "T-0m", "event": "Recovery", "type": "recovery"}
392
+ ]
393
 
394
+ for event in events:
395
+ fig.add_trace(go.Scatter(
396
+ x=[event["time"]],
397
+ y=[1],
398
+ mode='markers+text',
399
+ marker=dict(size=20, color='#4ECDC4'),
400
+ text=[event["event"]],
401
+ textposition="top center"
402
+ ))
403
+
404
+ fig.update_layout(
405
+ title=f"Timeline: {scenario_name}",
406
+ height=300,
407
+ showlegend=False,
408
+ yaxis=dict(showticklabels=False, range=[0.5, 1.5]),
409
+ margin=dict(l=20, r=20, t=40, b=20)
410
+ )
411
 
412
+ return fig
 
 
 
 
 
 
 
 
 
 
413
 
414
+ @staticmethod
415
+ def create_dashboard_plot():
416
+ """Create simple dashboard plot"""
417
+ if not PLOTLY_AVAILABLE:
418
+ return None
419
+
420
+ fig = make_subplots(rows=1, cols=2, subplot_titles=('Cost Savings', 'MTTR Improvement'))
421
+
422
+ # Cost savings
423
+ fig.add_trace(
424
+ go.Bar(x=['Without ARF', 'With ARF'], y=[100, 25], name='Cost'),
425
+ row=1, col=1
426
+ )
427
+
428
+ # MTTR improvement
429
+ fig.add_trace(
430
+ go.Bar(x=['Manual', 'ARF OSS', 'ARF Enterprise'], y=[120, 25, 8], name='MTTR'),
431
+ row=1, col=2
432
+ )
433
+
434
+ fig.update_layout(height=400, showlegend=False)
435
+ return fig
436
+
437
+ # ===========================================
438
+ # AUDIT TRAIL MANAGER
439
+ # ===========================================
440
+ class AuditTrailManager:
441
+ def __init__(self):
442
+ self.executions = []
443
+ self.incidents = []
444
+
445
+ def add_execution(self, scenario_name, mode, success=True, savings=0):
446
+ entry = {
447
+ "id": f"exec_{len(self.executions):03d}",
448
+ "time": datetime.datetime.now().strftime("%H:%M"),
449
+ "scenario": scenario_name,
450
+ "mode": mode,
451
+ "status": "βœ… Success" if success else "❌ Failed",
452
  "savings": f"${savings:,}",
453
+ "details": f"{mode} execution"
 
 
454
  }
455
+ self.executions.insert(0, entry)
 
 
 
 
 
 
 
 
 
 
 
456
  return entry
457
 
458
+ def add_incident(self, scenario_name, severity="HIGH"):
459
  entry = {
460
+ "id": f"inc_{len(self.incidents):03d}",
461
+ "time": datetime.datetime.now().strftime("%H:%M"),
462
+ "scenario": scenario_name,
463
+ "severity": severity,
464
+ "component": ENHANCED_SCENARIOS.get(scenario_name, {}).get("component", "unknown"),
465
+ "status": "Analyzed"
 
466
  }
467
+ self.incidents.insert(0, entry)
468
  return entry
469
 
470
+ def get_execution_table(self):
471
  return [
472
+ [e["time"], e["scenario"], e["mode"], e["status"], e["savings"], e["details"]]
473
+ for e in self.executions[:10]
 
474
  ]
475
 
476
+ def get_incident_table(self):
477
  return [
478
+ [e["time"], e["component"], e["scenario"], e["severity"], e["status"]]
479
+ for e in self.incidents[:15]
 
480
  ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
481
 
482
  # ===========================================
483
+ # CREATE DEMO INTERFACE - FIXED VERSION
484
  # ===========================================
485
  def create_demo_interface():
486
+ """Create the demo interface with all fixes applied"""
487
 
 
488
  import gradio as gr
489
 
490
  # Initialize components
491
+ viz_engine = SimpleVizEngine()
492
  audit_manager = AuditTrailManager()
493
 
494
+ # Initialize orchestrator if available
495
+ orchestrator = None
496
+ if DemoOrchestrator:
497
+ try:
498
+ orchestrator = DemoOrchestrator()
499
+ except:
500
+ pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
501
 
502
+ # Custom CSS for OSS vs Enterprise separation
503
  custom_css = """
504
+ .oss-section {
505
+ background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%) !important;
506
+ border-left: 4px solid #2196f3 !important;
507
+ padding: 15px !important;
508
+ border-radius: 8px !important;
509
+ margin-bottom: 15px !important;
 
 
 
 
 
 
 
510
  }
511
+ .enterprise-section {
512
+ background: linear-gradient(135deg, #e8f5e8 0%, #c8e6c9 100%) !important;
513
+ border-left: 4px solid #4caf50 !important;
514
+ padding: 15px !important;
515
+ border-radius: 8px !important;
 
 
 
 
516
  margin-bottom: 15px !important;
517
  }
518
+ .critical { color: #d32f2f !important; font-weight: bold; }
519
+ .success { color: #388e3c !important; font-weight: bold; }
520
  """
521
 
522
+ with gr.Blocks(title="πŸš€ ARF Investor Demo v3.8.0", css=custom_css) as demo:
 
 
 
 
 
 
 
523
 
524
+ # Use your modular header
525
+ create_header("3.3.6", False) # OSS version, Mock mode
526
 
527
+ # Status bar
528
  create_status_bar()
529
 
530
+ # Tabs
531
  with gr.Tabs():
532
 
533
+ # TAB 1: Live Incident Demo (Fixed)
534
  with gr.TabItem("πŸ”₯ Live Incident Demo"):
535
+ # Get components from your UI module
536
  (scenario_dropdown, scenario_description, metrics_display, impact_display,
537
  timeline_output, oss_btn, enterprise_btn, approval_toggle, demo_btn,
538
  approval_display, config_display, results_display) = create_tab1_incident_demo(
539
+ ENHANCED_SCENARIOS, "Cache Miss Storm"
540
  )
541
+
542
+ # Add OSS and Enterprise results displays
543
+ with gr.Row():
544
+ with gr.Column():
545
+ gr.Markdown("### πŸ“‹ OSS Analysis Results (Advisory Only)")
546
+ oss_results = gr.JSON(
547
+ value={},
548
+ label=""
549
+ )
550
+
551
+ with gr.Column():
552
+ gr.Markdown("### 🎯 Enterprise Execution Results")
553
+ enterprise_results = gr.JSON(
554
+ value={},
555
+ label=""
556
+ )
557
 
558
+ # TAB 2: Business Impact & ROI
559
  with gr.TabItem("πŸ’° Business Impact & ROI"):
560
  (dashboard_output, monthly_slider, impact_slider, team_slider,
561
  calculate_btn, roi_output) = create_tab2_business_roi()
562
 
563
+ # TAB 3: Audit Trail
564
  with gr.TabItem("πŸ“œ Audit Trail & History"):
565
  (refresh_btn, clear_btn, export_btn, execution_table, savings_chart,
566
  incident_table, memory_graph, export_text) = create_tab3_audit_trail()
567
 
568
+ # Other tabs...
569
  with gr.TabItem("🏒 Enterprise Features"):
570
+ create_tab4_enterprise_features()
 
571
 
 
572
  with gr.TabItem("🧠 Learning Engine"):
573
+ create_tab5_learning_engine()
 
 
574
 
575
+ # Footer
576
  create_footer()
577
 
578
+ # ============ EVENT HANDLERS (FIXED) ============
579
 
580
+ # Update scenario (FIXED: Proper parameter handling)
581
  def update_scenario(scenario_name):
582
+ scenario = ENHANCED_SCENARIOS.get(scenario_name, {})
583
+
584
+ # Get timeline plot
585
+ if PLOTLY_AVAILABLE:
586
+ timeline = viz_engine.create_timeline_plot(scenario_name)
587
+ else:
588
+ timeline = None
589
+
590
  return (
591
  f"### {scenario_name}\n{scenario.get('description', 'No description')}",
592
  scenario.get("metrics", {}),
593
  scenario.get("impact", {}),
594
+ timeline if timeline else gr.Plot(visible=False),
595
+ {}, # Clear OSS results
596
+ {} # Clear Enterprise results
597
  )
598
 
599
  scenario_dropdown.change(
600
  fn=update_scenario,
601
  inputs=[scenario_dropdown],
602
+ outputs=[scenario_description, metrics_display, impact_display,
603
+ timeline_output, oss_results, enterprise_results]
604
  )
605
 
606
+ # Run OSS Analysis (FIXED: Proper async handling)
607
  async def run_oss_analysis(scenario_name):
608
+ scenario = ENHANCED_SCENARIOS.get(scenario_name, {})
 
609
 
610
  # Add to audit trail
611
+ audit_manager.add_incident(scenario_name, scenario.get("severity", "HIGH"))
612
+
613
+ # Get OSS results
614
+ oss_result = scenario.get("oss_results", {})
615
 
616
  # Update tables
617
+ incident_table_data = audit_manager.get_incident_table()
618
 
619
+ return oss_result, incident_table_data
620
 
621
  oss_btn.click(
622
  fn=run_oss_analysis,
623
  inputs=[scenario_dropdown],
624
+ outputs=[oss_results, incident_table]
625
  )
626
 
627
+ # Execute Enterprise Healing (FIXED: Proper parameter matching)
628
+ def execute_enterprise_healing(scenario_name, approval_required):
629
+ scenario = ENHANCED_SCENARIOS.get(scenario_name, {})
630
 
631
+ # Get enterprise results
632
+ enterprise_result = scenario.get("enterprise_results", {})
 
 
 
 
 
633
 
634
+ # Determine mode
635
+ mode = "Approval" if approval_required else "Autonomous"
636
+
637
+ # Calculate savings from impact
638
+ impact = scenario.get("impact", {})
639
+ revenue_loss = impact.get("Revenue Loss", "$0")
640
+ try:
641
+ savings = int(revenue_loss.replace("$", "").replace(",", "").split("/")[0]) * 0.85
642
+ except:
643
+ savings = 5000
644
 
645
  # Add to audit trail
646
  audit_manager.add_execution(
647
  scenario_name,
648
+ mode,
649
+ savings=int(savings)
 
 
650
  )
651
 
652
+ # Create approval display
653
  if approval_required:
654
+ approval_html = f"""
655
+ <div class='enterprise-section'>
656
+ <h4>βœ… Approved & Executed</h4>
657
+ <p>Action for <strong>{scenario_name}</strong> was approved by system administrator and executed successfully.</p>
658
+ <p><strong>Mode:</strong> Manual Approval</p>
659
+ <p><strong>Cost Saved:</strong> ${int(savings):,}</p>
 
 
 
 
 
660
  </div>
661
  """
662
  else:
663
+ approval_html = f"""
664
+ <div class='enterprise-section'>
665
+ <h4>⚑ Auto-Executed</h4>
666
+ <p>Action for <strong>{scenario_name}</strong> was executed autonomously by ARF Enterprise.</p>
667
+ <p><strong>Mode:</strong> Fully Autonomous</p>
668
+ <p><strong>Cost Saved:</strong> ${int(savings):,}</p>
 
 
 
 
 
669
  </div>
670
  """
671
 
672
  # Update execution table
673
+ execution_table_data = audit_manager.get_execution_table()
674
 
675
+ return approval_html, enterprise_result, execution_table_data
676
 
677
  enterprise_btn.click(
678
+ fn=execute_enterprise_healing,
679
  inputs=[scenario_dropdown, approval_toggle],
680
+ outputs=[approval_display, enterprise_results, execution_table]
681
  )
682
 
683
+ # Quick Demo (FIXED: Proper async)
684
  async def run_quick_demo():
685
  # Run OSS analysis
686
+ scenario = ENHANCED_SCENARIOS["Cache Miss Storm"]
687
+ oss_result = scenario.get("oss_results", {})
688
 
689
+ # Execute enterprise
690
+ enterprise_result = scenario.get("enterprise_results", {})
 
 
 
 
691
 
692
  # Update audit trail
693
+ audit_manager.add_incident("Cache Miss Storm", "CRITICAL")
694
+ audit_manager.add_execution("Cache Miss Storm", "Autonomous", savings=7200)
 
 
 
 
 
 
695
 
696
+ # Get table data
697
+ execution_table_data = audit_manager.get_execution_table()
698
+ incident_table_data = audit_manager.get_incident_table()
699
 
700
+ # Create approval display
701
  approval_html = """
702
+ <div class='enterprise-section'>
703
+ <h4>⚑ Quick Demo Completed</h4>
704
+ <p>Full OSS analysis β†’ Enterprise execution completed successfully.</p>
705
+ <p><strong>Mode:</strong> Autonomous</p>
706
+ <p><strong>Cost Saved:</strong> $7,200</p>
 
 
 
 
 
707
  </div>
708
  """
709
 
710
  return (
711
+ oss_result,
712
  approval_html,
713
+ enterprise_result,
714
  execution_table_data,
715
  incident_table_data,
716
  gr.Checkbox.update(value=False)
 
719
  demo_btn.click(
720
  fn=run_quick_demo,
721
  outputs=[
722
+ oss_results,
723
  approval_display,
724
+ enterprise_results,
725
  execution_table,
726
  incident_table,
727
  approval_toggle
728
  ]
729
  )
730
 
731
+ # ROI Calculator (FIXED)
732
  def calculate_roi(monthly, impact, team):
733
+ if orchestrator:
734
+ company_data = {
735
+ "monthly_incidents": monthly,
736
+ "avg_cost_per_incident": impact,
737
+ "team_size": team
738
+ }
739
+ roi_result = orchestrator.calculate_roi(company_data)
740
+ else:
741
+ # Simple calculation
742
+ annual = monthly * 12 * impact
743
+ savings = annual * 0.82
744
+ team_cost = team * 150000
745
+ roi_multiplier = savings / team_cost if team_cost > 0 else 0
746
+
747
+ roi_result = {
748
+ "annual_impact": annual,
749
+ "team_cost": team_cost,
750
+ "potential_savings": savings,
751
+ "roi_multiplier": roi_multiplier,
752
+ "payback_months": (team_cost / (savings / 12)) if savings > 0 else 0
753
+ }
754
 
755
  # Format for display
756
+ formatted = {
757
+ "Annual Impact": f"${roi_result.get('annual_impact', 0):,.0f}",
758
+ "Team Cost": f"${roi_result.get('team_cost', 0):,.0f}",
759
+ "Potential Savings": f"${roi_result.get('potential_savings', 0):,.0f}",
760
+ "ROI Multiplier": f"{roi_result.get('roi_multiplier', 0):.1f}Γ—",
761
+ "Payback Period": f"{roi_result.get('payback_months', 0):.1f} months"
 
762
  }
763
 
764
+ # Add dashboard
765
+ dashboard = viz_engine.create_dashboard_plot()
766
 
767
+ return formatted, dashboard
768
 
769
  calculate_btn.click(
770
  fn=calculate_roi,
 
772
  outputs=[roi_output, dashboard_output]
773
  )
774
 
775
+ # Audit Trail Refresh (FIXED)
776
  def refresh_audit_trail():
777
+ return audit_manager.get_execution_table(), audit_manager.get_incident_table()
 
 
 
778
 
779
  refresh_btn.click(
780
  fn=refresh_audit_trail,
781
+ outputs=[execution_table, incident_table]
782
  )
783
 
784
+ # Clear History (FIXED)
785
  def clear_audit_trail():
786
+ audit_manager.executions = []
787
+ audit_manager.incidents = []
788
+ return audit_manager.get_execution_table(), audit_manager.get_incident_table()
 
789
 
790
  clear_btn.click(
791
  fn=clear_audit_trail,
792
+ outputs=[execution_table, incident_table]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
793
  )
794
 
795
+ # Initialize with first scenario
796
  demo.load(
797
+ fn=lambda: update_scenario("Cache Miss Storm"),
798
+ outputs=[scenario_description, metrics_display, impact_display,
799
+ timeline_output, oss_results, enterprise_results]
800
  )
801
 
802
  return demo
803
 
804
  # ===========================================
805
+ # MAIN EXECUTION
806
  # ===========================================
807
  def main():
808
+ """Main entry point"""
809
  print("πŸš€ Starting ARF Ultimate Investor Demo v3.8.0...")
810
  print("=" * 70)
811
  print("πŸ“Š Features:")
812
+ print(" β€’ 4 Enhanced Incident Scenarios")
813
+ print(" β€’ Clear OSS vs Enterprise Separation")
814
+ print(" β€’ Fixed Visualization Engine")
815
+ print(" β€’ Working Event Handlers")
 
 
816
  print("=" * 70)
 
 
817
  print("🌐 Opening web interface...")
818
 
 
819
  demo = create_demo_interface()
820
+ demo.launch(
821
+ server_name="0.0.0.0",
822
+ server_port=7860,
823
+ share=False
824
+ )
 
 
 
 
 
 
825
 
 
 
 
826
  if __name__ == "__main__":
827
  main()