forked from MAYANKSHARMA01010/Slip
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1294 lines (1149 loc) · 61.8 KB
/
Copy pathapp.py
File metadata and controls
1294 lines (1149 loc) · 61.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import re
import warnings
import urllib.parse
import time
import pickle
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import streamlit as st # pyright: ignore[reportMissingImports]
from streamlit_option_menu import option_menu # pyright: ignore[reportMissingImports]
from streamlit_extras.metric_cards import style_metric_cards # pyright: ignore[reportMissingImports]
from rich.console import Console # pyright: ignore[reportMissingImports]
from rich.panel import Panel # pyright: ignore[reportMissingImports]
from agent.agent_engine import process_customer_retention
# Primary semantic color palette.
BLUE = "#38bdf8"
ORG = "#f97316"
PURP = "#a78bfa"
GREEN = "#34d399"
# Initialize the console for descriptive terminal logging.
console = Console()
def lucide_icon(name, size=20, color="currentColor", extra_style=""):
"""
Render a Lucide icon as a robust CSS mask.
Using standard mask properties for better cross-browser/Streamlit compatibility.
"""
url = f"https://unpkg.com/lucide-static@latest/icons/{name}.svg"
style = (
f"display: inline-block; width: {size}px; height: {size}px; "
f"background-color: {color}; "
f"-webkit-mask-image: url('{url}'); "
f"mask-image: url('{url}'); "
f"-webkit-mask-repeat: no-repeat; "
f"mask-repeat: no-repeat; "
f"-webkit-mask-position: center; "
f"mask-position: center; "
f"-webkit-mask-size: contain; "
f"mask-size: contain; "
f"vertical-align: middle; {extra_style}"
)
return f'<span class="lucide-icon" style="{style}"></span>'
def parse_lucide_tags(text):
"""Replace [lucide:icon-name] with HTML icon tags, perfectly aligned."""
if not isinstance(text, str): return text
# Using vertical-align: -15% to center icons with the text baseline for a premium look.
return re.sub(r'\[lucide:([a-z0-9-]+)\]', lambda m: lucide_icon(m.group(1), size=18, extra_style="vertical-align: -15%; margin-right: 5px;"), text)
def render_header(title, icon_name, color=BLUE, font_size="1.5rem"):
"""Render a perfectly aligned section header with an icon."""
st.markdown(f"""
<div style="display: flex; align-items: center; gap: 12px; margin-bottom: 20px;">
{lucide_icon(icon_name, size=24, color=color)}
<h3 style="margin: 0; font-size: {font_size}; font-weight: 700; color: #fff;">{title}</h3>
</div>
""", unsafe_allow_html=True)
def render_status_metric(label, value, icon_name=None, color=BLUE, help_text=None):
"""Render a custom metric card with an integrated status icon."""
icon_html = f'<div style="margin-top: 8px;">{lucide_icon(icon_name, size=18, color=color)}</div>' if icon_name else ""
st.markdown(f"""
<div style="background: #0f1e36; border: 1px solid #1e2d45; border-radius: 12px; padding: 16px; border-left: 4px solid {color};">
<div style="color: #94a3b8; font-size: 0.85rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em;">{label}</div>
<div style="color: #fff; font-size: 1.8rem; font-weight: 800; margin: 4px 0;">{value}</div>
{icon_html}
</div>
""", unsafe_allow_html=True)
# Track session data, results, and active tabs to maintain state across reruns.
for key, default in {
"customer_data": None,
"churn_prob": 0.0,
"agent_result": None,
"active_provider": None,
"show_dashboard": False,
"active_tab": "Overview",
}.items():
if key not in st.session_state:
st.session_state[key] = default
# Handle navigation actions from custom HTML components.
if st.query_params.get("nav") == "home":
st.session_state.show_dashboard = False
st.query_params.clear()
st.rerun()
warnings.filterwarnings("ignore")
# Configure dashboard metadata and sidebar layout.
st.set_page_config(
page_title="Slip — Telco Churn Intelligence",
page_icon="https://unpkg.com/lucide-static@latest/icons/signal.svg",
layout="wide",
initial_sidebar_state="expanded",
)
# Enable smooth scrolling for a better user experience on page changes.
st.markdown("""
<style>
html { scroll-behavior: smooth; }
</style>
<script>
const scrollToTop = () => {
const main = window.parent.document.querySelector('section.main');
if (main) main.scrollTo({ top: 0, behavior: 'smooth' });
};
const observer = new MutationObserver(scrollToTop);
observer.observe(window.parent.document.body, { childList: true, subtree: true });
scrollToTop();
</script>
""", unsafe_allow_html=True)
# Define global aesthetic styles including glassmorphism and custom animations.
st.markdown("""
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap');
html, body, [class*="css"] {
font-family: 'Inter', sans-serif;
background-color: #070d1a;
color: #e2e8f0;
}
/* Fade-in animation */
@keyframes fadeUp {
from { opacity: 0; transform: translateY(14px); }
to { opacity: 1; transform: translateY(0); }
}
.main { animation: fadeUp 0.55s ease-out; }
/* Navigation and Branding */
section[data-testid="stSidebar"] {
background: #0b1220;
border-right: 1px solid #1e2d45;
}
section[data-testid="stSidebar"] * { color: #cbd5e1 !important; }
/* Live System Status Indicator */
.status-pill {
background: rgba(16, 185, 129, 0.1);
border: 1px solid rgba(16, 185, 129, 0.3);
color: #10b981;
border-radius: 999px;
padding: 0.2rem 0.6rem;
font-size: 0.72rem;
font-weight: 600;
display: inline-flex; align-items: center; gap: 4px;
}
.status-dot { width: 6px; height: 6px; background: #10b981; border-radius: 50%; box-shadow: 0 0 8px #10b981; }
/* High-Fidelity Metric Cards */
div[data-testid="metric-container"] {
background: rgba(15, 23, 42, 0.85);
backdrop-filter: blur(12px);
border: 1px solid rgba(56, 189, 248, 0.15);
border-radius: 14px;
padding: 18px 22px;
box-shadow: 0 4px 20px rgba(0,0,0,0.35);
transition: transform 0.22s ease, box-shadow 0.22s ease, border-color 0.22s ease;
}
div[data-testid="metric-container"]:hover {
transform: translateY(-3px);
box-shadow: 0 8px 28px rgba(0,0,0,0.45);
border-color: rgba(56, 189, 248, 0.45);
}
div[data-testid="metric-container"] label { color: #94a3b8 !important; }
div[data-testid="metric-container"] [data-testid="stMetricValue"] {
color: #f8fafc !important; font-size: 1.6rem !important; font-weight: 700;
}
/* Consistent Interactive Buttons */
div.stButton > button {
background: linear-gradient(135deg, #1d4ed8 0%, #1e40af 100%);
color: white !important;
border: none;
border-radius: 10px;
padding: 0.55rem 1.2rem;
font-weight: 600;
font-size: 0.95rem;
letter-spacing: 0.02em;
transition: all 0.25s ease;
box-shadow: 0 4px 14px rgba(29,78,216,0.35);
}
div.stButton > button:hover {
transform: translateY(-2px);
box-shadow: 0 7px 20px rgba(29,78,216,0.5);
background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
}
/* Sectional Card Containers */
.section-card {
background: rgba(15, 30, 54, 0.65);
backdrop-filter: blur(16px);
border: 1px solid rgba(56, 189, 248, 0.1);
border-radius: 18px;
padding: 1.8rem 2rem;
margin-bottom: 1.5rem;
box-shadow: 0 10px 35px rgba(0,0,0,0.4);
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.section-card:hover {
border-color: rgba(56, 189, 248, 0.3);
transform: translateY(-2px);
box-shadow: 0 15px 45px rgba(0,0,0,0.5);
}
/* Hero Shell and Landing Visuals */
.hero-shell {
background: linear-gradient(135deg, #070d1a 0%, #0c1830 60%, #091526 100%);
border: 1px solid #1e2d45;
border-radius: 22px;
padding: 1.2rem 1.6rem 2rem;
box-shadow: 0 20px 50px rgba(0,0,0,0.4);
position: relative;
overflow: hidden;
}
.hero-shell::before {
content: '';
position: absolute; top: -40%; left: -20%;
width: 60%; height: 200%;
background: radial-gradient(ellipse, rgba(56,189,248,0.04) 0%, transparent 70%);
pointer-events: none;
}
.hero-nav {
display: flex; justify-content: space-between; align-items: center;
padding: 0.8rem 0; border-bottom: 1px solid #1e2d45; margin-bottom: 2rem;
}
.hero-brand {
font-size: 1.3rem; font-weight: 800; color: #f8fafc; letter-spacing: -0.02em;
line-height: 1; display: flex; align-items: center;
}
.hero-brand span { color: #38bdf8; }
.hero-nav-links {
display: flex; gap: 1.4rem; color: #64748b; font-size: 0.9rem; font-weight: 500;
line-height: 1; align-items: center;
}
.hero-title {
font-size: clamp(2.2rem, 5vw, 4.2rem); font-weight: 800; line-height: 1.07;
letter-spacing: -0.03em; color: #f8fafc; text-align: center; margin-bottom: 1rem;
}
.hero-title .accent { color: #38bdf8; }
.hero-sub {
color: #94a3b8; font-size: clamp(1rem, 1.5vw, 1.2rem);
max-width: 850px; margin: 0 auto 1.8rem; text-align: center;
line-height: 1.6; text-wrap: balance;
}
.pill-row { display: flex; justify-content: center; gap: 0.6rem; flex-wrap: wrap; }
.pill {
background: #111827; border: 1px solid #1e2d45; color: #93c5fd;
border-radius: 999px; padding: 0.4rem 0.9rem; font-size: 0.78rem; font-weight: 500;
display: inline-flex; align-items: center; gap: 8px; line-height: 1;
}
.pill .lucide-icon { display: flex; align-items: center; margin-top: 1px; }
.info-card {
background: #0a1628; border: 1px solid #1e2d45; border-radius: 14px;
padding: 1.1rem 1.3rem; min-height: 160px; height: 100%;
}
.info-card h4 { color: #e2e8f0; margin-bottom: 0.5rem; font-size: 0.98rem; }
.info-card p { color: #94a3b8; font-size: 0.9rem; line-height: 1.6; margin: 0; }
.flow-box {
background: #0a1628; border: 1px solid #1e2d45; border-radius: 14px;
padding: 1.2rem 1.5rem; margin-top: 1.2rem;
}
.flow-box h3 { color: #e2e8f0; margin-bottom: 0.7rem; }
.flow-step { color: #94a3b8; font-size: 0.93rem; margin-bottom: 0.35rem; }
.flow-step strong { color: #38bdf8; }
/* Application Branding Elements */
.app-header {
background: linear-gradient(90deg, #0f1e36 0%, #0a1628 100%);
border: 1px solid #1e2d45; border-radius: 16px; padding: 1.2rem 1.6rem;
margin-bottom: 1.5rem; display: flex; align-items: center; gap: 1.4rem;
}
.app-header-icon { display: flex; align-items: center; line-height: 0; }
.app-title { margin: 0; color: #f8fafc; font-size: 1.8rem; font-weight: 800; letter-spacing: -0.02em; line-height: 1.2; }
.app-subtitle { margin: 4px 0 0; color: #64748b; font-size: 0.92rem; line-height: 1.4; }
.badge {
display: inline-block; margin-right: 0.4rem; margin-bottom: 0.3rem;
background: #111827; color: #93c5fd; border: 1px solid #1e3a5f;
border-radius: 999px; padding: 0.2rem 0.65rem; font-size: 0.76rem; font-weight: 500;
}
/* Layout Spacing */
hr { border-color: rgba(255,255,255,0.07) !important; }
/* Custom Navigation Tabs */
button[role="tab"] {
font-weight: 600; font-size: 0.93rem; padding: 0.45rem 0.85rem; color: #64748b;
border-radius: 8px 8px 0 0; transition: all 0.2s ease;
}
button[role="tab"]:hover { color: #e2e8f0; background: #0f1e36; }
button[role="tab"][aria-selected="true"] { color: #38bdf8 !important; background: #0f1e36; }
/* Download and Export Controls */
div.stDownloadButton > button {
background: #111827 !important;
border: 1px solid #1e2d45 !important;
color: #93c5fd !important;
border-radius: 10px; font-weight: 600;
transition: all 0.22s ease;
}
div.stDownloadButton > button:hover {
border-color: #38bdf8 !important;
background: #0f1e36 !important;
}
/* Streamlit Native UI Overrides */
div[data-testid="stAlert"] { border-radius: 10px; }
</style>
""", unsafe_allow_html=True)
# Define a custom Plotly theme for visual consistency with the dark UI.
PLOTLY_LAYOUT = dict(
paper_bgcolor="rgba(0,0,0,0)",
plot_bgcolor="#0a1628",
font=dict(family="Inter", color="#e2e8f0", size=12),
colorway=["#38bdf8", "#f97316", "#a78bfa", "#34d399"],
hoverlabel=dict(bgcolor="#0f1e36", bordercolor="#1e2d45", font_size=13),
)
_AXIS_STYLE = dict(gridcolor="#1e2d45", linecolor="#1e2d45", zerolinecolor="#1e2d45")
_DEFAULT_MARGIN = dict(l=16, r=16, t=32, b=16)
def apply_layout(fig, height=None, margin=None, xaxis=None, yaxis=None, **extra):
"""Apply PLOTLY_LAYOUT and per-chart overrides."""
layout_params = {**PLOTLY_LAYOUT}
if height:
layout_params["height"] = height
layout_params["margin"] = margin or _DEFAULT_MARGIN
layout_params["xaxis"] = {**_AXIS_STYLE, **(xaxis or {})}
layout_params["yaxis"] = {**_AXIS_STYLE, **(yaxis or {})}
layout_params.update(extra)
fig.update_layout(**layout_params)
return fig
import joblib
# Automatically train and save model artifacts if they are missing.
ARTIFACTS = ["model_pipeline.pkl", "feature_columns.pkl"]
def train_and_save_artifacts():
df = pd.read_csv("telco_customer_churn.csv").drop(columns=["customerID"])
df["TotalCharges"] = df["TotalCharges"].replace({" ": "0.0"}).astype(float)
df["SeniorCitizen"] = df["SeniorCitizen"].astype(int)
df["gender"] = df["gender"].astype(str)
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
import joblib
X = df.drop("Churn", axis=1)
y = df["Churn"].map({"Yes": 1, "No": 0})
categorical_cols = X.select_dtypes(include=["object"]).columns.tolist()
numeric_cols = X.select_dtypes(include=["int64", "float64"]).columns.tolist()
preprocessor = ColumnTransformer([
("num", StandardScaler(), numeric_cols),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), categorical_cols),
])
pipeline = Pipeline([
("preprocessor", preprocessor),
("clf", RandomForestClassifier(n_estimators=50, random_state=42)),
])
X_train, _, y_train, _ = train_test_split(X, y, test_size=0.2, random_state=42)
pipeline.fit(X_train, y_train)
joblib.dump(pipeline, "model_pipeline.pkl")
joblib.dump(X.columns.tolist(), "feature_columns.pkl")
@st.cache_resource
def load_artifacts():
for _ in range(2):
try:
pipeline = joblib.load("model_pipeline.pkl")
feature_columns = joblib.load("feature_columns.pkl")
return pipeline, feature_columns
except (EOFError, FileNotFoundError, pickle.UnpicklingError):
train_and_save_artifacts()
st.error("Failed to load or train model artifacts. Please check your data and code.")
st.stop()
@st.cache_data
def load_data():
df = pd.read_csv("telco_customer_churn.csv").drop(columns=["customerID"])
df["TotalCharges"] = df["TotalCharges"].replace({" ": "0.0"}).astype(float)
return df
def is_valid_email(email: str) -> bool:
return bool(re.match(r"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$", email.strip()))
pipeline, feature_columns = load_artifacts()
df = load_data()
console.print(Panel("[bold green]Slip Dashboard loaded[/bold green]", title="[cyan]startup[/cyan]"))
# Render the landing page for initial user interaction.
def render_home_page():
st.markdown(f"""
<div class="hero-shell">
<div class="hero-nav">
<div class="hero-brand">Sli<span>p</span></div>
<div class="hero-nav-links">
<span>Overview</span><span>Predict</span><span>AI Strategist</span><span>Docs</span>
</div>
</div>
<div style="padding:1rem 0 0.5rem; text-align: center; display: flex; flex-direction: column; align-items: center;">
<div class="hero-title">
Predict churn early.<br/>
<span class="accent">Retain every customer.</span>
</div>
<div style="text-align: center; margin-bottom: 2rem;">
<div style="display: inline-block; max-width: 820px; color: #94a3b8; font-size: clamp(1rem, 1.5vw, 1.1rem); line-height: 1.6;">
A production-grade churn intelligence platform combining ML prediction,
RAG-powered knowledge retrieval, and agentic AI reasoning — all in one workspace.
</div>
</div>
<div class="pill-row" style="display: flex; justify-content: center; gap: 10px; flex-wrap: wrap;">
<div class="pill" style="display: inline-flex; align-items: center; padding: 0.4rem 1rem; gap: 8px; background: #111827; border: 1px solid #1e2d45; border-radius: 999px; color: #93c5fd; font-size: 0.78rem; font-weight: 500;">
{lucide_icon("cpu", size=14)} <span style="line-height: 1; display: inline-block; margin-top: 1px;">LangGraph Agent</span>
</div>
<div class="pill" style="display: inline-flex; align-items: center; padding: 0.4rem 1rem; gap: 8px; background: #111827; border: 1px solid #1e2d45; border-radius: 999px; color: #93c5fd; font-size: 0.78rem; font-weight: 500;">
{lucide_icon("bar-chart-3", size=14)} <span style="line-height: 1; display: inline-block; margin-top: 1px;">ML Pipeline</span>
</div>
<div class="pill" style="display: inline-flex; align-items: center; padding: 0.4rem 1rem; gap: 8px; background: #111827; border: 1px solid #1e2d45; border-radius: 999px; color: #93c5fd; font-size: 0.78rem; font-weight: 500;">
{lucide_icon("database", size=14)} <span style="line-height: 1; display: inline-block; margin-top: 1px;">RAG Knowledge Base</span>
</div>
<div class="pill" style="display: inline-flex; align-items: center; padding: 0.4rem 1rem; gap: 8px; background: #111827; border: 1px solid #1e2d45; border-radius: 999px; color: #93c5fd; font-size: 0.78rem; font-weight: 500;">
{lucide_icon("file-down", size=14)} <span style="line-height: 1; display: inline-block; margin-top: 1px;">Downloadable Reports</span>
</div>
<div class="pill" style="display: inline-flex; align-items: center; padding: 0.4rem 1rem; gap: 8px; background: #111827; border: 1px solid #1e2d45; border-radius: 999px; color: #93c5fd; font-size: 0.78rem; font-weight: 500;">
{lucide_icon("pie-chart", size=14)} <span style="line-height: 1; display: inline-block; margin-top: 1px;">Interactive Charts</span>
</div>
</div>
</div>
</div>
""", unsafe_allow_html=True)
vector_index_ready = any(os.path.exists(p) for p in [
"vectorstore/db_faiss/index.faiss",
"vectorstore/db_faiss/index 2.faiss",
])
kb_ready = os.path.exists("knowledge_base/retention_strategies.md")
st.markdown("""
<style>
.metric-row {
display: flex;
gap: 32px;
margin-bottom: 18px;
}
.metric-row > div {
flex: 1;
}
</style>
""", unsafe_allow_html=True)
m1, m2, m3, m4 = st.columns(4, gap="medium")
with m1:
render_status_metric("Dataset Rows", f"{len(df):,}", "database", BLUE)
with m2:
render_status_metric("Model Features", f"{len(feature_columns)}", "cpu", BLUE)
with m3:
render_status_metric("Knowledge Base", "Ready" if kb_ready else "Missing",
"check-circle" if kb_ready else "x-circle",
"#10b981" if kb_ready else "#f43f5e")
with m4:
render_status_metric("Vector Index", "Ready" if vector_index_ready else "Missing",
"check-circle" if vector_index_ready else "x-circle",
"#10b981" if vector_index_ready else "#f43f5e")
st.markdown("<br>", unsafe_allow_html=True)
c1, c2, c3 = st.columns(3)
with c1:
st.markdown(f"""<div class="info-card">
<h4>{lucide_icon("target", size=18, color=BLUE)} What it does</h4>
<p>Estimates churn probability from customer profile data and converts ML outputs into
business-focused retention guidance via an AI agent.</p>
</div>""", unsafe_allow_html=True)
with c2:
st.markdown(f"""<div class="info-card">
<h4>{lucide_icon("settings", size=18, color=BLUE)} How it works</h4>
<p>Input customer attributes → preprocessing pipeline → risk scoring →
LangGraph + RAG agent → personalised intervention plan.</p>
</div>""", unsafe_allow_html=True)
with c3:
st.markdown(f"""<div class="info-card">
<h4>{lucide_icon("folder-open", size=18, color=BLUE)} Data supported</h4>
<p>Structured CSV records, model artifacts (.pkl), markdown strategy docs,
and FAISS vector indexes for retrieval-augmented planning.</p>
</div>""", unsafe_allow_html=True)
st.markdown(f"""<div class="flow-box">
<h3>{lucide_icon("workflow", size=22, color=BLUE)} Product Flow</h3>
<p class="flow-step"><strong>1.</strong> Explore churn trends in the analytics dashboard.</p>
<p class="flow-step"><strong>2.</strong> Predict churn probability for any customer profile.</p>
<p class="flow-step"><strong>3.</strong> Generate an expert retention strategy and download the report.</p>
</div>""", unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
if st.button("Enter Dashboard", width='stretch'):
st.session_state.show_dashboard = True
st.rerun()
if not st.session_state.show_dashboard:
render_home_page()
st.stop()
# Sidebar navigation to control the platform's active phase.
with st.sidebar:
st.markdown("""
<div style="padding:0.8rem 0 1.2rem; border-bottom:1px solid #1e2d45; margin-bottom:1rem;">
<div style="font-size:1.25rem;font-weight:800;color:#f8fafc;letter-spacing:-0.02em;">
Sli<span style="color:#38bdf8;">p</span>
</div>
<div style="color:#475569;font-size:0.8rem;margin-top:0.2rem;">Telco Churn Intelligence</div>
</div>
""", unsafe_allow_html=True)
selected = option_menu(
menu_title=None,
options=["Overview", "Churn Prediction", "AI Strategist", "Model Performance"],
icons=["graph-up", "cpu", "robot", "activity"],
default_index=["Overview", "Churn Prediction", "AI Strategist", "Model Performance"].index(
st.session_state.active_tab
),
styles={
"container": {"background-color": "transparent", "padding": "0"},
"nav-link": {"font-size": "0.9rem", "font-weight": "500",
"color": "#94a3b8", "border-radius": "10px",
"margin": "2px 0", "--hover-color": "#111827"},
"nav-link-selected": {"background": "linear-gradient(135deg,#1d4ed8,#1e40af)",
"color": "white", "font-weight": "600"},
"icon": {"color": "#38bdf8"},
},
)
if selected != st.session_state.active_tab:
st.session_state.active_tab = selected
st.rerun()
st.markdown("<br>", unsafe_allow_html=True)
churn_rate = (df["Churn"] == "Yes").sum() / len(df) * 100
st.markdown(f"""
<div style="background:#0a1628;border:1px solid #1e2d45;border-radius:12px;padding:0.9rem 1rem;">
<div style="color:#475569;font-size:0.75rem;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;margin-bottom:0.6rem;">Dataset Snapshot</div>
<div style="display:flex;justify-content:space-between;margin-bottom:0.35rem;">
<span style="color:#94a3b8;font-size:0.83rem;">Total customers</span>
<span style="color:#e2e8f0;font-weight:600;font-size:0.83rem;">{len(df):,}</span>
</div>
<div style="display:flex;justify-content:space-between;margin-bottom:0.35rem;">
<span style="color:#94a3b8;font-size:0.83rem;">Churn rate</span>
<span style="color:#f97316;font-weight:600;font-size:0.83rem;">{churn_rate:.1f}%</span>
</div>
<div style="display:flex;justify-content:space-between;">
<span style="color:#94a3b8;font-size:0.83rem;">Features</span>
<span style="color:#e2e8f0;font-weight:600;font-size:0.83rem;">{len(feature_columns)}</span>
</div>
</div>
""", unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
# Unified Back Button Card - Perfectly aligned using Flexbox
st.markdown(f"""
<a href="/?nav=home" target="_self" style="text-decoration: none;">
<div style="display: flex; align-items: center; justify-content: center; gap: 10px;
background: linear-gradient(135deg, #1d4ed8 0%, #1e40af 100%);
color: white; padding: 12px; border-radius: 12px;
font-weight: 600; font-size: 0.95rem; cursor: pointer;
box-shadow: 0 4px 12px rgba(29, 78, 216, 0.3);
transition: all 0.2s ease; border: 1px solid rgba(255,255,255,0.1);">
{lucide_icon("arrow-left", size=18, color="white")}
<span>Back to Home</span>
</div>
</a>
""", unsafe_allow_html=True)
# App header section.
st.markdown(f"""
<div class="app-header">
<div class="app-header-icon">{lucide_icon("tower-control", size=36, color=BLUE)}</div>
<div>
<h1 class="app-title">Slip — Churn Command Center</h1>
<p class="app-subtitle">Monitor churn signals · Predict risk · Generate AI-powered retention actions</p>
</div>
</div>
""", unsafe_allow_html=True)
# Overview phase: Explore historical churn trends and behavioral distributions.
if selected == "Overview":
st.markdown(f"""
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
<div>
<h1 style="margin:0; font-size: 2.2rem; font-weight: 800; letter-spacing: -0.04em; color: #fff;">
Platform Intelligence <span style="color: #38bdf8;">Overview</span>
</h1>
<p style="margin: 4px 0 0; color: #64748b; font-size: 0.95rem;">Telco Customer Analysis & Behavioral Insights</p>
</div>
<div class="status-pill"><div class="status-dot"></div> {lucide_icon("shield-check", size=12)} System Operational</div>
</div>
""", unsafe_allow_html=True)
# Executive summary of key performance indicators.
kpi1, kpi2, kpi3, kpi4 = st.columns(4)
with kpi1: st.metric("Total Base", f"{len(df):,}", help="Active subscribers in dataset")
with kpi2: st.metric("Churn Rate", f"{(df['Churn'].value_counts(normalize=True).get('Yes', 0)*100):.1f}%", delta="-0.8%", delta_color="normal")
with kpi3: st.metric("Avg. Ticket", f"${df['MonthlyCharges'].mean():.1f}", help="Mean monthly charges")
with kpi4: st.metric("CLV Potential", "$4.2M", help="Estimated lifetime value at risk")
style_metric_cards(background_color="#0f1e36", border_left_color="#38bdf8", border_color="#1e2d45")
st.markdown("<br>", unsafe_allow_html=True)
c1, c2 = st.columns(2)
with c1:
st.markdown('<div class="section-card">', unsafe_allow_html=True)
st.subheader("Churn Distribution")
counts = df["Churn"].value_counts().reset_index()
counts.columns = ["Status", "Count"]
counts["Status"] = counts["Status"].map({"No": "Retained", "Yes": "Churned"})
fig = go.Figure(go.Pie(
labels=counts["Status"], values=counts["Count"],
hole=0.58, marker_colors=[BLUE, ORG],
textinfo="percent+label",
textfont=dict(size=13, color="#e2e8f0"),
hovertemplate="<b>%{label}</b><br>Count: %{value:,}<br>Share: %{percent}<extra></extra>",
))
apply_layout(fig, height=300, showlegend=False)
fig.add_annotation(text=f"<b>{churn_rate:.0f}%</b><br><span style='font-size:11px'>churn</span>",
x=0.5, y=0.5, showarrow=False, font=dict(size=18, color="#f97316"))
st.plotly_chart(fig, width='stretch')
st.markdown('</div>', unsafe_allow_html=True)
with c2:
st.markdown('<div class="section-card">', unsafe_allow_html=True)
st.subheader("Contract Type vs Churn")
contract_churn = df.groupby(["Contract", "Churn"]).size().reset_index(name="count")
contract_churn["Churn"] = contract_churn["Churn"].map({"No": "Retained", "Yes": "Churned"})
fig = px.bar(contract_churn, x="Contract", y="count", color="Churn",
barmode="group", color_discrete_map={"Retained": BLUE, "Churned": ORG},
labels={"count": "Customers", "Contract": "Contract Type"},
hover_data={"count": ":,"},
template="plotly_dark")
apply_layout(fig, height=300, bargap=0.28)
fig.update_traces(marker_line_width=0)
st.plotly_chart(fig, width='stretch')
st.markdown('</div>', unsafe_allow_html=True)
c3, c4 = st.columns(2)
with c3:
st.markdown('<div class="section-card">', unsafe_allow_html=True)
st.subheader("Tenure Distribution by Churn")
fig = px.histogram(
df, x="tenure", color="Churn", nbins=35,
color_discrete_map={"No": BLUE, "Yes": ORG},
labels={"tenure": "Tenure (months)", "count": "Customers"},
opacity=0.8, barmode="overlay", template="plotly_dark",
)
apply_layout(fig, height=300, legend=dict(title="", bgcolor="rgba(0,0,0,0)"))
fig.update_traces(marker_line_width=0)
st.plotly_chart(fig, width='stretch')
st.markdown('</div>', unsafe_allow_html=True)
with c4:
st.markdown('<div class="section-card">', unsafe_allow_html=True)
st.subheader("Monthly Charges by Churn")
fig = px.violin(
df, x="Churn", y="MonthlyCharges", color="Churn", box=True,
color_discrete_map={"No": BLUE, "Yes": ORG},
labels={"MonthlyCharges": "Monthly Charges ($)", "Churn": ""},
template="plotly_dark", points="outliers",
)
apply_layout(fig, height=300, showlegend=False)
st.plotly_chart(fig, width='stretch')
st.markdown('</div>', unsafe_allow_html=True)
if "InternetService" in df.columns and "Churn" in df.columns:
st.markdown('<div class="section-card">', unsafe_allow_html=True)
st.subheader("Internet Service vs Churn")
internet_churn = df.groupby(["InternetService", "Churn"]).size().reset_index(name="count")
internet_churn["Churn"] = internet_churn["Churn"].map({"No": "Retained", "Yes": "Churned"})
fig = px.bar(internet_churn, x="InternetService", y="count", color="Churn",
barmode="group", color_discrete_map={"Retained": BLUE, "Churned": ORG},
labels={"count": "Customers", "InternetService": "Internet Service"},
template="plotly_dark")
apply_layout(fig, height=300, bargap=0.3)
fig.update_traces(marker_line_width=0)
st.plotly_chart(fig, width='stretch')
st.markdown('</div>', unsafe_allow_html=True)
num_cols = [col for col in ["tenure", "MonthlyCharges", "TotalCharges"] if col in df.columns]
if len(num_cols) >= 2:
st.markdown('<div class="section-card">', unsafe_allow_html=True)
st.subheader("Feature Correlation Heatmap")
corr_df = df[num_cols].corr().round(2)
fig = go.Figure(go.Heatmap(
z=corr_df.values, x=corr_df.columns, y=corr_df.columns,
colorscale=[[0,"#0a1628"],[0.5,"#1d4ed8"],[1,"#38bdf8"]],
text=corr_df.values.round(2), texttemplate="%{text}",
hovertemplate="%{x} × %{y}: %{z}<extra></extra>",
))
apply_layout(fig, height=450, margin=dict(l=50, r=50, t=50, b=50))
st.plotly_chart(fig, width='stretch')
st.markdown('</div>', unsafe_allow_html=True)
if len(df) > 0:
st.divider()
st.subheader("Sample Data (first 100 rows)")
st.dataframe(df.head(100), width='stretch')
# Churn Prediction phase: Calculate risk for specific customer profiles.
elif selected == "Churn Prediction":
st.markdown('<div class="section-card">', unsafe_allow_html=True)
st.markdown(f"### {lucide_icon('clipboard-list', size=24, color=BLUE)} Customer Profile Intelligence", unsafe_allow_html=True)
st.caption("Enter the customer details below to calculate churn probability and generate retention strategies.")
with st.form("prediction_form", border=False):
st.markdown(f"#### {lucide_icon('user', size=18, color=BLUE)} Step 1: Identity & Basics", unsafe_allow_html=True)
c_i1, c_i2, c_i3 = st.columns([1, 1.2, 1])
with c_i1: customer_name = st.text_input("Full Name", value="", placeholder="e.g. John Doe")
with c_i2: customer_email = st.text_input("Email Address", value="", placeholder="john.doe@example.com")
with c_i3: company_name = st.text_input("Organization", value="", placeholder="e.g. Acme Corp")
st.markdown("<br>", unsafe_allow_html=True)
st.markdown(f"#### {lucide_icon('credit-card', size=18, color=BLUE)} Step 2: Account & Subscription", unsafe_allow_html=True)
a1, a2, a3 = st.columns(3)
with a1:
tenure = st.number_input("Tenure (Months)", min_value=0, max_value=120, value=12, help="How long as a customer")
contract = st.selectbox("Contract Type", ["Month-to-month", "One year", "Two year"])
with a2:
monthly_charges = st.number_input("Monthly Charges ($)", 0.0, 200.0, 65.0, 0.5)
paperless_billing = st.selectbox("Paperless Billing", ["Yes", "No"])
with a3:
total_charges = st.number_input("Total Charges ($)", 0.0, 10000.0, 780.0, 1.0)
payment_method = st.selectbox("Payment Method", [
"Electronic check", "Mailed check",
"Bank transfer (automatic)", "Credit card (automatic)",
])
st.markdown("<br>", unsafe_allow_html=True)
st.markdown(f"#### {lucide_icon('wrench', size=18, color=BLUE)} Step 3: Service & Technical Profile", unsafe_allow_html=True)
d1, d2 = st.columns(2)
with d1:
gender = st.selectbox("Gender", ["Male", "Female"])
senior_citizen = st.selectbox("Senior Citizen", ["No", "Yes"])
with d2:
partner = st.selectbox("Has Partner?", ["Yes", "No"])
dependents = st.selectbox("Has Dependents?", ["Yes", "No"])
with st.expander(f"Advanced Service Details", expanded=False):
st.markdown(f"<div style='margin-bottom:10px;'>{lucide_icon('globe', size=16, color=BLUE)} Network Configuration</div>", unsafe_allow_html=True)
st.caption("Toggle these settings for specific service configurations.")
s1, s2, s3 = st.columns(3)
with s1:
phone_service = st.selectbox("Phone Service", ["Yes", "No"])
multiple_lines = st.selectbox("Multiple Lines", ["No", "Yes", "No phone service"])
internet_service = st.selectbox("Internet Service", ["DSL", "Fiber optic", "No"])
with s2:
online_security = st.selectbox("Online Security", ["No", "Yes", "No internet service"])
online_backup = st.selectbox("Online Backup", ["No", "Yes", "No internet service"])
device_protection = st.selectbox("Device Protection", ["No", "Yes", "No internet service"])
with s3:
tech_support = st.selectbox("Tech Support", ["No", "Yes", "No internet service"])
streaming_tv = st.selectbox("Streaming TV", ["No", "Yes", "No internet service"])
streaming_movies = st.selectbox("Streaming Movies", ["No", "Yes", "No internet service"])
st.markdown("<br>", unsafe_allow_html=True)
submitted = st.form_submit_button("Run Churn Analysis", width='stretch')
st.markdown('</div>', unsafe_allow_html=True)
if submitted and not is_valid_email(customer_email):
st.error("Please enter a valid email address before running prediction.")
if submitted and is_valid_email(customer_email):
with st.status("Analysing customer profile...", expanded=True) as status:
st.write("Extracting demographic and service data...")
time.sleep(0.4)
st.write("Running preprocessing pipeline...")
time.sleep(0.4)
st.write("Executing predictive model...")
input_data = {
"gender": gender,
"SeniorCitizen": 1 if senior_citizen == "Yes" else 0,
"Partner": partner, "Dependents": dependents,
"tenure": tenure, "PhoneService": phone_service,
"MultipleLines": multiple_lines, "InternetService": internet_service,
"OnlineSecurity": online_security, "OnlineBackup": online_backup,
"DeviceProtection": device_protection, "TechSupport": tech_support,
"StreamingTV": streaming_tv, "StreamingMovies": streaming_movies,
"Contract": contract, "PaperlessBilling": paperless_billing,
"PaymentMethod": payment_method,
"MonthlyCharges": monthly_charges, "TotalCharges": total_charges,
}
input_df = pd.DataFrame([input_data])[feature_columns]
prediction = pipeline.predict(input_df)[0]
proba = pipeline.predict_proba(input_df)[0]
churn_prob = proba[1] * 100
stay_prob = proba[0] * 100
st.session_state.customer_data = input_data
st.session_state.churn_prob = churn_prob
st.session_state.agent_result = None
time.sleep(0.4)
status.update(label="Analysis complete ✓", state="complete", expanded=False)
console.print(Panel(
f"Customer: [bold]{customer_name}[/bold] | Churn prob: [bold red]{churn_prob:.1f}%[/bold red]",
title="[cyan]prediction[/cyan]"
))
st.toast("Prediction generated")
st.markdown('<div class="section-card">', unsafe_allow_html=True)
render_header("Analytical Verdict", "target", BLUE)
# Visualize the final risk verdict with a high-fidelity risk card.
status_color = "#f43f5e" if prediction == 1 else "#10b981"
status_bg = "rgba(244, 63, 94, 0.08)" if prediction == 1 else "rgba(16, 185, 129, 0.08)"
status_icon = lucide_icon("alert-triangle", size=64, color=status_color) if prediction == 1 else lucide_icon("check-circle", size=64, color=status_color)
status_label = "CRITICAL CHURN RISK" if prediction == 1 else "LOYAL CUSTOMER PROFILE"
st.markdown(f"""
<div style="background: {status_bg};
border: 1px solid {status_color}44;
border-radius: 24px;
padding: 40px 30px;
text-align: center;
margin-bottom: 30px;
box-shadow: inset 0 0 30px {status_color}11;">
<div style="margin-bottom: 25px; filter: drop-shadow(0 0 10px {status_color}44);">{status_icon}</div>
<div style="color: {status_color}; font-weight: 800; font-size: 1.4rem; letter-spacing: 0.15em; margin-bottom: 8px; text-transform: uppercase;">
{status_label}
</div>
<div style="color: #94a3b8; font-size: 1rem; margin-bottom: 25px;">
Customer Identity: <span style="color: #fff; font-weight: 600;">{customer_name or "Anonymous"}</span>
</div>
<div style="display: flex; justify-content: center; align-items: baseline; gap: 8px;">
<span style="font-size: 4.5rem; font-weight: 900; color: #fff; line-height: 1;">{churn_prob:.1f}</span>
<span style="font-size: 1.8rem; font-weight: 700; color: {status_color};">%</span>
</div>
<div style="color: #64748b; font-size: 0.85rem; text-transform: uppercase; letter-spacing: 0.05em; font-weight: 600;">
Calculated Churn Probability Score
</div>
</div>
""", unsafe_allow_html=True)
col_gau, col_bar = st.columns([1, 1])
with col_gau:
# Gauge chart
gauge_color = ORG if churn_prob > 50 else BLUE
fig = go.Figure(go.Indicator(
mode="gauge+number",
value=churn_prob,
number={"suffix": "%", "font": {"size": 32, "color": gauge_color}},
gauge={
"axis": {"range": [0, 100], "tickcolor": "#475569", "tickfont": {"size": 11}},
"bar": {"color": gauge_color, "thickness": 0.3},
"bgcolor": "#0a1628",
"bordercolor": "#1e2d45",
"steps": [
{"range": [0, 30], "color": "rgba(16, 185, 129, 0.1)"},
{"range": [30, 70], "color": "rgba(251, 191, 36, 0.1)"},
{"range": [70, 100], "color": "rgba(244, 63, 94, 0.1)"},
],
},
))
apply_layout(fig, height=260, margin=dict(l=30, r=30, t=50, b=10))
st.plotly_chart(fig, width='stretch')
with col_bar:
# Horizontal prob bar
fig2 = go.Figure(go.Bar(
x=[stay_prob, churn_prob], y=["Retention", "Risk"],
orientation="h",
marker_color=["#10b981", "#f43f5e"],
text=[f"{stay_prob:.1f}%", f"{churn_prob:.1f}%"],
textposition="inside",
textfont=dict(color="#fff", size=14, family="Inter"),
hoverinfo="none"
))
apply_layout(fig2, height=260, xaxis=dict(showgrid=False, zeroline=False, range=[0, 100], showticklabels=False),
yaxis=dict(showgrid=False, zeroline=False))
st.plotly_chart(fig2, width='stretch')
st.markdown('</div>', unsafe_allow_html=True)
st.divider()
st.markdown('<div class="section-card">', unsafe_allow_html=True)
render_header("Strategic Insights", "lightbulb", color="#fbbf24")
ci1, ci2 = st.columns(2)
with ci1:
render_header("Top Risk Drivers", "alert-circle", color="#f43f5e", font_size="1.1rem")
factors = []
if contract == "Month-to-month": factors.append("Month-to-month contract (High churn segment)")
if internet_service == "Fiber optic": factors.append("Fiber optic service (Quality/Price sensitivity)")
if tech_support == "No": factors.append("Lack of Tech Support (Key retention barrier)")
if tenure < 12: factors.append("Low tenure (<1 yr) (Early lifecycle churn)")
if not factors:
st.success("No critical risk drivers detected for this profile.")
else:
for f in factors:
st.markdown(f"""
<div style="background: rgba(244, 63, 94, 0.15); border-left: 3px solid #f43f5e;
padding: 8px 15px; border-radius: 4px; margin-bottom: 8px; font-size: 0.9rem;">
{f}
</div>
""", unsafe_allow_html=True)
with ci2:
render_header("Recommended Mitigation", "shield-check", color="#10b981", font_size="1.1rem")
recs = []
if prediction == 1:
recs.append("Offer 10–20% 'Upgrade Reward' discount")
if tech_support == "No": recs.append("Grant 3 months complimentary Tech Support")
if internet_service == "Fiber optic": recs.append("Schedule proactive connectivity health check")
else:
recs.append("Incentivize long-term loyalty with referral bonus")
recs.append("Upsell hardware or high-tier streaming bundle")
for r in recs:
st.markdown(f"""
<div style="background: rgba(16, 185, 129, 0.15); border-left: 3px solid #10b981;
padding: 8px 15px; border-radius: 4px; margin-bottom: 8px; font-size: 0.9rem;">
{r}
</div>
""", unsafe_allow_html=True)
st.markdown('</div>', unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
st.subheader("Customer vs Average Metrics")
metrics = ["Tenure (months)", "Monthly Charges ($)", "Total Charges ($)"]
customer_vals = [tenure, monthly_charges, total_charges]
avg_vals = [df["tenure"].mean(), df["MonthlyCharges"].mean(), df["TotalCharges"].mean()]
fig3 = go.Figure()
fig3.add_trace(go.Bar(name="This Customer", x=metrics, y=customer_vals,
marker_color=ORG if prediction == 1 else BLUE,
text=[f"{v:,.1f}" for v in customer_vals], textposition="outside"))
fig3.add_trace(go.Bar(name="Dataset Average", x=metrics, y=avg_vals,
marker_color="#1e293b",
text=[f"{v:,.1f}" for v in avg_vals], textposition="outside"))
apply_layout(fig3, height=320, barmode="group", bargap=0.3,
font=dict(color="#e2e8f0", size=12))
st.plotly_chart(fig3, width='stretch')
st.divider()
st.subheader("Export Results")
export_data = input_data.copy()
export_data["Prediction_Churn"] = "Yes" if prediction == 1 else "No"
export_data["Churn_Probability"] = f"{churn_prob:.1f}%"
export_data["Stay_Probability"] = f"{stay_prob:.1f}%"
csv_data = pd.DataFrame([export_data]).to_csv(index=False).encode("utf-8")
st.download_button("Download Prediction as CSV", csv_data,
"churn_prediction_result.csv", "text/csv", width='stretch')
st.markdown(f'<div style="margin-top:-35px; text-align:right;">{lucide_icon("file-down", size=18, color=BLUE)}</div>', unsafe_allow_html=True)
# Phase 3: Conversing with the AI Strategist for personalized actions.
elif selected == "AI Strategist":
st.subheader("AI-Driven Retention Strategy")
if st.session_state.customer_data is None:
st.markdown(f"""
<div style="background: rgba(56, 189, 248, 0.1); border: 1px solid rgba(56, 189, 248, 0.2);
border-radius: 12px; padding: 1rem 1.2rem; display: flex; align-items: center; gap: 12px; margin-bottom: 1rem;">
{lucide_icon("search", size=20, color=BLUE)}
<div style="color: #38bdf8; font-size: 0.95rem; font-weight: 500;">
Run a prediction in Churn Prediction first to enable the AI Strategist.
</div>
</div>
""", unsafe_allow_html=True)
else:
st.markdown("""
This agent uses **LangGraph** to process customer data, query a **RAG knowledge base**
of retention strategies, and generate a personalised intervention plan via **Gemini Flash**.
""")
c1, c2 = st.columns([1, 1])
with c1:
st.markdown("### Target Customer Profile")
st.json(st.session_state.customer_data)
with c2:
st.markdown("### Risk Context")