File size: 2,361 Bytes
7ddd7d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import pickle
import pandas as pd

# Load model (make sure Heart_Project.pkl is in repo root)
with open("Heart_Project.pkl", "rb") as f:
    model = pickle.load(f)

# Prediction function
def predict(Age, Sex, ChestPainType, RestingBP, Cholesterol,
            FastingBS, RestingECG, MaxHR, ExerciseAngina, Oldpeak, ST_Slope):
    SEX_MAP    = {'M': 1, 'F': 0}
    CP_MAP     = {'TA': 0, 'ATA': 1, 'NAP': 2, 'ASY': 3}
    ECG_MAP    = {'Normal': 0, 'ST': 1, 'LVH': 2}
    ANGINA_MAP = {'Y': 1, 'N': 0}
    SLOPE_MAP  = {'Up': 2, 'Flat': 1, 'Down': 0}

    # Build feature row (same order as used during training)
    features = [[
        Age,
        SEX_MAP[Sex],
        CP_MAP[ChestPainType],
        RestingBP,
        Cholesterol,
        FastingBS,
        ECG_MAP[RestingECG],
        MaxHR,
        ANGINA_MAP[ExerciseAngina],
        Oldpeak,
        SLOPE_MAP[ST_Slope]
    ]]

    df = pd.DataFrame(features, columns=[
        'Age','Sex','ChestPainType','RestingBP','Cholesterol',
        'FastingBS','RestingECG','MaxHR','ExerciseAngina',
        'Oldpeak','ST_Slope'
    ])

    # Use predict_proba if available, otherwise fallback to predict
    if hasattr(model, "predict_proba"):
        prob = model.predict_proba(df)[0, 1]
    else:
        # fallback: model might not have predict_proba
        prob = None

    pred = model.predict(df)[0]
    if prob is None:
        return f"Prediction: {'Heart Disease' if pred==1 else 'No Heart Disease'}"
    return f"Prediction: {'Heart Disease' if pred==1 else 'No Heart Disease'} | Probability: {prob:.2f}"

# Build Gradio UI
demo = gr.Interface(
    fn=predict,
    inputs=[
        gr.Number(label="Age"),
        gr.Radio(["M","F"], label="Sex"),
        gr.Radio(["TA","ATA","NAP","ASY"], label="Chest Pain Type"),
        gr.Number(label="RestingBP"),
        gr.Number(label="Cholesterol"),
        gr.Radio([0,1], label="FastingBS"),
        gr.Radio(["Normal","ST","LVH"], label="RestingECG"),
        gr.Number(label="MaxHR"),
        gr.Radio(["Y","N"], label="ExerciseAngina"),
        gr.Number(label="Oldpeak"),
        gr.Radio(["Up","Flat","Down"], label="ST Slope")
    ],
    outputs="text",
    title="❤️ Heart Disease Predictor",
    description="Enter patient details to predict the risk of heart disease."
)

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