MBG0903's picture
Create app.py
0e1a9c0 verified
Raw History Blame Contribute Delete
19.2 kB
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(
"""
<style>
.main-title {
font-size: 2.2rem;
font-weight: 750;
margin-bottom: 0.1rem;
}
.sub-title {
color: #6b7280;
margin-bottom: 1.25rem;
}
.agent-box {
border: 1px solid #d1d5db;
border-radius: 12px;
padding: 14px 16px;
margin-bottom: 12px;
}
.status-ok {
font-weight: 700;
}
.small-note {
font-size: 0.88rem;
color: #6b7280;
}
</style>
""",
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(
'<div class="main-title">🏭 Intelligent Predictive Maintenance System</div>',
unsafe_allow_html=True,
)
st.markdown(
'<div class="sub-title">Random Forest + Local Qwen Reasoning + Agentic AI Workflow</div>',
unsafe_allow_html=True,
)
st.info(
"Workflow: IoT Data β†’ Random Forest Prediction β†’ Qwen Engineering Reasoning β†’ Maintenance Action β†’ Human Approval"
)
input_col, result_col = st.columns([1, 1.25], gap="large")
# ============================================================
# INPUT PANEL
# ============================================================
with input_col:
st.subheader("πŸ“‘ IoT Machine Parameters")
product_type = st.selectbox(
"Product Type",
options=["L", "M", "H"],
index=0,
help="L = Low, M = Medium, H = High product quality type used in the AI4I dataset.",
)
air_temperature = st.slider(
"Air Temperature [K]",
min_value=295.0,
max_value=305.0,
value=300.0,
step=0.1,
)
process_temperature = st.slider(
"Process Temperature [K]",
min_value=305.0,
max_value=315.0,
value=310.0,
step=0.1,
)
rotational_speed = st.slider(
"Rotational Speed [rpm]",
min_value=1100,
max_value=2900,
value=1500,
step=10,
)
torque = st.slider(
"Torque [Nm]",
min_value=3.0,
max_value=80.0,
value=45.0,
step=0.5,
)
tool_wear = st.slider(
"Tool Wear [min]",
min_value=0,
max_value=253,
value=150,
step=5,
)
run_button = st.button(
"πŸš€ Run Agentic AI Workflow",
type="primary",
use_container_width=True,
)
# ============================================================
# OUTPUT PANEL
# ============================================================
with result_col:
st.subheader("πŸ€– Machine Intelligence")
if not run_button:
st.write(
"Enter the operating parameters and run the workflow to see the agents collaborate."
)
if run_button:
with st.status(
"Running collaborative AI workflow...",
expanded=True,
) as status:
st.write("πŸ“‘ **Agent 1 β€” IoT Data Agent:** Validating sensor readings...")
sensor_record, errors = iot_data_agent(
product_type,
air_temperature,
process_temperature,
rotational_speed,
torque,
tool_wear,
)
if errors:
for error in errors:
st.error(error)
status.update(
label="Input validation failed",
state="error",
)
st.stop()
st.write("βœ… Sensor validation complete.")
st.write("πŸ€– **Agent 2 β€” ML Prediction Agent:** Calling trained Random Forest model...")
try:
ml_result = prediction_agent(sensor_record)
except Exception as exc:
st.error(f"Unable to load or run the trained ML model: {exc}")
st.info(
"Ensure predictive_maintenance_rf_pipeline.pkl is in the same folder as app.py "
"and that scikit-learn==1.6.1 is installed."
)
status.update(
label="ML prediction failed",
state="error",
)
st.stop()
st.write("βœ… Random Forest prediction complete.")
st.write("🧠 **Agent 3 β€” Engineering Reasoning Agent:** Qwen is interpreting the result...")
try:
reasoning = engineering_reasoning_agent(
sensor_record,
ml_result,
)
except Exception as exc:
reasoning = (
"The local language model could not generate an engineering explanation. "
f"Technical message: {exc}"
)
st.write("βœ… Engineering interpretation complete.")
st.write("πŸ”§ **Agent 4 β€” Maintenance Action Agent:** Creating maintenance action...")
work_order = maintenance_agent(
sensor_record,
ml_result,
)
st.write("βœ… Maintenance work order generated.")
status.update(
label="Agentic AI workflow completed",
state="complete",
)
probability = ml_result["failure_probability"]
prediction_text = (
"FAILURE RISK"
if ml_result["prediction"] == 1
else "HEALTHY"
)
metric1, metric2, metric3 = st.columns(3)
metric1.metric(
"Machine Status",
prediction_text,
)
metric2.metric(
"Failure Probability",
f"{probability:.1%}",
)
metric3.metric(
"Risk Level",
ml_result["risk_level"],
)
st.progress(
min(max(probability, 0.0), 1.0),
text=f"Predicted failure probability: {probability:.1%}",
)
with st.expander(
"πŸ“‘ Agent 1 β€” IoT Data Agent",
expanded=False,
):
st.dataframe(
sensor_record,
use_container_width=True,
hide_index=True,
)
with st.expander(
"πŸ€– Agent 2 β€” ML Prediction Agent",
expanded=True,
):
st.write(
"The trained Random Forest pipeline was called as an ML prediction tool."
)
st.json(
{
"prediction": prediction_text,
"failure_probability": round(probability, 4),
"risk_level": ml_result["risk_level"],
}
)
with st.expander(
"🧠 Agent 3 β€” Engineering Reasoning Agent",
expanded=True,
):
st.markdown(reasoning)
st.caption(
f"Local reasoning model: {LLM_MODEL_ID}"
)
with st.expander(
"πŸ”§ Agent 4 β€” Maintenance Action Agent",
expanded=True,
):
st.json(work_order)
st.warning(
"πŸ‘¨β€πŸ”§ Human-in-the-loop: A qualified engineer must validate the recommendation "
"before any real maintenance, repair, or shutdown action."
)
report = {
"sensor_readings": sensor_record.iloc[0].to_dict(),
"ml_prediction": {
"prediction": prediction_text,
"failure_probability": probability,
"risk_level": ml_result["risk_level"],
},
"engineering_reasoning": reasoning,
"maintenance_work_order": work_order,
}
st.download_button(
"⬇️ Download AI Maintenance Report",
data=json.dumps(report, indent=2),
file_name="predictive_maintenance_report.json",
mime="application/json",
use_container_width=True,
)
# ============================================================
# EXPLANATION TAB AREA
# ============================================================
st.divider()
with st.expander("πŸŽ“ How this Agentic AI system works"):
st.markdown(
"""
### 1. Random Forest is the prediction intelligence
The model was trained separately using the AI4I predictive-maintenance dataset.
It calculates the probability of machine failure from the current machine readings.
### 2. The Prediction Agent uses the RF model as a tool
The agent does not ask the language model to guess whether the machine will fail.
### 3. Qwen provides engineering interpretation
The local instruction-tuned model receives both the sensor readings and the
Random Forest prediction and explains the result in natural language.
### 4. The Maintenance Agent converts intelligence into action
It creates a structured maintenance work-order record.
### 5. Human approval remains mandatory
Agentic AI supports engineering decisions; it does not replace engineering accountability.
"""
)