ntam0001 commited on
Commit
374abdb
Β·
verified Β·
1 Parent(s): f978017

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -27
app.py CHANGED
@@ -15,6 +15,7 @@ os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
15
  # Load model artifacts
16
  def load_model_artifacts():
17
  try:
 
18
  with open('model_architecture.json', 'r') as json_file:
19
  model_json = json_file.read()
20
  model = model_from_json(model_json)
@@ -33,21 +34,26 @@ def load_model_artifacts():
33
  # Initialize model components
34
  try:
35
  model, scaler, metadata = load_model_artifacts()
36
- # Use only two features for prediction
37
- feature_names = ['Feature_1', 'Feature_2']
38
  print(f"βœ… Model loaded successfully with features: {feature_names}")
39
  except Exception as e:
40
  print(f"❌ Error loading model: {e}")
41
  model, scaler, metadata = None, None, {}
42
- feature_names = ['Feature_1', 'Feature_2']
43
 
44
  def predict_student_eligibility(*args):
45
  try:
46
  if model is None or scaler is None:
47
  return "Model not loaded", "N/A", "N/A", create_error_plot()
48
 
 
49
  input_data = {feature_names[i]: args[i] for i in range(len(feature_names))}
50
  input_df = pd.DataFrame([input_data])
 
 
 
 
 
51
  input_scaled = scaler.transform(input_df)
52
  input_reshaped = input_scaled.reshape(input_scaled.shape[0], input_scaled.shape[1], 1)
53
 
@@ -85,6 +91,7 @@ def create_prediction_viz(probability, prediction, input_data):
85
  [{"type": "bar"}, {"type": "scatter"}]]
86
  )
87
 
 
88
  fig.add_trace(
89
  go.Indicator(
90
  mode="gauge+number",
@@ -106,6 +113,7 @@ def create_prediction_viz(probability, prediction, input_data):
106
  ), row=1, col=1
107
  )
108
 
 
109
  confidence = abs(probability - 0.5) * 2
110
  fig.add_trace(
111
  go.Indicator(
@@ -124,27 +132,46 @@ def create_prediction_viz(probability, prediction, input_data):
124
  ), row=1, col=2
125
  )
126
 
 
127
  features = list(input_data.keys())
128
  values = list(input_data.values())
129
- fig.add_trace(go.Bar(x=features, y=values, name="Input Values", marker_color="skyblue"), row=2, col=1)
 
 
 
 
 
 
 
 
 
 
130
 
 
131
  fig.add_trace(
132
  go.Scatter(
133
- x=[0, 1], y=[probability, probability],
 
134
  mode='lines+markers',
135
  name="Probability",
136
  line=dict(color="red", width=3),
137
  marker=dict(size=10)
138
- ), row=2, col=2
 
139
  )
140
 
141
  fig.update_layout(
142
  height=800,
143
  showlegend=False,
144
  title_text="Student Eligibility Prediction Dashboard",
145
- title_x=0.5
 
146
  )
147
 
 
 
 
 
148
  return fig
149
  except Exception as e:
150
  return create_error_plot()
@@ -158,10 +185,13 @@ def batch_predict(file):
158
  return "Please upload a CSV file.", None
159
 
160
  df = pd.read_csv(file)
 
 
161
  missing_features = set(feature_names) - set(df.columns)
162
  if missing_features:
163
- return f"Missing features: {missing_features}", None
164
 
 
165
  df_features = df[feature_names]
166
  df_scaled = scaler.transform(df_features)
167
  df_reshaped = df_scaled.reshape(df_scaled.shape[0], df_scaled.shape[1], 1)
@@ -169,7 +199,7 @@ def batch_predict(file):
169
  probabilities = model.predict(df_reshaped).flatten()
170
  predictions = ["Eligible" if p > 0.5 else "Not Eligible" for p in probabilities]
171
 
172
- results_df = df_features.copy()
173
  results_df['Probability'] = probabilities
174
  results_df['Prediction'] = predictions
175
  results_df['Confidence'] = np.abs(probabilities - 0.5) * 2
@@ -197,27 +227,52 @@ Results saved to: {output_file}
197
  return f"Error processing file: {str(e)}", None
198
 
199
  # Gradio UI
200
- demo = gr.Blocks(theme=gr.themes.Soft())
201
-
202
- with demo:
203
  gr.Markdown("# πŸŽ“ Student Eligibility Prediction")
 
 
204
  with gr.Tabs():
205
- with gr.Tab("Single Prediction"):
206
- inputs = [gr.Number(label=feature, value=75) for feature in feature_names]
207
- predict_btn = gr.Button("Predict")
208
  with gr.Row():
209
- prediction = gr.Textbox(label="Prediction")
210
- probability = gr.Textbox(label="Probability")
211
- confidence = gr.Textbox(label="Confidence")
 
 
 
 
212
  plot = gr.Plot()
213
- predict_btn.click(predict_student_eligibility, inputs=inputs, outputs=[prediction, probability, confidence, plot])
214
-
215
- with gr.Tab("Batch Prediction"):
216
- file_input = gr.File(label="Upload CSV", file_types=[".csv"], type="filepath")
217
- batch_btn = gr.Button("Process Batch")
218
- batch_output = gr.Textbox(label="Results")
219
- download = gr.File(label="Download")
220
- batch_btn.click(batch_predict, inputs=file_input, outputs=[batch_output, download])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
 
222
  # Launch app
223
- demo.launch()
 
 
15
  # Load model artifacts
16
  def load_model_artifacts():
17
  try:
18
+ # Load from the same directory where training code saved artifacts
19
  with open('model_architecture.json', 'r') as json_file:
20
  model_json = json_file.read()
21
  model = model_from_json(model_json)
 
34
  # Initialize model components
35
  try:
36
  model, scaler, metadata = load_model_artifacts()
37
+ feature_names = metadata['feature_names'] # Get feature names from metadata
 
38
  print(f"βœ… Model loaded successfully with features: {feature_names}")
39
  except Exception as e:
40
  print(f"❌ Error loading model: {e}")
41
  model, scaler, metadata = None, None, {}
42
+ feature_names = ['Feature_1', 'Feature_2'] # Fallback if metadata not available
43
 
44
  def predict_student_eligibility(*args):
45
  try:
46
  if model is None or scaler is None:
47
  return "Model not loaded", "N/A", "N/A", create_error_plot()
48
 
49
+ # Create input dictionary with correct feature names
50
  input_data = {feature_names[i]: args[i] for i in range(len(feature_names))}
51
  input_df = pd.DataFrame([input_data])
52
+
53
+ # Ensure columns are in correct order
54
+ input_df = input_df[feature_names]
55
+
56
+ # Scale and reshape input
57
  input_scaled = scaler.transform(input_df)
58
  input_reshaped = input_scaled.reshape(input_scaled.shape[0], input_scaled.shape[1], 1)
59
 
 
91
  [{"type": "bar"}, {"type": "scatter"}]]
92
  )
93
 
94
+ # Prediction probability gauge
95
  fig.add_trace(
96
  go.Indicator(
97
  mode="gauge+number",
 
113
  ), row=1, col=1
114
  )
115
 
116
+ # Confidence meter
117
  confidence = abs(probability - 0.5) * 2
118
  fig.add_trace(
119
  go.Indicator(
 
132
  ), row=1, col=2
133
  )
134
 
135
+ # Input features bar chart
136
  features = list(input_data.keys())
137
  values = list(input_data.values())
138
+ fig.add_trace(
139
+ go.Bar(
140
+ x=features,
141
+ y=values,
142
+ name="Input Values",
143
+ marker_color="skyblue",
144
+ text=values,
145
+ textposition='auto'
146
+ ),
147
+ row=2, col=1
148
+ )
149
 
150
+ # Probability distribution
151
  fig.add_trace(
152
  go.Scatter(
153
+ x=[0, 1],
154
+ y=[probability, probability],
155
  mode='lines+markers',
156
  name="Probability",
157
  line=dict(color="red", width=3),
158
  marker=dict(size=10)
159
+ ),
160
+ row=2, col=2
161
  )
162
 
163
  fig.update_layout(
164
  height=800,
165
  showlegend=False,
166
  title_text="Student Eligibility Prediction Dashboard",
167
+ title_x=0.5,
168
+ margin=dict(l=50, r=50, t=100, b=50)
169
  )
170
 
171
+ # Update x-axis for probability plot
172
+ fig.update_xaxes(title_text="", row=2, col=2, range=[-0.1, 1.1])
173
+ fig.update_yaxes(title_text="Probability", row=2, col=2, range=[0, 1])
174
+
175
  return fig
176
  except Exception as e:
177
  return create_error_plot()
 
185
  return "Please upload a CSV file.", None
186
 
187
  df = pd.read_csv(file)
188
+
189
+ # Check for required features
190
  missing_features = set(feature_names) - set(df.columns)
191
  if missing_features:
192
+ return f"Missing features: {', '.join(missing_features)}", None
193
 
194
+ # Ensure correct column order
195
  df_features = df[feature_names]
196
  df_scaled = scaler.transform(df_features)
197
  df_reshaped = df_scaled.reshape(df_scaled.shape[0], df_scaled.shape[1], 1)
 
199
  probabilities = model.predict(df_reshaped).flatten()
200
  predictions = ["Eligible" if p > 0.5 else "Not Eligible" for p in probabilities]
201
 
202
+ results_df = df.copy()
203
  results_df['Probability'] = probabilities
204
  results_df['Prediction'] = predictions
205
  results_df['Confidence'] = np.abs(probabilities - 0.5) * 2
 
227
  return f"Error processing file: {str(e)}", None
228
 
229
  # Gradio UI
230
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
 
 
231
  gr.Markdown("# πŸŽ“ Student Eligibility Prediction")
232
+ gr.Markdown("This app predicts student eligibility based on academic performance metrics.")
233
+
234
  with gr.Tabs():
235
+ with gr.Tab("πŸ“ Single Prediction"):
 
 
236
  with gr.Row():
237
+ with gr.Column():
238
+ inputs = [gr.Number(label=feature, value=75) for feature in feature_names]
239
+ predict_btn = gr.Button("Predict", variant="primary")
240
+ with gr.Column():
241
+ prediction = gr.Textbox(label="Prediction")
242
+ probability = gr.Textbox(label="Probability")
243
+ confidence = gr.Textbox(label="Confidence")
244
  plot = gr.Plot()
245
+
246
+ predict_btn.click(
247
+ predict_student_eligibility,
248
+ inputs=inputs,
249
+ outputs=[prediction, probability, confidence, plot]
250
+ )
251
+
252
+ with gr.Tab("πŸ“ Batch Prediction"):
253
+ gr.Markdown("Upload a CSV file with student data to get batch predictions.")
254
+ with gr.Row():
255
+ with gr.Column():
256
+ file_input = gr.File(
257
+ label="Upload CSV",
258
+ file_types=[".csv"],
259
+ type="filepath"
260
+ )
261
+ batch_btn = gr.Button("Process Batch", variant="primary")
262
+ with gr.Column():
263
+ batch_output = gr.Textbox(label="Results", lines=10)
264
+ download = gr.File(label="Download Predictions")
265
+
266
+ batch_btn.click(
267
+ batch_predict,
268
+ inputs=file_input,
269
+ outputs=[batch_output, download]
270
+ )
271
+
272
+ # Footer
273
+ gr.Markdown("---")
274
+ gr.Markdown("> Note: This model was trained on student eligibility data. Ensure your input features match the training data format.")
275
 
276
  # Launch app
277
+ if __name__ == "__main__":
278
+ demo.launch()