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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -114
app.py CHANGED
@@ -4,8 +4,9 @@ import numpy as np
4
  import pickle
5
  import json
6
  import tensorflow as tf
7
- from tensorflow.keras.models import load_model, model_from_json
8
  import plotly.graph_objects as go
 
9
  import os
10
 
11
  # Set environment variable to avoid oneDNN warnings
@@ -14,22 +15,17 @@ os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
14
  # Load model artifacts
15
  def load_model_artifacts():
16
  try:
17
- # Load model architecture first
18
  with open('model_architecture.json', 'r') as json_file:
19
  model_json = json_file.read()
20
  model = model_from_json(model_json)
21
-
22
- # Then load weights
23
  model.load_weights('final_model.h5')
24
-
25
- # Load the scaler
26
  with open('scaler.pkl', 'rb') as f:
27
  scaler = pickle.load(f)
28
-
29
- # Load metadata
30
  with open('metadata.json', 'r') as f:
31
  metadata = json.load(f)
32
-
33
  return model, scaler, metadata
34
  except Exception as e:
35
  raise Exception(f"Error loading model artifacts: {str(e)}")
@@ -37,47 +33,35 @@ def load_model_artifacts():
37
  # Initialize model components
38
  try:
39
  model, scaler, metadata = load_model_artifacts()
40
- feature_names = metadata['feature_names']
 
41
  print(f"βœ… Model loaded successfully with features: {feature_names}")
42
  except Exception as e:
43
  print(f"❌ Error loading model: {e}")
44
- # Fallback values for testing
45
  model, scaler, metadata = None, None, {}
46
- feature_names = ['Feature_1', 'Feature_2', 'Feature_3', 'Feature_4']
47
 
48
  def predict_student_eligibility(*args):
49
- """Predict student eligibility based on input features"""
50
  try:
51
  if model is None or scaler is None:
52
  return "Model not loaded", "N/A", "N/A", create_error_plot()
53
-
54
- # Create input dictionary from gradio inputs
55
  input_data = {feature_names[i]: args[i] for i in range(len(feature_names))}
56
-
57
- # Convert to DataFrame
58
  input_df = pd.DataFrame([input_data])
59
-
60
- # Scale the input
61
  input_scaled = scaler.transform(input_df)
62
-
63
- # Reshape for CNN
64
  input_reshaped = input_scaled.reshape(input_scaled.shape[0], input_scaled.shape[1], 1)
65
-
66
- # Make prediction
67
  probability = float(model.predict(input_reshaped)[0][0])
68
  prediction = "Eligible" if probability > 0.5 else "Not Eligible"
69
- confidence = abs(probability - 0.5) * 2 # Convert to confidence score
70
-
71
- # Create prediction visualization
72
  fig = create_prediction_viz(probability, prediction, input_data)
73
-
74
  return prediction, f"{probability:.4f}", f"{confidence:.4f}", fig
75
-
76
  except Exception as e:
77
  return f"Error: {str(e)}", "N/A", "N/A", create_error_plot()
78
 
79
  def create_error_plot():
80
- """Create a simple error plot"""
81
  fig = go.Figure()
82
  fig.add_annotation(
83
  text="Model not available or error occurred",
@@ -93,22 +77,18 @@ def create_error_plot():
93
  return fig
94
 
95
  def create_prediction_viz(probability, prediction, input_data):
96
- """Create visualization for prediction results"""
97
  try:
98
- # Create subplots
99
  fig = make_subplots(
100
  rows=2, cols=2,
101
  subplot_titles=('Prediction Probability', 'Confidence Meter', 'Input Features', 'Probability Distribution'),
102
  specs=[[{"type": "indicator"}, {"type": "indicator"}],
103
  [{"type": "bar"}, {"type": "scatter"}]]
104
  )
105
-
106
- # Prediction probability gauge
107
  fig.add_trace(
108
  go.Indicator(
109
  mode="gauge+number",
110
  value=probability,
111
- domain={'x': [0, 1], 'y': [0, 1]},
112
  title={'text': "Eligibility Probability"},
113
  gauge={
114
  'axis': {'range': [None, 1]},
@@ -123,17 +103,14 @@ def create_prediction_viz(probability, prediction, input_data):
123
  'value': 0.5
124
  }
125
  }
126
- ),
127
- row=1, col=1
128
  )
129
-
130
- # Confidence meter
131
  confidence = abs(probability - 0.5) * 2
132
  fig.add_trace(
133
  go.Indicator(
134
  mode="gauge+number",
135
  value=confidence,
136
- domain={'x': [0, 1], 'y': [0, 1]},
137
  title={'text': "Prediction Confidence"},
138
  gauge={
139
  'axis': {'range': [None, 1]},
@@ -144,143 +121,103 @@ def create_prediction_viz(probability, prediction, input_data):
144
  {'range': [0.7, 1], 'color': "lightgreen"}
145
  ]
146
  }
147
- ),
148
- row=1, col=2
149
  )
150
-
151
- # Input features bar chart
152
  features = list(input_data.keys())
153
  values = list(input_data.values())
154
-
155
- fig.add_trace(
156
- go.Bar(x=features, y=values, name="Input Values", marker_color="skyblue"),
157
- row=2, col=1
158
- )
159
-
160
- # Simple probability visualization
161
  fig.add_trace(
162
  go.Scatter(
163
- x=[0, 1],
164
- y=[probability, probability],
165
  mode='lines+markers',
166
- name="Probability",
167
  line=dict(color="red", width=3),
168
  marker=dict(size=10)
169
- ),
170
- row=2, col=2
171
  )
172
-
173
  fig.update_layout(
174
  height=800,
175
  showlegend=False,
176
  title_text="Student Eligibility Prediction Dashboard",
177
  title_x=0.5
178
  )
179
-
180
  return fig
181
  except Exception as e:
182
  return create_error_plot()
183
 
184
  def batch_predict(file):
185
- """Batch prediction from uploaded CSV file"""
186
  try:
187
  if model is None or scaler is None:
188
  return "Model not loaded. Please check if all model files are uploaded.", None
189
-
190
  if file is None:
191
  return "Please upload a CSV file.", None
192
-
193
- # Read the uploaded file
194
  df = pd.read_csv(file)
195
-
196
- # Check if all required features are present
197
  missing_features = set(feature_names) - set(df.columns)
198
  if missing_features:
199
  return f"Missing features: {missing_features}", None
200
-
201
- # Select only the required features
202
  df_features = df[feature_names]
203
-
204
- # Scale the features
205
  df_scaled = scaler.transform(df_features)
206
-
207
- # Reshape for CNN
208
  df_reshaped = df_scaled.reshape(df_scaled.shape[0], df_scaled.shape[1], 1)
209
-
210
- # Make predictions
211
  probabilities = model.predict(df_reshaped).flatten()
212
  predictions = ["Eligible" if p > 0.5 else "Not Eligible" for p in probabilities]
213
-
214
- # Create results dataframe
215
  results_df = df_features.copy()
216
  results_df['Probability'] = probabilities
217
  results_df['Prediction'] = predictions
218
  results_df['Confidence'] = np.abs(probabilities - 0.5) * 2
219
-
220
- # Save results
221
  output_file = "batch_predictions.csv"
222
  results_df.to_csv(output_file, index=False)
223
-
224
- # Create summary statistics
225
- eligible_count = sum(1 for p in predictions if p == 'Eligible')
226
- not_eligible_count = len(predictions) - eligible_count
227
-
228
  summary = f"""Batch Prediction Summary:
229
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
230
  πŸ“Š Total predictions: {len(results_df)}
231
- βœ… Eligible: {eligible_count} ({eligible_count/len(predictions)*100:.1f}%)
232
- ❌ Not Eligible: {not_eligible_count} ({not_eligible_count/len(predictions)*100:.1f}%)
233
  πŸ“ˆ Average Probability: {np.mean(probabilities):.4f}
234
  🎯 Average Confidence: {np.mean(np.abs(probabilities - 0.5) * 2):.4f}
235
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
236
-
237
  Results saved to: {output_file}
238
  """
239
-
240
  return summary, output_file
241
-
242
  except Exception as e:
243
  return f"Error processing file: {str(e)}", None
244
 
245
- # Create Gradio interface
246
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
 
 
247
  gr.Markdown("# πŸŽ“ Student Eligibility Prediction")
248
-
249
  with gr.Tabs():
250
  with gr.Tab("Single Prediction"):
251
- inputs = []
252
- for feature in feature_names:
253
- inputs.append(gr.Number(label=feature, value=75))
254
-
255
  predict_btn = gr.Button("Predict")
256
-
257
  with gr.Row():
258
  prediction = gr.Textbox(label="Prediction")
259
  probability = gr.Textbox(label="Probability")
260
  confidence = gr.Textbox(label="Confidence")
261
-
262
  plot = gr.Plot()
263
-
264
- predict_btn.click(
265
- predict_student_eligibility,
266
- inputs=inputs,
267
- outputs=[prediction, probability, confidence, plot]
268
- )
269
-
270
  with gr.Tab("Batch Prediction"):
271
- file_input = gr.File(
272
- label="Upload CSV",
273
- file_types=[".csv"],
274
- type="filepath" # Fixed: Changed from 'file' to 'filepath'
275
- )
276
  batch_btn = gr.Button("Process Batch")
277
  batch_output = gr.Textbox(label="Results")
278
  download = gr.File(label="Download")
279
-
280
- batch_btn.click(
281
- batch_predict,
282
- inputs=file_input,
283
- outputs=[batch_output, download]
284
- )
285
-
286
- demo.launch()
 
4
  import pickle
5
  import json
6
  import tensorflow as tf
7
+ from tensorflow.keras.models import model_from_json
8
  import plotly.graph_objects as go
9
+ from plotly.subplots import make_subplots
10
  import os
11
 
12
  # Set environment variable to avoid oneDNN warnings
 
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)
 
 
21
  model.load_weights('final_model.h5')
22
+
 
23
  with open('scaler.pkl', 'rb') as f:
24
  scaler = pickle.load(f)
25
+
 
26
  with open('metadata.json', 'r') as f:
27
  metadata = json.load(f)
28
+
29
  return model, scaler, metadata
30
  except Exception as e:
31
  raise Exception(f"Error loading model artifacts: {str(e)}")
 
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
+
 
54
  probability = float(model.predict(input_reshaped)[0][0])
55
  prediction = "Eligible" if probability > 0.5 else "Not Eligible"
56
+ confidence = abs(probability - 0.5) * 2
 
 
57
  fig = create_prediction_viz(probability, prediction, input_data)
58
+
59
  return prediction, f"{probability:.4f}", f"{confidence:.4f}", fig
60
+
61
  except Exception as e:
62
  return f"Error: {str(e)}", "N/A", "N/A", create_error_plot()
63
 
64
  def create_error_plot():
 
65
  fig = go.Figure()
66
  fig.add_annotation(
67
  text="Model not available or error occurred",
 
77
  return fig
78
 
79
  def create_prediction_viz(probability, prediction, input_data):
 
80
  try:
 
81
  fig = make_subplots(
82
  rows=2, cols=2,
83
  subplot_titles=('Prediction Probability', 'Confidence Meter', 'Input Features', 'Probability Distribution'),
84
  specs=[[{"type": "indicator"}, {"type": "indicator"}],
85
  [{"type": "bar"}, {"type": "scatter"}]]
86
  )
87
+
 
88
  fig.add_trace(
89
  go.Indicator(
90
  mode="gauge+number",
91
  value=probability,
 
92
  title={'text': "Eligibility Probability"},
93
  gauge={
94
  'axis': {'range': [None, 1]},
 
103
  'value': 0.5
104
  }
105
  }
106
+ ), row=1, col=1
 
107
  )
108
+
 
109
  confidence = abs(probability - 0.5) * 2
110
  fig.add_trace(
111
  go.Indicator(
112
  mode="gauge+number",
113
  value=confidence,
 
114
  title={'text': "Prediction Confidence"},
115
  gauge={
116
  'axis': {'range': [None, 1]},
 
121
  {'range': [0.7, 1], 'color': "lightgreen"}
122
  ]
123
  }
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()
151
 
152
  def batch_predict(file):
 
153
  try:
154
  if model is None or scaler is None:
155
  return "Model not loaded. Please check if all model files are uploaded.", None
156
+
157
  if file is None:
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)
168
+
 
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
176
+
 
177
  output_file = "batch_predictions.csv"
178
  results_df.to_csv(output_file, index=False)
179
+
180
+ eligible_count = predictions.count('Eligible')
181
+ not_eligible_count = predictions.count('Not Eligible')
182
+
 
183
  summary = f"""Batch Prediction Summary:
184
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
185
  πŸ“Š Total predictions: {len(results_df)}
186
+ βœ… Eligible: {eligible_count} ({eligible_count / len(predictions) * 100:.1f}%)
187
+ ❌ Not Eligible: {not_eligible_count} ({not_eligible_count / len(predictions) * 100:.1f}%)
188
  πŸ“ˆ Average Probability: {np.mean(probabilities):.4f}
189
  🎯 Average Confidence: {np.mean(np.abs(probabilities - 0.5) * 2):.4f}
190
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 
191
  Results saved to: {output_file}
192
  """
193
+
194
  return summary, output_file
195
+
196
  except Exception as e:
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()