Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -10,6 +10,12 @@ import pandas as pd
|
|
| 10 |
from datetime import datetime
|
| 11 |
from typing import Dict, Any, List, Optional
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
# ----------------------------------------------------------------------
|
| 14 |
# Logging setup
|
| 15 |
# ----------------------------------------------------------------------
|
|
@@ -34,6 +40,9 @@ from iot_simulator import IoTSimulator
|
|
| 34 |
from robotics_diagnostician import RoboticsDiagnostician
|
| 35 |
from iot_event import IoTEvent
|
| 36 |
|
|
|
|
|
|
|
|
|
|
| 37 |
# ========== Infrastructure Reliability Imports (with fallbacks) ==========
|
| 38 |
INFRA_DEPS_AVAILABLE = False
|
| 39 |
try:
|
|
@@ -150,10 +159,15 @@ audio_quality_detector = AudioQualityDetector()
|
|
| 150 |
robotics_diagnostician = RoboticsDiagnostician()
|
| 151 |
|
| 152 |
# ----------------------------------------------------------------------
|
| 153 |
-
# Bayesian risk engine
|
| 154 |
# ----------------------------------------------------------------------
|
| 155 |
ai_risk_engine = AIRiskEngine()
|
| 156 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
# ----------------------------------------------------------------------
|
| 158 |
# IoT simulator
|
| 159 |
# ----------------------------------------------------------------------
|
|
@@ -177,6 +191,19 @@ else:
|
|
| 177 |
gnn_model = None
|
| 178 |
ontology = None
|
| 179 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
# ========== Execution Governance Functions ==========
|
| 181 |
|
| 182 |
def evaluate_policies(event_type: str, severity: str, component: str) -> Dict[str, Any]:
|
|
@@ -250,11 +277,12 @@ def autonomous_control_decision(analysis_result: Dict[str, Any], risk_threshold:
|
|
| 250 |
logger.error(f"Control decision error: {e}")
|
| 251 |
decision["reason"] = f"Error in decision process: {str(e)}"
|
| 252 |
|
|
|
|
| 253 |
return decision
|
| 254 |
|
| 255 |
# ========== Async Handlers with Governance ==========
|
| 256 |
|
| 257 |
-
async def handle_text(task_type, prompt):
|
| 258 |
"""Handle text generation with governance and control plane decisions."""
|
| 259 |
global last_task_category
|
| 260 |
last_task_category = task_type
|
|
@@ -291,7 +319,7 @@ async def handle_text(task_type, prompt):
|
|
| 291 |
|
| 292 |
# Run analysis
|
| 293 |
hallu_result = await hallucination_detective.analyze(event)
|
| 294 |
-
drift_result = await memory_drift_diagnostician.analyze(event)
|
| 295 |
risk_metrics = ai_risk_engine.risk_score(task_type)
|
| 296 |
|
| 297 |
# Combine results
|
|
@@ -333,7 +361,7 @@ async def handle_text(task_type, prompt):
|
|
| 333 |
}
|
| 334 |
}
|
| 335 |
|
| 336 |
-
async def handle_infra_with_governance(fault_type, session_state):
|
| 337 |
"""Infrastructure analysis with execution governance."""
|
| 338 |
if not INFRA_DEPS_AVAILABLE:
|
| 339 |
return {
|
|
@@ -399,6 +427,63 @@ async def handle_infra_with_governance(fault_type, session_state):
|
|
| 399 |
"governance": evaluate_policies("infrastructure", "critical", "system")
|
| 400 |
}, session_state
|
| 401 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 402 |
# ----------------------------------------------------------------------
|
| 403 |
# Gradio UI with Governance Focus
|
| 404 |
# ----------------------------------------------------------------------
|
|
@@ -411,9 +496,13 @@ with gr.Blocks(title="ARF v4 – Autonomous AI Control Plane", theme="soft") as
|
|
| 411 |
- **Policy‑based Governance** – Automatic evaluation and enforcement
|
| 412 |
- **Autonomous Control Decisions** – AI-driven remediation actions
|
| 413 |
- **Neuro‑Symbolic Reasoning** – Combining neural networks with symbolic logic
|
| 414 |
-
- **Real‑time Risk Assessment** – Bayesian online learning
|
|
|
|
| 415 |
""")
|
| 416 |
|
|
|
|
|
|
|
|
|
|
| 417 |
with gr.Tabs():
|
| 418 |
# Tab 1: Control Plane Dashboard
|
| 419 |
with gr.TabItem("Control Plane Dashboard"):
|
|
@@ -433,9 +522,19 @@ with gr.Blocks(title="ARF v4 – Autonomous AI Control Plane", theme="soft") as
|
|
| 433 |
"blocked_actions": 0,
|
| 434 |
"average_risk": 0.5
|
| 435 |
})
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 439 |
|
| 440 |
# Tab 2: Text Generation with Governance
|
| 441 |
with gr.TabItem("Text Generation"):
|
|
@@ -461,7 +560,21 @@ with gr.Blocks(title="ARF v4 – Autonomous AI Control Plane", theme="soft") as
|
|
| 461 |
with gr.Column():
|
| 462 |
infra_output = gr.JSON(label="Analysis with Control Decisions")
|
| 463 |
|
| 464 |
-
# Tab 4:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 465 |
with gr.TabItem("Policy Management"):
|
| 466 |
gr.Markdown("### 📋 Execution Policies")
|
| 467 |
policies = gr.JSON(label="Active Policies", value=[
|
|
@@ -502,7 +615,7 @@ with gr.Blocks(title="ARF v4 – Autonomous AI Control Plane", theme="soft") as
|
|
| 502 |
}
|
| 503 |
])
|
| 504 |
|
| 505 |
-
# Tab
|
| 506 |
with gr.TabItem("Enterprise"):
|
| 507 |
gr.Markdown("""
|
| 508 |
## 🚀 ARF Enterprise – Autonomous Control Plane for Critical Infrastructure
|
|
@@ -528,17 +641,23 @@ with gr.Blocks(title="ARF v4 – Autonomous AI Control Plane", theme="soft") as
|
|
| 528 |
|
| 529 |
# Wire events
|
| 530 |
text_btn.click(
|
| 531 |
-
fn=lambda task, p: asyncio.run(handle_text(task, p)),
|
| 532 |
-
inputs=[text_task, text_prompt],
|
| 533 |
outputs=text_output
|
| 534 |
)
|
| 535 |
|
| 536 |
infra_btn.click(
|
| 537 |
-
fn=lambda f, s: asyncio.run(handle_infra_with_governance(f, s)),
|
| 538 |
-
inputs=[infra_fault, infra_state],
|
| 539 |
outputs=[infra_output, infra_state]
|
| 540 |
)
|
| 541 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 542 |
def handle_control_feedback(approved: bool):
|
| 543 |
global last_task_category
|
| 544 |
if last_task_category is None:
|
|
|
|
| 10 |
from datetime import datetime
|
| 11 |
from typing import Dict, Any, List, Optional
|
| 12 |
|
| 13 |
+
# ----------------------------------------------------------------------
|
| 14 |
+
# Plotly for dashboards
|
| 15 |
+
# ----------------------------------------------------------------------
|
| 16 |
+
import plotly.graph_objects as go
|
| 17 |
+
from plotly.subplots import make_subplots
|
| 18 |
+
|
| 19 |
# ----------------------------------------------------------------------
|
| 20 |
# Logging setup
|
| 21 |
# ----------------------------------------------------------------------
|
|
|
|
| 40 |
from robotics_diagnostician import RoboticsDiagnostician
|
| 41 |
from iot_event import IoTEvent
|
| 42 |
|
| 43 |
+
# ========== Advanced Inference (HMC) ==========
|
| 44 |
+
from advanced_inference import HMCAnalyzer
|
| 45 |
+
|
| 46 |
# ========== Infrastructure Reliability Imports (with fallbacks) ==========
|
| 47 |
INFRA_DEPS_AVAILABLE = False
|
| 48 |
try:
|
|
|
|
| 159 |
robotics_diagnostician = RoboticsDiagnostician()
|
| 160 |
|
| 161 |
# ----------------------------------------------------------------------
|
| 162 |
+
# Bayesian risk engine (now with hyperpriors)
|
| 163 |
# ----------------------------------------------------------------------
|
| 164 |
ai_risk_engine = AIRiskEngine()
|
| 165 |
|
| 166 |
+
# ----------------------------------------------------------------------
|
| 167 |
+
# HMC analyzer
|
| 168 |
+
# ----------------------------------------------------------------------
|
| 169 |
+
hmc_analyzer = HMCAnalyzer()
|
| 170 |
+
|
| 171 |
# ----------------------------------------------------------------------
|
| 172 |
# IoT simulator
|
| 173 |
# ----------------------------------------------------------------------
|
|
|
|
| 191 |
gnn_model = None
|
| 192 |
ontology = None
|
| 193 |
|
| 194 |
+
# ========== Global History for Dashboard ==========
|
| 195 |
+
decision_history = [] # list of (timestamp, decision, category)
|
| 196 |
+
risk_history = [] # list of (timestamp, mean_risk)
|
| 197 |
+
|
| 198 |
+
def update_dashboard_data(decision: Dict, risk: float):
|
| 199 |
+
decision_history.append((datetime.utcnow().isoformat(), decision, risk))
|
| 200 |
+
risk_history.append((datetime.utcnow().isoformat(), risk))
|
| 201 |
+
# Keep only last 100
|
| 202 |
+
if len(decision_history) > 100:
|
| 203 |
+
decision_history.pop(0)
|
| 204 |
+
if len(risk_history) > 100:
|
| 205 |
+
risk_history.pop(0)
|
| 206 |
+
|
| 207 |
# ========== Execution Governance Functions ==========
|
| 208 |
|
| 209 |
def evaluate_policies(event_type: str, severity: str, component: str) -> Dict[str, Any]:
|
|
|
|
| 277 |
logger.error(f"Control decision error: {e}")
|
| 278 |
decision["reason"] = f"Error in decision process: {str(e)}"
|
| 279 |
|
| 280 |
+
update_dashboard_data(decision, analysis_result.get("risk_metrics", {}).get("mean", 0.5))
|
| 281 |
return decision
|
| 282 |
|
| 283 |
# ========== Async Handlers with Governance ==========
|
| 284 |
|
| 285 |
+
async def handle_text(task_type, prompt, context_window):
|
| 286 |
"""Handle text generation with governance and control plane decisions."""
|
| 287 |
global last_task_category
|
| 288 |
last_task_category = task_type
|
|
|
|
| 319 |
|
| 320 |
# Run analysis
|
| 321 |
hallu_result = await hallucination_detective.analyze(event)
|
| 322 |
+
drift_result = await memory_drift_diagnostician.analyze(event, context_window)
|
| 323 |
risk_metrics = ai_risk_engine.risk_score(task_type)
|
| 324 |
|
| 325 |
# Combine results
|
|
|
|
| 361 |
}
|
| 362 |
}
|
| 363 |
|
| 364 |
+
async def handle_infra_with_governance(fault_type, context_window, session_state):
|
| 365 |
"""Infrastructure analysis with execution governance."""
|
| 366 |
if not INFRA_DEPS_AVAILABLE:
|
| 367 |
return {
|
|
|
|
| 427 |
"governance": evaluate_policies("infrastructure", "critical", "system")
|
| 428 |
}, session_state
|
| 429 |
|
| 430 |
+
# ========== HMC Handler ==========
|
| 431 |
+
def run_hmc(samples, warmup):
|
| 432 |
+
summary = hmc_analyzer.run_inference(num_samples=samples, warmup=warmup)
|
| 433 |
+
trace_data = hmc_analyzer.get_trace_data()
|
| 434 |
+
fig_trace, fig_pair = None, None
|
| 435 |
+
if trace_data:
|
| 436 |
+
# Trace plot
|
| 437 |
+
fig_trace = go.Figure()
|
| 438 |
+
for key, vals in trace_data.items():
|
| 439 |
+
fig_trace.add_trace(go.Scatter(y=vals, mode='lines', name=key))
|
| 440 |
+
fig_trace.update_layout(title="Posterior Traces", xaxis_title="Sample", yaxis_title="Value")
|
| 441 |
+
|
| 442 |
+
# Pair plot (simplified scatter matrix)
|
| 443 |
+
df = pd.DataFrame(trace_data)
|
| 444 |
+
fig_pair = go.Figure(data=go.Splom(
|
| 445 |
+
dimensions=[dict(label=k, values=df[k]) for k in df.columns],
|
| 446 |
+
showupperhalf=False
|
| 447 |
+
))
|
| 448 |
+
fig_pair.update_layout(title="Posterior Pair Plot")
|
| 449 |
+
return summary, fig_trace, fig_pair
|
| 450 |
+
|
| 451 |
+
# ========== Dashboard Plot Generators ==========
|
| 452 |
+
def generate_risk_gauge():
|
| 453 |
+
if not risk_history:
|
| 454 |
+
return go.Figure()
|
| 455 |
+
latest_risk = risk_history[-1][1]
|
| 456 |
+
fig = go.Figure(go.Indicator(
|
| 457 |
+
mode="gauge+number",
|
| 458 |
+
value=latest_risk,
|
| 459 |
+
title={'text': "Current Risk"},
|
| 460 |
+
gauge={'axis': {'range': [0, 1]},
|
| 461 |
+
'bar': {'color': "darkblue"},
|
| 462 |
+
'steps': [
|
| 463 |
+
{'range': [0, 0.3], 'color': "lightgreen"},
|
| 464 |
+
{'range': [0.3, 0.7], 'color': "yellow"},
|
| 465 |
+
{'range': [0.7, 1], 'color': "red"}]}))
|
| 466 |
+
return fig
|
| 467 |
+
|
| 468 |
+
def generate_decision_pie():
|
| 469 |
+
if not decision_history:
|
| 470 |
+
return go.Figure()
|
| 471 |
+
approved = sum(1 for _, d, _ in decision_history if d.get("approved", False))
|
| 472 |
+
blocked = len(decision_history) - approved
|
| 473 |
+
fig = go.Figure(data=[go.Pie(labels=["Approved", "Blocked"], values=[approved, blocked])])
|
| 474 |
+
fig.update_layout(title="Policy Decisions")
|
| 475 |
+
return fig
|
| 476 |
+
|
| 477 |
+
def generate_action_timeline():
|
| 478 |
+
if not decision_history:
|
| 479 |
+
return go.Figure()
|
| 480 |
+
times = [d["timestamp"] for _, d, _ in decision_history]
|
| 481 |
+
approvals = [1 if d.get("approved", False) else 0 for _, d, _ in decision_history]
|
| 482 |
+
fig = go.Figure()
|
| 483 |
+
fig.add_trace(go.Scatter(x=times, y=approvals, mode='markers+lines', name='Approvals'))
|
| 484 |
+
fig.update_layout(title="Autonomous Actions Timeline", xaxis_title="Time", yaxis_title="Approved (1) / Blocked (0)")
|
| 485 |
+
return fig
|
| 486 |
+
|
| 487 |
# ----------------------------------------------------------------------
|
| 488 |
# Gradio UI with Governance Focus
|
| 489 |
# ----------------------------------------------------------------------
|
|
|
|
| 496 |
- **Policy‑based Governance** – Automatic evaluation and enforcement
|
| 497 |
- **Autonomous Control Decisions** – AI-driven remediation actions
|
| 498 |
- **Neuro‑Symbolic Reasoning** – Combining neural networks with symbolic logic
|
| 499 |
+
- **Real‑time Risk Assessment** – Bayesian online learning with hyperpriors
|
| 500 |
+
- **Hamiltonian Monte Carlo** – Offline deep pattern discovery
|
| 501 |
""")
|
| 502 |
|
| 503 |
+
# Historic Context Window (shared across tabs)
|
| 504 |
+
context_window_slider = gr.Slider(1, 200, value=50, step=1, label="Historic Context Window (readings)")
|
| 505 |
+
|
| 506 |
with gr.Tabs():
|
| 507 |
# Tab 1: Control Plane Dashboard
|
| 508 |
with gr.TabItem("Control Plane Dashboard"):
|
|
|
|
| 522 |
"blocked_actions": 0,
|
| 523 |
"average_risk": 0.5
|
| 524 |
})
|
| 525 |
+
with gr.Row():
|
| 526 |
+
risk_gauge = gr.Plot(label="Current Risk Gauge")
|
| 527 |
+
decision_pie = gr.Plot(label="Policy Decisions")
|
| 528 |
+
with gr.Row():
|
| 529 |
+
action_timeline = gr.Plot(label="Autonomous Actions Timeline")
|
| 530 |
+
with gr.Row():
|
| 531 |
+
health_score = gr.Number(label="System Health Score", value=85, precision=0)
|
| 532 |
+
# Refresh button for dashboard
|
| 533 |
+
refresh_dash_btn = gr.Button("Refresh Dashboard")
|
| 534 |
+
refresh_dash_btn.click(
|
| 535 |
+
fn=lambda: (generate_risk_gauge(), generate_decision_pie(), generate_action_timeline()),
|
| 536 |
+
outputs=[risk_gauge, decision_pie, action_timeline]
|
| 537 |
+
)
|
| 538 |
|
| 539 |
# Tab 2: Text Generation with Governance
|
| 540 |
with gr.TabItem("Text Generation"):
|
|
|
|
| 560 |
with gr.Column():
|
| 561 |
infra_output = gr.JSON(label="Analysis with Control Decisions")
|
| 562 |
|
| 563 |
+
# Tab 4: Deep Analysis (HMC)
|
| 564 |
+
with gr.TabItem("Deep Analysis (HMC)"):
|
| 565 |
+
gr.Markdown("### Hamiltonian Monte Carlo – Offline Pattern Discovery")
|
| 566 |
+
with gr.Row():
|
| 567 |
+
with gr.Column():
|
| 568 |
+
hmc_samples = gr.Slider(100, 2000, value=500, step=100, label="Number of Samples")
|
| 569 |
+
hmc_warmup = gr.Slider(50, 500, value=200, step=50, label="Warmup Steps")
|
| 570 |
+
hmc_run_btn = gr.Button("Run HMC")
|
| 571 |
+
with gr.Column():
|
| 572 |
+
hmc_summary = gr.JSON(label="Posterior Summary")
|
| 573 |
+
with gr.Row():
|
| 574 |
+
hmc_trace_plot = gr.Plot(label="Trace Plot")
|
| 575 |
+
hmc_pair_plot = gr.Plot(label="Pair Plot")
|
| 576 |
+
|
| 577 |
+
# Tab 5: Policy Management
|
| 578 |
with gr.TabItem("Policy Management"):
|
| 579 |
gr.Markdown("### 📋 Execution Policies")
|
| 580 |
policies = gr.JSON(label="Active Policies", value=[
|
|
|
|
| 615 |
}
|
| 616 |
])
|
| 617 |
|
| 618 |
+
# Tab 6: Enterprise
|
| 619 |
with gr.TabItem("Enterprise"):
|
| 620 |
gr.Markdown("""
|
| 621 |
## 🚀 ARF Enterprise – Autonomous Control Plane for Critical Infrastructure
|
|
|
|
| 641 |
|
| 642 |
# Wire events
|
| 643 |
text_btn.click(
|
| 644 |
+
fn=lambda task, p, w: asyncio.run(handle_text(task, p, w)),
|
| 645 |
+
inputs=[text_task, text_prompt, context_window_slider],
|
| 646 |
outputs=text_output
|
| 647 |
)
|
| 648 |
|
| 649 |
infra_btn.click(
|
| 650 |
+
fn=lambda f, w, s: asyncio.run(handle_infra_with_governance(f, w, s)),
|
| 651 |
+
inputs=[infra_fault, context_window_slider, infra_state],
|
| 652 |
outputs=[infra_output, infra_state]
|
| 653 |
)
|
| 654 |
|
| 655 |
+
hmc_run_btn.click(
|
| 656 |
+
fn=run_hmc,
|
| 657 |
+
inputs=[hmc_samples, hmc_warmup],
|
| 658 |
+
outputs=[hmc_summary, hmc_trace_plot, hmc_pair_plot]
|
| 659 |
+
)
|
| 660 |
+
|
| 661 |
def handle_control_feedback(approved: bool):
|
| 662 |
global last_task_category
|
| 663 |
if last_task_category is None:
|