Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -5,22 +5,24 @@ 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 |
-
#
|
13 |
-
|
|
|
|
|
|
|
14 |
|
15 |
-
|
16 |
-
|
|
|
17 |
try:
|
18 |
# Load model architecture
|
19 |
with open('model_architecture.json', 'r') as json_file:
|
20 |
model_json = json_file.read()
|
21 |
model = model_from_json(model_json)
|
22 |
|
23 |
-
# Load
|
24 |
model.load_weights('final_model.h5')
|
25 |
|
26 |
# Load scaler
|
@@ -30,261 +32,54 @@ def load_model_artifacts():
|
|
30 |
# Load metadata
|
31 |
with open('metadata.json', 'r') as f:
|
32 |
metadata = json.load(f)
|
33 |
-
|
34 |
-
|
35 |
-
|
|
|
36 |
except Exception as e:
|
37 |
-
print(f"❌ Error loading model
|
38 |
-
return None, None, {}
|
39 |
|
40 |
-
# Load model
|
41 |
-
|
42 |
-
if model:
|
43 |
-
feature_names = metadata.get('feature_names', ['Feature_1', 'Feature_2'])
|
44 |
-
print(f"✅ Model loaded successfully with features: {feature_names}")
|
45 |
-
else:
|
46 |
-
feature_names = ['Feature_1', 'Feature_2']
|
47 |
-
print("❌ Model failed to load - running in demo mode with placeholder features")
|
48 |
|
49 |
-
def
|
50 |
try:
|
51 |
if model is None or scaler is None:
|
52 |
-
raise
|
53 |
-
|
54 |
# Create input dictionary
|
55 |
input_data = {feature_names[i]: float(args[i]) for i in range(len(feature_names))}
|
56 |
-
|
57 |
-
# Create DataFrame ensuring correct column order
|
58 |
-
input_df = pd.DataFrame([input_data], columns=feature_names)
|
59 |
|
60 |
# Scale features
|
61 |
-
|
62 |
-
|
63 |
-
# Reshape for CNN (samples, timesteps, features)
|
64 |
-
input_reshaped = input_scaled.reshape(input_scaled.shape[0], input_scaled.shape[1], 1)
|
65 |
|
66 |
-
#
|
67 |
-
probability = float(model.predict(
|
68 |
prediction = "Eligible" if probability > 0.5 else "Not Eligible"
|
69 |
-
confidence = abs(probability - 0.5) * 2 # Convert to 0-1 range
|
70 |
-
|
71 |
-
# Create 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 |
-
error_msg = f"Error: {str(e)}"
|
78 |
-
print(error_msg)
|
79 |
-
return error_msg, "N/A", "N/A", create_error_plot(error_msg)
|
80 |
-
|
81 |
-
def create_error_plot(message="Model not available or error occurred"):
|
82 |
-
fig = go.Figure()
|
83 |
-
fig.add_annotation(
|
84 |
-
text=message,
|
85 |
-
xref="paper", yref="paper",
|
86 |
-
x=0.5, y=0.5, xanchor='center', yanchor='middle',
|
87 |
-
showarrow=False, font=dict(size=16, color="red")
|
88 |
-
)
|
89 |
-
fig.update_layout(
|
90 |
-
xaxis={'visible': False},
|
91 |
-
yaxis={'visible': False},
|
92 |
-
height=400,
|
93 |
-
margin=dict(l=20, r=20, t=30, b=20)
|
94 |
-
)
|
95 |
-
return fig
|
96 |
-
|
97 |
-
def create_prediction_viz(probability, prediction, input_data):
|
98 |
-
try:
|
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 |
-
title={'text': "Eligibility Probability"},
|
112 |
-
gauge={
|
113 |
-
'axis': {'range': [None, 1]},
|
114 |
-
'bar': {'color': "darkblue"},
|
115 |
-
'steps': [
|
116 |
-
{'range': [0, 0.5], 'color': "lightcoral"},
|
117 |
-
{'range': [0.5, 1], 'color': "lightgreen"}
|
118 |
-
],
|
119 |
-
'threshold': {
|
120 |
-
'line': {'color': "red", 'width': 4},
|
121 |
-
'thickness': 0.75,
|
122 |
-
'value': 0.5
|
123 |
-
}
|
124 |
-
}
|
125 |
-
), row=1, col=1
|
126 |
-
)
|
127 |
-
|
128 |
-
# Confidence meter
|
129 |
confidence = abs(probability - 0.5) * 2
|
130 |
-
fig.add_trace(
|
131 |
-
go.Indicator(
|
132 |
-
mode="gauge+number",
|
133 |
-
value=confidence,
|
134 |
-
title={'text': "Prediction Confidence"},
|
135 |
-
gauge={
|
136 |
-
'axis': {'range': [None, 1]},
|
137 |
-
'bar': {'color': "orange"},
|
138 |
-
'steps': [
|
139 |
-
{'range': [0, 0.3], 'color': "lightcoral"},
|
140 |
-
{'range': [0.3, 0.7], 'color': "lightyellow"},
|
141 |
-
{'range': [0.7, 1], 'color': "lightgreen"}
|
142 |
-
]
|
143 |
-
}
|
144 |
-
), row=1, col=2
|
145 |
-
)
|
146 |
-
|
147 |
-
# Input features bar chart
|
148 |
-
features = list(input_data.keys())
|
149 |
-
values = list(input_data.values())
|
150 |
-
fig.add_trace(
|
151 |
-
go.Bar(
|
152 |
-
x=features,
|
153 |
-
y=values,
|
154 |
-
name="Input Values",
|
155 |
-
marker_color="skyblue",
|
156 |
-
text=values,
|
157 |
-
textposition='auto'
|
158 |
-
),
|
159 |
-
row=2, col=1
|
160 |
-
)
|
161 |
-
|
162 |
-
# Probability distribution
|
163 |
-
fig.add_trace(
|
164 |
-
go.Scatter(
|
165 |
-
x=[0, 1],
|
166 |
-
y=[probability, probability],
|
167 |
-
mode='lines+markers',
|
168 |
-
name="Probability",
|
169 |
-
line=dict(color="red", width=3),
|
170 |
-
marker=dict(size=10)
|
171 |
-
),
|
172 |
-
row=2, col=2
|
173 |
-
)
|
174 |
-
|
175 |
-
fig.update_layout(
|
176 |
-
height=800,
|
177 |
-
showlegend=False,
|
178 |
-
title_text="Student Eligibility Prediction Dashboard",
|
179 |
-
title_x=0.5,
|
180 |
-
margin=dict(l=50, r=50, t=100, b=50)
|
181 |
-
)
|
182 |
-
|
183 |
-
# Update x-axis for probability plot
|
184 |
-
fig.update_xaxes(title_text="", row=2, col=2, range=[-0.1, 1.1])
|
185 |
-
fig.update_yaxes(title_text="Probability", row=2, col=2, range=[0, 1])
|
186 |
-
|
187 |
-
return fig
|
188 |
-
except Exception as e:
|
189 |
-
return create_error_plot(str(e))
|
190 |
-
|
191 |
-
def batch_predict(file):
|
192 |
-
try:
|
193 |
-
if model is None or scaler is None:
|
194 |
-
return "Model not loaded. Please check if all model files are uploaded.", None
|
195 |
-
|
196 |
-
if file is None:
|
197 |
-
return "Please upload a CSV file.", None
|
198 |
-
|
199 |
-
df = pd.read_csv(file)
|
200 |
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
# Ensure correct column order
|
207 |
-
df_features = df[feature_names]
|
208 |
-
df_scaled = scaler.transform(df_features)
|
209 |
-
df_reshaped = df_scaled.reshape(df_scaled.shape[0], df_scaled.shape[1], 1)
|
210 |
-
|
211 |
-
probabilities = model.predict(df_reshaped).flatten()
|
212 |
-
predictions = ["Eligible" if p > 0.5 else "Not Eligible" for p in probabilities]
|
213 |
-
|
214 |
-
results_df = df.copy()
|
215 |
-
results_df['Probability'] = probabilities
|
216 |
-
results_df['Prediction'] = predictions
|
217 |
-
results_df['Confidence'] = np.abs(probabilities - 0.5) * 2
|
218 |
-
|
219 |
-
output_file = "batch_predictions.csv"
|
220 |
-
results_df.to_csv(output_file, index=False)
|
221 |
-
|
222 |
-
eligible_count = predictions.count('Eligible')
|
223 |
-
not_eligible_count = predictions.count('Not Eligible')
|
224 |
-
|
225 |
-
summary = f"""Batch Prediction Summary:
|
226 |
-
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
227 |
-
📊 Total predictions: {len(results_df)}
|
228 |
-
✅ Eligible: {eligible_count} ({eligible_count / len(predictions) * 100:.1f}%)
|
229 |
-
❌ Not Eligible: {not_eligible_count} ({not_eligible_count / len(predictions) * 100:.1f}%)
|
230 |
-
📈 Average Probability: {np.mean(probabilities):.4f}
|
231 |
-
🎯 Average Confidence: {np.mean(np.abs(probabilities - 0.5) * 2):.4f}
|
232 |
-
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
233 |
-
Results saved to: {output_file}
|
234 |
-
"""
|
235 |
-
|
236 |
-
return summary, output_file
|
237 |
-
|
238 |
except Exception as e:
|
239 |
-
return
|
240 |
-
|
241 |
-
# Gradio
|
242 |
-
|
243 |
-
|
244 |
-
gr.
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
probability = gr.Textbox(label="Probability")
|
255 |
-
confidence = gr.Textbox(label="Confidence")
|
256 |
-
plot = gr.Plot()
|
257 |
-
|
258 |
-
predict_btn.click(
|
259 |
-
predict_student_eligibility,
|
260 |
-
inputs=inputs,
|
261 |
-
outputs=[prediction, probability, confidence, plot]
|
262 |
-
)
|
263 |
-
|
264 |
-
with gr.Tab("📁 Batch Prediction"):
|
265 |
-
gr.Markdown("Upload a CSV file with student data to get batch predictions.")
|
266 |
-
with gr.Row():
|
267 |
-
with gr.Column():
|
268 |
-
file_input = gr.File(
|
269 |
-
label="Upload CSV",
|
270 |
-
file_types=[".csv"],
|
271 |
-
type="filepath"
|
272 |
-
)
|
273 |
-
batch_btn = gr.Button("Process Batch", variant="primary")
|
274 |
-
with gr.Column():
|
275 |
-
batch_output = gr.Textbox(label="Results", lines=10)
|
276 |
-
download = gr.File(label="Download Predictions")
|
277 |
-
|
278 |
-
batch_btn.click(
|
279 |
-
batch_predict,
|
280 |
-
inputs=file_input,
|
281 |
-
outputs=[batch_output, download]
|
282 |
-
)
|
283 |
-
|
284 |
-
# Footer
|
285 |
-
gr.Markdown("---")
|
286 |
-
gr.Markdown("> Note: This model was trained on student eligibility data. Ensure your input features match the training data format.")
|
287 |
|
288 |
-
# Launch app
|
289 |
if __name__ == "__main__":
|
290 |
-
|
|
|
5 |
import json
|
6 |
import tensorflow as tf
|
7 |
from tensorflow.keras.models import model_from_json
|
|
|
|
|
8 |
import os
|
9 |
|
10 |
+
# Initialize model components
|
11 |
+
model = None
|
12 |
+
scaler = None
|
13 |
+
metadata = {}
|
14 |
+
feature_names = []
|
15 |
|
16 |
+
def load_model():
|
17 |
+
global model, scaler, metadata, feature_names
|
18 |
+
|
19 |
try:
|
20 |
# Load model architecture
|
21 |
with open('model_architecture.json', 'r') as json_file:
|
22 |
model_json = json_file.read()
|
23 |
model = model_from_json(model_json)
|
24 |
|
25 |
+
# Load weights
|
26 |
model.load_weights('final_model.h5')
|
27 |
|
28 |
# Load scaler
|
|
|
32 |
# Load metadata
|
33 |
with open('metadata.json', 'r') as f:
|
34 |
metadata = json.load(f)
|
35 |
+
feature_names = metadata['feature_names']
|
36 |
+
|
37 |
+
print("✅ Model loaded successfully!")
|
38 |
+
print(f"Using features: {feature_names}")
|
39 |
except Exception as e:
|
40 |
+
print(f"❌ Error loading model: {str(e)}")
|
|
|
41 |
|
42 |
+
# Load model at startup
|
43 |
+
load_model()
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
|
45 |
+
def predict(*args):
|
46 |
try:
|
47 |
if model is None or scaler is None:
|
48 |
+
raise Exception("Model not loaded. Please check the model files.")
|
49 |
+
|
50 |
# Create input dictionary
|
51 |
input_data = {feature_names[i]: float(args[i]) for i in range(len(feature_names))}
|
52 |
+
input_df = pd.DataFrame([input_data])
|
|
|
|
|
53 |
|
54 |
# Scale features
|
55 |
+
scaled_input = scaler.transform(input_df)
|
|
|
|
|
|
|
56 |
|
57 |
+
# Predict
|
58 |
+
probability = float(model.predict(scaled_input)[0][0])
|
59 |
prediction = "Eligible" if probability > 0.5 else "Not Eligible"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
60 |
confidence = abs(probability - 0.5) * 2
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
|
62 |
+
return {
|
63 |
+
"Prediction": prediction,
|
64 |
+
"Probability": f"{probability:.4f}",
|
65 |
+
"Confidence": f"{confidence:.4f}"
|
66 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
except Exception as e:
|
68 |
+
return {"Error": str(e)}
|
69 |
+
|
70 |
+
# Create Gradio interface
|
71 |
+
iface = gr.Interface(
|
72 |
+
fn=predict,
|
73 |
+
inputs=[gr.Number(label=name) for name in feature_names],
|
74 |
+
outputs=[
|
75 |
+
gr.Textbox(label="Prediction"),
|
76 |
+
gr.Textbox(label="Probability"),
|
77 |
+
gr.Textbox(label="Confidence")
|
78 |
+
],
|
79 |
+
title="🎓 Student Eligibility Predictor",
|
80 |
+
description="Predict student eligibility based on academic performance metrics",
|
81 |
+
examples=[[75, 80, 85] if len(feature_names) >= 3 else [75, 80]] # Example inputs
|
82 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
83 |
|
|
|
84 |
if __name__ == "__main__":
|
85 |
+
iface.launch()
|