Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -12,73 +12,85 @@ import os
|
|
| 12 |
# Set environment variable to avoid oneDNN warnings
|
| 13 |
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
|
| 14 |
|
| 15 |
-
#
|
| 16 |
def load_model_artifacts():
|
| 17 |
try:
|
| 18 |
-
# Load
|
| 19 |
with open('model_architecture.json', 'r') as json_file:
|
| 20 |
model_json = json_file.read()
|
| 21 |
model = model_from_json(model_json)
|
|
|
|
|
|
|
| 22 |
model.load_weights('final_model.h5')
|
| 23 |
-
|
|
|
|
| 24 |
with open('scaler.pkl', 'rb') as f:
|
| 25 |
scaler = pickle.load(f)
|
| 26 |
-
|
|
|
|
| 27 |
with open('metadata.json', 'r') as f:
|
| 28 |
metadata = json.load(f)
|
| 29 |
|
| 30 |
return model, scaler, metadata
|
|
|
|
| 31 |
except Exception as e:
|
| 32 |
-
|
|
|
|
| 33 |
|
| 34 |
-
#
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
feature_names = metadata
|
| 38 |
print(f"β
Model loaded successfully with features: {feature_names}")
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 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 |
-
|
| 48 |
-
|
| 49 |
-
# Create input dictionary
|
| 50 |
-
input_data = {feature_names[i]: args[i] for i in range(len(feature_names))}
|
| 51 |
-
input_df = pd.DataFrame([input_data])
|
| 52 |
|
| 53 |
-
#
|
| 54 |
-
input_df =
|
| 55 |
|
| 56 |
-
# Scale
|
| 57 |
input_scaled = scaler.transform(input_df)
|
|
|
|
|
|
|
| 58 |
input_reshaped = input_scaled.reshape(input_scaled.shape[0], input_scaled.shape[1], 1)
|
| 59 |
-
|
|
|
|
| 60 |
probability = float(model.predict(input_reshaped)[0][0])
|
| 61 |
prediction = "Eligible" if probability > 0.5 else "Not Eligible"
|
| 62 |
-
confidence = abs(probability - 0.5) * 2
|
|
|
|
|
|
|
| 63 |
fig = create_prediction_viz(probability, prediction, input_data)
|
| 64 |
-
|
| 65 |
return prediction, f"{probability:.4f}", f"{confidence:.4f}", fig
|
| 66 |
|
| 67 |
except Exception as e:
|
| 68 |
-
|
|
|
|
|
|
|
| 69 |
|
| 70 |
-
def create_error_plot():
|
| 71 |
fig = go.Figure()
|
| 72 |
fig.add_annotation(
|
| 73 |
-
text=
|
| 74 |
xref="paper", yref="paper",
|
| 75 |
x=0.5, y=0.5, xanchor='center', yanchor='middle',
|
| 76 |
-
showarrow=False, font=dict(size=
|
| 77 |
)
|
| 78 |
fig.update_layout(
|
| 79 |
xaxis={'visible': False},
|
| 80 |
yaxis={'visible': False},
|
| 81 |
-
height=400
|
|
|
|
| 82 |
)
|
| 83 |
return fig
|
| 84 |
|
|
@@ -174,7 +186,7 @@ def create_prediction_viz(probability, prediction, input_data):
|
|
| 174 |
|
| 175 |
return fig
|
| 176 |
except Exception as e:
|
| 177 |
-
return create_error_plot()
|
| 178 |
|
| 179 |
def batch_predict(file):
|
| 180 |
try:
|
|
@@ -227,7 +239,7 @@ Results saved to: {output_file}
|
|
| 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 |
|
|
|
|
| 12 |
# Set environment variable to avoid oneDNN warnings
|
| 13 |
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
|
| 14 |
|
| 15 |
+
# Initialize model components at startup
|
| 16 |
def load_model_artifacts():
|
| 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 model weights
|
| 24 |
model.load_weights('final_model.h5')
|
| 25 |
+
|
| 26 |
+
# Load scaler
|
| 27 |
with open('scaler.pkl', 'rb') as f:
|
| 28 |
scaler = pickle.load(f)
|
| 29 |
+
|
| 30 |
+
# Load metadata
|
| 31 |
with open('metadata.json', 'r') as f:
|
| 32 |
metadata = json.load(f)
|
| 33 |
|
| 34 |
return model, scaler, metadata
|
| 35 |
+
|
| 36 |
except Exception as e:
|
| 37 |
+
print(f"β Error loading model artifacts: {str(e)}")
|
| 38 |
+
return None, None, {}
|
| 39 |
|
| 40 |
+
# Load model
|
| 41 |
+
model, scaler, metadata = load_model_artifacts()
|
| 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 predict_student_eligibility(*args):
|
| 50 |
try:
|
| 51 |
if model is None or scaler is None:
|
| 52 |
+
raise RuntimeError("Model not loaded - please check the model files")
|
| 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 |
input_scaled = scaler.transform(input_df)
|
| 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 |
+
# 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 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 |
|
|
|
|
| 186 |
|
| 187 |
return fig
|
| 188 |
except Exception as e:
|
| 189 |
+
return create_error_plot(str(e))
|
| 190 |
|
| 191 |
def batch_predict(file):
|
| 192 |
try:
|
|
|
|
| 239 |
return f"Error processing file: {str(e)}", None
|
| 240 |
|
| 241 |
# Gradio UI
|
| 242 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="Student Eligibility Predictor") as demo:
|
| 243 |
gr.Markdown("# π Student Eligibility Prediction")
|
| 244 |
gr.Markdown("This app predicts student eligibility based on academic performance metrics.")
|
| 245 |
|