import os import json import numpy as np import gradio as gr from sklearn.ensemble import IsolationForest from dotenv import load_dotenv from datetime import datetime import time import threading # Load environment variables (optional) load_dotenv(override=True) # === Anomaly Detection Model === class AnomalyDetector: def __init__(self): # Train with realistic "normal" ranges normal_temp = np.random.normal(loc=50, scale=5, size=(200, 1)) normal_vibration = np.random.normal(loc=5, scale=1, size=(200, 1)) normal_pressure = np.random.normal(loc=100, scale=10, size=(200, 1)) normal_data = np.hstack([normal_temp, normal_vibration, normal_pressure]) self.model = IsolationForest(n_estimators=100, contamination=0.05, random_state=42) self.model.fit(normal_data) def is_anomaly(self, temp, vibration, pressure): X = np.array([[temp, vibration, pressure]]) return self.model.predict(X)[0] == -1 detector = AnomalyDetector() # === Logging Function === def log_event(data, anomaly): log_entry = { "data": data, "anomaly": "true" if anomaly else "false", # store as string "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S") } try: with open("maintenance_log.json", "a") as f: f.write(json.dumps(log_entry) + "\n") except Exception as e: print(f"[ERROR] Failed to write log: {e}") # === Generate Random Sensor Data === def get_random_sensor_data(): temp = round(np.random.normal(50, 5), 2) vibration = round(np.random.normal(5, 1), 2) pressure = round(np.random.normal(100, 10), 2) return temp, vibration, pressure # === Core Detection Logic === def detect_anomaly(temp, vibration, pressure): sensor_data = {"temp": temp, "vibration": vibration, "pressure": pressure} anomaly = detector.is_anomaly(temp, vibration, pressure) log_event(sensor_data, anomaly) if anomaly: return f"🚨 Anomaly Detected!\nTemp: {temp}, Vibration: {vibration}, Pressure: {pressure}" else: return f"✅ Normal Data: {sensor_data}" # === Live Update Generator for Gradio Live Feed === def live_feed(): while True: temp, vibration, pressure = get_random_sensor_data() result = detect_anomaly(temp, vibration, pressure) yield result time.sleep(3) # update every 3 seconds # === Gradio UI === with gr.Blocks(title="Maintenance & Fault Detection AI") as demo: gr.Markdown("# 🏗 Maintenance & Fault Detection Agent — Live Feed") gr.Markdown("This AI monitors sensor readings in real time and flags anomalies automatically.") output = gr.Textbox(label="Live Monitoring Output", lines=6) # Button for manual detection with gr.Row(): temp_in = gr.Number(label="Temperature (Manual Input)", value=50) vib_in = gr.Number(label="Vibration (Manual Input)", value=5) pres_in = gr.Number(label="Pressure (Manual Input)", value=100) manual_btn = gr.Button("Run Manual Detection") manual_btn.click(detect_anomaly, inputs=[temp_in, vib_in, pres_in], outputs=output) # Live feed updates automatically live = gr.Textbox(label="Automatic Live Feed", lines=6) gr.Markdown("### 🔴 Live Updates (refresh every 3s)") live_stream = gr.Textbox(value=live_feed, label="Live Sensor Data Feed", lines=6) demo.launch()