Download app.py from MBG0903/Intelligent_Predictive_Maintenance_System: direct link, hf CLI and curl.
- Browser
- Download file 15.2 kB
-
https://huggingface.co/spaces/MBG0903/Intelligent_Predictive_Maintenance_System/resolve/main/app.py
- Command line
-
hf download hf://spaces/MBG0903/Intelligent_Predictive_Maintenance_System/app.py
-
curl -L -o app.py https://huggingface.co/spaces/MBG0903/Intelligent_Predictive_Maintenance_System/resolve/main/app.py
15.2 kB
| import json | |
| from pathlib import Path | |
| import gradio as gr | |
| import pandas as pd | |
| import torch | |
| from sklearn.compose import ColumnTransformer | |
| from sklearn.ensemble import RandomForestClassifier | |
| from sklearn.metrics import ( | |
| accuracy_score, | |
| average_precision_score, | |
| confusion_matrix, | |
| f1_score, | |
| precision_score, | |
| recall_score, | |
| roc_auc_score, | |
| ) | |
| from sklearn.model_selection import train_test_split | |
| from sklearn.pipeline import Pipeline | |
| from sklearn.preprocessing import OneHotEncoder | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| DATA_PATH = Path(__file__).parent / "ai4i2020.csv" | |
| RANDOM_STATE = 42 | |
| DECISION_THRESHOLD = 0.40 | |
| LLM_MODEL_ID = "Qwen/Qwen2.5-0.5B-Instruct" | |
| FEATURES = [ | |
| "Type", | |
| "Air temperature [K]", | |
| "Process temperature [K]", | |
| "Rotational speed [rpm]", | |
| "Torque [Nm]", | |
| "Tool wear [min]", | |
| ] | |
| TARGET = "Machine failure" | |
| # ------------------------------------------------------------------- | |
| # Load dataset and train the predictive ML model | |
| # ------------------------------------------------------------------- | |
| df = pd.read_csv(DATA_PATH) | |
| X = df[FEATURES].copy() | |
| y = df[TARGET].astype(int) | |
| X_train, X_test, y_train, y_test = train_test_split( | |
| X, | |
| y, | |
| test_size=0.20, | |
| stratify=y, | |
| random_state=RANDOM_STATE, | |
| ) | |
| preprocessor = ColumnTransformer( | |
| transformers=[ | |
| ("type", OneHotEncoder(handle_unknown="ignore"), ["Type"]), | |
| ], | |
| remainder="passthrough", | |
| ) | |
| ml_model = Pipeline( | |
| steps=[ | |
| ("preprocessor", preprocessor), | |
| ( | |
| "classifier", | |
| RandomForestClassifier( | |
| n_estimators=250, | |
| min_samples_leaf=2, | |
| class_weight="balanced", | |
| random_state=RANDOM_STATE, | |
| n_jobs=-1, | |
| ), | |
| ), | |
| ] | |
| ) | |
| ml_model.fit(X_train, y_train) | |
| test_probabilities = ml_model.predict_proba(X_test)[:, 1] | |
| test_predictions = (test_probabilities >= DECISION_THRESHOLD).astype(int) | |
| metrics = { | |
| "Accuracy": accuracy_score(y_test, test_predictions), | |
| "Precision": precision_score(y_test, test_predictions, zero_division=0), | |
| "Recall": recall_score(y_test, test_predictions, zero_division=0), | |
| "F1 Score": f1_score(y_test, test_predictions, zero_division=0), | |
| "ROC-AUC": roc_auc_score(y_test, test_probabilities), | |
| "PR-AUC": average_precision_score(y_test, test_probabilities), | |
| } | |
| cm = confusion_matrix(y_test, test_predictions) | |
| # ------------------------------------------------------------------- | |
| # Load the local instruction-tuned language model | |
| # ------------------------------------------------------------------- | |
| LLM_MODEL_ID = "Qwen/Qwen2.5-0.5B-Instruct" | |
| DEVICE = "cuda" if torch.cuda.is_available() else "cpu" | |
| tokenizer = AutoTokenizer.from_pretrained( | |
| LLM_MODEL_ID | |
| ) | |
| llm_model = AutoModelForCausalLM.from_pretrained( | |
| LLM_MODEL_ID, | |
| dtype=torch.float16 if DEVICE == "cuda" else torch.float32, | |
| low_cpu_mem_usage=True, | |
| ) | |
| llm_model.to(DEVICE) | |
| llm_model.eval() | |
| def validate_inputs( | |
| product_type, | |
| air_temperature, | |
| process_temperature, | |
| rotational_speed, | |
| torque, | |
| tool_wear, | |
| ): | |
| values = { | |
| "Air temperature": air_temperature, | |
| "Process temperature": process_temperature, | |
| "Rotational speed": rotational_speed, | |
| "Torque": torque, | |
| "Tool wear": tool_wear, | |
| } | |
| for name, value in values.items(): | |
| if value is None: | |
| raise gr.Error(f"{name} is required.") | |
| if product_type not in {"L", "M", "H"}: | |
| raise gr.Error("Product type must be L, M or H.") | |
| def determine_risk_level(probability): | |
| if probability >= 0.70: | |
| return "High" | |
| if probability >= DECISION_THRESHOLD: | |
| return "Medium" | |
| return "Low" | |
| def build_reasoning_prompt( | |
| product_type, | |
| air_temperature, | |
| process_temperature, | |
| rotational_speed, | |
| torque, | |
| tool_wear, | |
| probability, | |
| risk_level, | |
| ): | |
| temperature_gap = process_temperature - air_temperature | |
| predicted_state = ( | |
| "Potential machine failure" | |
| if probability >= DECISION_THRESHOLD | |
| else "Machine currently appears healthy" | |
| ) | |
| system_message = """ | |
| You are an AI maintenance reasoning assistant for an educational engineering prototype. | |
| Your role is to interpret a machine-learning prediction using only the supplied sensor readings. | |
| Do not claim certainty. | |
| Do not invent sensor values, standards, failure codes, manufacturer limits, or maintenance history. | |
| Do not present your response as a substitute for a qualified engineer. | |
| Do not recommend unsafe actions. | |
| Any shutdown, repair, or maintenance action must be approved by a qualified engineer. | |
| Return the response under exactly these headings: | |
| ### Engineering Assessment | |
| ### Evidence from Sensor Readings | |
| ### Likely Engineering Concern | |
| ### Recommended Immediate Action | |
| ### Preventive Maintenance Recommendation | |
| ### Maintenance Work Order | |
| ### Human Approval Required | |
| """.strip() | |
| user_message = f""" | |
| Analyse the following industrial machine data. | |
| Product type: {product_type} | |
| Air temperature: {air_temperature:.1f} K | |
| Process temperature: {process_temperature:.1f} K | |
| Temperature difference: {temperature_gap:.1f} K | |
| Rotational speed: {rotational_speed:.0f} rpm | |
| Torque: {torque:.1f} Nm | |
| Tool wear: {tool_wear:.0f} minutes | |
| Machine-learning result: | |
| Predicted state: {predicted_state} | |
| Failure probability: {probability:.1%} | |
| Risk level: {risk_level} | |
| Decision threshold: {DECISION_THRESHOLD:.0%} | |
| Explain the result in clear language suitable for seventh-semester engineering students. | |
| Keep the response practical and concise. | |
| """.strip() | |
| return [ | |
| {"role": "system", "content": system_message}, | |
| {"role": "user", "content": user_message}, | |
| ] | |
| def generate_llm_reasoning(messages): | |
| prompt_text = tokenizer.apply_chat_template( | |
| messages, | |
| tokenize=False, | |
| add_generation_prompt=True, | |
| ) | |
| inputs = tokenizer( | |
| prompt_text, | |
| return_tensors="pt", | |
| truncation=True, | |
| max_length=2048, | |
| ).to(DEVICE) | |
| with torch.inference_mode(): | |
| output_ids = llm_model.generate( | |
| **inputs, | |
| max_new_tokens=220, | |
| do_sample=True, | |
| temperature=0.35, | |
| top_p=0.90, | |
| repetition_penalty=1.08, | |
| 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 | |
| def create_structured_work_order( | |
| probability, | |
| risk_level, | |
| llm_response, | |
| ): | |
| if risk_level == "High": | |
| priority = "P1 - Immediate Engineering Review" | |
| status = "Inspection Required" | |
| elif risk_level == "Medium": | |
| priority = "P2 - Urgent Monitoring and Inspection" | |
| status = "Maintenance Review Required" | |
| else: | |
| priority = "P3 - Continue Monitoring" | |
| status = "Monitor" | |
| return { | |
| "work_order_type": "AI-Assisted Predictive Maintenance", | |
| "priority": priority, | |
| "asset_status": status, | |
| "predicted_failure_probability": f"{probability:.1%}", | |
| "assigned_team": "Mechanical / Reliability Engineering", | |
| "approval_status": "Pending Human Engineer Approval", | |
| "llm_generated_engineering_note": llm_response, | |
| } | |
| def run_collaborative_ai( | |
| product_type, | |
| air_temperature, | |
| process_temperature, | |
| rotational_speed, | |
| torque, | |
| tool_wear, | |
| ): | |
| validate_inputs( | |
| product_type, | |
| air_temperature, | |
| process_temperature, | |
| rotational_speed, | |
| torque, | |
| tool_wear, | |
| ) | |
| input_record = pd.DataFrame( | |
| [ | |
| { | |
| "Type": product_type, | |
| "Air temperature [K]": air_temperature, | |
| "Process temperature [K]": process_temperature, | |
| "Rotational speed [rpm]": rotational_speed, | |
| "Torque [Nm]": torque, | |
| "Tool wear [min]": tool_wear, | |
| } | |
| ] | |
| ) | |
| probability = float(ml_model.predict_proba(input_record)[0, 1]) | |
| prediction = int(probability >= DECISION_THRESHOLD) | |
| risk_level = determine_risk_level(probability) | |
| prediction_status = ( | |
| "FAILURE RISK DETECTED" | |
| if prediction == 1 | |
| else "MACHINE APPEARS HEALTHY" | |
| ) | |
| prediction_markdown = f""" | |
| ## {prediction_status} | |
| **Failure probability:** {probability:.1%} | |
| **Risk level:** {risk_level} | |
| **Decision threshold:** {DECISION_THRESHOLD:.0%} | |
| The Random Forest model analysed the six machine operating inputs and estimated the probability of failure. | |
| """ | |
| messages = build_reasoning_prompt( | |
| product_type, | |
| air_temperature, | |
| process_temperature, | |
| rotational_speed, | |
| torque, | |
| tool_wear, | |
| probability, | |
| risk_level, | |
| ) | |
| llm_response = generate_llm_reasoning(messages) | |
| agent_report = f""" | |
| ## Local Agentic AI Reasoning | |
| **Reasoning model:** `{LLM_MODEL_ID}` | |
| **Execution device:** `{DEVICE}` | |
| {llm_response} | |
| --- | |
| The language model interprets the ML output. It does not independently predict machine failure and must not override engineering judgement. | |
| """ | |
| work_order = create_structured_work_order( | |
| probability, | |
| risk_level, | |
| llm_response, | |
| ) | |
| return prediction_markdown, agent_report, work_order | |
| def model_summary(): | |
| failure_count = int(df[TARGET].sum()) | |
| healthy_count = int((df[TARGET] == 0).sum()) | |
| metrics_df = pd.DataFrame( | |
| { | |
| "Metric": list(metrics.keys()), | |
| "Value": [round(value, 4) for value in metrics.values()], | |
| } | |
| ) | |
| confusion_df = pd.DataFrame( | |
| cm, | |
| index=["Actual Healthy", "Actual Failure"], | |
| columns=["Predicted Healthy", "Predicted Failure"], | |
| ) | |
| dataset_markdown = f""" | |
| ## Dataset Summary | |
| - **Rows:** {len(df):,} | |
| - **Healthy records:** {healthy_count:,} | |
| - **Failure records:** {failure_count:,} | |
| - **Failure rate:** {failure_count / len(df):.2%} | |
| - **Input features:** {len(FEATURES)} | |
| - **Target:** Machine failure | |
| - **Problem type:** Binary classification | |
| - **Train/test split:** 80% / 20%, stratified | |
| - **Decision threshold:** {DECISION_THRESHOLD:.0%} | |
| The columns `TWF`, `HDF`, `PWF`, `OSF`, and `RNF` are excluded from the model inputs because they reveal the failure outcome and would create target leakage. | |
| """ | |
| return dataset_markdown, metrics_df, confusion_df | |
| with gr.Blocks(title="Engineering AI: Predictive Maintenance") as demo: | |
| gr.Markdown( | |
| """ | |
| # Engineering AI in Action | |
| ### IoT Predictive Maintenance + Local Agentic AI Reasoning | |
| This prototype combines: | |
| 1. A **Random Forest machine-learning model** for failure prediction. | |
| 2. A local **SmolLM2 instruction model** for engineering interpretation. | |
| 3. An automated **maintenance work-order generator**. | |
| 4. A mandatory **human-in-the-loop approval step**. | |
| """ | |
| ) | |
| with gr.Tab("Live Engineering Demo"): | |
| with gr.Row(): | |
| with gr.Column(): | |
| product_type = gr.Dropdown( | |
| choices=["L", "M", "H"], | |
| value="M", | |
| label="Product Type", | |
| ) | |
| air_temperature = gr.Slider( | |
| minimum=295.0, | |
| maximum=305.0, | |
| value=300.0, | |
| step=0.1, | |
| label="Air Temperature [K]", | |
| ) | |
| process_temperature = gr.Slider( | |
| minimum=305.0, | |
| maximum=315.0, | |
| value=310.0, | |
| step=0.1, | |
| label="Process Temperature [K]", | |
| ) | |
| rotational_speed = gr.Slider( | |
| minimum=1100, | |
| maximum=2900, | |
| value=1450, | |
| step=1, | |
| label="Rotational Speed [rpm]", | |
| ) | |
| torque = gr.Slider( | |
| minimum=3.0, | |
| maximum=80.0, | |
| value=50.0, | |
| step=0.1, | |
| label="Torque [Nm]", | |
| ) | |
| tool_wear = gr.Slider( | |
| minimum=0, | |
| maximum=253, | |
| value=180, | |
| step=1, | |
| label="Tool Wear [min]", | |
| ) | |
| run_button = gr.Button( | |
| "Run ML + Local Agentic AI", | |
| variant="primary", | |
| ) | |
| with gr.Column(): | |
| prediction_output = gr.Markdown() | |
| work_order_output = gr.JSON( | |
| label="Generated Maintenance Work Order" | |
| ) | |
| reasoning_output = gr.Markdown() | |
| gr.Examples( | |
| examples=[ | |
| ["M", 298.1, 308.6, 1551, 42.8, 0], | |
| ["L", 300.7, 310.9, 1348, 58.7, 210], | |
| ["H", 302.0, 313.5, 1280, 70.0, 225], | |
| ], | |
| inputs=[ | |
| product_type, | |
| air_temperature, | |
| process_temperature, | |
| rotational_speed, | |
| torque, | |
| tool_wear, | |
| ], | |
| ) | |
| run_button.click( | |
| fn=run_collaborative_ai, | |
| inputs=[ | |
| product_type, | |
| air_temperature, | |
| process_temperature, | |
| rotational_speed, | |
| torque, | |
| tool_wear, | |
| ], | |
| outputs=[ | |
| prediction_output, | |
| reasoning_output, | |
| work_order_output, | |
| ], | |
| ) | |
| with gr.Tab("Model & Dataset"): | |
| dataset_output = gr.Markdown() | |
| metrics_output = gr.Dataframe( | |
| label="Test-set Performance", | |
| interactive=False, | |
| ) | |
| confusion_output = gr.Dataframe( | |
| label="Confusion Matrix", | |
| interactive=False, | |
| ) | |
| demo.load( | |
| fn=model_summary, | |
| outputs=[ | |
| dataset_output, | |
| metrics_output, | |
| confusion_output, | |
| ], | |
| ) | |
| with gr.Tab("How the Collaboration Works"): | |
| gr.Markdown( | |
| f""" | |
| ## Architecture | |
| **IoT Sensor Inputs** | |
| → **Random Forest Model** predicts failure probability | |
| → **SmolLM2-1.7B-Instruct** interprets the readings and ML result | |
| → **Action Layer** creates a maintenance work order | |
| → **Human Engineer** validates and approves the recommendation | |
| ## Models Used | |
| - Predictive ML model: `RandomForestClassifier` | |
| - Local reasoning model: `{LLM_MODEL_ID}` | |
| ## Important Design Principle | |
| The language model does not replace the predictive model. The Random Forest produces the numerical prediction. The language model converts that prediction and the sensor readings into an understandable engineering assessment. | |
| This is an educational prototype and must not be used for real industrial safety decisions. | |
| """ | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch( | |
| server_name="0.0.0.0", | |
| server_port=7860, | |
| ssr_mode=False | |
| ) | |