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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a1d648
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
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
    )