petter2025 commited on
Commit
e01d8b4
·
verified ·
1 Parent(s): 7956bb0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -15
app.py CHANGED
@@ -6,6 +6,7 @@ import traceback
6
  import os
7
  import torch
8
  import numpy as np
 
9
  from datetime import datetime
10
 
11
  # ARF components
@@ -81,7 +82,7 @@ def generate_with_logprobs(prompt, max_new_tokens=100):
81
  # ----------------------------------------------------------------------
82
  # NLI detector
83
  # ----------------------------------------------------------------------
84
- nli_detector = NLIDetector()
85
 
86
  # ----------------------------------------------------------------------
87
  # Retrieval (sentence‑transformers + ChromaDB)
@@ -136,7 +137,6 @@ ai_risk_engine = AIRiskEngine()
136
  # IoT simulator
137
  # ----------------------------------------------------------------------
138
  iot_sim = IoTSimulator()
139
- iot_history = [] # store recent readings for prediction
140
 
141
  # ----------------------------------------------------------------------
142
  # Helper: update risk with feedback (global state – shared across users)
@@ -292,15 +292,16 @@ async def handle_audio(audio_file):
292
  logger.error(f"Audio task error: {e}")
293
  return {"error": str(e)}
294
 
295
- async def read_iot_sensors(fault_type):
 
296
  """Read simulated IoT sensors, run diagnostics, predict failure, and return updated plot data."""
297
- global last_task_category, iot_history
298
  last_task_category = "iot"
299
  iot_sim.set_fault(fault_type if fault_type != "none" else None)
300
  data = iot_sim.read()
301
- iot_history.append(data)
302
- if len(iot_history) > 100:
303
- iot_history.pop(0)
304
 
305
  # Create IoTEvent with valid component name
306
  event = IoTEvent(
@@ -321,8 +322,8 @@ async def read_iot_sensors(fault_type):
321
 
322
  # Simple failure prediction
323
  prediction = None
324
- if len(iot_history) >= 5:
325
- temps = [h['temperature'] for h in iot_history[-5:]]
326
  x = np.arange(len(temps))
327
  slope, intercept = np.polyfit(x, temps, 1)
328
  next_temp = slope * len(temps) + intercept
@@ -333,9 +334,14 @@ async def read_iot_sensors(fault_type):
333
  "time_to_overheat_min": time_to_threshold
334
  }
335
 
336
- # Prepare temperature history for plotting
337
- temp_history = [h['temperature'] for h in iot_history[-20:]] # last 20 readings
338
- return data, diag_result, prediction, temp_history
 
 
 
 
 
339
 
340
  # ----------------------------------------------------------------------
341
  # Gradio UI
@@ -370,6 +376,8 @@ with gr.Blocks(title="ARF v4 – AI Reliability Lab", theme="soft") as demo:
370
  # Tab 4: Robotics / IoT (enhanced with live plot)
371
  with gr.TabItem("Robotics / IoT"):
372
  gr.Markdown("### Simulated Robotic Arm Monitoring")
 
 
373
  with gr.Row():
374
  with gr.Column():
375
  fault_type = gr.Dropdown(
@@ -438,10 +446,11 @@ with gr.Blocks(title="ARF v4 – AI Reliability Lab", theme="soft") as demo:
438
  inputs=audio_input,
439
  outputs=audio_output
440
  )
 
441
  refresh_btn.click(
442
- fn=lambda f: asyncio.run(read_iot_sensors(f)),
443
- inputs=fault_type,
444
- outputs=[sensor_display, diag_display, pred_display, temp_plot]
445
  )
446
  feedback_up.click(fn=lambda: feedback(True), outputs=feedback_msg)
447
  feedback_down.click(fn=lambda: feedback(False), outputs=feedback_msg)
 
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
 
82
  # ----------------------------------------------------------------------
83
  # NLI detector
84
  # ----------------------------------------------------------------------
85
+ nli_detector = NLIDetector() # Note: this file will be updated separately
86
 
87
  # ----------------------------------------------------------------------
88
  # Retrieval (sentence‑transformers + ChromaDB)
 
137
  # IoT simulator
138
  # ----------------------------------------------------------------------
139
  iot_sim = IoTSimulator()
 
140
 
141
  # ----------------------------------------------------------------------
142
  # Helper: update risk with feedback (global state – shared across users)
 
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
299
  last_task_category = "iot"
300
  iot_sim.set_fault(fault_type if fault_type != "none" else None)
301
  data = iot_sim.read()
302
+ history_state.append(data)
303
+ if len(history_state) > 100:
304
+ history_state.pop(0)
305
 
306
  # Create IoTEvent with valid component name
307
  event = IoTEvent(
 
322
 
323
  # Simple failure prediction
324
  prediction = None
325
+ if len(history_state) >= 5:
326
+ temps = [h['temperature'] for h in history_state[-5:]]
327
  x = np.arange(len(temps))
328
  slope, intercept = np.polyfit(x, temps, 1)
329
  next_temp = slope * len(temps) + intercept
 
334
  "time_to_overheat_min": time_to_threshold
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
 
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():
383
  fault_type = gr.Dropdown(
 
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)