File size: 7,942 Bytes
697fe11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import pandas as pd


import lightgbm as lgb
import xgboost as xgb
import gradio as gr
import joblib
import os

from obesity_rp import config as cfg

# Global variables to store loaded models, their columns, and the label encoder
loaded_models = {}
loaded_model_columns_map = {}
label_encoder = None


def load_model_artifacts(model_name):
    """
    Loads the trained model, feature columns, and the label encoder.
    """
    model_file = os.path.join(cfg.MODEL_DIR, f"obesity_{model_name}_model.joblib")
    columns_file = os.path.join(cfg.MODEL_DIR, f"{model_name}_model_columns.joblib")
    encoder_file = os.path.join(cfg.MODEL_DIR, "label_encoder.joblib")

    if not all(os.path.exists(f) for f in [model_file, columns_file, encoder_file]):
        raise FileNotFoundError(
            f"Model artifacts for '{model_name}' not found. Please ensure all required files exist."
        )

    loaded_model = joblib.load(model_file)
    loaded_model_columns = joblib.load(columns_file)
    le = joblib.load(encoder_file)
    print(
        f"{model_name} Model, feature columns, and label encoder loaded for prediction."
    )
    return loaded_model, loaded_model_columns, le


def predict_obesity_risk(
    model_choice,
    Gender,
    Age,
    Height,
    Weight,
    family_history_with_overweight,
    FAVC,
    FCVC,
    NCP,
    CAEC,
    SMOKE,
    CH2O,
    SCC,
    FAF,
    TUE,
    CALC,
    MTRANS,
):
    """
    Predicts obesity risk based on input features and chosen model.
    """
    global label_encoder

    if model_choice not in loaded_models:
        try:
            model, columns, le = load_model_artifacts(model_choice)
            loaded_models[model_choice] = model
            loaded_model_columns_map[model_choice] = columns
            if label_encoder is None:
                label_encoder = le
        except FileNotFoundError as e:
            return f"Error: {e}. Model '{model_choice}' not found. Please train the model first."
    else:
        model = loaded_models[model_choice]
        columns = loaded_model_columns_map[model_choice]
        le = label_encoder

    # Create a dictionary to hold the input data
    input_data_dict = {
        "Age": Age,
        "Height": Height,
        "Weight": Weight,
        "FCVC": FCVC,
        "NCP": NCP,
        "CH2O": CH2O,
        "FAF": FAF,
        "TUE": TUE,
    }

    input_df = pd.DataFrame(0, index=[0], columns=columns)

    for col, value in input_data_dict.items():
        if col in input_df.columns:
            input_df.loc[0, col] = value

    # Handle one-hot encoded categorical features
    categorical_inputs = {
        "Gender": Gender,
        "family_history_with_overweight": family_history_with_overweight,
        "FAVC": FAVC,
        "CAEC": CAEC,
        "SMOKE": SMOKE,
        "SCC": SCC,
        "CALC": CALC,
        "MTRANS": MTRANS,
    }

    for col_prefix, value in categorical_inputs.items():
        column_name = f"{col_prefix}_{value}"
        if column_name in input_df.columns:
            input_df.loc[0, column_name] = 1

    input_df = input_df[columns]

    prediction_proba = model.predict_proba(input_df)[0]
    prediction_encoded = model.predict(input_df)[0]
    prediction_label = le.inverse_transform([prediction_encoded])[0]

    results = f"Using {model_choice} Model:\nPrediction: {prediction_label}\n\n--- Prediction Probabilities ---\n"
    for i, class_name in enumerate(le.classes_):
        prob = prediction_proba[i] * 100
        results += f"{class_name}: {prob:.2f}%\n"

    return results


def launch_gradio_app(share=False):
    """
    Launches the Gradio web application for obesity risk prediction.
    """
    print("\n--- Starting Gradio App ---")

    # Define Gradio input components
    model_choice_input = gr.Dropdown(
        choices=cfg.MODEL_CHOICES, label="Select Model", value=cfg.RANDOM_FOREST
    )
    gender_input = gr.Dropdown(choices=["Female", "Male"], label="Gender")
    age_input = gr.Slider(minimum=1, maximum=100, step=1, label="Age")
    height_input = gr.Slider(minimum=1.0, maximum=2.2, step=0.01, label="Height (m)")
    weight_input = gr.Slider(minimum=30.0, maximum=200.0, step=0.1, label="Weight (kg)")
    family_history_input = gr.Radio(
        choices=["yes", "no"], label="Family History with Overweight"
    )
    favc_input = gr.Radio(
        choices=["yes", "no"], label="Frequent consumption of high caloric food (FAVC)"
    )
    fcvc_input = gr.Slider(
        minimum=1,
        maximum=3,
        step=1,
        label="Frequency of consumption of vegetables (FCVC)",
    )
    ncp_input = gr.Slider(
        minimum=1, maximum=4, step=1, label="Number of main meals (NCP)"
    )
    caec_input = gr.Dropdown(
        choices=["no", "Sometimes", "Frequently", "Always"],
        label="Consumption of food between meals (CAEC)",
    )
    smoke_input = gr.Radio(choices=["yes", "no"], label="SMOKE")
    ch2o_input = gr.Slider(
        minimum=1, maximum=3, step=1, label="Consumption of water daily (CH2O)"
    )
    scc_input = gr.Radio(
        choices=["yes", "no"], label="Calories consumption monitoring (SCC)"
    )
    faf_input = gr.Slider(
        minimum=0, maximum=3, step=1, label="Physical activity frequency (FAF)"
    )
    tue_input = gr.Slider(
        minimum=0, maximum=2, step=1, label="Time using technology devices (TUE)"
    )
    calc_input = gr.Dropdown(
        choices=["no", "Sometimes", "Frequently", "Always"],
        label="Consumption of alcohol (CALC)",
    )
    mtrans_input = gr.Dropdown(
        choices=["Automobile", "Motorbike", "Bike", "Public_Transportation", "Walking"],
        label="Transportation used (MTRANS)",
    )

    output_text = gr.Textbox(label="Obesity Risk Prediction Result", lines=10)

    iface = gr.Interface(
        fn=predict_obesity_risk,
        inputs=[
            model_choice_input,
            gender_input,
            age_input,
            height_input,
            weight_input,
            family_history_input,
            favc_input,
            fcvc_input,
            ncp_input,
            caec_input,
            smoke_input,
            ch2o_input,
            scc_input,
            faf_input,
            tue_input,
            calc_input,
            mtrans_input,
        ],
        outputs=output_text,
        title="Obesity Risk Prediction (Multi-Model)",
        description="Select a machine learning model and enter patient details to predict the obesity risk category.",
        examples=[
            [
                cfg.RANDOM_FOREST,
                "Male",
                25,
                1.8,
                85,
                "yes",
                "yes",
                2,
                3,
                "Sometimes",
                "no",
                2,
                "no",
                1,
                1,
                "Frequently",
                "Public_Transportation",
            ],
            [
                cfg.LIGHTGBM,
                "Female",
                30,
                1.65,
                70,
                "yes",
                "yes",
                3,
                3,
                "Frequently",
                "no",
                3,
                "yes",
                2,
                0,
                "Sometimes",
                "Automobile",
            ],
            [
                cfg.XGBOOST,
                "Female",
                21,
                1.52,
                56,
                "yes",
                "no",
                3,
                3,
                "Sometimes",
                "yes",
                3,
                "yes",
                3,
                0,
                "Sometimes",
                "Public_Transportation",
            ],
        ],
    )

    iface.launch(share=share)
    print("--- Gradio App Launched ---")


if __name__ == "__main__":
    launch_gradio_app(share=False)