petter2025 commited on
Commit
79db0ae
·
verified ·
1 Parent(s): 7e8b3f8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -30
app.py CHANGED
@@ -6,7 +6,7 @@ import traceback
6
  import os
7
  import torch
8
  import numpy as np
9
- import pandas as pd # <-- ADDED
10
  from datetime import datetime
11
 
12
  # ARF components
@@ -26,6 +26,20 @@ from iot_simulator import IoTSimulator
26
  from robotics_diagnostician import RoboticsDiagnostician
27
  from iot_event import IoTEvent
28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  # ----------------------------------------------------------------------
30
  # Logging setup
31
  # ----------------------------------------------------------------------
@@ -82,7 +96,7 @@ def generate_with_logprobs(prompt, max_new_tokens=100):
82
  # ----------------------------------------------------------------------
83
  # NLI detector
84
  # ----------------------------------------------------------------------
85
- nli_detector = NLIDetector() # Note: this file will be updated separately
86
 
87
  # ----------------------------------------------------------------------
88
  # Retrieval (sentence‑transformers + ChromaDB)
@@ -138,6 +152,25 @@ ai_risk_engine = AIRiskEngine()
138
  # ----------------------------------------------------------------------
139
  iot_sim = IoTSimulator()
140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  # ----------------------------------------------------------------------
142
  # Helper: update risk with feedback (global state – shared across users)
143
  # For per‑session risk, use gr.State instead of globals.
@@ -292,7 +325,6 @@ async def handle_audio(audio_file):
292
  logger.error(f"Audio task error: {e}")
293
  return {"error": str(e)}
294
 
295
- # MODIFIED: accept session state, return updated state and DataFrame
296
  async def read_iot_sensors(fault_type, history_state):
297
  """Read simulated IoT sensors, run diagnostics, predict failure, and return updated plot data."""
298
  global last_task_category
@@ -335,13 +367,53 @@ async def read_iot_sensors(fault_type, history_state):
335
  }
336
 
337
  # Prepare temperature history for plotting as DataFrame
338
- temp_history = [h['temperature'] for h in history_state[-20:]] # last 20 readings
339
  df = pd.DataFrame({
340
  "index": list(range(len(temp_history))),
341
  "temperature": temp_history
342
  })
343
 
344
- return data, diag_result, prediction, df, history_state # return updated state
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
345
 
346
  # ----------------------------------------------------------------------
347
  # Gradio UI
@@ -357,7 +429,7 @@ with gr.Blocks(title="ARF v4 – AI Reliability Lab", theme="soft") as demo:
357
  text_btn = gr.Button("Generate")
358
  text_output = gr.JSON(label="Analysis")
359
 
360
- # Tab 2: Image Generation (enhanced with steps slider)
361
  with gr.TabItem("Image Generation"):
362
  img_prompt = gr.Textbox(label="Prompt", value="A cat wearing a hat")
363
  img_steps = gr.Slider(1, 10, value=2, step=1, label="Inference Steps (higher = better quality, slower)")
@@ -367,16 +439,15 @@ with gr.Blocks(title="ARF v4 – AI Reliability Lab", theme="soft") as demo:
367
 
368
  # Tab 3: Audio Transcription
369
  with gr.TabItem("Audio Transcription"):
370
- # Add a sample audio button for quick testing
371
  gr.Markdown("Click the microphone to record, or upload a file. Try the sample: [Sample Audio](https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac)")
372
  audio_input = gr.Audio(type="filepath", label="Upload audio file")
373
  audio_btn = gr.Button("Transcribe")
374
  audio_output = gr.JSON(label="Analysis")
375
 
376
- # Tab 4: Robotics / IoT (enhanced with live plot)
377
  with gr.TabItem("Robotics / IoT"):
378
  gr.Markdown("### Simulated Robotic Arm Monitoring")
379
- iot_state = gr.State(value=[]) # per-session history state
380
 
381
  with gr.Row():
382
  with gr.Column():
@@ -394,37 +465,37 @@ with gr.Blocks(title="ARF v4 – AI Reliability Lab", theme="soft") as demo:
394
  with gr.Column():
395
  pred_display = gr.JSON(label="Failure Prediction")
396
  with gr.Row():
397
- with gr.Column(scale=1, min_width=600): # Controls width, height will be automatic
398
  temp_plot = gr.LinePlot(
399
  label="Temperature History (last 20 readings)",
400
  x="index",
401
  y="temperature"
402
  )
403
 
404
- # Tab 5: Enterprise Marketing and Sales
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
405
  with gr.TabItem("Enterprise"):
406
  gr.Markdown("""
407
  ## 🚀 ARF Enterprise – Governed Execution for Autonomous Infrastructure
408
-
409
- Take ARF to production with enterprise‑grade safety, compliance, and learning.
410
-
411
- ### Key Enterprise Features:
412
- - **Autonomous Execution** – Deterministic, policy‑controlled healing actions.
413
- - **Audit Trails & Compliance** – Full traceability for SOC2, HIPAA, GDPR.
414
- - **Learning Loops** – Models improve over time with your data.
415
- - **Multi‑Tenant Control** – Role‑based access and isolation.
416
- - **Cloud Integrations** – Azure, AWS, GCP native clients.
417
- - **24/7 Support & SLAs** – Enterprise‑grade reliability.
418
-
419
- ### Get Started
420
- - 📅 [Book a Demo](https://calendly.com/petter2025us/30min)
421
- - 📧 [Contact Sales](mailto:petter2025us@outlook.com)
422
- - 📄 [Download Datasheet](#) (coming soon)
423
-
424
- *Already using ARF OSS? Upgrade seamlessly – same core, governed execution.*
425
  """)
426
 
427
- # Feedback row (shared across all users – for demo purposes)
428
  with gr.Row():
429
  feedback_up = gr.Button("👍 Correct")
430
  feedback_down = gr.Button("👎 Incorrect")
@@ -446,12 +517,16 @@ with gr.Blocks(title="ARF v4 – AI Reliability Lab", theme="soft") as demo:
446
  inputs=audio_input,
447
  outputs=audio_output
448
  )
449
- # MODIFIED: include state as input and output
450
  refresh_btn.click(
451
  fn=lambda f, h: asyncio.run(read_iot_sensors(f, h)),
452
  inputs=[fault_type, iot_state],
453
  outputs=[sensor_display, diag_display, pred_display, temp_plot, iot_state]
454
  )
 
 
 
 
 
455
  feedback_up.click(fn=lambda: feedback(True), outputs=feedback_msg)
456
  feedback_down.click(fn=lambda: feedback(False), outputs=feedback_msg)
457
 
 
6
  import os
7
  import torch
8
  import numpy as np
9
+ import pandas as pd
10
  from datetime import datetime
11
 
12
  # ARF components
 
26
  from robotics_diagnostician import RoboticsDiagnostician
27
  from iot_event import IoTEvent
28
 
29
+ # ========== Infrastructure Reliability Imports (with fallbacks) ==========
30
+ INFRA_DEPS_AVAILABLE = False
31
+ try:
32
+ from infra_simulator import InfraSimulator
33
+ from infra_graph import InfraGraph
34
+ from bayesian_model import failure_model as pyro_model
35
+ from gnn_predictor import FailureGNN
36
+ from ontology_reasoner import InfraOntology
37
+ import problog
38
+ INFRA_DEPS_AVAILABLE = True
39
+ logger.info("Infrastructure reliability modules loaded.")
40
+ except ImportError as e:
41
+ logger.warning(f"Infrastructure modules not fully available: {e}. The Infrastructure tab will be disabled.")
42
+
43
  # ----------------------------------------------------------------------
44
  # Logging setup
45
  # ----------------------------------------------------------------------
 
96
  # ----------------------------------------------------------------------
97
  # NLI detector
98
  # ----------------------------------------------------------------------
99
+ nli_detector = NLIDetector()
100
 
101
  # ----------------------------------------------------------------------
102
  # Retrieval (sentence‑transformers + ChromaDB)
 
152
  # ----------------------------------------------------------------------
153
  iot_sim = IoTSimulator()
154
 
155
+ # ----------------------------------------------------------------------
156
+ # Infrastructure components (global, with fallback)
157
+ # ----------------------------------------------------------------------
158
+ if INFRA_DEPS_AVAILABLE:
159
+ # Use environment variables for Neo4j if provided, else mock
160
+ infra_sim = InfraSimulator()
161
+ infra_graph = InfraGraph(
162
+ uri=os.getenv("NEO4J_URI"),
163
+ user=os.getenv("NEO4J_USER"),
164
+ password=os.getenv("NEO4J_PASSWORD")
165
+ )
166
+ gnn_model = FailureGNN()
167
+ ontology = InfraOntology()
168
+ else:
169
+ infra_sim = None
170
+ infra_graph = None
171
+ gnn_model = None
172
+ ontology = None
173
+
174
  # ----------------------------------------------------------------------
175
  # Helper: update risk with feedback (global state – shared across users)
176
  # For per‑session risk, use gr.State instead of globals.
 
325
  logger.error(f"Audio task error: {e}")
326
  return {"error": str(e)}
327
 
 
328
  async def read_iot_sensors(fault_type, history_state):
329
  """Read simulated IoT sensors, run diagnostics, predict failure, and return updated plot data."""
330
  global last_task_category
 
367
  }
368
 
369
  # Prepare temperature history for plotting as DataFrame
370
+ temp_history = [h['temperature'] for h in history_state[-20:]]
371
  df = pd.DataFrame({
372
  "index": list(range(len(temp_history))),
373
  "temperature": temp_history
374
  })
375
 
376
+ return data, diag_result, prediction, df, history_state
377
+
378
+ # ========== NEW: Infrastructure Reliability Handler ==========
379
+ async def handle_infra(fault_type, session_state):
380
+ """Run infrastructure reliability analysis."""
381
+ if not INFRA_DEPS_AVAILABLE:
382
+ return {"error": "Infrastructure modules not installed (see logs)"}, session_state
383
+
384
+ # Create a new simulator per session (or reuse from state)
385
+ if "sim" not in session_state or session_state["sim"] is None:
386
+ session_state["sim"] = InfraSimulator()
387
+ sim = session_state["sim"]
388
+
389
+ # Inject fault
390
+ sim.set_fault(fault_type if fault_type != "none" else None)
391
+ components = sim.read_state()
392
+
393
+ # Update graph
394
+ infra_graph.update_from_state(components)
395
+
396
+ # Run Bayesian inference (mock for now; in reality would use Pyro)
397
+ bayesian_risk = {"switch_failure": 0.1, "server_failure": 0.05}
398
+
399
+ # Run GNN prediction (mock if PyG not available)
400
+ predictions = {"at_risk": ["server-1"] if fault_type != "none" else []}
401
+
402
+ # Run ProbLog (via python-problog)
403
+ logic_explanations = "ProbLog output: ..." # Replace with actual ProbLog call
404
+
405
+ # Ontology reasoning
406
+ ontology_result = ontology.classify("server") if ontology else {"inferred": [], "consistent": True}
407
+
408
+ # Combine results
409
+ output = {
410
+ "topology": components,
411
+ "bayesian_risk": bayesian_risk,
412
+ "gnn_predictions": predictions,
413
+ "logic_explanations": logic_explanations,
414
+ "ontology": ontology_result
415
+ }
416
+ return output, session_state
417
 
418
  # ----------------------------------------------------------------------
419
  # Gradio UI
 
429
  text_btn = gr.Button("Generate")
430
  text_output = gr.JSON(label="Analysis")
431
 
432
+ # Tab 2: Image Generation
433
  with gr.TabItem("Image Generation"):
434
  img_prompt = gr.Textbox(label="Prompt", value="A cat wearing a hat")
435
  img_steps = gr.Slider(1, 10, value=2, step=1, label="Inference Steps (higher = better quality, slower)")
 
439
 
440
  # Tab 3: Audio Transcription
441
  with gr.TabItem("Audio Transcription"):
 
442
  gr.Markdown("Click the microphone to record, or upload a file. Try the sample: [Sample Audio](https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac)")
443
  audio_input = gr.Audio(type="filepath", label="Upload audio file")
444
  audio_btn = gr.Button("Transcribe")
445
  audio_output = gr.JSON(label="Analysis")
446
 
447
+ # Tab 4: Robotics / IoT
448
  with gr.TabItem("Robotics / IoT"):
449
  gr.Markdown("### Simulated Robotic Arm Monitoring")
450
+ iot_state = gr.State(value=[])
451
 
452
  with gr.Row():
453
  with gr.Column():
 
465
  with gr.Column():
466
  pred_display = gr.JSON(label="Failure Prediction")
467
  with gr.Row():
468
+ with gr.Column(scale=1, min_width=600):
469
  temp_plot = gr.LinePlot(
470
  label="Temperature History (last 20 readings)",
471
  x="index",
472
  y="temperature"
473
  )
474
 
475
+ # ========== NEW: Infrastructure Reliability Tab ==========
476
+ with gr.TabItem("Infrastructure Reliability"):
477
+ gr.Markdown("### Neuro‑Symbolic Infrastructure Monitoring (Bayesian + Graph + Logic)")
478
+ infra_state = gr.State(value={}) # per‑session state
479
+
480
+ with gr.Row():
481
+ with gr.Column():
482
+ infra_fault = gr.Dropdown(
483
+ ["none", "switch_down", "server_overload", "cascade"],
484
+ value="none",
485
+ label="Inject Fault"
486
+ )
487
+ infra_btn = gr.Button("Run Analysis")
488
+ with gr.Column():
489
+ infra_output = gr.JSON(label="Analysis Results")
490
+
491
+ # Tab 5: Enterprise
492
  with gr.TabItem("Enterprise"):
493
  gr.Markdown("""
494
  ## 🚀 ARF Enterprise – Governed Execution for Autonomous Infrastructure
495
+ ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
496
  """)
497
 
498
+ # Feedback row
499
  with gr.Row():
500
  feedback_up = gr.Button("👍 Correct")
501
  feedback_down = gr.Button("👎 Incorrect")
 
517
  inputs=audio_input,
518
  outputs=audio_output
519
  )
 
520
  refresh_btn.click(
521
  fn=lambda f, h: asyncio.run(read_iot_sensors(f, h)),
522
  inputs=[fault_type, iot_state],
523
  outputs=[sensor_display, diag_display, pred_display, temp_plot, iot_state]
524
  )
525
+ infra_btn.click(
526
+ fn=lambda f, s: asyncio.run(handle_infra(f, s)),
527
+ inputs=[infra_fault, infra_state],
528
+ outputs=[infra_output, infra_state]
529
+ )
530
  feedback_up.click(fn=lambda: feedback(True), outputs=feedback_msg)
531
  feedback_down.click(fn=lambda: feedback(False), outputs=feedback_msg)
532