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49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
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("""

<style>

@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@400;600;700&display=swap');

* {

    font-family: 'Montserrat', 'Inter', sans-serif;

}

.main {

    background: linear-gradient(135deg, #212d3b 0%, #223a57 100%);

    padding: 2rem 0;

}

.header-container {

    background: linear-gradient(135deg, #243b55 0%, #141e30 100%);

    padding: 2rem;

    border-radius: 16px;

    box-shadow: 0 8px 32px rgba(36, 59, 85,0.13);

    margin-bottom: 2rem;

    text-align: center;

}

.header-title {

    color: white;

    font-size: 2.5rem;

    font-weight: 700;

    margin: 0;

    text-shadow: 2px 2px 6px rgba(20,30,48,0.2);

    font-family: 'Montserrat', sans-serif;

}

.header-subtitle {

    color: #aab3cf;

    font-size: 1.1rem;

    margin-top: 0.5rem;

    font-family: 'Montserrat', sans-serif;

}

.section-card {

    background: #25304b;

    padding: 1.5rem;

    border-radius: 12px;

    box-shadow: 0 4px 8px rgba(36, 59, 85,0.12);

    margin-bottom: 1.5rem;

    border-left: 4px solid #2952a3;

    color: #f3f4fa;

}

.section-title {

    color: #f1f7fc;

    font-size: 1.3rem;

    font-weight: 700;

    margin-bottom: 1rem;

    display: flex;

    align-items: center;

    gap: 0.5rem;

    font-family: 'Montserrat', sans-serif;

}

.info-box {

    background: linear-gradient(135deg, #344667 0%, #2952a3 100%);

    color: #f1f7fc;

    padding: 1rem;

    border-radius: 10px;

    margin: 1rem 0;

    border-left: 4px solid #18aad5;

    animation: slideIn 0.5s ease-out;

}

@keyframes slideIn {

    from { opacity: 0; transform: translateY(-10px); }

    to { opacity: 1; transform: translateY(0); }

}

.metric-card {

    background: linear-gradient(135deg, #2952a3 0%, #243b55 100%);

    padding: 1.2rem;

    border-radius: 12px;

    color: #f3f4fa;

    text-align: center;

    box-shadow: 0 4px 15px rgba(41, 82, 163, 0.2);

    transition: transform 0.3s ease;

}

.metric-card:hover {

    transform: translateY(-5px);

}

.metric-value {

    font-size: 2rem;

    font-weight: 700;

    margin: 0.5rem 0;

    font-family: 'Montserrat', sans-serif;

}

.metric-label {

    font-size: 0.9rem;

    opacity: 0.92;

}

.result-card {

    background: linear-gradient(135deg, #333b9b 0%, #2d375b 100%);

    padding: 2rem;

    border-radius: 16px;

    color: #f4f8ff;

    box-shadow: 0 8px 32px rgba(51, 59, 155, 0.10);

    margin: 1.5rem 0;

}

.result-grid {

    display: grid;

    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));

    gap: 1.5rem;

    margin-top: 1rem;

}

.result-item {

    background: rgba(25,40,65,0.2);

    padding: 1.5rem;

    border-radius: 12px;

    backdrop-filter: blur(10px);

}

.result-item-label {

    font-size: 0.9rem;

    opacity: 0.9;

    margin-bottom: 0.5rem;

}

.result-item-value {

    font-size: 1.8rem;

    font-weight: 700;

}

.advisor-box {

    background: linear-gradient(135deg, #2e8bcb 0%, #243b55 100%);

    color: #f5f5fa;

    padding: 1.5rem;

    border-radius: 12px;

    margin-top: 1.5rem;

    border-left: 4px solid #18aad5;

    box-shadow: 0 4px 15px rgba(46, 139, 203, 0.1);

}

.advisor-box h4 {

    color: #f1f7fc;

    margin-top: 0;

}

.chat-container {

    background: #24304e;

    color: #fff;

    padding: 1.5rem;

    border-radius: 12px;

    box-shadow: 0 4px 6px rgba(36, 48, 78,0.12);

    max-height: 400px;

    overflow-y: auto;

    margin-bottom: 1rem;

}

.chat-bubble-user {

    background: linear-gradient(135deg, #2952a3 0%, #243b55 100%);

    color: white;

    padding: 12px 18px;

    border-radius: 18px 18px 4px 18px;

    margin: 8px 0 8px auto;

    max-width: 70%;

    text-align: right;

    box-shadow: 0 2px 8px rgba(41,82,163, 0.13);

    animation: slideInRight 0.3s ease-out;

    font-family: 'Montserrat', sans-serif;

}

.chat-bubble-bot {

    background: #20293b;

    border: 2px solid #2a3d6a;

    color: #ebf2f8;

    padding: 12px 18px;

    border-radius: 18px 18px 18px 4px;

    margin: 8px auto 8px 0;

    max-width: 70%;

    box-shadow: 0 2px 8px rgba(0,0,0,0.1);

    animation: slideInLeft 0.3s ease-out;

    font-family: 'Montserrat', sans-serif;

}

@keyframes slideInRight {

    from { opacity: 0; transform: translateX(20px); }

    to { opacity: 1; transform: translateX(0); }

}

@keyframes slideInLeft {

    from { opacity: 0; transform: translateX(-20px); }

    to { opacity: 1; transform: translateX(0); }

}

.stButton>button {

    width: 100%;

    background: linear-gradient(135deg, #285aeb 0%, #223a57 100%);

    color: white;

    font-weight: 600;

    border: none;

    border-radius: 10px;

    padding: 0.8rem;

    font-size: 1rem;

    font-family: 'Montserrat', sans-serif;

    transition: all 0.3s ease;

    box-shadow: 0 4px 15px rgba(40, 90, 235, 0.13);

}

.stButton>button:hover {

    transform: translateY(-2px);

    box-shadow: 0 6px 20px rgba(40, 90, 235, 0.20);

}

.progress-container {

    margin: 1rem 0;

}

.stNumberInput>div>div>input,

.stSelectbox>div>div>select,

.stTextInput>div>div>input {

    border-radius: 8px;

    border: 2px solid #233269;

    padding: 0.5rem;

    transition: border-color 0.3s ease;

    background: #2d375b;

    color: #e9ecfa;

    font-family: 'Montserrat', sans-serif;

}

.stNumberInput>div>div>input:focus,

.stSelectbox>div>div>select:focus,

.stTextInput>div>div>input:focus {

    border-color: #285aeb;

    box-shadow: 0 0 0 3px rgba(40, 90, 235, 0.1);

}

.alert-banner {

    background: linear-gradient(135deg, #233269 0%, #285aeb 100%);

    color: #fff;

    padding: 1rem;

    border-radius: 10px;

    margin: 1rem 0;

    border-left: 4px solid #18aad5;

    display: flex;

    align-items: center;

    gap: 0.5rem;

}

.chat-container::-webkit-scrollbar {

    width: 8px;

}

.chat-container::-webkit-scrollbar-track {

    background: #1a2336;

    border-radius: 10px;

}

.chat-container::-webkit-scrollbar-thumb {

    background: #2952a3;

    border-radius: 10px;

}

.chat-container::-webkit-scrollbar-thumb:hover {

    background: #223a57;

}

</style>

""", unsafe_allow_html=True)

# ========================= HEADER =========================
st.markdown("""

<div class="header-container">

    <h1 class="header-title">πŸ›‘οΈ RiskGuard AI</h1>

    <p class="header-subtitle">Advanced AI-Powered Credit Risk Assessment Platform</p>

</div>

""", unsafe_allow_html=True)

# Alert Banner
st.markdown("""

<div class="alert-banner">

    ⚠️ <strong>Note:</strong> First request may take up to 20 seconds (API cold start).

</div>

""", 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("""

    <div class="info-box">

        <h4>πŸ“Š About RiskGuard AI</h4>

        <p><strong>What we analyze:</strong></p>

        <ul>

            <li>Personal financial profile and credit history</li>

            <li>Loan-to-income ratio and debt burden</li>

            <li>Payment patterns and delinquency records</li>

            <li>Credit utilization and account management</li>

        </ul>

        <p><strong>Our AI provides:</strong></p>

        <ul>

            <li>Default probability predictions</li>

            <li>Credit score assessment</li>

            <li>Risk rating classification</li>

            <li>Personalized recommendations</li>

        </ul>

    </div>

    """, unsafe_allow_html=True)

# ========================= INPUT FORM =========================
col_left, col_right = st.columns([1, 1], gap="large")

with col_left:
    st.markdown('<div class="section-card">', unsafe_allow_html=True)
    st.markdown('<div class="section-title">πŸ‘€ Personal & Loan Information</div>', 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('</div>', unsafe_allow_html=True)
    
    loan_to_income_ratio = loan_amount / income if income > 0 else 0
    st.markdown(f"""

    <div class="metric-card">

        <div class="metric-label">Loan-to-Income Ratio</div>

        <div class="metric-value">{loan_to_income_ratio:.2f}x</div>

    </div>

    """, unsafe_allow_html=True)

with col_right:
    st.markdown('<div class="section-card">', unsafe_allow_html=True)
    st.markdown('<div class="section-title">πŸ’³ Credit Profile</div>', 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('</div>', unsafe_allow_html=True)

# ========================= ANALYSIS BUTTON =========================
st.markdown("<br>", 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('<div class="result-card">', unsafe_allow_html=True)
                st.markdown('<h3 style="margin-top:0; color:white;">πŸ“Š Assessment Results</h3>', unsafe_allow_html=True)
                st.markdown(f"""

                <div class="result-grid">

                    <div class="result-item">

                        <div class="result-item-label">Default Probability</div>

                        <div class="result-item-value">{result['probability']:.2%}</div>

                    </div>

                    <div class="result-item">

                        <div class="result-item-label">Credit Score</div>

                        <div class="result-item-value">{result['credit_score']}</div>

                    </div>

                    <div class="result-item">

                        <div class="result-item-label">Risk Rating</div>

                        <div class="result-item-value">{result['rating']}</div>

                    </div>

                </div>

                """, unsafe_allow_html=True)
                st.markdown('</div>', unsafe_allow_html=True)

                if result.get("advisor_response"):
                    st.markdown(f"""

                    <div class="advisor-box">

                        <h4>πŸ€– AI Credit Advisor Insights</h4>

                        <p>{result['advisor_response']}</p>

                    </div>

                    """, 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("<br><br>", unsafe_allow_html=True)
    st.markdown('<div class="section-card">', unsafe_allow_html=True)
    st.markdown('<div class="section-title">πŸ’¬ Interactive Loan Chat Assistant</div>', unsafe_allow_html=True)
    if st.session_state.chat_history:
        st.markdown('<div class="chat-container">', 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"<div class='{bubble}'><strong>{prefix}</strong>{msg}</div>", unsafe_allow_html=True)
        st.markdown('</div>', 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('</div>', unsafe_allow_html=True)

# Footer
st.markdown("<br><br>", unsafe_allow_html=True)
st.markdown("""

<div style='text-align: center; color: #7f8c8d; font-size: 0.9rem;'>

    <p>πŸ›‘οΈ RiskGuard AI Β© 2025 | Powered by Advanced Machine Learning</p>

    <p style='font-size: 0.8rem;'>For demonstration purposes only. Not financial advice.</p>

</div>

""", unsafe_allow_html=True)