import streamlit as st import pandas as pd import joblib import numpy as np import warnings from streamlit.components.v1 import html import time # For simulating loading # --- Set page configuration --- st.set_page_config( page_title="CreditIQ - AI-Powered Credit Expenditure Prediction", page_icon="💳", layout="wide", # Use wide layout to better accommodate complex design initial_sidebar_state="collapsed" # Hide sidebar to give full canvas ) # --- Initialize session state for page management --- if 'active_page' not in st.session_state: st.session_state.active_page = 'home' if 'show_prediction' not in st.session_state: st.session_state.show_prediction = False if 'predicted_value' not in st.session_state: st.session_state.predicted_value = 0.0 warnings.filterwarnings('ignore') st.markdown(""" """, unsafe_allow_html=True) # --- Inject Custom HTML, CSS, and Inline JavaScript --- # This block defines the sophisticated styling and background animations, # navigation, and overall page structure. # Streamlit components will be injected into specific HTML placeholders. st.markdown(f""" CreditIQ - AI-Powered Credit Expenditure Prediction
""", unsafe_allow_html=True) st.markdown(""" """, unsafe_allow_html=True) # --- Load the trained model --- @st.cache_resource def load_model(): try: model = joblib.load('credit_card_expenditure_model.joblib') return model except FileNotFoundError: st.error("Model file 'credit_card_expenditure_model.joblib' not found. Please ensure it's in the same directory as this app.") st.stop() # Stop the app if model is not found except Exception as e: st.error(f"Error loading model: {e}") st.stop() # --- Streamlit Content Injection --- # This section uses st.empty() to create a placeholder where our content # for the active page will be rendered. streamlit_content_placeholder = st.empty() # --- Page Rendering Logic based on active_page state --- with streamlit_content_placeholder.container(): # Home Page if st.session_state.active_page == 'home': st.markdown(f"""

Predict Credit Expenditure with AI

Harness the power of advanced machine learning to accurately forecast credit card spending patterns and make informed financial decisions.

AI-Powered

Advanced algorithms analyze spending patterns

Secure

Bank-level security for your data

Fast

Instant predictions in seconds

""", unsafe_allow_html=True) with st.container(key="navbtn"): if st.button(" Start Predicting",key="pred"): st.session_state.active_page = 'predictor' st.rerun() if st.button(" Learn More",key="abt"): st.session_state.active_page = 'about' st.rerun() # We need to trigger the JS function to set active state and navigate elif st.session_state.active_page == 'predictor': # --- Prediction Form --- # We use st.form to group all the inputs. When the submit button is pressed, # Streamlit re-runs the script with all the new input values. with st.container(key ="main-form" ): st.markdown('

Customer Financial Profile

', unsafe_allow_html=True) with st.form(key="prediction_form"): # Create columns for the input grid layout col1, col2, col3 = st.columns(3) with col1: reports = st.number_input("Major Derogatory Reports", min_value=0, max_value=20, value=0, help="Number of serious credit issues reported") age = st.number_input("Age (years)", min_value=18.0, max_value=100.0, value=30.0, step=0.1, help="Customer's age in years") income = st.number_input("Yearly Income ($10,000s)", min_value=0.0, max_value=100.0, value=3.0, step=0.1, help="Annual income in tens of thousands") owner = st.selectbox("Home Owner", ('no', 'yes'), help="Does customer own their home?") with col2: card = st.selectbox("Card Owner", ('no', 'yes'), help="Does customer own a credit card?") share = st.number_input("Monthly Expenditure Ratio", min_value=0.0, max_value=1.0, value=0.1, step=0.01, help="Ratio of monthly spending to yearly income") active = st.number_input("Active Credit Accounts", min_value=0, max_value=50, value=5, help="Total number of active credit accounts") selfemp = st.selectbox("Self Employed", ('no', 'yes'), help="Is the customer self-employed?") with col3: dependents = st.number_input("Number of Dependents", min_value=0, max_value=10, value=0, help="Financially dependent individuals") months = st.number_input("Months at Current Address", min_value=0, max_value=500, value=36, help="Duration at current residence") majorcards = st.number_input("Major Credit Cards", min_value=0, max_value=10, value=1, help="Number of major credit cards owned") payments = st.number_input("Credit Card Payments", min_value=0, max_value=50, value=6, help="Total credit card payments made") # The submit button for the form submitted = st.form_submit_button("Predict Expenditure") # --- Model Prediction Logic --- # This block runs only when the form has been submitted. if st.button("Dismiss modal", key="dismiss_modal_btn", help="Hidden dismiss button"): st.session_state.show_prediction = False st.rerun() if submitted: model = load_model() if model is not None: # Show a loading spinner while processing with st.spinner("Analyzing financial data with AI..."): time.sleep(1) # Simulate processing time # Convert categorical inputs from 'yes'/'no' to 1/0 for the model owner_encoded = 1 if owner == 'yes' else 0 card_encoded = 1 if card == 'yes' else 0 selfemp_encoded = 1 if selfemp == 'yes' else 0 # Create a pandas DataFrame with the exact structure the model expects input_data = pd.DataFrame([{ 'card': card, # "yes"/"no" as string 'reports': reports, # int 'age': age, # float 'income': income, # float 'share': share, # float 'owner': owner, # "yes"/"no" as string 'selfemp': selfemp, # "yes"/"no" as string 'dependents': dependents, # int 'months': months, # int 'majorcards': majorcards, 'active':active# int # float or placeholder if unknown }]) expected_features = model.feature_names_in_ # Filter and reorder the input columns to match the model input_filtered = input_data[expected_features] print("input_data",input_data) print("expected",model.feature_names_in_) # If using scikit-learn 1.0+ print("input_data_type",input_data.dtypes) try: # Get the prediction from the model prediction = model.predict(input_filtered)[0] print("prediction:",prediction) # Store the result and set the flag to show it st.session_state.predicted_value = abs(prediction) # Ensure it's a positive number st.session_state.show_prediction = True except Exception as e: st.error(f"Could not make a prediction. Error: {e}") else: st.error("The prediction model is not available. Please check server logs.") # --- Display Prediction Result --- # This block displays the result card if a prediction has been made. if st.session_state.show_prediction: st.markdown(f""" """, unsafe_allow_html=True, ) my_js = """ // Close modal if clicking outside the modal-content const overlay = window.parent.document.getElementById("modal-overlay"); overlay.addEventListener("click", function(e) {{ if (e.target.id === "modal-overlay") {{ const btn = window.parent.document.querySelector('[class*="st-key-dismiss_modal_btn"]>div >div >div >div >button'); if (btn) { btn.click(); } //overlay.style.display = "none"; }} }}); """ my_html = f"" html(my_html) # Features Page elif st.session_state.active_page == 'features': st.markdown("""

Accurate Predictions

Leverage state-of-the-art machine learning models for highly precise expenditure forecasts.

Data Security

Your financial data is protected with industry-leading encryption and security protocols.

Privacy Focused

We prioritize your privacy with strict data handling and anonymity measures.

Responsive Design

Access CreditIQ seamlessly on any device, from desktop to mobile.

Actionable Insights

Understand your spending habits and gain insights to optimize your finances.

Customizable Models

Tailor prediction models to fit unique financial scenarios and individual needs.

""", unsafe_allow_html=True) # About Page elif st.session_state.active_page == 'about': st.markdown("""

Revolutionizing Financial Forecasting

CreditIQ was founded on the principle that informed financial decisions lead to greater stability and growth. We believe that by providing highly accurate, AI-driven credit expenditure predictions, we can help our users better manage their budgets, identify trends, and plan for the future with confidence.

Our team of data scientists and financial experts has developed a robust platform that combines cutting-edge machine learning algorithms with user-friendly design. We are committed to continuous innovation and maintaining the highest standards of data security and privacy.

99%
Accuracy Rate
1M+
Predictions Made
AI Financial Illustration
""", unsafe_allow_html=True) st.markdown(f"", unsafe_allow_html=True) # Contact Page elif st.session_state.active_page == 'contact': st.markdown("""
""", unsafe_allow_html=True) # Inject Streamlit components into the Contact form with st.container(key="contact-form"): with st.form("contact_form",clear_on_submit=True): st.text_input("Your Name", key="contact_name_input", help="Please enter your name.") st.text_input("Your Email", key="contact_email_input", help="Please enter your email address.") st.text_area("Message", key="contact_message_input", help="Type your message here.") submittedcon = st.form_submit_button("Send Message", help="Click to send your message.") if submittedcon : st.success("Thank you for your message! We will get back to you soon.")