import json from datetime import datetime from pathlib import Path import joblib import pandas as pd import streamlit as st import torch from transformers import AutoModelForCausalLM, AutoTokenizer # ============================================================ # APP CONFIGURATION # ============================================================ st.set_page_config( page_title="Intelligent Predictive Maintenance System", page_icon="🏭", layout="wide", ) MODEL_PATH = Path(__file__).parent / "predictive_maintenance_rf_pipeline.pkl" LLM_MODEL_ID = "Qwen/Qwen2.5-0.5B-Instruct" FAILURE_THRESHOLD = 0.50 MEDIUM_RISK_THRESHOLD = 0.40 HIGH_RISK_THRESHOLD = 0.70 # ============================================================ # LIGHT UI STYLING # ============================================================ st.markdown( """ """, unsafe_allow_html=True, ) # ============================================================ # LOAD TRAINED RANDOM FOREST PIPELINE # ============================================================ @st.cache_resource def load_predictive_model(): return joblib.load(MODEL_PATH) # ============================================================ # LOAD LOCAL QWEN MODEL # ============================================================ @st.cache_resource def load_reasoning_model(): device = "cuda" if torch.cuda.is_available() else "cpu" tokenizer = AutoTokenizer.from_pretrained( LLM_MODEL_ID ) model = AutoModelForCausalLM.from_pretrained( LLM_MODEL_ID, torch_dtype=torch.float16 if device == "cuda" else torch.float32, low_cpu_mem_usage=True, ) model.to(device) model.eval() return tokenizer, model, device # ============================================================ # AGENT 1 — IoT DATA AGENT # ============================================================ def iot_data_agent( product_type, air_temperature, process_temperature, rotational_speed, torque, tool_wear, ): """ Validates and packages incoming IoT-style machine readings. """ errors = [] if product_type not in {"L", "M", "H"}: errors.append("Product Type must be L, M or H.") if air_temperature <= 0: errors.append("Air temperature must be greater than 0 K.") if process_temperature <= 0: errors.append("Process temperature must be greater than 0 K.") if rotational_speed <= 0: errors.append("Rotational speed must be greater than 0 rpm.") if torque < 0: errors.append("Torque cannot be negative.") if tool_wear < 0: errors.append("Tool wear cannot be negative.") if errors: return None, errors sensor_record = pd.DataFrame( [ { "Type": product_type, "Air temperature [K]": float(air_temperature), "Process temperature [K]": float(process_temperature), "Rotational speed [rpm]": float(rotational_speed), "Torque [Nm]": float(torque), "Tool wear [min]": float(tool_wear), } ] ) return sensor_record, [] # ============================================================ # AGENT 2 — ML PREDICTION AGENT # ============================================================ def prediction_agent(sensor_record): """ Calls the trained Random Forest pipeline as a prediction tool. """ model = load_predictive_model() failure_probability = float( model.predict_proba(sensor_record)[0, 1] ) prediction = int( failure_probability >= FAILURE_THRESHOLD ) if failure_probability >= HIGH_RISK_THRESHOLD: risk_level = "HIGH" elif failure_probability >= MEDIUM_RISK_THRESHOLD: risk_level = "MEDIUM" else: risk_level = "LOW" return { "prediction": prediction, "failure_probability": failure_probability, "risk_level": risk_level, } # ============================================================ # AGENT 3 — ENGINEERING REASONING AGENT # ============================================================ def build_engineering_prompt(sensor_record, ml_result): row = sensor_record.iloc[0] system_prompt = """ You are an engineering maintenance reasoning assistant in an educational predictive-maintenance prototype. A trained Random Forest model has already produced the machine-failure probability. Do not replace or contradict the ML prediction. Use only the supplied sensor readings and ML result. Do not invent manufacturer limits, maintenance history, measurements, failure codes, or engineering standards that were not provided. Give a concise engineering interpretation suitable for final-year engineering students. Return exactly these headings: ### Engineering Assessment ### Evidence from Current Readings ### Possible Engineering Concern ### Recommended Next Action ### Preventive Maintenance Suggestion Always state that the recommendation requires validation by a qualified engineer before any real maintenance, shutdown, or repair decision. """.strip() user_prompt = f""" Machine readings: Product Type: {row['Type']} Air Temperature: {row['Air temperature [K]']:.1f} K Process Temperature: {row['Process temperature [K]']:.1f} K Rotational Speed: {row['Rotational speed [rpm]']:.0f} rpm Torque: {row['Torque [Nm]']:.1f} Nm Tool Wear: {row['Tool wear [min]']:.0f} min Random Forest result: Failure Probability: {ml_result['failure_probability']:.1%} Risk Level: {ml_result['risk_level']} Prediction: {'Failure Risk' if ml_result['prediction'] == 1 else 'Healthy'} Explain what this result means from a predictive-maintenance perspective. """.strip() return [ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}, ] def engineering_reasoning_agent(sensor_record, ml_result): """ Uses Qwen to interpret the ML output and sensor readings. """ tokenizer, model, device = load_reasoning_model() messages = build_engineering_prompt(sensor_record, ml_result) prompt_text = tokenizer.apply_chat_template( messages, tokenize=False, add_generation_prompt=True, ) inputs = tokenizer( prompt_text, return_tensors="pt", truncation=True, max_length=1536, ).to(device) with torch.inference_mode(): output_ids = model.generate( **inputs, max_new_tokens=220, do_sample=False, repetition_penalty=1.05, pad_token_id=tokenizer.eos_token_id, ) generated_tokens = output_ids[ 0, inputs["input_ids"].shape[1]: ] response = tokenizer.decode( generated_tokens, skip_special_tokens=True, ).strip() return response # ============================================================ # AGENT 4 — MAINTENANCE ACTION AGENT # ============================================================ def maintenance_agent(sensor_record, ml_result): """ Creates a structured action/work-order record from the ML result. The engineering reasoning text is generated separately by Qwen. """ probability = ml_result["failure_probability"] risk = ml_result["risk_level"] if risk == "HIGH": priority = "P1 - Immediate Engineering Review" action = "Inspect the equipment before continued operation." elif risk == "MEDIUM": priority = "P2 - Priority Inspection" action = "Schedule a maintenance inspection and increase monitoring." else: priority = "P3 - Routine Monitoring" action = "Continue monitoring under the normal maintenance plan." work_order_id = datetime.now().strftime("PM-%Y%m%d-%H%M%S") return { "work_order_id": work_order_id, "work_order_type": "AI-Assisted Predictive Maintenance", "priority": priority, "failure_probability": f"{probability:.1%}", "risk_level": risk, "recommended_action": action, "assigned_team": "Reliability / Maintenance Engineering", "approval_status": "Pending Human Engineer Approval", } # ============================================================ # ORCHESTRATOR # ============================================================ def run_agentic_workflow( product_type, air_temperature, process_temperature, rotational_speed, torque, tool_wear, ): sensor_record, errors = iot_data_agent( product_type, air_temperature, process_temperature, rotational_speed, torque, tool_wear, ) if errors: return { "success": False, "errors": errors, } ml_result = prediction_agent(sensor_record) reasoning = engineering_reasoning_agent( sensor_record, ml_result, ) work_order = maintenance_agent( sensor_record, ml_result, ) return { "success": True, "sensor_record": sensor_record, "ml_result": ml_result, "reasoning": reasoning, "work_order": work_order, } # ============================================================ # SIDEBAR # ============================================================ with st.sidebar: st.header("About the Prototype") st.write( """ This application demonstrates how a trained Machine Learning model can be used as a tool inside an Agentic AI workflow. """ ) st.markdown( """ **Architecture** 1. 📡 IoT Data Agent 2. 🤖 ML Prediction Agent 3. 🧠 Engineering Reasoning Agent 4. 🔧 Maintenance Action Agent 5. 👨🔧 Human Approval """ ) st.caption( "Educational prototype only. Not intended for real industrial safety decisions." ) # ============================================================ # MAIN PAGE # ============================================================ st.markdown( '