File size: 2,319 Bytes
a37265a
 
2e9e5c9
a37265a
 
 
c942b33
a37265a
c942b33
a37265a
 
 
 
 
 
 
31771be
870d43b
2e9e5c9
870d43b
2e9e5c9
 
 
 
 
 
 
80f2daf
a37265a
870d43b
 
 
 
a37265a
 
d7f02bd
a37265a
 
31771be
a37265a
2e9e5c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31771be
a37265a
 
 
31771be
870d43b
 
 
a37265a
 
 
 
 
 
 
 
 
31771be
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
import os
import numpy as np
import joblib
import gradio as gr
import warnings

from ml_features import preprocess_audio, extract_ml_features

warnings.filterwarnings('ignore')

LABEL_MAP_INVERSE = {
    0: 'Machine 1_Normal', 1: 'Machine 1_Abnormal',
    2: 'Machine 2_Normal', 3: 'Machine 2_Abnormal',
    4: 'Machine 3_Normal', 5: 'Machine 3_Abnormal'
}


# ==========================================
# LOAD MODEL
# ==========================================
model = None
model_error = ""
try:
    model = joblib.load("ml_XGBoost_v1_immed.joblib")
    print("XGBoost model loaded successfully.")
except Exception as e:
    model_error = str(e)
    print(f"Warning: Could not load model. Error: {model_error}")


# ==========================================
# PREDICTION
# ==========================================
def predict(audio_filepath):
    if model is None:
        return f"Model not loaded properly. Error: {model_error}"
    if audio_filepath is None:
        return "Please upload an audio file."

    try:
        # 1. Preprocess
        y = preprocess_audio(audio_filepath)

        # 2. Extract features
        features = extract_ml_features(y)

        # 3. Convert to array in the same column order the model expects
        feature_names = sorted(features.keys())
        X = np.array([[features[name] for name in feature_names]])

        # 4. Predict
        predicted_class = model.predict(X)[0]
        predicted_label = LABEL_MAP_INVERSE.get(int(predicted_class), "Unknown")

        # Get probabilities if available
        if hasattr(model, 'predict_proba'):
            proba = model.predict_proba(X)[0]
            confidence = float(np.max(proba))
            return f"Prediction: {predicted_label} (Confidence: {confidence:.2f})"
        else:
            return f"Prediction: {predicted_label}"

    except Exception as e:
        return f"Error processing file: {str(e)}"


# ==========================================
# GRADIO UI
# ==========================================
iface = gr.Interface(
    fn=predict,
    inputs=gr.Audio(type="filepath", label="Upload Machine Audio"),
    outputs="text",
    title="Machine Listener Diagnosis",
    description="Upload a sound from a machine to predict whether it is Normal or Abnormal."
)

if __name__ == "__main__":
    iface.launch()