File size: 12,400 Bytes
c57ba8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st 
import pandas as pd 
import matplotlib.pyplot as plt
import numpy as np 
import seaborn as sns 
import base64
import time
import pickle
from streamlit_extras import let_it_rain
from sklearn.preprocessing import LabelEncoder
st.set_page_config(layout="wide", initial_sidebar_state="expanded")

WelcomeText="""

Les assurances offrent une tranquillité d'esprit en protégeant contre 

les imprévus et les risques financiers. Elles permettent de se prémunir contre les pertes matérielles, 

les accidents, les maladies et autres événements inattendus. En souscrivant à une assurance, on se donne la garantie d'être soutenu et indemnisé en cas de sinistre, ce qui contribue à sécuriser son avenir et celui de ses proches. Les assurances jouent donc un rôle essentiel dans la gestion des risques

et la préservation du patrimoine, offrant ainsi une protection précieuse pour faire face aux aléas de la vie.

"""


@st.cache_data
def loadData(path):
    data= pd.read_csv(path)
    return data 

def filedownload(df): #telecharger un fichier depuis streamlit
        csv = df.to_csv(index=False)
        b64 = base64.b64encode(csv.encode()).decode()  # strings <-> bytes conversions
        href = f'<a href="data:file/csv;base64,{b64}" download="assurance_pred.csv">Telecharger les predictions</a>'
        return href
    
def displayText(texte):
    for word in texte.split(" "):
        yield word+ " "
        time.sleep(0.02)   
        
def pluie_billets_d_argent():
    let_it_rain.rain(
        emoji="💶💵", 
        font_size=60, 
        falling_speed=3, 
        animation_length="2",
        # color=["#FFD700", "#C0C0C0", "#FFA500", "#FFFF00"]
    )

        
        #fonction pour les simulations
def input_simulation():
    # 'age'	'sex'	'bmi'	'children'	'smoker'	'region'	'charges']
    age= st.slider("Age", 1, 100,step=1)
    tmp_sex= st.selectbox("Quel Est Votre Sexe? ", ["Masculin", "Feminin"])
    sex=0 #pour un hommme
    if tmp_sex== "Masculin":
        sex=0
    else:
        sex=1
    bmi = st.slider("BMI", 0.0, max_value=1000.0,step=0.1)
    children = st.slider("Nombre d'enfants: ", 0, step=1)
    tmp_smoker= st.selectbox("Prenez vous de la cigarette / drogue...? ",["oui", "Non"])
    smoker=1 #on pars sur la base qu'il ne fume pas
    if tmp_smoker=="oui":
        smoker=0
    else:
        smoker=1
    region = 1
    tmp_region= st.selectbox("Quelle est votre région d'origine? ",['southwest','southeast','northwest','northeast'])
    # [0,1,2,3]
    if tmp_region=="southwest":
            region= 0
    elif tmp_region=="southeast":
            region=1
    elif tmp_region=="northwest":
            region=2           
    elif tmp_region=="northeast":
            region=3   
    data = {
        'age':age,
        'sex':sex,
        'bmi':bmi,
        'children':children,	
        'smoker':smoker,
        'region':region
    }
    feature = pd.DataFrame(data, index=[0])
    return feature


#feature with text input
def input_simulation2():
    # 'age'	'sex'	'bmi'	'children'	'smoker'	'region'	'charges']
    age= st.slider("Age", 1, 100,step=1)
    tmp_sex= st.selectbox("Quel Est Votre Sexe? ", ["Masculin", "Feminin"])
    sex=0 #pour un hommme
    if tmp_sex== "Masculin":
        sex=0
    else:
        sex=1
    
    bmi = st.text_input("Entrez votre BMi", placeholder="Entrez votre BMI")
    children = st.text_input("Nombre d'enfants",placeholder="Entrez votre Nombre d'enfants")
    tmp_smoker= st.selectbox("Prenez vous de la cigarette / drogue...? ",["oui", "Non"])
    smoker=1 #on pars sur la base qu'il ne fume pas
    if tmp_smoker=="oui":
        smoker=0
    else:
        smoker=1
    region = 1
    tmp_region= st.selectbox("Quelle est votre région d'origine? ",['southwest','southeast','northwest','northeast'])
    # [0,1,2,3]
    if tmp_region=="southwest":
            region= 0
    elif tmp_region=="southeast":
            region=1
    elif tmp_region=="northwest":
            region=2           
    elif tmp_region=="northeast":
            region=3   
    data = {
        'age':[age if age else 10],
        'sex':sex,
        'bmi':[bmi if bmi else 10],
        'children':[children if children else 0],	
        'smoker':smoker,
        'region':region
    }
    feature = pd.DataFrame(data, index=[0])
    return feature



st.sidebar.image("1099.jpg", width=300) #ajout d'une image sur la barre de navigation Gauche
menuList= ["Accueil", "Visualisation", "Simulation", "Predictions"]
choosen = st.sidebar.selectbox("Selectionnez une option", menuList)
data= loadData("insurance.csv")

def displayText1(string):
    for word in string.split(" "):
        yield word+ " "
        time.sleep(0.1)


def main():
    data= loadData("insurance.csv")
    if choosen== menuList[0]:
        st.markdown("<h1 style='text-align:center;color: #005580; text-transform: uppercase'>Streamlit Assurance App 💶</h1>",unsafe_allow_html=True)#  affiche des titres html
        st.markdown("<br/> " , unsafe_allow_html=True)
        col1,col2,col3= st.columns((2,3,2))
        with col1:
            st.write(displayText(WelcomeText))
        with col3:
            st.image("ass2.jpg", use_column_width=True)
        with col2:
            st.image("ass1.jpg")
        with st.expander("Voir les  Données"):
            st.dataframe(data.head())
    elif choosen == menuList[1]:
        # st.balloons()
        with st.expander("Matrice de correlation"):
            tmp = data 
            le= LabelEncoder()
            tmp["sex"]= le.fit_transform(tmp["sex"])
            le2= LabelEncoder()
            tmp["region"]=le2.fit_transform(tmp["region"])
            le3= LabelEncoder()
            tmp["smoker"]=le3.fit_transform(tmp['smoker'])
            #matrice de correlation seaborn 
            mask = np.triu(np.ones_like(tmp.corr(), dtype=bool))
            f, ax = plt.subplots(figsize=(3,4))
            cmap = sns.diverging_palette(230, 20, as_cmap=True)
            sns.heatmap(tmp.corr(), mask=mask, cmap=cmap, vmax=.2, center=0,
            square=True, linewidths=.3, cbar_kws={"shrink": .4})
            st.pyplot(f, use_container_width=False)
        
        with st.expander("Charges d'assurance Vs Age"):
            sns.set_style("whitegrid")
            fig3= plt.figure(figsize=(5, 4))
            sns.lineplot(x='age', y='charges', data=tmp, marker='o', color='blue', linewidth=2)
            plt.title('Relation entre les charges d\'assurances  et l\'âge')
            plt.xlabel('Âge')
            plt.ylabel('Charge')
            plt.grid(True)
            st.pyplot(fig3, use_container_width=False)
        with st.expander("Nombre enfants Vs charges d'assurance"):
            sns.set_style("whitegrid")
            fig3= plt.figure(figsize=(5, 4))
            sns.lineplot(x='children', y='charges', data=tmp, marker='o', color='blue', linewidth=2)
            plt.title('Relation entre les charges d\'assurances  et le nombre d\'enfant')
            plt.xlabel('Nombre d\'enfants')
            plt.ylabel('Charge')
            plt.grid(True)
            st.pyplot(fig3, use_container_width=False)   
             
        with st.expander("Nombre enfants, Age Vs charges"):
            fig4= plt.figure(figsize=(10, 6))
            sns.scatterplot(x='age', y='charges', hue='children', data=tmp, palette='Set2', s=100)
            plt.title('Relation entre les charges, l\'âge et le nombre d\'enfants')
            plt.xlabel('Âge')
            plt.ylabel('Charges')
            plt.legend(title='Nombre d\'enfants')
            plt.grid(True)
            plt.show()
            st.pyplot(fig4, use_container_width=True)
    elif choosen== menuList[2]:
        st.markdown("<h1 style='text-align:center;color: #005580; text-transform: uppercase'> Simulation de vos frais d'assurances 💶</h1>",unsafe_allow_html=True)#  affiche des titres html

        col1,col2,col3= st.columns(3)
        df=None
        with col1:
            df= input_simulation()
        
        with col2:
            st.image("man.jpg")
        with col3:
            pickled_model = pickle.load(open('assurance.pkl', 'rb'))
            prediction= pickled_model.predict(df)
            
            string= "Vos Charges d'assurances s'élèvent à: "
            x= str(int(prediction[0]))+" CFA"
            st.write(displayText1(string))
            st.title(x)
    elif choosen == menuList[3]:
        tab1, tab2, tab3 = st.tabs([":clipboard: Data ",":bar_chart: Visualisation", " 💶Prediction"])
        file= st.sidebar.file_uploader("choisissez un fichier à uploader", type=['csv'])  
        globalData = []  
        with tab1:
            if st.sidebar.checkbox("Pas de fichier? Utiliser notre fichier  test"):
                file="test.csv"
            if file:
                df= loadData(file)
                st.write(df)
                 #matrice de correlation seaborn 
                mask = np.triu(np.ones_like(df.corr(), dtype=bool))
                f, ax = plt.subplots(figsize=(3,4))
                cmap = sns.diverging_palette(230, 20, as_cmap=True)
                sns.heatmap(df.corr(), mask=mask, cmap=cmap, vmax=.2, center=0,
                square=True, linewidths=.3, cbar_kws={"shrink": .4})
                st.pyplot(f, use_container_width=False)
                pickled_model = pickle.load(open('assurance.pkl', 'rb'))
                prediction= pickled_model.predict(df)
                df["charges"]=prediction
                with tab2:
                    col1,col2, col3= st.columns(3)
                    possibilities =['age',	'sex',	'bmi',	'children',	'smoker',	'region'	, 'charges']
                    userchoice=""
                    userSecondChoice=""
                    with col1:
                        userchoice= st.selectbox("Exprimé", possibilities)
                    with col2:
                        userSecondChoice= st.selectbox("En fonction de: ", possibilities)
                    sns.set_style("whitegrid")
                    fig3= plt.figure(figsize=(5, 4))
                    sns.lineplot(x=userchoice, y=userSecondChoice, data=df, marker='o', color='blue', linewidth=2)
                    sf= "Relation entre "+userchoice+" VS "+userSecondChoice
                    plt.title(sf)
                    plt.xlabel(userchoice)
                    plt.ylabel(userSecondChoice)
                    plt.grid(True)
                    st.pyplot(fig3, use_container_width=False)   
                with tab3:
                    
                    # time.sleep(20)
                    progress_text = "Prédictions en cours... veuillez patienter"
                    my_bar = st.progress(0, text=progress_text)
                    for percent_complete in range(100):
                        time.sleep(0.01)
                        my_bar.progress(percent_complete + 1, text=progress_text)
                        time.sleep(0.1)
                        my_bar.empty()
                    st.write(df)
                    if st.button("Download"):
                        st.markdown(filedownload(df), unsafe_allow_html=True)
            else:
            
                data=""
                
                col1, col2, col3= st.columns(3)
                with col2:
                    data = input_simulation2()
                with col1:
                    st.write(data)
                prediction= []
                string= "Vos Charges d'assurances s'élèvent à: "
                pickled_model = pickle.load(open('assurance.pkl', 'rb'))
                prediction= pickled_model.predict(data)
                x= str(int(prediction[0]))+" FCFA"
                data["prediction"]=prediction[0]
                with col1:
                    st.write(displayText1(string))
                    st.success(x)
                            
                with tab2:
                    st.write(data)
                with tab3:
                    st.write(displayText1(string))
                    st.success(x) 
                    pluie_billets_d_argent()
  
main()