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'Telecharger les predictions' 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("

Streamlit Assurance App 💶

",unsafe_allow_html=True)# affiche des titres html st.markdown("
" , 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("

Simulation de vos frais d'assurances 💶

",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()