CoolFace
Apppublic

Chethan4638/proactive-churn-predictor

sourceHugging Faceupdated 11mo agoView on Hugging Face
0likes
app.py100 linesDownload Raw Back to root
1import streamlit as st2import pandas as pd3import joblib4 5# --- Configuration ---6PAGE_TITLE = "Proactive Churn Dashboard"7PAGE_ICON = "🎯"8MODEL_FILE = 'churn_model.pkl'9DB_FILE = 'data/model_input.csv'10 11# --- Load Model & Pre-calculate Data ---12# Use st.cache_resource to load model and data only once13@st.cache_resource14def load_model_and_predictions():15    """16    Load the model and pre-calculate all churn probabilities.17    This runs only once when the app starts.18    """19    try:20        model = joblib.load(MODEL_FILE)21    except FileNotFoundError:22        st.error(f"Error: Model file not found. Make sure {MODEL_FILE} is in the repo.")23        return None24 25    try:26        df_full_data = pd.read_csv(DB_FILE)27    except FileNotFoundError:28        st.error(f"Error: Data file not found. Make sure {DB_FILE} is in the repo.")29        return None30 31    # Pre-calculate predictions32    try:33        user_ids = df_full_data['user_id']34        X_to_predict = df_full_data.drop(['user_id', 'churn'], axis=1)35 36        churn_probabilities = model.predict_proba(X_to_predict)[:, 1]37 38        df_results = pd.DataFrame({39            'user_id': user_ids,40            'churn_probability': churn_probabilities41        })42 43        # Sort and return44        return df_results.sort_values(by='churn_probability', ascending=False)45 46    except Exception as e:47        st.error(f"Error during prediction: {e}")48        return None49 50# --- Page Setup ---51st.set_page_config(page_title=PAGE_TITLE, page_icon=PAGE_ICON, layout="wide")52st.title(f"{PAGE_ICON} {PAGE_TITLE}")53 54st.markdown("""55This dashboard retrieves a prioritized list of users who are at high risk of churning.56This version is a self-contained Streamlit app hosted on Hugging Face, loading a pre-trained XGBoost model.57""")58 59# Load the sorted results60df_sorted_results = load_model_and_predictions()61 62if df_sorted_results is not None:63 64    # --- Main App ---65    top_n = st.number_input(66        "How many at-risk users do you want to see?",67        min_value=10,68        max_value=1000,69        value=100,70        step=1071    )72 73    # Get the top N users from the pre-calculated list74    df_top_n = df_sorted_results.head(top_n)75 76    # Clean up for display77    df_display = df_top_n.copy()78    df_display['churn_probability'] = (df_display['churn_probability'] * 100).round(2)79    df_display = df_display.rename(columns={80        'user_id': 'User ID',81        'churn_probability': 'Churn Probability (%)'82    })83 84    st.dataframe(df_display, use_container_width=True, height=500)85 86    # --- Download Button ---87    @st.cache_data88    def convert_df_to_csv(df):89        return df.to_csv(index=False).encode('utf-8')90 91    csv = convert_df_to_csv(df_top_n) # Download the raw data92 93    st.download_button(94        label="Download List as CSV",95        data=csv,96        file_name=f"at_risk_users_top_{top_n}.csv",97        mime="text/csv",98    )99else:100    st.error("Application failed to load model and data. Please check the logs.")