-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.py
More file actions
3034 lines (2653 loc) · 136 KB
/
Copy pathapp.py
File metadata and controls
3034 lines (2653 loc) · 136 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 streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import json
import numpy as np
from pathlib import Path
from datetime import datetime, timedelta
# ── Groq AI Analyst ────────────────────────────────────────────────────────
from Groq_analyst import GroqAnalyst, build_context
# ── Currency Configuration ──────────────────────────────────────────────────
IDR_RATE = 3500 # 1 RM = Rp 3,500 (historical conversion rate)
def _c(val):
"""Convert RM to IDR if IDR mode is selected in session state."""
if st.session_state.get('currency', 'RM') == 'IDR':
return val * IDR_RATE
return val
def _fmt_idr(n, fmt=",.0f"):
"""Format number in Indonesian style: . = thousand sep, , = decimal sep."""
s = format(n, fmt) # e.g. "1,234,567.89"
s = s.replace(",", "X") # "1X234X567.89"
s = s.replace(".", ",") # "1X234X567,89"
s = s.replace("X", ".") # "1.234.567,89"
return s
def currency(val, fmt=",.0f"):
"""Format a monetary value: converts RM→IDR if toggle is on, adds correct prefix."""
prefix = "Rp" if st.session_state.get('currency', 'RM') == 'IDR' else "RM"
return f"{prefix} {_fmt_idr(_c(val), fmt)}"
def cur_sym():
"""Return currency symbol ('Rp' or 'RM') based on current toggle."""
return "Rp" if st.session_state.get('currency', 'RM') == 'IDR' else "RM"
# ══════════════════════════════════════════════════════════════════════════════
# PAGE CONFIG — High-end dark mode
# ══════════════════════════════════════════════════════════════════════════════
st.set_page_config(
page_title='G Coffee Shop — Strategic Intelligence Dashboard',
page_icon='☕',
layout='wide',
initial_sidebar_state='expanded',
)
# ── Early Session State Init: Theme toggle (needed for token generation before sidebar renders)
if 'theme_toggle' not in st.session_state:
st.session_state['theme_toggle'] = 'Dark'
# ── Custom dark-theme CSS ────────────────────────────────────────────────────
# ── Helper: hex to rgba for plotly ────────────────────────────────────────────
def hex_to_rgba(hex_color, alpha=0.15):
"""Convert hex color to rgba string for plotly."""
hex_color = hex_color.lstrip('#')
r, g, b = int(hex_color[0:2], 16), int(hex_color[2:4], 16), int(hex_color[4:6], 16)
return f'rgba({r},{g},{b},{alpha})'
# ══════════════════════════════════════════════════════════════════════════════
# DYNAMIC CSS TOKEN SYSTEM
# ══════════════════════════════════════════════════════════════════════════════
# ── Determine effective theme (instant — no one-run delay) ────────────────
_toggle_val = st.session_state.get('theme_toggle')
if _toggle_val is not None:
_effective_theme = 'dark' if 'Dark' in _toggle_val else 'light'
else:
_effective_theme = st.session_state.get('theme', 'dark')
# ── Token values per theme ─────────────────────────────────────────────────
_DARK_TOKENS = {
# Backgrounds
'bg-app': '#0E1117', 'bg-card': '#1A1D27',
'bg-sidebar': '#12141E', 'bg-radio': '#1A1D27',
'bg-radio-sel': '#2D3142', 'bg-button': '#2D3142',
'bg-button-hv': '#3D4157', 'bg-alert': '#1A1D27',
'bg-table': '#1A1D27', 'bg-badge': 'linear-gradient(135deg, #1a1d27, #2a2d3e)',
# Text
'txt-primary': '#F0F0F0', 'txt-secondary': '#B0B0C0',
'txt-muted': '#888', 'txt-inverse': '#FFFFFF',
'txt-value': '#FFFFFF', 'txt-metric': '#FFFFFF',
'txt-metric-lbl': '#B0B0C0', 'txt-badge': '#B0B0C0',
'txt-sb-heading': '#F0F0F0', 'txt-sb-sub': '#888',
'txt-sb-footer': '#666', 'txt-table': '#E0E0E0',
'txt-table-hdr': '#B0B0C0', 'txt-btn': '#FFFFFF',
'bg-chart': '#0E1117', # chart pie-line border
# Borders & misc
'border': '#2D3142', 'border-badge': '#3d4157',
'shadow-card': 'none',
}
_LIGHT_TOKENS = {
# Backgrounds — Nordic Warm Light (krem-slate lembut, premium, ergonomis)
'bg-app': '#FDFBF7', 'bg-card': '#FFFFFF',
'bg-sidebar': '#F4F1EA', 'bg-radio': '#FFFFFF',
'bg-radio-sel': '#EAE4D9', 'bg-button': '#FFFFFF',
'bg-button-hv': '#F0ECE3', 'bg-alert': '#FFFFFF',
'bg-table': '#FFFFFF', 'bg-badge': '#F0ECE3',
# Text — slate arang pekat, kontras tinggi, mudah dibaca
'txt-primary': '#252F3F', 'txt-secondary': '#4A5568',
'txt-muted': '#718096', 'txt-inverse': '#252F3F',
'txt-value': '#252F3F', 'txt-metric': '#252F3F',
'txt-metric-lbl': '#718096', 'txt-badge': '#4A5568',
# Sidebar text — slate arang pekat, paksa teks menu keluar dari efek nyaru
'txt-sb-heading': '#252F3F', 'txt-sb-sub': '#4A5568',
'txt-sb-footer': '#94A3B8', 'txt-table': '#252F3F',
'txt-table-hdr': '#4A5568', 'txt-btn': '#252F3F',
'bg-chart': '#E2E8F0', # chart pie-line border
# Borders & misc — senada dengan bg-sidebar
'border': '#E8E2D6', 'border-badge': '#E8E2D6',
'shadow-card': '0 1px 3px rgba(0,0,0,0.05)',
}
# ── Build CSS variable block ───────────────────────────────────────────────
def _build_tokens(theme):
"""Return CSS :root block for the given theme."""
src = _DARK_TOKENS if theme == 'dark' else _LIGHT_TOKENS
lines = [':root {']
for k, v in src.items():
lines.append(f' --{k}: {v};')
lines.append('}')
return '\n'.join(lines)
_theme_tokens = _build_tokens(_effective_theme)
# ── Base CSS (all rules use var() tokens) ──────────────────────────────────
_BASE_CSS = """
/* ── Misc helpers ── */
.stApp { background-color: var(--bg-app); }
/* ── Main content headings & text ── */
section[data-testid="stMain"] h1,
section[data-testid="stMain"] h2,
section[data-testid="stMain"] h3,
section[data-testid="stMain"] h4,
section[data-testid="stMain"] p,
section[data-testid="stMain"] .stMarkdown p,
section[data-testid="stMain"] .stMarkdown span,
section[data-testid="stMain"] .stMarkdown div:not([class*="insight"]):not([class*="badge"]) {
color: var(--txt-primary) !important;
}
hr { border-color: var(--border); }
/* ── Analytical Lens Switcher (segmented control style) ── */
div[data-testid="stHorizontalBlock"]:has(> div > label[for="lens_radio"]) {
background: var(--bg-radio) !important;
border-radius: 8px !important;
padding: 2px !important;
display: inline-flex !important;
width: auto !important;
gap: 0 !important;
}
div[data-testid="stHorizontalBlock"]:has(> div > label[for="lens_radio"]) > div {
flex: 0 0 auto !important;
padding: 0 2px !important;
}
div[data-testid="stHorizontalBlock"]:has(> div > label[for="lens_radio"]) .stRadio label {
color: var(--txt-secondary) !important;
padding: 6px 16px !important;
border-radius: 6px !important;
font-size: 0.85rem !important;
font-weight: 500 !important;
transition: all 0.15s ease !important;
}
div[data-testid="stHorizontalBlock"]:has(> div > label[for="lens_radio"]) .stRadio label:has(input:checked) {
background: var(--bg-card) !important;
color: var(--txt-primary) !important;
box-shadow: 0 1px 3px rgba(0,0,0,0.1) !important;
}
/* ── Insight cards ── */
.insight-card {
background-color: var(--bg-card);
border: 1px solid var(--border);
border-radius: 12px;
padding: 20px;
margin: 8px 0;
box-shadow: var(--shadow-card);
}
.insight-card h4 {
color: var(--txt-secondary); font-size: 0.85rem;
text-transform: uppercase; letter-spacing: 0.5px; margin: 0 0 8px 0;
}
.insight-card .value { color: var(--txt-value); font-size: 2rem; font-weight: 700; }
.insight-card .sub { color: var(--txt-muted); font-size: 0.8rem; }
/* ── Business badge ── */
.business-badge {
background: var(--bg-badge);
border: 1px solid var(--border-badge); border-radius: 8px;
padding: 6px 14px; display: inline-block;
color: var(--txt-badge); font-size: 0.8rem; margin: 2px;
}
/* ── Sidebar ── */
/* Streamlit renders sidebar as <section> — NOT <div> */
section[data-testid="stSidebar"],
section[data-testid="stSidebar"] > div:first-child {
background-color: var(--bg-sidebar) !important;
border-right: 1px solid var(--border);
}
/* Sidebar: ALL markdown text, headings, labels — forced dark-teduh */
section[data-testid="stSidebar"] .stMarkdown p,
section[data-testid="stSidebar"] .stMarkdown div,
section[data-testid="stSidebar"] h1,
section[data-testid="stSidebar"] h2,
section[data-testid="stSidebar"] h3,
section[data-testid="stSidebar"] h4,
section[data-testid="stSidebar"] label,
section[data-testid="stSidebar"] .stSelectbox label {
color: var(--txt-sb-heading) !important;
}
/* Sidebar radio — clean text list (no circles, theme-aware highlight) */
/* opacity:1 + txt-primary paksa teks menu keluar dari efek nyaru */
section[data-testid="stSidebar"] .stRadio [role="radio"] {
color: var(--txt-primary) !important;
opacity: 1 !important;
border-radius: 6px !important;
padding: 4px 10px !important;
margin: 1px 0 !important;
transition: all 0.15s ease !important;
cursor: pointer !important;
}
/* Hide the radio circle / bullet entirely */
section[data-testid="stSidebar"] .stRadio [role="radio"] > span:first-child {
display: none !important;
}
/* Active item — teks tetap gelap pekat, highlight via bg-radio-sel */
section[data-testid="stSidebar"] .stRadio [role="radio"][aria-checked="true"] {
background-color: var(--bg-radio-sel) !important;
color: var(--txt-primary) !important;
opacity: 1 !important;
font-weight: 500 !important;
}
/* Hover state */
section[data-testid="stSidebar"] .stRadio [role="radio"]:hover {
background-color: var(--bg-radio-sel) !important;
}
/* Sidebar: universal force — semua anak elemen teks jadi gelap pekat */
section[data-testid="stSidebar"] *,
section[data-testid="stSidebar"] .stRadio [role="radio"] *,
section[data-testid="stSidebar"] .stRadio label span {
color: var(--txt-primary) !important;
opacity: 1 !important;
}
/* Sidebar active item — semua anak elemen tetap gelap */
section[data-testid="stSidebar"] [aria-checked="true"] *,
section[data-testid="stSidebar"] [aria-checked="true"] span {
color: var(--txt-primary) !important;
}
/* ── Metric cards ── */
.stMetric {
background-color: var(--bg-card); border-radius: 12px;
padding: 16px; border: 1px solid var(--border);
}
.stMetric label { color: var(--txt-metric-lbl); font-size: 0.85rem; }
.stMetric [data-testid="stMetricValue"] {
color: var(--txt-metric); font-size: 1.8rem; font-weight: 700;
}
/* ── DataFrames ── */
/* HANYA target kontainer utama — tanpa wildcard, tanpa role="grid" */
.stDataFrame,
div[data-testid="stDataFrame"] {
background-color: var(--bg-table) !important;
}
/* Teks di dalam data grid — tanpa merusak posisi canvas Glide */
div[data-testid="stDataFrame"] [data-testid="styled-data-grid"] {
color: var(--txt-table) !important;
}
/* Header row — kontras gelap */
.stDataFrame div[role="columnheader"],
div[data-testid="stDataFrame"] div[role="columnheader"] {
font-weight: 600 !important;
color: var(--txt-table-hdr) !important;
background-color: var(--bg-table) !important;
}
/* HTML table fallback untuk custom markdown tables */
table td, table th,
.stTable td, .stTable th {
color: var(--txt-primary) !important;
background-color: var(--bg-table) !important;
border-color: var(--border) !important;
}
/* ── Radio groups ── */
.stRadio [data-testid="stRadioLabel"] { color: var(--txt-secondary) !important; }
.stRadio [role="radiogroup"] { background-color: var(--bg-radio); border: 1px solid var(--border); border-radius: 8px; padding: 4px; }
/* Sidebar: radiogroup becomes a clean list (no border/bg) */
section[data-testid="stSidebar"] .stRadio [role="radiogroup"] {
background: none !important;
border: none !important;
padding: 0 !important;
}
.stRadio [role="radio"] { color: var(--txt-secondary) !important; }
.stRadio [role="radio"][aria-checked="true"] { background-color: var(--bg-radio-sel); color: var(--txt-inverse) !important; }
section[data-testid="stSidebar"] .stRadio [data-testid="stRadioLabel"] { color: var(--txt-secondary) !important; }
/* ── Selectbox & Slider labels ── */
.stSelectbox label, .stSlider label { color: var(--txt-muted); }
/* ── Alerts ── */
.stAlert { background-color: var(--bg-alert); border: 1px solid var(--border); color: var(--txt-table); }
/* ── Buttons (general) ── */
.stButton button {
background-color: var(--bg-button); color: var(--txt-btn);
border: 1px solid var(--border); border-radius: 8px; padding: 8px 20px; font-weight: 500;
}
.stButton button:hover { background-color: var(--bg-button-hv); }
/* ── Dropdown / Selectbox (bajak widget hitam) ── */
div[data-testid="stSelectbox"] div[data-baseweb="select"],
div[data-testid="stSelectbox"] ul[role="listbox"],
div[data-testid="stSelectbox"] li {
background-color: var(--bg-card) !important;
color: var(--txt-primary) !important;
}
div[data-testid="stSelectbox"] div[data-baseweb="select"] span,
div[data-testid="stSelectbox"] div[data-baseweb="select"] input {
color: var(--txt-primary) !important;
}
/* ── Widget text (slider, multi-select) ── */
.stMultiSelect div[data-baseweb="select"] *,
.stSlider div[data-baseweb="slider"] [role="slider"] + div,
.stSlider [data-testid="stThumbValue"],
.stSlider [data-testid="stTickBar"] * {
color: var(--txt-primary) !important;
}
/* ── Inline style overrides (controlled by token vars) ── */
[style*="color:#888"], [style*="color: #888"] { color: var(--txt-muted) !important; }
[style*="color:#B0B0C0"],[style*="color: #B0B0C0"]{ color: var(--txt-secondary) !important; }
[style*="color:#E0E0E0"],[style*="color: #E0E0E0"]{ color: var(--txt-table) !important; }
[style*="color:#F0F0F0"],[style*="color: #F0F0F0"]{ color: var(--txt-primary) !important; }
[style*="color:#666"], [style*="color: #666"] { color: var(--txt-sb-footer) !important; }
[style*="color:#555"], [style*="color: #555"] { color: var(--txt-muted) !important; }
[style*="border-color:#2D3142"],[style*="border-color: #2D3142"]{ border-color: var(--border) !important; }
"""
# ── Inject theme tokens + base CSS ─────────────────────────────────────────
st.markdown(f'<style>\n{_theme_tokens}\n\n{_BASE_CSS}\n</style>', unsafe_allow_html=True)
# ── Sync session state ─────────────────────────────────────────────────────
st.session_state.theme = _effective_theme
# ── Chart color theme helper ───────────────────────────────────────────────
def chart_theme():
"""Plotly theme dictionary sourced from the same CSS tokens."""
tokens = _DARK_TOKENS if _effective_theme == 'dark' else _LIGHT_TOKENS
return {
'font': tokens['txt-table'],
'grid': tokens['border'],
'axis': tokens['txt-muted'],
'legend': tokens['txt-table'],
'pie_line': tokens['bg-chart'],
}
CT = chart_theme()
# ══════════════════════════════════════════════════════════════════════════════
# DATA PATHS
# ══════════════════════════════════════════════════════════════════════════════
BASE = Path(__file__).parent.resolve()
MEMBER_META = BASE / 'member_cluster_metadata.json'
GUEST_META = BASE / 'guest_cluster_metadata.json'
MEMBER_RULES = BASE / 'df_rules_member.parquet'
GUEST_RULES = BASE / 'df_rules_guest.parquet'
MEMBER_SEG = BASE / 'df_member_with_segments.parquet'
GUEST_SEG = BASE / 'df_guest_with_segments.parquet'
MENU_DATA = BASE / 'menu_cleaned.parquet'
FC_HWR = BASE / 'df_forecast_90days_HWR-XGB.parquet'
FC_PROPHET = BASE / 'df_forecast_90days_Prophet-XGB.parquet'
FC_SARIMA = BASE / 'df_forecast_90days_SARIMA-XGB.parquet'
TRANS_FEATURES = BASE / 'df_transaction_features.parquet'
# ══════════════════════════════════════════════════════════════════════════════
# HELPER: LOADERS
# ══════════════════════════════════════════════════════════════════════════════
@st.cache_data
def load_json(path):
# Robust loader: when JSON file is missing on the deployment host, return empty dict
try:
if not Path(path).exists():
msg = f"Optional JSON file '{Path(path).name}' not found; continuing with empty defaults."
try:
st.warning(msg)
except Exception:
pass
return {}
with open(path, 'r', encoding='utf-8') as f:
return json.load(f)
except json.JSONDecodeError as e:
try:
st.error(f"Failed to parse JSON file {Path(path).name}: {e}")
except Exception:
pass
return {}
except Exception as e:
try:
st.exception(e)
except Exception:
pass
return {}
@st.cache_data
def load_parquet(path):
"""Read parquet, handle categorical type issues."""
import pyarrow.parquet as pq
try:
return pd.read_parquet(path)
except TypeError:
# If categorical dtype fails, read with pyarrow directly
tbl = pq.read_table(str(path))
return tbl.to_pandas()
@st.cache_data
def load_forecast(path):
"""Load forecast parquet safely."""
import pyarrow.parquet as pq
tbl = pq.read_table(str(path))
return tbl.to_pandas()
@st.cache_data
def load_segment_counts(path, col='segment_name'):
import pyarrow.parquet as pq
tbl = pq.read_table(str(path), columns=[col])
from collections import Counter
counts = Counter(tbl.column(col).to_pylist())
return pd.DataFrame([
{'segment': k, 'count': v, 'pct': round(v / len(tbl) * 100, 1)}
for k, v in sorted(counts.items(), key=lambda x: -x[1])
])
@st.cache_data
def load_menu():
# Try the cleaned menu first; if missing, fall back to raw `menu_items.parquet` if available.
ALT_MENU = BASE / 'menu_items.parquet'
try:
if MENU_DATA.exists():
return pd.read_parquet(MENU_DATA)
# Fallback: use raw menu items file if present
if ALT_MENU.exists():
msg = (
f"File '{MENU_DATA.name}' not found; falling back to '{ALT_MENU.name}'.\n"
"Consider adding a cleaned menu file to the repository for consistent results."
)
try:
st.warning(msg)
except Exception:
pass
return pd.read_parquet(ALT_MENU)
# Neither file exists — surface a clear error for logs/UI
msg = (
f"Required data file '{MENU_DATA.name}' not found in application directory, and fallback '{ALT_MENU.name}' is also missing. "
"Please add one of these files to the repository or update the path so the app can access it."
)
try:
st.error(msg)
except Exception:
pass
raise FileNotFoundError(msg)
except Exception as e:
try:
st.exception(e)
except Exception:
pass
raise
@st.cache_data
def load_transaction_sample():
"""Load a sample of transaction features for avg calculations."""
import pyarrow.parquet as pq
# If the parquet file is missing on the host, return an empty dataframe
if not TRANS_FEATURES.exists():
try:
st.warning(f"Optional data file '{TRANS_FEATURES.name}' not found; using fallback sample.")
except Exception:
pass
return pd.DataFrame(columns=['final_amount', 'basket_size', 'discount_applied'])
try:
tbl = pq.read_table(str(TRANS_FEATURES), columns=['final_amount', 'basket_size', 'discount_applied'])
# Take a representative sample
sample = tbl.slice(0, 500000)
return sample.to_pandas()
except Exception as e:
try:
st.warning(f"Failed to read '{TRANS_FEATURES.name}': {e}. Using fallback empty sample.")
except Exception:
pass
return pd.DataFrame(columns=['final_amount', 'basket_size', 'discount_applied'])
@st.cache_data
def load_historical_daily():
"""Daily transaction counts + revenue aggregated by city (2023-07 to 2025-06)."""
import pyarrow.parquet as pq
# If the transactions features parquet is missing, return empty dataframe
if not TRANS_FEATURES.exists():
try:
st.warning(f"Optional data file '{TRANS_FEATURES.name}' not found; returning empty daily history.")
except Exception:
pass
return pd.DataFrame(columns=['date', 'city', 'total_transactions', 'total_revenue'])
try:
tbl = pq.read_table(str(TRANS_FEATURES), columns=['city', 'created_at', 'final_amount'])
df = tbl.to_pandas()
df['date'] = pd.to_datetime(df['created_at']).dt.normalize()
daily = df.groupby(['date', 'city'], as_index=False).agg(
total_transactions=('final_amount', 'count'),
total_revenue=('final_amount', 'sum'),
)
daily = daily.sort_values(['date', 'city']).reset_index(drop=True)
return daily
except Exception as e:
try:
st.warning(f"Failed to read '{TRANS_FEATURES.name}' for historical daily: {e}. Returning empty daily history.")
except Exception:
pass
return pd.DataFrame(columns=['date', 'city', 'total_transactions', 'total_revenue'])
# ══════════════════════════════════════════════════════════════════════════════
# FINANCIAL ENGINE (Ref: 00-Cogs)
# ══════════════════════════════════════════════════════════════════════════════
class FinancialEngine:
"""
Calculates key financial metrics per transaction and per bundle.
Based on menu-level pricing with estimated cost structures.
"""
# Typical coffee shop cost assumptions (as fraction of retail)
COGS_RATIO = 0.32 # Cost of Goods Sold (raw materials ~32%)
OPEX_PER_TRANSACTION = 2.50 # Fixed operating cost per transaction (labour, utilities, rent分摊)
def __init__(self, menu_df):
self.menu = menu_df.set_index('item_name')['price'].to_dict()
self.avg_price = menu_df['price'].mean()
def get_cogs(self, item_name):
"""Estimate raw material cost for an item."""
price = self.menu.get(item_name, self.avg_price)
return price * self.COGS_RATIO
def get_operating_cost(self):
"""Per-transaction operating cost (labour, rent, utilities)."""
return self.OPEX_PER_TRANSACTION
def get_net_margin(self, item_name, discount=0.0):
"""
Net Profit Margin = Price - COGS - OpCost - Discount
Returns both absolute margin and margin ratio.
"""
price = self.menu.get(item_name, self.avg_price)
cogs = price * self.COGS_RATIO
op_cost = self.OPEX_PER_TRANSACTION
discount_abs = price * discount
net = price - cogs - op_cost - discount_abs
return {
'item': item_name,
'price': price,
'cogs': cogs,
'operating_cost': op_cost,
'discount': discount_abs,
'net_profit': net,
'net_margin_pct': (net / price * 100) if price > 0 else 0,
}
def get_bundle_margin(self, items, discount=0.0):
"""Calculate combined margin for a bundle of items."""
total = {'price': 0, 'cogs': 0, 'op_cost': 0, 'discount': 0, 'net': 0}
for item in items:
m = self.get_net_margin(item.strip(), discount)
total['price'] += m['price']
total['cogs'] += m['cogs']
total['op_cost'] += m['operating_cost']
total['discount'] += m['discount']
total['net'] += m['net_profit']
total['margin_pct'] = (total['net'] / total['price'] * 100) if total['price'] > 0 else 0
return total
def price_sensitivity(self, item_name, pct_change):
"""Return new margin if price changes by pct_change (e.g., 0.10 = +10%)."""
base = self.get_net_margin(item_name)
new_price = base['price'] * (1 + pct_change)
# COGS stays same (raw material cost doesn't change with retail price)
new_net = new_price - base['cogs'] - base['operating_cost'] - base['discount']
return {
'original_price': base['price'],
'new_price': new_price,
'original_net': base['net_profit'],
'new_net': new_net,
'margin_impact': new_net - base['net_profit'],
}
# ══════════════════════════════════════════════════════════════════════════════
# FORECAST ENGINE
# ══════════════════════════════════════════════════════════════════════════════
class ForecastEngine:
"""
Wraps both forecast models with business-friendly labels.
HWR-XGB -> 'Conservative Growth' (stable, trend-following)
Prophet-XGB -> 'Aggressive Growth' (captures more inflection, higher upside)
"""
LABELS = {
'HWR-XGB': 'Conservative Growth',
'Prophet-XGB': 'Aggressive Growth',
'SARIMA-XGB': 'Balanced Growth',
}
def __init__(self):
# Forecast files are optional in dev environments.
# If a parquet is missing, the app should still run with the remaining model(s).
models = []
# Prefer model-specific forecasts but allow a generic 90-day forecast as fallback
GENERIC_FC = BASE / 'df_forecast_90days.parquet'
generic_fc = None
if GENERIC_FC.exists():
try:
generic_fc = load_forecast(GENERIC_FC)
except Exception:
generic_fc = None
try:
conservative = load_forecast(FC_HWR)
conservative['scenario'] = self.LABELS.get('HWR-XGB', 'Conservative Growth')
models.append(conservative)
except FileNotFoundError:
if generic_fc is not None:
c = generic_fc.copy()
c['scenario'] = self.LABELS.get('HWR-XGB', 'Conservative Growth')
models.append(c)
else:
st.warning(f"Forecast file missing: {FC_HWR.name}. Using only Prophet model.")
except Exception as e:
st.warning(f"Failed to load HWR forecast ({FC_HWR.name}): {e}. Using only Prophet model.")
try:
aggressive = load_forecast(FC_PROPHET)
aggressive['scenario'] = self.LABELS.get('Prophet-XGB', 'Aggressive Growth')
models.append(aggressive)
except FileNotFoundError:
if generic_fc is not None:
a = generic_fc.copy()
a['scenario'] = self.LABELS.get('Prophet-XGB', 'Aggressive Growth')
models.append(a)
else:
st.warning(f"Forecast file missing: {FC_PROPHET.name}. Using only HWR model.")
except Exception as e:
st.warning(f"Failed to load Prophet forecast ({FC_PROPHET.name}): {e}. Using only HWR model.")
if not models:
# Hard fallback: allow app to render without forecast.
self.full = pd.DataFrame(columns=['created_at', 'branch', 'total_transactions', 'scenario'])
self.avg_transaction_value = 0.0
return
self.full = pd.concat(models, ignore_index=True)
if 'created_at' in self.full.columns:
self.full['created_at'] = pd.to_datetime(self.full['created_at'])
# Derive average transaction value from historical data
try:
tx_sample = load_transaction_sample()
if tx_sample is None or tx_sample.empty or 'final_amount' not in tx_sample.columns:
raise FileNotFoundError('transaction sample not available')
avg_val = tx_sample['final_amount'].mean()
if pd.isna(avg_val):
raise ValueError('computed avg is NaN')
self.avg_transaction_value = float(avg_val)
except Exception:
# Fallback: use menu average price from FinancialEngine if available
try:
self.avg_transaction_value = float(fin_engine.avg_price)
try:
st.warning('Using menu average price as fallback for average transaction value.')
except Exception:
pass
except Exception:
self.avg_transaction_value = 0.0
try:
st.warning('Could not derive average transaction value; defaulting to 0.0.')
except Exception:
pass
def get_profit_forecast(self, margin_pct=0.25):
"""
Convert transaction forecasts to profit forecasts.
margin_pct: estimated net profit margin on each transaction.
Uses FinancialEngine's typical margin per transaction.
"""
df = self.full.copy()
# Revenue forecast
df['projected_revenue'] = df['total_transactions'] * self.avg_transaction_value
# Profit forecast (net of all costs)
df['projected_profit'] = df['projected_revenue'] * margin_pct
return df
def get_bundle_impact_forecast(self, bundle_name, margin_pct=0.25, boost_factor=0.08):
"""
Simulate the projected profit increase if a specific bundle is launched.
boost_factor: estimated % increase in transactions due to bundle promo.
"""
df = self.get_profit_forecast(margin_pct)
df['bundle_boost'] = df['total_transactions'] * boost_factor
df['boosted_transactions'] = df['total_transactions'] + df['bundle_boost']
df['boosted_profit'] = df['boosted_transactions'] * self.avg_transaction_value * margin_pct
df['profit_increase'] = df['boosted_profit'] - df['projected_profit']
df['bundle_name'] = bundle_name
return df
# ══════════════════════════════════════════════════════════════════════════════
# BUSINESS LANGUAGE MAP
# ══════════════════════════════════════════════════════════════════════════════
BUSINESS_COLUMNS = {
'support': 'Popularity Score',
'confidence': 'Projected Success Rate',
'lift': 'Cross-Sell Potential',
'antecedents': 'Product A',
'consequents': 'Product B',
'leverage': 'Upsell Opportunity',
'conviction': 'Dependency Strength',
}
SEGMENT_DESCRIPTIONS = {
'At Risk Regulars': 'Loyal customers who haven\'t visited recently — reactivation opportunity',
'New Occasional': 'New customers with low visit frequency — nurture into regulars',
'Hibernating': 'Long-absent customers — re-engagement campaign target',
'Champions': 'Best customers — highest frequency & spending — VIP treatment',
'Big Spender': 'High-value guests with large basket sizes',
'Weekend Visitor': 'Weekend-only traffic — target with weekday promotions',
'Deal Hunter': 'Discount-sensitive — coupon & voucher-driven purchases',
'Quick Buy': 'Single-item, fast transactions — impulse buy opportunities',
}
# ══════════════════════════════════════════════════════════════════════════════
# SESSION STATE INIT
# ══════════════════════════════════════════════════════════════════════════════
if 'selected_bundle' not in st.session_state:
st.session_state.selected_bundle = None
if 'bundle_source' not in st.session_state:
st.session_state.bundle_source = None
if 'scenario_params' not in st.session_state:
st.session_state.scenario_params = {'price_adj': 0.0, 'stock_level': 0.0, 'discount_intensity': 0.0}
if 'forecast_fullscreen' not in st.session_state:
st.session_state.forecast_fullscreen = False
if 'theme' not in st.session_state:
st.session_state.theme = 'dark'
if 'dashboard_lens' not in st.session_state:
st.session_state.dashboard_lens = 'Profit'
# ══════════════════════════════════════════════════════════════════════════════
# LOAD ALL DATA
# ══════════════════════════════════════════════════════════════════════════════
menu_df = load_menu()
fin_engine = FinancialEngine(menu_df)
fc_engine = ForecastEngine()
member_meta = load_json(MEMBER_META)
guest_meta = load_json(GUEST_META)
member_rules = load_parquet(MEMBER_RULES)
guest_rules = load_parquet(GUEST_RULES)
member_seg_counts = load_segment_counts(MEMBER_SEG)
guest_seg_counts = load_segment_counts(GUEST_SEG)
# ── Gemini AI Analyst ─────────────────────────────────────────────────────────
gemini = GroqAnalyst()
# ── Color palette for dark mode ──────────────────────────────────────────────
DARK_COLORS = [
'#6C5CE7', '#00B894', '#FDAA5E', '#E17055',
'#0984E3', '#A29BFE', '#55EFC4', '#FAB1A0',
'#74B9FF', '#81ECEC', '#FDCB6E', '#E17055',
]
# ══════════════════════════════════════════════════════════════════════════════
# SIDEBAR REDESIGN — Modern SaaS Pattern
# ══════════════════════════════════════════════════════════════════════════════
# ── Navigation tabs (global scope for use in router) ─────────────────────────
NAV_TABS = [
'📊 Overview',
'👥 Customer Segments',
'🛒 Bundle Intelligence',
'📈 Forecast & Profit',
'🎯 Strategic Explorer',
'🤖 AI Analyst',
]
# ── Sidebar CSS Enhancements ────────────────────────────────────────────────
st.markdown("""
<style>
/* ── Sidebar Container Tweaks ── */
section[data-testid="stSidebar"] {
width: 280px !important;
}
/* ── Section Headers (Filters, Settings) ── */
.sidebar-section-header {
font-size: 0.75rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.5px;
color: var(--txt-secondary);
margin-top: 20px;
margin-bottom: 12px;
padding-left: 4px;
display: block;
}
/* ── Navigation Items (Modern SaaS Active State) ── */
.sidebar-nav-item {
display: block;
padding: 10px 12px;
margin: 4px 0;
border-radius: 8px;
font-size: 14px;
color: var(--txt-secondary);
cursor: pointer;
transition: all 0.2s ease;
border-left: 3px solid transparent;
position: relative;
}
.sidebar-nav-item:hover {
background-color: var(--bg-radio-sel);
color: var(--txt-primary);
border-left-color: #888;
}
.sidebar-nav-item.active {
background-color: var(--bg-radio-sel);
color: var(--txt-primary);
border-left-color: #00B894;
font-weight: 600;
}
/* ── Filter Section Container ── */
.sidebar-filters {
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: 10px;
padding: 12px;
margin: 8px 0;
}
.sidebar-filter-item {
margin-bottom: 12px;
}
.sidebar-filter-item:last-child {
margin-bottom: 0;
}
.sidebar-filter-label {
font-size: 0.8rem;
color: var(--txt-secondary);
font-weight: 600;
margin-bottom: 6px;
display: block;
}
/* ── Branding Compact ── */
.sidebar-branding {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 16px;
padding: 8px 0;
border-bottom: 1px solid var(--border);
}
.sidebar-branding-icon {
font-size: 28px;
line-height: 1;
}
.sidebar-branding-text {
flex: 1;
}
.sidebar-branding-name {
font-size: 0.95rem;
font-weight: 700;
color: var(--txt-primary);
margin: 0;
line-height: 1.2;
}
.sidebar-branding-tagline {
font-size: 0.7rem;
color: var(--txt-secondary);
margin: 2px 0 0 0;
}
/* ── Divider (minimal) ── */
.sidebar-divider {
border: none;
height: 1px;
background-color: var(--border);
margin: 16px 0;
}
/* ── Settings Section (bottom) ── */
.sidebar-settings {
margin-top: auto;
padding-top: 16px;
border-top: 1px solid var(--border);
}
.sidebar-footer-text {
font-size: 0.65rem;
color: var(--txt-muted);
text-align: center;
margin-top: 16px;
padding-top: 8px;
}
</style>
""", unsafe_allow_html=True)
# ── Helper Function: Render Branding Section ────────────────────────────────
def render_branding():
"""Compact branding section at top of sidebar."""
st.sidebar.markdown("""
<div class="sidebar-branding">
<div class="sidebar-branding-icon">☕</div>
<div class="sidebar-branding-text">
<div class="sidebar-branding-name">G Coffee Shop</div>
<div class="sidebar-branding-tagline">Strategic Intelligence</div>
</div>
</div>
""", unsafe_allow_html=True)
# ── Helper Function: Render Navigation ──────────────────────────────────────
def render_navigation():
"""Primary navigation menu with active state styling."""
st.sidebar.markdown('<h3 style="font-size:0.8rem;color:var(--txt-muted);text-transform:uppercase;margin:0 0 8px 0;font-weight:600;">Navigation</h3>', unsafe_allow_html=True)
# Use radio for navigation (Streamlit's built-in active state)
selected_tab = st.sidebar.radio(
'nav_menu',
NAV_TABS,
index=0,
label_visibility='collapsed',
key='nav_selection',
)
return selected_tab
# ── Helper Function: Render Filters ─────────────────────────────────────────
def render_filters():
"""Grouped filters section with consistent styling."""
st.sidebar.markdown('<div class="sidebar-section-header">🔍 Filters</div>', unsafe_allow_html=True)
with st.sidebar:
# Branch Filter
_branches = []
try:
_fc_path = BASE / 'df_forecast_90days.parquet'
if _fc_path.exists():
_tmp = pd.read_parquet(_fc_path)
if 'branch' in _tmp.columns:
_branches = sorted(_tmp['branch'].dropna().unique().tolist())
except Exception:
_branches = []
if 'branch_filter' not in st.session_state:
st.session_state['branch_filter'] = _branches
with st.container():
st.markdown('<label style="font-size:0.8rem;color:var(--txt-secondary);font-weight:600;display:block;margin-bottom:6px;">Branch</label>', unsafe_allow_html=True)
sel_branches = st.multiselect(
'branch_label',
options=_branches,
default=st.session_state.get('branch_filter', _branches),
key='branch_filter',
label_visibility='collapsed',
)
st.markdown('<div style="margin-bottom:12px;"></div>', unsafe_allow_html=True)