-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreamlit_app.py
More file actions
2218 lines (1896 loc) · 90.7 KB
/
Copy pathstreamlit_app.py
File metadata and controls
2218 lines (1896 loc) · 90.7 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
"""
Insurance Premium Prediction Streamlit Application
This module implements a Streamlit web application for predicting insurance premiums
based on customer attributes. It includes features for premium calculation, model
monitoring, drift detection, and model retraining.
"""
# Standard library imports
import os
import sys
import time
import logging
import uuid
from datetime import datetime
# Third-party imports
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
from scipy import stats
from scipy.spatial import distance
# Function to create sample visualizations for the instructions tab
def create_sample_visualization(tab_name):
"""Create and display sample visualizations directly in the instructions tab"""
if tab_name == "calculator":
# Premium Calculator Screenshot
st.subheader("Premium Calculator Interface")
# Create a sample input summary
df = pd.DataFrame({
'Feature': ['Age', 'Smoking_Status', 'BMI_Category', 'Medical_History', 'Region', 'Income_Lakhs'],
'Value': ['45', 'Non-Smoker', 'Normal', 'None', 'Northeast', '12.5']
})
# Display as a styled table
st.markdown("#### Sample Customer Information")
st.dataframe(df, use_container_width=True)
# Add some UI elements to simulate the calculator
col1, col2 = st.columns(2)
with col1:
st.number_input("Age", min_value=18, max_value=85,
value=45, disabled=True)
st.selectbox("Gender", ["Male", "Female"], disabled=True)
st.selectbox("BMI Category", [
"Underweight", "Normal", "Overweight", "Obese"], index=1, disabled=True)
with col2:
st.selectbox("Smoking Status", [
"Non-Smoker", "Smoker"], disabled=True)
st.selectbox(
"Region", ["Northeast", "Northwest", "Southeast", "Southwest"], disabled=True)
st.number_input("Income (Lakhs)", min_value=1.0,
max_value=50.0, value=12.5, disabled=True)
st.button("Calculate Premium", disabled=True)
elif tab_name == "results":
# Results Explanation
st.subheader("Premium Results Visualization")
# Create a sample premium result
st.markdown("#### Premium Estimate")
col1, col2 = st.columns([1, 2])
with col1:
st.markdown("""
<div style="background-color:#f0f8ff; padding:20px; border-radius:10px; text-align:center;">
<h1 style="color:#1e90ff; font-size:48px; margin:0;">₹15,420</h1>
<p style="color:#666; margin:5px 0 0 0;">Annual Premium</p>
</div>
""", unsafe_allow_html=True)
with col2:
st.markdown("##### Confidence Interval")
st.markdown("₹14,250 - ₹16,590")
st.markdown("##### Model Version")
st.markdown("v2.1.3 (Last updated: Jan 5, 2025)")
# Feature importance chart
st.markdown("#### Feature Importance")
df_results = pd.DataFrame({
'Factor': ['Smoking_Status', 'Age', 'BMI_Category', 'Medical_History', 'Region', 'Income_Lakhs'],
'Importance': [0.35, 0.25, 0.15, 0.12, 0.08, 0.05]
})
fig_results = px.bar(df_results, x='Importance', y='Factor',
title="Factors Influencing Premium Calculation",
labels={'Importance': 'Relative Importance',
'Factor': 'Feature'},
color='Importance', color_continuous_scale='Viridis')
st.plotly_chart(fig_results, use_container_width=True)
elif tab_name == "monitoring":
# Model Monitoring Dashboard
st.subheader("Model Monitoring Dashboard")
# Performance metrics chart
st.markdown("#### Performance Metrics Over Time")
dates = pd.date_range(start='2025-01-01', periods=10, freq='W')
r2_values = [0.92, 0.918, 0.915, 0.913,
0.91, 0.908, 0.905, 0.901, 0.897, 0.892]
df_monitor = pd.DataFrame({'Date': dates, 'R-squared': r2_values})
fig_monitor = px.line(df_monitor, x='Date', y='R-squared',
title="R² Score Trend",
markers=True)
fig_monitor.add_hline(
y=0.9, line_dash="dash", line_color="red", annotation_text="Alert Threshold")
st.plotly_chart(fig_monitor, use_container_width=True)
# Data drift visualization
st.markdown("#### Data Drift Detection")
col1, col2 = st.columns(2)
with col1:
st.markdown("##### Training Data")
age_train = np.random.normal(42, 15, 1000)
age_train = np.clip(age_train, 18, 85).astype(int)
fig_age_train = px.histogram(age_train, title="Age Distribution (Training)",
labels={'value': 'Age', 'count': 'Frequency'})
st.plotly_chart(fig_age_train, use_container_width=True)
with col2:
st.markdown("##### Current Data")
age_current = np.random.normal(38, 14, 1000) # Younger population
age_current = np.clip(age_current, 18, 85).astype(int)
fig_age_current = px.histogram(age_current, title="Age Distribution (Current)",
labels={'value': 'Age', 'count': 'Frequency'})
st.plotly_chart(fig_age_current, use_container_width=True)
# Set page configuration FIRST before any other Streamlit commands
st.set_page_config(
page_title="Insurance Premium Prediction",
page_icon="💸",
layout="wide",
initial_sidebar_state="expanded",
menu_items={
'Get Help': 'https://x.ai/grok',
'Report a bug': "https://github.com/yourusername/insurance-premium-prediction/issues",
'About': "Insurance Premium Prediction App by Erick K. Yegon, PhD"
}
)
# Now we can add the current directory to path and import custom packages
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
# Import project-specific modules after path configuration
try:
from InsurancePremiumPrediction.utils import read_yaml
from InsurancePremiumPrediction.pipeline.prediction_pipeline import PredictionPipeline
from InsurancePremiumPrediction import logger
except ImportError as e:
st.error(f"Error importing required modules: {e}")
st.info(
"Please make sure the InsurancePremiumPrediction package is installed correctly.")
# Setup a basic logger if the import fails
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("insurance_app")
# Define a fallback function to avoid breaking the app completely
def read_yaml(path):
import yaml
try:
with open(path, 'r') as f:
return yaml.safe_load(f)
except Exception as yaml_err:
st.error(f"Error reading YAML file: {yaml_err}")
return {}
class FallbackPredictionPipeline:
def predict(self, data):
logger.error(
"Using fallback prediction pipeline - real model not available!")
# Return a fallback prediction based on simple heuristics
base = 5000
if data.get("Smoking_Status") == "Smoker":
base *= 1.5
if data.get("Age", 30) > 50:
base *= 1.3
return base
# Cache the prediction pipeline and schema to improve performance
@st.cache_resource(show_spinner="Loading prediction model...")
def load_prediction_pipeline():
try:
return PredictionPipeline()
except NameError:
logger.error("PredictionPipeline not available, using fallback")
return FallbackPredictionPipeline()
except Exception as e:
logger.error(f"Error loading prediction pipeline: {e}")
st.error(f"Error loading prediction model: {e}")
return FallbackPredictionPipeline()
@st.cache_resource(show_spinner="Loading schema configuration...")
def load_schema():
"""Load schema configuration from YAML file or return a default schema."""
try:
# Try to load schema from file
schema_data = read_yaml("schema.yaml")
if not schema_data:
raise ValueError("Schema is empty or invalid")
# Convert dictionary to object with attributes for compatibility
schema_obj = type('obj', (object,), {})
columns_obj = type('cols', (object,), {})
setattr(schema_obj, 'columns', columns_obj)
# Create column objects with constraints and categories
for col_name, col_data in schema_data.get('columns', {}).items():
col_obj = type(col_name.lower(), (object,), {})
# Add constraints if they exist
if 'constraints' in col_data:
setattr(col_obj, 'constraints', type(
'constraints', (object,), col_data['constraints']))
# Add categories if they exist
if 'categories' in col_data:
setattr(col_obj, 'categories', col_data['categories'])
# Add the column to columns object
setattr(columns_obj, col_name, col_obj)
return schema_obj
except Exception as e:
logger.error(f"Error loading schema: {e}")
st.error(f"Error loading schema configuration: {e}")
# Return a minimal fallback schema with default values
schema_obj = type('obj', (object,), {})
columns_obj = type('cols', (object,), {})
setattr(schema_obj, 'columns', columns_obj)
# Define default columns
default_columns = {
'Age': {'constraints': {'min': 18, 'max': 100}},
'Gender': {'categories': ['Male', 'Female', 'Other']},
'BMI_Category': {'categories': ['Underweight', 'Normal', 'Overweight', 'Obese']},
'Number_Of_Dependants': {'constraints': {'min': 0, 'max': 10}},
'Smoking_Status': {'categories': ['Non-Smoker', 'Smoker']},
'Region': {'categories': ['northeast', 'northwest', 'southeast', 'southwest']},
'Marital_status': {'categories': ['Single', 'Married', 'Divorced', 'Widowed']},
'Employment_Status': {'categories': ['Employed', 'Self-employed', 'Unemployed', 'Retired']},
'Income_Level': {'categories': ['Low', 'Medium', 'High']},
'Income_Lakhs': {'constraints': {'min': 1.0, 'max': 100.0}},
'Medical_History': {'categories': ['None', 'Minor', 'Major']},
'Insurance_Plan': {'categories': ['Basic', 'Standard', 'Premium', 'Ultimate']}
}
# Create column objects
for col_name, col_data in default_columns.items():
col_obj = type(col_name.lower(), (object,), {})
# Add constraints if they exist
if 'constraints' in col_data:
setattr(col_obj, 'constraints', type(
'constraints', (object,), col_data['constraints']))
# Add categories if they exist
if 'categories' in col_data:
setattr(col_obj, 'categories', col_data['categories'])
# Add the column to columns object
setattr(columns_obj, col_name, col_obj)
return schema_obj
# Initialize session state if not already initialized
if 'initialized' not in st.session_state:
st.session_state.initialized = True
st.session_state.prediction_history = []
st.session_state.session_id = str(uuid.uuid4())
st.session_state.comparison_mode = False
st.session_state.show_advanced = False
# Initialize pipeline and schema
try:
prediction_pipeline = load_prediction_pipeline()
schema = load_schema()
logger.info("App initialized successfully")
except Exception as e:
logger.error(f"Critical error during initialization: {e}")
st.error(f"Critical error during app initialization: {e}")
# Create a fallback schema to avoid NameError
schema = type('obj', (object,), {})
columns_obj = type('cols', (object,), {})
setattr(schema, 'columns', columns_obj)
# Define default columns
default_columns = {
'Age': {'constraints': {'min': 18, 'max': 100}},
'Gender': {'categories': ['Male', 'Female', 'Other']},
'BMI_Category': {'categories': ['Underweight', 'Normal', 'Overweight', 'Obese']},
'Number_Of_Dependants': {'constraints': {'min': 0, 'max': 10}},
'Smoking_Status': {'categories': ['Non-Smoker', 'Smoker']},
'Region': {'categories': ['northeast', 'northwest', 'southeast', 'southwest']},
'Marital_status': {'categories': ['Single', 'Married', 'Divorced', 'Widowed']},
'Employment_Status': {'categories': ['Employed', 'Self-employed', 'Unemployed', 'Retired']},
'Income_Level': {'categories': ['Low', 'Medium', 'High']},
'Income_Lakhs': {'constraints': {'min': 1.0, 'max': 100.0}},
'Medical_History': {'categories': ['None', 'Minor', 'Major']},
'Insurance_Plan': {'categories': ['Basic', 'Standard', 'Premium', 'Ultimate']}
}
# Create column objects
for col_name, col_data in default_columns.items():
col_obj = type(col_name.lower(), (object,), {})
# Add constraints if they exist
if 'constraints' in col_data:
setattr(col_obj, 'constraints', type(
'constraints', (object,), col_data['constraints']))
# Add categories if they exist
if 'categories' in col_data:
setattr(col_obj, 'categories', col_data['categories'])
# Add the column to columns object
setattr(columns_obj, col_name, col_obj)
# Custom CSS with Tailwind CDN for modern, responsive styling
st.markdown("""
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
<style>
/* Custom overrides for Streamlit */
.stApp {
background-color: #f9fafb;
font-family: 'Inter', sans-serif;
}
.prediction-card {
background: linear-gradient(135deg, #e6fffa 0%, #a7f3d0 100%);
border-radius: 1rem;
box-shadow: 0 4px 20px rgba(0,0,0,0.1);
padding: 2rem;
text-align: center;
}
.sidebar .sidebar-content {
background-color: #ffffff;
border-right: 1px solid #e5e7eb;
}
.tips-card {
background-color: #f3f4f6;
border-left: 4px solid #3b82f6;
border-radius: 0.5rem;
padding: 1.5rem;
}
.footer {
text-align: center;
padding: 1.5rem;
color: #6b7280;
border-top: 1px solid #e5e7eb;
margin-top: 2rem;
}
/* Accessibility improvements */
[role="slider"] {
outline: none;
}
select:focus, input:focus {
outline: 2px solid #3b82f6;
outline-offset: 2px;
}
/* Dark mode support */
@media (prefers-color-scheme: dark) {
.dark-mode-text {
color: #f3f4f6 !important;
}
.dark-mode-bg {
background-color: #1f2937 !important;
}
}
/* Responsive adjustments */
@media (max-width: 768px) {
.prediction-card {
padding: 1rem;
}
.tips-card {
padding: 1rem;
}
}
/* Animation for the prediction result */
@keyframes fadeIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
.animate-fade-in {
animation: fadeIn 0.5s ease-in;
}
/* Error message styling */
.error-message {
background-color: #fee2e2;
border-left: 4px solid #ef4444;
color: #b91c1c;
padding: 1rem;
border-radius: 0.5rem;
margin: 1rem 0;
}
/* Success message styling */
.success-message {
background-color: #d1fae5;
border-left: 4px solid #10b981;
color: #065f46;
padding: 1rem;
border-radius: 0.5rem;
margin: 1rem 0;
}
</style>
""", unsafe_allow_html=True)
def render_header():
"""Render the main header with modern typography and animation."""
st.markdown("""
<div class="text-center py-8">
<h1 class="text-4xl font-bold text-blue-600 animate-fade-in">Insurance Premium Prediction</h1>
<p class="text-lg text-gray-600 mt-2">Estimate your health insurance premium with advanced machine learning</p>
</div>
""", unsafe_allow_html=True)
# Add a notification area for important messages
if st.session_state.get('notification'):
st.info(st.session_state.notification)
# Clear the notification after displaying it once
st.session_state.notification = None
def get_default_value(field_name, default):
"""Helper to get default values from session state if available"""
return st.session_state.get(f"{field_name}_input", default)
def render_sidebar_inputs():
"""Render sidebar inputs with improved UX and accessibility."""
st.sidebar.markdown(
"<h2 class='text-xl font-semibold text-gray-800 mb-4'>Your Information</h2>", unsafe_allow_html=True)
# Add option to load sample profiles
sample_profiles = {
"Select a profile": {},
"Young, Healthy Professional": {
"age": 28, "gender": "Male", "bmi_category": "Normal",
"dependants": 0, "smoking_status": "Non-smoker",
"region": "northeast", "marital_status": "Single",
"employment_status": "Employed", "income_level": "Medium",
"income_lakhs": 12.0, "medical_history": "None",
"insurance_plan": "Standard"
},
"Family with Children": {
"age": 42, "gender": "Female", "bmi_category": "Normal",
"dependants": 3, "smoking_status": "Non-smoker",
"region": "southeast", "marital_status": "Married",
"employment_status": "Employed", "income_level": "High",
"income_lakhs": 25.0, "medical_history": "Minor",
"insurance_plan": "Premium"
},
"Senior with Health Issues": {
"age": 68, "gender": "Male", "bmi_category": "Overweight",
"dependants": 0, "smoking_status": "Smoker",
"region": "southwest", "marital_status": "Widowed",
"employment_status": "Retired", "income_level": "Medium",
"income_lakhs": 8.5, "medical_history": "Major",
"insurance_plan": "Premium"
}
}
profile = st.sidebar.selectbox(
"Quick profile selection",
options=list(sample_profiles.keys()),
key="profile_select"
)
# Apply selected profile values
if profile != "Select a profile" and sample_profiles[profile]:
selected_profile = sample_profiles[profile]
for key, value in selected_profile.items():
st.session_state[f"{key}_input"] = value
# Advanced options toggle
st.sidebar.markdown("---")
st.sidebar.checkbox("Show advanced options", key="show_advanced")
# Get schema constraints safely with error handling
try:
age_min = int(schema.columns.Age.constraints.min)
age_max = int(schema.columns.Age.constraints.max)
dependants_min = int(
getattr(schema.columns, "Number_Of_Dependants").constraints.min)
dependants_max = int(
getattr(schema.columns, "Number_Of_Dependants").constraints.max)
income_min = float(schema.columns.Income_Lakhs.constraints.min)
income_max = float(getattr(schema.columns, "Income_Lakhs", type(
'', (), {'constraints': {'max': 50.0}})).constraints.max)
except (AttributeError, TypeError) as e:
logger.warning(
f"Error getting schema constraints: {e}, using defaults")
age_min, age_max = 18, 100
dependants_min, dependants_max = 0, 10
income_min, income_max = 1.0, 50.0
# Define and render all inputs
inputs = {
"age": st.sidebar.slider(
"Age",
min_value=age_min,
max_value=age_max,
value=get_default_value("age", 30),
help="Select your age",
key="age_input"
),
"gender": st.sidebar.selectbox(
"Gender",
options=getattr(schema.columns.Gender, "categories", [
"Male", "Female", "Other"]),
index=0,
help="Select your gender",
key="gender_input"
),
"bmi_category": st.sidebar.selectbox(
"BMI Category",
options=getattr(schema.columns.BMI_Category, "categories",
["Underweight", "Normal", "Overweight", "Obese"]),
index=1,
help="Select your BMI category",
key="bmi_input"
),
"dependants": st.sidebar.slider(
"Number of Dependants",
min_value=dependants_min,
max_value=dependants_max,
value=get_default_value("dependants", 0),
help="Select number of dependants",
key="dependants_input"
),
"smoking_status": st.sidebar.selectbox(
"Smoking Status",
options=getattr(schema.columns.Smoking_Status, "categories",
["Non-Smoker", "Smoker"]),
index=0,
help="Select smoking status",
key="smoking_input"
),
"region": st.sidebar.selectbox(
"Region",
options=getattr(schema.columns.Region, "categories",
["northeast", "northwest", "southeast", "southwest"]),
index=0,
help="Select your region",
key="region_input"
),
"marital_status": st.sidebar.selectbox(
"Marital Status",
options=getattr(schema.columns.Marital_status, "categories",
["Single", "Married", "Divorced", "Widowed"]),
index=0,
help="Select marital status",
key="marital_input"
),
"employment_status": st.sidebar.selectbox(
"Employment Status",
options=getattr(schema.columns.Employment_Status, "categories",
["Employed", "Self-employed", "Unemployed", "Retired"]),
index=0,
help="Select employment status",
key="employment_input"
)
}
# Conditional advanced options
if st.session_state.show_advanced:
inputs.update({
"income_level": st.sidebar.selectbox(
"Income Level",
options=getattr(schema.columns.Income_Level, "categories",
["Low", "Medium", "High"]),
index=1,
help="Select income level",
key="income_level_input"
),
"income_lakhs": st.sidebar.slider(
"Income (Lakhs)",
min_value=income_min,
max_value=income_max,
value=get_default_value("income_lakhs", 10.0),
step=0.5,
help="Select income in lakhs",
key="income_lakhs_input"
),
"medical_history": st.sidebar.selectbox(
"Medical History",
options=getattr(getattr(schema.columns, "Medical_History", None), "categories",
["None", "Minor", "Major"]),
index=0,
help="Select medical history",
key="medical_history_input"
),
"insurance_plan": st.sidebar.selectbox(
"Insurance Plan",
options=getattr(schema.columns.Insurance_Plan, "categories",
["Basic", "Standard", "Premium", "Ultimate"]),
index=1,
help="Select insurance plan",
key="insurance_plan_input"
)
})
else:
# Default values for advanced fields
inputs.update({
"income_level": get_default_value("income_level", "Medium"),
"income_lakhs": get_default_value("income_lakhs", 10.0),
"medical_history": get_default_value("medical_history", "None"),
"insurance_plan": get_default_value("insurance_plan", "Standard")
})
# Add a reset button
if st.sidebar.button("Reset All Fields", type="secondary"):
for key in list(st.session_state.keys()):
if key.endswith("_input"):
del st.session_state[key]
st.session_state.notification = "All fields have been reset to default values."
st.rerun()
# Add comparison mode toggle
st.sidebar.markdown("---")
st.sidebar.checkbox("Enable comparison mode", key="comparison_mode")
if st.session_state.comparison_mode:
st.sidebar.markdown(
"<h3 class='text-lg font-semibold text-blue-600 mt-4'>Comparison Scenario</h3>",
unsafe_allow_html=True
)
st.sidebar.info(
"Modify any values below to see how they affect your premium")
# Only show a subset of fields for comparison to keep the UI clean
comparison_inputs = {
"compare_age": st.sidebar.slider(
"Age (Comparison)",
min_value=age_min,
max_value=age_max,
value=inputs["age"],
key="compare_age_input"
),
"compare_bmi": st.sidebar.selectbox(
"BMI Category (Comparison)",
options=getattr(schema.columns.BMI_Category, "categories",
["Underweight", "Normal", "Overweight", "Obese"]),
index=list(getattr(schema.columns.BMI_Category, "categories",
["Underweight", "Normal", "Overweight", "Obese"])).index(inputs["bmi_category"]),
key="compare_bmi_input"
),
"compare_smoking": st.sidebar.selectbox(
"Smoking Status (Comparison)",
options=getattr(schema.columns.Smoking_Status, "categories",
["Non-Smoker", "Smoker"]),
index=list(getattr(schema.columns.Smoking_Status, "categories",
["Non-Smoker", "Smoker"])).index(inputs["smoking_status"]),
key="compare_smoking_input"
),
"compare_medical": st.sidebar.selectbox(
"Medical History (Comparison)",
options=getattr(getattr(schema.columns, "Medical_History", None), "categories",
["None", "Minor", "Major"]),
index=list(getattr(getattr(schema.columns, "Medical_History", None), "categories",
["None", "Minor", "Major"])).index(inputs["medical_history"]),
key="compare_medical_input"
)
}
inputs["comparison"] = comparison_inputs
return inputs
def render_main_content(inputs):
"""Render the main content with user info, prediction, and visualizations."""
col1, col2 = st.columns([3, 2])
with col1:
st.markdown(
"<h3 class='text-2xl font-semibold text-gray-800 mb-4'>Your Information</h3>", unsafe_allow_html=True)
# Display user inputs in a styled table
user_data = pd.DataFrame({
"Feature": ["Age", "Gender", "BMI Category", "Number of Dependants", "Smoking Status",
"Region", "Marital Status", "Employment Status", "Income Level",
"Income (Lakhs)", "Medical History", "Insurance Plan"],
"Value": [str(inputs["age"]), str(inputs["gender"]), str(inputs["bmi_category"]),
str(inputs["dependants"]), str(
inputs["smoking_status"]), str(inputs["region"].title()),
str(inputs["marital_status"]), str(
inputs["employment_status"]), str(inputs["income_level"]),
str(inputs["income_lakhs"]), str(inputs["medical_history"]), str(inputs["insurance_plan"])]
})
st.dataframe(user_data, use_container_width=True)
# Predict button with loading state
predict_col1, predict_col2 = st.columns(2)
with predict_col1:
predict_button = st.button(
"Calculate Premium",
type="primary",
use_container_width=True,
key="predict_button"
)
with predict_col2:
# Add option to save prediction
if st.session_state.get('last_prediction'):
save_button = st.button(
"Save This Prediction",
use_container_width=True,
key="save_button"
)
if save_button:
try:
if 'prediction_history' not in st.session_state:
st.session_state.prediction_history = []
# Save prediction with timestamp and inputs
st.session_state.prediction_history.append({
'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
'premium': st.session_state.last_prediction,
'inputs': inputs.copy() # Save a copy of the inputs
})
st.success("Prediction saved successfully!")
logger.info(
f"Prediction saved: ${st.session_state.last_prediction:.2f}")
except Exception as e:
st.error(f"Error saving prediction: {e}")
logger.error(f"Error saving prediction: {e}")
# Execute prediction if button is clicked
if predict_button:
with st.spinner("Calculating premium..."):
try:
# Prepare input data for primary prediction
input_data = {
"Age": inputs["age"],
"Gender": inputs["gender"],
"BMI_Category": inputs["bmi_category"],
"Number_Of_Dependants": inputs["dependants"],
# Include both versions for compatibility
"Number Of Dependants": inputs["dependants"],
"Smoking_Status": inputs["smoking_status"],
"Region": inputs["region"],
"Marital_status": inputs["marital_status"],
"Employment_Status": inputs["employment_status"],
"Income_Level": inputs["income_level"],
"Income_Lakhs": inputs["income_lakhs"],
"Medical_History": inputs["medical_history"],
# Include both versions for compatibility
"Medical History": inputs["medical_history"],
"Insurance_Plan": inputs["insurance_plan"]
}
# Make prediction
prediction = prediction_pipeline.predict(input_data)
# Store the prediction in session state
st.session_state.last_prediction = prediction
# Display prediction in a styled card
st.markdown(f"""
<div class='prediction-card animate-fade-in'>
<p class='text-lg font-medium text-green-800'>Estimated Annual Premium</p>
<p class='text-4xl font-bold text-green-900'>${prediction:,.2f}</p>
<p class='text-sm text-gray-600 mt-2'>Based on your provided information</p>
</div>
""", unsafe_allow_html=True)
# Log the prediction
logger.info(
f"Streamlit prediction made: ${prediction:.2f}")
# If comparison mode is enabled, show comparison
if st.session_state.comparison_mode and 'comparison' in inputs:
st.markdown("<hr class='my-4'>",
unsafe_allow_html=True)
st.markdown(
"<h4 class='text-xl font-semibold text-blue-600 mb-3'>Comparison Scenario</h4>",
unsafe_allow_html=True
)
# Create comparison input data - start with the base data
comparison_data = input_data.copy()
# Update with comparison values
comparison_data.update({
"Age": inputs["comparison"]["compare_age"],
"BMI_Category": inputs["comparison"]["compare_bmi"],
"Smoking_Status": inputs["comparison"]["compare_smoking"],
"Medical_History": inputs["comparison"]["compare_medical"],
# Include both versions for compatibility
"Medical History": inputs["comparison"]["compare_medical"]
})
# Make comparison prediction
comparison_prediction = prediction_pipeline.predict(
comparison_data)
# Calculate the difference
difference = comparison_prediction - prediction
difference_pct = (difference / prediction) * \
100 if prediction > 0 else 0
# Display comparison results
diff_color = "text-red-600" if difference > 0 else "text-green-600"
diff_sign = "+" if difference > 0 else ""
st.markdown(f"""
<div class='prediction-card animate-fade-in' style='background: linear-gradient(135deg, #ede9fe 0%, #c4b5fd 100%);'>
<p class='text-lg font-medium text-purple-800'>Comparison Premium</p>
<p class='text-4xl font-bold text-purple-900'>${comparison_prediction:,.2f}</p>
<div class='mt-2'>
<span class='text-lg font-semibold {diff_color}'>{diff_sign}${difference:,.2f} ({diff_sign}{difference_pct:.1f}%)</span>
</div>
<p class='text-sm text-gray-600 mt-2'>Based on your comparison scenario</p>
</div>
""", unsafe_allow_html=True)
# Create a differences table
st.markdown(
"<h5 class='text-lg font-medium text-gray-800 mt-4 mb-2'>Changes Made:</h5>", unsafe_allow_html=True)
diff_table = pd.DataFrame({
"Feature": ["Age", "BMI Category", "Smoking Status", "Medical History"],
"Original Value": [
inputs["age"],
inputs["bmi_category"],
inputs["smoking_status"],
inputs["medical_history"]
],
"Comparison Value": [
inputs["comparison"]["compare_age"],
inputs["comparison"]["compare_bmi"],
inputs["comparison"]["compare_smoking"],
inputs["comparison"]["compare_medical"]
]
})
st.table(diff_table)
except Exception as e:
st.error(f"Error making prediction: {e}")
logger.error(f"Error in Streamlit prediction: {e}")
# Show prediction history if available
if st.session_state.get('prediction_history') and len(st.session_state.prediction_history) > 0:
st.markdown("<hr class='my-4'>", unsafe_allow_html=True)
st.markdown(
"<h4 class='text-xl font-semibold text-gray-800 mb-3'>Previous Predictions</h4>",
unsafe_allow_html=True
)
# Display history in reverse order (newest first)
# Show last 5
for i, pred in enumerate(reversed(st.session_state.prediction_history[-5:])):
with st.expander(f"Prediction on {pred['timestamp']} - ${pred['premium']:,.2f}"):
# Display the inputs used for this prediction
pred_inputs = pred.get('inputs', {})
if pred_inputs:
st.write("Inputs used:")
# Show the key inputs
st.markdown(f"""
- Age: {pred_inputs.get('age', 'N/A')}
- BMI: {pred_inputs.get('bmi_category', 'N/A')}
- Smoking: {pred_inputs.get('smoking_status', 'N/A')}
- Medical History: {pred_inputs.get('medical_history', 'N/A')}
- Insurance Plan: {pred_inputs.get('insurance_plan', 'N/A')}
""")
# Add button to load these inputs
if st.button("Load these inputs", key=f"load_pred_{i}"):
for key, value in pred_inputs.items():
if key != 'comparison': # Skip comparison data
st.session_state[f"{key}_input"] = value
st.session_state.notification = "Previous inputs loaded successfully."
st.rerun()
with col2:
st.markdown(
"<h3 class='text-2xl font-semibold text-gray-800 mb-4'>Key Factors</h3>", unsafe_allow_html=True)
# Interactive Plotly chart for feature importance
factors = ["Smoking Status", "Age", "Medical History",
"Income", "BMI Category", "Region", "Insurance Plan"]
importance = [0.35, 0.15, 0.15, 0.12, 0.10, 0.08, 0.05]
# Create a DataFrame for better plotting
importance_df = pd.DataFrame({
'Factor': factors,
'Importance': importance
})
# Sort for better visualization
importance_df = importance_df.sort_values(
'Importance', ascending=False)
fig = px.bar(
importance_df,
x='Importance',
y='Factor',
orientation='h',
title="Feature Importance in Premium Calculation",
labels={'Importance': 'Relative Importance', 'Factor': ''},
color='Importance',
color_continuous_scale='Blues',
text='Importance'
)
fig.update_traces(
texttemplate='%{text:.0%}',
textposition='outside'
)
fig.update_layout(
showlegend=False,
margin=dict(l=20, r=20, t=50, b=20),
height=350,
coloraxis_showscale=False,
xaxis=dict(
tickformat='.0%',
range=[0, max(importance) * 1.1] # Add some padding
)
)
st.plotly_chart(fig, use_container_width=True)
# Tips section with improved content
st.markdown("""
<div class='tips-card'>
<h4 class='text-lg font-semibold text-gray-800 mb-3'>Tips for Lower Premiums</h4>
<ul class='list-disc list-inside text-gray-600'>
<li><strong>Quit smoking</strong> or avoid tobacco products - one of the biggest factors</li>
<li>Maintain a <strong>healthy BMI</strong> through regular exercise and diet</li>
<li>Schedule <strong>regular preventive check-ups</strong> to avoid serious health issues</li>
<li>Choose an insurance plan that <strong>matches your actual needs</strong></li>
<li>Consider a <strong>higher deductible</strong> for lower monthly premiums</li>
<li>Check if you qualify for any <strong>employer or group discounts</strong></li>
<li>Look into <strong>wellness program discounts</strong> offered by many providers</li>
</ul>
</div>
""", unsafe_allow_html=True)
# Add an FAQ section
with st.expander("Frequently Asked Questions"):
st.markdown("""
#### What factors most affect my insurance premium?
Smoking status, age, and medical history are typically the most significant factors in determining your premium.
#### How accurate is this prediction?
This model has been trained on comprehensive health insurance data and provides an estimate within 10-15% of actual premiums in most cases.
#### Can I use this for all types of health insurance?
This model is primarily designed for individual and family health insurance plans. Employer-provided group plans may have different pricing structures.
#### How often should I recalculate my premium?
It's good practice to recalculate whenever you experience a significant life change (marriage, new dependants, change in health status) or annually.
""")
# Add a visualization selector
st.markdown(
"<h4 class='text-xl font-semibold text-gray-800 mt-4 mb-3'>Premium Analysis</h4>", unsafe_allow_html=True)
viz_option = st.selectbox(
"Choose visualization",
["Premium by Age", "Premium by BMI Category",
"Premium by Smoking Status"],
index=0
)
# Generate data for visualizations
def generate_simulation_data(base_input, varying_factor, values):
"""Generate simulated data by varying one factor"""
sim_data = []
for value in values:
sim_input = base_input.copy()
sim_input[varying_factor] = value
try:
premium = prediction_pipeline.predict(sim_input)
sim_data.append({"Factor": value, "Premium": premium})
except Exception as e:
logger.error(f"Error in simulation: {e}")
continue
return pd.DataFrame(sim_data)
try:
# Base input from current selections
base_input = {