import streamlit as st
import requests
import uuid
from datetime import datetime
# Page configuration
st.set_page_config(
page_title="RiskGuard AI: Credit Risk Modelling",
page_icon="đĄī¸",
layout="wide"
)
# Initialize session storage
if "chat_history" not in st.session_state:
st.session_state.chat_history = []
if "thread_id" not in st.session_state:
st.session_state.thread_id = str(uuid.uuid4())
if "analysis_done" not in st.session_state:
st.session_state.analysis_done = False
if "show_info" not in st.session_state:
st.session_state.show_info = False
# ========================= ENHANCED UI STYLING (UPDATED) =========================
st.markdown("""
""", unsafe_allow_html=True)
# ========================= HEADER =========================
st.markdown("""
""", unsafe_allow_html=True)
# Alert Banner
st.markdown("""
â ī¸ Note: First request may take up to 20 seconds (API cold start).
""", unsafe_allow_html=True)
# Info Toggle
if st.button("âšī¸ How It Works"):
st.session_state.show_info = not st.session_state.show_info
if st.session_state.show_info:
st.markdown("""
đ About RiskGuard AI
What we analyze:
- Personal financial profile and credit history
- Loan-to-income ratio and debt burden
- Payment patterns and delinquency records
- Credit utilization and account management
Our AI provides:
- Default probability predictions
- Credit score assessment
- Risk rating classification
- Personalized recommendations
""", unsafe_allow_html=True)
# ========================= INPUT FORM =========================
col_left, col_right = st.columns([1, 1], gap="large")
with col_left:
st.markdown('', unsafe_allow_html=True)
st.markdown('
đ¤ Personal & Loan Information
', unsafe_allow_html=True)
age = st.number_input("Age", 18, 100, 28, help="Applicant's age in years")
income = st.number_input("Annual Income (âš)", 0, 50000000, 1200000, step=50000, help="Total annual income")
loan_amount = st.number_input("Loan Amount (âš)", 0, 50000000, 2500000, step=100000, help="Requested loan amount")
loan_tenure_months = st.number_input("Loan Tenure (months)", 0, 480, 36, help="Loan repayment period")
loan_purpose = st.selectbox("Loan Purpose", ["Education", "Home", "Auto", "Personal"])
residence_type = st.selectbox("Residence Type", ["Owned", "Rented", "Mortgage"])
loan_type = st.selectbox("Loan Type", ["Secured", "Unsecured"])
st.markdown('
', unsafe_allow_html=True)
loan_to_income_ratio = loan_amount / income if income > 0 else 0
st.markdown(f"""
Loan-to-Income Ratio
{loan_to_income_ratio:.2f}x
""", unsafe_allow_html=True)
with col_right:
st.markdown('', unsafe_allow_html=True)
st.markdown('
đŗ Credit Profile
', unsafe_allow_html=True)
avg_dpd_per_delinquency = st.number_input("Average Days Past Due", 0, 200, 20, help="Average days past due per delinquency")
delinquency_ratio = st.number_input("Delinquency Ratio (%)", 0, 100, 30, help="Percentage of delinquent accounts")
credit_utilization_ratio = st.number_input("Credit Utilization (%)", 0, 100, 30, help="Percentage of available credit used")
num_open_accounts = st.number_input("Open Loan Accounts", 0, 20, 2, help="Number of currently active loan accounts")
st.markdown('
', unsafe_allow_html=True)
# ========================= ANALYSIS BUTTON =========================
st.markdown("
", unsafe_allow_html=True)
if st.button("đ Analyze Credit Risk", use_container_width=True):
API_URL = st.secrets["API_URL"]
payload = {
"age": age,
"income": income,
"loan_amount": loan_amount,
"loan_tenure_months": loan_tenure_months,
"avg_dpd_per_delinquency": avg_dpd_per_delinquency,
"delinquency_ratio": delinquency_ratio,
"credit_utilization_ratio": credit_utilization_ratio,
"num_open_accounts": num_open_accounts,
"residence_type": residence_type,
"loan_purpose": loan_purpose,
"loan_type": loan_type
}
with st.spinner("đ¤ Analyzing your credit profile..."):
try:
r = requests.post(API_URL, json=payload, timeout=30)
if r.status_code == 200:
result = r.json()
# Display Results
st.markdown('', unsafe_allow_html=True)
st.markdown('
đ Assessment Results
', unsafe_allow_html=True)
st.markdown(f"""
Default Probability
{result['probability']:.2%}
Credit Score
{result['credit_score']}
Risk Rating
{result['rating']}
""", unsafe_allow_html=True)
st.markdown('
', unsafe_allow_html=True)
if result.get("advisor_response"):
st.markdown(f"""
đ¤ AI Credit Advisor Insights
{result['advisor_response']}
""", unsafe_allow_html=True)
st.session_state.probability = result["probability"]
st.session_state.credit_score = result["credit_score"]
st.session_state.rating = result["rating"]
st.session_state.advisor_reply = result["advisor_response"]
st.session_state.analysis_done = True
st.success("â
Analysis complete! You can now chat with our AI assistant below.")
else:
st.error(f"â API Error: {r.status_code} - {r.text}")
except requests.exceptions.Timeout:
st.error("âąī¸ Request timed out. Please try again.")
except Exception as e:
st.error(f"â Request failed: {e}")
# ========================= CHATBOT =========================
if st.session_state.analysis_done:
st.markdown("
", unsafe_allow_html=True)
st.markdown('', unsafe_allow_html=True)
st.markdown('
đŦ Interactive Loan Chat Assistant
', unsafe_allow_html=True)
if st.session_state.chat_history:
st.markdown('
', unsafe_allow_html=True)
for role, msg in st.session_state.chat_history:
bubble = "chat-bubble-user" if role == "user" else "chat-bubble-bot"
prefix = "You: " if role == "user" else "đ¤ Assistant: "
st.markdown(f"
{prefix}{msg}
", unsafe_allow_html=True)
st.markdown('
', unsafe_allow_html=True)
user_query = st.text_input("Ask a question about your credit assessment:", placeholder="e.g., How can I improve my credit score?")
col_send, col_clear = st.columns([3, 1])
with col_send:
send_button = st.button("đ¤ Send Message", use_container_width=True)
with col_clear:
if st.button("đī¸ Clear Chat", use_container_width=True):
st.session_state.chat_history = []
st.session_state.thread_id = str(uuid.uuid4())
st.experimental_rerun()
if send_button and user_query.strip():
CHAT_URL = st.secrets["CHAT_URL"]
payload = {
"thread_id": st.session_state.thread_id,
"message": user_query,
"probability": st.session_state.probability,
"credit_score": st.session_state.credit_score,
"rating": st.session_state.rating,
"advisor_reply": st.session_state.advisor_reply
}
with st.spinner("đ¤ Thinking..."):
try:
r = requests.post(CHAT_URL, json=payload, timeout=30)
if r.status_code == 200:
reply = r.json()["response"]
st.session_state.chat_history.append(("user", user_query))
st.session_state.chat_history.append(("bot", reply))
st.experimental_rerun()
else:
st.error(f"â Chat server error: {r.status_code}")
except Exception as e:
st.error(f"â Chat failed: {e}")
st.markdown('
', unsafe_allow_html=True)
# Footer
st.markdown("
", unsafe_allow_html=True)
st.markdown("""
đĄī¸ RiskGuard AI Š 2025 | Powered by Advanced Machine Learning
For demonstration purposes only. Not financial advice.
""", unsafe_allow_html=True)