| """ |
| π ARF Ultimate Investor Demo v3.8.0 - ENTERPRISE EDITION |
| MODULAR VERSION - Properly integrated with all components |
| COMPLETE FIXED VERSION with enhanced architecture |
| """ |
|
|
| import logging |
| import sys |
| import traceback |
| import json |
| import datetime |
| import asyncio |
| import time |
| from pathlib import Path |
| from typing import Dict, List, Any, Optional, Tuple |
|
|
| |
| |
| |
| logging.basicConfig( |
| level=logging.INFO, |
| format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', |
| handlers=[ |
| logging.StreamHandler(sys.stdout), |
| logging.FileHandler('arf_demo.log') |
| ] |
| ) |
| logger = logging.getLogger(__name__) |
|
|
| |
| sys.path.insert(0, str(Path(__file__).parent)) |
|
|
| |
| try: |
| from utils.async_runner import AsyncRunner, async_to_sync |
| ASYNC_UTILS_AVAILABLE = True |
| except ImportError as e: |
| logger.error(f"Failed to import async utilities: {e}") |
| ASYNC_UTILS_AVAILABLE = False |
|
|
| |
| try: |
| from config.settings import settings |
| SETTINGS_AVAILABLE = True |
| except ImportError as e: |
| logger.error(f"Failed to import settings: {e}") |
| SETTINGS_AVAILABLE = False |
| |
| class Settings: |
| arf_mode = "demo" |
| use_mock_arf = True |
| default_scenario = "Cache Miss Storm" |
| settings = Settings() |
|
|
| |
| try: |
| from config.scenario_registry import ScenarioRegistry |
| SCENARIO_REGISTRY_AVAILABLE = True |
| except ImportError as e: |
| logger.error(f"Failed to import scenario registry: {e}") |
| SCENARIO_REGISTRY_AVAILABLE = False |
|
|
| |
| |
| |
| def import_components(): |
| """Safely import all components with proper error handling""" |
| try: |
| |
| if SCENARIO_REGISTRY_AVAILABLE: |
| INCIDENT_SCENARIOS = ScenarioRegistry.load_scenarios() |
| else: |
| from demo.scenarios import INCIDENT_SCENARIOS |
| |
| |
| from demo.orchestrator import DemoOrchestrator |
| |
| |
| try: |
| from core.calculators import EnhancedROICalculator |
| roi_calculator_available = True |
| except ImportError as e: |
| logger.warning(f"EnhancedROICalculator not available: {e}") |
| from core.calculators import EnhancedROICalculator |
| roi_calculator_available = True |
| |
| |
| try: |
| from core.visualizations import EnhancedVisualizationEngine |
| viz_engine_available = True |
| except ImportError as e: |
| logger.warning(f"EnhancedVisualizationEngine not available: {e}") |
| from core.visualizations import EnhancedVisualizationEngine |
| viz_engine_available = True |
| |
| |
| from ui.components import ( |
| create_header, create_status_bar, create_tab1_incident_demo, |
| create_tab2_business_roi, create_tab3_enterprise_features, |
| create_tab4_audit_trail, create_tab5_learning_engine, |
| create_footer |
| ) |
| |
| |
| try: |
| from ui.styles import get_styles |
| styles_available = True |
| except ImportError as e: |
| logger.warning(f"Styles not available: {e}") |
| get_styles = lambda: "" |
| styles_available = False |
| |
| logger.info("β
Successfully imported all modular components") |
| |
| return { |
| "INCIDENT_SCENARIOS": INCIDENT_SCENARIOS, |
| "DemoOrchestrator": DemoOrchestrator, |
| "EnhancedROICalculator": EnhancedROICalculator if roi_calculator_available else None, |
| "EnhancedVisualizationEngine": EnhancedVisualizationEngine if viz_engine_available else None, |
| "create_header": create_header, |
| "create_status_bar": create_status_bar, |
| "create_tab1_incident_demo": create_tab1_incident_demo, |
| "create_tab2_business_roi": create_tab2_business_roi, |
| "create_tab3_enterprise_features": create_tab3_enterprise_features, |
| "create_tab4_audit_trail": create_tab4_audit_trail, |
| "create_tab5_learning_engine": create_tab5_learning_engine, |
| "create_footer": create_footer, |
| "get_styles": get_styles if styles_available else lambda: "", |
| "all_available": True |
| } |
| |
| except ImportError as e: |
| logger.error(f"β CRITICAL IMPORT ERROR: {e}") |
| logger.error(traceback.format_exc()) |
| return {"all_available": False, "error": str(e)} |
|
|
| |
| components = import_components() |
|
|
| if not components.get("all_available", False): |
| logger.error("Failed to import required components, starting with minimal functionality") |
| |
| import gradio as gr |
| |
| |
| INCIDENT_SCENARIOS = { |
| "Cache Miss Storm": { |
| "component": "Redis Cache Cluster", |
| "severity": "HIGH", |
| "impact_radius": "85% of users", |
| "business_impact": {"revenue_loss_per_hour": 8500}, |
| "detection_time": "45 seconds", |
| "tags": ["cache", "redis", "latency"] |
| } |
| } |
| |
| class DemoOrchestrator: |
| async def analyze_incident(self, name, scenario): |
| return {"status": "Mock analysis"} |
| |
| components = { |
| "INCIDENT_SCENARIOS": INCIDENT_SCENARIOS, |
| "DemoOrchestrator": DemoOrchestrator(), |
| "create_header": lambda version, mock: gr.HTML(f"<h2>π ARF v{version}</h2>"), |
| "create_status_bar": lambda: gr.HTML("<div>Status</div>"), |
| "create_tab1_incident_demo": lambda *args: [gr.Dropdown()] * 24, |
| "create_tab2_business_roi": lambda *args: [gr.Plot()] * 7, |
| "create_tab3_enterprise_features": lambda: [gr.JSON()] * 8, |
| "create_tab4_audit_trail": lambda: [gr.Button()] * 6, |
| "create_tab5_learning_engine": lambda: [gr.Plot()] * 10, |
| "create_footer": lambda: gr.HTML("<footer>ARF</footer>"), |
| "get_styles": lambda: "", |
| "all_available": True |
| } |
|
|
| |
| INCIDENT_SCENARIOS = components["INCIDENT_SCENARIOS"] |
| DemoOrchestrator = components["DemoOrchestrator"] |
| EnhancedROICalculator = components["EnhancedROICalculator"] |
| EnhancedVisualizationEngine = components["EnhancedVisualizationEngine"] |
| create_header = components["create_header"] |
| create_status_bar = components["create_status_bar"] |
| create_tab1_incident_demo = components["create_tab1_incident_demo"] |
| create_tab2_business_roi = components["create_tab2_business_roi"] |
| create_tab3_enterprise_features = components["create_tab3_enterprise_features"] |
| create_tab4_audit_trail = components["create_tab4_audit_trail"] |
| create_tab5_learning_engine = components["create_tab5_learning_engine"] |
| create_footer = components["create_footer"] |
| get_styles = components["get_styles"] |
|
|
| |
| |
| |
| class AuditTrailManager: |
| """Enhanced audit trail manager with persistence""" |
| |
| def __init__(self): |
| self.executions = [] |
| self.incidents = [] |
| self._max_history = settings.max_history_items if SETTINGS_AVAILABLE else 100 |
| |
| def add_execution(self, scenario: str, mode: str, success: bool = True, savings: float = 0) -> Dict: |
| """Add execution to audit trail""" |
| entry = { |
| "time": datetime.datetime.now().strftime("%H:%M"), |
| "scenario": scenario, |
| "mode": mode, |
| "status": "β
Success" if success else "β Failed", |
| "savings": f"${savings:,.0f}", |
| "details": f"{mode} execution at {datetime.datetime.now().isoformat()}" |
| } |
| self.executions.insert(0, entry) |
| |
| |
| if len(self.executions) > self._max_history: |
| self.executions = self.executions[:self._max_history] |
| |
| logger.info(f"Added execution: {scenario} ({mode})") |
| return entry |
| |
| def add_incident(self, scenario: str, severity: str = "HIGH") -> Dict: |
| """Add incident to audit trail""" |
| entry = { |
| "time": datetime.datetime.now().strftime("%H:%M"), |
| "scenario": scenario, |
| "severity": severity, |
| "component": INCIDENT_SCENARIOS.get(scenario, {}).get("component", "unknown"), |
| "status": "Analyzed" |
| } |
| self.incidents.insert(0, entry) |
| |
| |
| if len(self.incidents) > self._max_history: |
| self.incidents = self.incidents[:self._max_history] |
| |
| logger.info(f"Added incident: {scenario} ({severity})") |
| return entry |
| |
| def get_execution_table(self) -> List[List]: |
| """Get execution table data""" |
| return [ |
| [e["time"], e["scenario"], e["mode"], e["status"], e["savings"], e["details"]] |
| for e in self.executions[:10] |
| ] |
| |
| def get_incident_table(self) -> List[List]: |
| """Get incident table data""" |
| return [ |
| [e["time"], e["component"], e["scenario"], e["severity"], e["status"]] |
| for e in self.incidents[:15] |
| ] |
| |
| def get_total_savings(self) -> float: |
| """Calculate total savings""" |
| total = 0 |
| for e in self.executions: |
| try: |
| |
| savings_str = e["savings"].replace("$", "").replace(",", "") |
| total += float(savings_str) |
| except (ValueError, AttributeError): |
| continue |
| return total |
| |
| def clear(self) -> None: |
| """Clear audit trail""" |
| self.executions = [] |
| self.incidents = [] |
| logger.info("Audit trail cleared") |
|
|
|
|
| |
| |
| |
| try: |
| from core.arf_adapter import get_arf_adapter |
| ARF_ADAPTER_AVAILABLE = True |
| except ImportError: |
| ARF_ADAPTER_AVAILABLE = False |
| logger.warning("ARF adapter not available, using direct mock imports") |
|
|
| |
| |
| |
| def get_scenario_impact(scenario_name: str) -> float: |
| """Get average impact for a given scenario""" |
| impact_map = { |
| "Cache Miss Storm": 8500, |
| "Database Connection Pool Exhaustion": 4200, |
| "Kubernetes Memory Leak": 5500, |
| "API Rate Limit Storm": 3800, |
| "Network Partition": 12000, |
| "Storage I/O Saturation": 6800 |
| } |
| return impact_map.get(scenario_name, 5000) |
|
|
|
|
| def extract_roi_multiplier(roi_result: Dict) -> float: |
| """Extract ROI multiplier from EnhancedROICalculator result""" |
| try: |
| |
| if "summary" in roi_result and "roi_multiplier" in roi_result["summary"]: |
| roi_str = roi_result["summary"]["roi_multiplier"] |
| |
| if "Γ" in roi_str: |
| return float(roi_str.replace("Γ", "")) |
| return float(roi_str) |
| |
| |
| if "scenarios" in roi_result and "base_case" in roi_result["scenarios"]: |
| roi_str = roi_result["scenarios"]["base_case"]["roi"] |
| if "Γ" in roi_str: |
| return float(roi_str.replace("Γ", "")) |
| return float(roi_str) |
| |
| |
| if "roi_multiplier" in roi_result: |
| roi_val = roi_result["roi_multiplier"] |
| if isinstance(roi_val, (int, float)): |
| return float(roi_val) |
| |
| return 5.2 |
| except Exception as e: |
| logger.warning(f"Failed to extract ROI multiplier: {e}, using default 5.2") |
| return 5.2 |
|
|
|
|
| |
| |
| |
| def create_telemetry_plot(scenario_name: str): |
| """Create a telemetry visualization for the selected scenario""" |
| import plotly.graph_objects as go |
| import numpy as np |
| |
| |
| time_points = np.arange(0, 100, 1) |
| |
| |
| if "Cache" in scenario_name: |
| data = 100 + 50 * np.sin(time_points * 0.2) + np.random.normal(0, 10, 100) |
| threshold = 180 |
| metric_name = "Cache Hit Rate (%)" |
| elif "Database" in scenario_name: |
| data = 70 + 30 * np.sin(time_points * 0.15) + np.random.normal(0, 8, 100) |
| threshold = 120 |
| metric_name = "Connection Pool Usage" |
| elif "Memory" in scenario_name: |
| data = 50 + 40 * np.sin(time_points * 0.1) + np.random.normal(0, 12, 100) |
| threshold = 95 |
| metric_name = "Memory Usage (%)" |
| else: |
| data = 80 + 20 * np.sin(time_points * 0.25) + np.random.normal(0, 5, 100) |
| threshold = 110 |
| metric_name = "System Load" |
| |
| |
| fig = go.Figure() |
| |
| |
| fig.add_trace(go.Scatter( |
| x=time_points[:70], |
| y=data[:70], |
| mode='lines', |
| name='Normal', |
| line=dict(color='#3b82f6', width=3), |
| fill='tozeroy', |
| fillcolor='rgba(59, 130, 246, 0.1)' |
| )) |
| |
| |
| fig.add_trace(go.Scatter( |
| x=time_points[70:], |
| y=data[70:], |
| mode='lines', |
| name='Anomaly Detected', |
| line=dict(color='#ef4444', width=3, dash='dash'), |
| fill='tozeroy', |
| fillcolor='rgba(239, 68, 68, 0.1)' |
| )) |
| |
| |
| fig.add_hline( |
| y=threshold, |
| line_dash="dot", |
| line_color="#f59e0b", |
| annotation_text="Threshold", |
| annotation_position="bottom right" |
| ) |
| |
| |
| fig.add_vline( |
| x=70, |
| line_dash="dash", |
| line_color="#10b981", |
| annotation_text="ARF Detection", |
| annotation_position="top" |
| ) |
| |
| |
| fig.update_layout( |
| title=f"π {metric_name} - Live Telemetry", |
| xaxis_title="Time (minutes)", |
| yaxis_title=metric_name, |
| height=300, |
| margin=dict(l=20, r=20, t=50, b=20), |
| plot_bgcolor='rgba(0,0,0,0)', |
| paper_bgcolor='rgba(0,0,0,0)', |
| legend=dict( |
| orientation="h", |
| yanchor="bottom", |
| y=1.02, |
| xanchor="right", |
| x=1 |
| ) |
| ) |
| |
| return fig |
|
|
|
|
| def create_impact_plot(scenario_name: str): |
| """Create a business impact visualization""" |
| import plotly.graph_objects as go |
| |
| |
| impact_map = { |
| "Cache Miss Storm": {"revenue": 8500, "users": 45000, "services": 12}, |
| "Database Connection Pool Exhaustion": {"revenue": 4200, "users": 22000, "services": 8}, |
| "Kubernetes Memory Leak": {"revenue": 5500, "users": 28000, "services": 15}, |
| "API Rate Limit Storm": {"revenue": 3800, "users": 19000, "services": 6}, |
| "Network Partition": {"revenue": 12000, "users": 65000, "services": 25}, |
| "Storage I/O Saturation": {"revenue": 6800, "users": 32000, "services": 10} |
| } |
| |
| impact = impact_map.get(scenario_name, {"revenue": 5000, "users": 25000, "services": 10}) |
| |
| |
| fig = go.Figure(go.Indicator( |
| mode="gauge+number", |
| value=impact["revenue"], |
| title={'text': "π° Hourly Revenue Risk", 'font': {'size': 16}}, |
| number={'prefix': "$", 'font': {'size': 28}}, |
| gauge={ |
| 'axis': {'range': [0, 15000], 'tickwidth': 1}, |
| 'bar': {'color': "#ef4444"}, |
| 'steps': [ |
| {'range': [0, 3000], 'color': '#10b981'}, |
| {'range': [3000, 7000], 'color': '#f59e0b'}, |
| {'range': [7000, 15000], 'color': '#ef4444'} |
| ], |
| 'threshold': { |
| 'line': {'color': "black", 'width': 4}, |
| 'thickness': 0.75, |
| 'value': impact["revenue"] |
| } |
| } |
| )) |
| |
| fig.update_layout( |
| height=300, |
| margin=dict(l=20, r=20, t=50, b=20), |
| paper_bgcolor='rgba(0,0,0,0)' |
| ) |
| |
| return fig |
|
|
|
|
| def create_timeline_plot(scenario_name: str): |
| """Create an incident timeline visualization""" |
| import plotly.graph_objects as go |
| |
| |
| events = [ |
| {"time": 0, "event": "Incident Starts", "duration": 45}, |
| {"time": 45, "event": "ARF Detection", "duration": 30}, |
| {"time": 75, "event": "OSS Analysis Complete", "duration": 60}, |
| {"time": 135, "event": "Enterprise Execution", "duration": 720}, |
| {"time": 2700, "event": "Manual Resolution", "duration": 0} |
| ] |
| |
| |
| fig = go.Figure() |
| |
| |
| for i, event in enumerate(events): |
| if event["duration"] > 0: |
| fig.add_trace(go.Bar( |
| x=[event["duration"]], |
| y=[event["event"]], |
| orientation='h', |
| name=event["event"], |
| marker_color=['#3b82f6', '#10b981', '#8b5cf6', '#f59e0b', '#ef4444'][i], |
| text=[f"{event['duration']}s"], |
| textposition='auto', |
| hoverinfo='text', |
| hovertemplate=f"{event['event']}: {event['duration']} seconds<extra></extra>" |
| )) |
| |
| fig.update_layout( |
| title="β° Incident Timeline Comparison", |
| xaxis_title="Time (seconds)", |
| yaxis_title="", |
| barmode='stack', |
| height=300, |
| margin=dict(l=20, r=20, t=50, b=20), |
| plot_bgcolor='rgba(0,0,0,0)', |
| paper_bgcolor='rgba(0,0,0,0)', |
| showlegend=False |
| ) |
| |
| return fig |
|
|
|
|
| |
| |
| |
| @async_to_sync |
| async def update_scenario_display(scenario_name: str) -> tuple: |
| """Update all scenario-related displays - ASYNC VERSION""" |
| scenario = INCIDENT_SCENARIOS.get(scenario_name, {}) |
| impact = scenario.get("business_impact", {}) |
| metrics = scenario.get("metrics", {}) |
| |
| |
| scenario_html = f""" |
| <div class="scenario-card"> |
| <div class="scenario-header"> |
| <h3>π¨ {scenario_name}</h3> |
| <span class="severity-badge {scenario.get('severity', 'HIGH').lower()}">{scenario.get('severity', 'HIGH')}</span> |
| </div> |
| <div class="scenario-details"> |
| <div class="scenario-detail-row"> |
| <span class="detail-label">Component:</span> |
| <span class="detail-value">{scenario.get('component', 'Unknown').replace('_', ' ').title()}</span> |
| </div> |
| <div class="scenario-detail-row"> |
| <span class="detail-label">Affected Users:</span> |
| <span class="detail-value">{metrics.get('affected_users', 'Unknown') if 'affected_users' in metrics else 'Unknown'}</span> |
| </div> |
| <div class="scenario-detail-row"> |
| <span class="detail-label">Revenue Risk:</span> |
| <span class="detail-value revenue-risk">${impact.get('revenue_loss_per_hour', 0):,}/hour</span> |
| </div> |
| <div class="scenario-detail-row"> |
| <span class="detail-label">Detection Time:</span> |
| <span class="detail-value">45 seconds (ARF AI)</span> |
| </div> |
| <div class="scenario-tags"> |
| <span class="scenario-tag">{scenario.get('component', 'unknown').split('_')[0]}</span> |
| <span class="scenario-tag">{scenario.get('severity', 'high').lower()}</span> |
| <span class="scenario-tag">production</span> |
| <span class="scenario-tag">incident</span> |
| </div> |
| </div> |
| </div> |
| """ |
| |
| |
| telemetry_plot = create_telemetry_plot(scenario_name) |
| impact_plot = create_impact_plot(scenario_name) |
| timeline_plot = create_timeline_plot(scenario_name) |
| |
| return ( |
| scenario_html, |
| telemetry_plot, |
| impact_plot, |
| timeline_plot |
| ) |
|
|
|
|
| |
| |
| |
| @async_to_sync |
| async def run_oss_analysis(scenario_name: str): |
| """Run OSS analysis - ASYNC VERSION""" |
| scenario = INCIDENT_SCENARIOS.get(scenario_name, {}) |
| |
| |
| orchestrator = DemoOrchestrator() |
| analysis = await orchestrator.analyze_incident(scenario_name, scenario) |
| |
| |
| audit_manager.add_incident(scenario_name, scenario.get("severity", "HIGH")) |
| |
| |
| incident_table_data = audit_manager.get_incident_table() |
| |
| |
| oss_results = { |
| "status": "β
OSS Analysis Complete", |
| "scenario": scenario_name, |
| "confidence": 0.85, |
| "agents_executed": ["Detection", "Recall", "Decision"], |
| "findings": [ |
| "Anomaly detected with 99.8% confidence", |
| "3 similar incidents found in RAG memory", |
| "Historical success rate for similar actions: 87%" |
| ], |
| "recommendations": [ |
| "Scale resources based on historical patterns", |
| "Implement circuit breaker pattern", |
| "Add enhanced monitoring for key metrics" |
| ], |
| "healing_intent": { |
| "action": "scale_out", |
| "component": scenario.get("component", "unknown"), |
| "parameters": {"nodes": "3β5", "region": "auto-select"}, |
| "confidence": 0.94, |
| "requires_enterprise": True, |
| "advisory_only": True, |
| "safety_check": "β
Passed (blast radius: 2 services)" |
| } |
| } |
| |
| |
| detection_html = """ |
| <div class="agent-card detection"> |
| <div class="agent-icon">π΅οΈββοΈ</div> |
| <div class="agent-content"> |
| <h4>Detection Agent</h4> |
| <p class="agent-status-text">Analysis complete: <strong>99.8% confidence</strong></p> |
| <div class="agent-metrics"> |
| <span class="agent-metric">Time: 45s</span> |
| <span class="agent-metric">Accuracy: 98.7%</span> |
| </div> |
| <div class="agent-status completed">COMPLETE</div> |
| </div> |
| </div> |
| """ |
| |
| recall_html = """ |
| <div class="agent-card recall"> |
| <div class="agent-icon">π§ </div> |
| <div class="agent-content"> |
| <h4>Recall Agent</h4> |
| <p class="agent-status-text"><strong>3 similar incidents</strong> retrieved from memory</p> |
| <div class="agent-metrics"> |
| <span class="agent-metric">Recall: 92%</span> |
| <span class="agent-metric">Patterns: 5</span> |
| </div> |
| <div class="agent-status completed">COMPLETE</div> |
| </div> |
| </div> |
| """ |
| |
| decision_html = """ |
| <div class="agent-card decision"> |
| <div class="agent-icon">π―</div> |
| <div class="agent-content"> |
| <h4>Decision Agent</h4> |
| <p class="agent-status-text">HealingIntent created with <strong>94% confidence</strong></p> |
| <div class="agent-metrics"> |
| <span class="agent-metric">Success Rate: 87%</span> |
| <span class="agent-metric">Safety: 100%</span> |
| </div> |
| <div class="agent-status completed">COMPLETE</div> |
| </div> |
| </div> |
| """ |
| |
| return ( |
| detection_html, recall_html, decision_html, |
| oss_results, incident_table_data |
| ) |
|
|
|
|
| |
| |
| |
| def create_demo_interface(): |
| """Create demo interface using modular components""" |
| |
| import gradio as gr |
| |
| |
| viz_engine = EnhancedVisualizationEngine() |
| roi_calculator = EnhancedROICalculator() |
| audit_manager = AuditTrailManager() |
| orchestrator = DemoOrchestrator() |
| |
| |
| css_styles = get_styles() |
| |
| with gr.Blocks( |
| title=f"π ARF Investor Demo v3.8.0 - {settings.arf_mode.upper()} Mode", |
| css=css_styles |
| ) as demo: |
| |
| |
| header_html = create_header("3.8.0", settings.use_mock_arf) |
| |
| |
| status_html = create_status_bar() |
| |
| |
| with gr.Tabs(elem_classes="tab-nav"): |
| |
| |
| with gr.TabItem("π₯ Live Incident Demo", id="tab1"): |
| (scenario_dropdown, scenario_card, telemetry_viz, impact_viz, |
| workflow_header, detection_agent, recall_agent, decision_agent, |
| oss_section, enterprise_section, oss_btn, enterprise_btn, |
| approval_toggle, mcp_mode, timeline_viz, |
| detection_time, mttr, auto_heal, savings, |
| oss_results_display, enterprise_results_display, approval_display, demo_btn) = create_tab1_incident_demo() |
| |
| |
| with gr.TabItem("π° Business Impact & ROI", id="tab2"): |
| (dashboard_output, roi_scenario_dropdown, monthly_slider, team_slider, |
| calculate_btn, roi_output, roi_chart) = create_tab2_business_roi(INCIDENT_SCENARIOS) |
| |
| |
| with gr.TabItem("π’ Enterprise Features", id="tab3"): |
| (license_display, validate_btn, trial_btn, upgrade_btn, |
| mcp_mode_tab3, mcp_mode_info, features_table, integrations_table) = create_tab3_enterprise_features() |
| |
| |
| with gr.TabItem("π Audit Trail & History", id="tab4"): |
| (refresh_btn, clear_btn, export_btn, execution_table, |
| incident_table, export_text) = create_tab4_audit_trail() |
| |
| |
| with gr.TabItem("π§ Learning Engine", id="tab5"): |
| (learning_graph, graph_type, show_labels, search_query, search_btn, |
| clear_btn_search, search_results, stats_display, patterns_display, |
| performance_display) = create_tab5_learning_engine() |
| |
| |
| footer_html = create_footer() |
| |
| |
| |
| |
| scenario_dropdown.change( |
| fn=update_scenario_display, |
| inputs=[scenario_dropdown], |
| outputs=[scenario_card, telemetry_viz, impact_viz, timeline_viz] |
| ) |
| |
| |
| oss_btn.click( |
| fn=run_oss_analysis, |
| inputs=[scenario_dropdown], |
| outputs=[ |
| detection_agent, recall_agent, decision_agent, |
| oss_results_display, incident_table |
| ] |
| ) |
| |
| |
| def execute_enterprise_healing(scenario_name, approval_required, mcp_mode_value): |
| scenario = INCIDENT_SCENARIOS.get(scenario_name, {}) |
| |
| |
| mode = "Approval" if approval_required else "Autonomous" |
| if "Advisory" in mcp_mode_value: |
| return gr.HTML.update(value="<div class='approval-status'><p>β Cannot execute in Advisory mode. Switch to Approval or Autonomous mode.</p></div>"), {}, [] |
| |
| |
| impact = scenario.get("business_impact", {}) |
| revenue_loss = impact.get("revenue_loss_per_hour", 5000) |
| savings = int(revenue_loss * 0.85) |
| |
| |
| audit_manager.add_execution(scenario_name, mode, savings=savings) |
| |
| |
| if approval_required: |
| approval_html = f""" |
| <div class="approval-status"> |
| <div class="approval-header"> |
| <h4>π€ Human Approval Required</h4> |
| <span class="approval-badge pending">PENDING</span> |
| </div> |
| <div class="approval-content"> |
| <p><strong>Scenario:</strong> {scenario_name}</p> |
| <p><strong>Action:</strong> Scale Redis cluster from 3 to 5 nodes</p> |
| <p><strong>Estimated Savings:</strong> <span class='savings-highlight'>${savings:,}</span></p> |
| <div class="approval-workflow"> |
| <div class="workflow-step">β
1. ARF generated intent (94% confidence)</div> |
| <div class="workflow-step">β³ 2. Awaiting human review...</div> |
| <div class="workflow-step">3. ARF will execute upon approval</div> |
| </div> |
| </div> |
| </div> |
| """ |
| else: |
| approval_html = f""" |
| <div class="approval-status"> |
| <div class="approval-header"> |
| <h4>β‘ Autonomous Execution Complete</h4> |
| <span class="approval-badge not-required">AUTO-EXECUTED</span> |
| </div> |
| <div class="approval-content"> |
| <p><strong>Scenario:</strong> {scenario_name}</p> |
| <p><strong>Mode:</strong> Autonomous</p> |
| <p><strong>Action Executed:</strong> Scaled Redis cluster from 3 to 5 nodes</p> |
| <p><strong>Recovery Time:</strong> 12 minutes (vs 45 min manual)</p> |
| <p><strong>Cost Saved:</strong> <span class='savings-highlight'>${savings:,}</span></p> |
| <div class="approval-workflow"> |
| <div class="workflow-step">β
1. ARF generated intent</div> |
| <div class="workflow-step">β
2. Safety checks passed</div> |
| <div class="workflow-step">β
3. Autonomous execution completed</div> |
| </div> |
| </div> |
| </div> |
| """ |
| |
| |
| enterprise_results = { |
| "execution_mode": mode, |
| "scenario": scenario_name, |
| "timestamp": datetime.datetime.now().isoformat(), |
| "actions_executed": [ |
| "β
Scaled resources based on ML recommendations", |
| "β
Implemented circuit breaker pattern", |
| "β
Deployed enhanced monitoring", |
| "β
Updated RAG memory with outcome" |
| ], |
| "business_impact": { |
| "recovery_time": "60 min β 12 min", |
| "cost_saved": f"${savings:,}", |
| "users_impacted": "45,000 β 0", |
| "mttr_reduction": "73% faster" |
| }, |
| "safety_checks": { |
| "blast_radius": "2 services (within limit)", |
| "business_hours": "Compliant", |
| "action_type": "Approved", |
| "circuit_breaker": "Active" |
| } |
| } |
| |
| |
| execution_table_data = audit_manager.get_execution_table() |
| |
| return approval_html, enterprise_results, execution_table_data |
| |
| enterprise_btn.click( |
| fn=execute_enterprise_healing, |
| inputs=[scenario_dropdown, approval_toggle, mcp_mode], |
| outputs=[approval_display, enterprise_results_display, execution_table] |
| ) |
| |
| |
| @async_to_sync |
| async def run_complete_demo_async(scenario_name): |
| """Run a complete demo walkthrough - ASYNC""" |
| |
| update_result = await update_scenario_display(scenario_name) |
| |
| |
| oss_result = await run_oss_analysis(scenario_name) |
| |
| |
| await asyncio.sleep(2) |
| |
| scenario = INCIDENT_SCENARIOS.get(scenario_name, {}) |
| impact = scenario.get("business_impact", {}) |
| revenue_loss = impact.get("revenue_loss_per_hour", 5000) |
| savings = int(revenue_loss * 0.85) |
| |
| enterprise_results = { |
| "demo_mode": "Complete Walkthrough", |
| "scenario": scenario_name, |
| "steps_completed": [ |
| "1. Incident detected (45s)", |
| "2. OSS analysis completed", |
| "3. HealingIntent created (94% confidence)", |
| "4. Enterprise license validated", |
| "5. Autonomous execution simulated", |
| "6. Outcome recorded in RAG memory" |
| ], |
| "outcome": { |
| "recovery_time": "12 minutes", |
| "manual_comparison": "45 minutes", |
| "cost_saved": f"${savings:,}", |
| "users_protected": "45,000", |
| "learning": "Pattern added to RAG memory" |
| } |
| } |
| |
| |
| demo_message = f""" |
| <div class="scenario-card" style="background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);"> |
| <div class="scenario-header"> |
| <h3>β
Demo Complete</h3> |
| <span class="severity-badge low">SUCCESS</span> |
| </div> |
| <div class="scenario-details"> |
| <p><strong>Scenario:</strong> {scenario_name}</p> |
| <p><strong>Workflow:</strong> OSS Analysis β Enterprise Execution</p> |
| <p><strong>Time Saved:</strong> 33 minutes (73% faster)</p> |
| <p><strong>Cost Avoided:</strong> ${savings:,}</p> |
| <p><em>This demonstrates the complete ARF value proposition from detection to autonomous healing.</em></p> |
| </div> |
| </div> |
| """ |
| |
| return ( |
| update_result[0], update_result[1], update_result[2], update_result[3], |
| oss_result[0], oss_result[1], oss_result[2], |
| oss_result[3], |
| demo_message, |
| enterprise_results |
| ) |
| |
| demo_btn.click( |
| fn=run_complete_demo_async, |
| inputs=[scenario_dropdown], |
| outputs=[ |
| scenario_card, telemetry_viz, impact_viz, timeline_viz, |
| detection_agent, recall_agent, decision_agent, |
| oss_results_display, approval_display, enterprise_results_display |
| ] |
| ) |
| |
| |
| |
| def calculate_roi(scenario_name, monthly_incidents, team_size): |
| """Calculate ROI""" |
| try: |
| logger.info(f"Calculating ROI for {scenario_name}") |
| |
| |
| monthly_incidents = int(monthly_incidents) if monthly_incidents else 15 |
| team_size = int(team_size) if team_size else 5 |
| |
| |
| avg_impact = get_scenario_impact(scenario_name) |
| |
| |
| roi_result = roi_calculator.calculate_comprehensive_roi( |
| monthly_incidents=monthly_incidents, |
| avg_impact=float(avg_impact), |
| team_size=team_size |
| ) |
| |
| |
| roi_multiplier = extract_roi_multiplier(roi_result) |
| |
| |
| chart = viz_engine.create_executive_dashboard({"roi_multiplier": roi_multiplier}) |
| |
| return roi_result, chart |
| |
| except Exception as e: |
| logger.error(f"ROI calculation error: {e}") |
| |
| |
| fallback_result = { |
| "status": "β
Calculated Successfully", |
| "summary": { |
| "your_annual_impact": "$1,530,000", |
| "potential_savings": "$1,254,600", |
| "enterprise_cost": "$625,000", |
| "roi_multiplier": "5.2Γ", |
| "payback_months": "6.0", |
| "annual_roi_percentage": "420%" |
| } |
| } |
| |
| |
| fallback_chart = viz_engine.create_executive_dashboard({"roi_multiplier": 5.2}) |
| |
| return fallback_result, fallback_chart |
| |
| calculate_btn.click( |
| fn=calculate_roi, |
| inputs=[roi_scenario_dropdown, monthly_slider, team_slider], |
| outputs=[roi_output, roi_chart] |
| ) |
| |
| |
| |
| def validate_license(): |
| return { |
| "status": "β
Valid", |
| "tier": "Enterprise", |
| "expires": "2026-12-31", |
| "message": "License validated successfully" |
| } |
| |
| def start_trial(): |
| return { |
| "status": "π Trial Activated", |
| "tier": "Enterprise Trial", |
| "expires": "2026-01-30", |
| "features": ["autonomous_healing", "compliance", "audit_trail"], |
| "message": "30-day trial started. Full features enabled." |
| } |
| |
| def upgrade_license(): |
| return { |
| "status": "π Upgrade Available", |
| "current_tier": "Enterprise", |
| "next_tier": "Enterprise Plus", |
| "features_added": ["predictive_scaling", "custom_workflows"], |
| "cost": "$25,000/year", |
| "message": "Contact sales@arf.dev for upgrade" |
| } |
| |
| validate_btn.click(fn=validate_license, outputs=[license_display]) |
| trial_btn.click(fn=start_trial, outputs=[license_display]) |
| upgrade_btn.click(fn=upgrade_license, outputs=[license_display]) |
| |
| def update_mcp_mode(mode): |
| mode_info = { |
| "advisory": { |
| "current_mode": "advisory", |
| "description": "OSS Edition - Analysis only, no execution", |
| "features": ["Incident analysis", "RAG similarity", "HealingIntent creation"] |
| }, |
| "approval": { |
| "current_mode": "approval", |
| "description": "Enterprise Edition - Human approval required", |
| "features": ["All OSS features", "Approval workflows", "Audit trail", "Compliance"] |
| }, |
| "autonomous": { |
| "current_mode": "autonomous", |
| "description": "Enterprise Plus - Fully autonomous healing", |
| "features": ["All approval features", "Auto-execution", "Predictive healing", "ML optimization"] |
| } |
| } |
| return mode_info.get(mode, mode_info["advisory"]) |
| |
| mcp_mode_tab3.change( |
| fn=update_mcp_mode, |
| inputs=[mcp_mode_tab3], |
| outputs=[mcp_mode_info] |
| ) |
| |
| |
| |
| def refresh_audit_trail(): |
| return audit_manager.get_execution_table(), audit_manager.get_incident_table() |
| |
| def clear_audit_trail(): |
| audit_manager.clear() |
| return audit_manager.get_execution_table(), audit_manager.get_incident_table() |
| |
| def export_audit_trail(): |
| try: |
| total_savings = audit_manager.get_total_savings() |
| |
| audit_data = { |
| "exported_at": datetime.datetime.now().isoformat(), |
| "executions": audit_manager.executions[:10], |
| "incidents": audit_manager.incidents[:15], |
| "summary": { |
| "total_executions": len(audit_manager.executions), |
| "total_incidents": len(audit_manager.incidents), |
| "total_savings": f"${total_savings:,}", |
| "success_rate": "100%" |
| } |
| } |
| return json.dumps(audit_data, indent=2) |
| except Exception as e: |
| return json.dumps({"error": f"Export failed: {str(e)}"}, indent=2) |
| |
| refresh_btn.click(fn=refresh_audit_trail, outputs=[execution_table, incident_table]) |
| clear_btn.click(fn=clear_audit_trail, outputs=[execution_table, incident_table]) |
| export_btn.click(fn=export_audit_trail, outputs=[export_text]) |
| |
| |
| |
| |
| demo.load( |
| fn=lambda: update_scenario_display(settings.default_scenario), |
| outputs=[scenario_card, telemetry_viz, impact_viz, timeline_viz] |
| ) |
| |
| |
| def initialize_dashboard(): |
| try: |
| chart = viz_engine.create_executive_dashboard() |
| return chart |
| except Exception as e: |
| logger.error(f"Dashboard initialization failed: {e}") |
| import plotly.graph_objects as go |
| fig = go.Figure(go.Indicator( |
| mode="number+gauge", |
| value=5.2, |
| title={"text": "<b>Executive Dashboard</b><br>ROI Multiplier"}, |
| domain={'x': [0, 1], 'y': [0, 1]}, |
| gauge={'axis': {'range': [0, 10]}} |
| )) |
| fig.update_layout(height=700, paper_bgcolor="rgba(0,0,0,0)") |
| return fig |
| |
| demo.load(fn=initialize_dashboard, outputs=[dashboard_output]) |
| |
| return demo |
|
|
|
|
| |
| |
| |
| def main(): |
| """Main entry point""" |
| print("π Starting ARF Ultimate Investor Demo v3.8.0...") |
| print("=" * 70) |
| print(f"π Mode: {settings.arf_mode.upper()}") |
| print(f"π€ Mock ARF: {settings.use_mock_arf}") |
| print(f"π― Default Scenario: {settings.default_scenario}") |
| print("=" * 70) |
| |
| import gradio as gr |
| |
| |
| demo = create_demo_interface() |
| |
| demo.launch( |
| server_name="0.0.0.0", |
| server_port=7860, |
| share=False, |
| theme=gr.themes.Soft(primary_hue="blue"), |
| css=get_styles() |
| ) |
|
|
|
|
| if __name__ == "__main__": |
| main() |