-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
2507 lines (2255 loc) · 131 KB
/
Copy pathapp.py
File metadata and controls
2507 lines (2255 loc) · 131 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
"""
AI Underwriting Assistant — Internal Portal
Powered by Snowflake Cortex AI
"""
import json
import re
import math
import datetime
import _snowflake
import streamlit as st
import plotly.graph_objects as go
import plotly.express as px
from snowflake.snowpark.context import get_active_session
# ── Page config ───────────────────────────────────────────────────────────────
st.set_page_config(
page_title="Underwriting Portal · AI Assistant",
page_icon="📋",
layout="wide",
initial_sidebar_state="expanded",
)
# ── Custom CSS ─────────────────────────────────────────────────────────────────
st.markdown("""
<style>
@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@300;400;500;600;700&family=IBM+Plex+Serif:wght@400;600&family=IBM+Plex+Mono:wght@400;500&display=swap');
:root {
--brand: #1B3A6B;
--brand-mid: #244d8f;
--brand-light: #EBF0FA;
--accent: #2563EB;
--bg: #F1F4F8;
--surface: #FFFFFF;
--surface-2: #F8FAFC;
--border: #D9E2EE;
--border-strong: #B8C8DE;
--text-primary: #0F1C2E;
--text-body: #2C3E55;
--text-muted: #5B7290;
--text-faint: #8FA5BF;
--danger: #B91C1C;
--danger-bg: #FEF2F2;
--danger-border: #FECACA;
--warn: #92400E;
--warn-bg: #FFFBEB;
--warn-border: #FDE68A;
--safe: #14532D;
--safe-bg: #F0FDF4;
--safe-border: #BBF7D0;
--radius: 8px;
--radius-lg: 12px;
--shadow-sm: 0 1px 3px rgba(15,28,46,0.08), 0 1px 2px rgba(15,28,46,0.05);
--shadow: 0 4px 12px rgba(15,28,46,0.10), 0 2px 4px rgba(15,28,46,0.06);
}
html, body, [class*="css"] { font-family: 'IBM Plex Sans', sans-serif !important; color: var(--text-body); }
.stApp { background: var(--bg) !important; }
h1, h2, h3, h4, h5, h6 { font-family: 'IBM Plex Serif', serif !important; color: var(--text-primary) !important; }
/* ── Dark-mode safety: force readable text everywhere ── */
.stApp, .stApp p, .stApp span, .stApp div,
.stApp li, .stApp label, .stApp small,
[data-testid="stMarkdownContainer"] p,
[data-testid="stMarkdownContainer"] li,
[data-testid="stMarkdownContainer"] span {
color: var(--text-primary) !important;
}
[data-testid="stChatMessage"] [data-testid="stMarkdownContainer"] p,
[data-testid="stChatMessage"] [data-testid="stMarkdownContainer"] li,
[data-testid="stChatMessage"] [data-testid="stMarkdownContainer"] span,
[data-testid="stChatMessage"] p { color: var(--text-primary) !important; }
[data-testid="stAlert"] p, [data-testid="stAlert"] span { color: inherit !important; }
[data-testid="stExpander"] summary span { color: var(--text-primary) !important; }
[data-baseweb="select"] [data-testid="stMarkdownContainer"] { color: var(--text-primary) !important; }
.stApp .stCaption, [data-testid="stCaptionContainer"] { color: var(--text-muted) !important; }
/* ── Sidebar ── */
[data-testid="stSidebar"] {
background: var(--brand) !important; border-right: none !important;
box-shadow: 2px 0 16px rgba(15,28,46,0.18);
}
[data-testid="stSidebar"] * { font-family: 'IBM Plex Sans', sans-serif !important; }
[data-testid="stSidebar"] hr { border-color: rgba(255,255,255,0.12) !important; }
.sb-brand {
padding: 1.6rem 1.25rem 1.25rem; border-bottom: 1px solid rgba(255,255,255,0.12);
margin-bottom: 1.25rem; display: flex; align-items: center; gap: 0.75rem;
}
.sb-mark {
width: 38px; height: 38px; background: rgba(255,255,255,0.15);
border: 1px solid rgba(255,255,255,0.22); border-radius: 7px;
display: flex; align-items: center; justify-content: center;
font-family: 'IBM Plex Serif', serif !important;
font-size: 0.95rem; font-weight: 600; color: #FFFFFF; flex-shrink: 0;
}
.sb-title { font-size: 0.82rem; font-weight: 600; color: #FFFFFF; line-height: 1.2; }
.sb-subtitle { font-size: 0.67rem; color: rgba(255,255,255,0.5); margin-top: 0.1rem; }
.sb-section {
font-size: 0.61rem; font-weight: 700; letter-spacing: 0.18em;
text-transform: uppercase; color: rgba(255,255,255,0.38);
padding: 0.5rem 1.25rem 0.3rem; margin-top: 0.4rem;
}
.sb-stat {
margin: 0.3rem 0.75rem; padding: 0.65rem 0.9rem;
background: rgba(255,255,255,0.08); border: 1px solid rgba(255,255,255,0.1);
border-radius: var(--radius);
}
.sb-stat .s-label {
font-size: 0.65rem; color: rgba(255,255,255,0.48);
text-transform: uppercase; letter-spacing: 0.07em; margin-bottom: 0.18rem;
}
.sb-stat .s-value { font-size: 1.15rem; font-weight: 600; color: #FFFFFF; line-height: 1.1; }
.sb-stat .s-value.danger { color: #FCA5A5; }
.sb-stat .s-value.gold { color: #FCD34D; }
[data-testid="stSidebar"] .stButton > button {
background: rgba(255,255,255,0.08) !important; color: rgba(255,255,255,0.80) !important;
border: 1px solid rgba(255,255,255,0.16) !important; font-size: 0.75rem;
border-radius: var(--radius); width: calc(100% - 1.5rem) !important;
margin: 0.25rem 0.75rem; transition: background 0.2s; box-shadow: none !important;
}
[data-testid="stSidebar"] .stButton > button:hover {
background: rgba(255,255,255,0.16) !important; transform: none !important;
}
/* ── Page header ── */
.page-header {
background: var(--surface); border-bottom: 3px solid var(--brand);
padding: 1rem 1.75rem; margin: -1rem -1rem 1.5rem -1rem;
display: flex; align-items: center; justify-content: space-between;
box-shadow: var(--shadow-sm);
}
.ph-left { display: flex; align-items: center; gap: 0.85rem; }
.ph-mark {
width: 40px; height: 40px; background: var(--brand); border-radius: var(--radius);
display: flex; align-items: center; justify-content: center;
font-family: 'IBM Plex Serif', serif !important;
font-size: 1rem; font-weight: 700; color: #FFFFFF !important;
flex-shrink: 0; box-shadow: 0 0 0 2px rgba(255,255,255,0.25);
}
.ph-title {
font-family: 'IBM Plex Serif', serif !important; font-size: 1.2rem; font-weight: 600;
color: var(--text-primary) !important; margin: 0; line-height: 1.15;
}
.ph-sub { font-size: 0.73rem; color: var(--text-muted); margin-top: 0.12rem; }
.ph-badge {
font-size: 0.67rem; font-weight: 700; letter-spacing: 0.09em; text-transform: uppercase;
background: var(--brand-light); color: var(--brand); border: 1px solid #C5D5EE;
border-radius: 999px; padding: 0.28rem 0.85rem;
}
/* ── Tabs ── */
.stTabs [data-baseweb="tab-list"] {
background: transparent !important; gap: 0.1rem;
border-bottom: 1px solid var(--border) !important;
}
.stTabs [data-baseweb="tab"] {
background: transparent !important; color: var(--text-muted) !important;
font-size: 0.82rem !important; font-weight: 500 !important;
padding: 0.6rem 1.25rem !important; border-radius: 6px 6px 0 0 !important;
border: 1px solid transparent !important; border-bottom: none !important;
}
.stTabs [aria-selected="true"] {
background: var(--surface) !important; color: var(--brand) !important;
font-weight: 600 !important; border-color: var(--border) !important;
border-bottom-color: var(--surface) !important;
}
/* ── Panel ── */
.panel {
background: var(--surface); border: 1px solid var(--border);
border-radius: var(--radius-lg); box-shadow: var(--shadow-sm);
padding: 1.25rem 1.5rem; margin: 0.75rem 0;
}
.panel-title {
font-family: 'IBM Plex Serif', serif !important; font-size: 0.92rem; font-weight: 600;
color: var(--text-primary); margin-bottom: 0.75rem; padding-bottom: 0.6rem;
border-bottom: 1px solid var(--border);
display: flex; align-items: center; justify-content: space-between;
}
.panel-body { font-size: 0.875rem; line-height: 1.7; color: var(--text-body) !important; }
/* ── Risk badges ── */
.risk-badge {
display: inline-flex; align-items: center; gap: 0.4rem; padding: 0.28rem 0.85rem;
border-radius: 999px; font-size: 0.7rem; font-weight: 700;
letter-spacing: 0.09em; text-transform: uppercase;
}
.risk-badge.HIGH { background: var(--danger-bg); color: var(--danger); border: 1px solid var(--danger-border); }
.risk-badge.MEDIUM { background: var(--warn-bg); color: var(--warn); border: 1px solid var(--warn-border); }
.risk-badge.LOW { background: var(--safe-bg); color: var(--safe); border: 1px solid var(--safe-border); }
.risk-dot { width: 6px; height: 6px; border-radius: 50%; background: currentColor; flex-shrink: 0; }
/* ── Data grid ── */
.data-grid {
display: grid; grid-template-columns: repeat(3, 1fr); gap: 0.55rem; margin-top: 0.75rem;
}
.df-card {
background: var(--surface-2); border: 1px solid var(--border);
border-radius: var(--radius); padding: 0.65rem 0.9rem;
}
.df-label {
font-size: 0.61rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.12em;
color: var(--text-muted); margin-bottom: 0.22rem;
}
.df-value { font-size: 0.875rem; font-weight: 500; color: var(--text-primary) !important; word-break: break-word; }
/* ── Progress steps ── */
.progress-steps {
display: flex; margin: 0.75rem 0 1.25rem;
background: var(--surface); border: 1px solid var(--border);
border-radius: var(--radius); overflow: hidden; box-shadow: var(--shadow-sm);
}
.progress-step {
flex: 1; padding: 0.55rem 0.4rem; text-align: center; font-size: 0.67rem;
font-weight: 500; color: var(--text-faint); border-right: 1px solid var(--border);
transition: all 0.25s;
}
.progress-step:last-child { border-right: none; }
.ps-icon { display: block; font-size: 0.9rem; margin-bottom: 0.12rem; }
.progress-step.active { background: var(--brand-light); color: var(--brand); font-weight: 600; }
.progress-step.done { background: var(--safe-bg); color: var(--safe); }
/* ── Upload zone ── */
.upload-zone {
background: var(--surface-2); border: 2px dashed var(--border-strong);
border-radius: var(--radius-lg); padding: 1.75rem 1.5rem;
text-align: center; margin-bottom: 1rem;
}
.uz-icon { font-size: 1.6rem; margin-bottom: 0.4rem; display: block; }
.uz-title { font-weight: 600; color: var(--text-primary) !important; font-size: 0.92rem; margin-bottom: 0.25rem; }
.uz-sub { font-size: 0.77rem; color: var(--text-muted) !important; }
/* ── Chat header ── */
.chat-header {
background: var(--surface); border: 1px solid var(--border);
border-radius: var(--radius-lg) var(--radius-lg) 0 0; padding: 0.85rem 1.25rem;
display: flex; align-items: center; gap: 0.75rem; box-shadow: var(--shadow-sm);
}
.ch-pulse {
width: 8px; height: 8px; border-radius: 50%; background: #16A34A;
box-shadow: 0 0 0 0 rgba(22,163,74,0.35); animation: pulse-green 2s infinite;
}
@keyframes pulse-green {
0% { box-shadow: 0 0 0 0 rgba(22,163,74,0.35); }
70% { box-shadow: 0 0 0 6px rgba(22,163,74,0); }
100% { box-shadow: 0 0 0 0 rgba(22,163,74,0); }
}
.ch-title {
font-family: 'IBM Plex Serif', serif !important; font-size: 0.92rem;
font-weight: 600; color: var(--text-primary);
}
.ch-sub { font-size: 0.7rem; color: var(--text-muted); margin-left: auto; }
/* ── Section heading ── */
.section-heading {
font-family: 'IBM Plex Serif', serif !important; font-size: 0.92rem; font-weight: 600;
color: var(--text-primary); margin: 1.25rem 0 0.75rem;
padding-bottom: 0.45rem; border-bottom: 1px solid var(--border);
}
/* ── Buttons ── */
.stButton > button {
font-family: 'IBM Plex Sans', sans-serif !important; background: var(--surface) !important;
color: var(--accent) !important; border: 1px solid #C5D5EE !important;
border-radius: var(--radius) !important; font-size: 0.78rem !important;
font-weight: 500 !important; transition: all 0.15s !important;
box-shadow: var(--shadow-sm) !important;
}
.stButton > button:hover {
background: var(--brand-light) !important; border-color: var(--accent) !important;
transform: translateY(-1px) !important; box-shadow: var(--shadow) !important;
}
.primary-btn .stButton > button {
background: var(--brand) !important; color: #FFFFFF !important;
border-color: var(--brand) !important; font-weight: 600 !important;
font-size: 0.82rem !important; padding: 0.55rem 1.4rem !important;
}
.primary-btn .stButton > button:hover {
background: var(--brand-mid) !important; border-color: var(--brand-mid) !important;
}
/* ── File uploader — force light surface ── */
[data-testid="stFileUploader"] {
background: var(--surface) !important;
border: 1px solid var(--border) !important;
border-radius: var(--radius) !important;
}
[data-testid="stFileUploader"] * { color: var(--text-body) !important; }
[data-testid="stFileUploaderDropzone"] { background: var(--surface-2) !important; }
[data-testid="stFileUploaderDropzoneInstructions"] span,
[data-testid="stFileUploaderDropzoneInstructions"] p,
[data-testid="stFileUploaderDropzoneInstructions"] small { color: var(--text-muted) !important; }
[data-testid="stFileUploader"] button,
[data-testid="stFileUploaderDropzone"] button {
background: var(--surface) !important; color: var(--brand) !important;
border: 1.5px solid var(--brand) !important; border-radius: var(--radius) !important;
font-weight: 600 !important;
}
[data-testid="stFileUploader"] button:hover,
[data-testid="stFileUploaderDropzone"] button:hover { background: var(--brand-light) !important; }
/* ── Sidebar — all text explicitly white ── */
[data-testid="stSidebar"] .sb-stat .s-label,
[data-testid="stSidebar"] .sb-section,
[data-testid="stSidebar"] .sb-subtitle,
[data-testid="stSidebar"] p,
[data-testid="stSidebar"] span:not(.s-value),
[data-testid="stSidebar"] small { color: rgba(255,255,255,0.55) !important; }
[data-testid="stSidebar"] .s-value { color: #FFFFFF !important; }
[data-testid="stSidebar"] .s-value.danger { color: #FCA5A5 !important; }
[data-testid="stSidebar"] .s-value.gold { color: #FCD34D !important; }
[data-testid="stSidebar"] .sb-title { color: #FFFFFF !important; }
/* ── Streamlit overrides ── */
.stDataFrame {
border: 1px solid var(--border) !important; border-radius: var(--radius) !important;
overflow: hidden; box-shadow: var(--shadow-sm) !important;
}
[data-testid="stDataFrame"] th {
background: var(--surface-2) !important; font-size: 0.67rem !important;
letter-spacing: 0.08em !important; text-transform: uppercase !important;
color: var(--text-muted) !important; border-bottom: 1px solid var(--border) !important;
font-weight: 700 !important;
}
.stAlert { border-radius: var(--radius) !important; font-size: 0.84rem !important; }
hr { border-color: var(--border) !important; }
[data-testid="stSelectbox"] > div > div {
background: var(--surface) !important; border-color: var(--border) !important;
border-radius: var(--radius) !important; color: var(--text-body) !important;
font-size: 0.82rem !important;
}
code, pre { font-family: 'IBM Plex Mono', monospace !important; font-size: 0.8rem !important; }
.stCode { border-radius: var(--radius) !important; }
/* ── Danger button ── */
.danger-btn .stButton > button {
background: #FEF2F2 !important; color: var(--danger) !important;
border: 1px solid var(--danger-border) !important;
font-weight: 600 !important; font-size: 0.75rem !important;
}
.danger-btn .stButton > button:hover {
background: var(--danger-bg) !important;
border-color: var(--danger) !important; transform: none !important;
}
.danger-confirm .stButton > button {
background: var(--danger) !important; color: #FFFFFF !important;
border-color: var(--danger) !important; font-weight: 700 !important;
font-size: 0.75rem !important;
}
.danger-confirm .stButton > button:hover {
background: #991B1B !important; border-color: #991B1B !important;
transform: none !important;
}
.danger-confirm .stButton > button,
.danger-cancel .stButton > button {
white-space: nowrap !important; height: 2.2rem !important;
min-height: 2.2rem !important; padding-top: 0 !important; padding-bottom: 0 !important;
display: flex !important; align-items: center !important; justify-content: center !important;
}
.danger-cancel .stButton > button {
background: var(--surface) !important; color: var(--text-muted) !important;
border: 1px solid var(--border-strong) !important;
font-weight: 500 !important; font-size: 0.75rem !important;
}
::-webkit-scrollbar { width: 5px; height: 5px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: var(--border-strong); border-radius: 99px; }
</style>
""", unsafe_allow_html=True)
# ── Snowpark session ──────────────────────────────────────────────────────────
session = get_active_session()
# ── Constants ─────────────────────────────────────────────────────────────────
RISK_LABEL = {"LOW": "Low Risk", "MEDIUM": "Medium Risk", "HIGH": "High Risk"}
VALID_TIERS = {"HIGH", "MEDIUM", "LOW"}
STEPS = [
("📄", "Parse PDF"),
("🔍", "Extract Fields"),
("⚖️", "ML Score"),
("✍️", "Summarise"),
("💾", "Save Record"),
]
SEMANTIC_MODEL = "@UNDERWRITING_DB.UNDERWRITING_SCHEMA.YAML_STAGE/underwriting_model.yaml"
TABLE_FQN = "UNDERWRITING_DB.UNDERWRITING_SCHEMA.APPLICANTS_SCORED"
STAGE_FQN = "@UNDERWRITING_DB.UNDERWRITING_SCHEMA.UNDERWRITING_STAGE"
# ── Helpers ───────────────────────────────────────────────────────────────────
def safe_float(value, default: float = 0.0) -> float:
try:
return float(str(value).replace(",", "").replace("$", "").strip() or default)
except (ValueError, TypeError):
return default
def esc(text) -> str:
return str(text if text is not None else "").replace("$$", "$ $")
def sanitise_filename(name: str) -> str:
# Keep only alphanumerics, dots, hyphens, underscores — prevents SQL injection via filename
safe = re.sub(r'[^\w.\-]', '_', name)
return re.sub(r'_+', '_', safe)
def parse_json_from_llm(raw: str) -> dict:
if not raw:
return {}
raw = re.sub(r"```(?:json)?", "", raw).strip()
match = re.search(r"\{.*\}", raw, re.DOTALL)
if match:
try:
return json.loads(match.group())
except json.JSONDecodeError:
pass
return {}
def normalise_tier(raw: str) -> str:
upper = raw.strip().upper()
for tier in ("HIGH", "MEDIUM", "LOW"):
if tier in upper:
return tier
return "UNKNOWN"
def predict_risk_ml(extracted: dict) -> tuple[str, list[str], int]:
"""
Call Snowflake ML regressor UNDERWRITING_SCORE_MODEL to predict RISK_SCORE (0–20).
Derives RISK_TIER from the predicted score: LOW 0–6, MEDIUM 7–13, HIGH 14–20.
11 features — same encoding used in training CSV.
Falls back to MEDIUM / score 10 if the model is unavailable.
"""
age = safe_float(extracted.get("age"))
bmi = safe_float(extracted.get("bmi_numeric"))
sbp = safe_float(extracted.get("systolic_bp"))
dbp = safe_float(extracted.get("diastolic_bp"))
chol = safe_float(extracted.get("cholesterol_numeric"))
glucose = safe_float(extracted.get("glucose_numeric"))
income = safe_float(extracted.get("annual_income")) or safe_float(
re.sub(r"[^\d.]", "", str(extracted.get("annual_gross_income") or "").split()[0])
if extracted.get("annual_gross_income") else "0"
)
coverage = safe_float(extracted.get("coverage_amount_numeric"))
# Encode categoricals — same encoding used in training CSV
smoking = str(extracted.get("smoking_status") or "").lower()
if any(w in smoking for w in ["current smoker", "currently smokes", "active smoker", "yes"]):
smoking_enc = 2
elif any(w in smoking for w in ["former", "ex-smoker", "quit", "stopped"]):
smoking_enc = 1
else:
smoking_enc = 0
declines = str(extracted.get("prior_application_declines") or "").lower()
decline_enc = 1 if any(w in declines for w in ["yes", "declined", "rejected", "refused"]) else 0
family = " ".join([
str(extracted.get("family_history_father") or ""),
str(extracted.get("family_history_mother") or ""),
str(extracted.get("family_history_siblings") or ""),
str(extracted.get("hereditary_flags") or ""),
]).lower()
family_cvd_enc = 1 if any(kw in family for kw in [
"heart attack", "stroke", "cardiovascular", "cardiac", "coronary"
]) else 0
# ── New enriched features ─────────────────────────────────────────────────
conditions_text = str(extracted.get("pre_existing_conditions") or "").lower()
surgical_text = str(extracted.get("surgical_and_mental_health_history") or "").lower()
all_medical = conditions_text + " " + surgical_text
# HbA1c numeric
hba1c_match = re.search(r"hba1c[:\s]*(\d+\.?\d*)\s*%", all_medical)
hba1c_val = float(hba1c_match.group(1)) if hba1c_match else 0.0
# Conditions count — split on common separators
if conditions_text and conditions_text.strip() not in ("none", "null", "—", "", "n/a"):
parts = re.split(r"[;,\(\)\n]", conditions_text)
conditions_count = len([p for p in parts if len(p.strip()) > 5])
else:
conditions_count = 0
# Pending investigations flag
pending_text = str(extracted.get("pending_investigations") or "").lower().strip().rstrip(".")
pending_flag = 0 if pending_text in ("none", "null", "—", "", "n/a", "no") or pending_text.startswith("none") else 1
# Years since most recent diagnosis (best-effort regex)
years_since = 0.0
diag_match = re.search(r"(?:dx|diagnosed|diagnosis)[^\d]*(\d{4})", all_medical)
if diag_match:
diag_year = int(diag_match.group(1))
years_since = round(datetime.datetime.now().year - diag_year, 1)
years_since = max(0.0, min(years_since, 50.0))
# On medications flag
meds_text = str(extracted.get("current_medications") or "").lower().strip().rstrip(".")
on_meds = 0 if meds_text in ("none", "null", "—", "", "n/a", "no") or meds_text.startswith("none") else 1
try:
rows = session.sql(f"""
WITH input_data AS (
SELECT
{age}::FLOAT AS AGE,
{bmi}::FLOAT AS BMI_NUMERIC,
{sbp}::FLOAT AS SYSTOLIC_BP,
{dbp}::FLOAT AS DIASTOLIC_BP,
{chol}::FLOAT AS CHOLESTEROL_NUMERIC,
{glucose}::FLOAT AS GLUCOSE_NUMERIC,
{income}::FLOAT AS ANNUAL_INCOME,
{coverage}::FLOAT AS COVERAGE_AMOUNT_NUMERIC,
{smoking_enc}::FLOAT AS SMOKING_STATUS,
{decline_enc}::FLOAT AS PRIOR_APPLICATION_DECLINES,
{family_cvd_enc}::FLOAT AS FAMILY_HISTORY_CVD,
{hba1c_val}::FLOAT AS HBA1C_NUMERIC,
{conditions_count}::FLOAT AS CONDITIONS_COUNT,
{pending_flag}::FLOAT AS PENDING_INVESTIGATIONS,
{years_since}::FLOAT AS YEARS_SINCE_DIAGNOSIS,
{on_meds}::FLOAT AS ON_MEDICATIONS
)
SELECT UNDERWRITING_DB.UNDERWRITING_SCHEMA.UNDERWRITING_SCORE_MODEL!PREDICT(*) AS pred
FROM input_data
""").collect()
if rows:
pred = rows[0]["PRED"]
if isinstance(pred, str):
pred = json.loads(pred)
# Regressor output — Snowflake names it predicted_<TARGET_COLUMN>
raw_score = float(
pred.get("predicted_RISK_SCORE")
or pred.get("output_feature_0")
or 10
)
score = max(0, min(round(raw_score), 20))
if score >= 14:
tier = "HIGH"
elif score >= 7:
tier = "MEDIUM"
else:
tier = "LOW"
return tier, [f"ML regressor prediction — UNDERWRITING_SCORE_MODEL (raw: {raw_score:.1f})"], score
except Exception as e:
st.warning(f"ML model prediction failed: {e}")
return "MEDIUM", ["ML prediction unavailable — defaulted to MEDIUM"], 10
def render_progress(current_step: int) -> str:
html = '<div class="progress-steps">'
for i, (icon, label) in enumerate(STEPS):
cls = "done" if i < current_step else ("active" if i == current_step else "")
tick = "✓ " if i < current_step else ""
html += f'<div class="progress-step {cls}"><span class="ps-icon">{icon}</span>{tick}{label}</div>'
return html + "</div>"
def render_risk_badge(risk_tier: str) -> str:
label = RISK_LABEL.get(risk_tier, risk_tier)
css = risk_tier if risk_tier in VALID_TIERS else "MEDIUM"
return f'<span class="risk-badge {css}"><span class="risk-dot"></span>{label}</span>'
def render_data_grid(fields: dict) -> None:
html = '<div class="data-grid">'
for label, value in fields.items():
v = str(value) if value not in (None, "", "N/A", "null") else "—"
html += (
f'<div class="df-card">'
f'<div class="df-label">{label}</div>'
f'<div class="df-value">{v}</div>'
f'</div>'
)
st.markdown(html + "</div>", unsafe_allow_html=True)
def trunc(value, n: int) -> str:
"""Truncate a string to n chars, appending … if cut."""
s = str(value) if value not in (None, "", "null") else ""
return (s[:n] + "…") if len(s) > n else s
# ── Metrics ───────────────────────────────────────────────────────────────────
@st.cache_data(ttl=30, show_spinner=False)
def load_summary_metrics() -> dict:
try:
rows = session.sql(f"""
SELECT
COUNT(*) AS total,
COUNT_IF(RISK_TIER = 'HIGH') AS high_count,
COUNT_IF(RISK_TIER = 'LOW') AS low_count,
ROUND(COUNT_IF(RISK_TIER='HIGH') / NULLIF(COUNT(*),0) * 100, 1) AS pct_high,
ROUND(AVG(COVERAGE_AMOUNT_NUMERIC) / 1000, 0) AS avg_coverage_k,
ROUND(AVG(BMI_NUMERIC), 1) AS avg_bmi,
COUNT_IF(SMOKING_STATUS ILIKE '%current smoker%') AS current_smoker_count,
COUNT_IF(PRIOR_APPLICATION_DECLINES ILIKE '%yes%') AS prior_decline_count
FROM {TABLE_FQN}
""").collect()
m = rows[0] if rows else None
return {
"total": int(m["TOTAL"]) if m else 0,
"high_count": int(m["HIGH_COUNT"]) if m else 0,
"low_count": int(m["LOW_COUNT"]) if m else 0,
"pct_high": float(m["PCT_HIGH"]) if m and m["PCT_HIGH"] else 0.0,
"avg_coverage": float(m["AVG_COVERAGE_K"]) if m and m["AVG_COVERAGE_K"] else 0.0,
"avg_bmi": float(m["AVG_BMI"]) if m and m["AVG_BMI"] else 0.0,
"current_smoker_count": int(m["CURRENT_SMOKER_COUNT"]) if m else 0,
"prior_decline_count": int(m["PRIOR_DECLINE_COUNT"]) if m else 0,
}
except Exception:
return {
"total": 0, "high_count": 0, "low_count": 0, "pct_high": 0.0,
"avg_coverage": 0.0, "avg_bmi": 0.0,
"current_smoker_count": 0, "prior_decline_count": 0,
}
def fmt_coverage(value_k: float) -> str:
sign = "-" if value_k < 0 else ""
abs_k = abs(value_k)
if abs_k >= 999.5:
m = abs_k / 1000
return f"{sign}${m:.1f}M" if round(m, 1) != round(m) else f"{sign}${m:.0f}M"
return f"{sign}${abs_k:,.0f}K"
# ── Table + Delete ────────────────────────────────────────────────────────────
@st.cache_resource(show_spinner=False)
def ensure_table() -> None:
"""Create the APPLICANTS_SCORED table with the full schema if it does not exist."""
session.sql(f"""
CREATE TABLE IF NOT EXISTS {TABLE_FQN} (
FILE_NAME VARCHAR,
UPLOADED_AT TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP(),
FULL_LEGAL_NAME VARCHAR,
DATE_OF_BIRTH VARCHAR,
AGE FLOAT,
GENDER VARCHAR,
NATIONALITY VARCHAR,
MARITAL_STATUS VARCHAR,
RESIDENTIAL_ADDRESS VARCHAR,
PHONE VARCHAR,
JOB_TITLE VARCHAR,
EMPLOYER VARCHAR,
INDUSTRY_SECTOR VARCHAR,
EMPLOYMENT_TYPE VARCHAR,
ANNUAL_GROSS_INCOME VARCHAR,
ANNUAL_INCOME FLOAT,
YEARS_IN_CURRENT_ROLE VARCHAR,
OCCUPATIONAL_HAZARDS VARCHAR,
HEIGHT VARCHAR,
WEIGHT VARCHAR,
BMI VARCHAR,
BMI_NUMERIC FLOAT,
DRIVING_RECORD VARCHAR,
ALCOHOL_CONSUMPTION VARCHAR,
EXERCISE_FREQUENCY VARCHAR,
DIETARY_HABITS VARCHAR,
HAZARDOUS_HOBBIES VARCHAR,
SMOKING_STATUS VARCHAR,
BLOOD_PRESSURE VARCHAR,
SYSTOLIC_BP FLOAT,
DIASTOLIC_BP FLOAT,
TOTAL_CHOLESTEROL VARCHAR,
CHOLESTEROL_NUMERIC FLOAT,
FASTING_GLUCOSE VARCHAR,
GLUCOSE_NUMERIC FLOAT,
LAST_MEDICAL_EXAMINATION VARCHAR,
CURRENT_MEDICATIONS VARCHAR,
KNOWN_ALLERGIES VARCHAR,
PRE_EXISTING_CONDITIONS VARCHAR,
HOSPITALISATION_HISTORY VARCHAR,
SURGICAL_AND_MENTAL_HEALTH_HISTORY VARCHAR,
PENDING_INVESTIGATIONS VARCHAR,
FAMILY_HISTORY_FATHER VARCHAR,
FAMILY_HISTORY_MOTHER VARCHAR,
FAMILY_HISTORY_SIBLINGS VARCHAR,
FAMILY_HISTORY_PATERNAL_RELATIVES VARCHAR,
FAMILY_HISTORY_MATERNAL_RELATIVES VARCHAR,
HEREDITARY_FLAGS VARCHAR,
COVERAGE_REQUESTED VARCHAR,
COVERAGE_AMOUNT_NUMERIC FLOAT,
POLICY_TYPE VARCHAR,
BENEFICIARY VARCHAR,
EXISTING_LIFE_COVER VARCHAR,
REASON_FOR_COVERAGE VARCHAR,
PRIOR_APPLICATION_DECLINES VARCHAR,
PRIOR_CLAIMS VARCHAR,
MEDICAL_ASSESSMENT_NARRATIVE VARCHAR,
FINANCIAL_RISK_NARRATIVE VARCHAR,
RISK_TIER VARCHAR,
RISK_SCORE FLOAT,
UNDERWRITER_SUMMARY VARCHAR,
UPLOADED_BY VARCHAR
)
""").collect()
def delete_all_data() -> tuple[int, int, list[str]]:
errors: list[str] = []
rows_deleted = 0
files_deleted = 0
try:
count_rows = session.sql(f"SELECT COUNT(*) AS n FROM {TABLE_FQN}").collect()
rows_deleted = int(count_rows[0]["N"]) if count_rows else 0
session.sql(f"DELETE FROM {TABLE_FQN}").collect()
except Exception as e:
errors.append(f"Table delete failed: {e}")
try:
stage_bare = STAGE_FQN.lstrip("@")
file_rows = session.sql(f"LIST @{stage_bare}").collect()
files_deleted = len(file_rows)
if files_deleted > 0:
session.sql(f"REMOVE @{stage_bare} PATTERN='.*'").collect()
remaining = session.sql(f"LIST @{stage_bare}").collect()
if remaining:
errors.append(f"Stage removal incomplete: {len(remaining)} file(s) still present.")
files_deleted = files_deleted - len(remaining)
except Exception as e:
errors.append(f"Stage removal failed: {e}")
return rows_deleted, files_deleted, errors
# ═══════════════════════════════════════════════════════════════════════════════
# PIPELINE
# ═══════════════════════════════════════════════════════════════════════════════
def analyse_pdf(uploaded_file) -> dict | None:
step_ph = st.empty()
safe_name = sanitise_filename(uploaded_file.name)
# ── Deduplication check ───────────────────────────────────────────────────
try:
dup_rows = session.sql(
f"SELECT UPLOADED_AT, FULL_LEGAL_NAME, RISK_TIER "
f"FROM {TABLE_FQN} "
f"WHERE FILE_NAME = $${esc(safe_name)}$$ "
f"ORDER BY UPLOADED_AT DESC LIMIT 1"
).collect()
if dup_rows:
prev = dup_rows[0]
st.warning(
f"⚠️ **{safe_name}** was already processed on "
f"**{prev['UPLOADED_AT']}** — "
f"applicant **{prev['FULL_LEGAL_NAME']}**, "
f"risk tier **{prev['RISK_TIER']}**. "
f"Re-running will insert a duplicate record."
)
except Exception:
pass
# ── Step 0 · Upload ───────────────────────────────────────────────────────
step_ph.markdown(render_progress(0) + "_Uploading document to Snowflake stage…_", unsafe_allow_html=True)
try:
session.file.put_stream(
uploaded_file, f"{STAGE_FQN}/{safe_name}",
auto_compress=False, overwrite=True,
)
session.sql(f"ALTER STAGE {STAGE_FQN.lstrip('@')} REFRESH").collect()
except Exception as e:
st.error(f"**Upload failed.** {e}")
return None
# ── Step 1 · Parse PDF ────────────────────────────────────────────────────
step_ph.markdown(render_progress(1) + "_Extracting document text with AI_PARSE_DOCUMENT…_", unsafe_allow_html=True)
try:
rows = session.sql(f"""
SELECT SNOWFLAKE.CORTEX.AI_PARSE_DOCUMENT(
TO_FILE('{STAGE_FQN}', '{safe_name}'),
{{'mode': 'LAYOUT'}}
):content::VARCHAR AS raw_text
""").collect()
raw_text = (rows[0]["RAW_TEXT"] or "").strip() if rows else ""
except Exception as e:
st.error(f"**Document parsing failed.** {e}")
return None
if not raw_text:
st.warning("No text could be extracted from this document. Please check the file.")
return None
# ── Step 2 · Extract structured fields ───────────────────────────────────
step_ph.markdown(render_progress(2) + "_Extracting structured fields…_", unsafe_allow_html=True)
extract_prompt = f"""You are an insurance data extraction assistant.
Extract the following fields from the 7-section insurance application document below.
Return ONLY a valid JSON object with exactly these keys — no extra text, no markdown fences.
Keys to extract (grouped by section for reference only — return flat JSON):
SECTION 1 — PERSONAL INFORMATION:
full_legal_name, date_of_birth, age, gender, nationality,
marital_status, residential_address, phone
SECTION 2 — OCCUPATION & FINANCIAL PROFILE:
job_title, employer, industry_sector, employment_type,
annual_gross_income, years_in_current_role, occupational_hazards
SECTION 3 — LIFESTYLE & BIOMETRIC ASSESSMENT:
height, weight, bmi_text, bmi_numeric, driving_record,
alcohol_consumption, exercise_frequency, dietary_habits,
hazardous_hobbies, smoking_status
SECTION 4 — MEDICAL HISTORY & CLINICAL INDICATORS:
blood_pressure, systolic_bp, diastolic_bp, total_cholesterol,
cholesterol_numeric, fasting_glucose, glucose_numeric,
last_medical_examination, current_medications, known_allergies,
pre_existing_conditions, hospitalisation_history,
surgical_and_mental_health_history, pending_investigations
SECTION 5 — FAMILY MEDICAL HISTORY:
family_history_father, family_history_mother, family_history_siblings,
family_history_paternal_relatives, family_history_maternal_relatives,
hereditary_flags
SECTION 6 — COVERAGE REQUEST & POLICY DETAILS:
coverage_requested, coverage_amount_numeric, policy_type,
beneficiary, existing_life_cover, reason_for_coverage,
prior_application_declines, prior_claims
SECTION 7 — MEDICAL & FINANCIAL SUMMARY NARRATIVE:
medical_assessment_narrative, financial_risk_narrative
Extraction rules:
- bmi_numeric: numeric value only (e.g. 29.3)
- systolic_bp: first number from blood pressure only (e.g. 124 from "124 / 80 mmHg")
- diastolic_bp: second number from blood pressure only (e.g. 80 from "124 / 80 mmHg")
- cholesterol_numeric: numeric mg/dL value only (e.g. 198)
- glucose_numeric: numeric mg/dL value only (e.g. 95)
- coverage_amount_numeric: numeric USD value only, no $ or commas (e.g. 500000)
- annual_gross_income: keep as full text string including any supplementary income notes
- smoking_status: keep the full narrative text from the "Tobacco / Smoking Status:" block, not just Yes/No
- surgical_and_mental_health_history: extract full combined narrative block as a single string
- If a field is not present in the document, use null
Document text:
{esc(raw_text)}"""
try:
rows = session.sql(f"""
SELECT SNOWFLAKE.CORTEX.COMPLETE(
'mistral-large2',
$${esc(extract_prompt)}$$
) AS result
""").collect()
raw_result = rows[0]["RESULT"] if rows else ""
extracted: dict = parse_json_from_llm(raw_result)
except Exception as e:
st.error(f"**Field extraction failed.** {e}")
return None
if not extracted:
st.warning(f"Field extraction returned no data. Raw output: `{raw_result[:300]}`")
return None
# ── Step 3 · Score risk tier via ML model ─────────────────────────────────
step_ph.markdown(render_progress(3) + "_Scoring risk tier via ML model…_", unsafe_allow_html=True)
risk_tier, risk_reasons, risk_score = predict_risk_ml(extracted)
def g(key, fallback="Unknown"):
v = extracted.get(key)
return str(v) if v not in (None, "null", "") else fallback
classify_payload = f"""Applicant: {g('full_legal_name')}
Age: {g('age')} | Gender: {g('gender')} | Marital Status: {g('marital_status')}
Job Title: {g('job_title')} | Industry: {g('industry_sector')} | Employment Type: {g('employment_type')}
Annual Gross Income: {g('annual_gross_income')} | Occupational Hazards: {g('occupational_hazards')}
Height: {g('height')} | Weight: {g('weight')} | BMI: {g('bmi_numeric')}
Driving Record: {g('driving_record')} | Alcohol: {g('alcohol_consumption')}
Exercise Frequency: {g('exercise_frequency')} | Dietary Habits: {g('dietary_habits')}
Hazardous Hobbies: {g('hazardous_hobbies')}
Smoking Status: {g('smoking_status')}
Blood Pressure: {g('blood_pressure')} (Systolic: {g('systolic_bp')})
Total Cholesterol: {g('total_cholesterol')} ({g('cholesterol_numeric')} mg/dL)
Fasting Glucose: {g('fasting_glucose')} ({g('glucose_numeric')} mg/dL)
Last Medical Examination: {g('last_medical_examination')}
Current Medications: {g('current_medications')}
Known Allergies: {g('known_allergies')}
Pre-existing Conditions: {g('pre_existing_conditions')}
Hospitalisation History: {g('hospitalisation_history')}
Surgical & Mental Health History: {g('surgical_and_mental_health_history')}
Pending Investigations: {g('pending_investigations')}
Family History — Father: {g('family_history_father')}
Family History — Mother: {g('family_history_mother')}
Family History — Siblings: {g('family_history_siblings')}
Hereditary Flags: {g('hereditary_flags')}
Coverage Requested: {g('coverage_requested')} (Numeric: {g('coverage_amount_numeric')} USD)
Policy Type: {g('policy_type')} | Existing Life Cover: {g('existing_life_cover')}
Reason for Coverage: {g('reason_for_coverage')}
Prior Application Declines: {g('prior_application_declines')}
Medical Assessment Narrative: {g('medical_assessment_narrative')}
Financial Risk Narrative: {g('financial_risk_narrative')}
Risk Score: {risk_score} points | ML prediction: {"; ".join(risk_reasons)}"""
# ── Step 4 · Underwriter summary ──────────────────────────────────────────
step_ph.markdown(render_progress(4) + "_Generating underwriter summary…_", unsafe_allow_html=True)
summary_prompt = f"""You are a senior insurance underwriter.
Write two to three concise sentences summarising the key risk factors for this applicant
and justifying the assigned risk tier. Be specific and professional.
Refer explicitly to the medical and financial data. Do not use bullet points.
Applicant profile:
{classify_payload}
Assigned risk tier: {risk_tier}"""
try:
rows = session.sql(f"""
SELECT SNOWFLAKE.CORTEX.COMPLETE(
'mistral-large2',
$${esc(summary_prompt)}$$
) AS summary
""").collect()
summary = (rows[0]["SUMMARY"] or "Summary unavailable.").strip() if rows else "Summary unavailable."
except Exception as e:
st.error(f"**Summary generation failed.** {e}")
summary = "Summary generation failed."
# ── Step 5 · Save to Snowflake ────────────────────────────────────────────
step_ph.markdown(render_progress(5) + "_Saving record to Snowflake…_", unsafe_allow_html=True)
annual_income_numeric = safe_float(
re.sub(r"[^\d.]", "", str(extracted.get("annual_gross_income") or "").split()[0])
)
try:
session.sql(f"""
INSERT INTO {TABLE_FQN} (
FILE_NAME,
FULL_LEGAL_NAME, DATE_OF_BIRTH, AGE, GENDER, NATIONALITY,
MARITAL_STATUS, RESIDENTIAL_ADDRESS, PHONE,
JOB_TITLE, EMPLOYER, INDUSTRY_SECTOR, EMPLOYMENT_TYPE,
ANNUAL_GROSS_INCOME, ANNUAL_INCOME, YEARS_IN_CURRENT_ROLE, OCCUPATIONAL_HAZARDS,
HEIGHT, WEIGHT, BMI, BMI_NUMERIC, DRIVING_RECORD,
ALCOHOL_CONSUMPTION, EXERCISE_FREQUENCY, DIETARY_HABITS,
HAZARDOUS_HOBBIES, SMOKING_STATUS,
BLOOD_PRESSURE, SYSTOLIC_BP, DIASTOLIC_BP,
TOTAL_CHOLESTEROL, CHOLESTEROL_NUMERIC,
FASTING_GLUCOSE, GLUCOSE_NUMERIC,
LAST_MEDICAL_EXAMINATION, CURRENT_MEDICATIONS, KNOWN_ALLERGIES,
PRE_EXISTING_CONDITIONS, HOSPITALISATION_HISTORY,
SURGICAL_AND_MENTAL_HEALTH_HISTORY, PENDING_INVESTIGATIONS,
FAMILY_HISTORY_FATHER, FAMILY_HISTORY_MOTHER,
FAMILY_HISTORY_SIBLINGS, FAMILY_HISTORY_PATERNAL_RELATIVES,
FAMILY_HISTORY_MATERNAL_RELATIVES, HEREDITARY_FLAGS,
COVERAGE_REQUESTED, COVERAGE_AMOUNT_NUMERIC, POLICY_TYPE,
BENEFICIARY, EXISTING_LIFE_COVER, REASON_FOR_COVERAGE,
PRIOR_APPLICATION_DECLINES, PRIOR_CLAIMS,
MEDICAL_ASSESSMENT_NARRATIVE, FINANCIAL_RISK_NARRATIVE,
RISK_TIER, RISK_SCORE, UNDERWRITER_SUMMARY, UPLOADED_BY
) VALUES (
$${esc(safe_name)}$$,
$${esc(extracted.get('full_legal_name'))}$$,
$${esc(extracted.get('date_of_birth'))}$$,
{safe_float(extracted.get('age'))},
$${esc(extracted.get('gender'))}$$,
$${esc(extracted.get('nationality'))}$$,
$${esc(extracted.get('marital_status'))}$$,
$${esc(extracted.get('residential_address'))}$$,
$${esc(extracted.get('phone'))}$$,
$${esc(extracted.get('job_title'))}$$,
$${esc(extracted.get('employer'))}$$,
$${esc(extracted.get('industry_sector'))}$$,
$${esc(extracted.get('employment_type'))}$$,
$${esc(extracted.get('annual_gross_income'))}$$,
{annual_income_numeric},
$${esc(extracted.get('years_in_current_role'))}$$,
$${esc(extracted.get('occupational_hazards'))}$$,
$${esc(extracted.get('height'))}$$,
$${esc(extracted.get('weight'))}$$,
$${esc(extracted.get('bmi_text'))}$$,
{safe_float(extracted.get('bmi_numeric'))},
$${esc(extracted.get('driving_record'))}$$,
$${esc(extracted.get('alcohol_consumption'))}$$,
$${esc(extracted.get('exercise_frequency'))}$$,
$${esc(extracted.get('dietary_habits'))}$$,
$${esc(extracted.get('hazardous_hobbies'))}$$,
$${esc(extracted.get('smoking_status'))}$$,
$${esc(extracted.get('blood_pressure'))}$$,
{safe_float(extracted.get('systolic_bp'))},
{safe_float(extracted.get('diastolic_bp'))},
$${esc(extracted.get('total_cholesterol'))}$$,
{safe_float(extracted.get('cholesterol_numeric'))},
$${esc(extracted.get('fasting_glucose'))}$$,
{safe_float(extracted.get('glucose_numeric'))},
$${esc(extracted.get('last_medical_examination'))}$$,