import streamlit as st import pandas as pd import joblib from datetime import datetime from huggingface_hub import hf_hub_download st.set_page_config( page_title="Credit Risk App", page_icon="đŧ", layout="centered" ) # Load model @st.cache_resource def load_model(): model_path = hf_hub_download( repo_id="ZeeshanWattoo/random-forest-credit-model", filename="random_forest_model1.pkl" ) return joblib.load(model_path) model = load_model() # Category mappings home_mapping = {"Own": 2, "Mortgage": 1, "Rent": 0} intent_mapping = { "education": 0, "home_improvement": 1, "medical": 2, "personal": 3, "venture": 4 } default_mapping = {"Yes": 1, "No": 0} st.markdown("
đ Enter applicant details to predict the likelihood of loan repayment or default.
", unsafe_allow_html=True) with st.sidebar: st.markdown( "This app predicts the risk of default for loan applicants using a trained Random Forest model.
" "Created By: Zeeshan Ahmad Wattoo
"
"Framework: Streamlit
"
"Deployed on: Hugging Face đ¤
đĄ Tips: Use the sliders and inputs below to enter applicant details.
", unsafe_allow_html=True ) # Name input with placeholder and persistent state if "user_name" not in st.session_state: st.session_state.user_name = "" user_name = st.text_input( "đ¤ Enter Your Name", value=st.session_state.user_name, placeholder="Enter your name" ) st.session_state.user_name = user_name # Input form col1, col2 = st.columns(2) with col1: age = st.slider("đ Age", 18, 100, 30) income = st.number_input("đ° Annual Income ($)", min_value=0.0, value=50000.0, step=1000.0) emp_length = st.slider("đ Employment Length (years)", 0, 50, 5) intent = st.selectbox("đĻ Loan Purpose", ["education", "home_improvement", "medical", "personal", "venture"]) with col2: home = st.radio("đ Home Ownership", ["Own", "Mortgage", "Rent"]) amount = st.number_input("đĩ Loan Amount ($)", min_value=0.0, value=10000.0, step=500.0) rate = st.slider("đ Interest Rate (%)", 0.0, 100.0, 10.0, 0.5) default = st.radio("â ī¸ Previous Default", ["Yes", "No"]) cred_length = st.slider("đ Credit History Length (years)", 0, 50, 10) if income == 0: st.warning("â ī¸ Annual income must be greater than 0.") st.stop() # Derived feature percent_income = amount / income # Input DataFrame input_df = pd.DataFrame({ "Age": [age], "Income": [income], "Home": [home_mapping[home]], "Emp_length": [emp_length], "Intent": [intent_mapping[intent]], "Amount": [amount], "Rate": [rate], "Percent_income": [percent_income], "Default": [default_mapping[default]], "Cred_length": [cred_length] }) # Prediction button if st.button("đ Predict Credit Risk"): prediction = model.predict(input_df) proba = model.predict_proba(input_df)[0] if prediction[0] == 0: # Fully Paid st.balloons() st.success(f"đ **Congratulations, {user_name or 'Applicant'}!** You are eligible to get the loan. đ°") st.markdown("â **Prediction:** đĸ Fully Paid") st.metric(label="Loan Risk Score (Default)", value=f"{proba[1]*100:.1f}%") else: # Charged Off st.warning( f"â ī¸ **Sorry, {user_name or 'Applicant'}.** Based on our analysis, there is a high risk of default for this application. " f"Unfortunately, you are currently **not eligible for the loan**." ) st.markdown("â **Prediction:** đ´ Charged Off") st.metric(label="Loan Risk Score (Default)", value=f"{proba[1]*100:.1f}%") # Visualize progress st.progress(int(proba[1]*100)) # Probability details st.subheader("đ Prediction Probabilities") st.write(f"đĸ Fully Paid: **{proba[0] * 100:.2f}%**") st.write(f"đ´ Charged Off: **{proba[1] * 100:.2f}%**") # Show data preview st.subheader("đ Input Data Overview") st.dataframe(input_df.style.highlight_max(axis=1)) # Prepare downloadable results result_df = input_df.copy() status = "Fully Paid" if prediction[0] == 0 else "Charged Off" result_df["Predicted Status"] = status result_df["Fully Paid Probability (%)"] = round(proba[0] * 100, 2) result_df["Charged Off Probability (%)"] = round(proba[1] * 100, 2) filename = f"credit_risk_prediction_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv" st.download_button( label="đž Download Prediction as CSV", data=result_df.to_csv(index=False), file_name=filename, mime="text/csv" ) # Centered Footer st.markdown("---") st.markdown( "