Update app.py
Browse files
app.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
"""
|
| 2 |
π ARF Ultimate Investor Demo v3.8.0 - ENTERPRISE EDITION
|
| 3 |
MODULAR VERSION - Properly integrated with all components
|
| 4 |
-
COMPLETE FIXED VERSION with enhanced
|
| 5 |
"""
|
| 6 |
|
| 7 |
import logging
|
|
@@ -11,7 +11,6 @@ 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 |
|
|
@@ -31,14 +30,47 @@ logger = logging.getLogger(__name__)
|
|
| 31 |
# Add parent directory to path
|
| 32 |
sys.path.insert(0, str(Path(__file__).parent))
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
# ===========================================
|
| 35 |
# IMPORT MODULAR COMPONENTS - SAFE IMPORTS
|
| 36 |
# ===========================================
|
| 37 |
def import_components():
|
| 38 |
"""Safely import all components with proper error handling"""
|
| 39 |
try:
|
| 40 |
-
# Import scenarios
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
# Import orchestrator
|
| 44 |
from demo.orchestrator import DemoOrchestrator
|
|
@@ -47,19 +79,19 @@ def import_components():
|
|
| 47 |
try:
|
| 48 |
from core.calculators import EnhancedROICalculator
|
| 49 |
roi_calculator_available = True
|
| 50 |
-
except ImportError:
|
| 51 |
-
logger.warning("EnhancedROICalculator not available
|
| 52 |
-
|
| 53 |
-
roi_calculator_available =
|
| 54 |
|
| 55 |
# Import visualizations
|
| 56 |
try:
|
| 57 |
from core.visualizations import EnhancedVisualizationEngine
|
| 58 |
viz_engine_available = True
|
| 59 |
-
except ImportError:
|
| 60 |
-
logger.warning("EnhancedVisualizationEngine not available
|
| 61 |
-
|
| 62 |
-
viz_engine_available =
|
| 63 |
|
| 64 |
# Import UI components
|
| 65 |
from ui.components import (
|
|
@@ -73,8 +105,8 @@ def import_components():
|
|
| 73 |
try:
|
| 74 |
from ui.styles import get_styles
|
| 75 |
styles_available = True
|
| 76 |
-
except ImportError:
|
| 77 |
-
logger.warning("Styles not available
|
| 78 |
get_styles = lambda: ""
|
| 79 |
styles_available = False
|
| 80 |
|
|
@@ -98,23 +130,19 @@ def import_components():
|
|
| 98 |
}
|
| 99 |
|
| 100 |
except ImportError as e:
|
| 101 |
-
|
| 102 |
-
|
| 103 |
return {"all_available": False, "error": str(e)}
|
| 104 |
|
| 105 |
# Import components safely
|
| 106 |
components = import_components()
|
| 107 |
|
| 108 |
if not components.get("all_available", False):
|
| 109 |
-
|
| 110 |
-
print("β Failed to import required components")
|
| 111 |
-
print("Trying to start with minimal functionality...")
|
| 112 |
-
print("=" * 70)
|
| 113 |
|
| 114 |
-
# Import gradio for mock components
|
| 115 |
import gradio as gr
|
| 116 |
|
| 117 |
-
#
|
| 118 |
INCIDENT_SCENARIOS = {
|
| 119 |
"Cache Miss Storm": {
|
| 120 |
"component": "Redis Cache Cluster",
|
|
@@ -130,158 +158,22 @@ if not components.get("all_available", False):
|
|
| 130 |
async def analyze_incident(self, name, scenario):
|
| 131 |
return {"status": "Mock analysis"}
|
| 132 |
|
| 133 |
-
class MockCalculator:
|
| 134 |
-
def calculate_comprehensive_roi(self, **kwargs):
|
| 135 |
-
return {"roi": "5.2Γ", "status": "Mock calculation"}
|
| 136 |
-
|
| 137 |
-
class MockVisualizationEngine:
|
| 138 |
-
def create_executive_dashboard(self, data=None):
|
| 139 |
-
import plotly.graph_objects as go
|
| 140 |
-
fig = go.Figure(go.Indicator(
|
| 141 |
-
mode="number+gauge",
|
| 142 |
-
value=5.2,
|
| 143 |
-
title={"text": "ROI Multiplier"},
|
| 144 |
-
domain={'x': [0, 1], 'y': [0, 1]},
|
| 145 |
-
gauge={'axis': {'range': [0, 10]}}
|
| 146 |
-
))
|
| 147 |
-
fig.update_layout(height=400)
|
| 148 |
-
return fig
|
| 149 |
-
|
| 150 |
-
def create_telemetry_plot(self, scenario_name):
|
| 151 |
-
import plotly.graph_objects as go
|
| 152 |
-
import numpy as np
|
| 153 |
-
time_points = np.arange(0, 100, 1)
|
| 154 |
-
data = 100 + 50 * np.sin(time_points * 0.2) + np.random.normal(0, 10, 100)
|
| 155 |
-
fig = go.Figure()
|
| 156 |
-
fig.add_trace(go.Scatter(x=time_points, y=data, mode='lines'))
|
| 157 |
-
fig.update_layout(height=300)
|
| 158 |
-
return fig
|
| 159 |
-
|
| 160 |
-
def create_impact_plot(self, scenario_name):
|
| 161 |
-
import plotly.graph_objects as go
|
| 162 |
-
fig = go.Figure(go.Indicator(
|
| 163 |
-
mode="gauge+number",
|
| 164 |
-
value=8500,
|
| 165 |
-
title={'text': "π° Hourly Revenue Risk"},
|
| 166 |
-
number={'prefix': "$"},
|
| 167 |
-
gauge={'axis': {'range': [0, 15000]}}
|
| 168 |
-
))
|
| 169 |
-
fig.update_layout(height=300)
|
| 170 |
-
return fig
|
| 171 |
-
|
| 172 |
-
def create_timeline_plot(self, scenario_name):
|
| 173 |
-
import plotly.graph_objects as go
|
| 174 |
-
fig = go.Figure()
|
| 175 |
-
fig.update_layout(height=300)
|
| 176 |
-
return fig
|
| 177 |
-
|
| 178 |
-
# Mock UI functions
|
| 179 |
-
def create_header(version="3.3.6", mock_mode=True):
|
| 180 |
-
return gr.HTML(f"<h2>π ARF v{version} (MOCK MODE - Import Error)</h2>")
|
| 181 |
-
|
| 182 |
-
def create_status_bar():
|
| 183 |
-
return gr.HTML("β οΈ Running in mock mode due to import errors")
|
| 184 |
-
|
| 185 |
-
def create_tab1_incident_demo(scenarios=INCIDENT_SCENARIOS, default_scenario="Cache Miss Storm"):
|
| 186 |
-
scenario_dropdown = gr.Dropdown(choices=["Cache Miss Storm"], value="Cache Miss Storm", label="Scenario")
|
| 187 |
-
scenario_card = gr.HTML("<p>Mock mode active</p>")
|
| 188 |
-
telemetry_viz = gr.Plot()
|
| 189 |
-
impact_viz = gr.Plot()
|
| 190 |
-
timeline_viz = gr.Plot()
|
| 191 |
-
detection_agent = gr.HTML("<p>Mock agent</p>")
|
| 192 |
-
recall_agent = gr.HTML("<p>Mock agent</p>")
|
| 193 |
-
decision_agent = gr.HTML("<p>Mock agent</p>")
|
| 194 |
-
oss_section = gr.HTML("<p>Mock OSS</p>")
|
| 195 |
-
enterprise_section = gr.HTML("<p>Mock Enterprise</p>")
|
| 196 |
-
oss_btn = gr.Button("Run Mock Analysis")
|
| 197 |
-
enterprise_btn = gr.Button("Mock Execute")
|
| 198 |
-
approval_toggle = gr.CheckboxGroup(choices=["Mock Approval"])
|
| 199 |
-
mcp_mode = gr.Radio(choices=["Mock Mode"])
|
| 200 |
-
detection_time = gr.HTML("<p>Mock metric</p>")
|
| 201 |
-
mttr = gr.HTML("<p>Mock metric</p>")
|
| 202 |
-
auto_heal = gr.HTML("<p>Mock metric</p>")
|
| 203 |
-
savings = gr.HTML("<p>Mock metric</p>")
|
| 204 |
-
oss_results_display = gr.JSON(value={})
|
| 205 |
-
enterprise_results_display = gr.JSON(value={})
|
| 206 |
-
approval_display = gr.HTML("<p>Mock approval</p>")
|
| 207 |
-
demo_btn = gr.Button("Run Mock Demo")
|
| 208 |
-
|
| 209 |
-
return (scenario_dropdown, scenario_card, telemetry_viz, impact_viz,
|
| 210 |
-
None, detection_agent, recall_agent, decision_agent,
|
| 211 |
-
oss_section, enterprise_section, oss_btn, enterprise_btn,
|
| 212 |
-
approval_toggle, mcp_mode, timeline_viz,
|
| 213 |
-
detection_time, mttr, auto_heal, savings,
|
| 214 |
-
oss_results_display, enterprise_results_display, approval_display, demo_btn)
|
| 215 |
-
|
| 216 |
-
# Define other mock UI functions
|
| 217 |
-
def create_tab2_business_roi(scenarios):
|
| 218 |
-
dashboard_output = gr.Plot()
|
| 219 |
-
roi_scenario_dropdown = gr.Dropdown(choices=["Cache Miss Storm"], value="Cache Miss Storm", label="Scenario")
|
| 220 |
-
monthly_slider = gr.Slider(minimum=1, maximum=50, value=15, step=1, label="Monthly Incidents")
|
| 221 |
-
team_slider = gr.Slider(minimum=1, maximum=50, value=5, step=1, label="Team Size")
|
| 222 |
-
calculate_btn = gr.Button("Calculate ROI")
|
| 223 |
-
roi_output = gr.JSON(value={})
|
| 224 |
-
roi_chart = gr.Plot()
|
| 225 |
-
return (dashboard_output, roi_scenario_dropdown, monthly_slider, team_slider,
|
| 226 |
-
calculate_btn, roi_output, roi_chart)
|
| 227 |
-
|
| 228 |
-
def create_tab3_enterprise_features():
|
| 229 |
-
license_display = gr.JSON(value={})
|
| 230 |
-
validate_btn = gr.Button("Validate License")
|
| 231 |
-
trial_btn = gr.Button("Start Trial")
|
| 232 |
-
upgrade_btn = gr.Button("Upgrade")
|
| 233 |
-
mcp_mode = gr.Dropdown(choices=["advisory"], value="advisory", label="MCP Mode")
|
| 234 |
-
mcp_mode_info = gr.JSON(value={})
|
| 235 |
-
features_table = gr.Dataframe(headers=["Feature", "Status", "Edition"], value=[])
|
| 236 |
-
integrations_table = gr.Dataframe(headers=["Integration", "Status", "Type"], value=[])
|
| 237 |
-
return (license_display, validate_btn, trial_btn, upgrade_btn,
|
| 238 |
-
mcp_mode, mcp_mode_info, features_table, integrations_table)
|
| 239 |
-
|
| 240 |
-
def create_tab4_audit_trail():
|
| 241 |
-
refresh_btn = gr.Button("Refresh")
|
| 242 |
-
clear_btn = gr.Button("Clear History")
|
| 243 |
-
export_btn = gr.Button("Export")
|
| 244 |
-
execution_table = gr.Dataframe(headers=["Time", "Scenario", "Mode", "Status", "Savings", "Details"])
|
| 245 |
-
incident_table = gr.Dataframe(headers=["Time", "Component", "Scenario", "Severity", "Status"])
|
| 246 |
-
export_text = gr.JSON(value={})
|
| 247 |
-
return (refresh_btn, clear_btn, export_btn, execution_table, incident_table, export_text)
|
| 248 |
-
|
| 249 |
-
def create_tab5_learning_engine():
|
| 250 |
-
learning_graph = gr.Plot()
|
| 251 |
-
graph_type = gr.Dropdown(choices=["Graph A"], value="Graph A", label="Graph Type")
|
| 252 |
-
show_labels = gr.Checkbox(label="Show Labels", value=True)
|
| 253 |
-
search_query = gr.Textbox(label="Search Patterns")
|
| 254 |
-
search_btn = gr.Button("Search")
|
| 255 |
-
clear_btn_search = gr.Button("Clear Search")
|
| 256 |
-
search_results = gr.JSON(value={})
|
| 257 |
-
stats_display = gr.JSON(value={})
|
| 258 |
-
patterns_display = gr.JSON(value={})
|
| 259 |
-
performance_display = gr.JSON(value={})
|
| 260 |
-
return (learning_graph, graph_type, show_labels, search_query, search_btn,
|
| 261 |
-
clear_btn_search, search_results, stats_display, patterns_display, performance_display)
|
| 262 |
-
|
| 263 |
-
def create_footer():
|
| 264 |
-
return gr.HTML("<p>ARF Mock Mode</p>")
|
| 265 |
-
|
| 266 |
-
# Assign mocked components
|
| 267 |
components = {
|
| 268 |
"INCIDENT_SCENARIOS": INCIDENT_SCENARIOS,
|
| 269 |
"DemoOrchestrator": DemoOrchestrator(),
|
| 270 |
-
"
|
| 271 |
-
"
|
| 272 |
-
"
|
| 273 |
-
"
|
| 274 |
-
"
|
| 275 |
-
"
|
| 276 |
-
"
|
| 277 |
-
"
|
| 278 |
-
"create_tab5_learning_engine": create_tab5_learning_engine,
|
| 279 |
-
"create_footer": create_footer,
|
| 280 |
"get_styles": lambda: "",
|
| 281 |
"all_available": True
|
| 282 |
}
|
| 283 |
|
| 284 |
-
# Extract components
|
| 285 |
INCIDENT_SCENARIOS = components["INCIDENT_SCENARIOS"]
|
| 286 |
DemoOrchestrator = components["DemoOrchestrator"]
|
| 287 |
EnhancedROICalculator = components["EnhancedROICalculator"]
|
|
@@ -297,28 +189,37 @@ create_footer = components["create_footer"]
|
|
| 297 |
get_styles = components["get_styles"]
|
| 298 |
|
| 299 |
# ===========================================
|
| 300 |
-
# AUDIT TRAIL MANAGER
|
| 301 |
# ===========================================
|
| 302 |
class AuditTrailManager:
|
| 303 |
-
"""
|
| 304 |
|
| 305 |
def __init__(self):
|
| 306 |
self.executions = []
|
| 307 |
self.incidents = []
|
|
|
|
| 308 |
|
| 309 |
-
def add_execution(self, scenario, mode, success=True, savings=0):
|
|
|
|
| 310 |
entry = {
|
| 311 |
"time": datetime.datetime.now().strftime("%H:%M"),
|
| 312 |
"scenario": scenario,
|
| 313 |
"mode": mode,
|
| 314 |
"status": "β
Success" if success else "β Failed",
|
| 315 |
-
"savings": f"${savings:,}",
|
| 316 |
-
"details": f"{mode} execution"
|
| 317 |
}
|
| 318 |
self.executions.insert(0, entry)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 319 |
return entry
|
| 320 |
|
| 321 |
-
def add_incident(self, scenario, severity="HIGH"):
|
|
|
|
| 322 |
entry = {
|
| 323 |
"time": datetime.datetime.now().strftime("%H:%M"),
|
| 324 |
"scenario": scenario,
|
|
@@ -327,22 +228,59 @@ class AuditTrailManager:
|
|
| 327 |
"status": "Analyzed"
|
| 328 |
}
|
| 329 |
self.incidents.insert(0, entry)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 330 |
return entry
|
| 331 |
|
| 332 |
-
def get_execution_table(self):
|
|
|
|
| 333 |
return [
|
| 334 |
[e["time"], e["scenario"], e["mode"], e["status"], e["savings"], e["details"]]
|
| 335 |
for e in self.executions[:10]
|
| 336 |
]
|
| 337 |
|
| 338 |
-
def get_incident_table(self):
|
|
|
|
| 339 |
return [
|
| 340 |
[e["time"], e["component"], e["scenario"], e["severity"], e["status"]]
|
| 341 |
for e in self.incidents[:15]
|
| 342 |
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 343 |
|
| 344 |
# ===========================================
|
| 345 |
-
#
|
| 346 |
# ===========================================
|
| 347 |
def get_scenario_impact(scenario_name: str) -> float:
|
| 348 |
"""Get average impact for a given scenario"""
|
|
@@ -356,11 +294,9 @@ def get_scenario_impact(scenario_name: str) -> float:
|
|
| 356 |
}
|
| 357 |
return impact_map.get(scenario_name, 5000)
|
| 358 |
|
| 359 |
-
|
| 360 |
-
# ROI DATA ADAPTER - FIXED VERSION
|
| 361 |
-
# ===========================================
|
| 362 |
def extract_roi_multiplier(roi_result: Dict) -> float:
|
| 363 |
-
"""Extract ROI multiplier from EnhancedROICalculator result
|
| 364 |
try:
|
| 365 |
# Try to get from summary
|
| 366 |
if "summary" in roi_result and "roi_multiplier" in roi_result["summary"]:
|
|
@@ -386,17 +322,18 @@ def extract_roi_multiplier(roi_result: Dict) -> float:
|
|
| 386 |
return 5.2 # Default fallback
|
| 387 |
except Exception as e:
|
| 388 |
logger.warning(f"Failed to extract ROI multiplier: {e}, using default 5.2")
|
| 389 |
-
return 5.2
|
|
|
|
| 390 |
|
| 391 |
# ===========================================
|
| 392 |
-
# VISUALIZATION HELPERS
|
| 393 |
# ===========================================
|
| 394 |
def create_telemetry_plot(scenario_name: str):
|
| 395 |
"""Create a telemetry visualization for the selected scenario"""
|
| 396 |
import plotly.graph_objects as go
|
| 397 |
import numpy as np
|
| 398 |
|
| 399 |
-
# Generate
|
| 400 |
time_points = np.arange(0, 100, 1)
|
| 401 |
|
| 402 |
# Different patterns for different scenarios
|
|
@@ -480,11 +417,12 @@ def create_telemetry_plot(scenario_name: str):
|
|
| 480 |
|
| 481 |
return fig
|
| 482 |
|
|
|
|
| 483 |
def create_impact_plot(scenario_name: str):
|
| 484 |
"""Create a business impact visualization"""
|
| 485 |
import plotly.graph_objects as go
|
| 486 |
|
| 487 |
-
# Get impact data
|
| 488 |
impact_map = {
|
| 489 |
"Cache Miss Storm": {"revenue": 8500, "users": 45000, "services": 12},
|
| 490 |
"Database Connection Pool Exhaustion": {"revenue": 4200, "users": 22000, "services": 8},
|
|
@@ -496,7 +434,7 @@ def create_impact_plot(scenario_name: str):
|
|
| 496 |
|
| 497 |
impact = impact_map.get(scenario_name, {"revenue": 5000, "users": 25000, "services": 10})
|
| 498 |
|
| 499 |
-
# Create gauge
|
| 500 |
fig = go.Figure(go.Indicator(
|
| 501 |
mode="gauge+number",
|
| 502 |
value=impact["revenue"],
|
|
@@ -526,6 +464,7 @@ def create_impact_plot(scenario_name: str):
|
|
| 526 |
|
| 527 |
return fig
|
| 528 |
|
|
|
|
| 529 |
def create_timeline_plot(scenario_name: str):
|
| 530 |
"""Create an incident timeline visualization"""
|
| 531 |
import plotly.graph_objects as go
|
|
@@ -571,11 +510,13 @@ def create_timeline_plot(scenario_name: str):
|
|
| 571 |
|
| 572 |
return fig
|
| 573 |
|
|
|
|
| 574 |
# ===========================================
|
| 575 |
-
# SCENARIO UPDATE HANDLER -
|
| 576 |
# ===========================================
|
| 577 |
-
|
| 578 |
-
|
|
|
|
| 579 |
scenario = INCIDENT_SCENARIOS.get(scenario_name, {})
|
| 580 |
impact = scenario.get("business_impact", {})
|
| 581 |
metrics = scenario.get("metrics", {})
|
|
@@ -619,7 +560,6 @@ def update_scenario_display(scenario_name: str) -> tuple:
|
|
| 619 |
impact_plot = create_impact_plot(scenario_name)
|
| 620 |
timeline_plot = create_timeline_plot(scenario_name)
|
| 621 |
|
| 622 |
-
# Return as tuple for gradio compatibility
|
| 623 |
return (
|
| 624 |
scenario_html,
|
| 625 |
telemetry_plot,
|
|
@@ -627,8 +567,106 @@ def update_scenario_display(scenario_name: str) -> tuple:
|
|
| 627 |
timeline_plot
|
| 628 |
)
|
| 629 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 630 |
# ===========================================
|
| 631 |
-
# CREATE DEMO INTERFACE
|
| 632 |
# ===========================================
|
| 633 |
def create_demo_interface():
|
| 634 |
"""Create demo interface using modular components"""
|
|
@@ -644,13 +682,13 @@ def create_demo_interface():
|
|
| 644 |
# Get CSS styles
|
| 645 |
css_styles = get_styles()
|
| 646 |
|
| 647 |
-
# FIXED: Removed theme and css from Blocks constructor
|
| 648 |
with gr.Blocks(
|
| 649 |
-
title="π ARF Investor Demo v3.8.0"
|
|
|
|
| 650 |
) as demo:
|
| 651 |
|
| 652 |
# Header
|
| 653 |
-
header_html = create_header("3.
|
| 654 |
|
| 655 |
# Status bar
|
| 656 |
status_html = create_status_bar()
|
|
@@ -658,9 +696,8 @@ def create_demo_interface():
|
|
| 658 |
# ============ 5 TABS ============
|
| 659 |
with gr.Tabs(elem_classes="tab-nav"):
|
| 660 |
|
| 661 |
-
# TAB 1: Live Incident Demo
|
| 662 |
with gr.TabItem("π₯ Live Incident Demo", id="tab1"):
|
| 663 |
-
# Get components from UI module
|
| 664 |
(scenario_dropdown, scenario_card, telemetry_viz, impact_viz,
|
| 665 |
workflow_header, detection_agent, recall_agent, decision_agent,
|
| 666 |
oss_section, enterprise_section, oss_btn, enterprise_btn,
|
|
@@ -692,9 +729,9 @@ def create_demo_interface():
|
|
| 692 |
# Footer
|
| 693 |
footer_html = create_footer()
|
| 694 |
|
| 695 |
-
# ============ EVENT HANDLERS
|
| 696 |
|
| 697 |
-
# Update scenario display when dropdown changes
|
| 698 |
scenario_dropdown.change(
|
| 699 |
fn=update_scenario_display,
|
| 700 |
inputs=[scenario_dropdown],
|
|
@@ -702,96 +739,6 @@ def create_demo_interface():
|
|
| 702 |
)
|
| 703 |
|
| 704 |
# Run OSS Analysis
|
| 705 |
-
async def run_oss_analysis(scenario_name):
|
| 706 |
-
scenario = INCIDENT_SCENARIOS.get(scenario_name, {})
|
| 707 |
-
|
| 708 |
-
# Use orchestrator
|
| 709 |
-
analysis = await orchestrator.analyze_incident(scenario_name, scenario)
|
| 710 |
-
|
| 711 |
-
# Add to audit trail
|
| 712 |
-
audit_manager.add_incident(scenario_name, scenario.get("severity", "HIGH"))
|
| 713 |
-
|
| 714 |
-
# Update incident table
|
| 715 |
-
incident_table_data = audit_manager.get_incident_table()
|
| 716 |
-
|
| 717 |
-
# Enhanced OSS results
|
| 718 |
-
oss_results = {
|
| 719 |
-
"status": "β
OSS Analysis Complete",
|
| 720 |
-
"scenario": scenario_name,
|
| 721 |
-
"confidence": 0.85,
|
| 722 |
-
"agents_executed": ["Detection", "Recall", "Decision"],
|
| 723 |
-
"findings": [
|
| 724 |
-
"Anomaly detected with 99.8% confidence",
|
| 725 |
-
"3 similar incidents found in RAG memory",
|
| 726 |
-
"Historical success rate for similar actions: 87%"
|
| 727 |
-
],
|
| 728 |
-
"recommendations": [
|
| 729 |
-
"Scale resources based on historical patterns",
|
| 730 |
-
"Implement circuit breaker pattern",
|
| 731 |
-
"Add enhanced monitoring for key metrics"
|
| 732 |
-
],
|
| 733 |
-
"healing_intent": {
|
| 734 |
-
"action": "scale_out",
|
| 735 |
-
"component": scenario.get("component", "unknown"),
|
| 736 |
-
"parameters": {"nodes": "3β5", "region": "auto-select"},
|
| 737 |
-
"confidence": 0.94,
|
| 738 |
-
"requires_enterprise": True,
|
| 739 |
-
"advisory_only": True,
|
| 740 |
-
"safety_check": "β
Passed (blast radius: 2 services)"
|
| 741 |
-
}
|
| 742 |
-
}
|
| 743 |
-
|
| 744 |
-
# Update agent status
|
| 745 |
-
detection_html = """
|
| 746 |
-
<div class="agent-card detection">
|
| 747 |
-
<div class="agent-icon">π΅οΈββοΈ</div>
|
| 748 |
-
<div class="agent-content">
|
| 749 |
-
<h4>Detection Agent</h4>
|
| 750 |
-
<p class="agent-status-text">Analysis complete: <strong>99.8% confidence</strong></p>
|
| 751 |
-
<div class="agent-metrics">
|
| 752 |
-
<span class="agent-metric">Time: 45s</span>
|
| 753 |
-
<span class="agent-metric">Accuracy: 98.7%</span>
|
| 754 |
-
</div>
|
| 755 |
-
<div class="agent-status completed">COMPLETE</div>
|
| 756 |
-
</div>
|
| 757 |
-
</div>
|
| 758 |
-
"""
|
| 759 |
-
|
| 760 |
-
recall_html = """
|
| 761 |
-
<div class="agent-card recall">
|
| 762 |
-
<div class="agent-icon">π§ </div>
|
| 763 |
-
<div class="agent-content">
|
| 764 |
-
<h4>Recall Agent</h4>
|
| 765 |
-
<p class="agent-status-text"><strong>3 similar incidents</strong> retrieved from memory</p>
|
| 766 |
-
<div class="agent-metrics">
|
| 767 |
-
<span class="agent-metric">Recall: 92%</span>
|
| 768 |
-
<span class="agent-metric">Patterns: 5</span>
|
| 769 |
-
</div>
|
| 770 |
-
<div class="agent-status completed">COMPLETE</div>
|
| 771 |
-
</div>
|
| 772 |
-
</div>
|
| 773 |
-
"""
|
| 774 |
-
|
| 775 |
-
decision_html = """
|
| 776 |
-
<div class="agent-card decision">
|
| 777 |
-
<div class="agent-icon">π―</div>
|
| 778 |
-
<div class="agent-content">
|
| 779 |
-
<h4>Decision Agent</h4>
|
| 780 |
-
<p class="agent-status-text">HealingIntent created with <strong>94% confidence</strong></p>
|
| 781 |
-
<div class="agent-metrics">
|
| 782 |
-
<span class="agent-metric">Success Rate: 87%</span>
|
| 783 |
-
<span class="agent-metric">Safety: 100%</span>
|
| 784 |
-
</div>
|
| 785 |
-
<div class="agent-status completed">COMPLETE</div>
|
| 786 |
-
</div>
|
| 787 |
-
</div>
|
| 788 |
-
"""
|
| 789 |
-
|
| 790 |
-
return (
|
| 791 |
-
detection_html, recall_html, decision_html,
|
| 792 |
-
oss_results, incident_table_data
|
| 793 |
-
)
|
| 794 |
-
|
| 795 |
oss_btn.click(
|
| 796 |
fn=run_oss_analysis,
|
| 797 |
inputs=[scenario_dropdown],
|
|
@@ -813,7 +760,7 @@ def create_demo_interface():
|
|
| 813 |
# Calculate savings
|
| 814 |
impact = scenario.get("business_impact", {})
|
| 815 |
revenue_loss = impact.get("revenue_loss_per_hour", 5000)
|
| 816 |
-
savings = int(revenue_loss * 0.85)
|
| 817 |
|
| 818 |
# Add to audit trail
|
| 819 |
audit_manager.add_execution(scenario_name, mode, savings=savings)
|
|
@@ -897,21 +844,17 @@ def create_demo_interface():
|
|
| 897 |
)
|
| 898 |
|
| 899 |
# Run Complete Demo
|
| 900 |
-
|
| 901 |
-
|
| 902 |
-
|
| 903 |
-
|
| 904 |
# Step 1: Update scenario
|
| 905 |
-
update_result = update_scenario_display(scenario_name)
|
| 906 |
-
|
| 907 |
-
# Simulate OSS analysis
|
| 908 |
-
time.sleep(1)
|
| 909 |
|
| 910 |
# Step 2: Run OSS analysis
|
| 911 |
-
oss_result =
|
| 912 |
|
| 913 |
# Step 3: Execute Enterprise (simulated)
|
| 914 |
-
|
| 915 |
|
| 916 |
scenario = INCIDENT_SCENARIOS.get(scenario_name, {})
|
| 917 |
impact = scenario.get("business_impact", {})
|
|
@@ -956,15 +899,15 @@ def create_demo_interface():
|
|
| 956 |
"""
|
| 957 |
|
| 958 |
return (
|
| 959 |
-
update_result[0], update_result[1], update_result[2], update_result[3],
|
| 960 |
-
oss_result[0], oss_result[1], oss_result[2],
|
| 961 |
-
oss_result[3],
|
| 962 |
-
demo_message,
|
| 963 |
-
enterprise_results
|
| 964 |
)
|
| 965 |
|
| 966 |
demo_btn.click(
|
| 967 |
-
fn=
|
| 968 |
inputs=[scenario_dropdown],
|
| 969 |
outputs=[
|
| 970 |
scenario_card, telemetry_viz, impact_viz, timeline_viz,
|
|
@@ -975,58 +918,37 @@ def create_demo_interface():
|
|
| 975 |
|
| 976 |
# ============ TAB 2 HANDLERS ============
|
| 977 |
|
| 978 |
-
# Calculate ROI
|
| 979 |
def calculate_roi(scenario_name, monthly_incidents, team_size):
|
| 980 |
-
"""Calculate ROI
|
| 981 |
try:
|
| 982 |
-
logger.info(f"Calculating ROI for
|
| 983 |
|
| 984 |
# Validate inputs
|
| 985 |
-
if
|
| 986 |
-
|
| 987 |
-
logger.warning("No scenario selected, using default: Cache Miss Storm")
|
| 988 |
-
|
| 989 |
-
try:
|
| 990 |
-
monthly_incidents = int(monthly_incidents) if monthly_incidents else 15
|
| 991 |
-
team_size = int(team_size) if team_size else 5
|
| 992 |
-
except ValueError:
|
| 993 |
-
logger.warning(f"Invalid input values, using defaults: incidents=15, team=5")
|
| 994 |
-
monthly_incidents = 15
|
| 995 |
-
team_size = 5
|
| 996 |
|
| 997 |
# Get scenario-specific impact
|
| 998 |
avg_impact = get_scenario_impact(scenario_name)
|
| 999 |
-
logger.info(f"Using avg_impact for {scenario_name}: ${avg_impact}")
|
| 1000 |
|
| 1001 |
-
# Calculate ROI
|
| 1002 |
roi_result = roi_calculator.calculate_comprehensive_roi(
|
| 1003 |
monthly_incidents=monthly_incidents,
|
| 1004 |
avg_impact=float(avg_impact),
|
| 1005 |
team_size=team_size
|
| 1006 |
)
|
| 1007 |
|
| 1008 |
-
logger.info(f"ROI calculation successful, result keys: {list(roi_result.keys())}")
|
| 1009 |
-
|
| 1010 |
# Extract ROI multiplier for visualization
|
| 1011 |
roi_multiplier = extract_roi_multiplier(roi_result)
|
| 1012 |
-
logger.info(f"Extracted ROI multiplier: {roi_multiplier}")
|
| 1013 |
|
| 1014 |
# Create visualization
|
| 1015 |
-
|
| 1016 |
-
chart = viz_engine.create_executive_dashboard({"roi_multiplier": roi_multiplier})
|
| 1017 |
-
logger.info("Dashboard chart created successfully")
|
| 1018 |
-
except Exception as chart_error:
|
| 1019 |
-
logger.error(f"Chart creation failed: {chart_error}")
|
| 1020 |
-
# Create fallback chart
|
| 1021 |
-
chart = viz_engine.create_executive_dashboard()
|
| 1022 |
|
| 1023 |
return roi_result, chart
|
| 1024 |
|
| 1025 |
except Exception as e:
|
| 1026 |
logger.error(f"ROI calculation error: {e}")
|
| 1027 |
-
logger.error(traceback.format_exc())
|
| 1028 |
|
| 1029 |
-
# Provide fallback results
|
| 1030 |
fallback_result = {
|
| 1031 |
"status": "β
Calculated Successfully",
|
| 1032 |
"summary": {
|
|
@@ -1036,41 +958,11 @@ def create_demo_interface():
|
|
| 1036 |
"roi_multiplier": "5.2Γ",
|
| 1037 |
"payback_months": "6.0",
|
| 1038 |
"annual_roi_percentage": "420%"
|
| 1039 |
-
},
|
| 1040 |
-
"scenarios": {
|
| 1041 |
-
"base_case": {"roi": "5.2Γ", "payback": "6.0 months", "confidence": "High"},
|
| 1042 |
-
"best_case": {"roi": "6.5Γ", "payback": "4.8 months", "confidence": "Medium"},
|
| 1043 |
-
"worst_case": {"roi": "4.0Γ", "payback": "7.5 months", "confidence": "Medium"}
|
| 1044 |
-
},
|
| 1045 |
-
"comparison": {
|
| 1046 |
-
"industry_average": "5.2Γ ROI",
|
| 1047 |
-
"top_performers": "8.7Γ ROI",
|
| 1048 |
-
"your_position": "Top 25%"
|
| 1049 |
-
},
|
| 1050 |
-
"recommendation": {
|
| 1051 |
-
"action": "π Deploy ARF Enterprise",
|
| 1052 |
-
"reason": "Exceptional ROI (>5Γ) with quick payback",
|
| 1053 |
-
"timeline": "30-day implementation",
|
| 1054 |
-
"expected_value": ">$1M annual savings",
|
| 1055 |
-
"priority": "High"
|
| 1056 |
}
|
| 1057 |
}
|
| 1058 |
|
| 1059 |
# Always return a valid chart
|
| 1060 |
-
|
| 1061 |
-
fallback_chart = viz_engine.create_executive_dashboard({"roi_multiplier": 5.2})
|
| 1062 |
-
except:
|
| 1063 |
-
# Ultimate fallback - create a simple chart
|
| 1064 |
-
import plotly.graph_objects as go
|
| 1065 |
-
fig = go.Figure(go.Indicator(
|
| 1066 |
-
mode="number+gauge",
|
| 1067 |
-
value=5.2,
|
| 1068 |
-
title={"text": "ROI Multiplier"},
|
| 1069 |
-
domain={'x': [0, 1], 'y': [0, 1]},
|
| 1070 |
-
gauge={'axis': {'range': [0, 10]}}
|
| 1071 |
-
))
|
| 1072 |
-
fig.update_layout(height=400)
|
| 1073 |
-
fallback_chart = fig
|
| 1074 |
|
| 1075 |
return fallback_result, fallback_chart
|
| 1076 |
|
|
@@ -1082,62 +974,38 @@ def create_demo_interface():
|
|
| 1082 |
|
| 1083 |
# ============ TAB 3 HANDLERS ============
|
| 1084 |
|
| 1085 |
-
# Validate License
|
| 1086 |
def validate_license():
|
| 1087 |
-
logger.info("Validating license...")
|
| 1088 |
return {
|
| 1089 |
"status": "β
Valid",
|
| 1090 |
"tier": "Enterprise",
|
| 1091 |
"expires": "2026-12-31",
|
| 1092 |
-
"message": "License validated successfully"
|
| 1093 |
-
"next_renewal": "2026-06-30",
|
| 1094 |
-
"features": ["autonomous_healing", "compliance", "audit_trail",
|
| 1095 |
-
"predictive_analytics", "multi_cloud", "role_based_access"]
|
| 1096 |
}
|
| 1097 |
|
| 1098 |
-
# Start Trial
|
| 1099 |
def start_trial():
|
| 1100 |
-
logger.info("Starting trial...")
|
| 1101 |
return {
|
| 1102 |
"status": "π Trial Activated",
|
| 1103 |
"tier": "Enterprise Trial",
|
| 1104 |
"expires": "2026-01-30",
|
| 1105 |
-
"features": ["autonomous_healing", "compliance", "audit_trail",
|
| 1106 |
-
"predictive_analytics", "multi_cloud"],
|
| 1107 |
"message": "30-day trial started. Full features enabled."
|
| 1108 |
}
|
| 1109 |
|
| 1110 |
-
# Upgrade License
|
| 1111 |
def upgrade_license():
|
| 1112 |
-
logger.info("Checking upgrade options...")
|
| 1113 |
return {
|
| 1114 |
"status": "π Upgrade Available",
|
| 1115 |
"current_tier": "Enterprise",
|
| 1116 |
"next_tier": "Enterprise Plus",
|
| 1117 |
-
"features_added": ["predictive_scaling", "custom_workflows"
|
| 1118 |
"cost": "$25,000/year",
|
| 1119 |
"message": "Contact sales@arf.dev for upgrade"
|
| 1120 |
}
|
| 1121 |
|
| 1122 |
-
|
| 1123 |
-
|
| 1124 |
-
|
| 1125 |
-
outputs=[license_display]
|
| 1126 |
-
)
|
| 1127 |
-
|
| 1128 |
-
trial_btn.click(
|
| 1129 |
-
fn=start_trial,
|
| 1130 |
-
outputs=[license_display]
|
| 1131 |
-
)
|
| 1132 |
-
|
| 1133 |
-
upgrade_btn.click(
|
| 1134 |
-
fn=upgrade_license,
|
| 1135 |
-
outputs=[license_display]
|
| 1136 |
-
)
|
| 1137 |
|
| 1138 |
-
# MCP Mode change handler
|
| 1139 |
def update_mcp_mode(mode):
|
| 1140 |
-
logger.info(f"Updating MCP mode to: {mode}")
|
| 1141 |
mode_info = {
|
| 1142 |
"advisory": {
|
| 1143 |
"current_mode": "advisory",
|
|
@@ -1165,72 +1033,41 @@ def create_demo_interface():
|
|
| 1165 |
|
| 1166 |
# ============ TAB 4 HANDLERS ============
|
| 1167 |
|
| 1168 |
-
# Refresh Audit Trail
|
| 1169 |
def refresh_audit_trail():
|
| 1170 |
return audit_manager.get_execution_table(), audit_manager.get_incident_table()
|
| 1171 |
|
| 1172 |
-
refresh_btn.click(
|
| 1173 |
-
fn=refresh_audit_trail,
|
| 1174 |
-
outputs=[execution_table, incident_table]
|
| 1175 |
-
)
|
| 1176 |
-
|
| 1177 |
-
# Clear History
|
| 1178 |
def clear_audit_trail():
|
| 1179 |
-
audit_manager.
|
| 1180 |
-
audit_manager.incidents = []
|
| 1181 |
return audit_manager.get_execution_table(), audit_manager.get_incident_table()
|
| 1182 |
|
| 1183 |
-
clear_btn.click(
|
| 1184 |
-
fn=clear_audit_trail,
|
| 1185 |
-
outputs=[execution_table, incident_table]
|
| 1186 |
-
)
|
| 1187 |
-
|
| 1188 |
-
# Export Audit Trail
|
| 1189 |
def export_audit_trail():
|
| 1190 |
-
logger.info("Exporting audit trail...")
|
| 1191 |
try:
|
| 1192 |
-
|
| 1193 |
-
total_savings = 0
|
| 1194 |
-
for e in audit_manager.executions:
|
| 1195 |
-
if e['savings'] != '$0':
|
| 1196 |
-
try:
|
| 1197 |
-
# Remove $ and commas, convert to int
|
| 1198 |
-
savings_str = e['savings'].replace('$', '').replace(',', '')
|
| 1199 |
-
total_savings += int(float(savings_str))
|
| 1200 |
-
except:
|
| 1201 |
-
pass
|
| 1202 |
-
|
| 1203 |
-
# Calculate success rate
|
| 1204 |
-
successful = len([e for e in audit_manager.executions if 'β
' in e['status']])
|
| 1205 |
-
total = len(audit_manager.executions)
|
| 1206 |
-
success_rate = (successful / total * 100) if total > 0 else 0
|
| 1207 |
|
| 1208 |
audit_data = {
|
| 1209 |
"exported_at": datetime.datetime.now().isoformat(),
|
| 1210 |
"executions": audit_manager.executions[:10],
|
| 1211 |
"incidents": audit_manager.incidents[:15],
|
| 1212 |
"summary": {
|
| 1213 |
-
"total_executions":
|
| 1214 |
"total_incidents": len(audit_manager.incidents),
|
| 1215 |
"total_savings": f"${total_savings:,}",
|
| 1216 |
-
"success_rate":
|
| 1217 |
}
|
| 1218 |
}
|
| 1219 |
return json.dumps(audit_data, indent=2)
|
| 1220 |
except Exception as e:
|
| 1221 |
-
logger.error(f"Export failed: {e}")
|
| 1222 |
return json.dumps({"error": f"Export failed: {str(e)}"}, indent=2)
|
| 1223 |
|
| 1224 |
-
|
| 1225 |
-
|
| 1226 |
-
|
| 1227 |
-
)
|
| 1228 |
|
| 1229 |
# ============ INITIALIZATION ============
|
| 1230 |
|
| 1231 |
# Initialize scenario display
|
| 1232 |
demo.load(
|
| 1233 |
-
fn=lambda: update_scenario_display(
|
| 1234 |
outputs=[scenario_card, telemetry_viz, impact_viz, timeline_viz]
|
| 1235 |
)
|
| 1236 |
|
|
@@ -1247,27 +1084,16 @@ def create_demo_interface():
|
|
| 1247 |
value=5.2,
|
| 1248 |
title={"text": "<b>Executive Dashboard</b><br>ROI Multiplier"},
|
| 1249 |
domain={'x': [0, 1], 'y': [0, 1]},
|
| 1250 |
-
gauge={
|
| 1251 |
-
'axis': {'range': [0, 10]},
|
| 1252 |
-
'bar': {'color': "#4ECDC4"},
|
| 1253 |
-
'steps': [
|
| 1254 |
-
{'range': [0, 2], 'color': 'lightgray'},
|
| 1255 |
-
{'range': [2, 4], 'color': 'gray'},
|
| 1256 |
-
{'range': [4, 6], 'color': 'lightgreen'},
|
| 1257 |
-
{'range': [6, 10], 'color': "#4ECDC4"}
|
| 1258 |
-
]
|
| 1259 |
-
}
|
| 1260 |
))
|
| 1261 |
fig.update_layout(height=700, paper_bgcolor="rgba(0,0,0,0)")
|
| 1262 |
return fig
|
| 1263 |
|
| 1264 |
-
demo.load(
|
| 1265 |
-
fn=initialize_dashboard,
|
| 1266 |
-
outputs=[dashboard_output]
|
| 1267 |
-
)
|
| 1268 |
|
| 1269 |
return demo
|
| 1270 |
|
|
|
|
| 1271 |
# ===========================================
|
| 1272 |
# MAIN EXECUTION
|
| 1273 |
# ===========================================
|
|
@@ -1275,22 +1101,16 @@ def main():
|
|
| 1275 |
"""Main entry point"""
|
| 1276 |
print("π Starting ARF Ultimate Investor Demo v3.8.0...")
|
| 1277 |
print("=" * 70)
|
| 1278 |
-
print("π
|
| 1279 |
-
print("
|
| 1280 |
-
print("
|
| 1281 |
-
print(" β’ Working Button Handlers")
|
| 1282 |
-
print(" β’ 5 Functional Tabs")
|
| 1283 |
-
print(" β’ Full Demo Data")
|
| 1284 |
-
print(" β’ Enhanced Tab 1 with rich visualizations")
|
| 1285 |
print("=" * 70)
|
| 1286 |
|
| 1287 |
-
# Import gradio for theme
|
| 1288 |
import gradio as gr
|
| 1289 |
|
| 1290 |
# Create and launch demo
|
| 1291 |
demo = create_demo_interface()
|
| 1292 |
|
| 1293 |
-
# FIXED: Moved theme and css parameters to launch() method
|
| 1294 |
demo.launch(
|
| 1295 |
server_name="0.0.0.0",
|
| 1296 |
server_port=7860,
|
|
@@ -1299,5 +1119,6 @@ def main():
|
|
| 1299 |
css=get_styles()
|
| 1300 |
)
|
| 1301 |
|
|
|
|
| 1302 |
if __name__ == "__main__":
|
| 1303 |
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 architecture
|
| 5 |
"""
|
| 6 |
|
| 7 |
import logging
|
|
|
|
| 11 |
import datetime
|
| 12 |
import asyncio
|
| 13 |
import time
|
|
|
|
| 14 |
from pathlib import Path
|
| 15 |
from typing import Dict, List, Any, Optional, Tuple
|
| 16 |
|
|
|
|
| 30 |
# Add parent directory to path
|
| 31 |
sys.path.insert(0, str(Path(__file__).parent))
|
| 32 |
|
| 33 |
+
# Import async utilities FIRST
|
| 34 |
+
try:
|
| 35 |
+
from utils.async_runner import AsyncRunner, async_to_sync
|
| 36 |
+
ASYNC_UTILS_AVAILABLE = True
|
| 37 |
+
except ImportError as e:
|
| 38 |
+
logger.error(f"Failed to import async utilities: {e}")
|
| 39 |
+
ASYNC_UTILS_AVAILABLE = False
|
| 40 |
+
|
| 41 |
+
# Import settings
|
| 42 |
+
try:
|
| 43 |
+
from config.settings import settings
|
| 44 |
+
SETTINGS_AVAILABLE = True
|
| 45 |
+
except ImportError as e:
|
| 46 |
+
logger.error(f"Failed to import settings: {e}")
|
| 47 |
+
SETTINGS_AVAILABLE = False
|
| 48 |
+
# Create minimal settings
|
| 49 |
+
class Settings:
|
| 50 |
+
arf_mode = "demo"
|
| 51 |
+
use_mock_arf = True
|
| 52 |
+
default_scenario = "Cache Miss Storm"
|
| 53 |
+
settings = Settings()
|
| 54 |
+
|
| 55 |
+
# Import scenario registry
|
| 56 |
+
try:
|
| 57 |
+
from config.scenario_registry import ScenarioRegistry
|
| 58 |
+
SCENARIO_REGISTRY_AVAILABLE = True
|
| 59 |
+
except ImportError as e:
|
| 60 |
+
logger.error(f"Failed to import scenario registry: {e}")
|
| 61 |
+
SCENARIO_REGISTRY_AVAILABLE = False
|
| 62 |
+
|
| 63 |
# ===========================================
|
| 64 |
# IMPORT MODULAR COMPONENTS - SAFE IMPORTS
|
| 65 |
# ===========================================
|
| 66 |
def import_components():
|
| 67 |
"""Safely import all components with proper error handling"""
|
| 68 |
try:
|
| 69 |
+
# Import scenarios from registry
|
| 70 |
+
if SCENARIO_REGISTRY_AVAILABLE:
|
| 71 |
+
INCIDENT_SCENARIOS = ScenarioRegistry.load_scenarios()
|
| 72 |
+
else:
|
| 73 |
+
from demo.scenarios import INCIDENT_SCENARIOS
|
| 74 |
|
| 75 |
# Import orchestrator
|
| 76 |
from demo.orchestrator import DemoOrchestrator
|
|
|
|
| 79 |
try:
|
| 80 |
from core.calculators import EnhancedROICalculator
|
| 81 |
roi_calculator_available = True
|
| 82 |
+
except ImportError as e:
|
| 83 |
+
logger.warning(f"EnhancedROICalculator not available: {e}")
|
| 84 |
+
from core.calculators import EnhancedROICalculator
|
| 85 |
+
roi_calculator_available = True
|
| 86 |
|
| 87 |
# Import visualizations
|
| 88 |
try:
|
| 89 |
from core.visualizations import EnhancedVisualizationEngine
|
| 90 |
viz_engine_available = True
|
| 91 |
+
except ImportError as e:
|
| 92 |
+
logger.warning(f"EnhancedVisualizationEngine not available: {e}")
|
| 93 |
+
from core.visualizations import EnhancedVisualizationEngine
|
| 94 |
+
viz_engine_available = True
|
| 95 |
|
| 96 |
# Import UI components
|
| 97 |
from ui.components import (
|
|
|
|
| 105 |
try:
|
| 106 |
from ui.styles import get_styles
|
| 107 |
styles_available = True
|
| 108 |
+
except ImportError as e:
|
| 109 |
+
logger.warning(f"Styles not available: {e}")
|
| 110 |
get_styles = lambda: ""
|
| 111 |
styles_available = False
|
| 112 |
|
|
|
|
| 130 |
}
|
| 131 |
|
| 132 |
except ImportError as e:
|
| 133 |
+
logger.error(f"β CRITICAL IMPORT ERROR: {e}")
|
| 134 |
+
logger.error(traceback.format_exc())
|
| 135 |
return {"all_available": False, "error": str(e)}
|
| 136 |
|
| 137 |
# Import components safely
|
| 138 |
components = import_components()
|
| 139 |
|
| 140 |
if not components.get("all_available", False):
|
| 141 |
+
logger.error("Failed to import required components, starting with minimal functionality")
|
|
|
|
|
|
|
|
|
|
| 142 |
|
|
|
|
| 143 |
import gradio as gr
|
| 144 |
|
| 145 |
+
# Minimal fallback components
|
| 146 |
INCIDENT_SCENARIOS = {
|
| 147 |
"Cache Miss Storm": {
|
| 148 |
"component": "Redis Cache Cluster",
|
|
|
|
| 158 |
async def analyze_incident(self, name, scenario):
|
| 159 |
return {"status": "Mock analysis"}
|
| 160 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
components = {
|
| 162 |
"INCIDENT_SCENARIOS": INCIDENT_SCENARIOS,
|
| 163 |
"DemoOrchestrator": DemoOrchestrator(),
|
| 164 |
+
"create_header": lambda version, mock: gr.HTML(f"<h2>π ARF v{version}</h2>"),
|
| 165 |
+
"create_status_bar": lambda: gr.HTML("<div>Status</div>"),
|
| 166 |
+
"create_tab1_incident_demo": lambda *args: [gr.Dropdown()] * 24,
|
| 167 |
+
"create_tab2_business_roi": lambda *args: [gr.Plot()] * 7,
|
| 168 |
+
"create_tab3_enterprise_features": lambda: [gr.JSON()] * 8,
|
| 169 |
+
"create_tab4_audit_trail": lambda: [gr.Button()] * 6,
|
| 170 |
+
"create_tab5_learning_engine": lambda: [gr.Plot()] * 10,
|
| 171 |
+
"create_footer": lambda: gr.HTML("<footer>ARF</footer>"),
|
|
|
|
|
|
|
| 172 |
"get_styles": lambda: "",
|
| 173 |
"all_available": True
|
| 174 |
}
|
| 175 |
|
| 176 |
+
# Extract components
|
| 177 |
INCIDENT_SCENARIOS = components["INCIDENT_SCENARIOS"]
|
| 178 |
DemoOrchestrator = components["DemoOrchestrator"]
|
| 179 |
EnhancedROICalculator = components["EnhancedROICalculator"]
|
|
|
|
| 189 |
get_styles = components["get_styles"]
|
| 190 |
|
| 191 |
# ===========================================
|
| 192 |
+
# AUDIT TRAIL MANAGER - ENHANCED
|
| 193 |
# ===========================================
|
| 194 |
class AuditTrailManager:
|
| 195 |
+
"""Enhanced audit trail manager with persistence"""
|
| 196 |
|
| 197 |
def __init__(self):
|
| 198 |
self.executions = []
|
| 199 |
self.incidents = []
|
| 200 |
+
self._max_history = settings.max_history_items if SETTINGS_AVAILABLE else 100
|
| 201 |
|
| 202 |
+
def add_execution(self, scenario: str, mode: str, success: bool = True, savings: float = 0) -> Dict:
|
| 203 |
+
"""Add execution to audit trail"""
|
| 204 |
entry = {
|
| 205 |
"time": datetime.datetime.now().strftime("%H:%M"),
|
| 206 |
"scenario": scenario,
|
| 207 |
"mode": mode,
|
| 208 |
"status": "β
Success" if success else "β Failed",
|
| 209 |
+
"savings": f"${savings:,.0f}",
|
| 210 |
+
"details": f"{mode} execution at {datetime.datetime.now().isoformat()}"
|
| 211 |
}
|
| 212 |
self.executions.insert(0, entry)
|
| 213 |
+
|
| 214 |
+
# Limit history
|
| 215 |
+
if len(self.executions) > self._max_history:
|
| 216 |
+
self.executions = self.executions[:self._max_history]
|
| 217 |
+
|
| 218 |
+
logger.info(f"Added execution: {scenario} ({mode})")
|
| 219 |
return entry
|
| 220 |
|
| 221 |
+
def add_incident(self, scenario: str, severity: str = "HIGH") -> Dict:
|
| 222 |
+
"""Add incident to audit trail"""
|
| 223 |
entry = {
|
| 224 |
"time": datetime.datetime.now().strftime("%H:%M"),
|
| 225 |
"scenario": scenario,
|
|
|
|
| 228 |
"status": "Analyzed"
|
| 229 |
}
|
| 230 |
self.incidents.insert(0, entry)
|
| 231 |
+
|
| 232 |
+
# Limit history
|
| 233 |
+
if len(self.incidents) > self._max_history:
|
| 234 |
+
self.incidents = self.incidents[:self._max_history]
|
| 235 |
+
|
| 236 |
+
logger.info(f"Added incident: {scenario} ({severity})")
|
| 237 |
return entry
|
| 238 |
|
| 239 |
+
def get_execution_table(self) -> List[List]:
|
| 240 |
+
"""Get execution table data"""
|
| 241 |
return [
|
| 242 |
[e["time"], e["scenario"], e["mode"], e["status"], e["savings"], e["details"]]
|
| 243 |
for e in self.executions[:10]
|
| 244 |
]
|
| 245 |
|
| 246 |
+
def get_incident_table(self) -> List[List]:
|
| 247 |
+
"""Get incident table data"""
|
| 248 |
return [
|
| 249 |
[e["time"], e["component"], e["scenario"], e["severity"], e["status"]]
|
| 250 |
for e in self.incidents[:15]
|
| 251 |
]
|
| 252 |
+
|
| 253 |
+
def get_total_savings(self) -> float:
|
| 254 |
+
"""Calculate total savings"""
|
| 255 |
+
total = 0
|
| 256 |
+
for e in self.executions:
|
| 257 |
+
try:
|
| 258 |
+
# Extract numeric value from savings string
|
| 259 |
+
savings_str = e["savings"].replace("$", "").replace(",", "")
|
| 260 |
+
total += float(savings_str)
|
| 261 |
+
except (ValueError, AttributeError):
|
| 262 |
+
continue
|
| 263 |
+
return total
|
| 264 |
+
|
| 265 |
+
def clear(self) -> None:
|
| 266 |
+
"""Clear audit trail"""
|
| 267 |
+
self.executions = []
|
| 268 |
+
self.incidents = []
|
| 269 |
+
logger.info("Audit trail cleared")
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
# ===========================================
|
| 273 |
+
# ARF ADAPTER INTEGRATION
|
| 274 |
+
# ===========================================
|
| 275 |
+
try:
|
| 276 |
+
from core.arf_adapter import get_arf_adapter
|
| 277 |
+
ARF_ADAPTER_AVAILABLE = True
|
| 278 |
+
except ImportError:
|
| 279 |
+
ARF_ADAPTER_AVAILABLE = False
|
| 280 |
+
logger.warning("ARF adapter not available, using direct mock imports")
|
| 281 |
|
| 282 |
# ===========================================
|
| 283 |
+
# HELPER FUNCTIONS
|
| 284 |
# ===========================================
|
| 285 |
def get_scenario_impact(scenario_name: str) -> float:
|
| 286 |
"""Get average impact for a given scenario"""
|
|
|
|
| 294 |
}
|
| 295 |
return impact_map.get(scenario_name, 5000)
|
| 296 |
|
| 297 |
+
|
|
|
|
|
|
|
| 298 |
def extract_roi_multiplier(roi_result: Dict) -> float:
|
| 299 |
+
"""Extract ROI multiplier from EnhancedROICalculator result"""
|
| 300 |
try:
|
| 301 |
# Try to get from summary
|
| 302 |
if "summary" in roi_result and "roi_multiplier" in roi_result["summary"]:
|
|
|
|
| 322 |
return 5.2 # Default fallback
|
| 323 |
except Exception as e:
|
| 324 |
logger.warning(f"Failed to extract ROI multiplier: {e}, using default 5.2")
|
| 325 |
+
return 5.2
|
| 326 |
+
|
| 327 |
|
| 328 |
# ===========================================
|
| 329 |
+
# VISUALIZATION HELPERS
|
| 330 |
# ===========================================
|
| 331 |
def create_telemetry_plot(scenario_name: str):
|
| 332 |
"""Create a telemetry visualization for the selected scenario"""
|
| 333 |
import plotly.graph_objects as go
|
| 334 |
import numpy as np
|
| 335 |
|
| 336 |
+
# Generate sample data
|
| 337 |
time_points = np.arange(0, 100, 1)
|
| 338 |
|
| 339 |
# Different patterns for different scenarios
|
|
|
|
| 417 |
|
| 418 |
return fig
|
| 419 |
|
| 420 |
+
|
| 421 |
def create_impact_plot(scenario_name: str):
|
| 422 |
"""Create a business impact visualization"""
|
| 423 |
import plotly.graph_objects as go
|
| 424 |
|
| 425 |
+
# Get impact data
|
| 426 |
impact_map = {
|
| 427 |
"Cache Miss Storm": {"revenue": 8500, "users": 45000, "services": 12},
|
| 428 |
"Database Connection Pool Exhaustion": {"revenue": 4200, "users": 22000, "services": 8},
|
|
|
|
| 434 |
|
| 435 |
impact = impact_map.get(scenario_name, {"revenue": 5000, "users": 25000, "services": 10})
|
| 436 |
|
| 437 |
+
# Create gauge
|
| 438 |
fig = go.Figure(go.Indicator(
|
| 439 |
mode="gauge+number",
|
| 440 |
value=impact["revenue"],
|
|
|
|
| 464 |
|
| 465 |
return fig
|
| 466 |
|
| 467 |
+
|
| 468 |
def create_timeline_plot(scenario_name: str):
|
| 469 |
"""Create an incident timeline visualization"""
|
| 470 |
import plotly.graph_objects as go
|
|
|
|
| 510 |
|
| 511 |
return fig
|
| 512 |
|
| 513 |
+
|
| 514 |
# ===========================================
|
| 515 |
+
# SCENARIO UPDATE HANDLER - ASYNC FIXED
|
| 516 |
# ===========================================
|
| 517 |
+
@async_to_sync
|
| 518 |
+
async def update_scenario_display(scenario_name: str) -> tuple:
|
| 519 |
+
"""Update all scenario-related displays - ASYNC VERSION"""
|
| 520 |
scenario = INCIDENT_SCENARIOS.get(scenario_name, {})
|
| 521 |
impact = scenario.get("business_impact", {})
|
| 522 |
metrics = scenario.get("metrics", {})
|
|
|
|
| 560 |
impact_plot = create_impact_plot(scenario_name)
|
| 561 |
timeline_plot = create_timeline_plot(scenario_name)
|
| 562 |
|
|
|
|
| 563 |
return (
|
| 564 |
scenario_html,
|
| 565 |
telemetry_plot,
|
|
|
|
| 567 |
timeline_plot
|
| 568 |
)
|
| 569 |
|
| 570 |
+
|
| 571 |
+
# ===========================================
|
| 572 |
+
# OSS ANALYSIS HANDLER - ASYNC FIXED
|
| 573 |
+
# ===========================================
|
| 574 |
+
@async_to_sync
|
| 575 |
+
async def run_oss_analysis(scenario_name: str):
|
| 576 |
+
"""Run OSS analysis - ASYNC VERSION"""
|
| 577 |
+
scenario = INCIDENT_SCENARIOS.get(scenario_name, {})
|
| 578 |
+
|
| 579 |
+
# Use orchestrator
|
| 580 |
+
orchestrator = DemoOrchestrator()
|
| 581 |
+
analysis = await orchestrator.analyze_incident(scenario_name, scenario)
|
| 582 |
+
|
| 583 |
+
# Add to audit trail
|
| 584 |
+
audit_manager.add_incident(scenario_name, scenario.get("severity", "HIGH"))
|
| 585 |
+
|
| 586 |
+
# Update incident table
|
| 587 |
+
incident_table_data = audit_manager.get_incident_table()
|
| 588 |
+
|
| 589 |
+
# Enhanced OSS results
|
| 590 |
+
oss_results = {
|
| 591 |
+
"status": "β
OSS Analysis Complete",
|
| 592 |
+
"scenario": scenario_name,
|
| 593 |
+
"confidence": 0.85,
|
| 594 |
+
"agents_executed": ["Detection", "Recall", "Decision"],
|
| 595 |
+
"findings": [
|
| 596 |
+
"Anomaly detected with 99.8% confidence",
|
| 597 |
+
"3 similar incidents found in RAG memory",
|
| 598 |
+
"Historical success rate for similar actions: 87%"
|
| 599 |
+
],
|
| 600 |
+
"recommendations": [
|
| 601 |
+
"Scale resources based on historical patterns",
|
| 602 |
+
"Implement circuit breaker pattern",
|
| 603 |
+
"Add enhanced monitoring for key metrics"
|
| 604 |
+
],
|
| 605 |
+
"healing_intent": {
|
| 606 |
+
"action": "scale_out",
|
| 607 |
+
"component": scenario.get("component", "unknown"),
|
| 608 |
+
"parameters": {"nodes": "3β5", "region": "auto-select"},
|
| 609 |
+
"confidence": 0.94,
|
| 610 |
+
"requires_enterprise": True,
|
| 611 |
+
"advisory_only": True,
|
| 612 |
+
"safety_check": "β
Passed (blast radius: 2 services)"
|
| 613 |
+
}
|
| 614 |
+
}
|
| 615 |
+
|
| 616 |
+
# Update agent status
|
| 617 |
+
detection_html = """
|
| 618 |
+
<div class="agent-card detection">
|
| 619 |
+
<div class="agent-icon">π΅οΈββοΈ</div>
|
| 620 |
+
<div class="agent-content">
|
| 621 |
+
<h4>Detection Agent</h4>
|
| 622 |
+
<p class="agent-status-text">Analysis complete: <strong>99.8% confidence</strong></p>
|
| 623 |
+
<div class="agent-metrics">
|
| 624 |
+
<span class="agent-metric">Time: 45s</span>
|
| 625 |
+
<span class="agent-metric">Accuracy: 98.7%</span>
|
| 626 |
+
</div>
|
| 627 |
+
<div class="agent-status completed">COMPLETE</div>
|
| 628 |
+
</div>
|
| 629 |
+
</div>
|
| 630 |
+
"""
|
| 631 |
+
|
| 632 |
+
recall_html = """
|
| 633 |
+
<div class="agent-card recall">
|
| 634 |
+
<div class="agent-icon">π§ </div>
|
| 635 |
+
<div class="agent-content">
|
| 636 |
+
<h4>Recall Agent</h4>
|
| 637 |
+
<p class="agent-status-text"><strong>3 similar incidents</strong> retrieved from memory</p>
|
| 638 |
+
<div class="agent-metrics">
|
| 639 |
+
<span class="agent-metric">Recall: 92%</span>
|
| 640 |
+
<span class="agent-metric">Patterns: 5</span>
|
| 641 |
+
</div>
|
| 642 |
+
<div class="agent-status completed">COMPLETE</div>
|
| 643 |
+
</div>
|
| 644 |
+
</div>
|
| 645 |
+
"""
|
| 646 |
+
|
| 647 |
+
decision_html = """
|
| 648 |
+
<div class="agent-card decision">
|
| 649 |
+
<div class="agent-icon">π―</div>
|
| 650 |
+
<div class="agent-content">
|
| 651 |
+
<h4>Decision Agent</h4>
|
| 652 |
+
<p class="agent-status-text">HealingIntent created with <strong>94% confidence</strong></p>
|
| 653 |
+
<div class="agent-metrics">
|
| 654 |
+
<span class="agent-metric">Success Rate: 87%</span>
|
| 655 |
+
<span class="agent-metric">Safety: 100%</span>
|
| 656 |
+
</div>
|
| 657 |
+
<div class="agent-status completed">COMPLETE</div>
|
| 658 |
+
</div>
|
| 659 |
+
</div>
|
| 660 |
+
"""
|
| 661 |
+
|
| 662 |
+
return (
|
| 663 |
+
detection_html, recall_html, decision_html,
|
| 664 |
+
oss_results, incident_table_data
|
| 665 |
+
)
|
| 666 |
+
|
| 667 |
+
|
| 668 |
# ===========================================
|
| 669 |
+
# CREATE DEMO INTERFACE
|
| 670 |
# ===========================================
|
| 671 |
def create_demo_interface():
|
| 672 |
"""Create demo interface using modular components"""
|
|
|
|
| 682 |
# Get CSS styles
|
| 683 |
css_styles = get_styles()
|
| 684 |
|
|
|
|
| 685 |
with gr.Blocks(
|
| 686 |
+
title=f"π ARF Investor Demo v3.8.0 - {settings.arf_mode.upper()} Mode",
|
| 687 |
+
css=css_styles
|
| 688 |
) as demo:
|
| 689 |
|
| 690 |
# Header
|
| 691 |
+
header_html = create_header("3.8.0", settings.use_mock_arf)
|
| 692 |
|
| 693 |
# Status bar
|
| 694 |
status_html = create_status_bar()
|
|
|
|
| 696 |
# ============ 5 TABS ============
|
| 697 |
with gr.Tabs(elem_classes="tab-nav"):
|
| 698 |
|
| 699 |
+
# TAB 1: Live Incident Demo
|
| 700 |
with gr.TabItem("π₯ Live Incident Demo", id="tab1"):
|
|
|
|
| 701 |
(scenario_dropdown, scenario_card, telemetry_viz, impact_viz,
|
| 702 |
workflow_header, detection_agent, recall_agent, decision_agent,
|
| 703 |
oss_section, enterprise_section, oss_btn, enterprise_btn,
|
|
|
|
| 729 |
# Footer
|
| 730 |
footer_html = create_footer()
|
| 731 |
|
| 732 |
+
# ============ EVENT HANDLERS ============
|
| 733 |
|
| 734 |
+
# Update scenario display when dropdown changes
|
| 735 |
scenario_dropdown.change(
|
| 736 |
fn=update_scenario_display,
|
| 737 |
inputs=[scenario_dropdown],
|
|
|
|
| 739 |
)
|
| 740 |
|
| 741 |
# Run OSS Analysis
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 742 |
oss_btn.click(
|
| 743 |
fn=run_oss_analysis,
|
| 744 |
inputs=[scenario_dropdown],
|
|
|
|
| 760 |
# Calculate savings
|
| 761 |
impact = scenario.get("business_impact", {})
|
| 762 |
revenue_loss = impact.get("revenue_loss_per_hour", 5000)
|
| 763 |
+
savings = int(revenue_loss * 0.85)
|
| 764 |
|
| 765 |
# Add to audit trail
|
| 766 |
audit_manager.add_execution(scenario_name, mode, savings=savings)
|
|
|
|
| 844 |
)
|
| 845 |
|
| 846 |
# Run Complete Demo
|
| 847 |
+
@async_to_sync
|
| 848 |
+
async def run_complete_demo_async(scenario_name):
|
| 849 |
+
"""Run a complete demo walkthrough - ASYNC"""
|
|
|
|
| 850 |
# Step 1: Update scenario
|
| 851 |
+
update_result = await update_scenario_display(scenario_name)
|
|
|
|
|
|
|
|
|
|
| 852 |
|
| 853 |
# Step 2: Run OSS analysis
|
| 854 |
+
oss_result = await run_oss_analysis(scenario_name)
|
| 855 |
|
| 856 |
# Step 3: Execute Enterprise (simulated)
|
| 857 |
+
await asyncio.sleep(2)
|
| 858 |
|
| 859 |
scenario = INCIDENT_SCENARIOS.get(scenario_name, {})
|
| 860 |
impact = scenario.get("business_impact", {})
|
|
|
|
| 899 |
"""
|
| 900 |
|
| 901 |
return (
|
| 902 |
+
update_result[0], update_result[1], update_result[2], update_result[3],
|
| 903 |
+
oss_result[0], oss_result[1], oss_result[2],
|
| 904 |
+
oss_result[3],
|
| 905 |
+
demo_message,
|
| 906 |
+
enterprise_results
|
| 907 |
)
|
| 908 |
|
| 909 |
demo_btn.click(
|
| 910 |
+
fn=run_complete_demo_async,
|
| 911 |
inputs=[scenario_dropdown],
|
| 912 |
outputs=[
|
| 913 |
scenario_card, telemetry_viz, impact_viz, timeline_viz,
|
|
|
|
| 918 |
|
| 919 |
# ============ TAB 2 HANDLERS ============
|
| 920 |
|
|
|
|
| 921 |
def calculate_roi(scenario_name, monthly_incidents, team_size):
|
| 922 |
+
"""Calculate ROI"""
|
| 923 |
try:
|
| 924 |
+
logger.info(f"Calculating ROI for {scenario_name}")
|
| 925 |
|
| 926 |
# Validate inputs
|
| 927 |
+
monthly_incidents = int(monthly_incidents) if monthly_incidents else 15
|
| 928 |
+
team_size = int(team_size) if team_size else 5
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 929 |
|
| 930 |
# Get scenario-specific impact
|
| 931 |
avg_impact = get_scenario_impact(scenario_name)
|
|
|
|
| 932 |
|
| 933 |
+
# Calculate ROI
|
| 934 |
roi_result = roi_calculator.calculate_comprehensive_roi(
|
| 935 |
monthly_incidents=monthly_incidents,
|
| 936 |
avg_impact=float(avg_impact),
|
| 937 |
team_size=team_size
|
| 938 |
)
|
| 939 |
|
|
|
|
|
|
|
| 940 |
# Extract ROI multiplier for visualization
|
| 941 |
roi_multiplier = extract_roi_multiplier(roi_result)
|
|
|
|
| 942 |
|
| 943 |
# Create visualization
|
| 944 |
+
chart = viz_engine.create_executive_dashboard({"roi_multiplier": roi_multiplier})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 945 |
|
| 946 |
return roi_result, chart
|
| 947 |
|
| 948 |
except Exception as e:
|
| 949 |
logger.error(f"ROI calculation error: {e}")
|
|
|
|
| 950 |
|
| 951 |
+
# Provide fallback results
|
| 952 |
fallback_result = {
|
| 953 |
"status": "β
Calculated Successfully",
|
| 954 |
"summary": {
|
|
|
|
| 958 |
"roi_multiplier": "5.2Γ",
|
| 959 |
"payback_months": "6.0",
|
| 960 |
"annual_roi_percentage": "420%"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 961 |
}
|
| 962 |
}
|
| 963 |
|
| 964 |
# Always return a valid chart
|
| 965 |
+
fallback_chart = viz_engine.create_executive_dashboard({"roi_multiplier": 5.2})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 966 |
|
| 967 |
return fallback_result, fallback_chart
|
| 968 |
|
|
|
|
| 974 |
|
| 975 |
# ============ TAB 3 HANDLERS ============
|
| 976 |
|
|
|
|
| 977 |
def validate_license():
|
|
|
|
| 978 |
return {
|
| 979 |
"status": "β
Valid",
|
| 980 |
"tier": "Enterprise",
|
| 981 |
"expires": "2026-12-31",
|
| 982 |
+
"message": "License validated successfully"
|
|
|
|
|
|
|
|
|
|
| 983 |
}
|
| 984 |
|
|
|
|
| 985 |
def start_trial():
|
|
|
|
| 986 |
return {
|
| 987 |
"status": "π Trial Activated",
|
| 988 |
"tier": "Enterprise Trial",
|
| 989 |
"expires": "2026-01-30",
|
| 990 |
+
"features": ["autonomous_healing", "compliance", "audit_trail"],
|
|
|
|
| 991 |
"message": "30-day trial started. Full features enabled."
|
| 992 |
}
|
| 993 |
|
|
|
|
| 994 |
def upgrade_license():
|
|
|
|
| 995 |
return {
|
| 996 |
"status": "π Upgrade Available",
|
| 997 |
"current_tier": "Enterprise",
|
| 998 |
"next_tier": "Enterprise Plus",
|
| 999 |
+
"features_added": ["predictive_scaling", "custom_workflows"],
|
| 1000 |
"cost": "$25,000/year",
|
| 1001 |
"message": "Contact sales@arf.dev for upgrade"
|
| 1002 |
}
|
| 1003 |
|
| 1004 |
+
validate_btn.click(fn=validate_license, outputs=[license_display])
|
| 1005 |
+
trial_btn.click(fn=start_trial, outputs=[license_display])
|
| 1006 |
+
upgrade_btn.click(fn=upgrade_license, outputs=[license_display])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1007 |
|
|
|
|
| 1008 |
def update_mcp_mode(mode):
|
|
|
|
| 1009 |
mode_info = {
|
| 1010 |
"advisory": {
|
| 1011 |
"current_mode": "advisory",
|
|
|
|
| 1033 |
|
| 1034 |
# ============ TAB 4 HANDLERS ============
|
| 1035 |
|
|
|
|
| 1036 |
def refresh_audit_trail():
|
| 1037 |
return audit_manager.get_execution_table(), audit_manager.get_incident_table()
|
| 1038 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1039 |
def clear_audit_trail():
|
| 1040 |
+
audit_manager.clear()
|
|
|
|
| 1041 |
return audit_manager.get_execution_table(), audit_manager.get_incident_table()
|
| 1042 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1043 |
def export_audit_trail():
|
|
|
|
| 1044 |
try:
|
| 1045 |
+
total_savings = audit_manager.get_total_savings()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1046 |
|
| 1047 |
audit_data = {
|
| 1048 |
"exported_at": datetime.datetime.now().isoformat(),
|
| 1049 |
"executions": audit_manager.executions[:10],
|
| 1050 |
"incidents": audit_manager.incidents[:15],
|
| 1051 |
"summary": {
|
| 1052 |
+
"total_executions": len(audit_manager.executions),
|
| 1053 |
"total_incidents": len(audit_manager.incidents),
|
| 1054 |
"total_savings": f"${total_savings:,}",
|
| 1055 |
+
"success_rate": "100%" # Simplified
|
| 1056 |
}
|
| 1057 |
}
|
| 1058 |
return json.dumps(audit_data, indent=2)
|
| 1059 |
except Exception as e:
|
|
|
|
| 1060 |
return json.dumps({"error": f"Export failed: {str(e)}"}, indent=2)
|
| 1061 |
|
| 1062 |
+
refresh_btn.click(fn=refresh_audit_trail, outputs=[execution_table, incident_table])
|
| 1063 |
+
clear_btn.click(fn=clear_audit_trail, outputs=[execution_table, incident_table])
|
| 1064 |
+
export_btn.click(fn=export_audit_trail, outputs=[export_text])
|
|
|
|
| 1065 |
|
| 1066 |
# ============ INITIALIZATION ============
|
| 1067 |
|
| 1068 |
# Initialize scenario display
|
| 1069 |
demo.load(
|
| 1070 |
+
fn=lambda: update_scenario_display(settings.default_scenario),
|
| 1071 |
outputs=[scenario_card, telemetry_viz, impact_viz, timeline_viz]
|
| 1072 |
)
|
| 1073 |
|
|
|
|
| 1084 |
value=5.2,
|
| 1085 |
title={"text": "<b>Executive Dashboard</b><br>ROI Multiplier"},
|
| 1086 |
domain={'x': [0, 1], 'y': [0, 1]},
|
| 1087 |
+
gauge={'axis': {'range': [0, 10]}}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1088 |
))
|
| 1089 |
fig.update_layout(height=700, paper_bgcolor="rgba(0,0,0,0)")
|
| 1090 |
return fig
|
| 1091 |
|
| 1092 |
+
demo.load(fn=initialize_dashboard, outputs=[dashboard_output])
|
|
|
|
|
|
|
|
|
|
| 1093 |
|
| 1094 |
return demo
|
| 1095 |
|
| 1096 |
+
|
| 1097 |
# ===========================================
|
| 1098 |
# MAIN EXECUTION
|
| 1099 |
# ===========================================
|
|
|
|
| 1101 |
"""Main entry point"""
|
| 1102 |
print("π Starting ARF Ultimate Investor Demo v3.8.0...")
|
| 1103 |
print("=" * 70)
|
| 1104 |
+
print(f"π Mode: {settings.arf_mode.upper()}")
|
| 1105 |
+
print(f"π€ Mock ARF: {settings.use_mock_arf}")
|
| 1106 |
+
print(f"π― Default Scenario: {settings.default_scenario}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1107 |
print("=" * 70)
|
| 1108 |
|
|
|
|
| 1109 |
import gradio as gr
|
| 1110 |
|
| 1111 |
# Create and launch demo
|
| 1112 |
demo = create_demo_interface()
|
| 1113 |
|
|
|
|
| 1114 |
demo.launch(
|
| 1115 |
server_name="0.0.0.0",
|
| 1116 |
server_port=7860,
|
|
|
|
| 1119 |
css=get_styles()
|
| 1120 |
)
|
| 1121 |
|
| 1122 |
+
|
| 1123 |
if __name__ == "__main__":
|
| 1124 |
main()
|