enoch-alterego's picture
Update app.py
f80acd6 verified
def predict_and_explain(income, credit_score, debt_ratio, employment):
try:
# Prepare input
input_data = pd.DataFrame([[income, credit_score, debt_ratio, employment]],
columns=feature_names)
# Get Prediction
prob = model.predict_proba(input_data)[0][1]
status = "APPROVED" if prob > 0.5 else "REJECTED"
color = "#28a745" if status == "APPROVED" else "#dc3545"
# Generate SHAP Explanation (Stable version)
shap_values = explainer(input_data)
# Create a clean Matplotlib plot
plt.clf() # Clear previous plots
fig = plt.figure(figsize=(8, 4))
# We plot the explanation for the 'Positive' class (Approval)
# For tree models, we take the index [0] for the first row, and [1] for the class
shap.plots.bar(shap_values[0][..., 1], show=False)
plt.title("Decision Transparency Score")
plt.tight_layout()
result_html = f"<div style='text-align: center; padding: 20px; border-radius: 10px; background-color: {color}; color: white;'>" \
f"<h1 style='margin:0;'>LOAN STATUS: {status}</h1>" \
f"<h3>Confidence Score: {prob*100:.1f}%</h3></div>"
return result_html, fig
except Exception as e:
# This will show you exactly what is wrong in the UI if it fails again
return f"<div style='color:red;'>Error: {str(e)}</div>", None