-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
3598 lines (3186 loc) · 164 KB
/
Copy pathmain.py
File metadata and controls
3598 lines (3186 loc) · 164 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
# ======================================================================================
# DART — COMPLETE SINGLE-FILE STREAMLIT APPLICATION
# Includes the dashboard, Email Agent UI, embedded example automation/template,
# condition evaluation, change detection, HTML/text email generation, and SMTP delivery.
# No separate Python helper modules, JSON templates, or HTML template files are required.
# Runtime automation settings and baseline snapshots are created automatically under
# EMAIL_AGENT_DIR so alerts can persist across application runs.
# ======================================================================================
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
import os
import json
import re
import ssl
import smtplib
import hashlib
import html
import uuid
from datetime import datetime, timezone
from email.message import EmailMessage
from pathlib import Path
# ======================================================================================
# PAGE CONFIG
# ======================================================================================
st.set_page_config(
page_title="DART — CMS Data Assurance Reconciliation Tracker",
page_icon="🎯",
layout="wide",
initial_sidebar_state="expanded",
)
# ======================================================================================
# SYSTEM LABELS (the two systems being compared)
# ======================================================================================
SYS_A = "NCH/CVM" # System A (National Claims History / CWF Version)
SYS_B = "Shared Systems" # System B (SS – FISS / MCS / VMS)
# ======================================================================================
# THEME / PALETTE
# ======================================================================================
PRIMARY = "#8B6A00" # gold
ACCENT = "#12805C" # green (good)
WARN = "#F59E0B" # amber
DANGER = "#DC2626" # red (bad)
PURPLE = "#7C3AED"
SLATE = "#64748B"
SYS_A_COLOR = "#8B6A00" # gold for System A
SYS_B_COLOR = "#C9920A" # amber-gold for System B
CLASS_COLORS = {
"Match": "#12805C",
"Different": "#F59E0B",
"Missing": "#DC2626",
"View is not in the MDCR VDM": "#7C3AED",
"Table is empty": "#94A3B8",
"Unspecified": "#CBD5E1",
}
DISP_COLORS = {
"Good": "#12805C",
"Action needed": "#DC2626",
"Not analyzed": "#F59E0B",
"Table is empty": "#94A3B8",
"Other": "#64748B",
}
SEQ_BLUE = px.colors.sequential.Blues
# ======================================================================================
# USE-CASE KNOWLEDGE BASE (from the SSDS analysis presentation)
# Maps each data sub-classification to the business meaning + recommended action.
# ======================================================================================
USE_CASES = {
"Data matches / columns match": {
"category": "Match",
"severity": "good",
"title": "Perfect Match — Data & Columns Align",
"desc": (
f"The {SYS_A} and {SYS_B} columns hold identical data. This is the ideal "
"situation between the two claim streams."
),
"action": "No action needed.",
},
"Different format-SS has more info": {
"category": "Match",
"severity": "good",
"title": "Acceptable Match — SS Has More Information",
"desc": (
f"The {SYS_B} version contains more information than the {SYS_A} version. "
"Counted as an acceptable match because it reflects richer data in SS "
"(a bonus of using Shared Systems)."
),
"action": "No action needed — SS provides bonus detail.",
},
"NCH is missing": {
"category": "Match",
"severity": "good",
"title": "Acceptable Match — NCH Missing, SS Has More Data",
"desc": (
f"{SYS_A} is missing data that {SYS_B} contains for some streams. Still an "
"acceptable match since more data is reflected in SS. Null CD columns should "
"contain '~' per IDR standards."
),
"action": "No action needed — SS is more complete.",
},
"Zeros, tilde, blanks, null": {
"category": "Match",
"severity": "warn",
"title": "Match — But Values Are Zeros / Blanks / Null / Tildes",
"desc": (
"Columns match, but the data is always zeros, blanks, null, or tildes ('~'). "
"Considered an acceptable match (all are valid null values), yet a populated "
"'~' in '_CD' columns can indicate an ETL issue."
),
"action": "Monitor — potential ETL indicator on _CD columns.",
},
"NCH and SS have different values": {
"category": "Different",
"severity": "danger",
"title": "Different Values — Reconciliation Required",
"desc": (
f"The data in {SYS_A} and {SYS_B} differ and analysis determined that "
"reconciliation between the two feeds is necessary (e.g. columns not "
"populated for some streams, or differing date formats)."
),
"action": "Reconcile the NCH ↔ SS feeds.",
},
"Do Nothing. SS date is more accurate.": {
"category": "Different",
"severity": "good",
"title": "Different — SS Is More Accurate (No Action)",
"desc": (
f"Values differ, but {SYS_B} data is more accurate than the estimated "
f"{SYS_A} data. NCH estimates the value while SS contains the actual value."
),
"action": "No action needed — SS is authoritative.",
},
"Not expected to match": {
"category": "Different",
"severity": "good",
"title": "Different — Not Expected to Match",
"desc": (
"Analysis determined the difference is acceptable because these IDR-derived "
"columns are neither expected nor required to match."
),
"action": "No action needed — mismatch is by design.",
},
"Data in different column": {
"category": "Missing",
"severity": "warn",
"title": "Missing — Data Lives in a Different Column",
"desc": (
f"The {SYS_A} and {SYS_B} concepts match, but the data resides in a different "
"column. The SS maintainer would need to harmonize so NCH and SS report the "
"same way."
),
"action": "SS to harmonize column placement.",
},
"Scheduled payment concept does not apply in SS": {
"category": "Missing",
"severity": "good",
"title": "Missing — Concept Does Not Apply in SS",
"desc": (
"Acceptable: NCH estimates the scheduled payment date because CWF does not "
"know the real payment date at IDR load time, whereas SS holds the actual "
"payment date. The concept simply does not apply to SS."
),
"action": "No action needed — concept not applicable.",
},
"SS is missing this data": {
"category": "Missing",
"severity": "danger",
"title": "Missing — SS Is Not Sending This Data",
"desc": (
f"Analysis determined the {SYS_B} stream is not sending this information to "
"the IDR."
),
"action": "Have SS send the data, or confirm IDR users need it.",
},
"Data not available": {
"category": "Missing",
"severity": "warn",
"title": "Missing — Data Not Available",
"desc": "The data is not available in the source for comparison.",
"action": "Investigate source availability.",
},
"Table is empty": {
"category": "Table is empty",
"severity": "warn",
"title": "Table Is Empty",
"desc": "The table has only default values for every target column.",
"action": "Confirm whether the table should be populated.",
},
"Unspecified": {
"category": "Unspecified",
"severity": "warn",
"title": "Unspecified Sub-Classification",
"desc": "No sub-classification was recorded for these fields.",
"action": "Review and classify.",
},
}
# ======================================================================================
# GLOBAL STYLING (CSS)
# ======================================================================================
st.markdown(
"""
<style>
/* ---- App background & fonts ---- */
.stApp { background-color: #FDFCF8; }
html, body, [class*="css"] { font-family: 'Segoe UI', 'Inter', sans-serif; }
/* ---- Hero banner ---- */
/* Text block inside the hero; container provides the gradient background */
.hero {
background: transparent;
padding: 26px 34px 12px 34px; border-radius: 0; color: #ffffff;
box-shadow: none; margin-bottom: 0;
}
.hero h1 { color:#ffffff; margin:0; font-size:2.0rem; font-weight:700; letter-spacing:-0.02em; }
.hero p { color:#FFF8DC; margin:6px 0 0 0; font-size:1.02rem; max-width:100%; overflow-wrap:anywhere; }
.hero .tagpill {
display:inline-block; background:rgba(255,255,255,0.18); color:#fff;
padding:3px 12px; border-radius:20px; font-size:0.78rem; font-weight:600;
margin-top:12px; margin-right:8px; letter-spacing:0.03em;
}
/* The Streamlit container block that wraps both text and nav dropdowns */
[data-testid="stVerticalBlock"]:has(
> .element-container > [data-testid="stMarkdown"] .hero-anchor
) {
background: linear-gradient(135deg, #6B4E00 0%, #C9920A 100%);
border-radius: 16px;
box-shadow: 0 6px 20px rgba(107,78,0,0.30);
padding: 0 20px 24px 20px;
margin-bottom: 8px;
}
/* Expanders inside the hero container */
[data-testid="stVerticalBlock"]:has(
> .element-container > [data-testid="stMarkdown"] .hero-anchor
) [data-testid="stExpander"] {
background: rgba(255,255,255,0.16) !important;
border: 1px solid rgba(255,255,255,0.28) !important;
border-radius: 14px !important;
backdrop-filter: blur(8px);
box-shadow: 0 6px 16px rgba(2,6,23,0.12) !important;
}
/* Closed expander header: white text and icon on the gold background */
[data-testid="stVerticalBlock"]:has(
> .element-container > [data-testid="stMarkdown"] .hero-anchor
) [data-testid="stExpander"] details:not([open]) > summary {
background-color: transparent !important;
color: #ffffff !important;
border-radius: 14px !important;
}
[data-testid="stVerticalBlock"]:has(
> .element-container > [data-testid="stMarkdown"] .hero-anchor
) [data-testid="stExpander"] details:not([open]) > summary p,
[data-testid="stVerticalBlock"]:has(
> .element-container > [data-testid="stMarkdown"] .hero-anchor
) [data-testid="stExpander"] details:not([open]) > summary span,
[data-testid="stVerticalBlock"]:has(
> .element-container > [data-testid="stMarkdown"] .hero-anchor
) [data-testid="stExpander"] details:not([open]) > summary div,
[data-testid="stVerticalBlock"]:has(
> .element-container > [data-testid="stMarkdown"] .hero-anchor
) [data-testid="stExpander"] details:not([open]) > summary svg,
[data-testid="stVerticalBlock"]:has(
> .element-container > [data-testid="stMarkdown"] .hero-anchor
) [data-testid="stExpander"] details:not([open])
[data-testid="stExpanderToggleIcon"] {
color: #ffffff !important;
fill: #ffffff !important;
stroke: #ffffff !important;
font-weight: 700 !important;
opacity: 1 !important;
}
[data-testid="stVerticalBlock"]:has(
> .element-container > [data-testid="stMarkdown"] .hero-anchor
) [data-testid="stExpander"] details:not([open]) > summary:hover {
background-color: rgba(255,255,255,0.12) !important;
}
/* Open expander header: dark text and icon on Streamlit's white header */
[data-testid="stVerticalBlock"]:has(
> .element-container > [data-testid="stMarkdown"] .hero-anchor
) [data-testid="stExpander"] details[open] > summary {
background-color: rgba(255,255,255,0.97) !important;
color: #0F172A !important;
border-radius: 13px 13px 0 0 !important;
}
[data-testid="stVerticalBlock"]:has(
> .element-container > [data-testid="stMarkdown"] .hero-anchor
) [data-testid="stExpander"] details[open] > summary p,
[data-testid="stVerticalBlock"]:has(
> .element-container > [data-testid="stMarkdown"] .hero-anchor
) [data-testid="stExpander"] details[open] > summary span,
[data-testid="stVerticalBlock"]:has(
> .element-container > [data-testid="stMarkdown"] .hero-anchor
) [data-testid="stExpander"] details[open] > summary div,
[data-testid="stVerticalBlock"]:has(
> .element-container > [data-testid="stMarkdown"] .hero-anchor
) [data-testid="stExpander"] details[open] > summary svg,
[data-testid="stVerticalBlock"]:has(
> .element-container > [data-testid="stMarkdown"] .hero-anchor
) [data-testid="stExpander"] details[open]
[data-testid="stExpanderToggleIcon"] {
color: #0F172A !important;
fill: #0F172A !important;
stroke: #0F172A !important;
font-weight: 700 !important;
opacity: 1 !important;
}
/* Preserve readable colors while an open header is hovered or focused */
[data-testid="stVerticalBlock"]:has(
> .element-container > [data-testid="stMarkdown"] .hero-anchor
) [data-testid="stExpander"] details[open] > summary:hover,
[data-testid="stVerticalBlock"]:has(
> .element-container > [data-testid="stMarkdown"] .hero-anchor
) [data-testid="stExpander"] details[open] > summary:focus,
[data-testid="stVerticalBlock"]:has(
> .element-container > [data-testid="stMarkdown"] .hero-anchor
) [data-testid="stExpander"] details[open] > summary:focus-visible {
background-color: #FFF8DC !important;
color: #0F172A !important;
}
[data-testid="stVerticalBlock"]:has(
> .element-container > [data-testid="stMarkdown"] .hero-anchor
) [data-testid="stExpander"] details[open] > summary:hover *,
[data-testid="stVerticalBlock"]:has(
> .element-container > [data-testid="stMarkdown"] .hero-anchor
) [data-testid="stExpander"] details[open] > summary:focus *,
[data-testid="stVerticalBlock"]:has(
> .element-container > [data-testid="stMarkdown"] .hero-anchor
) [data-testid="stExpander"] details[open] > summary:focus-visible * {
color: #0F172A !important;
fill: #0F172A !important;
stroke: #0F172A !important;
}
/* Nav buttons inside the hero */
[data-testid="stVerticalBlock"]:has(
> .element-container > [data-testid="stMarkdown"] .hero-anchor
) .stButton > button {
width:100%; justify-content:center; margin:4px 0; border-radius:10px;
background: rgba(255,255,255,0.95); color:#0f172a;
border: 1px solid rgba(255,255,255,0.8);
font-weight:700; transition: all 0.18s ease;
}
[data-testid="stVerticalBlock"]:has(
> .element-container > [data-testid="stMarkdown"] .hero-anchor
) .stButton > button[kind="primary"] {
background: linear-gradient(135deg, #8B6A00 0%, #C9920A 100%) !important;
color:#ffffff !important; border-color:#8B6A00 !important;
box-shadow:0 0 0 2px rgba(255,255,255,0.25) inset;
}
/* ---- KPI cards ---- */
.kpi-card {
background:#ffffff; border-radius:14px; padding:16px 20px;
box-shadow:0 2px 10px rgba(15,23,42,0.06); border:1px solid #eef1f5;
margin-bottom:6px; height:100%; overflow-wrap:anywhere; word-break:break-word;
}
.kpi-label { font-size:0.74rem; color:#64748b; text-transform:uppercase; letter-spacing:0.06em; font-weight:700; }
.kpi-value { font-size:1.85rem; font-weight:750; color:#0f172a; margin-top:4px; line-height:1.1; }
.kpi-sub { font-size:0.82rem; color:#64748b; margin-top:4px; }
/* ---- Section headers ---- */
.section-title { font-size:1.25rem; font-weight:700; color:#0f172a; margin:8px 0 2px 0; }
.section-sub { font-size:0.9rem; color:#64748b; margin-bottom:12px; }
/* ---- Insight callout ---- */
.insight {
background:#ffffff; border-left:5px solid #8B6A00; border-radius:8px;
padding:12px 16px; margin:8px 0; box-shadow:0 1px 4px rgba(15,23,42,0.05);
color:#0f172a; font-size:0.92rem;
}
.insight.good { border-left-color:#12805C; }
.insight.warn { border-left-color:#F59E0B; }
.insight.danger { border-left-color:#DC2626; }
/* ---- AI agent bubble ---- */
.ai-bubble {
background:#ffffff; border:1px solid #e6ebf3; border-radius:14px;
padding:16px 18px 16px 54px; margin:10px 0; position:relative;
box-shadow:0 2px 10px rgba(15,23,42,0.06); color:#0f172a; font-size:0.95rem;
line-height:1.5;
}
.ai-bubble:before {
content:"🤖"; position:absolute; left:14px; top:14px; font-size:1.4rem;
background:linear-gradient(135deg,#8B6A00,#C9920A); -webkit-background-clip:text;
}
.ai-bubble.warn { border-left:5px solid #F59E0B; }
.ai-bubble.danger { border-left:5px solid #DC2626; }
.ai-bubble.good { border-left:5px solid #12805C; }
.ai-bubble b { color:#6B4E00; }
/* ---- Use-case card ---- */
.uc-card {
background:#ffffff; border-radius:14px; padding:16px 18px; margin-bottom:12px;
box-shadow:0 2px 10px rgba(15,23,42,0.06); border:1px solid #eef1f5;
}
.uc-badge {
display:inline-block; padding:2px 10px; border-radius:20px; font-size:0.72rem;
font-weight:700; color:#fff; letter-spacing:0.03em; margin-left:6px;
}
.uc-title { font-size:1.02rem; font-weight:700; color:#0f172a; }
.uc-desc { font-size:0.9rem; color:#334155; margin-top:6px; }
.uc-action{ font-size:0.86rem; color:#8B6A00; font-weight:600; margin-top:8px; }
/* ---- Methodology card ---- */
.info-card {
background:#ffffff; border:1px solid #eef1f5; border-radius:14px;
padding:16px 18px; margin-bottom:12px; box-shadow:0 2px 10px rgba(15,23,42,0.06);
overflow-wrap:anywhere; word-break:break-word;
}
.info-card ul { margin:6px 0 0 18px; padding:0; color:#334155; line-height:1.6; }
.info-card li { margin-bottom:4px; }
/* ---- Top navigation ---- */
.top-nav {
display:flex; flex-wrap:wrap; align-items:center; justify-content:space-between; gap:12px;
padding:12px 16px; margin-bottom:12px; border-radius:18px;
background: linear-gradient(135deg, #FFFEF0 0%, #FFF8DC 100%);
border:1px solid #E8D8A0; box-shadow:0 6px 18px rgba(107,78,0,0.08);
}
.nav-brand {
font-size:0.95rem; font-weight:800; letter-spacing:0.06em; text-transform:uppercase;
color:#8B6A00;
}
.nav-actions { display:flex; flex-wrap:wrap; gap:8px; align-items:center; }
.nav-pill {
background:#ffffff; color:#475569; border:1px solid #e6ebf3; border-radius:999px;
font-weight:700; padding:8px 14px; min-width:140px; transition: all 0.2s ease-in-out;
box-shadow:0 1px 3px rgba(15,23,42,0.04);
}
.nav-pill:hover { border-color:#8B6A00; color:#8B6A00; }
.nav-pill.active {
background: linear-gradient(135deg, #8B6A00 0%, #C9920A 100%) !important;
color:#ffffff !important; border-color:#8B6A00 !important; box-shadow:0 6px 16px rgba(139,106,0,0.25);
}
/* ---- Sidebar ---- */
section[data-testid="stSidebar"] { background:#1C1200; }
section[data-testid="stSidebar"] * { color:#e5edf7; }
section[data-testid="stSidebar"] .stMultiSelect label,
section[data-testid="stSidebar"] .stSlider label { color:#cbd8e8 !important; font-weight:600; }
/* ---- Native metric tweak ---- */
div[data-testid="stMetric"] {
background:#ffffff; border:1px solid #eef1f5; border-radius:12px;
padding:14px 16px; box-shadow:0 2px 8px rgba(15,23,42,0.05);
}
footer, #MainMenu { visibility: hidden; }
</style>
""",
unsafe_allow_html=True,
)
# ======================================================================================
# HELPERS
# ======================================================================================
def clean_pct(val):
"""Return a match rate as a fraction in [0, 1] or NaN."""
if val is None:
return np.nan
if isinstance(val, str):
s = val.strip().replace("%", "")
if s == "" or s == "-":
return np.nan
try:
num = float(s)
except ValueError:
return np.nan
else:
try:
num = float(val)
except (ValueError, TypeError):
return np.nan
if pd.isna(num):
return np.nan
if num > 1.5: # stored as a percentage (e.g. 99.9) -> fraction
num = num / 100.0
return num
def normalize_disposition(val):
s = str(val).strip().lower()
if s in ("good",):
return "Good"
if s in ("action needed", "needs action", "action", "m"):
return "Action needed"
if s in ("not analyzed", "not analysed"):
return "Not analyzed"
if s in ("table is empty", "empty"):
return "Table is empty"
return "Other"
def normalize_subclass(val):
s = str(val).strip()
low = s.lower()
if low in ("", "nan", "none"):
return "Unspecified"
if low.startswith("not expected"):
return "Not expected to match"
return s
def normalize_recommendation(val):
s = str(val).strip()
if s == "" or s.lower() in ("nan", "none"):
return "(none)"
# merge trivial case differences
fixups = {
"idr needs to derive": "IDR needs to derive",
"idr to derive": "IDR needs to derive",
}
return fixups.get(s.lower(), s)
def is_blank(series):
s = series.astype(str).str.strip().str.lower()
return s.isin(["", "-", "nan", "none"])
def kpi_card(col, label, value, sub="", accent=PRIMARY):
sub_html = f'<div class="kpi-sub">{sub}</div>' if sub else ""
col.markdown(
f"""
<div class="kpi-card" style="border-top:4px solid {accent};">
<div class="kpi-label">{label}</div>
<div class="kpi-value">{value}</div>
{sub_html}
</div>
""",
unsafe_allow_html=True,
)
def insight(text, kind=""):
st.markdown(f'<div class="insight {kind}">{text}</div>', unsafe_allow_html=True)
def ai_say(text, kind=""):
st.markdown(f'<div class="ai-bubble {kind}">{text}</div>', unsafe_allow_html=True)
def section(title, sub=""):
sub_html = f'<div class="section-sub">{sub}</div>' if sub else ""
st.markdown(f'<div class="section-title">{title}</div>{sub_html}', unsafe_allow_html=True)
def methodology_card(title, bullets, accent=PRIMARY):
bullet_html = "".join(f"<li>{b}</li>" for b in bullets)
st.markdown(
f"""
<div class="info-card" style="border-left:5px solid {accent};">
<div class="section-title" style="margin:0;">{title}</div>
<ul>{bullet_html}</ul>
</div>
""",
unsafe_allow_html=True,
)
def style_fig(fig, height=380):
fig.update_layout(
height=height,
margin=dict(l=10, r=10, t=40, b=10),
paper_bgcolor="rgba(0,0,0,0)",
plot_bgcolor="rgba(0,0,0,0)",
font=dict(family="Segoe UI, sans-serif", color="#0f172a", size=12),
legend=dict(bgcolor="rgba(0,0,0,0)"),
title=dict(font=dict(size=14, color="#0f172a")),
)
fig.update_xaxes(showgrid=True, gridcolor="#e6ebf2", zeroline=False)
fig.update_yaxes(showgrid=True, gridcolor="#e6ebf2", zeroline=False)
return fig
def fmt_int(n):
try:
return f"{int(n):,}"
except (ValueError, TypeError):
return "—"
def claim_weighted_match_rate(df, matched_col="MatchedClaims", unmatched_col="NotMatchedClaims"):
"""Return the claim/event-volume-weighted match rate and its component counts.
This remains available as a secondary diagnostic metric:
total matched / (total matched + total not matched)
It is intentionally not the dashboard's primary "Average Match Rate" because
very high-volume fields can dominate the result.
"""
if df is None or df.empty:
return np.nan, 0, 0, 0
matched = pd.to_numeric(df[matched_col], errors="coerce").fillna(0).sum()
unmatched = pd.to_numeric(df[unmatched_col], errors="coerce").fillna(0).sum()
total = matched + unmatched
rate = (matched / total) if total > 0 else np.nan
return rate, int(matched), int(unmatched), int(total)
def comparable_field_scope(df):
"""Return directly comparable rows with a usable field-level MatchRate.
ClassificationClean = Missing is excluded from the average because those rows
describe absent data, data living in another column, or a concept that does not
apply in Shared Systems. They are important data-quality findings, but they are
not direct value-to-value field comparisons.
"""
if df is None:
return pd.DataFrame()
if df.empty:
return df.copy()
out = df.copy()
if "ClassificationClean" in out.columns:
out = out[out["ClassificationClean"].isin(["Match", "Different"])]
elif "Classification" in out.columns:
cls = out["Classification"].astype(str).str.strip()
out = out[cls.isin(["Match", "Different"])]
if "MatchRate" in out.columns:
out = out[out["MatchRate"].notna()]
return out
def average_comparable_match_rate(df):
"""Arithmetic mean of MatchRate across directly comparable field rows."""
scope = comparable_field_scope(df)
if scope.empty:
return np.nan, 0
rate = pd.to_numeric(scope["MatchRate"], errors="coerce").mean()
return rate, len(scope)
# ======================================================================================
# DATA LOADING & PREPARATION
# ======================================================================================
MAIN_PATH = "Data/All Streams June 2026.xlsx"
RULES_PATH = "Data/CMS Version NCH to NCH STTM 12_13_2024.xlsx"
MATCHED_COL = "1/1/24 - 12/31/24 Matched claims"
NOTMATCHED_COL = "1/1/24 - 12/31/24 Not Matched claims"
@st.cache_data(show_spinner="Loading and preparing data...", ttl=300)
def load_data():
# ---------------- MAIN comparison dataset ----------------
df = pd.read_excel(MAIN_PATH, sheet_name="Sheet1")
df["MatchedClaims"] = pd.to_numeric(df[MATCHED_COL], errors="coerce")
df["NotMatchedClaims"] = pd.to_numeric(df[NOTMATCHED_COL], errors="coerce")
df["TotalClaims"] = df["MatchedClaims"].fillna(0) + df["NotMatchedClaims"].fillna(0)
df["MatchRate"] = df["% matched"].apply(clean_pct)
derived = df["MatchedClaims"] / df["TotalClaims"].replace(0, np.nan)
df["MatchRate"] = df["MatchRate"].fillna(derived)
# Claim-level mismatch rate (share of claims that did NOT match)
df["MismatchRate"] = df["NotMatchedClaims"] / df["TotalClaims"].replace(0, np.nan)
# Normalize categorical text
required_cols = ["Stream", "Classification", "Disposition", "% matched", MATCHED_COL, NOTMATCHED_COL]
missing_cols = [c for c in required_cols if c not in df.columns]
if missing_cols:
raise ValueError(f"The source workbook is missing required columns: {', '.join(missing_cols)}")
df["Classification"] = df["Classification"].astype(str).str.strip()
df["ClassificationClean"] = df["Classification"].replace({"": "Unspecified", "nan": "Unspecified"})
df["Disposition"] = df["Disposition"].astype(str).str.strip()
df["DispositionClean"] = df["Disposition"].apply(normalize_disposition)
df["Stream"] = df["Stream"].astype(str).str.strip()
if "Sub-Classification" in df.columns:
df["SubClassClean"] = df["Sub-Classification"].apply(normalize_subclass)
else:
df["SubClassClean"] = "Unspecified"
if "Recommendation" in df.columns:
df["RecommendationClean"] = df["Recommendation"].apply(normalize_recommendation)
else:
df["RecommendationClean"] = "(none)"
if "Lynette's recommendation" in df.columns:
df["LynetteRec"] = df["Lynette's recommendation"].fillna("").astype(str).str.strip()
else:
df["LynetteRec"] = ""
# A column "needs change" when it is flagged for action or not fully matching
df["NeedsChange"] = df["DispositionClean"].eq("Action needed")
# Stringify remaining object columns to avoid Arrow serialization issues
for col in df.columns:
if df[col].dtype == "object" and col not in (
"MatchedClaims", "NotMatchedClaims", "TotalClaims", "MatchRate", "MismatchRate",
):
df[col] = df[col].fillna("").astype(str)
# ---------------- RULES dataset (business rules / STTM) ----------------
df_rules = pd.read_excel(RULES_PATH, sheet_name="Lynnette's Version")
if str(df_rules.columns[0]).startswith("Unnamed"):
new_header = df_rules.iloc[0]
df_rules = df_rules[2:]
df_rules.columns = new_header
df_rules = df_rules.reset_index(drop=True)
for col in df_rules.columns:
if df_rules[col].dtype == "object":
df_rules[col] = df_rules[col].fillna("").astype(str).str.strip()
extra = {}
for sheet in ["NCH STTM to NCH Data & % Pop", "Missing STTM Cols with Data"]:
try:
ex = pd.read_excel(RULES_PATH, sheet_name=sheet)
for col in ex.columns:
if ex[col].dtype == "object":
ex[col] = ex[col].fillna("").astype(str)
extra[sheet] = ex
except Exception:
pass
# ---------------- CROSS-DATASET LINK ----------------
rules_lk = df_rules.copy()
if "NCH Target Column" in rules_lk.columns and "NCH Target Table" in rules_lk.columns:
valid = ~is_blank(rules_lk["NCH Target Column"])
rules_lk = rules_lk[valid]
keep_cols = [c for c in ["NCH Target Table", "NCH Target Column", "Business Rule",
"Data Match? Y/N", "MCS Table", "MCS Column",
"NCH Cobol Copy book Field Name"] if c in rules_lk.columns]
rules_lk = rules_lk[keep_cols].drop_duplicates(
subset=["NCH Target Table", "NCH Target Column"], keep="first"
)
rules_lk = rules_lk.rename(columns={
"Business Rule": "Rule_BusinessRule",
"Data Match? Y/N": "Rule_DataMatch",
"MCS Table": "Rule_MCSTable",
"MCS Column": "Rule_MCSColumn",
"NCH Cobol Copy book Field Name": "Rule_CobolField",
})
df = df.merge(rules_lk, on=["NCH Target Table", "NCH Target Column"], how="left")
df["HasRule"] = df.get("Rule_BusinessRule", "").astype(str).str.strip().replace(
{"-": "", "nan": ""}
).ne("")
def rule_verdict(v):
s = str(v).strip().upper()
if s.startswith("Y"):
return "Match"
if s.startswith("N"):
return "No Match"
return ""
df["RuleVerdict"] = df.get("Rule_DataMatch", "").apply(rule_verdict)
df["ComparisonVerdict"] = np.where(df["ClassificationClean"].eq("Match"), "Match", "No Match")
df["Agreement"] = np.select(
[df["RuleVerdict"].eq(""), df["RuleVerdict"].eq(df["ComparisonVerdict"])],
["No rule verdict", "Agree"],
default="Conflict",
)
return df, df_rules, extra
try:
df_all, df_rules, extra_sheets = load_data()
except Exception as e:
st.error(f"Error loading data: {e}")
st.stop()
# ======================================================================================
# REUSABLE ANALYSIS ENGINE (used by the main data AND the custom-upload demo tab)
# ======================================================================================
def analyze_from_counts(df, label_col, matched_col, notmatched_col):
"""Given a pre-computed comparison table (one row per column/field with matched &
not-matched counts), return a tidy per-column summary + headline metrics."""
out = pd.DataFrame()
out["Field"] = df[label_col].astype(str)
out["Matched"] = pd.to_numeric(df[matched_col], errors="coerce").fillna(0)
out["Mismatched"] = pd.to_numeric(df[notmatched_col], errors="coerce").fillna(0)
out["Total"] = out["Matched"] + out["Mismatched"]
out["Match Rate"] = out["Matched"] / out["Total"].replace(0, np.nan)
out["Mismatch Rate"] = out["Mismatched"] / out["Total"].replace(0, np.nan)
out["Status"] = np.where(out["Mismatched"] <= 0, "Full match", "Mismatch present")
return out
def compare_two_systems(dfa, dfb, key_cols, compare_cols):
"""Compare two raw system extracts row-by-row on a shared key.
Returns (per-column summary, merged frame)."""
a = dfa.copy()
b = dfb.copy()
for k in key_cols:
a[k] = a[k].astype(str).str.strip()
b[k] = b[k].astype(str).str.strip()
merged = a.merge(b, on=key_cols, how="outer", suffixes=("__A", "__B"), indicator=True)
both = merged["_merge"] == "both"
only_a = int((merged["_merge"] == "left_only").sum())
only_b = int((merged["_merge"] == "right_only").sum())
rows = []
for c in compare_cols:
ca, cb = f"{c}__A", f"{c}__B"
if ca not in merged.columns or cb not in merged.columns:
continue
va = merged.loc[both, ca].astype(str).str.strip()
vb = merged.loc[both, cb].astype(str).str.strip()
matched = int((va == vb).sum())
mismatched = int((va != vb).sum())
total = matched + mismatched
rows.append({
"Field": c,
"Matched": matched,
"Mismatched": mismatched,
"Total": total,
"Match Rate": (matched / total) if total else np.nan,
"Mismatch Rate": (mismatched / total) if total else np.nan,
"Status": "Full match" if mismatched == 0 else "Mismatch present",
})
summary = pd.DataFrame(rows)
meta = {"only_a": only_a, "only_b": only_b, "shared_keys": int(both.sum())}
return summary, meta
def generic_narrative(summary, sys_a=SYS_A, sys_b=SYS_B):
"""Produce AI-agent style statements from a per-field summary frame."""
lines = []
if summary.empty:
return [("No comparable columns were found.", "warn")]
n_fields = len(summary)
mismatch_fields = int((summary["Mismatched"] > 0).sum())
pct_fields = mismatch_fields / n_fields if n_fields else 0
total_matched = int(summary["Matched"].sum())
total_mismatched = int(summary["Mismatched"].sum())
grand = total_matched + total_mismatched
overall_rate = (total_matched / grand) if grand else np.nan
kind = "good" if pct_fields < 0.1 else ("warn" if pct_fields < 0.3 else "danger")
lines.append((
f"I compared <b>{n_fields}</b> columns between <b>{sys_a}</b> and <b>{sys_b}</b>. "
f"<b>{mismatch_fields}</b> of them (<b>{pct_fields:.0%}</b>) show at least one "
f"record-level mismatch.", kind,
))
if grand:
lines.append((
f"Across all compared records, <b>{total_mismatched:,}</b> did not match "
f"(<b>{(1-overall_rate):.2%}</b> of {grand:,}), while "
f"<b>{total_matched:,}</b> matched cleanly.", "good" if overall_rate >= 0.99 else "warn",
))
worst = summary[summary["Mismatched"] > 0].sort_values("Mismatch Rate", ascending=False).head(5)
if not worst.empty:
names = ", ".join(f"<b>{r['Field']}</b> ({r['Mismatch Rate']:.1%})" for _, r in worst.iterrows())
lines.append((f"🔎 Top columns by mismatch percentage: {names}.", "danger"))
vol = summary.sort_values("Mismatched", ascending=False).head(1)
if not vol.empty and vol.iloc[0]["Mismatched"] > 0:
r = vol.iloc[0]
lines.append((
f"📦 The largest mismatch by volume is <b>{r['Field']}</b> with "
f"<b>{int(r['Mismatched']):,}</b> mismatched records.", "warn",
))
lines.append((
f"✅ Recommendation: <b>{mismatch_fields}</b> column(s) need attention / reconciliation; "
f"the remaining <b>{n_fields - mismatch_fields}</b> are aligned.",
"good" if mismatch_fields == 0 else "warn",
))
return lines
def render_summary_block(summary, sys_a=SYS_A, sys_b=SYS_B, key_prefix="gen"):
"""Render KPIs + charts + drill-down for a per-field summary frame (shared UI)."""
if summary.empty:
st.info("No comparable columns to analyze.")
return
n_fields = len(summary)
mismatch_fields = int((summary["Mismatched"] > 0).sum())
total_matched = int(summary["Matched"].sum())
total_mismatched = int(summary["Mismatched"].sum())
grand = total_matched + total_mismatched
overall_rate = (total_matched / grand) if grand else np.nan
c1, c2, c3, c4, c5 = st.columns(5)
kpi_card(c1, "Columns Compared", f"{n_fields:,}", "fields analyzed", PRIMARY)
kpi_card(c2, "Columns w/ Mismatch", f"{mismatch_fields:,}",
f"{mismatch_fields/n_fields:.0%} of columns", DANGER)
kpi_card(c3, "Matched Records", f"{total_matched:,}", "row-level", ACCENT)
kpi_card(c4, "Mismatched Records", f"{total_mismatched:,}", "row-level", WARN)
kpi_card(c5, "Overall Match Rate",
f"{overall_rate:.2%}" if pd.notna(overall_rate) else "—", "record-level", PRIMARY)
st.markdown("<br>", unsafe_allow_html=True)
for text, kind in generic_narrative(summary, sys_a, sys_b):
ai_say(text, kind)
st.markdown("<br>", unsafe_allow_html=True)
lcol, rcol = st.columns([1.3, 1])
with lcol:
section("Matched vs. Mismatched by Column", "Top 20 columns by total records.")
top = summary.sort_values("Total", ascending=False).head(20)
melt = top.melt(id_vars="Field", value_vars=["Matched", "Mismatched"],
var_name="Result", value_name="Records")
fig = px.bar(melt, x="Records", y="Field", color="Result", orientation="h",
barmode="stack",
color_discrete_map={"Matched": ACCENT, "Mismatched": DANGER})
fig.update_layout(yaxis={"categoryorder": "total ascending"})
st.plotly_chart(style_fig(fig, height=460), use_container_width=True,
key=f"{key_prefix}_bar")
with rcol:
section("Top 5 Columns by Mismatch %", "Where the two systems diverge most.")
worst = summary[summary["Mismatched"] > 0].sort_values(
"Mismatch Rate", ascending=False).head(5)
if worst.empty:
st.success("No columns with mismatches — the systems fully agree.")
else:
fig = px.bar(worst, x="Mismatch Rate", y="Field", orientation="h",
color="Mismatch Rate", color_continuous_scale="Reds",
text=worst["Mismatch Rate"].apply(lambda v: f"{v:.1%}"))
fig.update_layout(coloraxis_showscale=False,
yaxis={"categoryorder": "total ascending"})
fig.update_xaxes(tickformat=".0%")
st.plotly_chart(style_fig(fig, height=460), use_container_width=True,
key=f"{key_prefix}_worst")
section("Per-Column Comparison", "Full matched / mismatched breakdown with actions.")
show = summary.copy()
show["Action"] = np.where(show["Mismatched"] > 0, "Review / reconcile", "None")
st.dataframe(
show.sort_values("Mismatch Rate", ascending=False).style.format({
"Matched": "{:,.0f}", "Mismatched": "{:,.0f}", "Total": "{:,.0f}",
"Match Rate": "{:.2%}", "Mismatch Rate": "{:.2%}",
}),
use_container_width=True, hide_index=True,
)
csv = show.to_csv(index=False).encode("utf-8")
st.download_button("⬇️ Download comparison summary (CSV)", data=csv,
file_name="two_system_comparison.csv", mime="text/csv",
key=f"{key_prefix}_dl")
def read_uploaded(file):
"""Read an uploaded CSV or Excel file into a DataFrame (all columns stringified)."""
name = file.name.lower()
if name.endswith(".csv"):
df = pd.read_csv(file)
else:
df = pd.read_excel(file)
for c in df.columns:
if df[c].dtype == "object":
df[c] = df[c].fillna("").astype(str)
return df
@st.cache_data(show_spinner=False)
def make_sample_systems():
"""Generate two synthetic system extracts so the demo works out of the box."""
rng = np.random.default_rng(42)
n = 600
claim_id = np.arange(100000, 100000 + n)
status = rng.choice(["PAID", "DENIED", "PENDING"], size=n, p=[0.7, 0.2, 0.1])
provider = rng.integers(1000, 1050, size=n)
amount = np.round(rng.uniform(50, 5000, size=n), 2)
diag = rng.choice(["A01", "B20", "C34", "D50", "E11"], size=n)
svc_date = pd.to_datetime("2024-01-01") + pd.to_timedelta(rng.integers(0, 364, size=n), unit="D")
sys_a = pd.DataFrame({
"claim_id": claim_id, "status_code": status, "provider_id": provider,
"payment_amount": amount, "diagnosis_code": diag,
"service_date": svc_date.strftime("%Y-%m-%d"),
})
sys_b = sys_a.copy()
# Introduce controlled, realistic differences
m = rng.random(n) < 0.06 # 6% payment differences
sys_b.loc[m, "payment_amount"] = np.round(sys_b.loc[m, "payment_amount"] * rng.uniform(0.9, 1.1, m.sum()), 2)
m2 = rng.random(n) < 0.02 # 2% status differences
sys_b.loc[m2, "status_code"] = rng.choice(["PAID", "DENIED", "PENDING"], size=m2.sum())
m3 = rng.random(n) < 0.15 # 15% date-format differences (still same day)
sys_b.loc[m3, "service_date"] = pd.to_datetime(sys_b.loc[m3, "service_date"]).dt.strftime("%m/%d/%Y")
for c in sys_a.columns:
sys_a[c] = sys_a[c].astype(str)
sys_b[c] = sys_b[c].astype(str)
return sys_a, sys_b
# ======================================================================================