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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
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.
        """
    )